aboutsummaryrefslogtreecommitdiffstats
path: root/libmproxy/dump.py
blob: e30c2422911e51871d7f06d068af96a85d096fc3 (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
import sys, os
import flow

class DumpError(Exception): pass


class Options(object):
    __slots__ = [
        "verbosity",
        "wfile",
    ]
    def __init__(self, **kwargs):
        for k, v in kwargs.items():
            setattr(self, k, v)
        for i in self.__slots__:
            if not hasattr(self, i):
                setattr(self, i, None)


class DumpMaster(flow.FlowMaster):
    def __init__(self, server, options, outfile=sys.stdout):
        flow.FlowMaster.__init__(self, server, flow.State())
        self.outfile = outfile
        self.o = options

        if options.wfile:
            path = os.path.expanduser(options.wfile)
            try:
                f = file(path, "wb")
                self.fwriter = flow.FlowWriter(f)
            except IOError, v:
                raise DumpError(v.strerror)

    def handle_clientconnection(self, r):
        flow.FlowMaster.handle_clientconnection(self, r)
        r.ack()

    def handle_error(self, r):
        flow.FlowMaster.handle_error(self, r)
        r.ack()

    def handle_request(self, r):
        flow.FlowMaster.handle_request(self, r)
        r.ack()

    def handle_response(self, msg):
        f = flow.FlowMaster.handle_response(self, msg)
        if f:
            if 0 < self.o.verbosity < 3:
                print >> self.outfile, ">>",
                print >> self.outfile, msg.request.short()
            if self.o.verbosity == 1:
                print >> self.outfile, "<<",
                print >> self.outfile, msg.short()
            elif self.o.verbosity == 2:
                print >> self.outfile, "<<"
                for i in msg.assemble().splitlines():
                    print >> self.outfile, "\t", i
                print >> self.outfile, "<<"
            elif self.o.verbosity == 3:
                print >> self.outfile, ">>"
                for i in msg.request.assemble().splitlines():
                    print >> self.outfile, "\t", i
                print >> self.outfile, ">>"
                print >> self.outfile, "<<"
                for i in msg.assemble().splitlines():
                    print >> self.outfile, "\t", i
                print >> self.outfile, "<<"

            msg.ack()
            self.state.delete_flow(f)

            if self.o.wfile:
                self.fwriter.add(f)


# begin nocover
    def run(self):
        try:
            return flow.FlowMaster.run(self)
        except KeyboardInterrupt:
            self.shutdown()