TorControl.py 14 KB

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