1#!/usr/local/bin/python3.8
2from __future__ import (absolute_import, division, print_function)
3# Copyright 2019-2020 Fortinet, Inc.
4#
5# This program is free software: you can redistribute it and/or modify
6# it under the terms of the GNU General Public License as published by
7# the Free Software Foundation, either version 3 of the License, or
8# (at your option) any later version.
9#
10# This program is distributed in the hope that it will be useful,
11# but WITHOUT ANY WARRANTY; without even the implied warranty of
12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13# GNU General Public License for more details.
14#
15# You should have received a copy of the GNU General Public License
16# along with this program.  If not, see <https://www.gnu.org/licenses/>.
17
18__metaclass__ = type
19
20ANSIBLE_METADATA = {'status': ['preview'],
21                    'supported_by': 'community',
22                    'metadata_version': '1.1'}
23
24DOCUMENTATION = '''
25---
26module: fortios_system_replacemsg_ec
27short_description: Replacement messages in Fortinet's FortiOS and FortiGate.
28description:
29    - This module is able to configure a FortiGate or FortiOS (FOS) device by allowing the
30      user to set and modify system_replacemsg feature and ec category.
31      Examples include all parameters and values need to be adjusted to datasources before usage.
32      Tested with FOS v6.0.0
33version_added: "2.10"
34author:
35    - Link Zheng (@chillancezen)
36    - Jie Xue (@JieX19)
37    - Hongbin Lu (@fgtdev-hblu)
38    - Frank Shen (@frankshen01)
39    - Miguel Angel Munoz (@mamunozgonzalez)
40    - Nicolas Thomas (@thomnico)
41notes:
42    - Legacy fortiosapi has been deprecated, httpapi is the preferred way to run playbooks
43
44requirements:
45    - ansible>=2.9.0
46options:
47    access_token:
48        description:
49            - Token-based authentication.
50              Generated from GUI of Fortigate.
51        type: str
52        required: false
53    enable_log:
54        description:
55            - Enable/Disable logging for task.
56        type: bool
57        required: false
58        default: false
59    vdom:
60        description:
61            - Virtual domain, among those defined previously. A vdom is a
62              virtual instance of the FortiGate that can be configured and
63              used as a different unit.
64        type: str
65        default: root
66
67    state:
68        description:
69            - Indicates whether to create or remove the object.
70        type: str
71        required: true
72        choices:
73            - present
74            - absent
75    system_replacemsg_ec:
76        description:
77            - Replacement messages.
78        default: null
79        type: dict
80        suboptions:
81            buffer:
82                description:
83                    - Message string.
84                type: str
85            format:
86                description:
87                    - Format flag.
88                type: str
89                choices:
90                    - none
91                    - text
92                    - html
93                    - wml
94            header:
95                description:
96                    - Header flag.
97                type: str
98                choices:
99                    - none
100                    - http
101                    - 8bit
102            msg_type:
103                description:
104                    - Message type.
105                type: str
106'''
107
108EXAMPLES = '''
109- hosts: fortigates
110  collections:
111    - fortinet.fortios
112  connection: httpapi
113  vars:
114   vdom: "root"
115   ansible_httpapi_use_ssl: yes
116   ansible_httpapi_validate_certs: no
117   ansible_httpapi_port: 443
118  tasks:
119  - name: Replacement messages.
120    fortios_system_replacemsg_ec:
121      vdom:  "{{ vdom }}"
122      state: "present"
123      access_token: "<your_own_value>"
124      system_replacemsg_ec:
125        buffer: "<your_own_value>"
126        format: "none"
127        header: "none"
128        msg_type: "<your_own_value>"
129
130'''
131
132RETURN = '''
133build:
134  description: Build number of the fortigate image
135  returned: always
136  type: str
137  sample: '1547'
138http_method:
139  description: Last method used to provision the content into FortiGate
140  returned: always
141  type: str
142  sample: 'PUT'
143http_status:
144  description: Last result given by FortiGate on last operation applied
145  returned: always
146  type: str
147  sample: "200"
148mkey:
149  description: Master key (id) used in the last call to FortiGate
150  returned: success
151  type: str
152  sample: "id"
153name:
154  description: Name of the table used to fulfill the request
155  returned: always
156  type: str
157  sample: "urlfilter"
158path:
159  description: Path of the table used to fulfill the request
160  returned: always
161  type: str
162  sample: "webfilter"
163revision:
164  description: Internal revision number
165  returned: always
166  type: str
167  sample: "17.0.2.10658"
168serial:
169  description: Serial number of the unit
170  returned: always
171  type: str
172  sample: "FGVMEVYYQT3AB5352"
173status:
174  description: Indication of the operation's result
175  returned: always
176  type: str
177  sample: "success"
178vdom:
179  description: Virtual domain used
180  returned: always
181  type: str
182  sample: "root"
183version:
184  description: Version of the FortiGate
185  returned: always
186  type: str
187  sample: "v5.6.3"
188
189'''
190from ansible.module_utils.basic import AnsibleModule
191from ansible.module_utils.connection import Connection
192from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import FortiOSHandler
193from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import check_legacy_fortiosapi
194from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import schema_to_module_spec
195from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import check_schema_versioning
196from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import FAIL_SOCKET_MSG
197from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import is_same_comparison
198from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import serialize
199
200
201def filter_system_replacemsg_ec_data(json):
202    option_list = ['buffer', 'format', 'header',
203                   'msg_type']
204    dictionary = {}
205
206    for attribute in option_list:
207        if attribute in json and json[attribute] is not None:
208            dictionary[attribute] = json[attribute]
209
210    return dictionary
211
212
213def underscore_to_hyphen(data):
214    if isinstance(data, list):
215        for i, elem in enumerate(data):
216            data[i] = underscore_to_hyphen(elem)
217    elif isinstance(data, dict):
218        new_data = {}
219        for k, v in data.items():
220            new_data[k.replace('_', '-')] = underscore_to_hyphen(v)
221        data = new_data
222
223    return data
224
225
226def system_replacemsg_ec(data, fos, check_mode=False):
227
228    vdom = data['vdom']
229
230    state = data['state']
231
232    system_replacemsg_ec_data = data['system_replacemsg_ec']
233    filtered_data = underscore_to_hyphen(filter_system_replacemsg_ec_data(system_replacemsg_ec_data))
234
235    # check_mode starts from here
236    if check_mode:
237        mkey = fos.get_mkey('system', 'interface', filtered_data, vdom=vdom)
238        current_data = fos.get('system', 'interface', vdom=vdom, mkey=mkey)
239        is_existed = current_data and current_data.get('http_status') == 200 \
240            and isinstance(current_data.get('results'), list) \
241            and len(current_data['results']) > 0
242
243        # 2. if it exists and the state is 'present' then compare current settings with desired
244        if state == 'present' or state is True:
245            if mkey is None:
246                return False, True, filtered_data
247
248            # if mkey exists then compare each other
249            # record exits and they're matched or not
250            if is_existed:
251                is_same = is_same_comparison(
252                    serialize(current_data['results'][0]), serialize(filtered_data))
253                return False, not is_same, filtered_data
254
255            # record does not exist
256            return False, True, filtered_data
257
258        if state == 'absent':
259            if mkey is None:
260                return False, False, filtered_data
261
262            if is_existed:
263                return False, True, filtered_data
264            return False, False, filtered_data
265
266        return True, False, {'reason: ': 'Must provide state parameter'}
267
268    if state == "present" or state is True:
269        return fos.set('system.replacemsg',
270                       'ec',
271                       data=filtered_data,
272                       vdom=vdom)
273
274    elif state == "absent":
275        return fos.delete('system.replacemsg',
276                          'ec',
277                          mkey=filtered_data['msg-type'],
278                          vdom=vdom)
279    else:
280        fos._module.fail_json(msg='state must be present or absent!')
281
282
283def is_successful_status(status):
284    return status['status'] == "success" or \
285        status['http_method'] == "DELETE" and status['http_status'] == 404
286
287
288def fortios_system_replacemsg(data, fos, check_mode):
289
290    if data['system_replacemsg_ec']:
291        resp = system_replacemsg_ec(data, fos, check_mode)
292    else:
293        fos._module.fail_json(msg='missing task body: %s' % ('system_replacemsg_ec'))
294    if check_mode:
295        return resp
296    return not is_successful_status(resp), \
297        resp['status'] == "success" and \
298        (resp['revision_changed'] if 'revision_changed' in resp else True), \
299        resp
300
301
302versioned_schema = {
303    "type": "list",
304    "children": {
305        "buffer": {
306            "type": "string",
307            "revisions": {
308                "v6.0.11": True,
309                "v6.0.0": True,
310                "v6.0.5": True
311            }
312        },
313        "header": {
314            "type": "string",
315            "options": [
316                {
317                    "value": "none",
318                    "revisions": {
319                        "v6.0.11": True,
320                        "v6.0.0": True,
321                        "v6.0.5": True
322                    }
323                },
324                {
325                    "value": "http",
326                    "revisions": {
327                        "v6.0.11": True,
328                        "v6.0.0": True,
329                        "v6.0.5": True
330                    }
331                },
332                {
333                    "value": "8bit",
334                    "revisions": {
335                        "v6.0.11": True,
336                        "v6.0.0": True,
337                        "v6.0.5": True
338                    }
339                }
340            ],
341            "revisions": {
342                "v6.0.11": True,
343                "v6.0.0": True,
344                "v6.0.5": True
345            }
346        },
347        "msg_type": {
348            "type": "string",
349            "revisions": {
350                "v6.0.11": True,
351                "v6.0.0": True,
352                "v6.0.5": True
353            }
354        },
355        "format": {
356            "type": "string",
357            "options": [
358                {
359                    "value": "none",
360                    "revisions": {
361                        "v6.0.11": True,
362                        "v6.0.0": True,
363                        "v6.0.5": True
364                    }
365                },
366                {
367                    "value": "text",
368                    "revisions": {
369                        "v6.0.11": True,
370                        "v6.0.0": True,
371                        "v6.0.5": True
372                    }
373                },
374                {
375                    "value": "html",
376                    "revisions": {
377                        "v6.0.11": True,
378                        "v6.0.0": True,
379                        "v6.0.5": True
380                    }
381                },
382                {
383                    "value": "wml",
384                    "revisions": {
385                        "v6.0.11": True,
386                        "v6.0.0": True,
387                        "v6.0.5": True
388                    }
389                }
390            ],
391            "revisions": {
392                "v6.0.11": True,
393                "v6.0.0": True,
394                "v6.0.5": True
395            }
396        }
397    },
398    "revisions": {
399        "v6.0.11": True,
400        "v6.0.0": True,
401        "v6.0.5": True
402    }
403}
404
405
406def main():
407    module_spec = schema_to_module_spec(versioned_schema)
408    mkeyname = 'msg-type'
409    fields = {
410        "access_token": {"required": False, "type": "str", "no_log": True},
411        "enable_log": {"required": False, "type": bool},
412        "vdom": {"required": False, "type": "str", "default": "root"},
413        "state": {"required": True, "type": "str",
414                  "choices": ["present", "absent"]},
415        "system_replacemsg_ec": {
416            "required": False, "type": "dict", "default": None,
417            "options": {
418            }
419        }
420    }
421    for attribute_name in module_spec['options']:
422        fields["system_replacemsg_ec"]['options'][attribute_name] = module_spec['options'][attribute_name]
423        if mkeyname and mkeyname == attribute_name:
424            fields["system_replacemsg_ec"]['options'][attribute_name]['required'] = True
425
426    check_legacy_fortiosapi()
427    module = AnsibleModule(argument_spec=fields,
428                           supports_check_mode=True)
429
430    versions_check_result = None
431    if module._socket_path:
432        connection = Connection(module._socket_path)
433        if 'access_token' in module.params:
434            connection.set_option('access_token', module.params['access_token'])
435
436        if 'enable_log' in module.params:
437            connection.set_option('enable_log', module.params['enable_log'])
438        else:
439            connection.set_option('enable_log', False)
440        fos = FortiOSHandler(connection, module, mkeyname)
441        versions_check_result = check_schema_versioning(fos, versioned_schema, "system_replacemsg_ec")
442
443        is_error, has_changed, result = fortios_system_replacemsg(module.params, fos, module.check_mode)
444
445    else:
446        module.fail_json(**FAIL_SOCKET_MSG)
447
448    if versions_check_result and versions_check_result['matched'] is False:
449        module.warn("Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv")
450
451    if not is_error:
452        if versions_check_result and versions_check_result['matched'] is False:
453            module.exit_json(changed=has_changed, version_check_warning=versions_check_result, meta=result)
454        else:
455            module.exit_json(changed=has_changed, meta=result)
456    else:
457        if versions_check_result and versions_check_result['matched'] is False:
458            module.fail_json(msg="Error in repo", version_check_warning=versions_check_result, meta=result)
459        else:
460            module.fail_json(msg="Error in repo", meta=result)
461
462
463if __name__ == '__main__':
464    main()
465