connection.c 53 KB

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