connection.c 51 KB

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