config.py 22.8 KB
Newer Older
juga's avatar
juga committed
1
2
"""Util functions to manage sbws configuration files."""

3
from configparser import (ConfigParser, ExtendedInterpolation)
Matt Traudt's avatar
Matt Traudt committed
4
from configparser import InterpolationMissingOptionError
5
import os
6
7
import logging
import logging.config
8
from urllib.parse import urlparse
Matt Traudt's avatar
Matt Traudt committed
9
from string import Template
10
from tempfile import NamedTemporaryFile
juga's avatar
juga committed
11
from sbws.globals import (DEFAULT_CONFIG_PATH, DEFAULT_LOG_CONFIG_PATH,
12
                          USER_CONFIG_PATH, SUPERVISED_RUN_DPATH,
13
                          SUPERVISED_USER_CONFIG_PATH)
14

15
16
from sbws.util.iso3166 import ISO_3166_ALPHA_2

17
18
19
20
_ALPHANUM = 'abcdefghijklmnopqrstuvwxyz'
_ALPHANUM += _ALPHANUM.upper()
_ALPHANUM += '0123456789'

Matt Traudt's avatar
Matt Traudt committed
21
22
_SYMBOLS_NO_QUOTES = '!@#$%^&*()-_=+\\|[]{}:;/?.,<>'

23
_HEX = '0123456789ABCDEF'
24

Matt Traudt's avatar
Matt Traudt committed
25
26
_LOG_LEVELS = ['debug', 'info', 'warning', 'error', 'critical']

27
log = logging.getLogger(__name__)
28

29

30
31
def _expand_path(path):
    """Expand path string containing shell variables and ~ constructions
32
33
    into their values. Environment variables have to have their $ escaped by
    another $. For example: $$XDG_RUNTIME_DIR/foo.bar
34
35
36
37
    """
    return os.path.expanduser(os.path.expandvars(path))


38
39
def _extend_config(conf, fname):
    """Extend ConfigParser from file configuration."""
40
    log.debug('Reading config file %s', fname)
41
42
43
44
45
    with open(fname, 'rt') as fd:
        conf.read_file(fd, source=fname)
    return conf


46
def _get_default_config():
juga's avatar
juga committed
47
    """Return ConfigParser with default configuration."""
48
49
    conf = ConfigParser(interpolation=ExtendedInterpolation(),
                        converters={'path': _expand_path})
50
    return _extend_config(conf, DEFAULT_CONFIG_PATH)
51
52


53
54
55
56
57
58
def _obtain_user_conf_path():
    if os.environ.get("SUPERVISED") == "1":
        return SUPERVISED_USER_CONFIG_PATH
    return USER_CONFIG_PATH


59
def _get_user_config(args, conf=None):
juga's avatar
juga committed
60
    """Get user configuration.
61
62
    Search for user configuration in the default path or the path passed as
    argument and extend the configuration if they are found.
juga's avatar
juga committed
63
    """
64
    if not conf:
65
66
        conf = ConfigParser(interpolation=ExtendedInterpolation(),
                            converters={'path': _expand_path})
67
68
    else:
        assert isinstance(conf, ConfigParser)
juga's avatar
juga committed
69
70
    if args.config:
        if not os.path.isfile(args.config):
71
72
73
74
            # XXX: The logger is not configured at this stage,
            # sbws should start with a logger before reading configurations.
            print('Configuration file %s not found, using defaults.' %
                  args.config)
75
76
77
            return conf
        print('Using configuration provided as argument %s' % args.config)
        return _extend_config(conf, args.config)
78
79
    user_config_path = _obtain_user_conf_path()
    if os.path.isfile(user_config_path):
80
        print('Using configuration file %s' % user_config_path)
81
        return _extend_config(conf, user_config_path)
82
    log.debug('No user config found, using defaults.')
83
    return conf
juga's avatar
juga committed
84
85
86
87


def _get_default_logging_config(conf=None):
    """Get default logging configuration."""
88
    if not conf:
89
90
        conf = ConfigParser(interpolation=ExtendedInterpolation(),
                            converters={'path': _expand_path})
91
92
    else:
        assert isinstance(conf, ConfigParser)
juga's avatar
juga committed
93
    return _extend_config(conf, DEFAULT_LOG_CONFIG_PATH)
94
95


96
def get_config(args):
juga's avatar
juga committed
97
    """Get ConfigParser interpolating all configuration files."""
98
    conf = _get_default_config()
juga's avatar
juga committed
99
    conf = _get_default_logging_config(conf=conf)
100
101
102
103
    conf = _get_user_config(args, conf=conf)
    return conf


Matt Traudt's avatar
Matt Traudt committed
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
def _can_log_to_file(conf):
    '''
    Checks all the known reasons for why we might not be able to log to a file,
    and returns whether or not we think we will be able to do so. This is
    useful because if we can't log to a file, we might want to force logging to
    stdout.

    If we can't log to file, return False and the reason. Otherwise return True
    and an empty string.
    '''
    # We won't be able to get paths.log_dname from the config when we are first
    # initializing sbws because it depends on paths.sbws_home (by default).
    # If there is an issue getting this option, tell the caller that we can't
    # log to file.
    try:
119
        conf.getpath('paths', 'log_dname')
Matt Traudt's avatar
Matt Traudt committed
120
121
122
123
124
125
    except InterpolationMissingOptionError as e:
        return False, e
    return True, ''


def configure_logging(args, conf):
126
    assert isinstance(conf, ConfigParser)
Matt Traudt's avatar
Matt Traudt committed
127
128
129
130
131
132
133
134
135
    logger = 'logger_sbws'
    # Set the correct handler(s) based on [logging] options
    handlers = set()
    can_log_to_file, reason = _can_log_to_file(conf)
    if not can_log_to_file or conf.getboolean('logging', 'to_stdout'):
        # always add to_stdout if we cannot log to file
        handlers.add('to_stdout')
    if can_log_to_file and conf.getboolean('logging', 'to_file'):
        handlers.add('to_file')
juga's avatar
juga committed
136
137
    if conf.getboolean('logging', 'to_syslog'):
        handlers.add('to_syslog')
Matt Traudt's avatar
Matt Traudt committed
138
139
140
    # Collect the handlers in the appropriate config option
    conf[logger]['handlers'] = ','.join(handlers)
    if 'to_file' in handlers:
141
        # This is weird.
Matt Traudt's avatar
Matt Traudt committed
142
        #
143
144
145
146
147
148
        # Python's logging library expects 'args' to be a tuple ... but it has
        # to be stored as a string and it evals() the string.
        #
        # The first argument is the file name to which it should log. Set it to
        # the sbws command (like 'scanner' or 'generate') if possible, or to
        # 'sbws' failing that.
149
        dname = conf.getpath('paths', 'log_dname')
Matt Traudt's avatar
Matt Traudt committed
150
151
        os.makedirs(dname, exist_ok=True)
        fname = os.path.join(dname, '{}.log'.format(args.command or 'sbws'))
Matt Traudt's avatar
Matt Traudt committed
152
153
154
        # The second argument is the file mode, and it should be left alone
        mode = 'a'
        # The third is the maximum file size (in bytes) each log file should be
155
        max_bytes = conf.getint('logging', 'to_file_max_bytes')
Matt Traudt's avatar
Matt Traudt committed
156
        # And the forth is the number of backups to keep
157
158
        num_backups = conf.getint('logging', 'to_file_num_backups')
        # Now store those things as a string in the config. So dumb.
Matt Traudt's avatar
Matt Traudt committed
159
160
        conf['handler_to_file']['args'] = \
            str((fname, mode, max_bytes, num_backups))
Matt Traudt's avatar
Matt Traudt committed
161
162
163
    # Set some stuff that needs config parser's interpolation
    conf['formatter_to_file']['format'] = conf['logging']['to_file_format']
    conf['formatter_to_stdout']['format'] = conf['logging']['to_stdout_format']
juga's avatar
juga committed
164
    conf['formatter_to_syslog']['format'] = conf['logging']['to_syslog_format']
Matt Traudt's avatar
Matt Traudt committed
165
166
167
168
    conf[logger]['level'] = conf['logging']['level'].upper()
    conf['handler_to_file']['level'] = conf['logging']['to_file_level'].upper()
    conf['handler_to_stdout']['level'] = \
        conf['logging']['to_stdout_level'].upper()
juga's avatar
juga committed
169
170
    conf['handler_to_syslog']['level'] = \
        conf['logging']['to_syslog_level'].upper()
171
172
173
174
175
176
177
178
179
    # If there's a log_level cli argument, the user would expect that level
    # in the standard output.
    # conf['logging']['level'] sets the lower level, but it's still needed to
    # set the stdout level.
    # It also must be set up in the end, since cli arguments have higher
    # priority.
    if args.log_level:
        conf['logging']['level'] = args.log_level.upper()
        conf['handler_to_stdout']['level'] = conf['logging']['level']
Matt Traudt's avatar
Matt Traudt committed
180
    # Now we configure the standard python logging system
181
182
183
184
185
186
    with NamedTemporaryFile('w+t') as fd:
        conf.write(fd)
        fd.seek(0, 0)
        logging.config.fileConfig(fd.name)


Matt Traudt's avatar
Matt Traudt committed
187
188
189
190
191
192
def validate_config(conf):
    ''' Checks the given conf for bad values or bad combinations of values. If
    there's something wrong, returns False and a list of error messages.
    Otherwise, return True and an empty list '''
    errors = []
    errors.extend(_validate_general(conf))
193
    errors.extend(_validate_cleanup(conf))
Matt Traudt's avatar
Matt Traudt committed
194
    errors.extend(_validate_scanner(conf))
Matt Traudt's avatar
Matt Traudt committed
195
196
    errors.extend(_validate_tor(conf))
    errors.extend(_validate_paths(conf))
197
    errors.extend(_validate_destinations(conf))
198
    errors.extend(_validate_relayprioritizer(conf))
199
    errors.extend(_validate_logging(conf))
Matt Traudt's avatar
Matt Traudt committed
200
201
202
    return len(errors) < 1, errors


203
204
205
206
207
def _validate_cleanup(conf):
    errors = []
    sec = 'cleanup'
    err_tmpl = Template('$sec/$key ($val): $e')
    ints = {
Matt Traudt's avatar
Matt Traudt committed
208
209
        'data_files_compress_after_days': {'minimum': 1, 'maximum': None},
        'data_files_delete_after_days': {'minimum': 1, 'maximum': None},
210
211
        'v3bw_files_compress_after_days': {'minimum': 1, 'maximum': None},
        'v3bw_files_delete_after_days': {'minimum': 1, 'maximum': None},
212
213
214
215
216
217
218
    }
    all_valid_keys = list(ints.keys())
    errors.extend(_validate_section_keys(conf, sec, all_valid_keys, err_tmpl))
    errors.extend(_validate_section_ints(conf, sec, ints, err_tmpl))
    return errors


Matt Traudt's avatar
Matt Traudt committed
219
220
221
222
223
224
def _validate_general(conf):
    errors = []
    sec = 'general'
    err_tmpl = Template('$sec/$key ($val): $e')
    ints = {
        'data_period': {'minimum': 1, 'maximum': None},
225
        'circuit_timeout': {'minimum': 1, 'maximum': None},
Matt Traudt's avatar
Matt Traudt committed
226
    }
Matt Traudt's avatar
Matt Traudt committed
227
228
229
    floats = {
        'http_timeout': {'minimum': 0.0, 'maximum': None},
    }
230
231
232
233
    bools = {
        'reset_bw_ipv4_changes': {},
        'reset_bw_ipv6_changes': {},
    }
234
235
    all_valid_keys = list(ints.keys()) + list(floats.keys()) + \
        list(bools.keys())
Matt Traudt's avatar
Matt Traudt committed
236
237
    errors.extend(_validate_section_keys(conf, sec, all_valid_keys, err_tmpl))
    errors.extend(_validate_section_ints(conf, sec, ints, err_tmpl))
Matt Traudt's avatar
Matt Traudt committed
238
    errors.extend(_validate_section_floats(conf, sec, floats, err_tmpl))
239
    errors.extend(_validate_section_bools(conf, sec, bools, err_tmpl))
Matt Traudt's avatar
Matt Traudt committed
240
241
242
    return errors


243
244
245
246
247
248
249
def _obtain_sbws_home(conf):
    sbws_home = conf.getpath('paths', 'sbws_home')
    # No need for .sbws when this is the default home
    if sbws_home == "/var/lib/sbws/.sbws":
        conf['paths']['sbws_home'] = os.path.dirname(sbws_home)


250
251
252
253
254
255
256
257
258
def _obtain_run_dpath(conf):
    """Set runtime directory when sbws is run by a system service."""
    xdg = os.environ.get('XDG_RUNTIME_DIR')
    if os.environ.get('SUPERVISED') == "1":
        conf['tor']['run_dpath'] = SUPERVISED_RUN_DPATH
    elif xdg is not None:
        conf['tor']['run_dpath'] = os.path.join(xdg, 'sbws', 'tor')


Matt Traudt's avatar
Matt Traudt committed
259
def _validate_paths(conf):
260
    _obtain_sbws_home(conf)
Matt Traudt's avatar
Matt Traudt committed
261
262
263
    errors = []
    sec = 'paths'
    err_tmpl = Template('$sec/$key ($val): $e')
Matt Traudt's avatar
Matt Traudt committed
264
    unvalidated_keys = [
265
266
        'datadir', 'sbws_home', 'v3bw_fname', 'v3bw_dname', 'state_fname',
        'log_dname']
Matt Traudt's avatar
Matt Traudt committed
267
    all_valid_keys = unvalidated_keys
268
269
270
    allow_missing = ['sbws_home']
    errors.extend(_validate_section_keys(conf, sec, all_valid_keys, err_tmpl,
                                         allow_missing=allow_missing))
Matt Traudt's avatar
Matt Traudt committed
271
272
273
    return errors


274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
def _validate_country(conf, sec, key, err_tmpl):
    errors = []
    if conf[sec].get(key, None) is None:
        errors.append(err_tmpl.substitute(
            sec=sec, key=key, val=None,
            e="Missing country in configuration file."))
        return errors
    valid = conf[sec]['country'] in ISO_3166_ALPHA_2
    if not valid:
        errors.append(err_tmpl.substitute(
            sec=sec, key=key, val=conf[sec][key],
            e="Not a valid ISO 3166 alpha-2 country code."))
    return errors


Matt Traudt's avatar
Matt Traudt committed
289
def _validate_scanner(conf):
Matt Traudt's avatar
Matt Traudt committed
290
    errors = []
Matt Traudt's avatar
Matt Traudt committed
291
    sec = 'scanner'
Matt Traudt's avatar
Matt Traudt committed
292
293
    err_tmpl = Template('$sec/$key ($val): $e')
    ints = {
juga's avatar
juga committed
294
        'num_rtts': {'minimum': 0, 'maximum': 100},
295
        'num_downloads': {'minimum': 1, 'maximum': 100},
Matt Traudt's avatar
Matt Traudt committed
296
297
        'initial_read_request': {'minimum': 1, 'maximum': None},
        'measurement_threads': {'minimum': 1, 'maximum': None},
298
299
        'min_download_size': {'minimum': 1, 'maximum': None},
        'max_download_size': {'minimum': 1, 'maximum': None},
Matt Traudt's avatar
Matt Traudt committed
300
301
302
303
304
305
306
    }
    floats = {
        'download_toofast': {'minimum': 0.001, 'maximum': None},
        'download_min': {'minimum': 0.001, 'maximum': None},
        'download_target': {'minimum': 0.001, 'maximum': None},
        'download_max': {'minimum': 0.001, 'maximum': None},
    }
juga's avatar
juga committed
307
    all_valid_keys = list(ints.keys()) + list(floats.keys()) + \
308
        ['nickname', 'country']
Matt Traudt's avatar
Matt Traudt committed
309
310
311
    errors.extend(_validate_section_keys(conf, sec, all_valid_keys, err_tmpl))
    errors.extend(_validate_section_ints(conf, sec, ints, err_tmpl))
    errors.extend(_validate_section_floats(conf, sec, floats, err_tmpl))
312
313
314
315
    valid, error_msg = _validate_nickname(conf[sec], 'nickname')
    if not valid:
        errors.append(err_tmpl.substitute(
            sec=sec, key='nickname', val=conf[sec]['nickname'], e=error_msg))
316
    errors.extend(_validate_country(conf, sec, 'country', err_tmpl))
Matt Traudt's avatar
Matt Traudt committed
317
318
319
320
    return errors


def _validate_tor(conf):
321
    _obtain_run_dpath(conf)
Matt Traudt's avatar
Matt Traudt committed
322
323
324
    errors = []
    sec = 'tor'
    err_tmpl = Template('$sec/$key ($val): $e')
325
    unvalidated_keys = [
326
327
328
        'datadir', 'run_dpath', 'control_socket', 'pid', 'log',
        'external_control_port', 'extra_lines',
    ]
Matt Traudt's avatar
Matt Traudt committed
329
    all_valid_keys = unvalidated_keys
Matt Traudt's avatar
Matt Traudt committed
330
331
332
333
    errors.extend(_validate_section_keys(conf, sec, all_valid_keys, err_tmpl))
    return errors


334
335
336
337
338
339
340
341
342
343
def _validate_relayprioritizer(conf):
    errors = []
    sec = 'relayprioritizer'
    err_tmpl = Template('$sec/$key ($val): $e')
    ints = {
        'min_relays': {'minimum': 1, 'maximum': None},
    }
    floats = {
        'fraction_relays': {'minimum': 0.0, 'maximum': 1.0},
    }
344
345
346
347
348
    bools = {
        'measure_authorities': {},
    }
    all_valid_keys = list(ints.keys()) + list(floats.keys()) +\
        list(bools.keys())
349
350
351
    errors.extend(_validate_section_keys(conf, sec, all_valid_keys, err_tmpl))
    errors.extend(_validate_section_ints(conf, sec, ints, err_tmpl))
    errors.extend(_validate_section_floats(conf, sec, floats, err_tmpl))
352
    errors.extend(_validate_section_bools(conf, sec, bools, err_tmpl))
353
354
355
    return errors


356
357
358
359
360
def _validate_logging(conf):
    errors = []
    sec = 'logging'
    err_tmpl = Template('$sec/$key ($val): $e')
    enums = {
Matt Traudt's avatar
Matt Traudt committed
361
362
363
        'level': {'choices': _LOG_LEVELS},
        'to_file_level': {'choices': _LOG_LEVELS},
        'to_stdout_level': {'choices': _LOG_LEVELS},
juga's avatar
juga committed
364
        'to_syslog_level': {'choices': _LOG_LEVELS},
365
366
367
368
    }
    bools = {
        'to_file': {},
        'to_stdout': {},
juga's avatar
juga committed
369
        'to_syslog': {},
370
    }
371
372
373
374
    ints = {
        'to_file_max_bytes': {'minimum': 0, 'maximum': None},
        'to_file_num_backups': {'minimum': 0, 'maximum': None},
    }
juga's avatar
juga committed
375
376
    unvalidated = ['format', 'to_file_format', 'to_stdout_format',
                   'to_syslog_format']
377
378
    all_valid_keys = list(bools.keys()) + list(enums.keys()) + \
        list(ints.keys()) + unvalidated
379
380
381
382
383
384
    errors.extend(_validate_section_keys(conf, sec, all_valid_keys, err_tmpl))
    errors.extend(_validate_section_bools(conf, sec, bools, err_tmpl))
    errors.extend(_validate_section_enums(conf, sec, enums, err_tmpl))
    return errors


385
def _validate_destinations(conf):
386
    errors = []
387
    sec = 'destinations'
388
389
    section = conf[sec]
    err_tmpl = Template('$sec/$key ($val): $e')
390
    dest_sections = []
391
    for key in section.keys():
392
393
394
395
396
397
398
        if key == 'usability_test_interval':
            value = section[key]
            valid, error_msg = _validate_int(section, key, minimum=1)
            if not valid:
                errors.append(err_tmpl.substitute(
                    sec=sec, key=key, val=value, e=error_msg))
            continue
399
        value = section[key]
400
        valid, error_msg = _validate_boolean(section, key)
401
402
403
404
405
406
        if not valid:
            errors.append(err_tmpl.substitute(
                sec=sec, key=key, val=value, e=error_msg))
            continue
        assert valid
        if section.getboolean(key):
407
408
409
            dest_sections.append('{}.{}'.format(sec, key))
    urls = {
        'url': {},
410
    }
411
412
    all_valid_keys = list(urls.keys()) \
        + ['verify', 'country', 'max_num_failures']
413
    for sec in dest_sections:
414
        if sec not in conf:
415
416
            errors.append('{} is an enabled destination but is not a '
                          'section in the config'.format(sec))
417
            continue
418
        errors.extend(_validate_section_keys(
419
420
            conf, sec, all_valid_keys, err_tmpl,
            allow_missing=['verify', 'max_num_failures']))
421
        errors.extend(_validate_section_urls(conf, sec, urls, err_tmpl))
422
        errors.extend(_validate_country(conf, sec, 'country', err_tmpl))
423
424
425
    return errors


426
427
428
def _validate_section_keys(conf, sec, keys, tmpl, allow_missing=None):
    if allow_missing is None:
        allow_missing = []
Matt Traudt's avatar
Matt Traudt committed
429
430
    errors = []
    section = conf[sec]
431
    # Find keys that exist in the user's config that are not known
Matt Traudt's avatar
Matt Traudt committed
432
433
434
435
    for key in section:
        if key not in keys:
            errors.append(tmpl.substitute(
                sec=sec, key=key, val=section[key], e='Unknown key'))
436
437
438
439
440
    # Find keys that don't exist in the user's config that should
    for key in keys:
        if key not in section and key not in allow_missing:
            errors.append(tmpl.substitute(
                sec=sec, key=key, val='[NOT SET]', e='Missing key'))
Matt Traudt's avatar
Matt Traudt committed
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
    return errors


def _validate_section_ints(conf, sec, ints, tmpl):
    errors = []
    section = conf[sec]
    for key in ints:
        valid, error = _validate_int(
            section, key, minimum=ints[key]['minimum'],
            maximum=ints[key]['maximum'])
        if not valid:
            errors.append(tmpl.substitute(
                sec=sec, key=key, val=section[key], e=error))
    return errors


def _validate_section_floats(conf, sec, floats, tmpl):
    errors = []
    section = conf[sec]
    for key in floats:
        valid, error = _validate_float(
            section, key, minimum=floats[key]['minimum'],
            maximum=floats[key]['maximum'])
        if not valid:
            errors.append(tmpl.substitute(
                sec=sec, key=key, val=section[key], e=error))
    return errors


def _validate_section_hosts(conf, sec, hosts, tmpl):
    errors = []
    section = conf[sec]
    for key in hosts:
        valid, error = _validate_host(section, key)
        if not valid:
            errors.append(tmpl.substitute(
                sec=sec, key=key, val=section[key], e=error))
    return errors


def _validate_section_ports(conf, sec, ports, tmpl):
    errors = []
    section = conf[sec]
    for key in ports:
        valid, error = _validate_int(section, key, minimum=1, maximum=2**16)
        if not valid:
            errors.append(tmpl.substitute(
                sec=sec, key=key, val=section[key],
                e='Not a valid port ({})'.format(error)))
    return errors


493
494
495
496
497
498
499
500
501
502
503
504
def _validate_section_bools(conf, sec, bools, tmpl):
    errors = []
    section = conf[sec]
    for key in bools:
        valid, error = _validate_boolean(section, key)
        if not valid:
            errors.append(tmpl.substitute(
                sec=sec, key=key, val=section[key],
                e='Not a valid boolean string ({})'.format(error)))
    return errors


505
506
507
508
509
510
511
512
513
514
515
516
def _validate_section_fingerprints(conf, sec, fps, tmpl):
    errors = []
    section = conf[sec]
    for key in fps:
        valid, error = _validate_fingerprint(section, key)
        if not valid:
            errors.append(tmpl.substitute(
                sec=sec, key=key, val=section[key],
                e='Not a valid fingerprint ({})'.format(error)))
    return errors


517
518
519
520
521
522
523
524
525
526
527
528
def _validate_section_urls(conf, sec, urls, tmpl):
    errors = []
    section = conf[sec]
    for key in urls:
        valid, error = _validate_url(section, key)
        if not valid:
            errors.append(tmpl.substitute(
                sec=sec, key=key, val=section[key],
                e='Not a valid url ({})'.format(error)))
    return errors


Matt Traudt's avatar
Matt Traudt committed
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
def _validate_section_enums(conf, sec, enums, tmpl):
    errors = []
    section = conf[sec]
    for key in enums:
        choices = enums[key]['choices']
        valid, error = _validate_enum(section, key, choices)
        if not valid:
            errors.append(tmpl.substitute(
                sec=sec, key=key, val=section[key],
                e='Not a valid enum choice ({})'.format(', '.join(choices))))
    return errors


def _validate_enum(section, key, choices):
    value = section[key]
    if value not in choices:
        return False, '{} not in allowed choices: {}'.format(
            value, ', '.join(choices))
    return True, ''


550
551
552
553
554
def _validate_url(section, key):
    value = section[key]
    url = urlparse(value)
    if not url.netloc:
        return False, 'Does not appear to contain a hostname'
555
556
557
558
559
560
561
    # It should be possible to have an URL that starts by http:// that uses
    # TLS,but python requests is just checking the scheme starts by https
    # when verifying certificate:
    # https://github.com/requests/requests/blob/master/requests/adapters.py#L215  # noqa
    # When the scheme is https but the protocol is not TLS, requests will hang.
    if url.scheme != 'https' and not url.netloc.startswith('127.0.0.1'):
        return False, 'URL scheme must be HTTPS (except for the test server)'
562
563
564
    return True, ''


Matt Traudt's avatar
Matt Traudt committed
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
def _validate_int(section, key, minimum=None, maximum=None):
    try:
        value = section.getint(key)
    except ValueError as e:
        return False, e
    if minimum is not None:
        assert isinstance(minimum, int)
        if value < minimum:
            return False, 'Cannot be less than {}'.format(minimum)
    if maximum is not None:
        assert isinstance(maximum, int)
        if value > maximum:
            return False, 'Cannot be greater than {}'.format(maximum)
    return True, ''


581
582
583
584
585
586
587
588
def _validate_boolean(section, key):
    try:
        section.getboolean(key)
    except ValueError as e:
        return False, e
    return True, ''


Matt Traudt's avatar
Matt Traudt committed
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
def _validate_float(section, key, minimum=None, maximum=None):
    try:
        value = section.getfloat(key)
    except ValueError as e:
        return False, e
    if minimum is not None:
        assert isinstance(minimum, float)
        if value < minimum:
            return False, 'Cannot be less than {}'.format(minimum)
    if maximum is not None:
        assert isinstance(maximum, float)
        if value > maximum:
            return False, 'Cannot be greater than {}'.format(maximum)
    return True, ''


def _validate_host(section, key):
    # XXX: Implement this
    return True, ''
608
609
610


def _validate_fingerprint(section, key):
611
    alphabet = _HEX
612
613
614
615
616
    length = 40
    return _validate_string(section, key, min_len=length, max_len=length,
                            alphabet=alphabet)


617
def _validate_nickname(section, key):
Matt Traudt's avatar
Matt Traudt committed
618
    alphabet = _ALPHANUM + _SYMBOLS_NO_QUOTES
619
620
621
622
623
624
    min_len = 1
    max_len = 32
    return _validate_string(section, key, min_len=min_len, max_len=max_len,
                            alphabet=alphabet)


625
626
def _validate_string(section, key, min_len=None, max_len=None, alphabet=None,
                     starts_with=None):
627
628
629
630
631
632
633
634
635
636
637
638
    s = section[key]
    if min_len is not None and len(s) < min_len:
        return False, '{} is below minimum allowed length {}'.format(
            len(s), min_len)
    if max_len is not None and len(s) > max_len:
        return False, '{} is above maximum allowed length {}'.format(
            len(s), max_len)
    if alphabet is not None:
        for i, c in enumerate(s):
            if c not in alphabet:
                return False, 'Letter {} at position {} is not in allowed '\
                    'characters "{}"'.format(c, i, alphabet)
639
640
641
    if starts_with is not None:
        if not s.startswith(starts_with):
            return False, '{} does not start with {}'.format(s, starts_with)
642
    return True, ''