connection.c 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125
  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. 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. 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. 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. 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. 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. 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. 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. 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. err(LD_BUG,"Bug: Attempt to close already-closed connection.");
  373. tor_fragile_assert();
  374. return;
  375. }
  376. if (conn->outbuf_flushlen) {
  377. 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. warn(LD_CONFIG, "Error parsing/resolving ListenAddress %s",listenaddress);
  474. return NULL;
  475. }
  476. if (usePort==0)
  477. usePort = listenport;
  478. listenaddr.sin_addr.s_addr = htonl(addr);
  479. listenaddr.sin_family = AF_INET;
  480. listenaddr.sin_port = htons((uint16_t) usePort);
  481. notice(LD_NET, "Opening %s on %s:%d",
  482. conn_type_to_string(type), address, usePort);
  483. s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
  484. if (s < 0) {
  485. warn(LD_NET,"Socket creation failed.");
  486. goto err;
  487. } else if (!SOCKET_IS_POLLABLE(s)) {
  488. warn(LD_NET,"Too many connections; can't create pollable listener.");
  489. tor_close_socket(s);
  490. goto err;
  491. }
  492. #ifndef MS_WINDOWS
  493. /* REUSEADDR on normal places means you can rebind to the port
  494. * right after somebody else has let it go. But REUSEADDR on win32
  495. * means you can bind to the port _even when somebody else
  496. * already has it bound_. So, don't do that on Win32. */
  497. setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*) &one, sizeof(one));
  498. #endif
  499. if (bind(s,(struct sockaddr *)&listenaddr,sizeof(listenaddr)) < 0) {
  500. const char *helpfulhint = "";
  501. int e = tor_socket_errno(s);
  502. if (ERRNO_IS_EADDRINUSE(e))
  503. helpfulhint = ". Is Tor already running?";
  504. warn(LD_NET, "Could not bind to %s:%u: %s%s", address, usePort,
  505. tor_socket_strerror(e), helpfulhint);
  506. goto err;
  507. }
  508. if (listen(s,SOMAXCONN) < 0) {
  509. warn(LD_NET, "Could not listen on %s:%u: %s", address, usePort,
  510. tor_socket_strerror(tor_socket_errno(s)));
  511. goto err;
  512. }
  513. set_socket_nonblocking(s);
  514. conn = connection_new(type);
  515. conn->s = s;
  516. conn->address = address;
  517. address = NULL;
  518. conn->port = usePort;
  519. if (connection_add(conn) < 0) { /* no space, forget it */
  520. warn(LD_NET,"connection_add failed. Giving up.");
  521. connection_free(conn);
  522. goto err;
  523. }
  524. debug(LD_NET,"%s listening on port %u.",conn_type_to_string(type), usePort);
  525. conn->state = LISTENER_STATE_READY;
  526. connection_start_reading(conn);
  527. return conn;
  528. err:
  529. tor_free(address);
  530. return NULL;
  531. }
  532. /** Do basic sanity checking on a newly received socket. Return 0
  533. * if it looks ok, else return -1. */
  534. static int
  535. check_sockaddr_in(struct sockaddr *sa, int len, int level)
  536. {
  537. int ok = 1;
  538. struct sockaddr_in *sin=(struct sockaddr_in*)sa;
  539. if (len != sizeof(struct sockaddr_in)) {
  540. log_fn(level, LD_NET, "Length of address not as expected: %d vs %d",
  541. len,(int)sizeof(struct sockaddr_in));
  542. ok = 0;
  543. }
  544. if (sa->sa_family != AF_INET) {
  545. log_fn(level, LD_NET, "Family of address not as expected: %d vs %d",
  546. sa->sa_family, AF_INET);
  547. ok = 0;
  548. }
  549. if (sin->sin_addr.s_addr == 0 || sin->sin_port == 0) {
  550. log_fn(level, LD_NET,
  551. "Address for new connection has address/port equal to zero.");
  552. ok = 0;
  553. }
  554. return ok ? 0 : -1;
  555. }
  556. /** The listener connection <b>conn</b> told poll() it wanted to read.
  557. * Call accept() on conn-\>s, and add the new connection if necessary.
  558. */
  559. static int
  560. connection_handle_listener_read(connection_t *conn, int new_type)
  561. {
  562. int news; /* the new socket */
  563. connection_t *newconn;
  564. /* information about the remote peer when connecting to other routers */
  565. struct sockaddr_in remote;
  566. char addrbuf[256];
  567. /* length of the remote address. Must be whatever accept() needs. */
  568. socklen_t remotelen = 256;
  569. char tmpbuf[INET_NTOA_BUF_LEN];
  570. tor_assert((size_t)remotelen >= sizeof(struct sockaddr_in));
  571. memset(addrbuf, 0, sizeof(addrbuf));
  572. news = accept(conn->s,(struct sockaddr *)&addrbuf,&remotelen);
  573. if (!SOCKET_IS_POLLABLE(news)) {
  574. /* accept() error, or too many conns to poll */
  575. int e;
  576. if (news>=0) {
  577. /* Too many conns to poll. */
  578. warn(LD_NET,"Too many connections; couldn't accept connection.");
  579. tor_close_socket(news);
  580. return 0;
  581. }
  582. e = tor_socket_errno(conn->s);
  583. if (ERRNO_IS_ACCEPT_EAGAIN(e)) {
  584. return 0; /* he hung up before we could accept(). that's fine. */
  585. } else if (ERRNO_IS_ACCEPT_RESOURCE_LIMIT(e)) {
  586. notice(LD_NET,"accept failed: %s. Dropping incoming connection.",
  587. tor_socket_strerror(e));
  588. return 0;
  589. }
  590. /* else there was a real error. */
  591. warn(LD_NET,"accept() failed: %s. Closing listener.",
  592. tor_socket_strerror(e));
  593. connection_mark_for_close(conn);
  594. return -1;
  595. }
  596. debug(LD_NET,"Connection accepted on socket %d (child of fd %d).",
  597. news,conn->s);
  598. set_socket_nonblocking(news);
  599. if (check_sockaddr_in((struct sockaddr*)addrbuf, remotelen, LOG_INFO)<0) {
  600. info(LD_NET, "accept() returned a strange address; trying getsockname().");
  601. remotelen=256;
  602. memset(addrbuf, 0, sizeof(addrbuf));
  603. if (getsockname(news, (struct sockaddr*)addrbuf, &remotelen)<0) {
  604. warn(LD_NET, "getsockname() failed.");
  605. } else {
  606. if (check_sockaddr_in((struct sockaddr*)addrbuf, remotelen,
  607. LOG_WARN) < 0) {
  608. warn(LD_NET,"Something's wrong with this conn. Closing it.");
  609. tor_close_socket(news);
  610. return 0;
  611. }
  612. }
  613. }
  614. memcpy(&remote, addrbuf, sizeof(struct sockaddr_in));
  615. /* process entrance policies here, before we even create the connection */
  616. if (new_type == CONN_TYPE_AP) {
  617. /* check sockspolicy to see if we should accept it */
  618. if (socks_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
  619. tor_inet_ntoa(&remote.sin_addr, tmpbuf, sizeof(tmpbuf));
  620. notice(LD_APP,"Denying socks connection from untrusted address %s.",
  621. tmpbuf);
  622. tor_close_socket(news);
  623. return 0;
  624. }
  625. }
  626. if (new_type == CONN_TYPE_DIR) {
  627. /* check dirpolicy to see if we should accept it */
  628. if (dir_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
  629. tor_inet_ntoa(&remote.sin_addr, tmpbuf, sizeof(tmpbuf));
  630. notice(LD_DIRSERV,"Denying dir connection from address %s.",
  631. tmpbuf);
  632. tor_close_socket(news);
  633. return 0;
  634. }
  635. }
  636. newconn = connection_new(new_type);
  637. newconn->s = news;
  638. /* remember the remote address */
  639. newconn->addr = ntohl(remote.sin_addr.s_addr);
  640. newconn->port = ntohs(remote.sin_port);
  641. newconn->address = tor_dup_addr(newconn->addr);
  642. if (connection_add(newconn) < 0) { /* no space, forget it */
  643. connection_free(newconn);
  644. return 0; /* no need to tear down the parent */
  645. }
  646. if (connection_init_accepted_conn(newconn) < 0) {
  647. connection_mark_for_close(newconn);
  648. return 0;
  649. }
  650. return 0;
  651. }
  652. /** Initialize states for newly accepted connection <b>conn</b>.
  653. * If conn is an OR, start the tls handshake.
  654. */
  655. static int
  656. connection_init_accepted_conn(connection_t *conn)
  657. {
  658. connection_start_reading(conn);
  659. switch (conn->type) {
  660. case CONN_TYPE_OR:
  661. return connection_tls_start_handshake(conn, 1);
  662. case CONN_TYPE_AP:
  663. conn->state = AP_CONN_STATE_SOCKS_WAIT;
  664. break;
  665. case CONN_TYPE_DIR:
  666. conn->purpose = DIR_PURPOSE_SERVER;
  667. conn->state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
  668. break;
  669. case CONN_TYPE_CONTROL:
  670. conn->state = CONTROL_CONN_STATE_NEEDAUTH_V0;
  671. break;
  672. }
  673. return 0;
  674. }
  675. /** Take conn, make a nonblocking socket; try to connect to
  676. * addr:port (they arrive in *host order*). If fail, return -1. Else
  677. * assign s to conn-\>s: if connected return 1, if EAGAIN return 0.
  678. *
  679. * address is used to make the logs useful.
  680. *
  681. * On success, add conn to the list of polled connections.
  682. */
  683. int
  684. connection_connect(connection_t *conn, char *address,
  685. uint32_t addr, uint16_t port)
  686. {
  687. int s, inprogress = 0;
  688. struct sockaddr_in dest_addr;
  689. or_options_t *options = get_options();
  690. s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
  691. if (s < 0) {
  692. warn(LD_NET,"Error creating network socket: %s",
  693. tor_socket_strerror(tor_socket_errno(-1)));
  694. return -1;
  695. } else if (!SOCKET_IS_POLLABLE(s)) {
  696. warn(LD_NET,
  697. "Too many connections; can't create pollable connection to %s",
  698. safe_str(address));
  699. tor_close_socket(s);
  700. return -1;
  701. }
  702. if (options->OutboundBindAddress) {
  703. struct sockaddr_in ext_addr;
  704. memset(&ext_addr, 0, sizeof(ext_addr));
  705. ext_addr.sin_family = AF_INET;
  706. ext_addr.sin_port = 0;
  707. if (!tor_inet_aton(options->OutboundBindAddress, &ext_addr.sin_addr)) {
  708. warn(LD_CONFIG,"Outbound bind address '%s' didn't parse. Ignoring.",
  709. options->OutboundBindAddress);
  710. } else {
  711. if (bind(s, (struct sockaddr*)&ext_addr, sizeof(ext_addr)) < 0) {
  712. warn(LD_NET,"Error binding network socket: %s",
  713. tor_socket_strerror(tor_socket_errno(s)));
  714. return -1;
  715. }
  716. }
  717. }
  718. set_socket_nonblocking(s);
  719. memset(&dest_addr,0,sizeof(dest_addr));
  720. dest_addr.sin_family = AF_INET;
  721. dest_addr.sin_port = htons(port);
  722. dest_addr.sin_addr.s_addr = htonl(addr);
  723. debug(LD_NET,"Connecting to %s:%u.",safe_str(address),port);
  724. if (connect(s,(struct sockaddr *)&dest_addr,sizeof(dest_addr)) < 0) {
  725. int e = tor_socket_errno(s);
  726. if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
  727. /* yuck. kill it. */
  728. info(LD_NET,"connect() to %s:%u failed: %s",safe_str(address),port,
  729. tor_socket_strerror(e));
  730. tor_close_socket(s);
  731. return -1;
  732. } else {
  733. inprogress = 1;
  734. }
  735. }
  736. if (!server_mode(options))
  737. client_check_address_changed(s);
  738. /* it succeeded. we're connected. */
  739. log_fn(inprogress?LOG_DEBUG:LOG_INFO, LD_NET,
  740. "Connection to %s:%u %s (sock %d).",safe_str(address),port,
  741. inprogress?"in progress":"established",s);
  742. conn->s = s;
  743. if (connection_add(conn) < 0) /* no space, forget it */
  744. return -1;
  745. return inprogress ? 0 : 1;
  746. }
  747. /**
  748. * Launch any configured listener connections of type <b>type</b>. (A
  749. * listener is configured if <b>port_option</b> is non-zero. If any
  750. * ListenAddress configuration options are given in <b>cfg</b>, create a
  751. * connection binding to each one. Otherwise, create a single
  752. * connection binding to the address <b>default_addr</b>.)
  753. *
  754. * If <b>force</b> is true, close and re-open all listener connections.
  755. * Otherwise, only relaunch the listeners of this type if the number of
  756. * existing connections is not as configured (e.g., because one died),
  757. * or if the existing connections do not match those configured.
  758. *
  759. * Add all old conns that should be closed to <b>replaced_conns</b>.
  760. * Add all new connections to <b>new_conns</b>.
  761. */
  762. static int
  763. retry_listeners(int type, config_line_t *cfg,
  764. int port_option, const char *default_addr, int force,
  765. smartlist_t *replaced_conns,
  766. smartlist_t *new_conns)
  767. {
  768. smartlist_t *launch = smartlist_create();
  769. int free_launch_elts = 1;
  770. config_line_t *c;
  771. int n_conn, i;
  772. connection_t *conn;
  773. connection_t **carray;
  774. config_line_t *line;
  775. if (cfg && port_option) {
  776. for (c = cfg; c; c = c->next) {
  777. smartlist_add(launch, c);
  778. }
  779. free_launch_elts = 0;
  780. } else if (port_option) {
  781. line = tor_malloc_zero(sizeof(config_line_t));
  782. line->key = tor_strdup("");
  783. line->value = tor_strdup(default_addr);
  784. smartlist_add(launch, line);
  785. }
  786. /*
  787. SMARTLIST_FOREACH(launch, config_line_t *, l,
  788. log_fn(LOG_NOTICE, "#%s#%s", l->key, l->value));
  789. */
  790. get_connection_array(&carray,&n_conn);
  791. for (i=0; i < n_conn; ++i) {
  792. conn = carray[i];
  793. if (conn->type != type || conn->marked_for_close)
  794. continue;
  795. if (force) {
  796. /* It's a listener, and we're relaunching all listeners of this
  797. * type. Close this one. */
  798. log_fn(LOG_NOTICE, LD_NET, "Closing %s on %s:%d",
  799. conn_type_to_string(type), conn->address, conn->port);
  800. connection_close_immediate(conn);
  801. connection_mark_for_close(conn);
  802. continue;
  803. }
  804. /* Okay, so this is a listener. Is it configured? */
  805. line = NULL;
  806. SMARTLIST_FOREACH(launch, config_line_t *, wanted,
  807. {
  808. char *address=NULL;
  809. uint16_t port;
  810. if (! parse_addr_port(wanted->value, &address, NULL, &port)) {
  811. int addr_matches = !strcasecmp(address, conn->address);
  812. tor_free(address);
  813. if (! port)
  814. port = port_option;
  815. if (port == conn->port && addr_matches) {
  816. line = wanted;
  817. break;
  818. }
  819. }
  820. });
  821. if (! line) {
  822. /* This one isn't configured. Close it. */
  823. notice(LD_NET, "Closing %s on %s:%d",
  824. conn_type_to_string(type), conn->address, conn->port);
  825. if (replaced_conns) {
  826. smartlist_add(replaced_conns, conn);
  827. } else {
  828. connection_close_immediate(conn);
  829. connection_mark_for_close(conn);
  830. }
  831. } else {
  832. /* It's configured; we don't need to launch it. */
  833. // debug(LD_NET, "Already have %s on %s:%d",
  834. // conn_type_to_string(type), conn->address, conn->port);
  835. smartlist_remove(launch, line);
  836. if (free_launch_elts)
  837. config_free_lines(line);
  838. }
  839. }
  840. /* Now open all the listeners that are configured but not opened. */
  841. i = 0;
  842. SMARTLIST_FOREACH(launch, config_line_t *, cfg,
  843. {
  844. conn = connection_create_listener(cfg->value, (uint16_t) port_option,
  845. type);
  846. if (!conn) {
  847. i = -1;
  848. } else {
  849. if (new_conns)
  850. smartlist_add(new_conns, conn);
  851. }
  852. });
  853. if (free_launch_elts) {
  854. SMARTLIST_FOREACH(launch, config_line_t *, cfg,
  855. config_free_lines(cfg));
  856. }
  857. smartlist_free(launch);
  858. return i;
  859. }
  860. /** (Re)launch listeners for each port you should have open. If
  861. * <b>force</b> is true, close and relaunch all listeners. If <b>force</b>
  862. * is false, then only relaunch listeners when we have the wrong number of
  863. * connections for a given type.
  864. *
  865. * Add all old conns that should be closed to <b>replaced_conns</b>.
  866. * Add all new connections to <b>new_conns</b>.
  867. */
  868. int
  869. retry_all_listeners(int force, smartlist_t *replaced_conns,
  870. smartlist_t *new_conns)
  871. {
  872. or_options_t *options = get_options();
  873. if (server_mode(options) &&
  874. retry_listeners(CONN_TYPE_OR_LISTENER, options->ORListenAddress,
  875. options->ORPort, "0.0.0.0", force,
  876. replaced_conns, new_conns)<0)
  877. return -1;
  878. if (retry_listeners(CONN_TYPE_DIR_LISTENER, options->DirListenAddress,
  879. options->DirPort, "0.0.0.0", force,
  880. replaced_conns, new_conns)<0)
  881. return -1;
  882. if (retry_listeners(CONN_TYPE_AP_LISTENER, options->SocksListenAddress,
  883. options->SocksPort, "127.0.0.1", force,
  884. replaced_conns, new_conns)<0)
  885. return -1;
  886. if (retry_listeners(CONN_TYPE_CONTROL_LISTENER, NULL,
  887. options->ControlPort, "127.0.0.1", force,
  888. replaced_conns, new_conns)<0)
  889. return -1;
  890. return 0;
  891. }
  892. extern int global_read_bucket, global_write_bucket;
  893. /** How many bytes at most can we read onto this connection? */
  894. static int
  895. connection_bucket_read_limit(connection_t *conn)
  896. {
  897. int at_most;
  898. int base = connection_speaks_cells(conn) ?
  899. CELL_NETWORK_SIZE : RELAY_PAYLOAD_SIZE;
  900. /* Do a rudimentary round-robin so one circuit can't hog a connection.
  901. * Pick at most 32 cells, at least 4 cells if possible, and if we're in
  902. * the middle pick 1/8 of the available bandwidth. */
  903. at_most = global_read_bucket / 8;
  904. at_most -= (at_most % base); /* round down */
  905. if (at_most > 32*base) /* 16 KB */
  906. at_most = 32*base;
  907. else if (at_most < 4*base) /* 2 KB */
  908. at_most = 4*base;
  909. if (at_most > global_read_bucket)
  910. at_most = global_read_bucket;
  911. if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN)
  912. if (at_most > conn->receiver_bucket)
  913. at_most = conn->receiver_bucket;
  914. if (at_most < 0)
  915. return 0;
  916. return at_most;
  917. }
  918. /** How many bytes at most can we write onto this connection? */
  919. int
  920. connection_bucket_write_limit(connection_t *conn)
  921. {
  922. unsigned int at_most;
  923. /* do a rudimentary round-robin so one circuit can't hog a connection */
  924. if (connection_speaks_cells(conn)) {
  925. at_most = 32*(CELL_NETWORK_SIZE);
  926. } else {
  927. at_most = 32*(RELAY_PAYLOAD_SIZE);
  928. }
  929. if (at_most > conn->outbuf_flushlen)
  930. at_most = conn->outbuf_flushlen;
  931. #if 0 /* don't enable til we actually do write limiting */
  932. if (at_most > global_write_bucket)
  933. at_most = global_write_bucket;
  934. #endif
  935. return at_most;
  936. }
  937. /** We just read num_read onto conn. Decrement buckets appropriately. */
  938. static void
  939. connection_read_bucket_decrement(connection_t *conn, int num_read)
  940. {
  941. global_read_bucket -= num_read;
  942. //tor_assert(global_read_bucket >= 0);
  943. if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
  944. conn->receiver_bucket -= num_read;
  945. //tor_assert(conn->receiver_bucket >= 0);
  946. }
  947. }
  948. /** If we have exhaused our global read bucket, or the read bucket for conn,
  949. * stop reading. */
  950. static void
  951. connection_consider_empty_buckets(connection_t *conn)
  952. {
  953. if (global_read_bucket <= 0) {
  954. LOG_FN_CONN(conn, (LOG_DEBUG,LD_NET,"global bucket exhausted. Pausing."));
  955. conn->wants_to_read = 1;
  956. connection_stop_reading(conn);
  957. return;
  958. }
  959. if (connection_speaks_cells(conn) &&
  960. conn->state == OR_CONN_STATE_OPEN &&
  961. conn->receiver_bucket <= 0) {
  962. LOG_FN_CONN(conn,
  963. (LOG_DEBUG,LD_NET,"receiver bucket exhausted. Pausing."));
  964. conn->wants_to_read = 1;
  965. connection_stop_reading(conn);
  966. }
  967. }
  968. /** Initialize the global read bucket to options->BandwidthBurst,
  969. * and current_time to the current time. */
  970. void
  971. connection_bucket_init(void)
  972. {
  973. or_options_t *options = get_options();
  974. /* start it at max traffic */
  975. global_read_bucket = (int)options->BandwidthBurst;
  976. global_write_bucket = (int)options->BandwidthBurst;
  977. }
  978. /** A second has rolled over; increment buckets appropriately. */
  979. void
  980. connection_bucket_refill(struct timeval *now)
  981. {
  982. int i, n;
  983. connection_t *conn;
  984. connection_t **carray;
  985. or_options_t *options = get_options();
  986. /* refill the global buckets */
  987. if (global_read_bucket < (int)options->BandwidthBurst) {
  988. global_read_bucket += (int)options->BandwidthRate;
  989. debug(LD_NET,"global_read_bucket now %d.", global_read_bucket);
  990. }
  991. if (global_write_bucket < (int)options->BandwidthBurst) {
  992. global_write_bucket += (int)options->BandwidthRate;
  993. debug(LD_NET,"global_write_bucket now %d.", global_write_bucket);
  994. }
  995. /* refill the per-connection buckets */
  996. get_connection_array(&carray,&n);
  997. for (i=0;i<n;i++) {
  998. conn = carray[i];
  999. if (connection_receiver_bucket_should_increase(conn)) {
  1000. conn->receiver_bucket = conn->bandwidth;
  1001. //log_fn(LOG_DEBUG,"Receiver bucket %d now %d.", i,
  1002. // conn->receiver_bucket);
  1003. }
  1004. if (conn->wants_to_read == 1 /* it's marked to turn reading back on now */
  1005. && global_read_bucket > 0 /* and we're allowed to read */
  1006. && global_write_bucket > 0 /* and we're allowed to write (XXXX,
  1007. * not the best place to check this.) */
  1008. && (!connection_speaks_cells(conn) ||
  1009. conn->state != OR_CONN_STATE_OPEN ||
  1010. conn->receiver_bucket > 0)) {
  1011. /* and either a non-cell conn or a cell conn with non-empty bucket */
  1012. LOG_FN_CONN(conn, (LOG_DEBUG,LD_NET,"waking up conn (fd %d)",conn->s));
  1013. conn->wants_to_read = 0;
  1014. connection_start_reading(conn);
  1015. if (conn->wants_to_write == 1) {
  1016. conn->wants_to_write = 0;
  1017. connection_start_writing(conn);
  1018. }
  1019. }
  1020. }
  1021. }
  1022. /** Is the receiver bucket for connection <b>conn</b> low enough that we
  1023. * should add another pile of tokens to it?
  1024. */
  1025. static int
  1026. connection_receiver_bucket_should_increase(connection_t *conn)
  1027. {
  1028. tor_assert(conn);
  1029. if (!connection_speaks_cells(conn))
  1030. return 0; /* edge connections don't use receiver_buckets */
  1031. if (conn->state != OR_CONN_STATE_OPEN)
  1032. return 0; /* only open connections play the rate limiting game */
  1033. if (conn->receiver_bucket >= conn->bandwidth)
  1034. return 0;
  1035. return 1;
  1036. }
  1037. /** Read bytes from conn-\>s and process them.
  1038. *
  1039. * This function gets called from conn_read() in main.c, either
  1040. * when poll() has declared that conn wants to read, or (for OR conns)
  1041. * when there are pending TLS bytes.
  1042. *
  1043. * It calls connection_read_to_buf() to bring in any new bytes,
  1044. * and then calls connection_process_inbuf() to process them.
  1045. *
  1046. * Mark the connection and return -1 if you want to close it, else
  1047. * return 0.
  1048. */
  1049. int
  1050. connection_handle_read(connection_t *conn)
  1051. {
  1052. int max_to_read=-1, try_to_read;
  1053. if (conn->marked_for_close)
  1054. return 0; /* do nothing */
  1055. conn->timestamp_lastread = time(NULL);
  1056. switch (conn->type) {
  1057. case CONN_TYPE_OR_LISTENER:
  1058. return connection_handle_listener_read(conn, CONN_TYPE_OR);
  1059. case CONN_TYPE_AP_LISTENER:
  1060. return connection_handle_listener_read(conn, CONN_TYPE_AP);
  1061. case CONN_TYPE_DIR_LISTENER:
  1062. return connection_handle_listener_read(conn, CONN_TYPE_DIR);
  1063. case CONN_TYPE_CONTROL_LISTENER:
  1064. return connection_handle_listener_read(conn, CONN_TYPE_CONTROL);
  1065. }
  1066. loop_again:
  1067. try_to_read = max_to_read;
  1068. tor_assert(!conn->marked_for_close);
  1069. if (connection_read_to_buf(conn, &max_to_read) < 0) {
  1070. /* There's a read error; kill the connection.*/
  1071. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  1072. if (CONN_IS_EDGE(conn)) {
  1073. connection_edge_end_errno(conn, conn->cpath_layer);
  1074. if (conn->socks_request) /* broken, so don't send a socks reply back */
  1075. conn->socks_request->has_finished = 1;
  1076. }
  1077. connection_mark_for_close(conn);
  1078. return -1;
  1079. }
  1080. if (CONN_IS_EDGE(conn) &&
  1081. try_to_read != max_to_read) {
  1082. /* instruct it not to try to package partial cells. */
  1083. if (connection_process_inbuf(conn, 0) < 0) {
  1084. return -1;
  1085. }
  1086. if (!conn->marked_for_close &&
  1087. connection_is_reading(conn) &&
  1088. !conn->inbuf_reached_eof &&
  1089. max_to_read > 0)
  1090. goto loop_again; /* try reading again, in case more is here now */
  1091. }
  1092. /* one last try, packaging partial cells and all. */
  1093. if (!conn->marked_for_close &&
  1094. connection_process_inbuf(conn, 1) < 0) {
  1095. return -1;
  1096. }
  1097. if (!conn->marked_for_close &&
  1098. conn->inbuf_reached_eof &&
  1099. connection_reached_eof(conn) < 0) {
  1100. return -1;
  1101. }
  1102. return 0;
  1103. }
  1104. /** Pull in new bytes from conn-\>s onto conn-\>inbuf, either
  1105. * directly or via TLS. Reduce the token buckets by the number of
  1106. * bytes read.
  1107. *
  1108. * If *max_to_read is -1, then decide it ourselves, else go with the
  1109. * value passed to us. When returning, if it's changed, subtract the
  1110. * number of bytes we read from *max_to_read.
  1111. *
  1112. * Return -1 if we want to break conn, else return 0.
  1113. */
  1114. static int
  1115. connection_read_to_buf(connection_t *conn, int *max_to_read)
  1116. {
  1117. int result, at_most = *max_to_read;
  1118. size_t bytes_in_buf, more_to_read;
  1119. if (at_most == -1) { /* we need to initialize it */
  1120. /* how many bytes are we allowed to read? */
  1121. at_most = connection_bucket_read_limit(conn);
  1122. }
  1123. bytes_in_buf = buf_capacity(conn->inbuf) - buf_datalen(conn->inbuf);
  1124. again:
  1125. if ((size_t)at_most > bytes_in_buf && bytes_in_buf >= 1024) {
  1126. more_to_read = at_most - bytes_in_buf;
  1127. at_most = bytes_in_buf;
  1128. } else {
  1129. more_to_read = 0;
  1130. }
  1131. if (connection_speaks_cells(conn) &&
  1132. conn->state > OR_CONN_STATE_PROXY_READING) {
  1133. int pending;
  1134. if (conn->state == OR_CONN_STATE_HANDSHAKING) {
  1135. /* continue handshaking even if global token bucket is empty */
  1136. return connection_tls_continue_handshake(conn);
  1137. }
  1138. debug(LD_NET,"%d: starting, inbuf_datalen %d (%d pending in tls object)."
  1139. " at_most %d.",
  1140. conn->s,(int)buf_datalen(conn->inbuf),
  1141. tor_tls_get_pending_bytes(conn->tls), at_most);
  1142. /* else open, or closing */
  1143. result = read_to_buf_tls(conn->tls, at_most, conn->inbuf);
  1144. switch (result) {
  1145. case TOR_TLS_CLOSE:
  1146. info(LD_NET,"TLS connection closed on read. Closing. "
  1147. "(Nickname %s, address %s",
  1148. conn->nickname ? conn->nickname : "not set", conn->address);
  1149. return -1;
  1150. case TOR_TLS_ERROR:
  1151. info(LD_NET,"tls error. breaking (nickname %s, address %s).",
  1152. conn->nickname ? conn->nickname : "not set", conn->address);
  1153. return -1;
  1154. case TOR_TLS_WANTWRITE:
  1155. connection_start_writing(conn);
  1156. return 0;
  1157. case TOR_TLS_WANTREAD: /* we're already reading */
  1158. case TOR_TLS_DONE: /* no data read, so nothing to process */
  1159. result = 0;
  1160. break; /* so we call bucket_decrement below */
  1161. default:
  1162. break;
  1163. }
  1164. pending = tor_tls_get_pending_bytes(conn->tls);
  1165. if (pending) {
  1166. /* XXXX If we have any pending bytes, read them now. This *can*
  1167. * take us over our read allotment, but really we shouldn't be
  1168. * believing that SSL bytes are the same as TCP bytes anyway. */
  1169. int r2 = read_to_buf_tls(conn->tls, pending, conn->inbuf);
  1170. if (r2<0) {
  1171. warn(LD_BUG, "Bug: apparently, reading pending bytes can fail.");
  1172. return -1;
  1173. } else {
  1174. result += r2;
  1175. }
  1176. }
  1177. } else {
  1178. CONN_LOG_PROTECT(conn,
  1179. result = read_to_buf(conn->s, at_most, conn->inbuf,
  1180. &conn->inbuf_reached_eof));
  1181. // log_fn(LOG_DEBUG,"read_to_buf returned %d.",read_result);
  1182. if (result < 0)
  1183. return -1;
  1184. }
  1185. if (result > 0) { /* change *max_to_read */
  1186. *max_to_read = at_most - result;
  1187. }
  1188. if (result > 0 && !is_local_IP(conn->addr)) { /* remember it */
  1189. rep_hist_note_bytes_read(result, time(NULL));
  1190. connection_read_bucket_decrement(conn, result);
  1191. }
  1192. if (more_to_read && result == at_most) {
  1193. bytes_in_buf = buf_capacity(conn->inbuf) - buf_datalen(conn->inbuf);
  1194. tor_assert(bytes_in_buf < 1024);
  1195. at_most = more_to_read;
  1196. goto again;
  1197. }
  1198. /* Call even if result is 0, since the global read bucket may
  1199. * have reached 0 on a different conn, and this guy needs to
  1200. * know to stop reading. */
  1201. connection_consider_empty_buckets(conn);
  1202. return 0;
  1203. }
  1204. /** A pass-through to fetch_from_buf. */
  1205. int
  1206. connection_fetch_from_buf(char *string, size_t len, connection_t *conn)
  1207. {
  1208. return fetch_from_buf(string, len, conn->inbuf);
  1209. }
  1210. /** Return conn-\>outbuf_flushlen: how many bytes conn wants to flush
  1211. * from its outbuf. */
  1212. int
  1213. connection_wants_to_flush(connection_t *conn)
  1214. {
  1215. return conn->outbuf_flushlen;
  1216. }
  1217. /** Are there too many bytes on edge connection <b>conn</b>'s outbuf to
  1218. * send back a relay-level sendme yet? Return 1 if so, 0 if not. Used by
  1219. * connection_edge_consider_sending_sendme().
  1220. */
  1221. int
  1222. connection_outbuf_too_full(connection_t *conn)
  1223. {
  1224. return (conn->outbuf_flushlen > 10*CELL_PAYLOAD_SIZE);
  1225. }
  1226. /** Try to flush more bytes onto conn-\>s.
  1227. *
  1228. * This function gets called either from conn_write() in main.c
  1229. * when poll() has declared that conn wants to write, or below
  1230. * from connection_write_to_buf() when an entire TLS record is ready.
  1231. *
  1232. * Update conn-\>timestamp_lastwritten to now, and call flush_buf
  1233. * or flush_buf_tls appropriately. If it succeeds and there no more
  1234. * more bytes on conn->outbuf, then call connection_finished_flushing
  1235. * on it too.
  1236. *
  1237. * Mark the connection and return -1 if you want to close it, else
  1238. * return 0.
  1239. */
  1240. int
  1241. connection_handle_write(connection_t *conn)
  1242. {
  1243. int e;
  1244. socklen_t len=sizeof(e);
  1245. int result;
  1246. int max_to_write;
  1247. time_t now = time(NULL);
  1248. tor_assert(!connection_is_listener(conn));
  1249. if (conn->marked_for_close)
  1250. return 0; /* do nothing */
  1251. conn->timestamp_lastwritten = now;
  1252. /* Sometimes, "writable" means "connected". */
  1253. if (connection_state_is_connecting(conn)) {
  1254. if (getsockopt(conn->s, SOL_SOCKET, SO_ERROR, (void*)&e, &len) < 0) {
  1255. warn(LD_BUG,"getsockopt() syscall failed?! Please report to tor-ops.");
  1256. if (CONN_IS_EDGE(conn))
  1257. connection_edge_end_errno(conn, conn->cpath_layer);
  1258. connection_mark_for_close(conn);
  1259. return -1;
  1260. }
  1261. if (e) {
  1262. /* some sort of error, but maybe just inprogress still */
  1263. if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
  1264. info(LD_NET,"in-progress connect failed. Removing.");
  1265. if (CONN_IS_EDGE(conn))
  1266. connection_edge_end_errno(conn, conn->cpath_layer);
  1267. connection_close_immediate(conn);
  1268. connection_mark_for_close(conn);
  1269. /* it's safe to pass OPs to router_mark_as_down(), since it just
  1270. * ignores unrecognized routers
  1271. */
  1272. if (conn->type == CONN_TYPE_OR && !get_options()->HttpsProxy)
  1273. router_mark_as_down(conn->identity_digest);
  1274. return -1;
  1275. } else {
  1276. return 0; /* no change, see if next time is better */
  1277. }
  1278. }
  1279. /* The connection is successful. */
  1280. if (connection_finished_connecting(conn)<0)
  1281. return -1;
  1282. }
  1283. max_to_write = connection_bucket_write_limit(conn);
  1284. if (connection_speaks_cells(conn) &&
  1285. conn->state > OR_CONN_STATE_PROXY_READING) {
  1286. if (conn->state == OR_CONN_STATE_HANDSHAKING) {
  1287. connection_stop_writing(conn);
  1288. if (connection_tls_continue_handshake(conn) < 0) {
  1289. /* Don't flush; connection is dead. */
  1290. connection_close_immediate(conn);
  1291. connection_mark_for_close(conn);
  1292. return -1;
  1293. }
  1294. return 0;
  1295. }
  1296. /* else open, or closing */
  1297. result = flush_buf_tls(conn->tls, conn->outbuf,
  1298. max_to_write, &conn->outbuf_flushlen);
  1299. switch (result) {
  1300. case TOR_TLS_ERROR:
  1301. case TOR_TLS_CLOSE:
  1302. info(LD_NET,result==TOR_TLS_ERROR?
  1303. "tls error. breaking.":"TLS connection closed on flush");
  1304. /* Don't flush; connection is dead. */
  1305. connection_close_immediate(conn);
  1306. connection_mark_for_close(conn);
  1307. return -1;
  1308. case TOR_TLS_WANTWRITE:
  1309. debug(LD_NET,"wanted write.");
  1310. /* we're already writing */
  1311. return 0;
  1312. case TOR_TLS_WANTREAD:
  1313. /* Make sure to avoid a loop if the receive buckets are empty. */
  1314. debug(LD_NET,"wanted read.");
  1315. if (!connection_is_reading(conn)) {
  1316. connection_stop_writing(conn);
  1317. conn->wants_to_write = 1;
  1318. /* we'll start reading again when the next second arrives,
  1319. * and then also start writing again.
  1320. */
  1321. }
  1322. /* else no problem, we're already reading */
  1323. return 0;
  1324. /* case TOR_TLS_DONE:
  1325. * for TOR_TLS_DONE, fall through to check if the flushlen
  1326. * is empty, so we can stop writing.
  1327. */
  1328. }
  1329. } else {
  1330. CONN_LOG_PROTECT(conn,
  1331. result = flush_buf(conn->s, conn->outbuf,
  1332. max_to_write, &conn->outbuf_flushlen));
  1333. if (result < 0) {
  1334. if (CONN_IS_EDGE(conn))
  1335. connection_edge_end_errno(conn, conn->cpath_layer);
  1336. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  1337. connection_mark_for_close(conn);
  1338. return -1;
  1339. }
  1340. }
  1341. if (result > 0 && !is_local_IP(conn->addr)) { /* remember it */
  1342. rep_hist_note_bytes_written(result, now);
  1343. global_write_bucket -= result;
  1344. }
  1345. if (!connection_wants_to_flush(conn)) { /* it's done flushing */
  1346. if (connection_finished_flushing(conn) < 0) {
  1347. /* already marked */
  1348. return -1;
  1349. }
  1350. }
  1351. return 0;
  1352. }
  1353. /* A controller event has just happened with such urgency that we
  1354. * need to write it onto controller <b>conn</b> immediately. */
  1355. void
  1356. _connection_controller_force_write(connection_t *conn)
  1357. {
  1358. /* XXX This is hideous code duplication, but raising it seems a little
  1359. * tricky for now. Think more about this one. We only call it for
  1360. * EVENT_ERR_MSG, so messing with buckets a little isn't such a big problem.
  1361. */
  1362. int result;
  1363. tor_assert(conn);
  1364. tor_assert(!conn->tls);
  1365. tor_assert(conn->type == CONN_TYPE_CONTROL);
  1366. if (conn->marked_for_close || conn->s < 0)
  1367. return;
  1368. CONN_LOG_PROTECT(conn,
  1369. result = flush_buf(conn->s, conn->outbuf,
  1370. conn->outbuf_flushlen, &conn->outbuf_flushlen));
  1371. if (result < 0) {
  1372. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  1373. connection_mark_for_close(conn);
  1374. return;
  1375. }
  1376. if (result > 0 && !is_local_IP(conn->addr)) { /* remember it */
  1377. rep_hist_note_bytes_written(result, time(NULL));
  1378. global_write_bucket -= result;
  1379. }
  1380. if (!connection_wants_to_flush(conn)) { /* it's done flushing */
  1381. if (connection_finished_flushing(conn) < 0) {
  1382. /* already marked */
  1383. return;
  1384. }
  1385. }
  1386. }
  1387. /** Append <b>len</b> bytes of <b>string</b> onto <b>conn</b>'s
  1388. * outbuf, and ask it to start writing.
  1389. */
  1390. void
  1391. connection_write_to_buf(const char *string, size_t len, connection_t *conn)
  1392. {
  1393. int r;
  1394. if (!len)
  1395. return;
  1396. /* if it's marked for close, only allow write if we mean to flush it */
  1397. if (conn->marked_for_close && !conn->hold_open_until_flushed)
  1398. return;
  1399. CONN_LOG_PROTECT(conn, r = write_to_buf(string, len, conn->outbuf));
  1400. if (r < 0) {
  1401. if (CONN_IS_EDGE(conn)) {
  1402. /* if it failed, it means we have our package/delivery windows set
  1403. wrong compared to our max outbuf size. close the whole circuit. */
  1404. warn(LD_NET,"write_to_buf failed. Closing circuit (fd %d).", conn->s);
  1405. circuit_mark_for_close(circuit_get_by_edge_conn(conn),
  1406. END_CIRC_REASON_INTERNAL);
  1407. } else {
  1408. warn(LD_NET,"write_to_buf failed. Closing connection (fd %d).", conn->s);
  1409. connection_mark_for_close(conn);
  1410. }
  1411. return;
  1412. }
  1413. connection_start_writing(conn);
  1414. conn->outbuf_flushlen += len;
  1415. }
  1416. /** Return the conn to addr/port that has the most recent
  1417. * timestamp_created, or NULL if no such conn exists. */
  1418. connection_t *
  1419. connection_or_exact_get_by_addr_port(uint32_t addr, uint16_t port)
  1420. {
  1421. int i, n;
  1422. connection_t *conn, *best=NULL;
  1423. connection_t **carray;
  1424. get_connection_array(&carray,&n);
  1425. for (i=0;i<n;i++) {
  1426. conn = carray[i];
  1427. if (conn->type == CONN_TYPE_OR &&
  1428. conn->addr == addr &&
  1429. conn->port == port &&
  1430. !conn->marked_for_close &&
  1431. (!best || best->timestamp_created < conn->timestamp_created))
  1432. best = conn;
  1433. }
  1434. return best;
  1435. }
  1436. /** Return a connection with given type, address, port, and purpose;
  1437. * or NULL if no such connection exists. */
  1438. connection_t *
  1439. connection_get_by_type_addr_port_purpose(int type,
  1440. uint32_t addr, uint16_t port,
  1441. int purpose)
  1442. {
  1443. int i, n;
  1444. connection_t *conn;
  1445. connection_t **carray;
  1446. get_connection_array(&carray,&n);
  1447. for (i=0;i<n;i++) {
  1448. conn = carray[i];
  1449. if (conn->type == type &&
  1450. conn->addr == addr &&
  1451. conn->port == port &&
  1452. conn->purpose == purpose &&
  1453. !conn->marked_for_close)
  1454. return conn;
  1455. }
  1456. return NULL;
  1457. }
  1458. /** Return the connection with id <b>id</b> if it is not already marked for
  1459. * close.
  1460. */
  1461. connection_t *
  1462. connection_get_by_global_id(uint32_t id)
  1463. {
  1464. int i, n;
  1465. connection_t *conn;
  1466. connection_t **carray;
  1467. get_connection_array(&carray,&n);
  1468. for (i=0;i<n;i++) {
  1469. conn = carray[i];
  1470. if (conn->global_identifier == id) {
  1471. if (!conn->marked_for_close)
  1472. return conn;
  1473. else
  1474. return NULL;
  1475. }
  1476. }
  1477. return NULL;
  1478. }
  1479. /** Return a connection of type <b>type</b> that is not marked for close.
  1480. */
  1481. connection_t *
  1482. connection_get_by_type(int type)
  1483. {
  1484. int i, n;
  1485. connection_t *conn;
  1486. connection_t **carray;
  1487. get_connection_array(&carray,&n);
  1488. for (i=0;i<n;i++) {
  1489. conn = carray[i];
  1490. if (conn->type == type && !conn->marked_for_close)
  1491. return conn;
  1492. }
  1493. return NULL;
  1494. }
  1495. /** Return a connection of type <b>type</b> that is in state <b>state</b>,
  1496. * and that is not marked for close.
  1497. */
  1498. connection_t *
  1499. connection_get_by_type_state(int type, int state)
  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->state == state && !conn->marked_for_close)
  1508. return conn;
  1509. }
  1510. return NULL;
  1511. }
  1512. /** Return the connection of type <b>type</b> that is in state
  1513. * <b>state</b>, that was written to least recently, and that is not
  1514. * marked for close.
  1515. */
  1516. connection_t *
  1517. connection_get_by_type_state_lastwritten(int type, int state)
  1518. {
  1519. int i, n;
  1520. connection_t *conn, *best=NULL;
  1521. connection_t **carray;
  1522. get_connection_array(&carray,&n);
  1523. for (i=0;i<n;i++) {
  1524. conn = carray[i];
  1525. if (conn->type == type && conn->state == state && !conn->marked_for_close)
  1526. if (!best || conn->timestamp_lastwritten < best->timestamp_lastwritten)
  1527. best = conn;
  1528. }
  1529. return best;
  1530. }
  1531. /** Return a connection of type <b>type</b> that has rendquery equal
  1532. * to <b>rendquery</b>, and that is not marked for close. If state
  1533. * is non-zero, conn must be of that state too.
  1534. */
  1535. connection_t *
  1536. connection_get_by_type_state_rendquery(int type, int state,
  1537. const char *rendquery)
  1538. {
  1539. int i, n;
  1540. connection_t *conn;
  1541. connection_t **carray;
  1542. get_connection_array(&carray,&n);
  1543. for (i=0;i<n;i++) {
  1544. conn = carray[i];
  1545. if (conn->type == type &&
  1546. !conn->marked_for_close &&
  1547. (!state || state == conn->state) &&
  1548. !rend_cmp_service_ids(rendquery, conn->rend_query))
  1549. return conn;
  1550. }
  1551. return NULL;
  1552. }
  1553. /** Return an open, non-marked connection of a given type and purpose, or NULL
  1554. * if no such connection exists. */
  1555. connection_t *
  1556. connection_get_by_type_purpose(int type, int purpose)
  1557. {
  1558. int i, n;
  1559. connection_t *conn;
  1560. connection_t **carray;
  1561. get_connection_array(&carray,&n);
  1562. for (i=0;i<n;i++) {
  1563. conn = carray[i];
  1564. if (conn->type == type &&
  1565. !conn->marked_for_close &&
  1566. (purpose == conn->purpose))
  1567. return conn;
  1568. }
  1569. return NULL;
  1570. }
  1571. /** Return 1 if <b>conn</b> is a listener conn, else return 0. */
  1572. int
  1573. connection_is_listener(connection_t *conn)
  1574. {
  1575. if (conn->type == CONN_TYPE_OR_LISTENER ||
  1576. conn->type == CONN_TYPE_AP_LISTENER ||
  1577. conn->type == CONN_TYPE_DIR_LISTENER ||
  1578. conn->type == CONN_TYPE_CONTROL_LISTENER)
  1579. return 1;
  1580. return 0;
  1581. }
  1582. /** Return 1 if <b>conn</b> is in state "open" and is not marked
  1583. * for close, else return 0.
  1584. */
  1585. int
  1586. connection_state_is_open(connection_t *conn)
  1587. {
  1588. tor_assert(conn);
  1589. if (conn->marked_for_close)
  1590. return 0;
  1591. if ((conn->type == CONN_TYPE_OR && conn->state == OR_CONN_STATE_OPEN) ||
  1592. (conn->type == CONN_TYPE_AP && conn->state == AP_CONN_STATE_OPEN) ||
  1593. (conn->type == CONN_TYPE_EXIT && conn->state == EXIT_CONN_STATE_OPEN) ||
  1594. (conn->type == CONN_TYPE_CONTROL &&
  1595. (conn->state == CONTROL_CONN_STATE_OPEN_V0 ||
  1596. conn->state == CONTROL_CONN_STATE_OPEN_V1)))
  1597. return 1;
  1598. return 0;
  1599. }
  1600. /** Return 1 if conn is in 'connecting' state, else return 0. */
  1601. int
  1602. connection_state_is_connecting(connection_t *conn)
  1603. {
  1604. tor_assert(conn);
  1605. if (conn->marked_for_close)
  1606. return 0;
  1607. switch (conn->type)
  1608. {
  1609. case CONN_TYPE_OR:
  1610. return conn->state == OR_CONN_STATE_CONNECTING;
  1611. case CONN_TYPE_EXIT:
  1612. return conn->state == EXIT_CONN_STATE_CONNECTING;
  1613. case CONN_TYPE_DIR:
  1614. return conn->state == DIR_CONN_STATE_CONNECTING;
  1615. }
  1616. return 0;
  1617. }
  1618. /** Alloocates a base64'ed authenticator for use in http or https
  1619. * auth, based on the input string <b>authenticator</b>. Returns it
  1620. * if success, else returns NULL. */
  1621. char *
  1622. alloc_http_authenticator(const char *authenticator)
  1623. {
  1624. /* an authenticator in Basic authentication
  1625. * is just the string "username:password" */
  1626. const int authenticator_length = strlen(authenticator);
  1627. /* The base64_encode function needs a minimum buffer length
  1628. * of 66 bytes. */
  1629. const int base64_authenticator_length = (authenticator_length/48+1)*66;
  1630. char *base64_authenticator = tor_malloc(base64_authenticator_length);
  1631. if (base64_encode(base64_authenticator, base64_authenticator_length,
  1632. authenticator, authenticator_length) < 0) {
  1633. tor_free(base64_authenticator); /* free and set to null */
  1634. } else {
  1635. /* remove extra \n at end of encoding */
  1636. base64_authenticator[strlen(base64_authenticator) - 1] = 0;
  1637. }
  1638. return base64_authenticator;
  1639. }
  1640. /** Given a socket handle, check whether the local address (sockname) of the
  1641. * socket is one that we've connected from before. If so, double-check
  1642. * whether our address has changed and we need to generate keys. If we do,
  1643. * call init_keys().
  1644. */
  1645. /* XXXX Handle IPv6, eventually. */
  1646. static void
  1647. client_check_address_changed(int sock)
  1648. {
  1649. uint32_t iface_ip, ip_out;
  1650. struct sockaddr_in out_addr;
  1651. socklen_t out_addr_len = sizeof(out_addr);
  1652. uint32_t *ip;
  1653. if (!last_interface_ip)
  1654. get_interface_address(&last_interface_ip);
  1655. if (!outgoing_addrs)
  1656. outgoing_addrs = smartlist_create();
  1657. if (getsockname(sock, (struct sockaddr*)&out_addr, &out_addr_len)<0) {
  1658. int e = tor_socket_errno(sock);
  1659. warn(LD_NET, "getsockname() failed: %s", tor_socket_strerror(e));
  1660. return;
  1661. }
  1662. /* Okay. If we've used this address previously, we're okay. */
  1663. ip_out = ntohl(out_addr.sin_addr.s_addr);
  1664. SMARTLIST_FOREACH(outgoing_addrs, uint32_t*, ip,
  1665. if (*ip == ip_out) return;
  1666. );
  1667. /* Uh-oh. We haven't connected from this address before. Has the interface
  1668. * address changed? */
  1669. if (get_interface_address(&iface_ip)<0)
  1670. return;
  1671. ip = tor_malloc(sizeof(uint32_t));
  1672. *ip = ip_out;
  1673. if (iface_ip == last_interface_ip) {
  1674. /* Nope, it hasn't changed. Add this address to the list. */
  1675. smartlist_add(outgoing_addrs, ip);
  1676. } else {
  1677. /* The interface changed. We're a client, so we need to regenerate our
  1678. * keys. First, reset the state. */
  1679. log(LOG_NOTICE, LD_NET, "Our IP has changed. Rotating keys...");
  1680. last_interface_ip = iface_ip;
  1681. SMARTLIST_FOREACH(outgoing_addrs, void*, ip, tor_free(ip));
  1682. smartlist_clear(outgoing_addrs);
  1683. smartlist_add(outgoing_addrs, ip);
  1684. /* Okay, now change our keys. */
  1685. init_keys(); /* XXXX NM return value-- safe to ignore? */
  1686. }
  1687. }
  1688. /** Process new bytes that have arrived on conn-\>inbuf.
  1689. *
  1690. * This function just passes conn to the connection-specific
  1691. * connection_*_process_inbuf() function. It also passes in
  1692. * package_partial if wanted.
  1693. */
  1694. static int
  1695. connection_process_inbuf(connection_t *conn, int package_partial)
  1696. {
  1697. tor_assert(conn);
  1698. switch (conn->type) {
  1699. case CONN_TYPE_OR:
  1700. return connection_or_process_inbuf(conn);
  1701. case CONN_TYPE_EXIT:
  1702. case CONN_TYPE_AP:
  1703. return connection_edge_process_inbuf(conn, package_partial);
  1704. case CONN_TYPE_DIR:
  1705. return connection_dir_process_inbuf(conn);
  1706. case CONN_TYPE_DNSWORKER:
  1707. return connection_dns_process_inbuf(conn);
  1708. case CONN_TYPE_CPUWORKER:
  1709. return connection_cpu_process_inbuf(conn);
  1710. case CONN_TYPE_CONTROL:
  1711. return connection_control_process_inbuf(conn);
  1712. default:
  1713. err(LD_BUG,"Bug: got unexpected conn type %d.", conn->type);
  1714. tor_fragile_assert();
  1715. return -1;
  1716. }
  1717. }
  1718. /** We just finished flushing bytes from conn-\>outbuf, and there
  1719. * are no more bytes remaining.
  1720. *
  1721. * This function just passes conn to the connection-specific
  1722. * connection_*_finished_flushing() function.
  1723. */
  1724. static int
  1725. connection_finished_flushing(connection_t *conn)
  1726. {
  1727. tor_assert(conn);
  1728. // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
  1729. switch (conn->type) {
  1730. case CONN_TYPE_OR:
  1731. return connection_or_finished_flushing(conn);
  1732. case CONN_TYPE_AP:
  1733. case CONN_TYPE_EXIT:
  1734. return connection_edge_finished_flushing(conn);
  1735. case CONN_TYPE_DIR:
  1736. return connection_dir_finished_flushing(conn);
  1737. case CONN_TYPE_DNSWORKER:
  1738. return connection_dns_finished_flushing(conn);
  1739. case CONN_TYPE_CPUWORKER:
  1740. return connection_cpu_finished_flushing(conn);
  1741. case CONN_TYPE_CONTROL:
  1742. return connection_control_finished_flushing(conn);
  1743. default:
  1744. err(LD_BUG,"Bug: got unexpected conn type %d.", conn->type);
  1745. tor_fragile_assert();
  1746. return -1;
  1747. }
  1748. }
  1749. /** Called when our attempt to connect() to another server has just
  1750. * succeeded.
  1751. *
  1752. * This function just passes conn to the connection-specific
  1753. * connection_*_finished_connecting() function.
  1754. */
  1755. static int
  1756. connection_finished_connecting(connection_t *conn)
  1757. {
  1758. tor_assert(conn);
  1759. switch (conn->type)
  1760. {
  1761. case CONN_TYPE_OR:
  1762. return connection_or_finished_connecting(conn);
  1763. case CONN_TYPE_EXIT:
  1764. return connection_edge_finished_connecting(conn);
  1765. case CONN_TYPE_DIR:
  1766. return connection_dir_finished_connecting(conn);
  1767. default:
  1768. err(LD_BUG,"Bug: got unexpected conn type %d.", conn->type);
  1769. tor_fragile_assert();
  1770. return -1;
  1771. }
  1772. }
  1773. /** Callback: invoked when a connection reaches an EOF event. */
  1774. static int
  1775. connection_reached_eof(connection_t *conn)
  1776. {
  1777. switch (conn->type) {
  1778. case CONN_TYPE_OR:
  1779. return connection_or_reached_eof(conn);
  1780. case CONN_TYPE_AP:
  1781. case CONN_TYPE_EXIT:
  1782. return connection_edge_reached_eof(conn);
  1783. case CONN_TYPE_DIR:
  1784. return connection_dir_reached_eof(conn);
  1785. case CONN_TYPE_DNSWORKER:
  1786. return connection_dns_reached_eof(conn);
  1787. case CONN_TYPE_CPUWORKER:
  1788. return connection_cpu_reached_eof(conn);
  1789. case CONN_TYPE_CONTROL:
  1790. return connection_control_reached_eof(conn);
  1791. default:
  1792. err(LD_BUG,"Bug: got unexpected conn type %d.", conn->type);
  1793. tor_fragile_assert();
  1794. return -1;
  1795. }
  1796. }
  1797. /** Verify that connection <b>conn</b> has all of its invariants
  1798. * correct. Trigger an assert if anything is invalid.
  1799. */
  1800. void
  1801. assert_connection_ok(connection_t *conn, time_t now)
  1802. {
  1803. tor_assert(conn);
  1804. tor_assert(conn->magic == CONNECTION_MAGIC);
  1805. tor_assert(conn->type >= _CONN_TYPE_MIN);
  1806. tor_assert(conn->type <= _CONN_TYPE_MAX);
  1807. if (conn->outbuf_flushlen > 0) {
  1808. tor_assert(connection_is_writing(conn) || conn->wants_to_write);
  1809. }
  1810. if (conn->hold_open_until_flushed)
  1811. tor_assert(conn->marked_for_close);
  1812. /* XXX check: wants_to_read, wants_to_write, s, poll_index,
  1813. * marked_for_close. */
  1814. /* buffers */
  1815. if (!connection_is_listener(conn)) {
  1816. assert_buf_ok(conn->inbuf);
  1817. assert_buf_ok(conn->outbuf);
  1818. }
  1819. /* XXX Fix this; no longer so.*/
  1820. #if 0
  1821. if (conn->type != CONN_TYPE_OR && conn->type != CONN_TYPE_DIR)
  1822. tor_assert(!conn->pkey);
  1823. /* pkey is set if we're a dir client, or if we're an OR in state OPEN
  1824. * connected to another OR.
  1825. */
  1826. #endif
  1827. if (conn->type != CONN_TYPE_OR) {
  1828. tor_assert(!conn->tls);
  1829. } else {
  1830. if (conn->state == OR_CONN_STATE_OPEN) {
  1831. /* tor_assert(conn->bandwidth > 0); */
  1832. /* the above isn't necessarily true: if we just did a TLS
  1833. * handshake but we didn't recognize the other peer, or it
  1834. * gave a bad cert/etc, then we won't have assigned bandwidth,
  1835. * yet it will be open. -RD
  1836. */
  1837. // tor_assert(conn->receiver_bucket >= 0);
  1838. }
  1839. // tor_assert(conn->addr && conn->port);
  1840. tor_assert(conn->address);
  1841. if (conn->state > OR_CONN_STATE_PROXY_READING)
  1842. tor_assert(conn->tls);
  1843. }
  1844. if (! CONN_IS_EDGE(conn)) {
  1845. tor_assert(!conn->stream_id);
  1846. tor_assert(!conn->next_stream);
  1847. tor_assert(!conn->cpath_layer);
  1848. tor_assert(!conn->package_window);
  1849. tor_assert(!conn->deliver_window);
  1850. #if 0
  1851. tor_assert(!conn->done_sending);
  1852. tor_assert(!conn->done_receiving);
  1853. #endif
  1854. } else {
  1855. /* XXX unchecked: package window, deliver window. */
  1856. }
  1857. if (conn->type == CONN_TYPE_AP) {
  1858. tor_assert(conn->socks_request);
  1859. if (conn->state == AP_CONN_STATE_OPEN) {
  1860. tor_assert(conn->socks_request->has_finished);
  1861. if (!conn->marked_for_close) {
  1862. tor_assert(conn->cpath_layer);
  1863. assert_cpath_layer_ok(conn->cpath_layer);
  1864. }
  1865. }
  1866. } else {
  1867. tor_assert(!conn->socks_request);
  1868. }
  1869. if (conn->type == CONN_TYPE_EXIT) {
  1870. tor_assert(conn->purpose == EXIT_PURPOSE_CONNECT ||
  1871. conn->purpose == EXIT_PURPOSE_RESOLVE);
  1872. } else if (conn->type != CONN_TYPE_DIR) {
  1873. tor_assert(!conn->purpose); /* only used for dir types currently */
  1874. }
  1875. if (conn->type != CONN_TYPE_DIR) {
  1876. tor_assert(!conn->requested_resource);
  1877. }
  1878. switch (conn->type)
  1879. {
  1880. case CONN_TYPE_OR_LISTENER:
  1881. case CONN_TYPE_AP_LISTENER:
  1882. case CONN_TYPE_DIR_LISTENER:
  1883. case CONN_TYPE_CONTROL_LISTENER:
  1884. tor_assert(conn->state == LISTENER_STATE_READY);
  1885. break;
  1886. case CONN_TYPE_OR:
  1887. tor_assert(conn->state >= _OR_CONN_STATE_MIN);
  1888. tor_assert(conn->state <= _OR_CONN_STATE_MAX);
  1889. tor_assert(conn->n_circuits >= 0);
  1890. break;
  1891. case CONN_TYPE_EXIT:
  1892. tor_assert(conn->state >= _EXIT_CONN_STATE_MIN);
  1893. tor_assert(conn->state <= _EXIT_CONN_STATE_MAX);
  1894. break;
  1895. case CONN_TYPE_AP:
  1896. tor_assert(conn->state >= _AP_CONN_STATE_MIN);
  1897. tor_assert(conn->state <= _AP_CONN_STATE_MAX);
  1898. tor_assert(conn->socks_request);
  1899. break;
  1900. case CONN_TYPE_DIR:
  1901. tor_assert(conn->state >= _DIR_CONN_STATE_MIN);
  1902. tor_assert(conn->state <= _DIR_CONN_STATE_MAX);
  1903. tor_assert(conn->purpose >= _DIR_PURPOSE_MIN);
  1904. tor_assert(conn->purpose <= _DIR_PURPOSE_MAX);
  1905. break;
  1906. case CONN_TYPE_DNSWORKER:
  1907. tor_assert(conn->state == DNSWORKER_STATE_IDLE ||
  1908. conn->state == DNSWORKER_STATE_BUSY);
  1909. break;
  1910. case CONN_TYPE_CPUWORKER:
  1911. tor_assert(conn->state >= _CPUWORKER_STATE_MIN);
  1912. tor_assert(conn->state <= _CPUWORKER_STATE_MAX);
  1913. break;
  1914. case CONN_TYPE_CONTROL:
  1915. tor_assert(conn->state >= _CONTROL_CONN_STATE_MIN);
  1916. tor_assert(conn->state <= _CONTROL_CONN_STATE_MAX);
  1917. break;
  1918. default:
  1919. tor_assert(0);
  1920. }
  1921. }