Fix spacing for --with-dmalloc
[tor.git] / contrib / tor-control.py
blob929ee43b0130eb2a99a6a1cfd32b908fbedd769b
1 #!/usr/bin/python2
2 #$Id$
4 import socket
5 import struct
6 import sys
8 MSG_TYPE_SETCONF = 0x0002
9 MSG_TYPE_GETCONF = 0x0003
10 MSG_TYPE_SETEVENTS = 0x0005
11 MSG_TYPE_AUTH = 0x0007
13 EVENT_TYPE_BANDWIDTH = 0x0004
14 EVENT_TYPE_WARN = 0x0005
16 def parseHostAndPort(h):
17 host, port = "localhost", 9051
18 if ":" in h:
19 i = h.index(":")
20 host = h[:i]
21 try:
22 port = int(h[i+1:])
23 except ValueError:
24 print "Bad hostname %r"%h
25 sys.exit(1)
26 elif h:
27 try:
28 port = int(h)
29 except ValueError:
30 host = h
32 return host, port
34 def receive_message(s):
35 body = ""
36 header = s.recv(4)
37 length,type = struct.unpack("!HH",header)
38 print "Got response length %d, type %d"%(length,type)
39 if length:
40 body = s.recv(length)
41 print "Got response length %d, type %d, body %s"%(length,type,body)
42 return length,type,body
44 def pack_message(type, body=""):
45 length = len(body)
46 reqheader = struct.pack("!HH", length, type)
47 return "%s%s"%(reqheader,body)
49 def authenticate(s):
50 s.sendall(pack_message(MSG_TYPE_AUTH))
51 length,type,body = receive_message(s)
52 return
54 def get_option(s,name):
55 s.sendall(pack_message(MSG_TYPE_GETCONF,name))
56 length,type,body = receive_message(s)
57 return
59 def set_option(s,msg):
60 s.sendall(pack_message(MSG_TYPE_SETCONF,msg))
61 length,type,body = receive_message(s)
62 return
64 def get_event(s,events):
65 eventbody = struct.pack("!H", events)
66 s.sendall(pack_message(MSG_TYPE_SETEVENTS,eventbody))
67 length,type,body = receive_message(s)
68 return
70 def listen_for_events(s):
71 while(1):
72 length,type,body = receive_message(s)
73 return
75 def do_main_loop(host,port):
76 print "host is %s:%d"%(host,port)
77 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
78 s.connect((host,port))
79 authenticate(s)
80 get_option(s,"nickname")
81 get_option(s,"DirFetchPostPeriod\n")
82 set_option(s,"1")
83 set_option(s,"bandwidthburstbytes 100000")
84 # set_option(s,"runasdaemon 1")
85 # get_event(s,EVENT_TYPE_WARN)
86 get_event(s,EVENT_TYPE_BANDWIDTH)
88 listen_for_events(s)
90 return
92 if __name__ == '__main__':
93 if len(sys.argv) != 2:
94 print "Syntax: tor-control.py torhost:torport"
95 sys.exit(0)
96 sh,sp = parseHostAndPort(sys.argv[1])
97 do_main_loop(sh,sp)