connection.c 82 KB

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