Read a config file: execute a python file while loading scapy, that may contain some pre-configured values. If _globals or _locals are specified, they will be updated with the loaded vars. This allows an external program to use the function. Otherwise, vars are only available from
(cf, _globals=globals(), _locals=locals(),
interactive=True, default=None)
| 130 | |
| 131 | |
| 132 | def _read_config_file(cf, _globals=globals(), _locals=locals(), |
| 133 | interactive=True, default=None): |
| 134 | # type: (str, Dict[str, Any], Dict[str, Any], bool, Optional[str]) -> None |
| 135 | """Read a config file: execute a python file while loading scapy, that |
| 136 | may contain some pre-configured values. |
| 137 | |
| 138 | If _globals or _locals are specified, they will be updated with |
| 139 | the loaded vars. This allows an external program to use the |
| 140 | function. Otherwise, vars are only available from inside the scapy |
| 141 | console. |
| 142 | |
| 143 | Parameters: |
| 144 | |
| 145 | :param _globals: the globals() vars |
| 146 | :param _locals: the locals() vars |
| 147 | :param interactive: specified whether or not errors should be printed |
| 148 | using the scapy console or raised. |
| 149 | :param default: if provided, set a default value for the config file |
| 150 | |
| 151 | ex, content of a config.py file: |
| 152 | 'conf.verb = 42\n' |
| 153 | Manual loading: |
| 154 | >>> _read_config_file("./config.py")) |
| 155 | >>> conf.verb |
| 156 | 2 |
| 157 | |
| 158 | """ |
| 159 | cf_path = pathlib.Path(cf) |
| 160 | if not cf_path.exists(): |
| 161 | log_loading.debug("Config file [%s] does not exist.", cf) |
| 162 | if default is None: |
| 163 | return |
| 164 | # We have a default ! set it |
| 165 | try: |
| 166 | if not cf_path.parent.exists(): |
| 167 | cf_path.parent.mkdir(parents=True, exist_ok=True) |
| 168 | _check_perms(cf_path.parent) |
| 169 | |
| 170 | with cf_path.open("w") as fd: |
| 171 | fd.write(default) |
| 172 | |
| 173 | _check_perms(cf_path) |
| 174 | log_loading.debug("Config file [%s] created with default.", cf) |
| 175 | except OSError: |
| 176 | log_loading.warning("Config file [%s] could not be created.", cf, |
| 177 | exc_info=True) |
| 178 | return |
| 179 | log_loading.debug("Loading config file [%s]", cf) |
| 180 | try: |
| 181 | with open(cf) as cfgf: |
| 182 | exec( |
| 183 | compile(cfgf.read(), cf, 'exec'), |
| 184 | _globals, _locals |
| 185 | ) |
| 186 | except IOError as e: |
| 187 | if interactive: |
| 188 | raise |
| 189 | log_loading.warning("Cannot read config file [%s] [%s]", cf, e) |