connection.c 58 KB

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