connection.c 59 KB

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