connection.c 82 KB

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