TorControl.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. #!/usr/bin/python
  2. #$Id$
  3. import socket
  4. import struct
  5. import sys
  6. class _Enum:
  7. def __init__(self, start, names):
  8. self.nameOf = {}
  9. idx = start
  10. for name in names:
  11. setattr(self,name,idx)
  12. self.nameOf[idx] = name
  13. idx += 1
  14. class _Enum2:
  15. def __init__(self, **args):
  16. self.__dict__.update(args)
  17. MSG_TYPE = _Enum(0x0000,
  18. ["ERROR",
  19. "DONE",
  20. "SETCONF",
  21. "GETCONF",
  22. "CONFVALUE",
  23. "SETEVENTS",
  24. "EVENT",
  25. "AUTH",
  26. "SAVECONF",
  27. "SIGNAL",
  28. "MAPADDRESS",
  29. "GETINFO",
  30. "INFOVALUE",
  31. "EXTENDCIRCUIT",
  32. "ATTACHSTREAM",
  33. "POSTDESCRIPTOR",
  34. "FRAGMENTHEADER",
  35. "FRAGMENT",
  36. "REDIRECTSTREAM",
  37. "CLOSESTREAM",
  38. "CLOSECIRCUIT",
  39. ])
  40. assert MSG_TYPE.SAVECONF == 0x0008
  41. assert MSG_TYPE.CLOSECIRCUIT == 0x0014
  42. EVENT_TYPE = _Enum(0x0001,
  43. ["CIRCSTATUS",
  44. "STREAMSTATUS",
  45. "ORCONNSTATUS",
  46. "BANDWIDTH",
  47. "WARN",
  48. "NEWDESC"])
  49. CIRC_STATUS = _Enum(0x00,
  50. ["LAUNCHED",
  51. "BUILT",
  52. "EXTENDED",
  53. "FAILED",
  54. "CLOSED"])
  55. STREAM_STATUS = _Enum(0x00,
  56. ["SENT_CONNECT",
  57. "SENT_RESOLVE",
  58. "SUCCEEDED",
  59. "FAILED",
  60. "CLOSED",
  61. "NEW_CONNECT",
  62. "NEW_RESOLVE",
  63. "DETACHED"])
  64. OR_CONN_STATUS = _Enum(0x00,
  65. ["LAUNCHED","CONNECTED","FAILED","CLOSED"])
  66. SIGNAL = _Enum2(HUP=0x01,INT=0x02,USR1=0x0A,USR2=0x0C,TERM=0x0F)
  67. ERR_CODES = {
  68. 0x0000 : "Unspecified error",
  69. 0x0001 : "Internal error",
  70. 0x0002 : "Unrecognized message type",
  71. 0x0003 : "Syntax error",
  72. 0x0004 : "Unrecognized configuration key",
  73. 0x0005 : "Invalid configuration value",
  74. 0x0006 : "Unrecognized byte code",
  75. 0x0007 : "Unauthorized",
  76. 0x0008 : "Failed authentication attempt",
  77. 0x0009 : "Resource exhausted",
  78. 0x000A : "No such stream",
  79. 0x000B : "No such circuit",
  80. 0x000C : "No such OR"
  81. }
  82. class TorCtlError(Exception):
  83. pass
  84. class ProtocolError(TorCtlError):
  85. pass
  86. class ErrorReply(TorCtlError):
  87. pass
  88. def parseHostAndPort(h):
  89. host, port = "localhost", 9051
  90. if ":" in h:
  91. i = h.index(":")
  92. host = h[:i]
  93. try:
  94. port = int(h[i+1:])
  95. except ValueError:
  96. print "Bad hostname %r"%h
  97. sys.exit(1)
  98. elif h:
  99. try:
  100. port = int(h)
  101. except ValueError:
  102. host = h
  103. return host, port
  104. def _unpack_msg(msg):
  105. "return None, minLength, body or type,body,rest"
  106. if len(msg) < 4:
  107. return None, 4, msg
  108. length,type = struct.unpack("!HH",msg)
  109. if len(msg) >= 4+length:
  110. return type,msg[4:4+length],msg[4+length:]
  111. else:
  112. return None,4+length,msg
  113. def _minLengthToPack(bytes):
  114. whole,left = divmod(bytes,65535)
  115. if left:
  116. return whole*(65535+4)+4+left
  117. else:
  118. return whole*(65535+4)
  119. def unpack_msg(msg):
  120. "returns as for _unpack_msg"
  121. tp,body,rest = _unpack_msg(msg)
  122. if tp != MSG_TYPE.FRAGMENTHEADER:
  123. return tp, body, rest
  124. if len(body) < 6:
  125. raise ProtocolError("FRAGMENTHEADER message too short")
  126. realType,realLength = struct.unpack("!HL", body[:6])
  127. # Okay; could the message _possibly_ be here?
  128. minLength = _minLengthToPack(realLength+6)
  129. if len(msg) < minLength:
  130. return None, minLength, msg
  131. # Okay; optimistically try to build up the msg.
  132. soFar = [ body[6:] ]
  133. lenSoFarLen = len(body)-6
  134. while len(rest)>=4 and lenSoFar < realLength:
  135. ln, tp = struct.unpack("!HH", rest[:4])
  136. if tp != MSG_TYPE.FRAGMENT:
  137. raise ProtocolError("Missing FRAGMENT message")
  138. soFar.append(rest[4:4+ln])
  139. lenSoFar += ln
  140. if 4+ln > len(rest):
  141. rest = ""
  142. leftInPacket = 4+ln-len(rest)
  143. else:
  144. rest = rest[4+ln:]
  145. leftInPacket=0
  146. if lenSoFar == realLength:
  147. return realType, "".join(soFar), rest
  148. elif lenSoFar > realLength:
  149. raise ProtocolError("Bad fragmentation: message longer than declared")
  150. else:
  151. inOtherPackets = realLength-lenSoFar-leftInPacket
  152. minLength = _minLengthToPack(inOtherPackets)
  153. return None, len(msg)+leftInPacket+inOtherPackets, msg
  154. def _receive_msg(s):
  155. body = ""
  156. header = s.recv(4)
  157. length,type = struct.unpack("!HH",header)
  158. if length:
  159. body = s.recv(length)
  160. return length,type,body
  161. def receive_message(s):
  162. length, tp, body = _receive_msg(s)
  163. if tp != MSG_TYPE.FRAGMENTHEADER:
  164. return length, tp, body
  165. if length < 6:
  166. raise ProtocolError("FRAGMENTHEADER message too short")
  167. realType,realLength = struct.unpack("!HL", body[:6])
  168. data = [ body[6:] ]
  169. soFar = len(data[0])
  170. while 1:
  171. length, tp, body = _receive_msg(s)
  172. if tp != MSG_TYPE.FRAGMENT:
  173. raise ProtocolError("Missing FRAGMENT message")
  174. soFar += length
  175. data.append(body)
  176. if soFar == realLength:
  177. return realLength, realType, "".join(data)
  178. elif soFar > realLengtH:
  179. raise ProtocolError("FRAGMENT message too long!")
  180. _event_handler = None
  181. def receive_reply(s, expected=None):
  182. while 1:
  183. _, tp, body = receive_message(s)
  184. if tp == MSG_TYPE.EVENT:
  185. if _event_handler is not None:
  186. _event_handler(body)
  187. elif tp == MSG_TYPE.ERROR:
  188. if len(body)<2:
  189. raise ProtocolError("(Truncated error message)")
  190. errCode, = struct.unpack("!H", body[:2])
  191. raise ErrorReply((errCode,
  192. ERR_CODES.get(errCode,"[unrecognized]"),
  193. body[2:]))
  194. elif (expected is not None) and (tp not in expected):
  195. raise ProtocolError("Unexpected message type 0x%04x"%tp)
  196. else:
  197. return tp, body
  198. def pack_message(type, body=""):
  199. length = len(body)
  200. if length < 65536:
  201. reqheader = struct.pack("!HH", length, type)
  202. return "%s%s"%(reqheader,body)
  203. fragheader = struct.pack("!HHHL",
  204. 65535, MSG_TYPE.FRAGMENTHEADER, type, length)
  205. msgs = [ fragheader, body[:65535-6] ]
  206. body = body[65535-6:]
  207. while body:
  208. if len(body) > 65535:
  209. fl = 65535
  210. else:
  211. fl = len(body)
  212. fragheader = struct.pack("!HH", MSG_TYPE.FRAGMENT, fl)
  213. msgs.append(fragheader)
  214. msgs.append(body[:fl])
  215. body = body[fl:]
  216. return "".join(msgs)
  217. def send_message(s, type, body=""):
  218. s.sendall(pack_message(type, body))
  219. def authenticate(s):
  220. send_message(s,MSG_TYPE.AUTH)
  221. type,body = receive_reply(s)
  222. return
  223. def _parseKV(body,sep=" ",term="\n"):
  224. res = []
  225. for line in body.split(term):
  226. if not line: continue
  227. print repr(line)
  228. k, v = line.split(sep,1)
  229. res.append((k,v))
  230. return res
  231. def get_option(s,name):
  232. send_message(s,MSG_TYPE.GETCONF,name)
  233. tp,body = receive_reply(s,[MSG_TYPE.CONFVALUE])
  234. return _parseKV(body)
  235. def set_option(s,msg):
  236. send_message(s,MSG_TYPE.SETCONF,msg)
  237. tp,body = receive_reply(s,[MSG_TYPE.DONE])
  238. def get_info(s,name):
  239. send_message(s,MSG_TYPE.GETINFO,name)
  240. tp,body = receive_reply(s,[MSG_TYPE.INFOVALUE])
  241. kvs = body.split("\0")
  242. d = {}
  243. for i in xrange(0,len(kvs)-1,2):
  244. d[kvs[i]] = kvs[i+1]
  245. return d
  246. def set_events(s,events):
  247. send_message(s,MSG_TYPE.SETEVENTS,
  248. "".join([struct.pack("!H", event) for event in events]))
  249. type,body = receive_reply(s,[MSG_TYPE.DONE])
  250. return
  251. def save_conf(s):
  252. send_message(s,MSG_TYPE.SAVECONF)
  253. receive_reply(s,[MSG_TYPE.DONE])
  254. def send_signal(s, sig):
  255. send_message(s,MSG_TYPE.SIGNAL,struct.pack("B",sig))
  256. receive_reply(s,[MSG_TYPE.DONE])
  257. def map_address(s, kv):
  258. msg = [ "%s %s\n"%(k,v) for k,v in kv ]
  259. send_message(s,MSG_TYPE.MAPADDRESS,"".join(msg))
  260. tp, body = receive_reply(s,[MSG_TYPE.DONE])
  261. return _parseKV(body)
  262. def extend_circuit(s, circid, hops):
  263. msg = struct.pack("!L",circid) + ",".join(hops) + "\0"
  264. send_message(s,MSG_TYPE.EXTENDCIRCUIT,msg)
  265. tp, body = receive_reply(s,[MSG_TYPE.DONE])
  266. if len(body) != 4:
  267. raise ProtocolError("Extendcircuit reply too short or long")
  268. return struct.unpack("!L",body)[0]
  269. def redirect_stream(s, streamid, newtarget):
  270. msg = struct.pack("!L",streamid) + newtarget + "\0"
  271. send_message(s,MSG_TYPE.REDIRECTSTREAM,msg)
  272. tp,body = receive_reply(s,[MSG_TYPE.DONE])
  273. def attach_stream(s, streamid, circid):
  274. msg = struct.pack("!LL",streamid, circid)
  275. send_message(s,MSG_TYPE.ATTACHSTREAM,msg)
  276. tp,body = receive_reply(s,[MSG_TYPE.DONE])
  277. def close_stream(s, streamid, reason=0, flags=0):
  278. msg = struct.pack("!LBB",streamid,reason,flags)
  279. send_message(s,MSG_TYPE.CLOSESTREAM,msg)
  280. tp,body = receive_reply(s,[MSG_TYPE.DONE])
  281. def close_circuit(s, circid, flags=0):
  282. msg = struct.pack("!LB",circid,flags)
  283. send_message(s,MSG_TYPE.CLOSECIRCUIT,msg)
  284. tp,body = receive_reply(s,[MSG_TYPE.DONE])
  285. def _unterminate(s):
  286. if s[-1] == '\0':
  287. return s[:-1]
  288. else:
  289. return s
  290. def unpack_event(body):
  291. if len(body)<2:
  292. raise ProtocolError("EVENT body too short.")
  293. evtype, = struct.unpack("!H", body[:2])
  294. body = body[2:]
  295. if evtype == EVENT_TYPE.CIRCSTATUS:
  296. if len(body)<5:
  297. raise ProtocolError("CIRCUITSTATUS event too short.")
  298. status,ident = struct.unpack("!BL", body[:5])
  299. path = _unterminate(body[5:]).split(",")
  300. args = status, ident, path
  301. elif evtype == EVENT_TYPE.STREAMSTATUS:
  302. if len(body)<5:
  303. raise ProtocolError("CIRCUITSTATUS event too short.")
  304. status,ident = struct.unpack("!BL", body[:5])
  305. target = _unterminate(body[5:])
  306. args = status, ident, target
  307. elif evtype == EVENT_TYPE.ORCONNSTATUS:
  308. if len(body)<2:
  309. raise ProtocolError("CIRCUITSTATUS event too short.")
  310. status = ord(body[0])
  311. target = _unterminate(body[1:])
  312. args = status, target
  313. elif evtype == EVENT_TYPE.BANDWIDTH:
  314. if len(body)<8:
  315. raise ProtocolError("BANDWIDTH event too short.")
  316. read, written = struct.unpack("!LL",body[:8])
  317. args = read, written
  318. elif evtype == EVENT_TYPE.WARN:
  319. args = (_unterminate(body),)
  320. elif evtype == EVENT_TYPE.NEWDESC:
  321. args = (_unterminate(body).split(","),)
  322. else:
  323. args = (body,)
  324. return evtype, args
  325. def listen_for_events(s):
  326. while(1):
  327. _,type,body = receive_message(s)
  328. print "event",type
  329. return
  330. def do_main_loop(host,port):
  331. print "host is %s:%d"%(host,port)
  332. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  333. s.connect((host,port))
  334. authenticate(s)
  335. print "nick",`get_option(s,"nickname")`
  336. print get_option(s,"DirFetchPeriod\n")
  337. print `get_info(s,"version")`
  338. #print `get_info(s,"desc/name/moria1")`
  339. print `get_info(s,"network-status")`
  340. print `get_info(s,"addr-mappings/all")`
  341. print `get_info(s,"addr-mappings/config")`
  342. print `get_info(s,"addr-mappings/cache")`
  343. print `get_info(s,"addr-mappings/control")`
  344. print `map_address(s, [("0.0.0.0", "Foobar.com"),
  345. ("1.2.3.4", "foobaz.com"),
  346. ("frebnitz.com", "5.6.7.8"),
  347. (".", "abacinator.onion")])`
  348. print `extend_circuit(s,0,["moria1"])`
  349. send_signal(s,1)
  350. #save_conf(s)
  351. #set_option(s,"1")
  352. #set_option(s,"bandwidthburstbytes 100000")
  353. #set_option(s,"runasdaemon 1")
  354. #set_events(s,[EVENT_TYPE.WARN])
  355. set_events(s,[EVENT_TYPE.WARN,EVENT_TYPE.STREAMSTATUS])
  356. listen_for_events(s)
  357. return
  358. if __name__ == '__main__':
  359. if len(sys.argv) != 2:
  360. print "Syntax: tor-control.py torhost:torport"
  361. sys.exit(0)
  362. sh,sp = parseHostAndPort(sys.argv[1])
  363. do_main_loop(sh,sp)