connection.c 76 KB

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