connection.c 50 KB

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