connection.c 66 KB

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