connection.c 61 KB

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