aboutsummaryrefslogtreecommitdiffstats
path: root/mitmproxy/optmanager.py
blob: 9553bd32604a5e7385080e5bd3248175c4cce2ae (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
import contextlib
import blinker
import pprint
import copy
import functools
import weakref
import os
import typing
import textwrap

import ruamel.yaml

from mitmproxy import exceptions
from mitmproxy.utils import typecheck

"""
    The base implementation for Options.
"""

unset = object()


class _Option:
    __slots__ = ("name", "typespec", "value", "_default", "choices", "help")

    def __init__(
        self,
        name: str,
        typespec: type,
        default: typing.Any,
        help: str,
        choices: typing.Optional[typing.Sequence[str]]
    ) -> None:
        typecheck.check_type(name, default, typespec)
        self.name = name
        self.typespec = typespec
        self._default = default
        self.value = unset
        self.help = help
        self.choices = choices

    def __repr__(self):
        return "{value} [{type}]".format(value=self.current(), type=self.typespec)

    @property
    def default(self):
        return copy.deepcopy(self._default)

    def current(self) -> typing.Any:
        if self.value is unset:
            v = self.default
        else:
            v = self.value
        return copy.deepcopy(v)

    def set(self, value: typing.Any) -> None:
        typecheck.check_type(self.name, value, self.typespec)
        self.value = value

    def reset(self) -> None:
        self.value = unset

    def has_changed(self) -> bool:
        return self.value is not unset

    def __eq__(self, other) -> bool:
        for i in self.__slots__:
            if getattr(self, i) != getattr(other, i):
                return False
        return True

    def __deepcopy__(self, _):
        o = _Option(
            self.name, self.typespec, self.default, self.help, self.choices
        )
        if self.has_changed():
            o.value = self.current()
        return o


class OptManager:
    """
        OptManager is the base class from which Options objects are derived.
        Note that the __init__ method of all child classes must force all
        arguments to be positional only, by including a "*" argument.

        .changed is a blinker Signal that triggers whenever options are
        updated. If any handler in the chain raises an exceptions.OptionsError
        exception, all changes are rolled back, the exception is suppressed,
        and the .errored signal is notified.

        Optmanager always returns a deep copy of options to ensure that
        mutation doesn't change the option state inadvertently.
    """
    def __init__(self):
        self.__dict__["_options"] = {}
        self.__dict__["changed"] = blinker.Signal()
        self.__dict__["errored"] = blinker.Signal()
        self.__dict__["_processed"] = {}

    def add_option(
        self,
        name: str,
        typespec: type,
        default: typing.Any,
        help: str,
        choices: typing.Optional[typing.Sequence[str]] = None
    ) -> None:
        if name in self._options:
            raise ValueError("Option %s already exists" % name)
        self._options[name] = _Option(name, typespec, default, help, choices)

    @contextlib.contextmanager
    def rollback(self, updated, reraise=False):
        old = copy.deepcopy(self._options)
        try:
            yield
        except exceptions.OptionsError as e:
            # Notify error handlers
            self.errored.send(self, exc=e)
            # Rollback
            self.__dict__["_options"] = old
            self.changed.send(self, updated=updated)
            if reraise:
                raise e

    def subscribe(self, func, opts):
        """
            Subscribe a callable to the .changed signal, but only for a
            specified list of options. The callable should accept arguments
            (options, updated), and may raise an OptionsError.
        """
        func = weakref.proxy(func)

        @functools.wraps(func)
        def _call(options, updated):
            if updated.intersection(set(opts)):
                try:
                    func(options, updated)
                except ReferenceError:
                    self.changed.disconnect(_call)

        # Our wrapper function goes out of scope immediately, so we have to set
        # weakrefs to false. This means we need to keep our own weakref, and
        # clean up the hook when it's gone.
        self.changed.connect(_call, weak=False)

    def __eq__(self, other):
        return self._options == other._options

    def __copy__(self):
        o = OptManager()
        o.__dict__["_options"] = copy.deepcopy(self._options)
        return o

    def __getattr__(self, attr):
        if attr in self._options:
            return self._options[attr].current()
        else:
            raise AttributeError("No such option: %s" % attr)

    def __setattr__(self, attr, value):
        self.update(**{attr: value})

    def keys(self):
        return set(self._options.keys())

    def __contains__(self, k):
        return k in self._options

    def reset(self):
        """
            Restore defaults for all options.
        """
        for o in self._options.values():
            o.reset()
        self.changed.send(self._options.keys())

    def update(self, **kwargs):
        updated = set(kwargs.keys())
        with self.rollback(updated):
            for k, v in kwargs.items():
                if k not in self._options:
                    raise KeyError("No such option: %s" % k)
                self._options[k].set(v)
            self.changed.send(self, updated=updated)
        return self

    def setter(self, attr):
        """
            Generate a setter for a given attribute. This returns a callable
            taking a single argument.
        """
        if attr not in self._options:
            raise KeyError("No such option: %s" % attr)

        def setter(x):
            setattr(self, attr, x)
        return setter

    def toggler(self, attr):
        """
            Generate a toggler for a boolean attribute. This returns a callable
            that takes no arguments.
        """
        if attr not in self._options:
            raise KeyError("No such option: %s" % attr)
        o = self._options[attr]
        if o.typespec != bool:
            raise ValueError("Toggler can only be used with boolean options")

        def toggle():
            setattr(self, attr, not getattr(self, attr))
        return toggle

    def default(self, option: str) -> typing.Any:
        return self._options[option].default

    def has_changed(self, option):
        """
            Has the option changed from the default?
        """
        return self._options[option].has_changed()

    def save(self, path, defaults=False):
        """
            Save to path. If the destination file exists, modify it in-place.
        """
        if os.path.exists(path) and os.path.isfile(path):
            with open(path, "r") as f:
                data = f.read()
        else:
            data = ""
        data = self.serialize(data, defaults)
        with open(path, "w") as f:
            f.write(data)

    def serialize(self, text, defaults=False):
        """
            Performs a round-trip serialization. If text is not None, it is
            treated as a previous serialization that should be modified
            in-place.

            - If "defaults" is False, only options with non-default values are
              serialized. Default values in text are preserved.
            - Unknown options in text are removed.
            - Raises OptionsError if text is invalid.
        """
        data = self._load(text)
        for k in self.keys():
            if defaults or self.has_changed(k):
                data[k] = getattr(self, k)
        for k in list(data.keys()):
            if k not in self._options:
                del data[k]
        return ruamel.yaml.round_trip_dump(data)

    def _load(self, text):
        if not text:
            return {}
        try:
            data = ruamel.yaml.load(text, ruamel.yaml.RoundTripLoader)
        except ruamel.yaml.error.YAMLError as v:
            snip = v.problem_mark.get_snippet()
            raise exceptions.OptionsError(
                "Config error at line %s:\n%s\n%s" %
                (v.problem_mark.line + 1, snip, v.problem)
            )
        if isinstance(data, str):
            raise exceptions.OptionsError("Config error - no keys found.")
        return data

    def load(self, text):
        """
            Load configuration from text, over-writing options already set in
            this object. May raise OptionsError if the config file is invalid.
        """
        data = self._load(text)
        try:
            self.update(**data)
        except KeyError as v:
            raise exceptions.OptionsError(v)

    def load_paths(self, *paths):
        """
            Load paths in order. Each path takes precedence over the previous
            path. Paths that don't exist are ignored, errors raise an
            OptionsError.
        """
        for p in paths:
            p = os.path.expanduser(p)
            if os.path.exists(p) and os.path.isfile(p):
                with open(p, "r") as f:
                    txt = f.read()
                try:
                    self.load(txt)
                except exceptions.OptionsError as e:
                    raise exceptions.OptionsError(
                        "Error reading %s: %s" % (p, e)
                    )

    def merge(self, opts):
        """
            Merge a dict of options into this object. Options that have None
            value are ignored. Lists and tuples are appended to the current
            option value.
        """
        toset = {}
        for k, v in opts.items():
            if v is not None:
                if isinstance(v, (list, tuple)):
                    toset[k] = getattr(self, k) + v
                else:
                    toset[k] = v
        self.update(**toset)

    def __repr__(self):
        options = pprint.pformat(self._options, indent=4).strip(" {}")
        if "\n" in options:
            options = "\n    " + options + "\n"
        return "{mod}.{cls}({{{options}}})".format(
            mod=type(self).__module__,
            cls=type(self).__name__,
            options=options
        )

    def set(self, spec):
        parts = spec.split("=", maxsplit=1)
        if len(parts) == 1:
            optname, optval = parts[0], None
        else:
            optname, optval = parts[0], parts[1]
        o = self._options[optname]

        if o.typespec in (str, typing.Optional[str]):
            setattr(self, optname, optval)
        elif o.typespec in (int, typing.Optional[int]):
            if optval:
                try:
                    optval = int(optval)
                except ValueError:
                    raise exceptions.OptionsError("Not an integer: %s" % optval)
            setattr(self, optname, optval)
        elif o.typespec == bool:
            if not optval or optval == "true":
                v = True
            elif optval == "false":
                v = False
            else:
                raise exceptions.OptionsError(
                    "Boolean must be \"true\", \"false\", or have the value " "omitted (a synonym for \"true\")."
                )
            setattr(self, optname, v)
        elif o.typespec == typing.Sequence[str]:
            if not optval:
                setattr(self, optname, [])
            else:
                setattr(
                    self,
                    optname,
                    getattr(self, optname) + [optval]
                )
        else:  # pragma: no cover
            raise NotImplementedError("Unsupported option type: %s", o.typespec)

    def make_parser(self, parser, optname, metavar=None, short=None):
        o = self._options[optname]

        def mkf(l, s):
            l = l.replace("_", "-")
            f = ["--%s" % l]
            if s:
                f.append("-" + s)
            return f

        flags = mkf(optname, short)

        if o.typespec == bool:
            g = parser.add_mutually_exclusive_group(required=False)
            onf = mkf(optname, None)
            offf = mkf("no-" + optname, None)
            # The short option for a bool goes to whatever is NOT the default
            if short:
                if o.default:
                    offf = mkf("no-" + optname, short)
                else:
                    onf = mkf(optname, short)
            g.add_argument(
                *offf,
                action="store_false",
                dest=optname,
            )
            g.add_argument(
                *onf,
                action="store_true",
                dest=optname,
                help=o.help
            )
            parser.set_defaults(**{optname: None})
        elif o.typespec in (int, typing.Optional[int]):
            parser.add_argument(
                *flags,
                action="store",
                type=int,
                dest=optname,
                help=o.help,
                metavar=metavar,
            )
        elif o.typespec in (str, typing.Optional[str]):
            parser.add_argument(
                *flags,
                action="store",
                type=str,
                dest=optname,
                help=o.help,
                metavar=metavar,
                choices=o.choices
            )
        elif o.typespec == typing.Sequence[str]:
            parser.add_argument(
                *flags,
                action="append",
                type=str,
                dest=optname,
                help=o.help + " May be passed multiple times.",
                metavar=metavar,
                choices=o.choices,
            )
        else:
            raise ValueError("Unsupported option type: %s", o.typespec)


def dump(opts):
    """
        Dumps an annotated file with all options.
    """
    # Sort data
    s = ruamel.yaml.comments.CommentedMap()
    for k in sorted(opts.keys()):
        o = opts._options[k]
        s[k] = o.default
        txt = o.help.strip()

        if o.choices:
            txt += " Valid values are %s." % ", ".join(repr(c) for c in o.choices)
        else:
            if o.typespec in (str, int, bool):
                t = o.typespec.__name__
            elif o.typespec == typing.Optional[str]:
                t = "optional str"
            elif o.typespec == typing.Sequence[str]:
                t = "sequence of str"
            else:  # pragma: no cover
                raise NotImplementedError
            txt += " Type %s." % t

        txt = "\n".join(
            textwrap.wrap(
                textwrap.dedent(txt)
            )
        )
        s.yaml_set_comment_before_after_key(k, before = "\n" + txt)
    return ruamel.yaml.round_trip_dump(s)