connection.c 61 KB

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