aboutsummaryrefslogtreecommitdiffstats
path: root/mitmproxy/tools/console/commander/commander.py
blob: d751422b28da35740b5c88bc98b8612f1886eba0 (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
import abc
import collections
import copy
import typing

import urwid
from urwid.text_layout import calc_coords

import mitmproxy.command
import mitmproxy.flow
import mitmproxy.master
import mitmproxy.types


class Completer:
    @abc.abstractmethod
    def cycle(self, forward: bool = True) -> str:
        raise NotImplementedError()


class ListCompleter(Completer):
    def __init__(
            self,
            start: str,
            options: typing.Sequence[str],
    ) -> None:
        self.start = start
        self.options: typing.List[str] = []
        for o in options:
            if o.startswith(start):
                self.options.append(o)
        self.options.sort()
        self.offset = 0

    def cycle(self, forward: bool = True) -> str:
        if not self.options:
            return self.start
        ret = self.options[self.offset]
        delta = 1 if forward else -1
        self.offset = (self.offset + delta) % len(self.options)
        return ret


class CompletionState(typing.NamedTuple):
    completer: Completer
    parsed: typing.Sequence[mitmproxy.command.ParseResult]


class CommandBuffer:
    def __init__(self, master: mitmproxy.master.Master, start: str = "") -> None:
        self.master = master
        self.text = start
        # Cursor is always within the range [0:len(buffer)].
        self._cursor = len(self.text)
        self.completion: typing.Optional[CompletionState] = None

    @property
    def cursor(self) -> int:
        return self._cursor

    @cursor.setter
    def cursor(self, x) -> None:
        if x < 0:
            self._cursor = 0
        elif x > len(self.text):
            self._cursor = len(self.text)
        else:
            self._cursor = x

    def render(self):
        parts, remaining = self.master.commands.parse_partial(self.text)
        ret = []
        if not parts:
            # Means we just received the leader, so we need to give a blank
            # text to the widget to render or it crashes
            ret.append(("text", ""))
        else:
            for p in parts:
                if p.valid:
                    if p.type == mitmproxy.types.Cmd:
                        ret.append(("commander_command", p.value))
                    else:
                        ret.append(("text", p.value))
                elif p.value:
                    ret.append(("commander_invalid", p.value))

            if remaining:
                if parts[-1].type != mitmproxy.types.Space:
                    ret.append(("text", " "))
                for param in remaining:
                    ret.append(("commander_hint", f"{param} "))

        return ret

    def left(self) -> None:
        self.cursor = self.cursor - 1

    def right(self) -> None:
        self.cursor = self.cursor + 1

    def cycle_completion(self, forward: bool = True) -> None:
        if not self.completion:
            parts, remaining = self.master.commands.parse_partial(self.text[:self.cursor])
            if parts and parts[-1].type != mitmproxy.types.Space:
                type_to_complete = parts[-1].type
                cycle_prefix = parts[-1].value
                parsed = parts[:-1]
            elif remaining:
                type_to_complete = remaining[0].type
                cycle_prefix = ""
                parsed = parts
            else:
                return
            ct = mitmproxy.types.CommandTypes.get(type_to_complete, None)
            if ct:
                self.completion = CompletionState(
                    completer=ListCompleter(
                        cycle_prefix,
                        ct.completion(self.master.commands, type_to_complete, cycle_prefix)
                    ),
                    parsed=parsed,
                )
        if self.completion:
            nxt = self.completion.completer.cycle(forward)
            buf = "".join([i.value for i in self.completion.parsed]) + nxt
            self.text = buf
            self.cursor = len(self.text)

    def backspace(self) -> None:
        if self.cursor == 0:
            return
        self.text = self.text[:self.cursor - 1] + self.text[self.cursor:]
        self.cursor = self.cursor - 1
        self.completion = None

    def insert(self, k: str) -> None:
        """
            Inserts text at the cursor.
        """

        # We don't want to insert a space before the command
        if k == ' ' and self.text[0:self.cursor].strip() == '':
            return

        self.text = self.text[:self.cursor] + k + self.text[self.cursor:]
        self.cursor += len(k)
        self.completion = None


class CommandHistory:
    def __init__(self, master: mitmproxy.master.Master, size: int = 30) -> None:
        self.saved_commands: collections.deque = collections.deque(
            [CommandBuffer(master, "")],
            maxlen=size
        )
        self.index: int = 0

    @property
    def last_index(self):
        return len(self.saved_commands) - 1

    def get_next(self) -> typing.Optional[CommandBuffer]:
        if self.index < self.last_index:
            self.index = self.index + 1
            return self.saved_commands[self.index]
        return None

    def get_prev(self) -> typing.Optional[CommandBuffer]:
        if self.index > 0:
            self.index = self.index - 1
            return self.saved_commands[self.index]
        return None

    def add_command(self, command: CommandBuffer, execution: bool = False) -> None:
        if self.index == self.last_index or execution:
            last_item = self.saved_commands[-1]
            last_item_empty = not last_item.text
            if last_item.text == command.text or (last_item_empty and execution):
                self.saved_commands[-1] = copy.copy(command)
            else:
                self.saved_commands.append(command)
                if not execution and self.index < self.last_index:
                    self.index += 1
            if execution:
                self.index = self.last_index


class CommandEdit(urwid.WidgetWrap):
    leader = ": "

    def __init__(self, master: mitmproxy.master.Master,
                 text: str, history: CommandHistory) -> None:
        super().__init__(urwid.Text(self.leader))
        self.master = master
        self.cbuf = CommandBuffer(master, text)
        self.history = history
        self.update()

    def keypress(self, size, key) -> None:
        if key == "backspace":
            self.cbuf.backspace()
        elif key == "left":
            self.cbuf.left()
        elif key == "right":
            self.cbuf.right()
        elif key == "up":
            self.history.add_command(self.cbuf)
            self.cbuf = self.history.get_prev() or self.cbuf
        elif key == "down":
            self.cbuf = self.history.get_next() or self.cbuf
        elif key == "shift tab":
            self.cbuf.cycle_completion(False)
        elif key == "tab":
            self.cbuf.cycle_completion()
        elif len(key) == 1:
            self.cbuf.insert(key)
        self.update()

    def update(self) -> None:
        self._w.set_text([self.leader, self.cbuf.render()])

    def render(self, size, focus=False) -> urwid.Canvas:
        (maxcol,) = size
        canv = self._w.render((maxcol,))
        canv = urwid.CompositeCanvas(canv)
        canv.cursor = self.get_cursor_coords((maxcol,))
        return canv

    def get_cursor_coords(self, size) -> typing.Tuple[int, int]:
        p = self.cbuf.cursor + len(self.leader)
        trans = self._w.get_line_translation(size[0])
        x, y = calc_coords(self._w.get_text()[0], trans, p)
        return x, y

    def get_edit_text(self) -> str:
        return self.cbuf.text