connection.c 65 KB

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