connection.c 50 KB

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