connection.c 65 KB

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