connection.c 79 KB

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