connection.c 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088
  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. static connection_t *connection_create_listener(const char *listenaddress,
  14. uint16_t listenport, int type);
  15. static int connection_init_accepted_conn(connection_t *conn);
  16. static int connection_handle_listener_read(connection_t *conn, int new_type);
  17. static int connection_receiver_bucket_should_increase(connection_t *conn);
  18. static int connection_finished_flushing(connection_t *conn);
  19. static int connection_finished_connecting(connection_t *conn);
  20. static int connection_reached_eof(connection_t *conn);
  21. static int connection_read_to_buf(connection_t *conn, int *max_to_read);
  22. static int connection_process_inbuf(connection_t *conn, int package_partial);
  23. static int connection_bucket_read_limit(connection_t *conn);
  24. static void client_check_address_changed(int sock);
  25. static uint32_t last_interface_ip = 0;
  26. static smartlist_t *outgoing_addrs = NULL;
  27. /**************************************************************/
  28. /**
  29. * Return the human-readable name for the connection type <b>type</b>
  30. */
  31. const char *
  32. conn_type_to_string(int type)
  33. {
  34. static char buf[64];
  35. switch (type) {
  36. case CONN_TYPE_OR_LISTENER: return "OR listener";
  37. case CONN_TYPE_OR: return "OR";
  38. case CONN_TYPE_EXIT: return "Exit";
  39. case CONN_TYPE_AP_LISTENER: return "Socks listener";
  40. case CONN_TYPE_AP: return "Socks";
  41. case CONN_TYPE_DIR_LISTENER: return "Directory listener";
  42. case CONN_TYPE_DIR: return "Directory";
  43. case CONN_TYPE_DNSWORKER: return "DNS worker";
  44. case CONN_TYPE_CPUWORKER: return "CPU worker";
  45. case CONN_TYPE_CONTROL_LISTENER: return "Control listener";
  46. case CONN_TYPE_CONTROL: return "Control";
  47. default:
  48. warn(LD_BUG, "Bug: unknown connection type %d", type);
  49. tor_snprintf(buf, sizeof(buf), "unknown [%d]", type);
  50. return buf;
  51. }
  52. }
  53. /**
  54. * Return the human-readable name for the connection state <b>state</b>
  55. * for the connection type <b>type</b>
  56. */
  57. const char *
  58. conn_state_to_string(int type, int state)
  59. {
  60. static char buf[96];
  61. switch (type) {
  62. case CONN_TYPE_OR_LISTENER:
  63. case CONN_TYPE_AP_LISTENER:
  64. case CONN_TYPE_DIR_LISTENER:
  65. case CONN_TYPE_CONTROL_LISTENER:
  66. if (state == LISTENER_STATE_READY)
  67. return "ready";
  68. break;
  69. case CONN_TYPE_OR:
  70. switch (state) {
  71. case OR_CONN_STATE_CONNECTING: return "connect()ing";
  72. case OR_CONN_STATE_PROXY_FLUSHING: return "proxy flushing";
  73. case OR_CONN_STATE_PROXY_READING: return "proxy reading";
  74. case OR_CONN_STATE_HANDSHAKING: return "proxy reading";
  75. case OR_CONN_STATE_OPEN: return "open";
  76. }
  77. break;
  78. case CONN_TYPE_EXIT:
  79. switch (state) {
  80. case EXIT_CONN_STATE_RESOLVING: return "waiting for dest info";
  81. case EXIT_CONN_STATE_CONNECTING: return "connecting";
  82. case EXIT_CONN_STATE_OPEN: return "open";
  83. case EXIT_CONN_STATE_RESOLVEFAILED: return "resolve failed";
  84. }
  85. break;
  86. case CONN_TYPE_AP:
  87. switch (state) {
  88. case AP_CONN_STATE_SOCKS_WAIT: return "waiting for dest info";
  89. case AP_CONN_STATE_RENDDESC_WAIT: return "waiting for rendezvous desc";
  90. case AP_CONN_STATE_CONTROLLER_WAIT: return "waiting for controller";
  91. case AP_CONN_STATE_CIRCUIT_WAIT: return "waiting for safe circuit";
  92. case AP_CONN_STATE_CONNECT_WAIT: return "waiting for connect";
  93. case AP_CONN_STATE_RESOLVE_WAIT: return "waiting for resolve";
  94. case AP_CONN_STATE_OPEN: return "open";
  95. }
  96. break;
  97. case CONN_TYPE_DIR:
  98. switch (state) {
  99. case DIR_CONN_STATE_CONNECTING: return "connecting";
  100. case DIR_CONN_STATE_CLIENT_SENDING: return "client sending";
  101. case DIR_CONN_STATE_CLIENT_READING: return "cleint reading";
  102. case DIR_CONN_STATE_SERVER_COMMAND_WAIT: return "waiting for command";
  103. case DIR_CONN_STATE_SERVER_WRITING: return "writing";
  104. }
  105. break;
  106. case CONN_TYPE_DNSWORKER:
  107. switch (state) {
  108. case DNSWORKER_STATE_IDLE: return "idle";
  109. case DNSWORKER_STATE_BUSY: return "busy";
  110. }
  111. break;
  112. case CONN_TYPE_CPUWORKER:
  113. switch (state) {
  114. case CPUWORKER_STATE_IDLE: return "idle";
  115. case CPUWORKER_STATE_BUSY_ONION: return "busy with onion";
  116. }
  117. break;
  118. case CONN_TYPE_CONTROL:
  119. switch (state) {
  120. case CONTROL_CONN_STATE_OPEN_V0: return "open (protocol v0)";
  121. case CONTROL_CONN_STATE_OPEN_V1: return "open (protocol v1)";
  122. case CONTROL_CONN_STATE_NEEDAUTH_V0:
  123. return "waiting for authentication (protocol unknown)";
  124. case CONTROL_CONN_STATE_NEEDAUTH_V1:
  125. return "waiting for authentication (protocol v1)";
  126. }
  127. break;
  128. }
  129. warn(LD_BUG, "Bug: unknown connection state %d (type %d)", state, type);
  130. tor_snprintf(buf, sizeof(buf),
  131. "unknown state [%d] on unknown [%s] connection",
  132. state, conn_type_to_string(type));
  133. return buf;
  134. }
  135. /** Allocate space for a new connection_t. This function just initializes
  136. * conn; you must call connection_add() to link it into the main array.
  137. *
  138. * Set conn-\>type to <b>type</b>. Set conn-\>s and conn-\>poll_index to
  139. * -1 to signify they are not yet assigned.
  140. *
  141. * If conn is not a listener type, allocate buffers for it. If it's
  142. * an AP type, allocate space to store the socks_request.
  143. *
  144. * Assign a pseudorandom next_circ_id between 0 and 2**15.
  145. *
  146. * Initialize conn's timestamps to now.
  147. */
  148. connection_t *
  149. connection_new(int type)
  150. {
  151. static uint32_t n_connections_allocated = 0;
  152. connection_t *conn;
  153. time_t now = time(NULL);
  154. conn = tor_malloc_zero(sizeof(connection_t));
  155. conn->magic = CONNECTION_MAGIC;
  156. conn->s = -1; /* give it a default of 'not used' */
  157. conn->poll_index = -1; /* also default to 'not used' */
  158. conn->global_identifier = n_connections_allocated++;
  159. conn->type = type;
  160. if (!connection_is_listener(conn)) { /* listeners never use their buf */
  161. conn->inbuf = buf_new();
  162. conn->outbuf = buf_new();
  163. }
  164. if (type == CONN_TYPE_AP) {
  165. conn->socks_request = tor_malloc_zero(sizeof(socks_request_t));
  166. }
  167. conn->next_circ_id = crypto_rand_int(1<<15);
  168. conn->timestamp_created = now;
  169. conn->timestamp_lastread = now;
  170. conn->timestamp_lastwritten = now;
  171. return conn;
  172. }
  173. /** Tell libevent that we don't care about <b>conn</b> any more. */
  174. void
  175. connection_unregister(connection_t *conn)
  176. {
  177. if (conn->read_event) {
  178. if (event_del(conn->read_event))
  179. warn(LD_BUG, "Error removing read event for %d", conn->s);
  180. tor_free(conn->read_event);
  181. }
  182. if (conn->write_event) {
  183. if (event_del(conn->write_event))
  184. warn(LD_BUG, "Error removing write event for %d", conn->s);
  185. tor_free(conn->write_event);
  186. }
  187. }
  188. /** Deallocate memory used by <b>conn</b>. Deallocate its buffers if necessary,
  189. * close its socket if necessary, and mark the directory as dirty if <b>conn</b>
  190. * is an OR or OP connection.
  191. */
  192. static void
  193. _connection_free(connection_t *conn)
  194. {
  195. tor_assert(conn->magic == CONNECTION_MAGIC);
  196. if (!connection_is_listener(conn)) {
  197. buf_free(conn->inbuf);
  198. buf_free(conn->outbuf);
  199. }
  200. tor_free(conn->address);
  201. tor_free(conn->chosen_exit_name);
  202. if (connection_speaks_cells(conn)) {
  203. if (conn->tls) {
  204. tor_tls_free(conn->tls);
  205. conn->tls = NULL;
  206. }
  207. }
  208. if (conn->identity_pkey)
  209. crypto_free_pk_env(conn->identity_pkey);
  210. tor_free(conn->nickname);
  211. tor_free(conn->socks_request);
  212. tor_free(conn->incoming_cmd);
  213. tor_free(conn->read_event); /* Probably already freed by connection_free. */
  214. tor_free(conn->write_event); /* Probably already freed by connection_free. */
  215. tor_free(conn->requested_resource);
  216. if (conn->s >= 0) {
  217. debug(LD_NET,"closing fd %d.",conn->s);
  218. tor_close_socket(conn->s);
  219. }
  220. memset(conn, 0xAA, sizeof(connection_t)); /* poison memory */
  221. tor_free(conn);
  222. }
  223. /** Make sure <b>conn</b> isn't in any of the global conn lists; then free it.
  224. */
  225. void
  226. connection_free(connection_t *conn)
  227. {
  228. tor_assert(conn);
  229. tor_assert(!connection_is_on_closeable_list(conn));
  230. tor_assert(!connection_in_array(conn));
  231. if (connection_speaks_cells(conn)) {
  232. if (conn->state == OR_CONN_STATE_OPEN)
  233. directory_set_dirty();
  234. }
  235. if (conn->type == CONN_TYPE_CONTROL) {
  236. conn->event_mask = 0;
  237. control_update_global_event_mask();
  238. }
  239. connection_unregister(conn);
  240. _connection_free(conn);
  241. }
  242. /** Call _connection_free() on every connection in our array, and release all
  243. * storage helpd by connection.c. This is used by cpuworkers and dnsworkers
  244. * when they fork, so they don't keep resources held open (especially
  245. * sockets).
  246. *
  247. * Don't do the checks in connection_free(), because they will
  248. * fail.
  249. */
  250. void
  251. connection_free_all(void)
  252. {
  253. int i, n;
  254. connection_t **carray;
  255. get_connection_array(&carray,&n);
  256. /* We don't want to log any messages to controllers. */
  257. for (i=0;i<n;i++)
  258. if (carray[i]->type == CONN_TYPE_CONTROL)
  259. carray[i]->event_mask = 0;
  260. control_update_global_event_mask();
  261. for (i=0;i<n;i++)
  262. _connection_free(carray[i]);
  263. if (outgoing_addrs) {
  264. SMARTLIST_FOREACH(outgoing_addrs, void*, addr, tor_free(addr));
  265. smartlist_free(outgoing_addrs);
  266. outgoing_addrs = NULL;
  267. }
  268. }
  269. /** Do any cleanup needed:
  270. * - Directory conns that failed to fetch a rendezvous descriptor
  271. * need to inform pending rendezvous streams.
  272. * - OR conns need to call rep_hist_note_*() to record status.
  273. * - AP conns need to send a socks reject if necessary.
  274. * - Exit conns need to call connection_dns_remove() if necessary.
  275. * - AP and Exit conns need to send an end cell if they can.
  276. * - DNS conns need to fail any resolves that are pending on them.
  277. */
  278. void
  279. connection_about_to_close_connection(connection_t *conn)
  280. {
  281. circuit_t *circ;
  282. assert(conn->marked_for_close);
  283. if (CONN_IS_EDGE(conn)) {
  284. if (!conn->has_sent_end) {
  285. warn(LD_BUG,"Harmless bug: Edge connection (marked at %s:%d) hasn't sent end yet?", conn->marked_for_close_file, conn->marked_for_close);
  286. tor_fragile_assert();
  287. }
  288. }
  289. switch (conn->type) {
  290. case CONN_TYPE_DIR:
  291. if (conn->state < DIR_CONN_STATE_CLIENT_FINISHED) {
  292. /* It's a directory connection and connecting or fetching
  293. * failed: forget about this router, and maybe try again. */
  294. connection_dir_request_failed(conn);
  295. }
  296. if (conn->purpose == DIR_PURPOSE_FETCH_RENDDESC)
  297. rend_client_desc_here(conn->rend_query); /* give it a try */
  298. break;
  299. case CONN_TYPE_OR:
  300. /* Remember why we're closing this connection. */
  301. if (conn->state != OR_CONN_STATE_OPEN) {
  302. if (connection_or_nonopen_was_started_here(conn)) {
  303. rep_hist_note_connect_failed(conn->identity_digest, time(NULL));
  304. helper_node_set_status(conn->identity_digest, 0);
  305. control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED);
  306. }
  307. } else if (conn->hold_open_until_flushed) {
  308. /* XXXX009 We used to have an arg that told us whether we closed the
  309. * connection on purpose or not. Can we use hold_open_until_flushed
  310. * instead? We only set it when we are intentionally closing a
  311. * connection. -NM
  312. *
  313. * (Of course, now things we set to close which expire rather than
  314. * flushing still get noted as dead, not disconnected. But this is an
  315. * improvement. -NM
  316. */
  317. rep_hist_note_disconnect(conn->identity_digest, time(NULL));
  318. control_event_or_conn_status(conn, OR_CONN_EVENT_CLOSED);
  319. } else if (conn->identity_digest) {
  320. rep_hist_note_connection_died(conn->identity_digest, time(NULL));
  321. control_event_or_conn_status(conn, OR_CONN_EVENT_CLOSED);
  322. }
  323. break;
  324. case CONN_TYPE_AP:
  325. if (conn->socks_request->has_finished == 0) {
  326. /* since conn gets removed right after this function finishes,
  327. * there's no point trying to send back a reply at this point. */
  328. warn(LD_BUG,"Bug: Closing stream (marked at %s:%d) without sending back a socks reply.",
  329. conn->marked_for_close_file, conn->marked_for_close);
  330. } else {
  331. control_event_stream_status(conn, STREAM_EVENT_CLOSED);
  332. }
  333. break;
  334. case CONN_TYPE_EXIT:
  335. if (conn->state == EXIT_CONN_STATE_RESOLVING) {
  336. circ = circuit_get_by_edge_conn(conn);
  337. if (circ)
  338. circuit_detach_stream(circ, conn);
  339. connection_dns_remove(conn);
  340. }
  341. break;
  342. case CONN_TYPE_DNSWORKER:
  343. if (conn->state == DNSWORKER_STATE_BUSY) {
  344. dns_cancel_pending_resolve(conn->address);
  345. }
  346. break;
  347. }
  348. }
  349. /** Close the underlying socket for <b>conn</b>, so we don't try to
  350. * flush it. Must be used in conjunction with (right before)
  351. * connection_mark_for_close().
  352. */
  353. void
  354. connection_close_immediate(connection_t *conn)
  355. {
  356. assert_connection_ok(conn,0);
  357. if (conn->s < 0) {
  358. err(LD_BUG,"Bug: Attempt to close already-closed connection.");
  359. tor_fragile_assert();
  360. return;
  361. }
  362. if (conn->outbuf_flushlen) {
  363. info(LD_NET,"fd %d, type %s, state %s, %d bytes on outbuf.",
  364. conn->s, conn_type_to_string(conn->type),
  365. conn_state_to_string(conn->type, conn->state),
  366. (int)conn->outbuf_flushlen);
  367. }
  368. connection_unregister(conn);
  369. tor_close_socket(conn->s);
  370. conn->s = -1;
  371. if (!connection_is_listener(conn)) {
  372. buf_clear(conn->outbuf);
  373. conn->outbuf_flushlen = 0;
  374. }
  375. }
  376. /** Mark <b>conn</b> to be closed next time we loop through
  377. * conn_close_if_marked() in main.c. */
  378. void
  379. _connection_mark_for_close(connection_t *conn, int line, const char *file)
  380. {
  381. assert_connection_ok(conn,0);
  382. tor_assert(line);
  383. tor_assert(file);
  384. if (conn->marked_for_close) {
  385. log(LOG_WARN,LD_BUG,"Duplicate call to connection_mark_for_close at %s:%d"
  386. " (first at %s:%d)", file, line, conn->marked_for_close_file,
  387. conn->marked_for_close);
  388. tor_fragile_assert();
  389. return;
  390. }
  391. conn->marked_for_close = line;
  392. conn->marked_for_close_file = file;
  393. add_connection_to_closeable_list(conn);
  394. /* in case we're going to be held-open-til-flushed, reset
  395. * the number of seconds since last successful write, so
  396. * we get our whole 15 seconds */
  397. conn->timestamp_lastwritten = time(NULL);
  398. }
  399. /** Find each connection that has hold_open_until_flushed set to
  400. * 1 but hasn't written in the past 15 seconds, and set
  401. * hold_open_until_flushed to 0. This means it will get cleaned
  402. * up in the next loop through close_if_marked() in main.c.
  403. */
  404. void
  405. connection_expire_held_open(void)
  406. {
  407. connection_t **carray, *conn;
  408. int n, i;
  409. time_t now;
  410. now = time(NULL);
  411. get_connection_array(&carray, &n);
  412. for (i = 0; i < n; ++i) {
  413. conn = carray[i];
  414. /* If we've been holding the connection open, but we haven't written
  415. * for 15 seconds...
  416. */
  417. if (conn->hold_open_until_flushed) {
  418. tor_assert(conn->marked_for_close);
  419. if (now - conn->timestamp_lastwritten >= 15) {
  420. int severity;
  421. if (conn->type == CONN_TYPE_EXIT ||
  422. (conn->type == CONN_TYPE_DIR && conn->purpose == DIR_PURPOSE_SERVER))
  423. severity = LOG_INFO;
  424. else
  425. severity = LOG_NOTICE;
  426. log_fn(severity, LD_NET,
  427. "Giving up on marked_for_close conn that's been flushing for 15s (fd %d, type %s, state %s).",
  428. conn->s, conn_type_to_string(conn->type),
  429. conn_state_to_string(conn->type, conn->state));
  430. conn->hold_open_until_flushed = 0;
  431. }
  432. }
  433. }
  434. }
  435. /** Bind a new non-blocking socket listening to
  436. * <b>listenaddress</b>:<b>listenport</b>, and add this new connection
  437. * (of type <b>type</b>) to the connection array.
  438. *
  439. * If <b>listenaddress</b> includes a port, we bind on that port;
  440. * otherwise, we use listenport.
  441. */
  442. static connection_t *
  443. connection_create_listener(const char *listenaddress, uint16_t listenport,
  444. int type)
  445. {
  446. struct sockaddr_in listenaddr; /* where to bind */
  447. char *address = NULL;
  448. connection_t *conn;
  449. uint16_t usePort;
  450. uint32_t addr;
  451. int s; /* the socket we're going to make */
  452. #ifndef MS_WINDOWS
  453. int one=1;
  454. #endif
  455. memset(&listenaddr,0,sizeof(struct sockaddr_in));
  456. if (parse_addr_port(listenaddress, &address, &addr, &usePort)<0) {
  457. warn(LD_CONFIG, "Error parsing/resolving ListenAddress %s",listenaddress);
  458. return NULL;
  459. }
  460. if (usePort==0)
  461. usePort = listenport;
  462. listenaddr.sin_addr.s_addr = htonl(addr);
  463. listenaddr.sin_family = AF_INET;
  464. listenaddr.sin_port = htons((uint16_t) usePort);
  465. notice(LD_NET, "Opening %s on %s:%d",
  466. conn_type_to_string(type), address, usePort);
  467. s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
  468. if (s < 0) {
  469. warn(LD_NET,"Socket creation failed.");
  470. goto err;
  471. } else if (!SOCKET_IS_POLLABLE(s)) {
  472. warn(LD_NET,"Too many connections; can't create pollable listener.");
  473. tor_close_socket(s);
  474. goto err;
  475. }
  476. #ifndef MS_WINDOWS
  477. /* REUSEADDR on normal places means you can rebind to the port
  478. * right after somebody else has let it go. But REUSEADDR on win32
  479. * means you can bind to the port _even when somebody else
  480. * already has it bound_. So, don't do that on Win32. */
  481. setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*) &one, sizeof(one));
  482. #endif
  483. if (bind(s,(struct sockaddr *)&listenaddr,sizeof(listenaddr)) < 0) {
  484. warn(LD_NET, "Could not bind to %s:%u: %s", address, usePort,
  485. tor_socket_strerror(tor_socket_errno(s)));
  486. goto err;
  487. }
  488. if (listen(s,SOMAXCONN) < 0) {
  489. warn(LD_NET, "Could not listen on %s:%u: %s", address, usePort,
  490. tor_socket_strerror(tor_socket_errno(s)));
  491. goto err;
  492. }
  493. set_socket_nonblocking(s);
  494. conn = connection_new(type);
  495. conn->s = s;
  496. conn->address = address;
  497. address = NULL;
  498. conn->port = usePort;
  499. if (connection_add(conn) < 0) { /* no space, forget it */
  500. warn(LD_NET,"connection_add failed. Giving up.");
  501. connection_free(conn);
  502. goto err;
  503. }
  504. debug(LD_NET,"%s listening on port %u.",conn_type_to_string(type), usePort);
  505. conn->state = LISTENER_STATE_READY;
  506. connection_start_reading(conn);
  507. return conn;
  508. err:
  509. tor_free(address);
  510. return NULL;
  511. }
  512. /** Do basic sanity checking on a newly received socket. Return 0
  513. * if it looks ok, else return -1. */
  514. static int
  515. check_sockaddr_in(struct sockaddr *sa, int len, int level)
  516. {
  517. int ok = 1;
  518. struct sockaddr_in *sin=(struct sockaddr_in*)sa;
  519. if (len != sizeof(struct sockaddr_in)) {
  520. log_fn(level, LD_NET, "Length of address not as expected: %d vs %d",
  521. len,(int)sizeof(struct sockaddr_in));
  522. ok = 0;
  523. }
  524. if (sa->sa_family != AF_INET) {
  525. log_fn(level, LD_NET, "Family of address not as expected: %d vs %d",
  526. sa->sa_family, AF_INET);
  527. ok = 0;
  528. }
  529. if (sin->sin_addr.s_addr == 0 || sin->sin_port == 0) {
  530. log_fn(level, LD_NET, "Address for new connection has address/port equal to zero.");
  531. ok = 0;
  532. }
  533. return ok ? 0 : -1;
  534. }
  535. /** The listener connection <b>conn</b> told poll() it wanted to read.
  536. * Call accept() on conn-\>s, and add the new connection if necessary.
  537. */
  538. static int
  539. connection_handle_listener_read(connection_t *conn, int new_type)
  540. {
  541. int news; /* the new socket */
  542. connection_t *newconn;
  543. /* information about the remote peer when connecting to other routers */
  544. struct sockaddr_in remote;
  545. char addrbuf[256];
  546. /* length of the remote address. Must be whatever accept() needs. */
  547. socklen_t remotelen = 256;
  548. char tmpbuf[INET_NTOA_BUF_LEN];
  549. tor_assert((size_t)remotelen >= sizeof(struct sockaddr_in));
  550. memset(addrbuf, 0, sizeof(addrbuf));
  551. news = accept(conn->s,(struct sockaddr *)&addrbuf,&remotelen);
  552. if (!SOCKET_IS_POLLABLE(news)) {
  553. /* accept() error, or too many conns to poll */
  554. int e;
  555. if (news>=0) {
  556. /* Too many conns to poll. */
  557. warn(LD_NET,"Too many connections; couldn't accept connection.");
  558. tor_close_socket(news);
  559. return 0;
  560. }
  561. e = tor_socket_errno(conn->s);
  562. if (ERRNO_IS_ACCEPT_EAGAIN(e)) {
  563. return 0; /* he hung up before we could accept(). that's fine. */
  564. } else if (ERRNO_IS_ACCEPT_RESOURCE_LIMIT(e)) {
  565. notice(LD_NET,"accept failed: %s. Dropping incoming connection.",
  566. tor_socket_strerror(e));
  567. return 0;
  568. }
  569. /* else there was a real error. */
  570. warn(LD_NET,"accept() failed: %s. Closing listener.",
  571. tor_socket_strerror(e));
  572. connection_mark_for_close(conn);
  573. return -1;
  574. }
  575. debug(LD_NET,"Connection accepted on socket %d (child of fd %d).",news,conn->s);
  576. set_socket_nonblocking(news);
  577. if (check_sockaddr_in((struct sockaddr*)addrbuf, remotelen, LOG_INFO)<0) {
  578. info(LD_NET, "accept() returned a strange address; trying getsockname().");
  579. remotelen=256;
  580. memset(addrbuf, 0, sizeof(addrbuf));
  581. if (getsockname(news, (struct sockaddr*)addrbuf, &remotelen)<0) {
  582. warn(LD_NET, "getsockname() failed.");
  583. } else {
  584. if (check_sockaddr_in((struct sockaddr*)addrbuf, remotelen, LOG_WARN)<0) {
  585. warn(LD_NET,"Something's wrong with this conn. Closing it.");
  586. tor_close_socket(news);
  587. return 0;
  588. }
  589. }
  590. }
  591. memcpy(&remote, addrbuf, sizeof(struct sockaddr_in));
  592. /* process entrance policies here, before we even create the connection */
  593. if (new_type == CONN_TYPE_AP) {
  594. /* check sockspolicy to see if we should accept it */
  595. if (socks_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
  596. tor_inet_ntoa(&remote.sin_addr, tmpbuf, sizeof(tmpbuf));
  597. notice(LD_APP,"Denying socks connection from untrusted address %s.",
  598. tmpbuf);
  599. tor_close_socket(news);
  600. return 0;
  601. }
  602. }
  603. if (new_type == CONN_TYPE_DIR) {
  604. /* check dirpolicy to see if we should accept it */
  605. if (dir_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
  606. tor_inet_ntoa(&remote.sin_addr, tmpbuf, sizeof(tmpbuf));
  607. notice(LD_DIRSERV,"Denying dir connection from address %s.",
  608. tmpbuf);
  609. tor_close_socket(news);
  610. return 0;
  611. }
  612. }
  613. newconn = connection_new(new_type);
  614. newconn->s = news;
  615. /* remember the remote address */
  616. newconn->addr = ntohl(remote.sin_addr.s_addr);
  617. newconn->port = ntohs(remote.sin_port);
  618. newconn->address = tor_dup_addr(newconn->addr);
  619. if (connection_add(newconn) < 0) { /* no space, forget it */
  620. connection_free(newconn);
  621. return 0; /* no need to tear down the parent */
  622. }
  623. if (connection_init_accepted_conn(newconn) < 0) {
  624. connection_mark_for_close(newconn);
  625. return 0;
  626. }
  627. return 0;
  628. }
  629. /** Initialize states for newly accepted connection <b>conn</b>.
  630. * If conn is an OR, start the tls handshake.
  631. */
  632. static int
  633. connection_init_accepted_conn(connection_t *conn)
  634. {
  635. connection_start_reading(conn);
  636. switch (conn->type) {
  637. case CONN_TYPE_OR:
  638. return connection_tls_start_handshake(conn, 1);
  639. case CONN_TYPE_AP:
  640. conn->state = AP_CONN_STATE_SOCKS_WAIT;
  641. break;
  642. case CONN_TYPE_DIR:
  643. conn->purpose = DIR_PURPOSE_SERVER;
  644. conn->state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
  645. break;
  646. case CONN_TYPE_CONTROL:
  647. conn->state = CONTROL_CONN_STATE_NEEDAUTH_V0;
  648. break;
  649. }
  650. return 0;
  651. }
  652. /** Take conn, make a nonblocking socket; try to connect to
  653. * addr:port (they arrive in *host order*). If fail, return -1. Else
  654. * assign s to conn-\>s: if connected return 1, if EAGAIN return 0.
  655. *
  656. * address is used to make the logs useful.
  657. *
  658. * On success, add conn to the list of polled connections.
  659. */
  660. int
  661. connection_connect(connection_t *conn, char *address,
  662. uint32_t addr, uint16_t port)
  663. {
  664. int s, inprogress = 0;
  665. struct sockaddr_in dest_addr;
  666. or_options_t *options = get_options();
  667. s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
  668. if (s < 0) {
  669. warn(LD_NET,"Error creating network socket: %s",
  670. tor_socket_strerror(tor_socket_errno(-1)));
  671. return -1;
  672. } else if (!SOCKET_IS_POLLABLE(s)) {
  673. warn(LD_NET,
  674. "Too many connections; can't create pollable connection to %s",
  675. safe_str(address));
  676. tor_close_socket(s);
  677. return -1;
  678. }
  679. if (options->OutboundBindAddress) {
  680. struct sockaddr_in ext_addr;
  681. memset(&ext_addr, 0, sizeof(ext_addr));
  682. ext_addr.sin_family = AF_INET;
  683. ext_addr.sin_port = 0;
  684. if (!tor_inet_aton(options->OutboundBindAddress, &ext_addr.sin_addr)) {
  685. warn(LD_CONFIG,"Outbound bind address '%s' didn't parse. Ignoring.",
  686. options->OutboundBindAddress);
  687. } else {
  688. if (bind(s, (struct sockaddr*)&ext_addr, sizeof(ext_addr)) < 0) {
  689. warn(LD_NET,"Error binding network socket: %s",
  690. tor_socket_strerror(tor_socket_errno(s)));
  691. return -1;
  692. }
  693. }
  694. }
  695. set_socket_nonblocking(s);
  696. memset(&dest_addr,0,sizeof(dest_addr));
  697. dest_addr.sin_family = AF_INET;
  698. dest_addr.sin_port = htons(port);
  699. dest_addr.sin_addr.s_addr = htonl(addr);
  700. debug(LD_NET,"Connecting to %s:%u.",safe_str(address),port);
  701. if (connect(s,(struct sockaddr *)&dest_addr,sizeof(dest_addr)) < 0) {
  702. int e = tor_socket_errno(s);
  703. if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
  704. /* yuck. kill it. */
  705. info(LD_NET,"connect() to %s:%u failed: %s",safe_str(address),port,
  706. tor_socket_strerror(e));
  707. tor_close_socket(s);
  708. return -1;
  709. } else {
  710. inprogress = 1;
  711. }
  712. }
  713. if (!server_mode(options))
  714. client_check_address_changed(s);
  715. /* it succeeded. we're connected. */
  716. log_fn(inprogress?LOG_DEBUG:LOG_INFO, LD_NET,
  717. "Connection to %s:%u %s (sock %d).",safe_str(address),port,
  718. inprogress?"in progress":"established",s);
  719. conn->s = s;
  720. if (connection_add(conn) < 0) /* no space, forget it */
  721. return -1;
  722. return inprogress ? 0 : 1;
  723. }
  724. /**
  725. * Launch any configured listener connections of type <b>type</b>. (A
  726. * listener is configured if <b>port_option</b> is non-zero. If any
  727. * ListenAddress configuration options are given in <b>cfg</b>, create a
  728. * connection binding to each one. Otherwise, create a single
  729. * connection binding to the address <b>default_addr</b>.)
  730. *
  731. * If <b>force</b> is true, close and re-open all listener connections.
  732. * Otherwise, only relaunch the listeners of this type if the number of
  733. * existing connections is not as configured (e.g., because one died),
  734. * or if the existing connections do not match those configured.
  735. *
  736. * Add all old conns that should be closed to <b>replaced_conns</b>.
  737. * Add all new connections to <b>new_conns</b>.
  738. */
  739. static int
  740. retry_listeners(int type, config_line_t *cfg,
  741. int port_option, const char *default_addr, int force,
  742. smartlist_t *replaced_conns,
  743. smartlist_t *new_conns)
  744. {
  745. smartlist_t *launch = smartlist_create();
  746. int free_launch_elts = 1;
  747. config_line_t *c;
  748. int n_conn, i;
  749. connection_t *conn;
  750. connection_t **carray;
  751. config_line_t *line;
  752. if (cfg && port_option) {
  753. for (c = cfg; c; c = c->next) {
  754. smartlist_add(launch, c);
  755. }
  756. free_launch_elts = 0;
  757. } else if (port_option) {
  758. line = tor_malloc_zero(sizeof(config_line_t));
  759. line->key = tor_strdup("");
  760. line->value = tor_strdup(default_addr);
  761. smartlist_add(launch, line);
  762. }
  763. /*
  764. SMARTLIST_FOREACH(launch, config_line_t *, l,
  765. log_fn(LOG_NOTICE, "#%s#%s", l->key, l->value));
  766. */
  767. get_connection_array(&carray,&n_conn);
  768. for (i=0; i < n_conn; ++i) {
  769. conn = carray[i];
  770. if (conn->type != type || conn->marked_for_close)
  771. continue;
  772. if (force) {
  773. /* It's a listener, and we're relaunching all listeners of this
  774. * type. Close this one. */
  775. log_fn(LOG_NOTICE, LD_NET, "Closing %s on %s:%d",
  776. conn_type_to_string(type), conn->address, conn->port);
  777. connection_close_immediate(conn);
  778. connection_mark_for_close(conn);
  779. continue;
  780. }
  781. /* Okay, so this is a listener. Is it configured? */
  782. line = NULL;
  783. SMARTLIST_FOREACH(launch, config_line_t *, wanted,
  784. {
  785. char *address=NULL;
  786. uint16_t port;
  787. if (! parse_addr_port(wanted->value, &address, NULL, &port)) {
  788. int addr_matches = !strcasecmp(address, conn->address);
  789. tor_free(address);
  790. if (! port)
  791. port = port_option;
  792. if (port == conn->port && addr_matches) {
  793. line = wanted;
  794. break;
  795. }
  796. }
  797. });
  798. if (! line) {
  799. /* This one isn't configured. Close it. */
  800. notice(LD_NET, "Closing %s on %s:%d",
  801. conn_type_to_string(type), conn->address, conn->port);
  802. if (replaced_conns) {
  803. smartlist_add(replaced_conns, conn);
  804. } else {
  805. connection_close_immediate(conn);
  806. connection_mark_for_close(conn);
  807. }
  808. } else {
  809. /* It's configured; we don't need to launch it. */
  810. debug(LD_NET, "Already have %s on %s:%d",
  811. conn_type_to_string(type), conn->address, conn->port);
  812. smartlist_remove(launch, line);
  813. if (free_launch_elts)
  814. config_free_lines(line);
  815. }
  816. }
  817. /* Now open all the listeners that are configured but not opened. */
  818. i = 0;
  819. SMARTLIST_FOREACH(launch, config_line_t *, cfg,
  820. {
  821. conn = connection_create_listener(cfg->value, (uint16_t) port_option,
  822. type);
  823. if (!conn) {
  824. i = -1;
  825. } else {
  826. if (new_conns)
  827. smartlist_add(new_conns, conn);
  828. }
  829. });
  830. if (free_launch_elts) {
  831. SMARTLIST_FOREACH(launch, config_line_t *, cfg,
  832. config_free_lines(cfg));
  833. }
  834. smartlist_free(launch);
  835. return i;
  836. }
  837. /** (Re)launch listeners for each port you should have open. If
  838. * <b>force</b> is true, close and relaunch all listeners. If <b>force</b>
  839. * is false, then only relaunch listeners when we have the wrong number of
  840. * connections for a given type.
  841. *
  842. * Add all old conns that should be closed to <b>replaced_conns</b>.
  843. * Add all new connections to <b>new_conns</b>.
  844. */
  845. int
  846. retry_all_listeners(int force, smartlist_t *replaced_conns,
  847. smartlist_t *new_conns)
  848. {
  849. or_options_t *options = get_options();
  850. if (server_mode(options) &&
  851. retry_listeners(CONN_TYPE_OR_LISTENER, options->ORListenAddress,
  852. options->ORPort, "0.0.0.0", force,
  853. replaced_conns, new_conns)<0)
  854. return -1;
  855. if (retry_listeners(CONN_TYPE_DIR_LISTENER, options->DirListenAddress,
  856. options->DirPort, "0.0.0.0", force,
  857. replaced_conns, new_conns)<0)
  858. return -1;
  859. if (retry_listeners(CONN_TYPE_AP_LISTENER, options->SocksListenAddress,
  860. options->SocksPort, "127.0.0.1", force,
  861. replaced_conns, new_conns)<0)
  862. return -1;
  863. if (retry_listeners(CONN_TYPE_CONTROL_LISTENER, NULL,
  864. options->ControlPort, "127.0.0.1", force,
  865. replaced_conns, new_conns)<0)
  866. return -1;
  867. return 0;
  868. }
  869. extern int global_read_bucket, global_write_bucket;
  870. /** How many bytes at most can we read onto this connection? */
  871. static int
  872. connection_bucket_read_limit(connection_t *conn)
  873. {
  874. int at_most;
  875. /* do a rudimentary round-robin so one circuit can't hog a connection */
  876. if (connection_speaks_cells(conn)) {
  877. at_most = 32*(CELL_NETWORK_SIZE);
  878. } else {
  879. at_most = 32*(RELAY_PAYLOAD_SIZE);
  880. }
  881. if (at_most > global_read_bucket)
  882. at_most = global_read_bucket;
  883. if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN)
  884. if (at_most > conn->receiver_bucket)
  885. at_most = conn->receiver_bucket;
  886. if (at_most < 0)
  887. return 0;
  888. return at_most;
  889. }
  890. /** We just read num_read onto conn. Decrement buckets appropriately. */
  891. static void
  892. connection_read_bucket_decrement(connection_t *conn, int num_read)
  893. {
  894. global_read_bucket -= num_read; //tor_assert(global_read_bucket >= 0);
  895. if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
  896. conn->receiver_bucket -= num_read; //tor_assert(conn->receiver_bucket >= 0);
  897. }
  898. }
  899. /** DOCDOC */
  900. static void
  901. connection_consider_empty_buckets(connection_t *conn)
  902. {
  903. if (global_read_bucket <= 0) {
  904. LOG_FN_CONN(conn, (LOG_DEBUG,LD_NET,"global bucket exhausted. Pausing."));
  905. conn->wants_to_read = 1;
  906. connection_stop_reading(conn);
  907. return;
  908. }
  909. if (connection_speaks_cells(conn) &&
  910. conn->state == OR_CONN_STATE_OPEN &&
  911. conn->receiver_bucket <= 0) {
  912. LOG_FN_CONN(conn, (LOG_DEBUG,LD_NET,"receiver bucket exhausted. Pausing."));
  913. conn->wants_to_read = 1;
  914. connection_stop_reading(conn);
  915. }
  916. }
  917. /** Initialize the global read bucket to options->BandwidthBurst,
  918. * and current_time to the current time. */
  919. void
  920. connection_bucket_init(void)
  921. {
  922. or_options_t *options = get_options();
  923. global_read_bucket = (int)options->BandwidthBurst; /* start it at max traffic */
  924. global_write_bucket = (int)options->BandwidthBurst; /* start it at max traffic */
  925. }
  926. /** A second has rolled over; increment buckets appropriately. */
  927. void
  928. connection_bucket_refill(struct timeval *now)
  929. {
  930. int i, n;
  931. connection_t *conn;
  932. connection_t **carray;
  933. or_options_t *options = get_options();
  934. /* refill the global buckets */
  935. if (global_read_bucket < (int)options->BandwidthBurst) {
  936. global_read_bucket += (int)options->BandwidthRate;
  937. debug(LD_NET,"global_read_bucket now %d.", global_read_bucket);
  938. }
  939. if (global_write_bucket < (int)options->BandwidthBurst) {
  940. global_write_bucket += (int)options->BandwidthRate;
  941. debug(LD_NET,"global_write_bucket now %d.", global_write_bucket);
  942. }
  943. /* refill the per-connection buckets */
  944. get_connection_array(&carray,&n);
  945. for (i=0;i<n;i++) {
  946. conn = carray[i];
  947. if (connection_receiver_bucket_should_increase(conn)) {
  948. conn->receiver_bucket = conn->bandwidth;
  949. //log_fn(LOG_DEBUG,"Receiver bucket %d now %d.", i, conn->receiver_bucket);
  950. }
  951. if (conn->wants_to_read == 1 /* it's marked to turn reading back on now */
  952. && global_read_bucket > 0 /* and we're allowed to read */
  953. && global_write_bucket > 0 /* and we're allowed to write (XXXX,
  954. * not the best place to check this.) */
  955. && (!connection_speaks_cells(conn) ||
  956. conn->state != OR_CONN_STATE_OPEN ||
  957. conn->receiver_bucket > 0)) {
  958. /* and either a non-cell conn or a cell conn with non-empty bucket */
  959. LOG_FN_CONN(conn, (LOG_DEBUG,LD_NET,"waking up conn (fd %d)",conn->s));
  960. conn->wants_to_read = 0;
  961. connection_start_reading(conn);
  962. if (conn->wants_to_write == 1) {
  963. conn->wants_to_write = 0;
  964. connection_start_writing(conn);
  965. }
  966. }
  967. }
  968. }
  969. /** Is the receiver bucket for connection <b>conn</b> low enough that we
  970. * should add another pile of tokens to it?
  971. */
  972. static int
  973. connection_receiver_bucket_should_increase(connection_t *conn)
  974. {
  975. tor_assert(conn);
  976. if (!connection_speaks_cells(conn))
  977. return 0; /* edge connections don't use receiver_buckets */
  978. if (conn->state != OR_CONN_STATE_OPEN)
  979. return 0; /* only open connections play the rate limiting game */
  980. if (conn->receiver_bucket >= conn->bandwidth)
  981. return 0;
  982. return 1;
  983. }
  984. /** Read bytes from conn-\>s and process them.
  985. *
  986. * This function gets called from conn_read() in main.c, either
  987. * when poll() has declared that conn wants to read, or (for OR conns)
  988. * when there are pending TLS bytes.
  989. *
  990. * It calls connection_read_to_buf() to bring in any new bytes,
  991. * and then calls connection_process_inbuf() to process them.
  992. *
  993. * Mark the connection and return -1 if you want to close it, else
  994. * return 0.
  995. */
  996. int
  997. connection_handle_read(connection_t *conn)
  998. {
  999. int max_to_read=-1, try_to_read;
  1000. if (conn->marked_for_close)
  1001. return 0; /* do nothing */
  1002. conn->timestamp_lastread = time(NULL);
  1003. switch (conn->type) {
  1004. case CONN_TYPE_OR_LISTENER:
  1005. return connection_handle_listener_read(conn, CONN_TYPE_OR);
  1006. case CONN_TYPE_AP_LISTENER:
  1007. return connection_handle_listener_read(conn, CONN_TYPE_AP);
  1008. case CONN_TYPE_DIR_LISTENER:
  1009. return connection_handle_listener_read(conn, CONN_TYPE_DIR);
  1010. case CONN_TYPE_CONTROL_LISTENER:
  1011. return connection_handle_listener_read(conn, CONN_TYPE_CONTROL);
  1012. }
  1013. loop_again:
  1014. try_to_read = max_to_read;
  1015. tor_assert(!conn->marked_for_close);
  1016. if (connection_read_to_buf(conn, &max_to_read) < 0) {
  1017. /* There's a read error; kill the connection.*/
  1018. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  1019. if (CONN_IS_EDGE(conn)) {
  1020. connection_edge_end_errno(conn, conn->cpath_layer);
  1021. if (conn->socks_request) /* broken, so don't send a socks reply back */
  1022. conn->socks_request->has_finished = 1;
  1023. }
  1024. connection_mark_for_close(conn);
  1025. return -1;
  1026. }
  1027. if (CONN_IS_EDGE(conn) &&
  1028. try_to_read != max_to_read) {
  1029. /* instruct it not to try to package partial cells. */
  1030. if (connection_process_inbuf(conn, 0) < 0) {
  1031. return -1;
  1032. }
  1033. if (!conn->marked_for_close &&
  1034. connection_is_reading(conn) &&
  1035. !conn->inbuf_reached_eof &&
  1036. max_to_read > 0)
  1037. goto loop_again; /* try reading again, in case more is here now */
  1038. }
  1039. /* one last try, packaging partial cells and all. */
  1040. if (!conn->marked_for_close &&
  1041. connection_process_inbuf(conn, 1) < 0) {
  1042. return -1;
  1043. }
  1044. if (!conn->marked_for_close &&
  1045. conn->inbuf_reached_eof &&
  1046. connection_reached_eof(conn) < 0) {
  1047. return -1;
  1048. }
  1049. return 0;
  1050. }
  1051. /** Pull in new bytes from conn-\>s onto conn-\>inbuf, either
  1052. * directly or via TLS. Reduce the token buckets by the number of
  1053. * bytes read.
  1054. *
  1055. * If *max_to_read is -1, then decide it ourselves, else go with the
  1056. * value passed to us. When returning, if it's changed, subtract the
  1057. * number of bytes we read from *max_to_read.
  1058. *
  1059. * Return -1 if we want to break conn, else return 0.
  1060. */
  1061. static int
  1062. connection_read_to_buf(connection_t *conn, int *max_to_read)
  1063. {
  1064. int result, at_most = *max_to_read;
  1065. size_t bytes_in_buf, more_to_read;
  1066. if (at_most == -1) { /* we need to initialize it */
  1067. /* how many bytes are we allowed to read? */
  1068. at_most = connection_bucket_read_limit(conn);
  1069. }
  1070. bytes_in_buf = buf_capacity(conn->inbuf) - buf_datalen(conn->inbuf);
  1071. again:
  1072. if ((size_t)at_most > bytes_in_buf && bytes_in_buf >= 1024) {
  1073. more_to_read = at_most - bytes_in_buf;
  1074. at_most = bytes_in_buf;
  1075. } else {
  1076. more_to_read = 0;
  1077. }
  1078. if (connection_speaks_cells(conn) && conn->state > OR_CONN_STATE_PROXY_READING) {
  1079. int pending;
  1080. if (conn->state == OR_CONN_STATE_HANDSHAKING) {
  1081. /* continue handshaking even if global token bucket is empty */
  1082. return connection_tls_continue_handshake(conn);
  1083. }
  1084. debug(LD_NET,"%d: starting, inbuf_datalen %d (%d pending in tls object). at_most %d.",
  1085. conn->s,(int)buf_datalen(conn->inbuf),tor_tls_get_pending_bytes(conn->tls), at_most);
  1086. /* else open, or closing */
  1087. result = read_to_buf_tls(conn->tls, at_most, conn->inbuf);
  1088. switch (result) {
  1089. case TOR_TLS_CLOSE:
  1090. info(LD_NET,"TLS connection closed on read. Closing. (Nickname %s, address %s",
  1091. conn->nickname ? conn->nickname : "not set", conn->address);
  1092. return -1;
  1093. case TOR_TLS_ERROR:
  1094. info(LD_NET,"tls error. breaking (nickname %s, address %s).",
  1095. conn->nickname ? conn->nickname : "not set", conn->address);
  1096. return -1;
  1097. case TOR_TLS_WANTWRITE:
  1098. connection_start_writing(conn);
  1099. return 0;
  1100. case TOR_TLS_WANTREAD: /* we're already reading */
  1101. case TOR_TLS_DONE: /* no data read, so nothing to process */
  1102. result = 0;
  1103. break; /* so we call bucket_decrement below */
  1104. default:
  1105. break;
  1106. }
  1107. pending = tor_tls_get_pending_bytes(conn->tls);
  1108. if (pending) {
  1109. /* XXXX If we have any pending bytes, read them now. This *can*
  1110. * take us over our read allotment, but really we shouldn't be
  1111. * believing that SSL bytes are the same as TCP bytes anyway. */
  1112. int r2 = read_to_buf_tls(conn->tls, pending, conn->inbuf);
  1113. if (r2<0) {
  1114. warn(LD_BUG, "Bug: apparently, reading pending bytes can fail.");
  1115. return -1;
  1116. } else {
  1117. result += r2;
  1118. }
  1119. }
  1120. } else {
  1121. CONN_LOG_PROTECT(conn,
  1122. result = read_to_buf(conn->s, at_most, conn->inbuf,
  1123. &conn->inbuf_reached_eof));
  1124. // log_fn(LOG_DEBUG,"read_to_buf returned %d.",read_result);
  1125. if (result < 0)
  1126. return -1;
  1127. }
  1128. if (result > 0) { /* change *max_to_read */
  1129. *max_to_read = at_most - result;
  1130. }
  1131. if (result > 0 && !is_local_IP(conn->addr)) { /* remember it */
  1132. rep_hist_note_bytes_read(result, time(NULL));
  1133. connection_read_bucket_decrement(conn, result);
  1134. }
  1135. if (more_to_read && result == at_most) {
  1136. bytes_in_buf = buf_capacity(conn->inbuf) - buf_datalen(conn->inbuf);
  1137. tor_assert(bytes_in_buf < 1024);
  1138. at_most = more_to_read;
  1139. goto again;
  1140. }
  1141. /* Call even if result is 0, since the global read bucket may
  1142. * have reached 0 on a different conn, and this guy needs to
  1143. * know to stop reading. */
  1144. connection_consider_empty_buckets(conn);
  1145. return 0;
  1146. }
  1147. /** A pass-through to fetch_from_buf. */
  1148. int
  1149. connection_fetch_from_buf(char *string, size_t len, connection_t *conn)
  1150. {
  1151. return fetch_from_buf(string, len, conn->inbuf);
  1152. }
  1153. /** Return conn-\>outbuf_flushlen: how many bytes conn wants to flush
  1154. * from its outbuf. */
  1155. int
  1156. connection_wants_to_flush(connection_t *conn)
  1157. {
  1158. return conn->outbuf_flushlen;
  1159. }
  1160. /** Are there too many bytes on edge connection <b>conn</b>'s outbuf to
  1161. * send back a relay-level sendme yet? Return 1 if so, 0 if not. Used by
  1162. * connection_edge_consider_sending_sendme().
  1163. */
  1164. int
  1165. connection_outbuf_too_full(connection_t *conn)
  1166. {
  1167. return (conn->outbuf_flushlen > 10*CELL_PAYLOAD_SIZE);
  1168. }
  1169. /** Try to flush more bytes onto conn-\>s.
  1170. *
  1171. * This function gets called either from conn_write() in main.c
  1172. * when poll() has declared that conn wants to write, or below
  1173. * from connection_write_to_buf() when an entire TLS record is ready.
  1174. *
  1175. * Update conn-\>timestamp_lastwritten to now, and call flush_buf
  1176. * or flush_buf_tls appropriately. If it succeeds and there no more
  1177. * more bytes on conn->outbuf, then call connection_finished_flushing
  1178. * on it too.
  1179. *
  1180. * Mark the connection and return -1 if you want to close it, else
  1181. * return 0.
  1182. */
  1183. int
  1184. connection_handle_write(connection_t *conn)
  1185. {
  1186. int e;
  1187. socklen_t len=sizeof(e);
  1188. int result;
  1189. time_t now = time(NULL);
  1190. tor_assert(!connection_is_listener(conn));
  1191. if (conn->marked_for_close)
  1192. return 0; /* do nothing */
  1193. conn->timestamp_lastwritten = now;
  1194. /* Sometimes, "writable" means "connected". */
  1195. if (connection_state_is_connecting(conn)) {
  1196. if (getsockopt(conn->s, SOL_SOCKET, SO_ERROR, (void*)&e, &len) < 0) {
  1197. warn(LD_BUG,"getsockopt() syscall failed?! Please report to tor-ops.");
  1198. if (CONN_IS_EDGE(conn))
  1199. connection_edge_end_errno(conn, conn->cpath_layer);
  1200. connection_mark_for_close(conn);
  1201. return -1;
  1202. }
  1203. if (e) {
  1204. /* some sort of error, but maybe just inprogress still */
  1205. if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
  1206. info(LD_NET,"in-progress connect failed. Removing.");
  1207. if (CONN_IS_EDGE(conn))
  1208. connection_edge_end_errno(conn, conn->cpath_layer);
  1209. connection_close_immediate(conn);
  1210. connection_mark_for_close(conn);
  1211. /* it's safe to pass OPs to router_mark_as_down(), since it just
  1212. * ignores unrecognized routers
  1213. */
  1214. if (conn->type == CONN_TYPE_OR && !get_options()->HttpsProxy)
  1215. router_mark_as_down(conn->identity_digest);
  1216. return -1;
  1217. } else {
  1218. return 0; /* no change, see if next time is better */
  1219. }
  1220. }
  1221. /* The connection is successful. */
  1222. if (connection_finished_connecting(conn)<0)
  1223. return -1;
  1224. }
  1225. if (connection_speaks_cells(conn) && conn->state > OR_CONN_STATE_PROXY_READING) {
  1226. if (conn->state == OR_CONN_STATE_HANDSHAKING) {
  1227. connection_stop_writing(conn);
  1228. if (connection_tls_continue_handshake(conn) < 0) {
  1229. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  1230. connection_mark_for_close(conn);
  1231. return -1;
  1232. }
  1233. return 0;
  1234. }
  1235. /* else open, or closing */
  1236. result = flush_buf_tls(conn->tls, conn->outbuf, &conn->outbuf_flushlen);
  1237. switch (result) {
  1238. case TOR_TLS_ERROR:
  1239. case TOR_TLS_CLOSE:
  1240. info(LD_NET,result==TOR_TLS_ERROR?
  1241. "tls error. breaking.":"TLS connection closed on flush");
  1242. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  1243. connection_mark_for_close(conn);
  1244. return -1;
  1245. case TOR_TLS_WANTWRITE:
  1246. debug(LD_NET,"wanted write.");
  1247. /* we're already writing */
  1248. return 0;
  1249. case TOR_TLS_WANTREAD:
  1250. /* Make sure to avoid a loop if the receive buckets are empty. */
  1251. debug(LD_NET,"wanted read.");
  1252. if (!connection_is_reading(conn)) {
  1253. connection_stop_writing(conn);
  1254. conn->wants_to_write = 1;
  1255. /* we'll start reading again when the next second arrives,
  1256. * and then also start writing again.
  1257. */
  1258. }
  1259. /* else no problem, we're already reading */
  1260. return 0;
  1261. /* case TOR_TLS_DONE:
  1262. * for TOR_TLS_DONE, fall through to check if the flushlen
  1263. * is empty, so we can stop writing.
  1264. */
  1265. }
  1266. } else {
  1267. CONN_LOG_PROTECT(conn,
  1268. result = flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen));
  1269. if (result < 0) {
  1270. if (CONN_IS_EDGE(conn))
  1271. connection_edge_end_errno(conn, conn->cpath_layer);
  1272. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  1273. connection_mark_for_close(conn);
  1274. return -1;
  1275. }
  1276. }
  1277. if (result > 0 && !is_local_IP(conn->addr)) { /* remember it */
  1278. rep_hist_note_bytes_written(result, now);
  1279. global_write_bucket -= result;
  1280. }
  1281. if (!connection_wants_to_flush(conn)) { /* it's done flushing */
  1282. if (connection_finished_flushing(conn) < 0) {
  1283. /* already marked */
  1284. return -1;
  1285. }
  1286. }
  1287. return 0;
  1288. }
  1289. /* DOCDOC */
  1290. void
  1291. _connection_controller_force_write(connection_t *conn)
  1292. {
  1293. /* XXX This is hideous code duplication, but raising it seems a little
  1294. * tricky for now. Think more about this one. We only call it for
  1295. * EVENT_ERR_MSG, so messing with buckets a little isn't such a big problem.
  1296. */
  1297. int result;
  1298. tor_assert(conn);
  1299. tor_assert(!conn->tls);
  1300. tor_assert(conn->type == CONN_TYPE_CONTROL);
  1301. if (conn->marked_for_close || conn->s < 0)
  1302. return;
  1303. CONN_LOG_PROTECT(conn,
  1304. result = flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen));
  1305. if (result < 0) {
  1306. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  1307. connection_mark_for_close(conn);
  1308. return;
  1309. }
  1310. if (result > 0 && !is_local_IP(conn->addr)) { /* remember it */
  1311. rep_hist_note_bytes_written(result, time(NULL));
  1312. global_write_bucket -= result;
  1313. }
  1314. if (!connection_wants_to_flush(conn)) { /* it's done flushing */
  1315. if (connection_finished_flushing(conn) < 0) {
  1316. /* already marked */
  1317. return;
  1318. }
  1319. }
  1320. }
  1321. /** Append <b>len</b> bytes of <b>string</b> onto <b>conn</b>'s
  1322. * outbuf, and ask it to start writing.
  1323. */
  1324. void
  1325. connection_write_to_buf(const char *string, size_t len, connection_t *conn)
  1326. {
  1327. int r;
  1328. if (!len)
  1329. return;
  1330. /* if it's marked for close, only allow write if we mean to flush it */
  1331. if (conn->marked_for_close && !conn->hold_open_until_flushed)
  1332. return;
  1333. CONN_LOG_PROTECT(conn, r = write_to_buf(string, len, conn->outbuf));
  1334. if (r < 0) {
  1335. if (CONN_IS_EDGE(conn)) {
  1336. /* if it failed, it means we have our package/delivery windows set
  1337. wrong compared to our max outbuf size. close the whole circuit. */
  1338. warn(LD_NET,"write_to_buf failed. Closing circuit (fd %d).", conn->s);
  1339. circuit_mark_for_close(circuit_get_by_edge_conn(conn));
  1340. } else {
  1341. warn(LD_NET,"write_to_buf failed. Closing connection (fd %d).", conn->s);
  1342. connection_mark_for_close(conn);
  1343. }
  1344. return;
  1345. }
  1346. connection_start_writing(conn);
  1347. conn->outbuf_flushlen += len;
  1348. }
  1349. /** Return the conn to addr/port that has the most recent
  1350. * timestamp_created, or NULL if no such conn exists. */
  1351. connection_t *
  1352. connection_or_exact_get_by_addr_port(uint32_t addr, uint16_t port)
  1353. {
  1354. int i, n;
  1355. connection_t *conn, *best=NULL;
  1356. connection_t **carray;
  1357. get_connection_array(&carray,&n);
  1358. for (i=0;i<n;i++) {
  1359. conn = carray[i];
  1360. if (conn->type == CONN_TYPE_OR &&
  1361. conn->addr == addr &&
  1362. conn->port == port &&
  1363. !conn->marked_for_close &&
  1364. (!best || best->timestamp_created < conn->timestamp_created))
  1365. best = conn;
  1366. }
  1367. return best;
  1368. }
  1369. /** Return a connection with give type, address, port, and purpose or NULL if
  1370. * no such connection exists. */
  1371. connection_t *
  1372. connection_get_by_type_addr_port_purpose(int type, uint32_t addr, uint16_t port,
  1373. int purpose)
  1374. {
  1375. int i, n;
  1376. connection_t *conn;
  1377. connection_t **carray;
  1378. get_connection_array(&carray,&n);
  1379. for (i=0;i<n;i++) {
  1380. conn = carray[i];
  1381. if (conn->type == type &&
  1382. conn->addr == addr &&
  1383. conn->port == port &&
  1384. conn->purpose == purpose &&
  1385. !conn->marked_for_close)
  1386. return conn;
  1387. }
  1388. return NULL;
  1389. }
  1390. connection_t *
  1391. connection_get_by_identity_digest(const char *digest, int type)
  1392. {
  1393. int i, n;
  1394. connection_t *conn, *best=NULL;
  1395. connection_t **carray;
  1396. get_connection_array(&carray,&n);
  1397. for (i=0;i<n;i++) {
  1398. conn = carray[i];
  1399. if (conn->type != type)
  1400. continue;
  1401. if (!memcmp(conn->identity_digest, digest, DIGEST_LEN) &&
  1402. !conn->marked_for_close &&
  1403. (!best || best->timestamp_created < conn->timestamp_created))
  1404. best = conn;
  1405. }
  1406. return best;
  1407. }
  1408. /** Return the connection with id <b>id</b> if it is not already
  1409. * marked for close.
  1410. */
  1411. connection_t *
  1412. connection_get_by_global_id(uint32_t id)
  1413. {
  1414. int i, n;
  1415. connection_t *conn;
  1416. connection_t **carray;
  1417. get_connection_array(&carray,&n);
  1418. for (i=0;i<n;i++) {
  1419. conn = carray[i];
  1420. if (conn->global_identifier == id) {
  1421. if (!conn->marked_for_close)
  1422. return conn;
  1423. else
  1424. return NULL;
  1425. }
  1426. }
  1427. return NULL;
  1428. }
  1429. /** Return a connection of type <b>type</b> that is not marked for
  1430. * close.
  1431. */
  1432. connection_t *
  1433. connection_get_by_type(int type)
  1434. {
  1435. int i, n;
  1436. connection_t *conn;
  1437. connection_t **carray;
  1438. get_connection_array(&carray,&n);
  1439. for (i=0;i<n;i++) {
  1440. conn = carray[i];
  1441. if (conn->type == type && !conn->marked_for_close)
  1442. return conn;
  1443. }
  1444. return NULL;
  1445. }
  1446. /** Return a connection of type <b>type</b> that is in state <b>state</b>,
  1447. * and that is not marked for close.
  1448. */
  1449. connection_t *
  1450. connection_get_by_type_state(int type, int state)
  1451. {
  1452. int i, n;
  1453. connection_t *conn;
  1454. connection_t **carray;
  1455. get_connection_array(&carray,&n);
  1456. for (i=0;i<n;i++) {
  1457. conn = carray[i];
  1458. if (conn->type == type && conn->state == state && !conn->marked_for_close)
  1459. return conn;
  1460. }
  1461. return NULL;
  1462. }
  1463. /** Return the connection of type <b>type</b> that is in state
  1464. * <b>state</b>, that was written to least recently, and that is not
  1465. * marked for close.
  1466. */
  1467. connection_t *
  1468. connection_get_by_type_state_lastwritten(int type, int state)
  1469. {
  1470. int i, n;
  1471. connection_t *conn, *best=NULL;
  1472. connection_t **carray;
  1473. get_connection_array(&carray,&n);
  1474. for (i=0;i<n;i++) {
  1475. conn = carray[i];
  1476. if (conn->type == type && conn->state == state && !conn->marked_for_close)
  1477. if (!best || conn->timestamp_lastwritten < best->timestamp_lastwritten)
  1478. best = conn;
  1479. }
  1480. return best;
  1481. }
  1482. /** Return a connection of type <b>type</b> that has rendquery equal
  1483. * to <b>rendquery</b>, and that is not marked for close. If state
  1484. * is non-zero, conn must be of that state too.
  1485. */
  1486. connection_t *
  1487. connection_get_by_type_state_rendquery(int type, int state, const char *rendquery)
  1488. {
  1489. int i, n;
  1490. connection_t *conn;
  1491. connection_t **carray;
  1492. get_connection_array(&carray,&n);
  1493. for (i=0;i<n;i++) {
  1494. conn = carray[i];
  1495. if (conn->type == type &&
  1496. !conn->marked_for_close &&
  1497. (!state || state == conn->state) &&
  1498. !rend_cmp_service_ids(rendquery, conn->rend_query))
  1499. return conn;
  1500. }
  1501. return NULL;
  1502. }
  1503. /** Return an open, non-marked connection of a given type and purpose, or NULL
  1504. * if no such connection exists. */
  1505. connection_t *
  1506. connection_get_by_type_purpose(int type, int purpose)
  1507. {
  1508. int i, n;
  1509. connection_t *conn;
  1510. connection_t **carray;
  1511. get_connection_array(&carray,&n);
  1512. for (i=0;i<n;i++) {
  1513. conn = carray[i];
  1514. if (conn->type == type &&
  1515. !conn->marked_for_close &&
  1516. (purpose == conn->purpose))
  1517. return conn;
  1518. }
  1519. return NULL;
  1520. }
  1521. /** Return 1 if <b>conn</b> is a listener conn, else return 0. */
  1522. int
  1523. connection_is_listener(connection_t *conn)
  1524. {
  1525. if (conn->type == CONN_TYPE_OR_LISTENER ||
  1526. conn->type == CONN_TYPE_AP_LISTENER ||
  1527. conn->type == CONN_TYPE_DIR_LISTENER ||
  1528. conn->type == CONN_TYPE_CONTROL_LISTENER)
  1529. return 1;
  1530. return 0;
  1531. }
  1532. /** Return 1 if <b>conn</b> is in state "open" and is not marked
  1533. * for close, else return 0.
  1534. */
  1535. int
  1536. connection_state_is_open(connection_t *conn)
  1537. {
  1538. tor_assert(conn);
  1539. if (conn->marked_for_close)
  1540. return 0;
  1541. if ((conn->type == CONN_TYPE_OR && conn->state == OR_CONN_STATE_OPEN) ||
  1542. (conn->type == CONN_TYPE_AP && conn->state == AP_CONN_STATE_OPEN) ||
  1543. (conn->type == CONN_TYPE_EXIT && conn->state == EXIT_CONN_STATE_OPEN) ||
  1544. (conn->type == CONN_TYPE_CONTROL &&
  1545. (conn->state == CONTROL_CONN_STATE_OPEN_V0 ||
  1546. conn->state == CONTROL_CONN_STATE_OPEN_V1)))
  1547. return 1;
  1548. return 0;
  1549. }
  1550. /** Return 1 if conn is in 'connecting' state, else return 0. */
  1551. int
  1552. connection_state_is_connecting(connection_t *conn)
  1553. {
  1554. tor_assert(conn);
  1555. if (conn->marked_for_close)
  1556. return 0;
  1557. switch (conn->type)
  1558. {
  1559. case CONN_TYPE_OR:
  1560. return conn->state == OR_CONN_STATE_CONNECTING;
  1561. case CONN_TYPE_EXIT:
  1562. return conn->state == EXIT_CONN_STATE_CONNECTING;
  1563. case CONN_TYPE_DIR:
  1564. return conn->state == DIR_CONN_STATE_CONNECTING;
  1565. }
  1566. return 0;
  1567. }
  1568. /** Write a destroy cell with circ ID <b>circ_id</b> onto OR connection
  1569. * <b>conn</b>.
  1570. *
  1571. * Return 0.
  1572. */
  1573. /*XXXX Why isn't this in connection_or.c?*/
  1574. int
  1575. connection_send_destroy(uint16_t circ_id, connection_t *conn)
  1576. {
  1577. cell_t cell;
  1578. tor_assert(conn);
  1579. tor_assert(connection_speaks_cells(conn));
  1580. memset(&cell, 0, sizeof(cell_t));
  1581. cell.circ_id = circ_id;
  1582. cell.command = CELL_DESTROY;
  1583. debug(LD_OR,"Sending destroy (circID %d).", circ_id);
  1584. connection_or_write_cell_to_buf(&cell, conn);
  1585. return 0;
  1586. }
  1587. /** Alloocates a base64'ed authenticator for use in http or https
  1588. * auth, based on the input string <b>authenticator</b>. Returns it
  1589. * if success, else returns NULL. */
  1590. char *
  1591. alloc_http_authenticator(const char *authenticator)
  1592. {
  1593. /* an authenticator in Basic authentication
  1594. * is just the string "username:password" */
  1595. const int authenticator_length = strlen(authenticator);
  1596. /* The base64_encode function needs a minimum buffer length
  1597. * of 66 bytes. */
  1598. const int base64_authenticator_length = (authenticator_length/48+1)*66;
  1599. char *base64_authenticator = tor_malloc(base64_authenticator_length);
  1600. if (base64_encode(base64_authenticator, base64_authenticator_length,
  1601. authenticator, authenticator_length) < 0) {
  1602. tor_free(base64_authenticator); /* free and set to null */
  1603. } else {
  1604. /* remove extra \n at end of encoding */
  1605. base64_authenticator[strlen(base64_authenticator) - 1] = 0;
  1606. }
  1607. return base64_authenticator;
  1608. }
  1609. /** DOCDOC
  1610. * XXXX ipv6 NM
  1611. */
  1612. static void
  1613. client_check_address_changed(int sock)
  1614. {
  1615. uint32_t iface_ip, ip_out;
  1616. struct sockaddr_in out_addr;
  1617. socklen_t out_addr_len = sizeof(out_addr);
  1618. uint32_t *ip;
  1619. if (!last_interface_ip)
  1620. get_interface_address(&last_interface_ip);
  1621. if (!outgoing_addrs)
  1622. outgoing_addrs = smartlist_create();
  1623. if (getsockname(sock, (struct sockaddr*)&out_addr, &out_addr_len)<0) {
  1624. int e = tor_socket_errno(sock);
  1625. warn(LD_NET, "getsockname() failed: %s", tor_socket_strerror(e));
  1626. return;
  1627. }
  1628. /* Okay. If we've used this address previously, we're okay. */
  1629. ip_out = ntohl(out_addr.sin_addr.s_addr);
  1630. SMARTLIST_FOREACH(outgoing_addrs, uint32_t*, ip,
  1631. if (*ip == ip_out) return;
  1632. );
  1633. /* Uh-oh. We haven't connected from this address before. Has the interface
  1634. * address changed? */
  1635. if (get_interface_address(&iface_ip)<0)
  1636. return;
  1637. ip = tor_malloc(sizeof(uint32_t));
  1638. *ip = ip_out;
  1639. if (iface_ip == last_interface_ip) {
  1640. /* Nope, it hasn't changed. Add this address to the list. */
  1641. smartlist_add(outgoing_addrs, ip);
  1642. } else {
  1643. /* The interface changed. We're a client, so we need to regenerate our
  1644. * keys. First, reset the state. */
  1645. notice(LD_NET, "Our IP has changed. Rotating keys...");
  1646. last_interface_ip = iface_ip;
  1647. SMARTLIST_FOREACH(outgoing_addrs, void*, ip, tor_free(ip));
  1648. smartlist_clear(outgoing_addrs);
  1649. smartlist_add(outgoing_addrs, ip);
  1650. /* Okay, now change our keys. */
  1651. init_keys(); /* XXXX NM return value-- safe to ignore? */
  1652. }
  1653. }
  1654. /** Process new bytes that have arrived on conn-\>inbuf.
  1655. *
  1656. * This function just passes conn to the connection-specific
  1657. * connection_*_process_inbuf() function. It also passes in
  1658. * package_partial if wanted.
  1659. */
  1660. static int
  1661. connection_process_inbuf(connection_t *conn, int package_partial)
  1662. {
  1663. tor_assert(conn);
  1664. switch (conn->type) {
  1665. case CONN_TYPE_OR:
  1666. return connection_or_process_inbuf(conn);
  1667. case CONN_TYPE_EXIT:
  1668. case CONN_TYPE_AP:
  1669. return connection_edge_process_inbuf(conn, package_partial);
  1670. case CONN_TYPE_DIR:
  1671. return connection_dir_process_inbuf(conn);
  1672. case CONN_TYPE_DNSWORKER:
  1673. return connection_dns_process_inbuf(conn);
  1674. case CONN_TYPE_CPUWORKER:
  1675. return connection_cpu_process_inbuf(conn);
  1676. case CONN_TYPE_CONTROL:
  1677. return connection_control_process_inbuf(conn);
  1678. default:
  1679. err(LD_BUG,"Bug: got unexpected conn type %d.", conn->type);
  1680. tor_fragile_assert();
  1681. return -1;
  1682. }
  1683. }
  1684. /** We just finished flushing bytes from conn-\>outbuf, and there
  1685. * are no more bytes remaining.
  1686. *
  1687. * This function just passes conn to the connection-specific
  1688. * connection_*_finished_flushing() function.
  1689. */
  1690. static int
  1691. connection_finished_flushing(connection_t *conn)
  1692. {
  1693. tor_assert(conn);
  1694. // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
  1695. switch (conn->type) {
  1696. case CONN_TYPE_OR:
  1697. return connection_or_finished_flushing(conn);
  1698. case CONN_TYPE_AP:
  1699. case CONN_TYPE_EXIT:
  1700. return connection_edge_finished_flushing(conn);
  1701. case CONN_TYPE_DIR:
  1702. return connection_dir_finished_flushing(conn);
  1703. case CONN_TYPE_DNSWORKER:
  1704. return connection_dns_finished_flushing(conn);
  1705. case CONN_TYPE_CPUWORKER:
  1706. return connection_cpu_finished_flushing(conn);
  1707. case CONN_TYPE_CONTROL:
  1708. return connection_control_finished_flushing(conn);
  1709. default:
  1710. err(LD_BUG,"Bug: got unexpected conn type %d.", conn->type);
  1711. tor_fragile_assert();
  1712. return -1;
  1713. }
  1714. }
  1715. /** Called when our attempt to connect() to another server has just
  1716. * succeeded.
  1717. *
  1718. * This function just passes conn to the connection-specific
  1719. * connection_*_finished_connecting() function.
  1720. */
  1721. static int
  1722. connection_finished_connecting(connection_t *conn)
  1723. {
  1724. tor_assert(conn);
  1725. switch (conn->type)
  1726. {
  1727. case CONN_TYPE_OR:
  1728. return connection_or_finished_connecting(conn);
  1729. case CONN_TYPE_EXIT:
  1730. return connection_edge_finished_connecting(conn);
  1731. case CONN_TYPE_DIR:
  1732. return connection_dir_finished_connecting(conn);
  1733. default:
  1734. err(LD_BUG,"Bug: got unexpected conn type %d.", conn->type);
  1735. tor_fragile_assert();
  1736. return -1;
  1737. }
  1738. }
  1739. /** Callback: invoked when a connection reaches an EOF event. */
  1740. static int
  1741. connection_reached_eof(connection_t *conn)
  1742. {
  1743. switch (conn->type) {
  1744. case CONN_TYPE_OR:
  1745. return connection_or_reached_eof(conn);
  1746. case CONN_TYPE_AP:
  1747. case CONN_TYPE_EXIT:
  1748. return connection_edge_reached_eof(conn);
  1749. case CONN_TYPE_DIR:
  1750. return connection_dir_reached_eof(conn);
  1751. case CONN_TYPE_DNSWORKER:
  1752. return connection_dns_reached_eof(conn);
  1753. case CONN_TYPE_CPUWORKER:
  1754. return connection_cpu_reached_eof(conn);
  1755. case CONN_TYPE_CONTROL:
  1756. return connection_control_reached_eof(conn);
  1757. default:
  1758. err(LD_BUG,"Bug: got unexpected conn type %d.", conn->type);
  1759. tor_fragile_assert();
  1760. return -1;
  1761. }
  1762. }
  1763. /** Verify that connection <b>conn</b> has all of its invariants
  1764. * correct. Trigger an assert if anything is invalid.
  1765. */
  1766. void
  1767. assert_connection_ok(connection_t *conn, time_t now)
  1768. {
  1769. tor_assert(conn);
  1770. tor_assert(conn->magic == CONNECTION_MAGIC);
  1771. tor_assert(conn->type >= _CONN_TYPE_MIN);
  1772. tor_assert(conn->type <= _CONN_TYPE_MAX);
  1773. if (conn->outbuf_flushlen > 0) {
  1774. tor_assert(connection_is_writing(conn) || conn->wants_to_write);
  1775. }
  1776. if (conn->hold_open_until_flushed)
  1777. tor_assert(conn->marked_for_close);
  1778. /* XXX check: wants_to_read, wants_to_write, s, poll_index,
  1779. * marked_for_close. */
  1780. /* buffers */
  1781. if (!connection_is_listener(conn)) {
  1782. assert_buf_ok(conn->inbuf);
  1783. assert_buf_ok(conn->outbuf);
  1784. }
  1785. /* XXX Fix this; no longer so.*/
  1786. #if 0
  1787. if (conn->type != CONN_TYPE_OR && conn->type != CONN_TYPE_DIR)
  1788. tor_assert(!conn->pkey);
  1789. /* pkey is set if we're a dir client, or if we're an OR in state OPEN
  1790. * connected to another OR.
  1791. */
  1792. #endif
  1793. if (conn->type != CONN_TYPE_OR) {
  1794. tor_assert(!conn->tls);
  1795. } else {
  1796. if (conn->state == OR_CONN_STATE_OPEN) {
  1797. /* tor_assert(conn->bandwidth > 0); */
  1798. /* the above isn't necessarily true: if we just did a TLS
  1799. * handshake but we didn't recognize the other peer, or it
  1800. * gave a bad cert/etc, then we won't have assigned bandwidth,
  1801. * yet it will be open. -RD
  1802. */
  1803. // tor_assert(conn->receiver_bucket >= 0);
  1804. }
  1805. // tor_assert(conn->addr && conn->port);
  1806. tor_assert(conn->address);
  1807. if (conn->state > OR_CONN_STATE_PROXY_READING)
  1808. tor_assert(conn->tls);
  1809. }
  1810. if (! CONN_IS_EDGE(conn)) {
  1811. tor_assert(!conn->stream_id);
  1812. tor_assert(!conn->next_stream);
  1813. tor_assert(!conn->cpath_layer);
  1814. tor_assert(!conn->package_window);
  1815. tor_assert(!conn->deliver_window);
  1816. #if 0
  1817. tor_assert(!conn->done_sending);
  1818. tor_assert(!conn->done_receiving);
  1819. #endif
  1820. } else {
  1821. /* XXX unchecked: package window, deliver window. */
  1822. }
  1823. if (conn->type == CONN_TYPE_AP) {
  1824. tor_assert(conn->socks_request);
  1825. if (conn->state == AP_CONN_STATE_OPEN) {
  1826. tor_assert(conn->socks_request->has_finished);
  1827. if (!conn->marked_for_close) {
  1828. tor_assert(conn->cpath_layer);
  1829. assert_cpath_layer_ok(conn->cpath_layer);
  1830. }
  1831. }
  1832. } else {
  1833. tor_assert(!conn->socks_request);
  1834. }
  1835. if (conn->type == CONN_TYPE_EXIT) {
  1836. tor_assert(conn->purpose == EXIT_PURPOSE_CONNECT ||
  1837. conn->purpose == EXIT_PURPOSE_RESOLVE);
  1838. } else if (conn->type != CONN_TYPE_DIR) {
  1839. tor_assert(!conn->purpose); /* only used for dir types currently */
  1840. }
  1841. if (conn->type != CONN_TYPE_DIR) {
  1842. tor_assert(!conn->requested_resource);
  1843. }
  1844. switch (conn->type)
  1845. {
  1846. case CONN_TYPE_OR_LISTENER:
  1847. case CONN_TYPE_AP_LISTENER:
  1848. case CONN_TYPE_DIR_LISTENER:
  1849. case CONN_TYPE_CONTROL_LISTENER:
  1850. tor_assert(conn->state == LISTENER_STATE_READY);
  1851. break;
  1852. case CONN_TYPE_OR:
  1853. tor_assert(conn->state >= _OR_CONN_STATE_MIN);
  1854. tor_assert(conn->state <= _OR_CONN_STATE_MAX);
  1855. break;
  1856. case CONN_TYPE_EXIT:
  1857. tor_assert(conn->state >= _EXIT_CONN_STATE_MIN);
  1858. tor_assert(conn->state <= _EXIT_CONN_STATE_MAX);
  1859. break;
  1860. case CONN_TYPE_AP:
  1861. tor_assert(conn->state >= _AP_CONN_STATE_MIN);
  1862. tor_assert(conn->state <= _AP_CONN_STATE_MAX);
  1863. tor_assert(conn->socks_request);
  1864. break;
  1865. case CONN_TYPE_DIR:
  1866. tor_assert(conn->state >= _DIR_CONN_STATE_MIN);
  1867. tor_assert(conn->state <= _DIR_CONN_STATE_MAX);
  1868. tor_assert(conn->purpose >= _DIR_PURPOSE_MIN);
  1869. tor_assert(conn->purpose <= _DIR_PURPOSE_MAX);
  1870. break;
  1871. case CONN_TYPE_DNSWORKER:
  1872. tor_assert(conn->state == DNSWORKER_STATE_IDLE ||
  1873. conn->state == DNSWORKER_STATE_BUSY);
  1874. break;
  1875. case CONN_TYPE_CPUWORKER:
  1876. tor_assert(conn->state >= _CPUWORKER_STATE_MIN);
  1877. tor_assert(conn->state <= _CPUWORKER_STATE_MAX);
  1878. break;
  1879. case CONN_TYPE_CONTROL:
  1880. tor_assert(conn->state >= _CONTROL_CONN_STATE_MIN);
  1881. tor_assert(conn->state <= _CONTROL_CONN_STATE_MAX);
  1882. break;
  1883. default:
  1884. tor_assert(0);
  1885. }
  1886. }