connection.c 48 KB

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