connection.c 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427
  1. /* Copyright 2001,2002,2003 Roger Dingledine, Matej Pfajfar. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. /**
  5. * \file connection.c
  6. * \brief General high-level functions to handle reading and writing
  7. * on connections.
  8. **/
  9. #include "or.h"
  10. /********* START VARIABLES **********/
  11. extern or_options_t options; /* command-line and config-file options */
  12. /** Array of strings to make conn-\>type human-readable. */
  13. const char *conn_type_to_string[] = {
  14. "", /* 0 */
  15. "OP listener", /* 1 */
  16. "OP", /* 2 */
  17. "OR listener", /* 3 */
  18. "OR", /* 4 */
  19. "Exit", /* 5 */
  20. "App listener",/* 6 */
  21. "App", /* 7 */
  22. "Dir listener",/* 8 */
  23. "Dir", /* 9 */
  24. "DNS worker", /* 10 */
  25. "CPU worker", /* 11 */
  26. };
  27. /** Array of string arrays to make {conn-\>type,conn-\>state} human-readable. */
  28. const char *conn_state_to_string[][_CONN_TYPE_MAX+1] = {
  29. { NULL }, /* no type associated with 0 */
  30. { NULL }, /* op listener, obsolete */
  31. { NULL }, /* op, obsolete */
  32. { "ready" }, /* or listener, 0 */
  33. { "", /* OR, 0 */
  34. "connect()ing", /* 1 */
  35. "handshaking", /* 2 */
  36. "open" }, /* 3 */
  37. { "", /* exit, 0 */
  38. "waiting for dest info", /* 1 */
  39. "connecting", /* 2 */
  40. "open", /* 3 */
  41. "resolve failed" }, /* 4 */
  42. { "ready" }, /* app listener, 0 */
  43. { "", /* 0 */
  44. "", /* 1 */
  45. "", /* 2 */
  46. "", /* 3 */
  47. "", /* 4 */
  48. "awaiting dest info", /* app, 5 */
  49. "waiting for rendezvous desc", /* 6 */
  50. "waiting for safe circuit", /* 7 */
  51. "waiting for connected", /* 8 */
  52. "open" }, /* 9 */
  53. { "ready" }, /* dir listener, 0 */
  54. { "", /* dir, 0 */
  55. "connecting", /* 1 */
  56. "client sending", /* 2 */
  57. "client reading", /* 3 */
  58. "awaiting command", /* 4 */
  59. "writing" }, /* 5 */
  60. { "", /* dns worker, 0 */
  61. "idle", /* 1 */
  62. "busy" }, /* 2 */
  63. { "", /* cpu worker, 0 */
  64. "idle", /* 1 */
  65. "busy with onion", /* 2 */
  66. "busy with handshake" }, /* 3 */
  67. };
  68. /********* END VARIABLES ************/
  69. static int connection_create_listener(const char *bindaddress,
  70. uint16_t bindport, int type);
  71. static int connection_init_accepted_conn(connection_t *conn);
  72. static int connection_handle_listener_read(connection_t *conn, int new_type);
  73. static int connection_receiver_bucket_should_increase(connection_t *conn);
  74. static int connection_finished_flushing(connection_t *conn);
  75. static int connection_finished_connecting(connection_t *conn);
  76. static int connection_read_to_buf(connection_t *conn);
  77. static int connection_process_inbuf(connection_t *conn);
  78. /**************************************************************/
  79. /** Allocate space for a new connection_t. This function just initializes
  80. * conn; you must call connection_add() to link it into the main array.
  81. *
  82. * Set conn-\>type to <b>type</b>. Set conn-\>s and conn-\>poll_index to
  83. * -1 to signify they are not yet assigned.
  84. *
  85. * If conn is not a listener type, allocate buffers for it. If it's
  86. * an AP type, allocate space to store the socks_request.
  87. *
  88. * Assign a pseudorandom next_circ_id between 0 and 2**15.
  89. *
  90. * Initialize conn's timestamps to now.
  91. */
  92. connection_t *connection_new(int type) {
  93. connection_t *conn;
  94. time_t now = time(NULL);
  95. conn = tor_malloc_zero(sizeof(connection_t));
  96. conn->magic = CONNECTION_MAGIC;
  97. conn->s = -1; /* give it a default of 'not used' */
  98. conn->poll_index = -1; /* also default to 'not used' */
  99. conn->type = type;
  100. if(!connection_is_listener(conn)) { /* listeners never use their buf */
  101. conn->inbuf = buf_new();
  102. conn->outbuf = buf_new();
  103. }
  104. if (type == CONN_TYPE_AP) {
  105. conn->socks_request = tor_malloc_zero(sizeof(socks_request_t));
  106. }
  107. conn->next_circ_id = crypto_pseudo_rand_int(1<<15);
  108. conn->timestamp_created = now;
  109. conn->timestamp_lastread = now;
  110. conn->timestamp_lastwritten = now;
  111. return conn;
  112. }
  113. /** Deallocate memory used by <b>conn</b>. Deallocate its buffers if necessary,
  114. * close its socket if necessary, and mark the directory as dirty if <b>conn</b>
  115. * is an OR or OP connection.
  116. */
  117. void connection_free(connection_t *conn) {
  118. tor_assert(conn);
  119. tor_assert(conn->magic == CONNECTION_MAGIC);
  120. if(!connection_is_listener(conn)) {
  121. buf_free(conn->inbuf);
  122. buf_free(conn->outbuf);
  123. }
  124. tor_free(conn->address);
  125. if(connection_speaks_cells(conn)) {
  126. if(conn->state == OR_CONN_STATE_OPEN)
  127. directory_set_dirty();
  128. if (conn->tls)
  129. tor_tls_free(conn->tls);
  130. }
  131. if (conn->identity_pkey)
  132. crypto_free_pk_env(conn->identity_pkey);
  133. tor_free(conn->nickname);
  134. tor_free(conn->socks_request);
  135. if(conn->s >= 0) {
  136. log_fn(LOG_INFO,"closing fd %d.",conn->s);
  137. tor_close_socket(conn->s);
  138. }
  139. memset(conn, 0xAA, sizeof(connection_t)); /* poison memory */
  140. tor_free(conn);
  141. }
  142. /** Call connection_free() on every connection in our array.
  143. * This is used by cpuworkers and dnsworkers when they fork,
  144. * so they don't keep resources held open (especially sockets).
  145. */
  146. void connection_free_all(void) {
  147. int i, n;
  148. connection_t **carray;
  149. get_connection_array(&carray,&n);
  150. for(i=0;i<n;i++)
  151. connection_free(carray[i]);
  152. }
  153. void connection_about_to_close_connection(connection_t *conn)
  154. {
  155. assert(conn->marked_for_close);
  156. if(conn->type == CONN_TYPE_AP || conn->type == CONN_TYPE_EXIT) {
  157. if(!conn->has_sent_end)
  158. log_fn(LOG_WARN,"Edge connection hasn't sent end yet? Bug.");
  159. }
  160. switch(conn->type) {
  161. case CONN_TYPE_DIR:
  162. if(conn->purpose == DIR_PURPOSE_FETCH_RENDDESC)
  163. rend_client_desc_fetched(conn->rend_query, 0);
  164. break;
  165. case CONN_TYPE_OR:
  166. /* Remember why we're closing this connection. */
  167. if (conn->state != OR_CONN_STATE_OPEN) {
  168. if(connection_or_nonopen_was_started_here(conn))
  169. rep_hist_note_connect_failed(conn->identity_digest, time(NULL));
  170. } else if (0) { // XXX reason == CLOSE_REASON_UNUSED_OR_CONN) {
  171. rep_hist_note_disconnect(conn->identity_digest, time(NULL));
  172. } else if(conn->identity_digest) {
  173. rep_hist_note_connection_died(conn->identity_digest, time(NULL));
  174. }
  175. break;
  176. case CONN_TYPE_AP:
  177. if (conn->socks_request->has_finished == 0) {
  178. log_fn(LOG_INFO,"Cleaning up AP -- sending socks reject.");
  179. connection_ap_handshake_socks_reply(conn, NULL, 0, 0);
  180. conn->socks_request->has_finished = 1;
  181. conn->hold_open_until_flushed = 1;
  182. }
  183. break;
  184. case CONN_TYPE_EXIT:
  185. if (conn->state == EXIT_CONN_STATE_RESOLVING) {
  186. circuit_detach_stream(circuit_get_by_conn(conn), conn);
  187. connection_dns_remove(conn);
  188. }
  189. break;
  190. case CONN_TYPE_DNSWORKER:
  191. if (conn->state == DNSWORKER_STATE_BUSY) {
  192. dns_cancel_pending_resolve(conn->address);
  193. }
  194. break;
  195. }
  196. }
  197. /** Close the underlying socket for <b>conn</b>, so we don't try to
  198. * flush it. Must be used in conjunction with (right before)
  199. * connection_mark_for_close().
  200. */
  201. void connection_close_immediate(connection_t *conn)
  202. {
  203. assert_connection_ok(conn,0);
  204. if (conn->s < 0) {
  205. log_fn(LOG_WARN,"Attempt to close already-closed connection.");
  206. return;
  207. }
  208. if (conn->outbuf_flushlen) {
  209. log_fn(LOG_INFO,"fd %d, type %s, state %d, %d bytes on outbuf.",
  210. conn->s, CONN_TYPE_TO_STRING(conn->type),
  211. conn->state, (int)conn->outbuf_flushlen);
  212. }
  213. tor_close_socket(conn->s);
  214. conn->s = -1;
  215. if(!connection_is_listener(conn)) {
  216. buf_clear(conn->outbuf);
  217. conn->outbuf_flushlen = 0;
  218. }
  219. }
  220. /** Mark <b>conn</b> to be closed next time we loop through
  221. * conn_close_if_marked() in main.c. Do any cleanup needed:
  222. * - Directory conns that fail to fetch a rendezvous descriptor need
  223. * to inform pending rendezvous streams.
  224. * - OR conns need to call rep_hist_note_*() to record status.
  225. * - AP conns need to send a socks reject if necessary.
  226. * - Exit conns need to call connection_dns_remove() if necessary.
  227. * - AP and Exit conns need to send an end cell if they can.
  228. * - DNS conns need to fail any resolves that are pending on them.
  229. */
  230. int
  231. _connection_mark_for_close(connection_t *conn)
  232. {
  233. assert_connection_ok(conn,0);
  234. if (conn->marked_for_close) {
  235. log(LOG_WARN, "Double mark-for-close on connection.");
  236. return -1;
  237. }
  238. conn->marked_for_close = 1;
  239. /* in case we're going to be held-open-til-flushed, reset
  240. * the number of seconds since last successful write, so
  241. * we get our whole 15 seconds */
  242. conn->timestamp_lastwritten = time(NULL);
  243. return 0;
  244. }
  245. /** Find each connection that has hold_open_until_flushed set to
  246. * 1 but hasn't written in the past 15 seconds, and set
  247. * hold_open_until_flushed to 0. This means it will get cleaned
  248. * up in the next loop through close_if_marked() in main.c.
  249. */
  250. void connection_expire_held_open(void)
  251. {
  252. connection_t **carray, *conn;
  253. int n, i;
  254. time_t now;
  255. now = time(NULL);
  256. get_connection_array(&carray, &n);
  257. for (i = 0; i < n; ++i) {
  258. conn = carray[i];
  259. /* If we've been holding the connection open, but we haven't written
  260. * for 15 seconds...
  261. */
  262. if (conn->hold_open_until_flushed) {
  263. tor_assert(conn->marked_for_close);
  264. if (now - conn->timestamp_lastwritten >= 15) {
  265. log_fn(LOG_WARN,"Giving up on marked_for_close conn that's been flushing for 15s (fd %d, type %s, state %d).",
  266. conn->s, CONN_TYPE_TO_STRING(conn->type), conn->state);
  267. conn->hold_open_until_flushed = 0;
  268. }
  269. }
  270. }
  271. }
  272. /** Bind a new non-blocking socket listening to
  273. * <b>bindaddress</b>:<b>bindport</b>, and add this new connection
  274. * (of type <b>type</b>) to the connection array.
  275. *
  276. * If <b>bindaddress</b> includes a port, we bind on that port; otherwise, we
  277. * use bindport.
  278. */
  279. static int connection_create_listener(const char *bindaddress, uint16_t bindport, int type) {
  280. struct sockaddr_in bindaddr; /* where to bind */
  281. connection_t *conn;
  282. uint16_t usePort;
  283. uint32_t addr;
  284. int s; /* the socket we're going to make */
  285. int one=1;
  286. memset(&bindaddr,0,sizeof(struct sockaddr_in));
  287. if (parse_addr_port(bindaddress, NULL, &addr, &usePort)<0) {
  288. log_fn(LOG_WARN, "Error parsing/resolving BindAddress %s",bindaddress);
  289. return -1;
  290. }
  291. if (usePort==0)
  292. usePort = bindport;
  293. bindaddr.sin_addr.s_addr = htonl(addr);
  294. bindaddr.sin_family = AF_INET;
  295. bindaddr.sin_port = htons((uint16_t) usePort);
  296. s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
  297. if (s < 0) {
  298. log_fn(LOG_WARN,"Socket creation failed.");
  299. return -1;
  300. }
  301. setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*) &one, sizeof(one));
  302. if(bind(s,(struct sockaddr *)&bindaddr,sizeof(bindaddr)) < 0) {
  303. log_fn(LOG_WARN,"Could not bind to port %u: %s",usePort,
  304. tor_socket_strerror(tor_socket_errno(s)));
  305. return -1;
  306. }
  307. if(listen(s,SOMAXCONN) < 0) {
  308. log_fn(LOG_WARN,"Could not listen on port %u: %s",usePort,
  309. tor_socket_strerror(tor_socket_errno(s)));
  310. return -1;
  311. }
  312. set_socket_nonblocking(s);
  313. conn = connection_new(type);
  314. conn->s = s;
  315. if(connection_add(conn) < 0) { /* no space, forget it */
  316. log_fn(LOG_WARN,"connection_add failed. Giving up.");
  317. connection_free(conn);
  318. return -1;
  319. }
  320. log_fn(LOG_DEBUG,"%s listening on port %u.",conn_type_to_string[type], usePort);
  321. conn->state = LISTENER_STATE_READY;
  322. connection_start_reading(conn);
  323. return 0;
  324. }
  325. /** The listener connection <b>conn</b> told poll() it wanted to read.
  326. * Call accept() on conn-\>s, and add the new connection if necessary.
  327. */
  328. static int connection_handle_listener_read(connection_t *conn, int new_type) {
  329. int news; /* the new socket */
  330. connection_t *newconn;
  331. /* information about the remote peer when connecting to other routers */
  332. struct sockaddr_in remote;
  333. /* length of the remote address. Must be an int, since accept() needs that. */
  334. int remotelen = sizeof(struct sockaddr_in);
  335. news = accept(conn->s,(struct sockaddr *)&remote,&remotelen);
  336. if (news == -1) { /* accept() error */
  337. int e = tor_socket_errno(conn->s);
  338. if (ERRNO_IS_ACCEPT_EAGAIN(e)) {
  339. return 0; /* he hung up before we could accept(). that's fine. */
  340. } else if (ERRNO_IS_ACCEPT_RESOURCE_LIMIT(e)) {
  341. log_fn(LOG_WARN,"accept failed: %s. Dropping incoming connection.",
  342. tor_socket_strerror(e));
  343. return 0;
  344. }
  345. /* else there was a real error. */
  346. log_fn(LOG_WARN,"accept() failed: %s. Closing listener.",
  347. tor_socket_strerror(e));
  348. connection_mark_for_close(conn);
  349. return -1;
  350. }
  351. log(LOG_INFO,"Connection accepted on socket %d (child of fd %d).",news, conn->s);
  352. set_socket_nonblocking(news);
  353. /* process entrance policies here, before we even create the connection */
  354. if(new_type == CONN_TYPE_AP) {
  355. /* check sockspolicy to see if we should accept it */
  356. if(socks_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
  357. log_fn(LOG_WARN,"Denying socks connection from untrusted address %s.",
  358. inet_ntoa(remote.sin_addr));
  359. tor_close_socket(news);
  360. return 0;
  361. }
  362. }
  363. if(new_type == CONN_TYPE_DIR) {
  364. /* check dirpolicy to see if we should accept it */
  365. if(dir_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
  366. log_fn(LOG_WARN,"Denying dir connection from address %s.",
  367. inet_ntoa(remote.sin_addr));
  368. tor_close_socket(news);
  369. return 0;
  370. }
  371. }
  372. newconn = connection_new(new_type);
  373. newconn->s = news;
  374. newconn->address = tor_strdup(inet_ntoa(remote.sin_addr)); /* remember the remote address */
  375. newconn->addr = ntohl(remote.sin_addr.s_addr);
  376. newconn->port = ntohs(remote.sin_port);
  377. if(connection_add(newconn) < 0) { /* no space, forget it */
  378. connection_free(newconn);
  379. return 0; /* no need to tear down the parent */
  380. }
  381. if(connection_init_accepted_conn(newconn) < 0) {
  382. connection_mark_for_close(newconn);
  383. return 0;
  384. }
  385. return 0;
  386. }
  387. /** Initialize states for newly accepted connection <b>conn</b>.
  388. * If conn is an OR, start the tls handshake.
  389. */
  390. static int connection_init_accepted_conn(connection_t *conn) {
  391. connection_start_reading(conn);
  392. switch(conn->type) {
  393. case CONN_TYPE_OR:
  394. return connection_tls_start_handshake(conn, 1);
  395. case CONN_TYPE_AP:
  396. conn->state = AP_CONN_STATE_SOCKS_WAIT;
  397. break;
  398. case CONN_TYPE_DIR:
  399. conn->purpose = DIR_PURPOSE_SERVER;
  400. conn->state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
  401. break;
  402. }
  403. return 0;
  404. }
  405. /** Take conn, make a nonblocking socket; try to connect to
  406. * addr:port (they arrive in *host order*). If fail, return -1. Else
  407. * assign s to conn->\s: if connected return 1, if EAGAIN return 0.
  408. *
  409. * address is used to make the logs useful.
  410. *
  411. * On success, add conn to the list of polled connections.
  412. */
  413. int connection_connect(connection_t *conn, char *address, uint32_t addr, uint16_t port) {
  414. int s;
  415. struct sockaddr_in dest_addr;
  416. s=socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
  417. if (s < 0) {
  418. log_fn(LOG_WARN,"Error creating network socket: %s",
  419. tor_socket_strerror(tor_socket_errno(-1)));
  420. return -1;
  421. }
  422. if (options.OutboundBindAddress) {
  423. struct sockaddr_in ext_addr;
  424. memset(&ext_addr, 0, sizeof(ext_addr));
  425. ext_addr.sin_family = AF_INET;
  426. ext_addr.sin_port = 0;
  427. if (!tor_inet_aton(options.OutboundBindAddress, &ext_addr.sin_addr)) {
  428. log_fn(LOG_WARN,"Outbound bind address '%s' didn't parse. Ignoring.",
  429. options.OutboundBindAddress);
  430. } else {
  431. if(bind(s, (struct sockaddr*)&ext_addr, sizeof(ext_addr)) < 0) {
  432. log_fn(LOG_WARN,"Error binding network socket: %s",
  433. tor_socket_strerror(tor_socket_errno(s)));
  434. return -1;
  435. }
  436. }
  437. }
  438. set_socket_nonblocking(s);
  439. memset(&dest_addr,0,sizeof(dest_addr));
  440. dest_addr.sin_family = AF_INET;
  441. dest_addr.sin_port = htons(port);
  442. dest_addr.sin_addr.s_addr = htonl(addr);
  443. log_fn(LOG_DEBUG,"Connecting to %s:%u.",address,port);
  444. if(connect(s,(struct sockaddr *)&dest_addr,sizeof(dest_addr)) < 0) {
  445. if(!ERRNO_IS_CONN_EINPROGRESS(tor_socket_errno(s))) {
  446. /* yuck. kill it. */
  447. log_fn(LOG_INFO,"Connect() to %s:%u failed: %s",address,port,
  448. tor_socket_strerror(tor_socket_errno(s)));
  449. tor_close_socket(s);
  450. return -1;
  451. } else {
  452. /* it's in progress. set state appropriately and return. */
  453. conn->s = s;
  454. if(connection_add(conn) < 0) /* no space, forget it */
  455. return -1;
  456. log_fn(LOG_DEBUG,"connect in progress, socket %d.",s);
  457. return 0;
  458. }
  459. }
  460. /* it succeeded. we're connected. */
  461. log_fn(LOG_INFO,"Connection to %s:%u established.",address,port);
  462. conn->s = s;
  463. if(connection_add(conn) < 0) /* no space, forget it */
  464. return -1;
  465. return 1;
  466. }
  467. /** If there exist any listeners of type <b>type</b> in the connection
  468. * array, mark them for close.
  469. */
  470. static void listener_close_if_present(int type) {
  471. connection_t *conn;
  472. connection_t **carray;
  473. int i,n;
  474. tor_assert(type == CONN_TYPE_OR_LISTENER ||
  475. type == CONN_TYPE_AP_LISTENER ||
  476. type == CONN_TYPE_DIR_LISTENER);
  477. get_connection_array(&carray,&n);
  478. for(i=0;i<n;i++) {
  479. conn = carray[i];
  480. if (conn->type == type && !conn->marked_for_close) {
  481. connection_close_immediate(conn);
  482. connection_mark_for_close(conn);
  483. }
  484. }
  485. }
  486. /**
  487. * Launch any configured listener connections of type <b>type</b>. (A
  488. * listener is configured if <b>port_option</b> is non-zero. If any
  489. * BindAddress configuration options are given in <b>cfg</b>, create a
  490. * connection binding to each one. Otherwise, create a single
  491. * connection binding to the address <b>default_addr</b>.)
  492. *
  493. * If <b>force</b> is true, close and re-open all listener connections.
  494. * Otherwise, only relaunch the listeners of this type if the number of
  495. * existing connections is not as configured (e.g., because one died).
  496. */
  497. static int retry_listeners(int type, struct config_line_t *cfg,
  498. int port_option, const char *default_addr,
  499. int force)
  500. {
  501. if (!force) {
  502. int want, have, n_conn, i;
  503. struct config_line_t *c;
  504. connection_t *conn;
  505. connection_t **carray;
  506. /* How many should there be? */
  507. if (cfg && port_option) {
  508. want = 0;
  509. for (c = cfg; c; c = c->next)
  510. ++want;
  511. } else if (port_option) {
  512. want = 1;
  513. } else {
  514. want = 0;
  515. }
  516. /* How many are there actually? */
  517. have = 0;
  518. get_connection_array(&carray,&n_conn);
  519. for(i=0;i<n_conn;i++) {
  520. conn = carray[i];
  521. if (conn->type == type && !conn->marked_for_close)
  522. ++have;
  523. }
  524. /* If we have the right number of listeners, do nothing. */
  525. if (have == want)
  526. return 0;
  527. /* Otherwise, warn the user and relaunch. */
  528. log_fn(LOG_WARN,"We have %d %s(s) open, but we want %d; relaunching.",
  529. have, conn_type_to_string[type], want);
  530. }
  531. listener_close_if_present(type);
  532. if (port_option) {
  533. if (!cfg) {
  534. if (connection_create_listener(default_addr, (uint16_t) port_option,
  535. type)<0)
  536. return -1;
  537. } else {
  538. for ( ; cfg; cfg = cfg->next) {
  539. if (connection_create_listener(cfg->value, (uint16_t) port_option,
  540. type)<0)
  541. return -1;
  542. }
  543. }
  544. }
  545. return 0;
  546. }
  547. /** (Re)launch listeners for each port you should have open. If
  548. * <b>force</b> is true, close and relaunch all listeners. If <b>force</b>
  549. * is false, then only relaunch listeners when we have the wrong number of
  550. * connections for a given type.
  551. */
  552. int retry_all_listeners(int force) {
  553. if (retry_listeners(CONN_TYPE_OR_LISTENER, options.ORBindAddress,
  554. options.ORPort, "0.0.0.0", force)<0)
  555. return -1;
  556. if (retry_listeners(CONN_TYPE_DIR_LISTENER, options.DirBindAddress,
  557. options.DirPort, "0.0.0.0", force)<0)
  558. return -1;
  559. if (retry_listeners(CONN_TYPE_AP_LISTENER, options.SocksBindAddress,
  560. options.SocksPort, "127.0.0.1", force)<0)
  561. return -1;
  562. return 0;
  563. }
  564. extern int global_read_bucket, global_write_bucket;
  565. /** How many bytes at most can we read onto this connection? */
  566. int connection_bucket_read_limit(connection_t *conn) {
  567. int at_most;
  568. /* do a rudimentary round-robin so one circuit can't hog a connection */
  569. if(connection_speaks_cells(conn)) {
  570. at_most = 32*(CELL_NETWORK_SIZE);
  571. } else {
  572. at_most = 32*(RELAY_PAYLOAD_SIZE);
  573. }
  574. if(at_most > global_read_bucket)
  575. at_most = global_read_bucket;
  576. if(connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN)
  577. if(at_most > conn->receiver_bucket)
  578. at_most = conn->receiver_bucket;
  579. return at_most;
  580. }
  581. /** We just read num_read onto conn. Decrement buckets appropriately. */
  582. static void connection_read_bucket_decrement(connection_t *conn, int num_read) {
  583. global_read_bucket -= num_read; tor_assert(global_read_bucket >= 0);
  584. if(connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
  585. conn->receiver_bucket -= num_read; tor_assert(conn->receiver_bucket >= 0);
  586. }
  587. if(global_read_bucket == 0) {
  588. log_fn(LOG_DEBUG,"global bucket exhausted. Pausing.");
  589. conn->wants_to_read = 1;
  590. connection_stop_reading(conn);
  591. return;
  592. }
  593. if(connection_speaks_cells(conn) &&
  594. conn->state == OR_CONN_STATE_OPEN &&
  595. conn->receiver_bucket == 0) {
  596. log_fn(LOG_DEBUG,"receiver bucket exhausted. Pausing.");
  597. conn->wants_to_read = 1;
  598. connection_stop_reading(conn);
  599. }
  600. }
  601. /** Keep a timeval to know when time has passed enough to refill buckets */
  602. static struct timeval current_time;
  603. /** Initiatialize the global read bucket to options.BandwidthBurst,
  604. * and current_time to the current time. */
  605. void connection_bucket_init(void) {
  606. tor_gettimeofday(&current_time);
  607. global_read_bucket = options.BandwidthBurst; /* start it at max traffic */
  608. global_write_bucket = options.BandwidthBurst; /* start it at max traffic */
  609. }
  610. /** Some time has passed; increment buckets appropriately. */
  611. void connection_bucket_refill(struct timeval *now) {
  612. int i, n;
  613. connection_t *conn;
  614. connection_t **carray;
  615. if(now->tv_sec <= current_time.tv_sec)
  616. return; /* wait until the second has rolled over */
  617. current_time.tv_sec = now->tv_sec; /* update current_time */
  618. /* (ignore usecs for now) */
  619. /* refill the global buckets */
  620. if(global_read_bucket < options.BandwidthBurst) {
  621. global_read_bucket += options.BandwidthRate;
  622. log_fn(LOG_DEBUG,"global_read_bucket now %d.", global_read_bucket);
  623. }
  624. if(global_write_bucket < options.BandwidthBurst) {
  625. global_write_bucket += options.BandwidthRate;
  626. log_fn(LOG_DEBUG,"global_write_bucket now %d.", global_write_bucket);
  627. }
  628. /* refill the per-connection buckets */
  629. get_connection_array(&carray,&n);
  630. for(i=0;i<n;i++) {
  631. conn = carray[i];
  632. if(connection_receiver_bucket_should_increase(conn)) {
  633. conn->receiver_bucket += conn->bandwidth;
  634. //log_fn(LOG_DEBUG,"Receiver bucket %d now %d.", i, conn->receiver_bucket);
  635. }
  636. if(conn->wants_to_read == 1 /* it's marked to turn reading back on now */
  637. && global_read_bucket > 0 /* and we're allowed to read */
  638. && global_write_bucket > 0 /* and we're allowed to write (XXXX,
  639. * not the best place to check this.) */
  640. && (!connection_speaks_cells(conn) ||
  641. conn->state != OR_CONN_STATE_OPEN ||
  642. conn->receiver_bucket > 0)) {
  643. /* and either a non-cell conn or a cell conn with non-empty bucket */
  644. log_fn(LOG_DEBUG,"waking up conn (fd %d)",conn->s);
  645. conn->wants_to_read = 0;
  646. connection_start_reading(conn);
  647. if(conn->wants_to_write == 1) {
  648. conn->wants_to_write = 0;
  649. connection_start_writing(conn);
  650. }
  651. }
  652. }
  653. }
  654. /** Is the receiver bucket for connection <b>conn</b> low enough that we
  655. * should add another pile of tokens to it?
  656. */
  657. static int connection_receiver_bucket_should_increase(connection_t *conn) {
  658. tor_assert(conn);
  659. if(!connection_speaks_cells(conn))
  660. return 0; /* edge connections don't use receiver_buckets */
  661. if(conn->state != OR_CONN_STATE_OPEN)
  662. return 0; /* only open connections play the rate limiting game */
  663. tor_assert(conn->bandwidth > 0);
  664. if(conn->receiver_bucket > 9*conn->bandwidth)
  665. return 0;
  666. return 1;
  667. }
  668. /** Read bytes from conn->\s and process them.
  669. *
  670. * This function gets called from conn_read() in main.c, either
  671. * when poll() has declared that conn wants to read, or (for OR conns)
  672. * when there are pending TLS bytes.
  673. *
  674. * It calls connection_read_to_buf() to bring in any new bytes,
  675. * and then calls connection_process_inbuf() to process them.
  676. *
  677. * Mark the connection and return -1 if you want to close it, else
  678. * return 0.
  679. */
  680. int connection_handle_read(connection_t *conn) {
  681. conn->timestamp_lastread = time(NULL);
  682. switch(conn->type) {
  683. case CONN_TYPE_OR_LISTENER:
  684. return connection_handle_listener_read(conn, CONN_TYPE_OR);
  685. case CONN_TYPE_AP_LISTENER:
  686. return connection_handle_listener_read(conn, CONN_TYPE_AP);
  687. case CONN_TYPE_DIR_LISTENER:
  688. return connection_handle_listener_read(conn, CONN_TYPE_DIR);
  689. }
  690. if(connection_read_to_buf(conn) < 0) {
  691. /* There's a read error; kill the connection.*/
  692. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  693. if(conn->type == CONN_TYPE_AP || conn->type == CONN_TYPE_EXIT) {
  694. connection_edge_end(conn, (char)(connection_state_is_open(conn) ?
  695. END_STREAM_REASON_MISC : END_STREAM_REASON_CONNECTFAILED),
  696. conn->cpath_layer);
  697. }
  698. connection_mark_for_close(conn);
  699. if(conn->type == CONN_TYPE_DIR &&
  700. conn->state == DIR_CONN_STATE_CONNECTING) {
  701. /* it's a directory server and connecting failed: forget about this router */
  702. /* XXX I suspect pollerr may make Windows not get to this point. :( */
  703. router_mark_as_down(conn->identity_digest);
  704. if(conn->purpose == DIR_PURPOSE_FETCH_DIR &&
  705. !all_trusted_directory_servers_down()) {
  706. log_fn(LOG_INFO,"Giving up on dirserver %s; trying another.", conn->address);
  707. directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 0);
  708. }
  709. }
  710. return -1;
  711. }
  712. if(connection_process_inbuf(conn) < 0) {
  713. // log_fn(LOG_DEBUG,"connection_process_inbuf returned -1.");
  714. return -1;
  715. }
  716. return 0;
  717. }
  718. /** Pull in new bytes from conn-\>s onto conn-\>inbuf, either
  719. * directly or via TLS. Reduce the token buckets by the number of
  720. * bytes read.
  721. *
  722. * Return -1 if we want to break conn, else return 0.
  723. */
  724. static int connection_read_to_buf(connection_t *conn) {
  725. int result;
  726. int at_most;
  727. /* how many bytes are we allowed to read? */
  728. at_most = connection_bucket_read_limit(conn);
  729. if(connection_speaks_cells(conn) && conn->state != OR_CONN_STATE_CONNECTING) {
  730. if(conn->state == OR_CONN_STATE_HANDSHAKING) {
  731. /* continue handshaking even if global token bucket is empty */
  732. return connection_tls_continue_handshake(conn);
  733. }
  734. log_fn(LOG_DEBUG,"%d: starting, inbuf_datalen %d (%d pending in tls object). at_most %d.",
  735. conn->s,(int)buf_datalen(conn->inbuf),tor_tls_get_pending_bytes(conn->tls), at_most);
  736. /* else open, or closing */
  737. result = read_to_buf_tls(conn->tls, at_most, conn->inbuf);
  738. switch(result) {
  739. case TOR_TLS_ERROR:
  740. case TOR_TLS_CLOSE:
  741. log_fn(LOG_INFO,"tls error. breaking (nickname %s, address %s).",
  742. conn->nickname ? conn->nickname : "not set", conn->address);
  743. return -1; /* XXX deal with close better */
  744. case TOR_TLS_WANTWRITE:
  745. connection_start_writing(conn);
  746. return 0;
  747. case TOR_TLS_WANTREAD: /* we're already reading */
  748. case TOR_TLS_DONE: /* no data read, so nothing to process */
  749. result = 0;
  750. break; /* so we call bucket_decrement below */
  751. }
  752. } else {
  753. result = read_to_buf(conn->s, at_most, conn->inbuf,
  754. &conn->inbuf_reached_eof);
  755. // log(LOG_DEBUG,"connection_read_to_buf(): read_to_buf returned %d.",read_result);
  756. if(result < 0)
  757. return -1;
  758. }
  759. if(result > 0 && !is_local_IP(conn->addr)) { /* remember it */
  760. rep_hist_note_bytes_read(result, time(NULL));
  761. }
  762. connection_read_bucket_decrement(conn, result);
  763. return 0;
  764. }
  765. /** A pass-through to fetch_from_buf. */
  766. int connection_fetch_from_buf(char *string, size_t len, connection_t *conn) {
  767. return fetch_from_buf(string, len, conn->inbuf);
  768. }
  769. /** Return conn-\>outbuf_flushlen: how many bytes conn wants to flush
  770. * from its outbuf. */
  771. int connection_wants_to_flush(connection_t *conn) {
  772. return conn->outbuf_flushlen;
  773. }
  774. /** Are there too many bytes on edge connection <b>conn</b>'s outbuf to
  775. * send back a relay-level sendme yet? Return 1 if so, 0 if not. Used by
  776. * connection_edge_consider_sending_sendme().
  777. */
  778. int connection_outbuf_too_full(connection_t *conn) {
  779. return (conn->outbuf_flushlen > 10*CELL_PAYLOAD_SIZE);
  780. }
  781. /** Try to flush more bytes onto conn-\>s.
  782. *
  783. * This function gets called either from conn_write() in main.c
  784. * when poll() has declared that conn wants to write, or below
  785. * from connection_write_to_buf() when an entire TLS record is ready.
  786. *
  787. * Update conn-\>timestamp_lastwritten to now, and call flush_buf
  788. * or flush_buf_tls appropriately. If it succeeds and there no more
  789. * more bytes on conn->outbuf, then call connection_finished_flushing
  790. * on it too.
  791. *
  792. * Mark the connection and return -1 if you want to close it, else
  793. * return 0.
  794. */
  795. int connection_handle_write(connection_t *conn) {
  796. int e, len=sizeof(e);
  797. int result;
  798. time_t now = time(NULL);
  799. tor_assert(!connection_is_listener(conn));
  800. conn->timestamp_lastwritten = now;
  801. /* Sometimes, "writeable" means "connected". */
  802. if (connection_state_is_connecting(conn)) {
  803. if (getsockopt(conn->s, SOL_SOCKET, SO_ERROR, (void*)&e, &len) < 0) {
  804. log_fn(LOG_WARN,"getsockopt() syscall failed?! Please report to tor-ops.");
  805. connection_close_immediate(conn);
  806. connection_mark_for_close(conn);
  807. return -1;
  808. }
  809. if(e) {
  810. /* some sort of error, but maybe just inprogress still */
  811. errno = e; /* XXX008 this is a kludge. maybe we should rearrange
  812. our error-hunting functions? E.g. pass errno to
  813. tor_socket_errno(). */
  814. if(!ERRNO_IS_CONN_EINPROGRESS(tor_socket_errno(conn->s))) {
  815. log_fn(LOG_INFO,"in-progress connect failed. Removing.");
  816. connection_close_immediate(conn);
  817. connection_mark_for_close(conn);
  818. /* it's safe to pass OPs to router_mark_as_down(), since it just
  819. * ignores unrecognized routers
  820. */
  821. if (conn->type == CONN_TYPE_OR)
  822. router_mark_as_down(conn->identity_digest);
  823. return -1;
  824. } else {
  825. return 0; /* no change, see if next time is better */
  826. }
  827. }
  828. /* The connection is successful. */
  829. return connection_finished_connecting(conn);
  830. }
  831. if (connection_speaks_cells(conn)) {
  832. if (conn->state == OR_CONN_STATE_HANDSHAKING) {
  833. connection_stop_writing(conn);
  834. if(connection_tls_continue_handshake(conn) < 0) {
  835. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  836. connection_mark_for_close(conn);
  837. return -1;
  838. }
  839. return 0;
  840. }
  841. /* else open, or closing */
  842. result = flush_buf_tls(conn->tls, conn->outbuf, &conn->outbuf_flushlen);
  843. switch(result) {
  844. case TOR_TLS_ERROR:
  845. case TOR_TLS_CLOSE:
  846. log_fn(LOG_INFO,"tls error. breaking.");
  847. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  848. connection_mark_for_close(conn);
  849. return -1; /* XXX deal with close better */
  850. case TOR_TLS_WANTWRITE:
  851. log_fn(LOG_DEBUG,"wanted write.");
  852. /* we're already writing */
  853. return 0;
  854. case TOR_TLS_WANTREAD:
  855. /* Make sure to avoid a loop if the receive buckets are empty. */
  856. log_fn(LOG_DEBUG,"wanted read.");
  857. if(!connection_is_reading(conn)) {
  858. connection_stop_writing(conn);
  859. conn->wants_to_write = 1;
  860. /* we'll start reading again when the next second arrives,
  861. * and then also start writing again.
  862. */
  863. }
  864. /* else no problem, we're already reading */
  865. return 0;
  866. /* case TOR_TLS_DONE:
  867. * for TOR_TLS_DONE, fall through to check if the flushlen
  868. * is empty, so we can stop writing.
  869. */
  870. }
  871. } else {
  872. result = flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen);
  873. if (result < 0) {
  874. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  875. conn->has_sent_end = 1;
  876. connection_mark_for_close(conn);
  877. return -1;
  878. }
  879. }
  880. if(result > 0 && !is_local_IP(conn->addr)) { /* remember it */
  881. rep_hist_note_bytes_written(result, now);
  882. }
  883. global_write_bucket -= result;
  884. if(!connection_wants_to_flush(conn)) { /* it's done flushing */
  885. if(connection_finished_flushing(conn) < 0) {
  886. /* already marked */
  887. return -1;
  888. }
  889. }
  890. return 0;
  891. }
  892. /** Append <b>len</b> bytes of <b>string</b> onto <b>conn</b>'s
  893. * outbuf, and ask it to start writing.
  894. */
  895. void connection_write_to_buf(const char *string, size_t len, connection_t *conn) {
  896. if(!len || conn->marked_for_close)
  897. return;
  898. if(write_to_buf(string, len, conn->outbuf) < 0) {
  899. if(conn->type == CONN_TYPE_AP || conn->type == CONN_TYPE_EXIT) {
  900. /* if it failed, it means we have our package/delivery windows set
  901. wrong compared to our max outbuf size. close the whole circuit. */
  902. log_fn(LOG_WARN,"write_to_buf failed. Closing circuit (fd %d).", conn->s);
  903. circuit_mark_for_close(circuit_get_by_conn(conn));
  904. } else {
  905. log_fn(LOG_WARN,"write_to_buf failed. Closing connection (fd %d).", conn->s);
  906. connection_mark_for_close(conn);
  907. }
  908. return;
  909. }
  910. connection_start_writing(conn);
  911. conn->outbuf_flushlen += len;
  912. }
  913. /** Return the conn to addr/port that has the most recent
  914. * timestamp_created, or NULL if no such conn exists. */
  915. connection_t *connection_exact_get_by_addr_port(uint32_t addr, uint16_t port) {
  916. int i, n;
  917. connection_t *conn, *best=NULL;
  918. connection_t **carray;
  919. get_connection_array(&carray,&n);
  920. for(i=0;i<n;i++) {
  921. conn = carray[i];
  922. if(conn->addr == addr && conn->port == port && !conn->marked_for_close &&
  923. (!best || best->timestamp_created < conn->timestamp_created))
  924. best = conn;
  925. }
  926. return best;
  927. }
  928. connection_t *connection_get_by_identity_digest(const char *digest, int type)
  929. {
  930. int i, n;
  931. connection_t *conn, *best=NULL;
  932. connection_t **carray;
  933. get_connection_array(&carray,&n);
  934. for(i=0;i<n;i++) {
  935. conn = carray[i];
  936. if (conn->type != type)
  937. continue;
  938. if (!memcmp(conn->identity_digest, digest, DIGEST_LEN)
  939. && !conn->marked_for_close
  940. && (!best || best->timestamp_created < conn->timestamp_created))
  941. best = conn;
  942. }
  943. return best;
  944. }
  945. /** Return a connection of type <b>type</b> that is not marked for
  946. * close.
  947. */
  948. connection_t *connection_get_by_type(int type) {
  949. int i, n;
  950. connection_t *conn;
  951. connection_t **carray;
  952. get_connection_array(&carray,&n);
  953. for(i=0;i<n;i++) {
  954. conn = carray[i];
  955. if(conn->type == type && !conn->marked_for_close)
  956. return conn;
  957. }
  958. return NULL;
  959. }
  960. /** Return a connection of type <b>type</b> that is in state <b>state</b>,
  961. * and that is not marked for close.
  962. */
  963. connection_t *connection_get_by_type_state(int type, int state) {
  964. int i, n;
  965. connection_t *conn;
  966. connection_t **carray;
  967. get_connection_array(&carray,&n);
  968. for(i=0;i<n;i++) {
  969. conn = carray[i];
  970. if(conn->type == type && conn->state == state && !conn->marked_for_close)
  971. return conn;
  972. }
  973. return NULL;
  974. }
  975. /** Return the connection of type <b>type</b> that is in state
  976. * <b>state</b>, that was written to least recently, and that is not
  977. * marked for close.
  978. */
  979. connection_t *connection_get_by_type_state_lastwritten(int type, int state) {
  980. int i, n;
  981. connection_t *conn, *best=NULL;
  982. connection_t **carray;
  983. get_connection_array(&carray,&n);
  984. for(i=0;i<n;i++) {
  985. conn = carray[i];
  986. if(conn->type == type && conn->state == state && !conn->marked_for_close)
  987. if(!best || conn->timestamp_lastwritten < best->timestamp_lastwritten)
  988. best = conn;
  989. }
  990. return best;
  991. }
  992. /** Return a connection of type <b>type</b> that has rendquery equal
  993. * to <b>rendquery</b>, and that is not marked for close.
  994. */
  995. connection_t *connection_get_by_type_rendquery(int type, const char *rendquery) {
  996. int i, n;
  997. connection_t *conn;
  998. connection_t **carray;
  999. get_connection_array(&carray,&n);
  1000. for(i=0;i<n;i++) {
  1001. conn = carray[i];
  1002. if(conn->type == type &&
  1003. !conn->marked_for_close &&
  1004. !rend_cmp_service_ids(rendquery, conn->rend_query))
  1005. return conn;
  1006. }
  1007. return NULL;
  1008. }
  1009. /** Return 1 if <b>conn</b> is a listener conn, else return 0. */
  1010. int connection_is_listener(connection_t *conn) {
  1011. if(conn->type == CONN_TYPE_OR_LISTENER ||
  1012. conn->type == CONN_TYPE_AP_LISTENER ||
  1013. conn->type == CONN_TYPE_DIR_LISTENER)
  1014. return 1;
  1015. return 0;
  1016. }
  1017. /** Return 1 if <b>conn</b> is in state "open" and is not marked
  1018. * for close, else return 0.
  1019. */
  1020. int connection_state_is_open(connection_t *conn) {
  1021. tor_assert(conn);
  1022. if(conn->marked_for_close)
  1023. return 0;
  1024. if((conn->type == CONN_TYPE_OR && conn->state == OR_CONN_STATE_OPEN) ||
  1025. (conn->type == CONN_TYPE_AP && conn->state == AP_CONN_STATE_OPEN) ||
  1026. (conn->type == CONN_TYPE_EXIT && conn->state == EXIT_CONN_STATE_OPEN))
  1027. return 1;
  1028. return 0;
  1029. }
  1030. /** Return 1 if conn is in 'connecting' state, else return 0. */
  1031. int connection_state_is_connecting(connection_t *conn) {
  1032. tor_assert(conn);
  1033. if (conn->marked_for_close)
  1034. return 0;
  1035. switch (conn->type)
  1036. {
  1037. case CONN_TYPE_OR:
  1038. return conn->state == OR_CONN_STATE_CONNECTING;
  1039. case CONN_TYPE_EXIT:
  1040. return conn->state == EXIT_CONN_STATE_CONNECTING;
  1041. case CONN_TYPE_DIR:
  1042. return conn->state == DIR_CONN_STATE_CONNECTING;
  1043. }
  1044. return 0;
  1045. }
  1046. /** Write a destroy cell with circ ID <b>circ_id</b> onto OR connection
  1047. * <b>conn</b>.
  1048. *
  1049. * Return 0.
  1050. */
  1051. int connection_send_destroy(uint16_t circ_id, connection_t *conn) {
  1052. cell_t cell;
  1053. tor_assert(conn);
  1054. tor_assert(connection_speaks_cells(conn));
  1055. memset(&cell, 0, sizeof(cell_t));
  1056. cell.circ_id = circ_id;
  1057. cell.command = CELL_DESTROY;
  1058. log_fn(LOG_INFO,"Sending destroy (circID %d).", circ_id);
  1059. connection_or_write_cell_to_buf(&cell, conn);
  1060. return 0;
  1061. }
  1062. /** Process new bytes that have arrived on conn-\>inbuf.
  1063. *
  1064. * This function just passes conn to the connection-specific
  1065. * connection_*_process_inbuf() function.
  1066. */
  1067. static int connection_process_inbuf(connection_t *conn) {
  1068. tor_assert(conn);
  1069. switch(conn->type) {
  1070. case CONN_TYPE_OR:
  1071. return connection_or_process_inbuf(conn);
  1072. case CONN_TYPE_EXIT:
  1073. case CONN_TYPE_AP:
  1074. return connection_edge_process_inbuf(conn);
  1075. case CONN_TYPE_DIR:
  1076. return connection_dir_process_inbuf(conn);
  1077. case CONN_TYPE_DNSWORKER:
  1078. return connection_dns_process_inbuf(conn);
  1079. case CONN_TYPE_CPUWORKER:
  1080. return connection_cpu_process_inbuf(conn);
  1081. default:
  1082. log_fn(LOG_WARN,"got unexpected conn->type %d.", conn->type);
  1083. return -1;
  1084. }
  1085. }
  1086. /** We just finished flushing bytes from conn-\>outbuf, and there
  1087. * are no more bytes remaining.
  1088. *
  1089. * This function just passes conn to the connection-specific
  1090. * connection_*_finished_flushing() function.
  1091. */
  1092. static int connection_finished_flushing(connection_t *conn) {
  1093. tor_assert(conn);
  1094. // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
  1095. switch(conn->type) {
  1096. case CONN_TYPE_OR:
  1097. return connection_or_finished_flushing(conn);
  1098. case CONN_TYPE_AP:
  1099. case CONN_TYPE_EXIT:
  1100. return connection_edge_finished_flushing(conn);
  1101. case CONN_TYPE_DIR:
  1102. return connection_dir_finished_flushing(conn);
  1103. case CONN_TYPE_DNSWORKER:
  1104. return connection_dns_finished_flushing(conn);
  1105. case CONN_TYPE_CPUWORKER:
  1106. return connection_cpu_finished_flushing(conn);
  1107. default:
  1108. log_fn(LOG_WARN,"got unexpected conn->type %d.", conn->type);
  1109. return -1;
  1110. }
  1111. }
  1112. /** Called when our attempt to connect() to another server has just
  1113. * succeeded.
  1114. *
  1115. * This function just passes conn to the connection-specific
  1116. * connection_*_finished_connecting() function.
  1117. */
  1118. static int connection_finished_connecting(connection_t *conn)
  1119. {
  1120. tor_assert(conn);
  1121. switch (conn->type)
  1122. {
  1123. case CONN_TYPE_OR:
  1124. return connection_or_finished_connecting(conn);
  1125. case CONN_TYPE_EXIT:
  1126. return connection_edge_finished_connecting(conn);
  1127. case CONN_TYPE_DIR:
  1128. return connection_dir_finished_connecting(conn);
  1129. default:
  1130. tor_assert(0);
  1131. return -1;
  1132. }
  1133. }
  1134. /** Verify that connection <b>conn</b> has all of its invariants
  1135. * correct. Trigger an assert if anything is invalid.
  1136. */
  1137. void assert_connection_ok(connection_t *conn, time_t now)
  1138. {
  1139. tor_assert(conn);
  1140. tor_assert(conn->magic == CONNECTION_MAGIC);
  1141. tor_assert(conn->type >= _CONN_TYPE_MIN);
  1142. tor_assert(conn->type <= _CONN_TYPE_MAX);
  1143. if(conn->outbuf_flushlen > 0) {
  1144. tor_assert(connection_is_writing(conn) || conn->wants_to_write);
  1145. }
  1146. if(conn->hold_open_until_flushed)
  1147. tor_assert(conn->marked_for_close);
  1148. /* XXX check: wants_to_read, wants_to_write, s, poll_index,
  1149. * marked_for_close. */
  1150. /* buffers */
  1151. if (!connection_is_listener(conn)) {
  1152. assert_buf_ok(conn->inbuf);
  1153. assert_buf_ok(conn->outbuf);
  1154. }
  1155. #if 0 /* computers often go back in time; no way to know */
  1156. tor_assert(!now || conn->timestamp_lastread <= now);
  1157. tor_assert(!now || conn->timestamp_lastwritten <= now);
  1158. tor_assert(conn->timestamp_created <= conn->timestamp_lastread);
  1159. tor_assert(conn->timestamp_created <= conn->timestamp_lastwritten);
  1160. #endif
  1161. /* XXX Fix this; no longer so.*/
  1162. #if 0
  1163. if(conn->type != CONN_TYPE_OR && conn->type != CONN_TYPE_DIR)
  1164. tor_assert(!conn->pkey);
  1165. /* pkey is set if we're a dir client, or if we're an OR in state OPEN
  1166. * connected to another OR.
  1167. */
  1168. #endif
  1169. if (conn->type != CONN_TYPE_OR) {
  1170. tor_assert(!conn->tls);
  1171. } else {
  1172. if(conn->state == OR_CONN_STATE_OPEN) {
  1173. /* tor_assert(conn->bandwidth > 0); */
  1174. /* the above isn't necessarily true: if we just did a TLS
  1175. * handshake but we didn't recognize the other peer, or it
  1176. * gave a bad cert/etc, then we won't have assigned bandwidth,
  1177. * yet it will be open. -RD
  1178. */
  1179. tor_assert(conn->receiver_bucket >= 0);
  1180. }
  1181. tor_assert(conn->addr && conn->port);
  1182. tor_assert(conn->address);
  1183. if (conn->state != OR_CONN_STATE_CONNECTING)
  1184. tor_assert(conn->tls);
  1185. }
  1186. if (conn->type != CONN_TYPE_EXIT && conn->type != CONN_TYPE_AP) {
  1187. tor_assert(!conn->stream_id);
  1188. tor_assert(!conn->next_stream);
  1189. tor_assert(!conn->cpath_layer);
  1190. tor_assert(!conn->package_window);
  1191. tor_assert(!conn->deliver_window);
  1192. tor_assert(!conn->done_sending);
  1193. tor_assert(!conn->done_receiving);
  1194. } else {
  1195. /* XXX unchecked: package window, deliver window. */
  1196. }
  1197. if (conn->type == CONN_TYPE_AP) {
  1198. tor_assert(conn->socks_request);
  1199. if (conn->state == AP_CONN_STATE_OPEN) {
  1200. tor_assert(conn->socks_request->has_finished);
  1201. tor_assert(conn->cpath_layer);
  1202. assert_cpath_layer_ok(conn->cpath_layer);
  1203. }
  1204. } else {
  1205. tor_assert(!conn->socks_request);
  1206. }
  1207. if (conn->type == CONN_TYPE_EXIT) {
  1208. tor_assert(conn->purpose == EXIT_PURPOSE_CONNECT ||
  1209. conn->purpose == EXIT_PURPOSE_RESOLVE);
  1210. } else if(conn->type != CONN_TYPE_DIR) {
  1211. tor_assert(!conn->purpose); /* only used for dir types currently */
  1212. }
  1213. switch(conn->type)
  1214. {
  1215. case CONN_TYPE_OR_LISTENER:
  1216. case CONN_TYPE_AP_LISTENER:
  1217. case CONN_TYPE_DIR_LISTENER:
  1218. tor_assert(conn->state == LISTENER_STATE_READY);
  1219. break;
  1220. case CONN_TYPE_OR:
  1221. tor_assert(conn->state >= _OR_CONN_STATE_MIN);
  1222. tor_assert(conn->state <= _OR_CONN_STATE_MAX);
  1223. break;
  1224. case CONN_TYPE_EXIT:
  1225. tor_assert(conn->state >= _EXIT_CONN_STATE_MIN);
  1226. tor_assert(conn->state <= _EXIT_CONN_STATE_MAX);
  1227. break;
  1228. case CONN_TYPE_AP:
  1229. tor_assert(conn->state >= _AP_CONN_STATE_MIN);
  1230. tor_assert(conn->state <= _AP_CONN_STATE_MAX);
  1231. tor_assert(conn->socks_request);
  1232. break;
  1233. case CONN_TYPE_DIR:
  1234. tor_assert(conn->state >= _DIR_CONN_STATE_MIN);
  1235. tor_assert(conn->state <= _DIR_CONN_STATE_MAX);
  1236. tor_assert(conn->purpose >= _DIR_PURPOSE_MIN);
  1237. tor_assert(conn->purpose <= _DIR_PURPOSE_MAX);
  1238. break;
  1239. case CONN_TYPE_DNSWORKER:
  1240. tor_assert(conn->state == DNSWORKER_STATE_IDLE ||
  1241. conn->state == DNSWORKER_STATE_BUSY);
  1242. break;
  1243. case CONN_TYPE_CPUWORKER:
  1244. tor_assert(conn->state >= _CPUWORKER_STATE_MIN);
  1245. tor_assert(conn->state <= _CPUWORKER_STATE_MAX);
  1246. break;
  1247. default:
  1248. tor_assert(0);
  1249. }
  1250. }
  1251. /*
  1252. Local Variables:
  1253. mode:c
  1254. indent-tabs-mode:nil
  1255. c-basic-offset:2
  1256. End:
  1257. */