connection.c 49 KB

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