connection.c 52 KB

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