connection.c 49 KB

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