connection.c 49 KB

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