connection.c 66 KB

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