connection.c 79 KB

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