connection.c 120 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2011, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file connection.c
  8. * \brief General high-level functions to handle reading and writing
  9. * on connections.
  10. **/
  11. #include "or.h"
  12. #include "buffers.h"
  13. #include "circuitbuild.h"
  14. #include "circuitlist.h"
  15. #include "circuituse.h"
  16. #include "config.h"
  17. #include "connection.h"
  18. #include "connection_edge.h"
  19. #include "connection_or.h"
  20. #include "control.h"
  21. #include "cpuworker.h"
  22. #include "directory.h"
  23. #include "dirserv.h"
  24. #include "dns.h"
  25. #include "dnsserv.h"
  26. #include "geoip.h"
  27. #include "main.h"
  28. #include "policies.h"
  29. #include "reasons.h"
  30. #include "relay.h"
  31. #include "rendclient.h"
  32. #include "rendcommon.h"
  33. #include "rephist.h"
  34. #include "router.h"
  35. #include "routerparse.h"
  36. static connection_t *connection_create_listener(
  37. const struct sockaddr *listensockaddr,
  38. socklen_t listensocklen, int type,
  39. char* address);
  40. static void connection_init(time_t now, connection_t *conn, int type,
  41. int socket_family);
  42. static int connection_init_accepted_conn(connection_t *conn,
  43. uint8_t listener_type);
  44. static int connection_handle_listener_read(connection_t *conn, int new_type);
  45. static int connection_bucket_should_increase(int bucket,
  46. or_connection_t *conn);
  47. static int connection_finished_flushing(connection_t *conn);
  48. static int connection_flushed_some(connection_t *conn);
  49. static int connection_finished_connecting(connection_t *conn);
  50. static int connection_reached_eof(connection_t *conn);
  51. static int connection_read_to_buf(connection_t *conn, ssize_t *max_to_read,
  52. int *socket_error);
  53. static int connection_process_inbuf(connection_t *conn, int package_partial);
  54. static void client_check_address_changed(int sock);
  55. static void set_constrained_socket_buffers(int sock, int size);
  56. static const char *connection_proxy_state_to_string(int state);
  57. static int connection_read_https_proxy_response(connection_t *conn);
  58. static void connection_send_socks5_connect(connection_t *conn);
  59. /** The last IPv4 address that our network interface seemed to have been
  60. * binding to, in host order. We use this to detect when our IP changes. */
  61. static uint32_t last_interface_ip = 0;
  62. /** A list of uint32_ts for addresses we've used in outgoing connections.
  63. * Used to detect IP address changes. */
  64. static smartlist_t *outgoing_addrs = NULL;
  65. /**************************************************************/
  66. /**
  67. * Return the human-readable name for the connection type <b>type</b>
  68. */
  69. const char *
  70. conn_type_to_string(int type)
  71. {
  72. static char buf[64];
  73. switch (type) {
  74. case CONN_TYPE_OR_LISTENER: return "OR listener";
  75. case CONN_TYPE_OR: return "OR";
  76. case CONN_TYPE_EXIT: return "Exit";
  77. case CONN_TYPE_AP_LISTENER: return "Socks listener";
  78. case CONN_TYPE_AP_TRANS_LISTENER:
  79. return "Transparent pf/netfilter listener";
  80. case CONN_TYPE_AP_NATD_LISTENER: return "Transparent natd listener";
  81. case CONN_TYPE_AP_DNS_LISTENER: return "DNS listener";
  82. case CONN_TYPE_AP: return "Socks";
  83. case CONN_TYPE_DIR_LISTENER: return "Directory listener";
  84. case CONN_TYPE_DIR: return "Directory";
  85. case CONN_TYPE_CPUWORKER: return "CPU worker";
  86. case CONN_TYPE_CONTROL_LISTENER: return "Control listener";
  87. case CONN_TYPE_CONTROL: return "Control";
  88. default:
  89. log_warn(LD_BUG, "unknown connection type %d", type);
  90. tor_snprintf(buf, sizeof(buf), "unknown [%d]", type);
  91. return buf;
  92. }
  93. }
  94. /**
  95. * Return the human-readable name for the connection state <b>state</b>
  96. * for the connection type <b>type</b>
  97. */
  98. const char *
  99. conn_state_to_string(int type, int state)
  100. {
  101. static char buf[96];
  102. switch (type) {
  103. case CONN_TYPE_OR_LISTENER:
  104. case CONN_TYPE_AP_LISTENER:
  105. case CONN_TYPE_AP_TRANS_LISTENER:
  106. case CONN_TYPE_AP_NATD_LISTENER:
  107. case CONN_TYPE_AP_DNS_LISTENER:
  108. case CONN_TYPE_DIR_LISTENER:
  109. case CONN_TYPE_CONTROL_LISTENER:
  110. if (state == LISTENER_STATE_READY)
  111. return "ready";
  112. break;
  113. case CONN_TYPE_OR:
  114. switch (state) {
  115. case OR_CONN_STATE_CONNECTING: return "connect()ing";
  116. case OR_CONN_STATE_PROXY_HANDSHAKING: return "handshaking (proxy)";
  117. case OR_CONN_STATE_TLS_HANDSHAKING: return "handshaking (TLS)";
  118. case OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING:
  119. return "renegotiating (TLS)";
  120. case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING:
  121. return "waiting for renegotiation (TLS)";
  122. case OR_CONN_STATE_OR_HANDSHAKING: return "handshaking (Tor)";
  123. case OR_CONN_STATE_OPEN: return "open";
  124. }
  125. break;
  126. case CONN_TYPE_EXIT:
  127. switch (state) {
  128. case EXIT_CONN_STATE_RESOLVING: return "waiting for dest info";
  129. case EXIT_CONN_STATE_CONNECTING: return "connecting";
  130. case EXIT_CONN_STATE_OPEN: return "open";
  131. case EXIT_CONN_STATE_RESOLVEFAILED: return "resolve failed";
  132. }
  133. break;
  134. case CONN_TYPE_AP:
  135. switch (state) {
  136. case AP_CONN_STATE_SOCKS_WAIT: return "waiting for socks info";
  137. case AP_CONN_STATE_NATD_WAIT: return "waiting for natd dest info";
  138. case AP_CONN_STATE_RENDDESC_WAIT: return "waiting for rendezvous desc";
  139. case AP_CONN_STATE_CONTROLLER_WAIT: return "waiting for controller";
  140. case AP_CONN_STATE_CIRCUIT_WAIT: return "waiting for circuit";
  141. case AP_CONN_STATE_CONNECT_WAIT: return "waiting for connect response";
  142. case AP_CONN_STATE_RESOLVE_WAIT: return "waiting for resolve response";
  143. case AP_CONN_STATE_OPEN: return "open";
  144. }
  145. break;
  146. case CONN_TYPE_DIR:
  147. switch (state) {
  148. case DIR_CONN_STATE_CONNECTING: return "connecting";
  149. case DIR_CONN_STATE_CLIENT_SENDING: return "client sending";
  150. case DIR_CONN_STATE_CLIENT_READING: return "client reading";
  151. case DIR_CONN_STATE_CLIENT_FINISHED: return "client finished";
  152. case DIR_CONN_STATE_SERVER_COMMAND_WAIT: return "waiting for command";
  153. case DIR_CONN_STATE_SERVER_WRITING: return "writing";
  154. }
  155. break;
  156. case CONN_TYPE_CPUWORKER:
  157. switch (state) {
  158. case CPUWORKER_STATE_IDLE: return "idle";
  159. case CPUWORKER_STATE_BUSY_ONION: return "busy with onion";
  160. }
  161. break;
  162. case CONN_TYPE_CONTROL:
  163. switch (state) {
  164. case CONTROL_CONN_STATE_OPEN: return "open (protocol v1)";
  165. case CONTROL_CONN_STATE_NEEDAUTH:
  166. return "waiting for authentication (protocol v1)";
  167. }
  168. break;
  169. }
  170. log_warn(LD_BUG, "unknown connection state %d (type %d)", state, type);
  171. tor_snprintf(buf, sizeof(buf),
  172. "unknown state [%d] on unknown [%s] connection",
  173. state, conn_type_to_string(type));
  174. return buf;
  175. }
  176. /** Allocate and return a new dir_connection_t, initialized as by
  177. * connection_init(). */
  178. dir_connection_t *
  179. dir_connection_new(int socket_family)
  180. {
  181. dir_connection_t *dir_conn = tor_malloc_zero(sizeof(dir_connection_t));
  182. connection_init(time(NULL), TO_CONN(dir_conn), CONN_TYPE_DIR, socket_family);
  183. return dir_conn;
  184. }
  185. /** Allocate and return a new or_connection_t, initialized as by
  186. * connection_init(). */
  187. or_connection_t *
  188. or_connection_new(int socket_family)
  189. {
  190. or_connection_t *or_conn = tor_malloc_zero(sizeof(or_connection_t));
  191. time_t now = time(NULL);
  192. connection_init(now, TO_CONN(or_conn), CONN_TYPE_OR, socket_family);
  193. or_conn->timestamp_last_added_nonpadding = time(NULL);
  194. or_conn->next_circ_id = crypto_rand_int(1<<15);
  195. or_conn->active_circuit_pqueue = smartlist_create();
  196. or_conn->active_circuit_pqueue_last_recalibrated = cell_ewma_get_tick();
  197. return or_conn;
  198. }
  199. /** Allocate and return a new edge_connection_t, initialized as by
  200. * connection_init(). */
  201. edge_connection_t *
  202. edge_connection_new(int type, int socket_family)
  203. {
  204. edge_connection_t *edge_conn = tor_malloc_zero(sizeof(edge_connection_t));
  205. tor_assert(type == CONN_TYPE_EXIT || type == CONN_TYPE_AP);
  206. connection_init(time(NULL), TO_CONN(edge_conn), type, socket_family);
  207. if (type == CONN_TYPE_AP)
  208. edge_conn->socks_request = tor_malloc_zero(sizeof(socks_request_t));
  209. return edge_conn;
  210. }
  211. /** Allocate and return a new control_connection_t, initialized as by
  212. * connection_init(). */
  213. control_connection_t *
  214. control_connection_new(int socket_family)
  215. {
  216. control_connection_t *control_conn =
  217. tor_malloc_zero(sizeof(control_connection_t));
  218. connection_init(time(NULL),
  219. TO_CONN(control_conn), CONN_TYPE_CONTROL, socket_family);
  220. log_notice(LD_CONTROL, "New control connection opened.");
  221. return control_conn;
  222. }
  223. /** Allocate, initialize, and return a new connection_t subtype of <b>type</b>
  224. * to make or receive connections of address family <b>socket_family</b>. The
  225. * type should be one of the CONN_TYPE_* constants. */
  226. connection_t *
  227. connection_new(int type, int socket_family)
  228. {
  229. switch (type) {
  230. case CONN_TYPE_OR:
  231. return TO_CONN(or_connection_new(socket_family));
  232. case CONN_TYPE_EXIT:
  233. case CONN_TYPE_AP:
  234. return TO_CONN(edge_connection_new(type, socket_family));
  235. case CONN_TYPE_DIR:
  236. return TO_CONN(dir_connection_new(socket_family));
  237. case CONN_TYPE_CONTROL:
  238. return TO_CONN(control_connection_new(socket_family));
  239. default: {
  240. connection_t *conn = tor_malloc_zero(sizeof(connection_t));
  241. connection_init(time(NULL), conn, type, socket_family);
  242. return conn;
  243. }
  244. }
  245. }
  246. /** Initializes conn. (you must call connection_add() to link it into the main
  247. * array).
  248. *
  249. * Set conn-\>type to <b>type</b>. Set conn-\>s and conn-\>conn_array_index to
  250. * -1 to signify they are not yet assigned.
  251. *
  252. * If conn is not a listener type, allocate buffers for it. If it's
  253. * an AP type, allocate space to store the socks_request.
  254. *
  255. * Assign a pseudorandom next_circ_id between 0 and 2**15.
  256. *
  257. * Initialize conn's timestamps to now.
  258. */
  259. static void
  260. connection_init(time_t now, connection_t *conn, int type, int socket_family)
  261. {
  262. static uint64_t n_connections_allocated = 1;
  263. switch (type) {
  264. case CONN_TYPE_OR:
  265. conn->magic = OR_CONNECTION_MAGIC;
  266. break;
  267. case CONN_TYPE_EXIT:
  268. case CONN_TYPE_AP:
  269. conn->magic = EDGE_CONNECTION_MAGIC;
  270. break;
  271. case CONN_TYPE_DIR:
  272. conn->magic = DIR_CONNECTION_MAGIC;
  273. break;
  274. case CONN_TYPE_CONTROL:
  275. conn->magic = CONTROL_CONNECTION_MAGIC;
  276. break;
  277. default:
  278. conn->magic = BASE_CONNECTION_MAGIC;
  279. break;
  280. }
  281. conn->s = -1; /* give it a default of 'not used' */
  282. conn->conn_array_index = -1; /* also default to 'not used' */
  283. conn->global_identifier = n_connections_allocated++;
  284. conn->type = type;
  285. conn->socket_family = socket_family;
  286. if (!connection_is_listener(conn)) { /* listeners never use their buf */
  287. conn->inbuf = buf_new();
  288. conn->outbuf = buf_new();
  289. }
  290. conn->timestamp_created = now;
  291. conn->timestamp_lastread = now;
  292. conn->timestamp_lastwritten = now;
  293. }
  294. /** Create a link between <b>conn_a</b> and <b>conn_b</b>. */
  295. void
  296. connection_link_connections(connection_t *conn_a, connection_t *conn_b)
  297. {
  298. tor_assert(conn_a->s < 0);
  299. tor_assert(conn_b->s < 0);
  300. conn_a->linked = 1;
  301. conn_b->linked = 1;
  302. conn_a->linked_conn = conn_b;
  303. conn_b->linked_conn = conn_a;
  304. }
  305. /** Deallocate memory used by <b>conn</b>. Deallocate its buffers if
  306. * necessary, close its socket if necessary, and mark the directory as dirty
  307. * if <b>conn</b> is an OR or OP connection.
  308. */
  309. static void
  310. _connection_free(connection_t *conn)
  311. {
  312. void *mem;
  313. size_t memlen;
  314. if (!conn)
  315. return;
  316. switch (conn->type) {
  317. case CONN_TYPE_OR:
  318. tor_assert(conn->magic == OR_CONNECTION_MAGIC);
  319. mem = TO_OR_CONN(conn);
  320. memlen = sizeof(or_connection_t);
  321. break;
  322. case CONN_TYPE_AP:
  323. case CONN_TYPE_EXIT:
  324. tor_assert(conn->magic == EDGE_CONNECTION_MAGIC);
  325. mem = TO_EDGE_CONN(conn);
  326. memlen = sizeof(edge_connection_t);
  327. break;
  328. case CONN_TYPE_DIR:
  329. tor_assert(conn->magic == DIR_CONNECTION_MAGIC);
  330. mem = TO_DIR_CONN(conn);
  331. memlen = sizeof(dir_connection_t);
  332. break;
  333. case CONN_TYPE_CONTROL:
  334. tor_assert(conn->magic == CONTROL_CONNECTION_MAGIC);
  335. mem = TO_CONTROL_CONN(conn);
  336. memlen = sizeof(control_connection_t);
  337. break;
  338. default:
  339. tor_assert(conn->magic == BASE_CONNECTION_MAGIC);
  340. mem = conn;
  341. memlen = sizeof(connection_t);
  342. break;
  343. }
  344. if (conn->linked) {
  345. log_info(LD_GENERAL, "Freeing linked %s connection [%s] with %d "
  346. "bytes on inbuf, %d on outbuf.",
  347. conn_type_to_string(conn->type),
  348. conn_state_to_string(conn->type, conn->state),
  349. (int)buf_datalen(conn->inbuf), (int)buf_datalen(conn->outbuf));
  350. }
  351. if (!connection_is_listener(conn)) {
  352. buf_free(conn->inbuf);
  353. buf_free(conn->outbuf);
  354. } else {
  355. if (conn->socket_family == AF_UNIX) {
  356. /* For now only control ports can be Unix domain sockets
  357. * and listeners at the same time */
  358. tor_assert(conn->type == CONN_TYPE_CONTROL_LISTENER);
  359. if (unlink(conn->address) < 0 && errno != ENOENT) {
  360. log_warn(LD_NET, "Could not unlink %s: %s", conn->address,
  361. strerror(errno));
  362. }
  363. }
  364. }
  365. tor_free(conn->address);
  366. if (connection_speaks_cells(conn)) {
  367. or_connection_t *or_conn = TO_OR_CONN(conn);
  368. tor_tls_free(or_conn->tls);
  369. or_conn->tls = NULL;
  370. or_handshake_state_free(or_conn->handshake_state);
  371. or_conn->handshake_state = NULL;
  372. smartlist_free(or_conn->active_circuit_pqueue);
  373. tor_free(or_conn->nickname);
  374. }
  375. if (CONN_IS_EDGE(conn)) {
  376. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  377. tor_free(edge_conn->chosen_exit_name);
  378. if (edge_conn->socks_request) {
  379. memset(edge_conn->socks_request, 0xcc, sizeof(socks_request_t));
  380. tor_free(edge_conn->socks_request);
  381. }
  382. rend_data_free(edge_conn->rend_data);
  383. }
  384. if (conn->type == CONN_TYPE_CONTROL) {
  385. control_connection_t *control_conn = TO_CONTROL_CONN(conn);
  386. tor_free(control_conn->incoming_cmd);
  387. }
  388. tor_free(conn->read_event); /* Probably already freed by connection_free. */
  389. tor_free(conn->write_event); /* Probably already freed by connection_free. */
  390. if (conn->type == CONN_TYPE_DIR) {
  391. dir_connection_t *dir_conn = TO_DIR_CONN(conn);
  392. tor_free(dir_conn->requested_resource);
  393. tor_zlib_free(dir_conn->zlib_state);
  394. if (dir_conn->fingerprint_stack) {
  395. SMARTLIST_FOREACH(dir_conn->fingerprint_stack, char *, cp, tor_free(cp));
  396. smartlist_free(dir_conn->fingerprint_stack);
  397. }
  398. cached_dir_decref(dir_conn->cached_dir);
  399. rend_data_free(dir_conn->rend_data);
  400. }
  401. if (conn->s >= 0) {
  402. log_debug(LD_NET,"closing fd %d.",conn->s);
  403. tor_close_socket(conn->s);
  404. conn->s = -1;
  405. }
  406. if (conn->type == CONN_TYPE_OR &&
  407. !tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest)) {
  408. log_warn(LD_BUG, "called on OR conn with non-zeroed identity_digest");
  409. connection_or_remove_from_identity_map(TO_OR_CONN(conn));
  410. }
  411. memset(mem, 0xCC, memlen); /* poison memory */
  412. tor_free(mem);
  413. }
  414. /** Make sure <b>conn</b> isn't in any of the global conn lists; then free it.
  415. */
  416. void
  417. connection_free(connection_t *conn)
  418. {
  419. if (!conn)
  420. return;
  421. tor_assert(!connection_is_on_closeable_list(conn));
  422. tor_assert(!connection_in_array(conn));
  423. if (conn->linked_conn) {
  424. log_err(LD_BUG, "Called with conn->linked_conn still set.");
  425. tor_fragile_assert();
  426. conn->linked_conn->linked_conn = NULL;
  427. if (! conn->linked_conn->marked_for_close &&
  428. conn->linked_conn->reading_from_linked_conn)
  429. connection_start_reading(conn->linked_conn);
  430. conn->linked_conn = NULL;
  431. }
  432. if (connection_speaks_cells(conn)) {
  433. if (!tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest)) {
  434. connection_or_remove_from_identity_map(TO_OR_CONN(conn));
  435. }
  436. }
  437. if (conn->type == CONN_TYPE_CONTROL) {
  438. TO_CONTROL_CONN(conn)->event_mask = 0;
  439. control_update_global_event_mask();
  440. }
  441. connection_unregister_events(conn);
  442. _connection_free(conn);
  443. }
  444. /** Call _connection_free() on every connection in our array, and release all
  445. * storage held by connection.c. This is used by cpuworkers and dnsworkers
  446. * when they fork, so they don't keep resources held open (especially
  447. * sockets).
  448. *
  449. * Don't do the checks in connection_free(), because they will
  450. * fail.
  451. */
  452. void
  453. connection_free_all(void)
  454. {
  455. smartlist_t *conns = get_connection_array();
  456. /* We don't want to log any messages to controllers. */
  457. SMARTLIST_FOREACH(conns, connection_t *, conn,
  458. if (conn->type == CONN_TYPE_CONTROL)
  459. TO_CONTROL_CONN(conn)->event_mask = 0);
  460. control_update_global_event_mask();
  461. /* Unlink everything from the identity map. */
  462. connection_or_clear_identity_map();
  463. SMARTLIST_FOREACH(conns, connection_t *, conn, _connection_free(conn));
  464. if (outgoing_addrs) {
  465. SMARTLIST_FOREACH(outgoing_addrs, void*, addr, tor_free(addr));
  466. smartlist_free(outgoing_addrs);
  467. outgoing_addrs = NULL;
  468. }
  469. }
  470. /** Do any cleanup needed:
  471. * - Directory conns that failed to fetch a rendezvous descriptor
  472. * need to inform pending rendezvous streams.
  473. * - OR conns need to call rep_hist_note_*() to record status.
  474. * - AP conns need to send a socks reject if necessary.
  475. * - Exit conns need to call connection_dns_remove() if necessary.
  476. * - AP and Exit conns need to send an end cell if they can.
  477. * - DNS conns need to fail any resolves that are pending on them.
  478. * - OR and edge connections need to be unlinked from circuits.
  479. */
  480. void
  481. connection_about_to_close_connection(connection_t *conn)
  482. {
  483. circuit_t *circ;
  484. dir_connection_t *dir_conn;
  485. or_connection_t *or_conn;
  486. edge_connection_t *edge_conn;
  487. time_t now = time(NULL);
  488. tor_assert(conn->marked_for_close);
  489. if (CONN_IS_EDGE(conn)) {
  490. edge_conn = TO_EDGE_CONN(conn);
  491. if (!edge_conn->edge_has_sent_end) {
  492. log_warn(LD_BUG, "(Harmless.) Edge connection (marked at %s:%d) "
  493. "hasn't sent end yet?",
  494. conn->marked_for_close_file, conn->marked_for_close);
  495. tor_fragile_assert();
  496. }
  497. }
  498. switch (conn->type) {
  499. case CONN_TYPE_DIR:
  500. dir_conn = TO_DIR_CONN(conn);
  501. if (conn->state < DIR_CONN_STATE_CLIENT_FINISHED) {
  502. /* It's a directory connection and connecting or fetching
  503. * failed: forget about this router, and maybe try again. */
  504. connection_dir_request_failed(dir_conn);
  505. }
  506. /* If we were trying to fetch a v2 rend desc and did not succeed,
  507. * retry as needed. (If a fetch is successful, the connection state
  508. * is changed to DIR_PURPOSE_HAS_FETCHED_RENDDESC to mark that
  509. * refetching is unnecessary.) */
  510. if (conn->purpose == DIR_PURPOSE_FETCH_RENDDESC_V2 &&
  511. dir_conn->rend_data &&
  512. strlen(dir_conn->rend_data->onion_address) ==
  513. REND_SERVICE_ID_LEN_BASE32)
  514. rend_client_refetch_v2_renddesc(dir_conn->rend_data);
  515. break;
  516. case CONN_TYPE_OR:
  517. or_conn = TO_OR_CONN(conn);
  518. /* Remember why we're closing this connection. */
  519. if (conn->state != OR_CONN_STATE_OPEN) {
  520. /* Inform any pending (not attached) circs that they should
  521. * give up. */
  522. circuit_n_conn_done(TO_OR_CONN(conn), 0);
  523. /* now mark things down as needed */
  524. if (connection_or_nonopen_was_started_here(or_conn)) {
  525. or_options_t *options = get_options();
  526. rep_hist_note_connect_failed(or_conn->identity_digest, now);
  527. entry_guard_register_connect_status(or_conn->identity_digest,0,
  528. !options->HTTPSProxy, now);
  529. if (conn->state >= OR_CONN_STATE_TLS_HANDSHAKING) {
  530. int reason = tls_error_to_orconn_end_reason(or_conn->tls_error);
  531. control_event_or_conn_status(or_conn, OR_CONN_EVENT_FAILED,
  532. reason);
  533. if (!authdir_mode_tests_reachability(options))
  534. control_event_bootstrap_problem(
  535. orconn_end_reason_to_control_string(reason), reason);
  536. }
  537. }
  538. } else if (conn->hold_open_until_flushed) {
  539. /* We only set hold_open_until_flushed when we're intentionally
  540. * closing a connection. */
  541. rep_hist_note_disconnect(or_conn->identity_digest, now);
  542. control_event_or_conn_status(or_conn, OR_CONN_EVENT_CLOSED,
  543. tls_error_to_orconn_end_reason(or_conn->tls_error));
  544. } else if (!tor_digest_is_zero(or_conn->identity_digest)) {
  545. rep_hist_note_connection_died(or_conn->identity_digest, now);
  546. control_event_or_conn_status(or_conn, OR_CONN_EVENT_CLOSED,
  547. tls_error_to_orconn_end_reason(or_conn->tls_error));
  548. }
  549. /* Now close all the attached circuits on it. */
  550. circuit_unlink_all_from_or_conn(TO_OR_CONN(conn),
  551. END_CIRC_REASON_OR_CONN_CLOSED);
  552. break;
  553. case CONN_TYPE_AP:
  554. edge_conn = TO_EDGE_CONN(conn);
  555. if (edge_conn->socks_request->has_finished == 0) {
  556. /* since conn gets removed right after this function finishes,
  557. * there's no point trying to send back a reply at this point. */
  558. log_warn(LD_BUG,"Closing stream (marked at %s:%d) without sending"
  559. " back a socks reply.",
  560. conn->marked_for_close_file, conn->marked_for_close);
  561. }
  562. if (!edge_conn->end_reason) {
  563. log_warn(LD_BUG,"Closing stream (marked at %s:%d) without having"
  564. " set end_reason.",
  565. conn->marked_for_close_file, conn->marked_for_close);
  566. }
  567. if (edge_conn->dns_server_request) {
  568. log_warn(LD_BUG,"Closing stream (marked at %s:%d) without having"
  569. " replied to DNS request.",
  570. conn->marked_for_close_file, conn->marked_for_close);
  571. dnsserv_reject_request(edge_conn);
  572. }
  573. control_event_stream_bandwidth(edge_conn);
  574. control_event_stream_status(edge_conn, STREAM_EVENT_CLOSED,
  575. edge_conn->end_reason);
  576. circ = circuit_get_by_edge_conn(edge_conn);
  577. if (circ)
  578. circuit_detach_stream(circ, edge_conn);
  579. break;
  580. case CONN_TYPE_EXIT:
  581. edge_conn = TO_EDGE_CONN(conn);
  582. circ = circuit_get_by_edge_conn(edge_conn);
  583. if (circ)
  584. circuit_detach_stream(circ, edge_conn);
  585. if (conn->state == EXIT_CONN_STATE_RESOLVING) {
  586. connection_dns_remove(edge_conn);
  587. }
  588. break;
  589. }
  590. }
  591. /** Return true iff connection_close_immediate() has been called on this
  592. * connection. */
  593. #define CONN_IS_CLOSED(c) \
  594. ((c)->linked ? ((c)->linked_conn_is_closed) : ((c)->s < 0))
  595. /** Close the underlying socket for <b>conn</b>, so we don't try to
  596. * flush it. Must be used in conjunction with (right before)
  597. * connection_mark_for_close().
  598. */
  599. void
  600. connection_close_immediate(connection_t *conn)
  601. {
  602. assert_connection_ok(conn,0);
  603. if (CONN_IS_CLOSED(conn)) {
  604. log_err(LD_BUG,"Attempt to close already-closed connection.");
  605. tor_fragile_assert();
  606. return;
  607. }
  608. if (conn->outbuf_flushlen) {
  609. log_info(LD_NET,"fd %d, type %s, state %s, %d bytes on outbuf.",
  610. conn->s, conn_type_to_string(conn->type),
  611. conn_state_to_string(conn->type, conn->state),
  612. (int)conn->outbuf_flushlen);
  613. }
  614. connection_unregister_events(conn);
  615. if (conn->s >= 0)
  616. tor_close_socket(conn->s);
  617. conn->s = -1;
  618. if (conn->linked)
  619. conn->linked_conn_is_closed = 1;
  620. if (!connection_is_listener(conn)) {
  621. buf_clear(conn->outbuf);
  622. conn->outbuf_flushlen = 0;
  623. }
  624. }
  625. /** Mark <b>conn</b> to be closed next time we loop through
  626. * conn_close_if_marked() in main.c. */
  627. void
  628. _connection_mark_for_close(connection_t *conn, int line, const char *file)
  629. {
  630. assert_connection_ok(conn,0);
  631. tor_assert(line);
  632. tor_assert(line < 1<<16); /* marked_for_close can only fit a uint16_t. */
  633. tor_assert(file);
  634. if (conn->marked_for_close) {
  635. log(LOG_WARN,LD_BUG,"Duplicate call to connection_mark_for_close at %s:%d"
  636. " (first at %s:%d)", file, line, conn->marked_for_close_file,
  637. conn->marked_for_close);
  638. tor_fragile_assert();
  639. return;
  640. }
  641. conn->marked_for_close = line;
  642. conn->marked_for_close_file = file;
  643. add_connection_to_closeable_list(conn);
  644. /* in case we're going to be held-open-til-flushed, reset
  645. * the number of seconds since last successful write, so
  646. * we get our whole 15 seconds */
  647. conn->timestamp_lastwritten = time(NULL);
  648. }
  649. /** Find each connection that has hold_open_until_flushed set to
  650. * 1 but hasn't written in the past 15 seconds, and set
  651. * hold_open_until_flushed to 0. This means it will get cleaned
  652. * up in the next loop through close_if_marked() in main.c.
  653. */
  654. void
  655. connection_expire_held_open(void)
  656. {
  657. time_t now;
  658. smartlist_t *conns = get_connection_array();
  659. now = time(NULL);
  660. SMARTLIST_FOREACH(conns, connection_t *, conn,
  661. {
  662. /* If we've been holding the connection open, but we haven't written
  663. * for 15 seconds...
  664. */
  665. if (conn->hold_open_until_flushed) {
  666. tor_assert(conn->marked_for_close);
  667. if (now - conn->timestamp_lastwritten >= 15) {
  668. int severity;
  669. if (conn->type == CONN_TYPE_EXIT ||
  670. (conn->type == CONN_TYPE_DIR &&
  671. conn->purpose == DIR_PURPOSE_SERVER))
  672. severity = LOG_INFO;
  673. else
  674. severity = LOG_NOTICE;
  675. log_fn(severity, LD_NET,
  676. "Giving up on marked_for_close conn that's been flushing "
  677. "for 15s (fd %d, type %s, state %s).",
  678. conn->s, conn_type_to_string(conn->type),
  679. conn_state_to_string(conn->type, conn->state));
  680. conn->hold_open_until_flushed = 0;
  681. }
  682. }
  683. });
  684. }
  685. /** Create an AF_INET listenaddr struct.
  686. * <b>listenaddress</b> provides the host and optionally the port information
  687. * for the new structure. If no port is provided in <b>listenaddress</b> then
  688. * <b>listenport</b> is used.
  689. *
  690. * If not NULL <b>readable_address</b> will contain a copy of the host part of
  691. * <b>listenaddress</b>.
  692. *
  693. * The listenaddr struct has to be freed by the caller.
  694. */
  695. static struct sockaddr_in *
  696. create_inet_sockaddr(const char *listenaddress, int listenport,
  697. char **readable_address, socklen_t *socklen_out) {
  698. struct sockaddr_in *listenaddr = NULL;
  699. uint32_t addr;
  700. uint16_t usePort = 0;
  701. if (parse_addr_port(LOG_WARN,
  702. listenaddress, readable_address, &addr, &usePort)<0) {
  703. log_warn(LD_CONFIG,
  704. "Error parsing/resolving ListenAddress %s", listenaddress);
  705. goto err;
  706. }
  707. if (usePort==0) {
  708. if (listenport != CFG_AUTO_PORT)
  709. usePort = listenport;
  710. }
  711. listenaddr = tor_malloc_zero(sizeof(struct sockaddr_in));
  712. listenaddr->sin_addr.s_addr = htonl(addr);
  713. listenaddr->sin_family = AF_INET;
  714. listenaddr->sin_port = htons((uint16_t) usePort);
  715. *socklen_out = sizeof(struct sockaddr_in);
  716. return listenaddr;
  717. err:
  718. tor_free(listenaddr);
  719. return NULL;
  720. }
  721. #ifdef HAVE_SYS_UN_H
  722. /** Create an AF_UNIX listenaddr struct.
  723. * <b>listenaddress</b> provides the path to the Unix socket.
  724. *
  725. * Eventually <b>listenaddress</b> will also optionally contain user, group,
  726. * and file permissions for the new socket. But not yet. XXX
  727. * Also, since we do not create the socket here the information doesn't help
  728. * here.
  729. *
  730. * If not NULL <b>readable_address</b> will contain a copy of the path part of
  731. * <b>listenaddress</b>.
  732. *
  733. * The listenaddr struct has to be freed by the caller.
  734. */
  735. static struct sockaddr_un *
  736. create_unix_sockaddr(const char *listenaddress, char **readable_address,
  737. socklen_t *len_out)
  738. {
  739. struct sockaddr_un *sockaddr = NULL;
  740. sockaddr = tor_malloc_zero(sizeof(struct sockaddr_un));
  741. sockaddr->sun_family = AF_UNIX;
  742. strncpy(sockaddr->sun_path, listenaddress, sizeof(sockaddr->sun_path));
  743. if (readable_address)
  744. *readable_address = tor_strdup(listenaddress);
  745. *len_out = sizeof(struct sockaddr_un);
  746. return sockaddr;
  747. }
  748. #else
  749. static struct sockaddr *
  750. create_unix_sockaddr(const char *listenaddress, char **readable_address,
  751. socklen_t *len_out)
  752. {
  753. (void)listenaddress;
  754. (void)readable_address;
  755. log_fn(LOG_ERR, LD_BUG,
  756. "Unix domain sockets not supported, yet we tried to create one.");
  757. *len_out = 0;
  758. tor_assert(0);
  759. };
  760. #endif /* HAVE_SYS_UN_H */
  761. /** Warn that an accept or a connect has failed because we're running up
  762. * against our ulimit. Rate-limit these warnings so that we don't spam
  763. * the log. */
  764. static void
  765. warn_too_many_conns(void)
  766. {
  767. #define WARN_TOO_MANY_CONNS_INTERVAL (6*60*60)
  768. static ratelim_t last_warned = RATELIM_INIT(WARN_TOO_MANY_CONNS_INTERVAL);
  769. char *m;
  770. if ((m = rate_limit_log(&last_warned, approx_time()))) {
  771. int n_conns = get_n_open_sockets();
  772. log_warn(LD_NET,"Failing because we have %d connections already. Please "
  773. "raise your ulimit -n.%s", n_conns, m);
  774. tor_free(m);
  775. control_event_general_status(LOG_WARN, "TOO_MANY_CONNECTIONS CURRENT=%d",
  776. n_conns);
  777. }
  778. }
  779. #ifdef HAVE_SYS_UN_H
  780. /** Check whether we should be willing to open an AF_UNIX socket in
  781. * <b>path</b>. Return 0 if we should go ahead and -1 if we shouldn't. */
  782. static int
  783. check_location_for_unix_socket(or_options_t *options, const char *path)
  784. {
  785. int r = -1;
  786. char *p = tor_strdup(path);
  787. cpd_check_t flags = CPD_CHECK_MODE_ONLY;
  788. if (get_parent_directory(p)<0)
  789. goto done;
  790. if (options->ControlSocketsGroupWritable)
  791. flags |= CPD_GROUP_OK;
  792. if (check_private_dir(p, flags) < 0) {
  793. char *escpath, *escdir;
  794. escpath = esc_for_log(path);
  795. escdir = esc_for_log(p);
  796. log_warn(LD_GENERAL, "Before Tor can create a control socket in %s, the "
  797. "directory %s needs to exist, and to be accessible only by the "
  798. "user%s account that is running Tor. (On some Unix systems, "
  799. "anybody who can list a socket can conect to it, so Tor is "
  800. "being careful.)", escpath, escdir,
  801. options->ControlSocketsGroupWritable ? " and group" : "");
  802. tor_free(escpath);
  803. tor_free(escdir);
  804. goto done;
  805. }
  806. r = 0;
  807. done:
  808. tor_free(p);
  809. return r;
  810. }
  811. #endif
  812. /** Tell the TCP stack that it shouldn't wait for a long time after
  813. * <b>sock</b> has closed before reusing its port. */
  814. static void
  815. make_socket_reuseable(int sock)
  816. {
  817. #ifdef MS_WINDOWS
  818. (void) sock;
  819. #else
  820. int one=1;
  821. /* REUSEADDR on normal places means you can rebind to the port
  822. * right after somebody else has let it go. But REUSEADDR on win32
  823. * means you can bind to the port _even when somebody else
  824. * already has it bound_. So, don't do that on Win32. */
  825. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*) &one,
  826. (socklen_t)sizeof(one));
  827. #endif
  828. }
  829. /** Bind a new non-blocking socket listening to the socket described
  830. * by <b>listensockaddr</b>.
  831. *
  832. * <b>address</b> is only used for logging purposes and to add the information
  833. * to the conn.
  834. */
  835. static connection_t *
  836. connection_create_listener(const struct sockaddr *listensockaddr,
  837. socklen_t socklen,
  838. int type, char* address)
  839. {
  840. connection_t *conn;
  841. int s; /* the socket we're going to make */
  842. uint16_t usePort = 0, gotPort = 0;
  843. int start_reading = 0;
  844. if (get_n_open_sockets() >= get_options()->_ConnLimit-1) {
  845. warn_too_many_conns();
  846. return NULL;
  847. }
  848. if (listensockaddr->sa_family == AF_INET) {
  849. tor_addr_t addr;
  850. int is_tcp = (type != CONN_TYPE_AP_DNS_LISTENER);
  851. if (is_tcp)
  852. start_reading = 1;
  853. tor_addr_from_sockaddr(&addr, listensockaddr, &usePort);
  854. log_notice(LD_NET, "Opening %s on %s:%d",
  855. conn_type_to_string(type), fmt_addr(&addr), usePort);
  856. s = tor_open_socket(PF_INET,
  857. is_tcp ? SOCK_STREAM : SOCK_DGRAM,
  858. is_tcp ? IPPROTO_TCP: IPPROTO_UDP);
  859. if (s < 0) {
  860. log_warn(LD_NET,"Socket creation failed.");
  861. goto err;
  862. }
  863. make_socket_reuseable(s);
  864. if (bind(s,listensockaddr,socklen) < 0) {
  865. const char *helpfulhint = "";
  866. int e = tor_socket_errno(s);
  867. if (ERRNO_IS_EADDRINUSE(e))
  868. helpfulhint = ". Is Tor already running?";
  869. log_warn(LD_NET, "Could not bind to %s:%u: %s%s", address, usePort,
  870. tor_socket_strerror(e), helpfulhint);
  871. tor_close_socket(s);
  872. goto err;
  873. }
  874. if (is_tcp) {
  875. if (listen(s,SOMAXCONN) < 0) {
  876. log_warn(LD_NET, "Could not listen on %s:%u: %s", address, usePort,
  877. tor_socket_strerror(tor_socket_errno(s)));
  878. tor_close_socket(s);
  879. goto err;
  880. }
  881. }
  882. if (usePort != 0) {
  883. gotPort = usePort;
  884. } else {
  885. tor_addr_t addr2;
  886. struct sockaddr_storage ss;
  887. socklen_t ss_len=sizeof(ss);
  888. if (getsockname(s, (struct sockaddr*)&ss, &ss_len)<0) {
  889. log_warn(LD_NET, "getsockname() couldn't learn address for %s: %s",
  890. conn_type_to_string(type),
  891. tor_socket_strerror(tor_socket_errno(s)));
  892. gotPort = 0;
  893. }
  894. tor_addr_from_sockaddr(&addr2, (struct sockaddr*)&ss, &gotPort);
  895. }
  896. #ifdef HAVE_SYS_UN_H
  897. } else if (listensockaddr->sa_family == AF_UNIX) {
  898. start_reading = 1;
  899. /* For now only control ports can be Unix domain sockets
  900. * and listeners at the same time */
  901. tor_assert(type == CONN_TYPE_CONTROL_LISTENER);
  902. if (check_location_for_unix_socket(get_options(), address) < 0)
  903. goto err;
  904. log_notice(LD_NET, "Opening %s on %s",
  905. conn_type_to_string(type), address);
  906. if (unlink(address) < 0 && errno != ENOENT) {
  907. log_warn(LD_NET, "Could not unlink %s: %s", address,
  908. strerror(errno));
  909. goto err;
  910. }
  911. s = tor_open_socket(AF_UNIX, SOCK_STREAM, 0);
  912. if (s < 0) {
  913. log_warn(LD_NET,"Socket creation failed: %s.", strerror(errno));
  914. goto err;
  915. }
  916. if (bind(s, listensockaddr, (socklen_t)sizeof(struct sockaddr_un)) == -1) {
  917. log_warn(LD_NET,"Bind to %s failed: %s.", address,
  918. tor_socket_strerror(tor_socket_errno(s)));
  919. goto err;
  920. }
  921. if (get_options()->ControlSocketsGroupWritable) {
  922. /* We need to use chmod; fchmod doesn't work on sockets on all
  923. * platforms. */
  924. if (chmod(address, 0660) < 0) {
  925. log_warn(LD_FS,"Unable to make %s group-writable.", address);
  926. tor_close_socket(s);
  927. goto err;
  928. }
  929. }
  930. if (listen(s,SOMAXCONN) < 0) {
  931. log_warn(LD_NET, "Could not listen on %s: %s", address,
  932. tor_socket_strerror(tor_socket_errno(s)));
  933. tor_close_socket(s);
  934. goto err;
  935. }
  936. #endif /* HAVE_SYS_UN_H */
  937. } else {
  938. log_err(LD_BUG,"Got unexpected address family %d.",
  939. listensockaddr->sa_family);
  940. tor_assert(0);
  941. }
  942. set_socket_nonblocking(s);
  943. conn = connection_new(type, listensockaddr->sa_family);
  944. conn->socket_family = listensockaddr->sa_family;
  945. conn->s = s;
  946. conn->address = tor_strdup(address);
  947. conn->port = gotPort;
  948. if (connection_add(conn) < 0) { /* no space, forget it */
  949. log_warn(LD_NET,"connection_add for listener failed. Giving up.");
  950. connection_free(conn);
  951. goto err;
  952. }
  953. log_fn(usePort==gotPort ? LOG_DEBUG : LOG_NOTICE, LD_NET,
  954. "%s listening on port %u.",
  955. conn_type_to_string(type), gotPort);
  956. if (type == CONN_TYPE_CONTROL_LISTENER)
  957. control_ports_write_to_file();
  958. conn->state = LISTENER_STATE_READY;
  959. if (start_reading) {
  960. connection_start_reading(conn);
  961. } else {
  962. tor_assert(type == CONN_TYPE_AP_DNS_LISTENER);
  963. dnsserv_configure_listener(conn);
  964. }
  965. return conn;
  966. err:
  967. return NULL;
  968. }
  969. /** Do basic sanity checking on a newly received socket. Return 0
  970. * if it looks ok, else return -1. */
  971. static int
  972. check_sockaddr(struct sockaddr *sa, int len, int level)
  973. {
  974. int ok = 1;
  975. if (sa->sa_family == AF_INET) {
  976. struct sockaddr_in *sin=(struct sockaddr_in*)sa;
  977. if (len != sizeof(struct sockaddr_in)) {
  978. log_fn(level, LD_NET, "Length of address not as expected: %d vs %d",
  979. len,(int)sizeof(struct sockaddr_in));
  980. ok = 0;
  981. }
  982. if (sin->sin_addr.s_addr == 0 || sin->sin_port == 0) {
  983. log_fn(level, LD_NET,
  984. "Address for new connection has address/port equal to zero.");
  985. ok = 0;
  986. }
  987. } else if (sa->sa_family == AF_INET6) {
  988. struct sockaddr_in6 *sin6=(struct sockaddr_in6*)sa;
  989. if (len != sizeof(struct sockaddr_in6)) {
  990. log_fn(level, LD_NET, "Length of address not as expected: %d vs %d",
  991. len,(int)sizeof(struct sockaddr_in6));
  992. ok = 0;
  993. }
  994. if (tor_mem_is_zero((void*)sin6->sin6_addr.s6_addr, 16) ||
  995. sin6->sin6_port == 0) {
  996. log_fn(level, LD_NET,
  997. "Address for new connection has address/port equal to zero.");
  998. ok = 0;
  999. }
  1000. } else {
  1001. ok = 0;
  1002. }
  1003. return ok ? 0 : -1;
  1004. }
  1005. /** Check whether the socket family from an accepted socket <b>got</b> is the
  1006. * same as the one that <b>listener</b> is waiting for. If it isn't, log
  1007. * a useful message and return -1. Else return 0.
  1008. *
  1009. * This is annoying, but can apparently happen on some Darwins. */
  1010. static int
  1011. check_sockaddr_family_match(sa_family_t got, connection_t *listener)
  1012. {
  1013. if (got != listener->socket_family) {
  1014. log_info(LD_BUG, "A listener connection returned a socket with a "
  1015. "mismatched family. %s for addr_family %d gave us a socket "
  1016. "with address family %d. Dropping.",
  1017. conn_type_to_string(listener->type),
  1018. (int)listener->socket_family,
  1019. (int)got);
  1020. return -1;
  1021. }
  1022. return 0;
  1023. }
  1024. /** The listener connection <b>conn</b> told poll() it wanted to read.
  1025. * Call accept() on conn-\>s, and add the new connection if necessary.
  1026. */
  1027. static int
  1028. connection_handle_listener_read(connection_t *conn, int new_type)
  1029. {
  1030. int news; /* the new socket */
  1031. connection_t *newconn;
  1032. /* information about the remote peer when connecting to other routers */
  1033. char addrbuf[256];
  1034. struct sockaddr *remote = (struct sockaddr*)addrbuf;
  1035. /* length of the remote address. Must be whatever accept() needs. */
  1036. socklen_t remotelen = (socklen_t)sizeof(addrbuf);
  1037. or_options_t *options = get_options();
  1038. tor_assert((size_t)remotelen >= sizeof(struct sockaddr_in));
  1039. memset(addrbuf, 0, sizeof(addrbuf));
  1040. news = tor_accept_socket(conn->s,remote,&remotelen);
  1041. if (news < 0) { /* accept() error */
  1042. int e = tor_socket_errno(conn->s);
  1043. if (ERRNO_IS_ACCEPT_EAGAIN(e)) {
  1044. return 0; /* he hung up before we could accept(). that's fine. */
  1045. } else if (ERRNO_IS_ACCEPT_RESOURCE_LIMIT(e)) {
  1046. warn_too_many_conns();
  1047. return 0;
  1048. }
  1049. /* else there was a real error. */
  1050. log_warn(LD_NET,"accept() failed: %s. Closing listener.",
  1051. tor_socket_strerror(e));
  1052. connection_mark_for_close(conn);
  1053. return -1;
  1054. }
  1055. log_debug(LD_NET,
  1056. "Connection accepted on socket %d (child of fd %d).",
  1057. news,conn->s);
  1058. make_socket_reuseable(news);
  1059. set_socket_nonblocking(news);
  1060. if (options->ConstrainedSockets)
  1061. set_constrained_socket_buffers(news, (int)options->ConstrainedSockSize);
  1062. if (check_sockaddr_family_match(remote->sa_family, conn) < 0) {
  1063. tor_close_socket(news);
  1064. return 0;
  1065. }
  1066. if (conn->socket_family == AF_INET || conn->socket_family == AF_INET6) {
  1067. tor_addr_t addr;
  1068. uint16_t port;
  1069. if (check_sockaddr(remote, remotelen, LOG_INFO)<0) {
  1070. log_info(LD_NET,
  1071. "accept() returned a strange address; trying getsockname().");
  1072. remotelen=sizeof(addrbuf);
  1073. memset(addrbuf, 0, sizeof(addrbuf));
  1074. if (getsockname(news, remote, &remotelen)<0) {
  1075. int e = tor_socket_errno(news);
  1076. log_warn(LD_NET, "getsockname() for new connection failed: %s",
  1077. tor_socket_strerror(e));
  1078. } else {
  1079. if (check_sockaddr((struct sockaddr*)addrbuf, remotelen,
  1080. LOG_WARN) < 0) {
  1081. log_warn(LD_NET,"Something's wrong with this conn. Closing it.");
  1082. tor_close_socket(news);
  1083. return 0;
  1084. }
  1085. }
  1086. }
  1087. if (check_sockaddr_family_match(remote->sa_family, conn) < 0) {
  1088. tor_close_socket(news);
  1089. return 0;
  1090. }
  1091. tor_addr_from_sockaddr(&addr, remote, &port);
  1092. /* process entrance policies here, before we even create the connection */
  1093. if (new_type == CONN_TYPE_AP) {
  1094. /* check sockspolicy to see if we should accept it */
  1095. if (socks_policy_permits_address(&addr) == 0) {
  1096. log_notice(LD_APP,
  1097. "Denying socks connection from untrusted address %s.",
  1098. fmt_addr(&addr));
  1099. tor_close_socket(news);
  1100. return 0;
  1101. }
  1102. }
  1103. if (new_type == CONN_TYPE_DIR) {
  1104. /* check dirpolicy to see if we should accept it */
  1105. if (dir_policy_permits_address(&addr) == 0) {
  1106. log_notice(LD_DIRSERV,"Denying dir connection from address %s.",
  1107. fmt_addr(&addr));
  1108. tor_close_socket(news);
  1109. return 0;
  1110. }
  1111. }
  1112. newconn = connection_new(new_type, conn->socket_family);
  1113. newconn->s = news;
  1114. /* remember the remote address */
  1115. tor_addr_copy(&newconn->addr, &addr);
  1116. newconn->port = port;
  1117. newconn->address = tor_dup_addr(&addr);
  1118. } else if (conn->socket_family == AF_UNIX) {
  1119. /* For now only control ports can be Unix domain sockets
  1120. * and listeners at the same time */
  1121. tor_assert(conn->type == CONN_TYPE_CONTROL_LISTENER);
  1122. newconn = connection_new(new_type, conn->socket_family);
  1123. newconn->s = news;
  1124. /* remember the remote address -- do we have anything sane to put here? */
  1125. tor_addr_make_unspec(&newconn->addr);
  1126. newconn->port = 1;
  1127. newconn->address = tor_strdup(conn->address);
  1128. } else {
  1129. tor_assert(0);
  1130. };
  1131. if (connection_add(newconn) < 0) { /* no space, forget it */
  1132. connection_free(newconn);
  1133. return 0; /* no need to tear down the parent */
  1134. }
  1135. if (connection_init_accepted_conn(newconn, conn->type) < 0) {
  1136. if (! newconn->marked_for_close)
  1137. connection_mark_for_close(newconn);
  1138. return 0;
  1139. }
  1140. return 0;
  1141. }
  1142. /** Initialize states for newly accepted connection <b>conn</b>.
  1143. * If conn is an OR, start the TLS handshake.
  1144. * If conn is a transparent AP, get its original destination
  1145. * and place it in circuit_wait.
  1146. */
  1147. static int
  1148. connection_init_accepted_conn(connection_t *conn, uint8_t listener_type)
  1149. {
  1150. connection_start_reading(conn);
  1151. switch (conn->type) {
  1152. case CONN_TYPE_OR:
  1153. control_event_or_conn_status(TO_OR_CONN(conn), OR_CONN_EVENT_NEW, 0);
  1154. return connection_tls_start_handshake(TO_OR_CONN(conn), 1);
  1155. case CONN_TYPE_AP:
  1156. switch (listener_type) {
  1157. case CONN_TYPE_AP_LISTENER:
  1158. conn->state = AP_CONN_STATE_SOCKS_WAIT;
  1159. break;
  1160. case CONN_TYPE_AP_TRANS_LISTENER:
  1161. TO_EDGE_CONN(conn)->is_transparent_ap = 1;
  1162. conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  1163. return connection_ap_process_transparent(TO_EDGE_CONN(conn));
  1164. case CONN_TYPE_AP_NATD_LISTENER:
  1165. TO_EDGE_CONN(conn)->is_transparent_ap = 1;
  1166. conn->state = AP_CONN_STATE_NATD_WAIT;
  1167. break;
  1168. }
  1169. break;
  1170. case CONN_TYPE_DIR:
  1171. conn->purpose = DIR_PURPOSE_SERVER;
  1172. conn->state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
  1173. break;
  1174. case CONN_TYPE_CONTROL:
  1175. conn->state = CONTROL_CONN_STATE_NEEDAUTH;
  1176. break;
  1177. }
  1178. return 0;
  1179. }
  1180. /** Take conn, make a nonblocking socket; try to connect to
  1181. * addr:port (they arrive in *host order*). If fail, return -1 and if
  1182. * applicable put your best guess about errno into *<b>socket_error</b>.
  1183. * Else assign s to conn-\>s: if connected return 1, if EAGAIN return 0.
  1184. *
  1185. * address is used to make the logs useful.
  1186. *
  1187. * On success, add conn to the list of polled connections.
  1188. */
  1189. int
  1190. connection_connect(connection_t *conn, const char *address,
  1191. const tor_addr_t *addr, uint16_t port, int *socket_error)
  1192. {
  1193. int s, inprogress = 0;
  1194. char addrbuf[256];
  1195. struct sockaddr *dest_addr;
  1196. socklen_t dest_addr_len;
  1197. or_options_t *options = get_options();
  1198. int protocol_family;
  1199. if (get_n_open_sockets() >= get_options()->_ConnLimit-1) {
  1200. warn_too_many_conns();
  1201. return -1;
  1202. }
  1203. if (tor_addr_family(addr) == AF_INET6)
  1204. protocol_family = PF_INET6;
  1205. else
  1206. protocol_family = PF_INET;
  1207. s = tor_open_socket(protocol_family,SOCK_STREAM,IPPROTO_TCP);
  1208. if (s < 0) {
  1209. *socket_error = tor_socket_errno(-1);
  1210. log_warn(LD_NET,"Error creating network socket: %s",
  1211. tor_socket_strerror(*socket_error));
  1212. return -1;
  1213. }
  1214. if (options->OutboundBindAddress && !tor_addr_is_loopback(addr)) {
  1215. struct sockaddr_in ext_addr;
  1216. memset(&ext_addr, 0, sizeof(ext_addr));
  1217. ext_addr.sin_family = AF_INET;
  1218. ext_addr.sin_port = 0;
  1219. if (!tor_inet_aton(options->OutboundBindAddress, &ext_addr.sin_addr)) {
  1220. log_warn(LD_CONFIG,"Outbound bind address '%s' didn't parse. Ignoring.",
  1221. options->OutboundBindAddress);
  1222. } else {
  1223. if (bind(s, (struct sockaddr*)&ext_addr,
  1224. (socklen_t)sizeof(ext_addr)) < 0) {
  1225. *socket_error = tor_socket_errno(s);
  1226. log_warn(LD_NET,"Error binding network socket: %s",
  1227. tor_socket_strerror(*socket_error));
  1228. tor_close_socket(s);
  1229. return -1;
  1230. }
  1231. }
  1232. }
  1233. set_socket_nonblocking(s);
  1234. if (options->ConstrainedSockets)
  1235. set_constrained_socket_buffers(s, (int)options->ConstrainedSockSize);
  1236. memset(addrbuf,0,sizeof(addrbuf));
  1237. dest_addr = (struct sockaddr*) addrbuf;
  1238. dest_addr_len = tor_addr_to_sockaddr(addr, port, dest_addr, sizeof(addrbuf));
  1239. tor_assert(dest_addr_len > 0);
  1240. log_debug(LD_NET, "Connecting to %s:%u.",
  1241. escaped_safe_str_client(address), port);
  1242. make_socket_reuseable(s);
  1243. if (connect(s, dest_addr, dest_addr_len) < 0) {
  1244. int e = tor_socket_errno(s);
  1245. if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
  1246. /* yuck. kill it. */
  1247. *socket_error = e;
  1248. log_info(LD_NET,
  1249. "connect() to %s:%u failed: %s",
  1250. escaped_safe_str_client(address),
  1251. port, tor_socket_strerror(e));
  1252. tor_close_socket(s);
  1253. return -1;
  1254. } else {
  1255. inprogress = 1;
  1256. }
  1257. }
  1258. if (!server_mode(options))
  1259. client_check_address_changed(s);
  1260. /* it succeeded. we're connected. */
  1261. log_fn(inprogress?LOG_DEBUG:LOG_INFO, LD_NET,
  1262. "Connection to %s:%u %s (sock %d).",
  1263. escaped_safe_str_client(address),
  1264. port, inprogress?"in progress":"established", s);
  1265. conn->s = s;
  1266. if (connection_add(conn) < 0) /* no space, forget it */
  1267. return -1;
  1268. return inprogress ? 0 : 1;
  1269. }
  1270. /** Convert state number to string representation for logging purposes.
  1271. */
  1272. static const char *
  1273. connection_proxy_state_to_string(int state)
  1274. {
  1275. static const char *unknown = "???";
  1276. static const char *states[] = {
  1277. "PROXY_NONE",
  1278. "PROXY_HTTPS_WANT_CONNECT_OK",
  1279. "PROXY_SOCKS4_WANT_CONNECT_OK",
  1280. "PROXY_SOCKS5_WANT_AUTH_METHOD_NONE",
  1281. "PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929",
  1282. "PROXY_SOCKS5_WANT_AUTH_RFC1929_OK",
  1283. "PROXY_SOCKS5_WANT_CONNECT_OK",
  1284. "PROXY_CONNECTED",
  1285. };
  1286. if (state < PROXY_NONE || state > PROXY_CONNECTED)
  1287. return unknown;
  1288. return states[state];
  1289. }
  1290. /** Write a proxy request of <b>type</b> (socks4, socks5, https) to conn
  1291. * for conn->addr:conn->port, authenticating with the auth details given
  1292. * in the configuration (if available). SOCKS 5 and HTTP CONNECT proxies
  1293. * support authentication.
  1294. *
  1295. * Returns -1 if conn->addr is incompatible with the proxy protocol, and
  1296. * 0 otherwise.
  1297. *
  1298. * Use connection_read_proxy_handshake() to complete the handshake.
  1299. */
  1300. int
  1301. connection_proxy_connect(connection_t *conn, int type)
  1302. {
  1303. or_options_t *options;
  1304. tor_assert(conn);
  1305. options = get_options();
  1306. switch (type) {
  1307. case PROXY_CONNECT: {
  1308. char buf[1024];
  1309. char *base64_authenticator=NULL;
  1310. const char *authenticator = options->HTTPSProxyAuthenticator;
  1311. /* Send HTTP CONNECT and authentication (if available) in
  1312. * one request */
  1313. if (authenticator) {
  1314. base64_authenticator = alloc_http_authenticator(authenticator);
  1315. if (!base64_authenticator)
  1316. log_warn(LD_OR, "Encoding https authenticator failed");
  1317. }
  1318. if (base64_authenticator) {
  1319. tor_snprintf(buf, sizeof(buf), "CONNECT %s:%d HTTP/1.1\r\n"
  1320. "Proxy-Authorization: Basic %s\r\n\r\n",
  1321. fmt_addr(&conn->addr),
  1322. conn->port, base64_authenticator);
  1323. tor_free(base64_authenticator);
  1324. } else {
  1325. tor_snprintf(buf, sizeof(buf), "CONNECT %s:%d HTTP/1.0\r\n\r\n",
  1326. fmt_addr(&conn->addr), conn->port);
  1327. }
  1328. connection_write_to_buf(buf, strlen(buf), conn);
  1329. conn->proxy_state = PROXY_HTTPS_WANT_CONNECT_OK;
  1330. break;
  1331. }
  1332. case PROXY_SOCKS4: {
  1333. unsigned char buf[9];
  1334. uint16_t portn;
  1335. uint32_t ip4addr;
  1336. /* Send a SOCKS4 connect request with empty user id */
  1337. if (tor_addr_family(&conn->addr) != AF_INET) {
  1338. log_warn(LD_NET, "SOCKS4 client is incompatible with IPv6");
  1339. return -1;
  1340. }
  1341. ip4addr = tor_addr_to_ipv4n(&conn->addr);
  1342. portn = htons(conn->port);
  1343. buf[0] = 4; /* version */
  1344. buf[1] = SOCKS_COMMAND_CONNECT; /* command */
  1345. memcpy(buf + 2, &portn, 2); /* port */
  1346. memcpy(buf + 4, &ip4addr, 4); /* addr */
  1347. buf[8] = 0; /* userid (empty) */
  1348. connection_write_to_buf((char *)buf, sizeof(buf), conn);
  1349. conn->proxy_state = PROXY_SOCKS4_WANT_CONNECT_OK;
  1350. break;
  1351. }
  1352. case PROXY_SOCKS5: {
  1353. unsigned char buf[4]; /* fields: vers, num methods, method list */
  1354. /* Send a SOCKS5 greeting (connect request must wait) */
  1355. buf[0] = 5; /* version */
  1356. /* number of auth methods */
  1357. if (options->Socks5ProxyUsername) {
  1358. buf[1] = 2;
  1359. buf[2] = 0x00; /* no authentication */
  1360. buf[3] = 0x02; /* rfc1929 Username/Passwd auth */
  1361. conn->proxy_state = PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929;
  1362. } else {
  1363. buf[1] = 1;
  1364. buf[2] = 0x00; /* no authentication */
  1365. conn->proxy_state = PROXY_SOCKS5_WANT_AUTH_METHOD_NONE;
  1366. }
  1367. connection_write_to_buf((char *)buf, 2 + buf[1], conn);
  1368. break;
  1369. }
  1370. default:
  1371. log_err(LD_BUG, "Invalid proxy protocol, %d", type);
  1372. tor_fragile_assert();
  1373. return -1;
  1374. }
  1375. log_debug(LD_NET, "set state %s",
  1376. connection_proxy_state_to_string(conn->proxy_state));
  1377. return 0;
  1378. }
  1379. /** Read conn's inbuf. If the http response from the proxy is all
  1380. * here, make sure it's good news, then return 1. If it's bad news,
  1381. * return -1. Else return 0 and hope for better luck next time.
  1382. */
  1383. static int
  1384. connection_read_https_proxy_response(connection_t *conn)
  1385. {
  1386. char *headers;
  1387. char *reason=NULL;
  1388. int status_code;
  1389. time_t date_header;
  1390. switch (fetch_from_buf_http(conn->inbuf,
  1391. &headers, MAX_HEADERS_SIZE,
  1392. NULL, NULL, 10000, 0)) {
  1393. case -1: /* overflow */
  1394. log_warn(LD_PROTOCOL,
  1395. "Your https proxy sent back an oversized response. Closing.");
  1396. return -1;
  1397. case 0:
  1398. log_info(LD_NET,"https proxy response not all here yet. Waiting.");
  1399. return 0;
  1400. /* case 1, fall through */
  1401. }
  1402. if (parse_http_response(headers, &status_code, &date_header,
  1403. NULL, &reason) < 0) {
  1404. log_warn(LD_NET,
  1405. "Unparseable headers from proxy (connecting to '%s'). Closing.",
  1406. conn->address);
  1407. tor_free(headers);
  1408. return -1;
  1409. }
  1410. if (!reason) reason = tor_strdup("[no reason given]");
  1411. if (status_code == 200) {
  1412. log_info(LD_NET,
  1413. "HTTPS connect to '%s' successful! (200 %s) Starting TLS.",
  1414. conn->address, escaped(reason));
  1415. tor_free(reason);
  1416. return 1;
  1417. }
  1418. /* else, bad news on the status code */
  1419. switch (status_code) {
  1420. case 403:
  1421. log_warn(LD_NET,
  1422. "The https proxy refused to allow connection to %s "
  1423. "(status code %d, %s). Closing.",
  1424. conn->address, status_code, escaped(reason));
  1425. break;
  1426. default:
  1427. log_warn(LD_NET,
  1428. "The https proxy sent back an unexpected status code %d (%s). "
  1429. "Closing.",
  1430. status_code, escaped(reason));
  1431. break;
  1432. }
  1433. tor_free(reason);
  1434. return -1;
  1435. }
  1436. /** Send SOCKS5 CONNECT command to <b>conn</b>, copying <b>conn->addr</b>
  1437. * and <b>conn->port</b> into the request.
  1438. */
  1439. static void
  1440. connection_send_socks5_connect(connection_t *conn)
  1441. {
  1442. unsigned char buf[1024];
  1443. size_t reqsize = 6;
  1444. uint16_t port = htons(conn->port);
  1445. buf[0] = 5; /* version */
  1446. buf[1] = SOCKS_COMMAND_CONNECT; /* command */
  1447. buf[2] = 0; /* reserved */
  1448. if (tor_addr_family(&conn->addr) == AF_INET) {
  1449. uint32_t addr = tor_addr_to_ipv4n(&conn->addr);
  1450. buf[3] = 1;
  1451. reqsize += 4;
  1452. memcpy(buf + 4, &addr, 4);
  1453. memcpy(buf + 8, &port, 2);
  1454. } else { /* AF_INET6 */
  1455. buf[3] = 4;
  1456. reqsize += 16;
  1457. memcpy(buf + 4, tor_addr_to_in6(&conn->addr), 16);
  1458. memcpy(buf + 20, &port, 2);
  1459. }
  1460. connection_write_to_buf((char *)buf, reqsize, conn);
  1461. conn->proxy_state = PROXY_SOCKS5_WANT_CONNECT_OK;
  1462. }
  1463. /** Call this from connection_*_process_inbuf() to advance the proxy
  1464. * handshake.
  1465. *
  1466. * No matter what proxy protocol is used, if this function returns 1, the
  1467. * handshake is complete, and the data remaining on inbuf may contain the
  1468. * start of the communication with the requested server.
  1469. *
  1470. * Returns 0 if the current buffer contains an incomplete response, and -1
  1471. * on error.
  1472. */
  1473. int
  1474. connection_read_proxy_handshake(connection_t *conn)
  1475. {
  1476. int ret = 0;
  1477. char *reason = NULL;
  1478. log_debug(LD_NET, "enter state %s",
  1479. connection_proxy_state_to_string(conn->proxy_state));
  1480. switch (conn->proxy_state) {
  1481. case PROXY_HTTPS_WANT_CONNECT_OK:
  1482. ret = connection_read_https_proxy_response(conn);
  1483. if (ret == 1)
  1484. conn->proxy_state = PROXY_CONNECTED;
  1485. break;
  1486. case PROXY_SOCKS4_WANT_CONNECT_OK:
  1487. ret = fetch_from_buf_socks_client(conn->inbuf,
  1488. conn->proxy_state,
  1489. &reason);
  1490. if (ret == 1)
  1491. conn->proxy_state = PROXY_CONNECTED;
  1492. break;
  1493. case PROXY_SOCKS5_WANT_AUTH_METHOD_NONE:
  1494. ret = fetch_from_buf_socks_client(conn->inbuf,
  1495. conn->proxy_state,
  1496. &reason);
  1497. /* no auth needed, do connect */
  1498. if (ret == 1) {
  1499. connection_send_socks5_connect(conn);
  1500. ret = 0;
  1501. }
  1502. break;
  1503. case PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929:
  1504. ret = fetch_from_buf_socks_client(conn->inbuf,
  1505. conn->proxy_state,
  1506. &reason);
  1507. /* send auth if needed, otherwise do connect */
  1508. if (ret == 1) {
  1509. connection_send_socks5_connect(conn);
  1510. ret = 0;
  1511. } else if (ret == 2) {
  1512. unsigned char buf[1024];
  1513. size_t reqsize, usize, psize;
  1514. const char *user, *pass;
  1515. user = get_options()->Socks5ProxyUsername;
  1516. pass = get_options()->Socks5ProxyPassword;
  1517. tor_assert(user && pass);
  1518. /* XXX len of user and pass must be <= 255 !!! */
  1519. usize = strlen(user);
  1520. psize = strlen(pass);
  1521. tor_assert(usize <= 255 && psize <= 255);
  1522. reqsize = 3 + usize + psize;
  1523. buf[0] = 1; /* negotiation version */
  1524. buf[1] = usize;
  1525. memcpy(buf + 2, user, usize);
  1526. buf[2 + usize] = psize;
  1527. memcpy(buf + 3 + usize, pass, psize);
  1528. connection_write_to_buf((char *)buf, reqsize, conn);
  1529. conn->proxy_state = PROXY_SOCKS5_WANT_AUTH_RFC1929_OK;
  1530. ret = 0;
  1531. }
  1532. break;
  1533. case PROXY_SOCKS5_WANT_AUTH_RFC1929_OK:
  1534. ret = fetch_from_buf_socks_client(conn->inbuf,
  1535. conn->proxy_state,
  1536. &reason);
  1537. /* send the connect request */
  1538. if (ret == 1) {
  1539. connection_send_socks5_connect(conn);
  1540. ret = 0;
  1541. }
  1542. break;
  1543. case PROXY_SOCKS5_WANT_CONNECT_OK:
  1544. ret = fetch_from_buf_socks_client(conn->inbuf,
  1545. conn->proxy_state,
  1546. &reason);
  1547. if (ret == 1)
  1548. conn->proxy_state = PROXY_CONNECTED;
  1549. break;
  1550. default:
  1551. log_err(LD_BUG, "Invalid proxy_state for reading, %d",
  1552. conn->proxy_state);
  1553. tor_fragile_assert();
  1554. ret = -1;
  1555. break;
  1556. }
  1557. log_debug(LD_NET, "leaving state %s",
  1558. connection_proxy_state_to_string(conn->proxy_state));
  1559. if (ret < 0) {
  1560. if (reason) {
  1561. log_warn(LD_NET, "Proxy Client: unable to connect to %s:%d (%s)",
  1562. conn->address, conn->port, escaped(reason));
  1563. tor_free(reason);
  1564. } else {
  1565. log_warn(LD_NET, "Proxy Client: unable to connect to %s:%d",
  1566. conn->address, conn->port);
  1567. }
  1568. } else if (ret == 1) {
  1569. log_info(LD_NET, "Proxy Client: connection to %s:%d successful",
  1570. conn->address, conn->port);
  1571. }
  1572. return ret;
  1573. }
  1574. /**
  1575. * Launch any configured listener connections of type <b>type</b>. (A
  1576. * listener is configured if <b>port_option</b> is non-zero. If any
  1577. * ListenAddress configuration options are given in <b>cfg</b>, create a
  1578. * connection binding to each one. Otherwise, create a single
  1579. * connection binding to the address <b>default_addr</b>.)
  1580. *
  1581. * Only launch the listeners of this type that are not already open, and
  1582. * only close listeners that are no longer wanted. Existing listeners
  1583. * that are still configured are not touched.
  1584. *
  1585. * If <b>disable_all_conns</b> is set, then never open new conns, and
  1586. * close the existing ones.
  1587. *
  1588. * Add all old conns that should be closed to <b>replaced_conns</b>.
  1589. * Add all new connections to <b>new_conns</b>.
  1590. */
  1591. static int
  1592. retry_listeners(int type, config_line_t *cfg,
  1593. int port_option, const char *default_addr,
  1594. smartlist_t *replaced_conns,
  1595. smartlist_t *new_conns,
  1596. int disable_all_conns,
  1597. int socket_family)
  1598. {
  1599. smartlist_t *launch = smartlist_create(), *conns;
  1600. int free_launch_elts = 1;
  1601. int r;
  1602. config_line_t *c;
  1603. connection_t *conn;
  1604. config_line_t *line;
  1605. tor_assert(socket_family == AF_INET || socket_family == AF_UNIX);
  1606. if (cfg && port_option) {
  1607. for (c = cfg; c; c = c->next) {
  1608. smartlist_add(launch, c);
  1609. }
  1610. free_launch_elts = 0;
  1611. } else if (port_option) {
  1612. line = tor_malloc_zero(sizeof(config_line_t));
  1613. line->key = tor_strdup("");
  1614. line->value = tor_strdup(default_addr);
  1615. smartlist_add(launch, line);
  1616. }
  1617. /*
  1618. SMARTLIST_FOREACH(launch, config_line_t *, l,
  1619. log_fn(LOG_NOTICE, "#%s#%s", l->key, l->value));
  1620. */
  1621. conns = get_connection_array();
  1622. SMARTLIST_FOREACH(conns, connection_t *, conn,
  1623. {
  1624. if (conn->type != type ||
  1625. conn->socket_family != socket_family ||
  1626. conn->marked_for_close)
  1627. continue;
  1628. /* Okay, so this is a listener. Is it configured? */
  1629. line = NULL;
  1630. SMARTLIST_FOREACH(launch, config_line_t *, wanted,
  1631. {
  1632. char *address=NULL;
  1633. uint16_t port;
  1634. switch (socket_family) {
  1635. case AF_INET:
  1636. if (!parse_addr_port(LOG_WARN,
  1637. wanted->value, &address, NULL, &port)) {
  1638. int addr_matches = !strcasecmp(address, conn->address);
  1639. int port_matches;
  1640. tor_free(address);
  1641. if (port) {
  1642. /* The Listener line has a port */
  1643. port_matches = (port == conn->port);
  1644. } else if (port_option == CFG_AUTO_PORT) {
  1645. /* The Listener line has no port, and the Port line is "auto".
  1646. * "auto" matches anything; transitions from any port to
  1647. * "auto" succeed. */
  1648. port_matches = 1;
  1649. } else {
  1650. /* The Listener line has no port, and the Port line is "auto".
  1651. * "auto" matches anything; transitions from any port to
  1652. * "auto" succeed. */
  1653. port_matches = (port_option == conn->port);
  1654. }
  1655. if (port_matches && addr_matches) {
  1656. line = wanted;
  1657. break;
  1658. }
  1659. }
  1660. break;
  1661. case AF_UNIX:
  1662. if (!strcasecmp(wanted->value, conn->address)) {
  1663. line = wanted;
  1664. break;
  1665. }
  1666. break;
  1667. default:
  1668. tor_assert(0);
  1669. }
  1670. });
  1671. if (!line || disable_all_conns) {
  1672. /* This one isn't configured. Close it. */
  1673. log_notice(LD_NET, "Closing no-longer-configured %s on %s:%d",
  1674. conn_type_to_string(type), conn->address, conn->port);
  1675. if (replaced_conns) {
  1676. smartlist_add(replaced_conns, conn);
  1677. } else {
  1678. connection_close_immediate(conn);
  1679. connection_mark_for_close(conn);
  1680. }
  1681. } else {
  1682. /* It's configured; we don't need to launch it. */
  1683. // log_debug(LD_NET, "Already have %s on %s:%d",
  1684. // conn_type_to_string(type), conn->address, conn->port);
  1685. smartlist_remove(launch, line);
  1686. if (free_launch_elts)
  1687. config_free_lines(line);
  1688. }
  1689. });
  1690. /* Now open all the listeners that are configured but not opened. */
  1691. r = 0;
  1692. if (!disable_all_conns) {
  1693. SMARTLIST_FOREACH_BEGIN(launch, config_line_t *, cfg_line) {
  1694. char *address = NULL;
  1695. struct sockaddr *listensockaddr;
  1696. socklen_t listensocklen = 0;
  1697. switch (socket_family) {
  1698. case AF_INET:
  1699. listensockaddr = (struct sockaddr *)
  1700. create_inet_sockaddr(cfg_line->value,
  1701. port_option,
  1702. &address, &listensocklen);
  1703. break;
  1704. case AF_UNIX:
  1705. listensockaddr = (struct sockaddr *)
  1706. create_unix_sockaddr(cfg_line->value,
  1707. &address, &listensocklen);
  1708. break;
  1709. default:
  1710. tor_assert(0);
  1711. }
  1712. if (listensockaddr) {
  1713. conn = connection_create_listener(listensockaddr, listensocklen,
  1714. type, address);
  1715. tor_free(listensockaddr);
  1716. tor_free(address);
  1717. } else
  1718. conn = NULL;
  1719. if (!conn) {
  1720. r = -1;
  1721. } else {
  1722. if (new_conns)
  1723. smartlist_add(new_conns, conn);
  1724. }
  1725. } SMARTLIST_FOREACH_END(cfg_line);
  1726. }
  1727. if (free_launch_elts) {
  1728. SMARTLIST_FOREACH(launch, config_line_t *, cfg_line,
  1729. config_free_lines(cfg_line));
  1730. }
  1731. smartlist_free(launch);
  1732. return r;
  1733. }
  1734. /** Launch listeners for each port you should have open. Only launch
  1735. * listeners who are not already open, and only close listeners we no longer
  1736. * want.
  1737. *
  1738. * Add all old conns that should be closed to <b>replaced_conns</b>.
  1739. * Add all new connections to <b>new_conns</b>.
  1740. */
  1741. int
  1742. retry_all_listeners(smartlist_t *replaced_conns,
  1743. smartlist_t *new_conns)
  1744. {
  1745. or_options_t *options = get_options();
  1746. if (retry_listeners(CONN_TYPE_OR_LISTENER, options->ORListenAddress,
  1747. options->ORPort, "0.0.0.0",
  1748. replaced_conns, new_conns, options->ClientOnly,
  1749. AF_INET)<0)
  1750. return -1;
  1751. if (retry_listeners(CONN_TYPE_DIR_LISTENER, options->DirListenAddress,
  1752. options->DirPort, "0.0.0.0",
  1753. replaced_conns, new_conns, options->ClientOnly,
  1754. AF_INET)<0)
  1755. return -1;
  1756. if (retry_listeners(CONN_TYPE_AP_LISTENER, options->SocksListenAddress,
  1757. options->SocksPort, "127.0.0.1",
  1758. replaced_conns, new_conns, 0,
  1759. AF_INET)<0)
  1760. return -1;
  1761. if (retry_listeners(CONN_TYPE_AP_TRANS_LISTENER, options->TransListenAddress,
  1762. options->TransPort, "127.0.0.1",
  1763. replaced_conns, new_conns, 0,
  1764. AF_INET)<0)
  1765. return -1;
  1766. if (retry_listeners(CONN_TYPE_AP_NATD_LISTENER, options->NATDListenAddress,
  1767. options->NATDPort, "127.0.0.1",
  1768. replaced_conns, new_conns, 0,
  1769. AF_INET)<0)
  1770. return -1;
  1771. if (retry_listeners(CONN_TYPE_AP_DNS_LISTENER, options->DNSListenAddress,
  1772. options->DNSPort, "127.0.0.1",
  1773. replaced_conns, new_conns, 0,
  1774. AF_INET)<0)
  1775. return -1;
  1776. if (retry_listeners(CONN_TYPE_CONTROL_LISTENER,
  1777. options->ControlListenAddress,
  1778. options->ControlPort, "127.0.0.1",
  1779. replaced_conns, new_conns, 0,
  1780. AF_INET)<0)
  1781. return -1;
  1782. if (retry_listeners(CONN_TYPE_CONTROL_LISTENER,
  1783. options->ControlSocket,
  1784. options->ControlSocket ? 1 : 0, NULL,
  1785. replaced_conns, new_conns, 0,
  1786. AF_UNIX)<0)
  1787. return -1;
  1788. return 0;
  1789. }
  1790. /** Return 1 if we should apply rate limiting to <b>conn</b>,
  1791. * and 0 otherwise. Right now this just checks if it's an internal
  1792. * IP address or an internal connection. */
  1793. static int
  1794. connection_is_rate_limited(connection_t *conn)
  1795. {
  1796. if (conn->linked || /* internal connection */
  1797. tor_addr_family(&conn->addr) == AF_UNSPEC || /* no address */
  1798. tor_addr_is_internal(&conn->addr, 0)) /* internal address */
  1799. return 0;
  1800. else
  1801. return 1;
  1802. }
  1803. extern int global_read_bucket, global_write_bucket;
  1804. extern int global_relayed_read_bucket, global_relayed_write_bucket;
  1805. /** Did either global write bucket run dry last second? If so,
  1806. * we are likely to run dry again this second, so be stingy with the
  1807. * tokens we just put in. */
  1808. static int write_buckets_empty_last_second = 0;
  1809. /** How many seconds of no active local circuits will make the
  1810. * connection revert to the "relayed" bandwidth class? */
  1811. #define CLIENT_IDLE_TIME_FOR_PRIORITY 30
  1812. /** Return 1 if <b>conn</b> should use tokens from the "relayed"
  1813. * bandwidth rates, else 0. Currently, only OR conns with bandwidth
  1814. * class 1, and directory conns that are serving data out, count.
  1815. */
  1816. static int
  1817. connection_counts_as_relayed_traffic(connection_t *conn, time_t now)
  1818. {
  1819. if (conn->type == CONN_TYPE_OR &&
  1820. TO_OR_CONN(conn)->client_used + CLIENT_IDLE_TIME_FOR_PRIORITY < now)
  1821. return 1;
  1822. if (conn->type == CONN_TYPE_DIR && DIR_CONN_IS_SERVER(conn))
  1823. return 1;
  1824. return 0;
  1825. }
  1826. /** Helper function to decide how many bytes out of <b>global_bucket</b>
  1827. * we're willing to use for this transaction. <b>base</b> is the size
  1828. * of a cell on the network; <b>priority</b> says whether we should
  1829. * write many of them or just a few; and <b>conn_bucket</b> (if
  1830. * non-negative) provides an upper limit for our answer. */
  1831. static ssize_t
  1832. connection_bucket_round_robin(int base, int priority,
  1833. ssize_t global_bucket, ssize_t conn_bucket)
  1834. {
  1835. ssize_t at_most;
  1836. ssize_t num_bytes_high = (priority ? 32 : 16) * base;
  1837. ssize_t num_bytes_low = (priority ? 4 : 2) * base;
  1838. /* Do a rudimentary round-robin so one circuit can't hog a connection.
  1839. * Pick at most 32 cells, at least 4 cells if possible, and if we're in
  1840. * the middle pick 1/8 of the available bandwidth. */
  1841. at_most = global_bucket / 8;
  1842. at_most -= (at_most % base); /* round down */
  1843. if (at_most > num_bytes_high) /* 16 KB, or 8 KB for low-priority */
  1844. at_most = num_bytes_high;
  1845. else if (at_most < num_bytes_low) /* 2 KB, or 1 KB for low-priority */
  1846. at_most = num_bytes_low;
  1847. if (at_most > global_bucket)
  1848. at_most = global_bucket;
  1849. if (conn_bucket >= 0 && at_most > conn_bucket)
  1850. at_most = conn_bucket;
  1851. if (at_most < 0)
  1852. return 0;
  1853. return at_most;
  1854. }
  1855. /** How many bytes at most can we read onto this connection? */
  1856. static ssize_t
  1857. connection_bucket_read_limit(connection_t *conn, time_t now)
  1858. {
  1859. int base = connection_speaks_cells(conn) ?
  1860. CELL_NETWORK_SIZE : RELAY_PAYLOAD_SIZE;
  1861. int priority = conn->type != CONN_TYPE_DIR;
  1862. int conn_bucket = -1;
  1863. int global_bucket = global_read_bucket;
  1864. if (connection_speaks_cells(conn)) {
  1865. or_connection_t *or_conn = TO_OR_CONN(conn);
  1866. if (conn->state == OR_CONN_STATE_OPEN)
  1867. conn_bucket = or_conn->read_bucket;
  1868. }
  1869. if (!connection_is_rate_limited(conn)) {
  1870. /* be willing to read on local conns even if our buckets are empty */
  1871. return conn_bucket>=0 ? conn_bucket : 1<<14;
  1872. }
  1873. if (connection_counts_as_relayed_traffic(conn, now) &&
  1874. global_relayed_read_bucket <= global_read_bucket)
  1875. global_bucket = global_relayed_read_bucket;
  1876. return connection_bucket_round_robin(base, priority,
  1877. global_bucket, conn_bucket);
  1878. }
  1879. /** How many bytes at most can we write onto this connection? */
  1880. ssize_t
  1881. connection_bucket_write_limit(connection_t *conn, time_t now)
  1882. {
  1883. int base = connection_speaks_cells(conn) ?
  1884. CELL_NETWORK_SIZE : RELAY_PAYLOAD_SIZE;
  1885. int priority = conn->type != CONN_TYPE_DIR;
  1886. int conn_bucket = (int)conn->outbuf_flushlen;
  1887. int global_bucket = global_write_bucket;
  1888. if (!connection_is_rate_limited(conn)) {
  1889. /* be willing to write to local conns even if our buckets are empty */
  1890. return conn->outbuf_flushlen;
  1891. }
  1892. if (connection_speaks_cells(conn)) {
  1893. /* use the per-conn write limit if it's lower, but if it's less
  1894. * than zero just use zero */
  1895. or_connection_t *or_conn = TO_OR_CONN(conn);
  1896. if (conn->state == OR_CONN_STATE_OPEN)
  1897. if (or_conn->write_bucket < conn_bucket)
  1898. conn_bucket = or_conn->write_bucket >= 0 ?
  1899. or_conn->write_bucket : 0;
  1900. }
  1901. if (connection_counts_as_relayed_traffic(conn, now) &&
  1902. global_relayed_write_bucket <= global_write_bucket)
  1903. global_bucket = global_relayed_write_bucket;
  1904. return connection_bucket_round_robin(base, priority,
  1905. global_bucket, conn_bucket);
  1906. }
  1907. /** Return 1 if the global write buckets are low enough that we
  1908. * shouldn't send <b>attempt</b> bytes of low-priority directory stuff
  1909. * out to <b>conn</b>. Else return 0.
  1910. * Priority is 1 for v1 requests (directories and running-routers),
  1911. * and 2 for v2 requests (statuses and descriptors). But see FFFF in
  1912. * directory_handle_command_get() for why we don't use priority 2 yet.
  1913. *
  1914. * There are a lot of parameters we could use here:
  1915. * - global_relayed_write_bucket. Low is bad.
  1916. * - global_write_bucket. Low is bad.
  1917. * - bandwidthrate. Low is bad.
  1918. * - bandwidthburst. Not a big factor?
  1919. * - attempt. High is bad.
  1920. * - total bytes queued on outbufs. High is bad. But I'm wary of
  1921. * using this, since a few slow-flushing queues will pump up the
  1922. * number without meaning what we meant to mean. What we really
  1923. * mean is "total directory bytes added to outbufs recently", but
  1924. * that's harder to quantify and harder to keep track of.
  1925. */
  1926. int
  1927. global_write_bucket_low(connection_t *conn, size_t attempt, int priority)
  1928. {
  1929. int smaller_bucket = global_write_bucket < global_relayed_write_bucket ?
  1930. global_write_bucket : global_relayed_write_bucket;
  1931. if (authdir_mode(get_options()) && priority>1)
  1932. return 0; /* there's always room to answer v2 if we're an auth dir */
  1933. if (!connection_is_rate_limited(conn))
  1934. return 0; /* local conns don't get limited */
  1935. if (smaller_bucket < (int)attempt)
  1936. return 1; /* not enough space no matter the priority */
  1937. if (write_buckets_empty_last_second)
  1938. return 1; /* we're already hitting our limits, no more please */
  1939. if (priority == 1) { /* old-style v1 query */
  1940. /* Could we handle *two* of these requests within the next two seconds? */
  1941. or_options_t *options = get_options();
  1942. int64_t can_write = (int64_t)smaller_bucket
  1943. + 2*(options->RelayBandwidthRate ? options->RelayBandwidthRate :
  1944. options->BandwidthRate);
  1945. if (can_write < 2*(int64_t)attempt)
  1946. return 1;
  1947. } else { /* v2 query */
  1948. /* no further constraints yet */
  1949. }
  1950. return 0;
  1951. }
  1952. /** We just read <b>num_read</b> and wrote <b>num_written</b> bytes
  1953. * onto <b>conn</b>. Decrement buckets appropriately. */
  1954. static void
  1955. connection_buckets_decrement(connection_t *conn, time_t now,
  1956. size_t num_read, size_t num_written)
  1957. {
  1958. if (num_written >= INT_MAX || num_read >= INT_MAX) {
  1959. log_err(LD_BUG, "Value out of range. num_read=%lu, num_written=%lu, "
  1960. "connection type=%s, state=%s",
  1961. (unsigned long)num_read, (unsigned long)num_written,
  1962. conn_type_to_string(conn->type),
  1963. conn_state_to_string(conn->type, conn->state));
  1964. if (num_written >= INT_MAX) num_written = 1;
  1965. if (num_read >= INT_MAX) num_read = 1;
  1966. tor_fragile_assert();
  1967. }
  1968. /* Count bytes of answering direct and tunneled directory requests */
  1969. if (conn->type == CONN_TYPE_DIR && conn->purpose == DIR_PURPOSE_SERVER) {
  1970. if (num_read > 0)
  1971. rep_hist_note_dir_bytes_read(num_read, now);
  1972. if (num_written > 0)
  1973. rep_hist_note_dir_bytes_written(num_written, now);
  1974. }
  1975. if (!connection_is_rate_limited(conn))
  1976. return; /* local IPs are free */
  1977. if (num_read > 0) {
  1978. rep_hist_note_bytes_read(num_read, now);
  1979. }
  1980. if (num_written > 0) {
  1981. rep_hist_note_bytes_written(num_written, now);
  1982. }
  1983. if (conn->type == CONN_TYPE_EXIT)
  1984. rep_hist_note_exit_bytes(conn->port, num_written, num_read);
  1985. if (connection_counts_as_relayed_traffic(conn, now)) {
  1986. global_relayed_read_bucket -= (int)num_read;
  1987. global_relayed_write_bucket -= (int)num_written;
  1988. }
  1989. global_read_bucket -= (int)num_read;
  1990. global_write_bucket -= (int)num_written;
  1991. if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
  1992. TO_OR_CONN(conn)->read_bucket -= (int)num_read;
  1993. TO_OR_CONN(conn)->write_bucket -= (int)num_written;
  1994. }
  1995. }
  1996. /** If we have exhausted our global buckets, or the buckets for conn,
  1997. * stop reading. */
  1998. static void
  1999. connection_consider_empty_read_buckets(connection_t *conn)
  2000. {
  2001. const char *reason;
  2002. if (global_read_bucket <= 0) {
  2003. reason = "global read bucket exhausted. Pausing.";
  2004. } else if (connection_counts_as_relayed_traffic(conn, approx_time()) &&
  2005. global_relayed_read_bucket <= 0) {
  2006. reason = "global relayed read bucket exhausted. Pausing.";
  2007. } else if (connection_speaks_cells(conn) &&
  2008. conn->state == OR_CONN_STATE_OPEN &&
  2009. TO_OR_CONN(conn)->read_bucket <= 0) {
  2010. reason = "connection read bucket exhausted. Pausing.";
  2011. } else
  2012. return; /* all good, no need to stop it */
  2013. LOG_FN_CONN(conn, (LOG_DEBUG, LD_NET, "%s", reason));
  2014. conn->read_blocked_on_bw = 1;
  2015. connection_stop_reading(conn);
  2016. }
  2017. /** If we have exhausted our global buckets, or the buckets for conn,
  2018. * stop writing. */
  2019. static void
  2020. connection_consider_empty_write_buckets(connection_t *conn)
  2021. {
  2022. const char *reason;
  2023. if (global_write_bucket <= 0) {
  2024. reason = "global write bucket exhausted. Pausing.";
  2025. } else if (connection_counts_as_relayed_traffic(conn, approx_time()) &&
  2026. global_relayed_write_bucket <= 0) {
  2027. reason = "global relayed write bucket exhausted. Pausing.";
  2028. } else if (connection_speaks_cells(conn) &&
  2029. conn->state == OR_CONN_STATE_OPEN &&
  2030. TO_OR_CONN(conn)->write_bucket <= 0) {
  2031. reason = "connection write bucket exhausted. Pausing.";
  2032. } else
  2033. return; /* all good, no need to stop it */
  2034. LOG_FN_CONN(conn, (LOG_DEBUG, LD_NET, "%s", reason));
  2035. conn->write_blocked_on_bw = 1;
  2036. connection_stop_writing(conn);
  2037. }
  2038. /** Initialize the global read bucket to options-\>BandwidthBurst. */
  2039. void
  2040. connection_bucket_init(void)
  2041. {
  2042. or_options_t *options = get_options();
  2043. /* start it at max traffic */
  2044. global_read_bucket = (int)options->BandwidthBurst;
  2045. global_write_bucket = (int)options->BandwidthBurst;
  2046. if (options->RelayBandwidthRate) {
  2047. global_relayed_read_bucket = (int)options->RelayBandwidthBurst;
  2048. global_relayed_write_bucket = (int)options->RelayBandwidthBurst;
  2049. } else {
  2050. global_relayed_read_bucket = (int)options->BandwidthBurst;
  2051. global_relayed_write_bucket = (int)options->BandwidthBurst;
  2052. }
  2053. }
  2054. /** Refill a single <b>bucket</b> called <b>name</b> with bandwidth rate
  2055. * <b>rate</b> and bandwidth burst <b>burst</b>, assuming that
  2056. * <b>seconds_elapsed</b> seconds have passed since the last call.
  2057. **/
  2058. static void
  2059. connection_bucket_refill_helper(int *bucket, int rate, int burst,
  2060. int seconds_elapsed, const char *name)
  2061. {
  2062. int starting_bucket = *bucket;
  2063. if (starting_bucket < burst && seconds_elapsed) {
  2064. if (((burst - starting_bucket)/seconds_elapsed) < rate) {
  2065. *bucket = burst; /* We would overflow the bucket; just set it to
  2066. * the maximum. */
  2067. } else {
  2068. int incr = rate*seconds_elapsed;
  2069. *bucket += incr;
  2070. if (*bucket > burst || *bucket < starting_bucket) {
  2071. /* If we overflow the burst, or underflow our starting bucket,
  2072. * cap the bucket value to burst. */
  2073. /* XXXX this might be redundant now, but it doesn't show up
  2074. * in profiles. Remove it after analysis. */
  2075. *bucket = burst;
  2076. }
  2077. }
  2078. log(LOG_DEBUG, LD_NET,"%s now %d.", name, *bucket);
  2079. }
  2080. }
  2081. /** A second has rolled over; increment buckets appropriately. */
  2082. void
  2083. connection_bucket_refill(int seconds_elapsed, time_t now)
  2084. {
  2085. or_options_t *options = get_options();
  2086. smartlist_t *conns = get_connection_array();
  2087. int relayrate, relayburst;
  2088. if (options->RelayBandwidthRate) {
  2089. relayrate = (int)options->RelayBandwidthRate;
  2090. relayburst = (int)options->RelayBandwidthBurst;
  2091. } else {
  2092. relayrate = (int)options->BandwidthRate;
  2093. relayburst = (int)options->BandwidthBurst;
  2094. }
  2095. tor_assert(seconds_elapsed >= 0);
  2096. write_buckets_empty_last_second =
  2097. global_relayed_write_bucket <= 0 || global_write_bucket <= 0;
  2098. /* refill the global buckets */
  2099. connection_bucket_refill_helper(&global_read_bucket,
  2100. (int)options->BandwidthRate,
  2101. (int)options->BandwidthBurst,
  2102. seconds_elapsed, "global_read_bucket");
  2103. connection_bucket_refill_helper(&global_write_bucket,
  2104. (int)options->BandwidthRate,
  2105. (int)options->BandwidthBurst,
  2106. seconds_elapsed, "global_write_bucket");
  2107. connection_bucket_refill_helper(&global_relayed_read_bucket,
  2108. relayrate, relayburst, seconds_elapsed,
  2109. "global_relayed_read_bucket");
  2110. connection_bucket_refill_helper(&global_relayed_write_bucket,
  2111. relayrate, relayburst, seconds_elapsed,
  2112. "global_relayed_write_bucket");
  2113. /* refill the per-connection buckets */
  2114. SMARTLIST_FOREACH(conns, connection_t *, conn,
  2115. {
  2116. if (connection_speaks_cells(conn)) {
  2117. or_connection_t *or_conn = TO_OR_CONN(conn);
  2118. if (connection_bucket_should_increase(or_conn->read_bucket, or_conn)) {
  2119. connection_bucket_refill_helper(&or_conn->read_bucket,
  2120. or_conn->bandwidthrate,
  2121. or_conn->bandwidthburst,
  2122. seconds_elapsed,
  2123. "or_conn->read_bucket");
  2124. }
  2125. if (connection_bucket_should_increase(or_conn->write_bucket, or_conn)) {
  2126. connection_bucket_refill_helper(&or_conn->write_bucket,
  2127. or_conn->bandwidthrate,
  2128. or_conn->bandwidthburst,
  2129. seconds_elapsed,
  2130. "or_conn->write_bucket");
  2131. }
  2132. }
  2133. if (conn->read_blocked_on_bw == 1 /* marked to turn reading back on now */
  2134. && global_read_bucket > 0 /* and we're allowed to read */
  2135. && (!connection_counts_as_relayed_traffic(conn, now) ||
  2136. global_relayed_read_bucket > 0) /* even if we're relayed traffic */
  2137. && (!connection_speaks_cells(conn) ||
  2138. conn->state != OR_CONN_STATE_OPEN ||
  2139. TO_OR_CONN(conn)->read_bucket > 0)) {
  2140. /* and either a non-cell conn or a cell conn with non-empty bucket */
  2141. LOG_FN_CONN(conn, (LOG_DEBUG,LD_NET,
  2142. "waking up conn (fd %d) for read", conn->s));
  2143. conn->read_blocked_on_bw = 0;
  2144. connection_start_reading(conn);
  2145. }
  2146. if (conn->write_blocked_on_bw == 1
  2147. && global_write_bucket > 0 /* and we're allowed to write */
  2148. && (!connection_counts_as_relayed_traffic(conn, now) ||
  2149. global_relayed_write_bucket > 0) /* even if it's relayed traffic */
  2150. && (!connection_speaks_cells(conn) ||
  2151. conn->state != OR_CONN_STATE_OPEN ||
  2152. TO_OR_CONN(conn)->write_bucket > 0)) {
  2153. LOG_FN_CONN(conn, (LOG_DEBUG,LD_NET,
  2154. "waking up conn (fd %d) for write", conn->s));
  2155. conn->write_blocked_on_bw = 0;
  2156. connection_start_writing(conn);
  2157. }
  2158. });
  2159. }
  2160. /** Is the <b>bucket</b> for connection <b>conn</b> low enough that we
  2161. * should add another pile of tokens to it?
  2162. */
  2163. static int
  2164. connection_bucket_should_increase(int bucket, or_connection_t *conn)
  2165. {
  2166. tor_assert(conn);
  2167. if (conn->_base.state != OR_CONN_STATE_OPEN)
  2168. return 0; /* only open connections play the rate limiting game */
  2169. if (bucket >= conn->bandwidthburst)
  2170. return 0;
  2171. return 1;
  2172. }
  2173. /** Read bytes from conn-\>s and process them.
  2174. *
  2175. * This function gets called from conn_read() in main.c, either
  2176. * when poll() has declared that conn wants to read, or (for OR conns)
  2177. * when there are pending TLS bytes.
  2178. *
  2179. * It calls connection_read_to_buf() to bring in any new bytes,
  2180. * and then calls connection_process_inbuf() to process them.
  2181. *
  2182. * Mark the connection and return -1 if you want to close it, else
  2183. * return 0.
  2184. */
  2185. static int
  2186. connection_handle_read_impl(connection_t *conn)
  2187. {
  2188. ssize_t max_to_read=-1, try_to_read;
  2189. size_t before, n_read = 0;
  2190. int socket_error = 0;
  2191. if (conn->marked_for_close)
  2192. return 0; /* do nothing */
  2193. conn->timestamp_lastread = approx_time();
  2194. switch (conn->type) {
  2195. case CONN_TYPE_OR_LISTENER:
  2196. return connection_handle_listener_read(conn, CONN_TYPE_OR);
  2197. case CONN_TYPE_AP_LISTENER:
  2198. case CONN_TYPE_AP_TRANS_LISTENER:
  2199. case CONN_TYPE_AP_NATD_LISTENER:
  2200. return connection_handle_listener_read(conn, CONN_TYPE_AP);
  2201. case CONN_TYPE_DIR_LISTENER:
  2202. return connection_handle_listener_read(conn, CONN_TYPE_DIR);
  2203. case CONN_TYPE_CONTROL_LISTENER:
  2204. return connection_handle_listener_read(conn, CONN_TYPE_CONTROL);
  2205. case CONN_TYPE_AP_DNS_LISTENER:
  2206. /* This should never happen; eventdns.c handles the reads here. */
  2207. tor_fragile_assert();
  2208. return 0;
  2209. }
  2210. loop_again:
  2211. try_to_read = max_to_read;
  2212. tor_assert(!conn->marked_for_close);
  2213. before = buf_datalen(conn->inbuf);
  2214. if (connection_read_to_buf(conn, &max_to_read, &socket_error) < 0) {
  2215. /* There's a read error; kill the connection.*/
  2216. if (conn->type == CONN_TYPE_OR &&
  2217. conn->state == OR_CONN_STATE_CONNECTING) {
  2218. connection_or_connect_failed(TO_OR_CONN(conn),
  2219. errno_to_orconn_end_reason(socket_error),
  2220. tor_socket_strerror(socket_error));
  2221. }
  2222. if (CONN_IS_EDGE(conn)) {
  2223. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  2224. connection_edge_end_errno(edge_conn);
  2225. if (edge_conn->socks_request) /* broken, don't send a socks reply back */
  2226. edge_conn->socks_request->has_finished = 1;
  2227. }
  2228. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  2229. connection_mark_for_close(conn);
  2230. return -1;
  2231. }
  2232. n_read += buf_datalen(conn->inbuf) - before;
  2233. if (CONN_IS_EDGE(conn) && try_to_read != max_to_read) {
  2234. /* instruct it not to try to package partial cells. */
  2235. if (connection_process_inbuf(conn, 0) < 0) {
  2236. return -1;
  2237. }
  2238. if (!conn->marked_for_close &&
  2239. connection_is_reading(conn) &&
  2240. !conn->inbuf_reached_eof &&
  2241. max_to_read > 0)
  2242. goto loop_again; /* try reading again, in case more is here now */
  2243. }
  2244. /* one last try, packaging partial cells and all. */
  2245. if (!conn->marked_for_close &&
  2246. connection_process_inbuf(conn, 1) < 0) {
  2247. return -1;
  2248. }
  2249. if (conn->linked_conn) {
  2250. /* The other side's handle_write() will never actually get called, so
  2251. * we need to invoke the appropriate callbacks ourself. */
  2252. connection_t *linked = conn->linked_conn;
  2253. if (n_read) {
  2254. /* Probably a no-op, since linked conns typically don't count for
  2255. * bandwidth rate limiting. But do it anyway so we can keep stats
  2256. * accurately. Note that since we read the bytes from conn, and
  2257. * we're writing the bytes onto the linked connection, we count
  2258. * these as <i>written</i> bytes. */
  2259. connection_buckets_decrement(linked, approx_time(), 0, n_read);
  2260. if (connection_flushed_some(linked) < 0)
  2261. connection_mark_for_close(linked);
  2262. if (!connection_wants_to_flush(linked))
  2263. connection_finished_flushing(linked);
  2264. }
  2265. if (!buf_datalen(linked->outbuf) && conn->active_on_link)
  2266. connection_stop_reading_from_linked_conn(conn);
  2267. }
  2268. /* If we hit the EOF, call connection_reached_eof(). */
  2269. if (!conn->marked_for_close &&
  2270. conn->inbuf_reached_eof &&
  2271. connection_reached_eof(conn) < 0) {
  2272. return -1;
  2273. }
  2274. return 0;
  2275. }
  2276. int
  2277. connection_handle_read(connection_t *conn)
  2278. {
  2279. int res;
  2280. tor_gettimeofday_cache_clear();
  2281. res = connection_handle_read_impl(conn);
  2282. return res;
  2283. }
  2284. /** Pull in new bytes from conn-\>s or conn-\>linked_conn onto conn-\>inbuf,
  2285. * either directly or via TLS. Reduce the token buckets by the number of bytes
  2286. * read.
  2287. *
  2288. * If *max_to_read is -1, then decide it ourselves, else go with the
  2289. * value passed to us. When returning, if it's changed, subtract the
  2290. * number of bytes we read from *max_to_read.
  2291. *
  2292. * Return -1 if we want to break conn, else return 0.
  2293. */
  2294. static int
  2295. connection_read_to_buf(connection_t *conn, ssize_t *max_to_read,
  2296. int *socket_error)
  2297. {
  2298. int result;
  2299. ssize_t at_most = *max_to_read;
  2300. size_t slack_in_buf, more_to_read;
  2301. size_t n_read = 0, n_written = 0;
  2302. if (at_most == -1) { /* we need to initialize it */
  2303. /* how many bytes are we allowed to read? */
  2304. at_most = connection_bucket_read_limit(conn, approx_time());
  2305. }
  2306. slack_in_buf = buf_slack(conn->inbuf);
  2307. again:
  2308. if ((size_t)at_most > slack_in_buf && slack_in_buf >= 1024) {
  2309. more_to_read = at_most - slack_in_buf;
  2310. at_most = slack_in_buf;
  2311. } else {
  2312. more_to_read = 0;
  2313. }
  2314. if (connection_speaks_cells(conn) &&
  2315. conn->state > OR_CONN_STATE_PROXY_HANDSHAKING) {
  2316. int pending;
  2317. or_connection_t *or_conn = TO_OR_CONN(conn);
  2318. size_t initial_size;
  2319. if (conn->state == OR_CONN_STATE_TLS_HANDSHAKING ||
  2320. conn->state == OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING) {
  2321. /* continue handshaking even if global token bucket is empty */
  2322. return connection_tls_continue_handshake(or_conn);
  2323. }
  2324. log_debug(LD_NET,
  2325. "%d: starting, inbuf_datalen %ld (%d pending in tls object)."
  2326. " at_most %ld.",
  2327. conn->s,(long)buf_datalen(conn->inbuf),
  2328. tor_tls_get_pending_bytes(or_conn->tls), (long)at_most);
  2329. initial_size = buf_datalen(conn->inbuf);
  2330. /* else open, or closing */
  2331. result = read_to_buf_tls(or_conn->tls, at_most, conn->inbuf);
  2332. if (TOR_TLS_IS_ERROR(result) || result == TOR_TLS_CLOSE)
  2333. or_conn->tls_error = result;
  2334. else
  2335. or_conn->tls_error = 0;
  2336. switch (result) {
  2337. case TOR_TLS_CLOSE:
  2338. case TOR_TLS_ERROR_IO:
  2339. log_debug(LD_NET,"TLS connection closed %son read. Closing. "
  2340. "(Nickname %s, address %s)",
  2341. result == TOR_TLS_CLOSE ? "cleanly " : "",
  2342. or_conn->nickname ? or_conn->nickname : "not set",
  2343. conn->address);
  2344. return result;
  2345. CASE_TOR_TLS_ERROR_ANY_NONIO:
  2346. log_debug(LD_NET,"tls error [%s]. breaking (nickname %s, address %s).",
  2347. tor_tls_err_to_string(result),
  2348. or_conn->nickname ? or_conn->nickname : "not set",
  2349. conn->address);
  2350. return result;
  2351. case TOR_TLS_WANTWRITE:
  2352. connection_start_writing(conn);
  2353. return 0;
  2354. case TOR_TLS_WANTREAD: /* we're already reading */
  2355. case TOR_TLS_DONE: /* no data read, so nothing to process */
  2356. result = 0;
  2357. break; /* so we call bucket_decrement below */
  2358. default:
  2359. break;
  2360. }
  2361. pending = tor_tls_get_pending_bytes(or_conn->tls);
  2362. if (pending) {
  2363. /* If we have any pending bytes, we read them now. This *can*
  2364. * take us over our read allotment, but really we shouldn't be
  2365. * believing that SSL bytes are the same as TCP bytes anyway. */
  2366. int r2 = read_to_buf_tls(or_conn->tls, pending, conn->inbuf);
  2367. if (r2<0) {
  2368. log_warn(LD_BUG, "apparently, reading pending bytes can fail.");
  2369. return -1;
  2370. }
  2371. }
  2372. result = (int)(buf_datalen(conn->inbuf)-initial_size);
  2373. tor_tls_get_n_raw_bytes(or_conn->tls, &n_read, &n_written);
  2374. log_debug(LD_GENERAL, "After TLS read of %d: %ld read, %ld written",
  2375. result, (long)n_read, (long)n_written);
  2376. } else if (conn->linked) {
  2377. if (conn->linked_conn) {
  2378. result = move_buf_to_buf(conn->inbuf, conn->linked_conn->outbuf,
  2379. &conn->linked_conn->outbuf_flushlen);
  2380. } else {
  2381. result = 0;
  2382. }
  2383. //log_notice(LD_GENERAL, "Moved %d bytes on an internal link!", result);
  2384. /* If the other side has disappeared, or if it's been marked for close and
  2385. * we flushed its outbuf, then we should set our inbuf_reached_eof. */
  2386. if (!conn->linked_conn ||
  2387. (conn->linked_conn->marked_for_close &&
  2388. buf_datalen(conn->linked_conn->outbuf) == 0))
  2389. conn->inbuf_reached_eof = 1;
  2390. n_read = (size_t) result;
  2391. } else {
  2392. /* !connection_speaks_cells, !conn->linked_conn. */
  2393. int reached_eof = 0;
  2394. CONN_LOG_PROTECT(conn,
  2395. result = read_to_buf(conn->s, at_most, conn->inbuf, &reached_eof,
  2396. socket_error));
  2397. if (reached_eof)
  2398. conn->inbuf_reached_eof = 1;
  2399. // log_fn(LOG_DEBUG,"read_to_buf returned %d.",read_result);
  2400. if (result < 0)
  2401. return -1;
  2402. n_read = (size_t) result;
  2403. }
  2404. if (n_read > 0) {
  2405. /* change *max_to_read */
  2406. *max_to_read = at_most - n_read;
  2407. /* Update edge_conn->n_read */
  2408. if (conn->type == CONN_TYPE_AP) {
  2409. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  2410. /* Check for overflow: */
  2411. if (PREDICT_LIKELY(UINT32_MAX - edge_conn->n_read > n_read))
  2412. edge_conn->n_read += (int)n_read;
  2413. else
  2414. edge_conn->n_read = UINT32_MAX;
  2415. }
  2416. }
  2417. connection_buckets_decrement(conn, approx_time(), n_read, n_written);
  2418. if (more_to_read && result == at_most) {
  2419. slack_in_buf = buf_slack(conn->inbuf);
  2420. at_most = more_to_read;
  2421. goto again;
  2422. }
  2423. /* Call even if result is 0, since the global read bucket may
  2424. * have reached 0 on a different conn, and this guy needs to
  2425. * know to stop reading. */
  2426. connection_consider_empty_read_buckets(conn);
  2427. if (n_written > 0 && connection_is_writing(conn))
  2428. connection_consider_empty_write_buckets(conn);
  2429. return 0;
  2430. }
  2431. /** A pass-through to fetch_from_buf. */
  2432. int
  2433. connection_fetch_from_buf(char *string, size_t len, connection_t *conn)
  2434. {
  2435. return fetch_from_buf(string, len, conn->inbuf);
  2436. }
  2437. /** Return conn-\>outbuf_flushlen: how many bytes conn wants to flush
  2438. * from its outbuf. */
  2439. int
  2440. connection_wants_to_flush(connection_t *conn)
  2441. {
  2442. return conn->outbuf_flushlen > 0;
  2443. }
  2444. /** Are there too many bytes on edge connection <b>conn</b>'s outbuf to
  2445. * send back a relay-level sendme yet? Return 1 if so, 0 if not. Used by
  2446. * connection_edge_consider_sending_sendme().
  2447. */
  2448. int
  2449. connection_outbuf_too_full(connection_t *conn)
  2450. {
  2451. return (conn->outbuf_flushlen > 10*CELL_PAYLOAD_SIZE);
  2452. }
  2453. /** Try to flush more bytes onto conn-\>s.
  2454. *
  2455. * This function gets called either from conn_write() in main.c
  2456. * when poll() has declared that conn wants to write, or below
  2457. * from connection_write_to_buf() when an entire TLS record is ready.
  2458. *
  2459. * Update conn-\>timestamp_lastwritten to now, and call flush_buf
  2460. * or flush_buf_tls appropriately. If it succeeds and there are no more
  2461. * more bytes on conn->outbuf, then call connection_finished_flushing
  2462. * on it too.
  2463. *
  2464. * If <b>force</b>, then write as many bytes as possible, ignoring bandwidth
  2465. * limits. (Used for flushing messages to controller connections on fatal
  2466. * errors.)
  2467. *
  2468. * Mark the connection and return -1 if you want to close it, else
  2469. * return 0.
  2470. */
  2471. static int
  2472. connection_handle_write_impl(connection_t *conn, int force)
  2473. {
  2474. int e;
  2475. socklen_t len=(socklen_t)sizeof(e);
  2476. int result;
  2477. ssize_t max_to_write;
  2478. time_t now = approx_time();
  2479. size_t n_read = 0, n_written = 0;
  2480. tor_assert(!connection_is_listener(conn));
  2481. if (conn->marked_for_close || conn->s < 0)
  2482. return 0; /* do nothing */
  2483. if (conn->in_flushed_some) {
  2484. log_warn(LD_BUG, "called recursively from inside conn->in_flushed_some");
  2485. return 0;
  2486. }
  2487. conn->timestamp_lastwritten = now;
  2488. /* Sometimes, "writable" means "connected". */
  2489. if (connection_state_is_connecting(conn)) {
  2490. if (getsockopt(conn->s, SOL_SOCKET, SO_ERROR, (void*)&e, &len) < 0) {
  2491. log_warn(LD_BUG,
  2492. "getsockopt() syscall failed?! Please report to tor-ops.");
  2493. if (CONN_IS_EDGE(conn))
  2494. connection_edge_end_errno(TO_EDGE_CONN(conn));
  2495. connection_mark_for_close(conn);
  2496. return -1;
  2497. }
  2498. if (e) {
  2499. /* some sort of error, but maybe just inprogress still */
  2500. if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
  2501. log_info(LD_NET,"in-progress connect failed. Removing. (%s)",
  2502. tor_socket_strerror(e));
  2503. if (CONN_IS_EDGE(conn))
  2504. connection_edge_end_errno(TO_EDGE_CONN(conn));
  2505. if (conn->type == CONN_TYPE_OR)
  2506. connection_or_connect_failed(TO_OR_CONN(conn),
  2507. errno_to_orconn_end_reason(e),
  2508. tor_socket_strerror(e));
  2509. connection_close_immediate(conn);
  2510. connection_mark_for_close(conn);
  2511. return -1;
  2512. } else {
  2513. return 0; /* no change, see if next time is better */
  2514. }
  2515. }
  2516. /* The connection is successful. */
  2517. if (connection_finished_connecting(conn)<0)
  2518. return -1;
  2519. }
  2520. max_to_write = force ? (ssize_t)conn->outbuf_flushlen
  2521. : connection_bucket_write_limit(conn, now);
  2522. if (connection_speaks_cells(conn) &&
  2523. conn->state > OR_CONN_STATE_PROXY_HANDSHAKING) {
  2524. or_connection_t *or_conn = TO_OR_CONN(conn);
  2525. if (conn->state == OR_CONN_STATE_TLS_HANDSHAKING ||
  2526. conn->state == OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING) {
  2527. connection_stop_writing(conn);
  2528. if (connection_tls_continue_handshake(or_conn) < 0) {
  2529. /* Don't flush; connection is dead. */
  2530. connection_close_immediate(conn);
  2531. connection_mark_for_close(conn);
  2532. return -1;
  2533. }
  2534. return 0;
  2535. } else if (conn->state == OR_CONN_STATE_TLS_SERVER_RENEGOTIATING) {
  2536. return connection_handle_read(conn);
  2537. }
  2538. /* else open, or closing */
  2539. result = flush_buf_tls(or_conn->tls, conn->outbuf,
  2540. max_to_write, &conn->outbuf_flushlen);
  2541. /* If we just flushed the last bytes, check if this tunneled dir
  2542. * request is done. */
  2543. if (buf_datalen(conn->outbuf) == 0 && conn->dirreq_id)
  2544. geoip_change_dirreq_state(conn->dirreq_id, DIRREQ_TUNNELED,
  2545. DIRREQ_OR_CONN_BUFFER_FLUSHED);
  2546. switch (result) {
  2547. CASE_TOR_TLS_ERROR_ANY:
  2548. case TOR_TLS_CLOSE:
  2549. log_info(LD_NET,result!=TOR_TLS_CLOSE?
  2550. "tls error. breaking.":"TLS connection closed on flush");
  2551. /* Don't flush; connection is dead. */
  2552. connection_close_immediate(conn);
  2553. connection_mark_for_close(conn);
  2554. return -1;
  2555. case TOR_TLS_WANTWRITE:
  2556. log_debug(LD_NET,"wanted write.");
  2557. /* we're already writing */
  2558. return 0;
  2559. case TOR_TLS_WANTREAD:
  2560. /* Make sure to avoid a loop if the receive buckets are empty. */
  2561. log_debug(LD_NET,"wanted read.");
  2562. if (!connection_is_reading(conn)) {
  2563. connection_stop_writing(conn);
  2564. conn->write_blocked_on_bw = 1;
  2565. /* we'll start reading again when we get more tokens in our
  2566. * read bucket; then we'll start writing again too.
  2567. */
  2568. }
  2569. /* else no problem, we're already reading */
  2570. return 0;
  2571. /* case TOR_TLS_DONE:
  2572. * for TOR_TLS_DONE, fall through to check if the flushlen
  2573. * is empty, so we can stop writing.
  2574. */
  2575. }
  2576. tor_tls_get_n_raw_bytes(or_conn->tls, &n_read, &n_written);
  2577. log_debug(LD_GENERAL, "After TLS write of %d: %ld read, %ld written",
  2578. result, (long)n_read, (long)n_written);
  2579. } else {
  2580. CONN_LOG_PROTECT(conn,
  2581. result = flush_buf(conn->s, conn->outbuf,
  2582. max_to_write, &conn->outbuf_flushlen));
  2583. if (result < 0) {
  2584. if (CONN_IS_EDGE(conn))
  2585. connection_edge_end_errno(TO_EDGE_CONN(conn));
  2586. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  2587. connection_mark_for_close(conn);
  2588. return -1;
  2589. }
  2590. n_written = (size_t) result;
  2591. }
  2592. if (n_written && conn->type == CONN_TYPE_AP) {
  2593. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  2594. /* Check for overflow: */
  2595. if (PREDICT_LIKELY(UINT32_MAX - edge_conn->n_written > n_written))
  2596. edge_conn->n_written += (int)n_written;
  2597. else
  2598. edge_conn->n_written = UINT32_MAX;
  2599. }
  2600. connection_buckets_decrement(conn, approx_time(), n_read, n_written);
  2601. if (result > 0) {
  2602. /* If we wrote any bytes from our buffer, then call the appropriate
  2603. * functions. */
  2604. if (connection_flushed_some(conn) < 0)
  2605. connection_mark_for_close(conn);
  2606. }
  2607. if (!connection_wants_to_flush(conn)) { /* it's done flushing */
  2608. if (connection_finished_flushing(conn) < 0) {
  2609. /* already marked */
  2610. return -1;
  2611. }
  2612. return 0;
  2613. }
  2614. /* Call even if result is 0, since the global write bucket may
  2615. * have reached 0 on a different conn, and this guy needs to
  2616. * know to stop writing. */
  2617. connection_consider_empty_write_buckets(conn);
  2618. if (n_read > 0 && connection_is_reading(conn))
  2619. connection_consider_empty_read_buckets(conn);
  2620. return 0;
  2621. }
  2622. int
  2623. connection_handle_write(connection_t *conn, int force)
  2624. {
  2625. int res;
  2626. tor_gettimeofday_cache_clear();
  2627. res = connection_handle_write_impl(conn, force);
  2628. return res;
  2629. }
  2630. /** OpenSSL TLS record size is 16383; this is close. The goal here is to
  2631. * push data out as soon as we know there's enough for a TLS record, so
  2632. * during periods of high load we won't read entire megabytes from
  2633. * input before pushing any data out. It also has the feature of not
  2634. * growing huge outbufs unless something is slow. */
  2635. #define MIN_TLS_FLUSHLEN 15872
  2636. /** Append <b>len</b> bytes of <b>string</b> onto <b>conn</b>'s
  2637. * outbuf, and ask it to start writing.
  2638. *
  2639. * If <b>zlib</b> is nonzero, this is a directory connection that should get
  2640. * its contents compressed or decompressed as they're written. If zlib is
  2641. * negative, this is the last data to be compressed, and the connection's zlib
  2642. * state should be flushed.
  2643. *
  2644. * If it's an OR conn and an entire TLS record is ready, then try to
  2645. * flush the record now. Similarly, if it's a local control connection
  2646. * and a 64k chunk is ready, try to flush it all, so we don't end up with
  2647. * many megabytes of controller info queued at once.
  2648. */
  2649. void
  2650. _connection_write_to_buf_impl(const char *string, size_t len,
  2651. connection_t *conn, int zlib)
  2652. {
  2653. /* XXXX This function really needs to return -1 on failure. */
  2654. int r;
  2655. size_t old_datalen;
  2656. if (!len && !(zlib<0))
  2657. return;
  2658. /* if it's marked for close, only allow write if we mean to flush it */
  2659. if (conn->marked_for_close && !conn->hold_open_until_flushed)
  2660. return;
  2661. old_datalen = buf_datalen(conn->outbuf);
  2662. if (zlib) {
  2663. dir_connection_t *dir_conn = TO_DIR_CONN(conn);
  2664. int done = zlib < 0;
  2665. CONN_LOG_PROTECT(conn, r = write_to_buf_zlib(conn->outbuf,
  2666. dir_conn->zlib_state,
  2667. string, len, done));
  2668. } else {
  2669. CONN_LOG_PROTECT(conn, r = write_to_buf(string, len, conn->outbuf));
  2670. }
  2671. if (r < 0) {
  2672. if (CONN_IS_EDGE(conn)) {
  2673. /* if it failed, it means we have our package/delivery windows set
  2674. wrong compared to our max outbuf size. close the whole circuit. */
  2675. log_warn(LD_NET,
  2676. "write_to_buf failed. Closing circuit (fd %d).", conn->s);
  2677. circuit_mark_for_close(circuit_get_by_edge_conn(TO_EDGE_CONN(conn)),
  2678. END_CIRC_REASON_INTERNAL);
  2679. } else {
  2680. log_warn(LD_NET,
  2681. "write_to_buf failed. Closing connection (fd %d).", conn->s);
  2682. connection_mark_for_close(conn);
  2683. }
  2684. return;
  2685. }
  2686. connection_start_writing(conn);
  2687. if (zlib) {
  2688. conn->outbuf_flushlen += buf_datalen(conn->outbuf) - old_datalen;
  2689. } else {
  2690. ssize_t extra = 0;
  2691. conn->outbuf_flushlen += len;
  2692. /* Should we try flushing the outbuf now? */
  2693. if (conn->in_flushed_some) {
  2694. /* Don't flush the outbuf when the reason we're writing more stuff is
  2695. * _because_ we flushed the outbuf. That's unfair. */
  2696. return;
  2697. }
  2698. if (conn->type == CONN_TYPE_OR &&
  2699. conn->outbuf_flushlen-len < MIN_TLS_FLUSHLEN &&
  2700. conn->outbuf_flushlen >= MIN_TLS_FLUSHLEN) {
  2701. /* We just pushed outbuf_flushlen to MIN_TLS_FLUSHLEN or above;
  2702. * we can send out a full TLS frame now if we like. */
  2703. extra = conn->outbuf_flushlen - MIN_TLS_FLUSHLEN;
  2704. conn->outbuf_flushlen = MIN_TLS_FLUSHLEN;
  2705. } else if (conn->type == CONN_TYPE_CONTROL &&
  2706. !connection_is_rate_limited(conn) &&
  2707. conn->outbuf_flushlen-len < 1<<16 &&
  2708. conn->outbuf_flushlen >= 1<<16) {
  2709. /* just try to flush all of it */
  2710. } else
  2711. return; /* no need to try flushing */
  2712. if (connection_handle_write(conn, 0) < 0) {
  2713. if (!conn->marked_for_close) {
  2714. /* this connection is broken. remove it. */
  2715. log_warn(LD_BUG, "unhandled error on write for "
  2716. "conn (type %d, fd %d); removing",
  2717. conn->type, conn->s);
  2718. tor_fragile_assert();
  2719. /* do a close-immediate here, so we don't try to flush */
  2720. connection_close_immediate(conn);
  2721. }
  2722. return;
  2723. }
  2724. if (extra) {
  2725. conn->outbuf_flushlen += extra;
  2726. connection_start_writing(conn);
  2727. }
  2728. }
  2729. }
  2730. /** Return a connection with given type, address, port, and purpose;
  2731. * or NULL if no such connection exists. */
  2732. connection_t *
  2733. connection_get_by_type_addr_port_purpose(int type,
  2734. const tor_addr_t *addr, uint16_t port,
  2735. int purpose)
  2736. {
  2737. smartlist_t *conns = get_connection_array();
  2738. SMARTLIST_FOREACH(conns, connection_t *, conn,
  2739. {
  2740. if (conn->type == type &&
  2741. tor_addr_eq(&conn->addr, addr) &&
  2742. conn->port == port &&
  2743. conn->purpose == purpose &&
  2744. !conn->marked_for_close)
  2745. return conn;
  2746. });
  2747. return NULL;
  2748. }
  2749. /** Return the stream with id <b>id</b> if it is not already marked for
  2750. * close.
  2751. */
  2752. connection_t *
  2753. connection_get_by_global_id(uint64_t id)
  2754. {
  2755. smartlist_t *conns = get_connection_array();
  2756. SMARTLIST_FOREACH(conns, connection_t *, conn,
  2757. {
  2758. if (conn->global_identifier == id)
  2759. return conn;
  2760. });
  2761. return NULL;
  2762. }
  2763. /** Return a connection of type <b>type</b> that is not marked for close.
  2764. */
  2765. connection_t *
  2766. connection_get_by_type(int type)
  2767. {
  2768. smartlist_t *conns = get_connection_array();
  2769. SMARTLIST_FOREACH(conns, connection_t *, conn,
  2770. {
  2771. if (conn->type == type && !conn->marked_for_close)
  2772. return conn;
  2773. });
  2774. return NULL;
  2775. }
  2776. /** Return a connection of type <b>type</b> that is in state <b>state</b>,
  2777. * and that is not marked for close.
  2778. */
  2779. connection_t *
  2780. connection_get_by_type_state(int type, int state)
  2781. {
  2782. smartlist_t *conns = get_connection_array();
  2783. SMARTLIST_FOREACH(conns, connection_t *, conn,
  2784. {
  2785. if (conn->type == type && conn->state == state && !conn->marked_for_close)
  2786. return conn;
  2787. });
  2788. return NULL;
  2789. }
  2790. /** Return a connection of type <b>type</b> that has rendquery equal
  2791. * to <b>rendquery</b>, and that is not marked for close. If state
  2792. * is non-zero, conn must be of that state too.
  2793. */
  2794. connection_t *
  2795. connection_get_by_type_state_rendquery(int type, int state,
  2796. const char *rendquery)
  2797. {
  2798. smartlist_t *conns = get_connection_array();
  2799. tor_assert(type == CONN_TYPE_DIR ||
  2800. type == CONN_TYPE_AP || type == CONN_TYPE_EXIT);
  2801. tor_assert(rendquery);
  2802. SMARTLIST_FOREACH(conns, connection_t *, conn,
  2803. {
  2804. if (conn->type == type &&
  2805. !conn->marked_for_close &&
  2806. (!state || state == conn->state)) {
  2807. if (type == CONN_TYPE_DIR &&
  2808. TO_DIR_CONN(conn)->rend_data &&
  2809. !rend_cmp_service_ids(rendquery,
  2810. TO_DIR_CONN(conn)->rend_data->onion_address))
  2811. return conn;
  2812. else if (CONN_IS_EDGE(conn) &&
  2813. TO_EDGE_CONN(conn)->rend_data &&
  2814. !rend_cmp_service_ids(rendquery,
  2815. TO_EDGE_CONN(conn)->rend_data->onion_address))
  2816. return conn;
  2817. }
  2818. });
  2819. return NULL;
  2820. }
  2821. /** Return an open, non-marked connection of a given type and purpose, or NULL
  2822. * if no such connection exists. */
  2823. connection_t *
  2824. connection_get_by_type_purpose(int type, int purpose)
  2825. {
  2826. smartlist_t *conns = get_connection_array();
  2827. SMARTLIST_FOREACH(conns, connection_t *, conn,
  2828. {
  2829. if (conn->type == type &&
  2830. !conn->marked_for_close &&
  2831. (purpose == conn->purpose))
  2832. return conn;
  2833. });
  2834. return NULL;
  2835. }
  2836. /** Return 1 if <b>conn</b> is a listener conn, else return 0. */
  2837. int
  2838. connection_is_listener(connection_t *conn)
  2839. {
  2840. if (conn->type == CONN_TYPE_OR_LISTENER ||
  2841. conn->type == CONN_TYPE_AP_LISTENER ||
  2842. conn->type == CONN_TYPE_AP_TRANS_LISTENER ||
  2843. conn->type == CONN_TYPE_AP_DNS_LISTENER ||
  2844. conn->type == CONN_TYPE_AP_NATD_LISTENER ||
  2845. conn->type == CONN_TYPE_DIR_LISTENER ||
  2846. conn->type == CONN_TYPE_CONTROL_LISTENER)
  2847. return 1;
  2848. return 0;
  2849. }
  2850. /** Return 1 if <b>conn</b> is in state "open" and is not marked
  2851. * for close, else return 0.
  2852. */
  2853. int
  2854. connection_state_is_open(connection_t *conn)
  2855. {
  2856. tor_assert(conn);
  2857. if (conn->marked_for_close)
  2858. return 0;
  2859. if ((conn->type == CONN_TYPE_OR && conn->state == OR_CONN_STATE_OPEN) ||
  2860. (conn->type == CONN_TYPE_AP && conn->state == AP_CONN_STATE_OPEN) ||
  2861. (conn->type == CONN_TYPE_EXIT && conn->state == EXIT_CONN_STATE_OPEN) ||
  2862. (conn->type == CONN_TYPE_CONTROL &&
  2863. conn->state == CONTROL_CONN_STATE_OPEN))
  2864. return 1;
  2865. return 0;
  2866. }
  2867. /** Return 1 if conn is in 'connecting' state, else return 0. */
  2868. int
  2869. connection_state_is_connecting(connection_t *conn)
  2870. {
  2871. tor_assert(conn);
  2872. if (conn->marked_for_close)
  2873. return 0;
  2874. switch (conn->type)
  2875. {
  2876. case CONN_TYPE_OR:
  2877. return conn->state == OR_CONN_STATE_CONNECTING;
  2878. case CONN_TYPE_EXIT:
  2879. return conn->state == EXIT_CONN_STATE_CONNECTING;
  2880. case CONN_TYPE_DIR:
  2881. return conn->state == DIR_CONN_STATE_CONNECTING;
  2882. }
  2883. return 0;
  2884. }
  2885. /** Allocates a base64'ed authenticator for use in http or https
  2886. * auth, based on the input string <b>authenticator</b>. Returns it
  2887. * if success, else returns NULL. */
  2888. char *
  2889. alloc_http_authenticator(const char *authenticator)
  2890. {
  2891. /* an authenticator in Basic authentication
  2892. * is just the string "username:password" */
  2893. const size_t authenticator_length = strlen(authenticator);
  2894. /* The base64_encode function needs a minimum buffer length
  2895. * of 66 bytes. */
  2896. const size_t base64_authenticator_length = (authenticator_length/48+1)*66;
  2897. char *base64_authenticator = tor_malloc(base64_authenticator_length);
  2898. if (base64_encode(base64_authenticator, base64_authenticator_length,
  2899. authenticator, authenticator_length) < 0) {
  2900. tor_free(base64_authenticator); /* free and set to null */
  2901. } else {
  2902. int i = 0, j = 0;
  2903. int len = strlen(base64_authenticator);
  2904. /* remove all newline occurrences within the string */
  2905. for (i=0; i < len; ++i) {
  2906. if ('\n' != base64_authenticator[i]) {
  2907. base64_authenticator[j] = base64_authenticator[i];
  2908. ++j;
  2909. }
  2910. }
  2911. base64_authenticator[j]='\0';
  2912. }
  2913. return base64_authenticator;
  2914. }
  2915. /** Given a socket handle, check whether the local address (sockname) of the
  2916. * socket is one that we've connected from before. If so, double-check
  2917. * whether our address has changed and we need to generate keys. If we do,
  2918. * call init_keys().
  2919. */
  2920. static void
  2921. client_check_address_changed(int sock)
  2922. {
  2923. uint32_t iface_ip, ip_out; /* host order */
  2924. struct sockaddr_in out_addr;
  2925. socklen_t out_addr_len = (socklen_t) sizeof(out_addr);
  2926. uint32_t *ip; /* host order */
  2927. if (!last_interface_ip)
  2928. get_interface_address(LOG_INFO, &last_interface_ip);
  2929. if (!outgoing_addrs)
  2930. outgoing_addrs = smartlist_create();
  2931. if (getsockname(sock, (struct sockaddr*)&out_addr, &out_addr_len)<0) {
  2932. int e = tor_socket_errno(sock);
  2933. log_warn(LD_NET, "getsockname() to check for address change failed: %s",
  2934. tor_socket_strerror(e));
  2935. return;
  2936. }
  2937. /* If we've used this address previously, we're okay. */
  2938. ip_out = ntohl(out_addr.sin_addr.s_addr);
  2939. SMARTLIST_FOREACH(outgoing_addrs, uint32_t*, ip_ptr,
  2940. if (*ip_ptr == ip_out) return;
  2941. );
  2942. /* Uh-oh. We haven't connected from this address before. Has the interface
  2943. * address changed? */
  2944. if (get_interface_address(LOG_INFO, &iface_ip)<0)
  2945. return;
  2946. ip = tor_malloc(sizeof(uint32_t));
  2947. *ip = ip_out;
  2948. if (iface_ip == last_interface_ip) {
  2949. /* Nope, it hasn't changed. Add this address to the list. */
  2950. smartlist_add(outgoing_addrs, ip);
  2951. } else {
  2952. /* The interface changed. We're a client, so we need to regenerate our
  2953. * keys. First, reset the state. */
  2954. log(LOG_NOTICE, LD_NET, "Our IP address has changed. Rotating keys...");
  2955. last_interface_ip = iface_ip;
  2956. SMARTLIST_FOREACH(outgoing_addrs, void*, ip_ptr, tor_free(ip_ptr));
  2957. smartlist_clear(outgoing_addrs);
  2958. smartlist_add(outgoing_addrs, ip);
  2959. /* Okay, now change our keys. */
  2960. ip_address_changed(1);
  2961. }
  2962. }
  2963. /** Some systems have limited system buffers for recv and xmit on
  2964. * sockets allocated in a virtual server or similar environment. For a Tor
  2965. * server this can produce the "Error creating network socket: No buffer
  2966. * space available" error once all available TCP buffer space is consumed.
  2967. * This method will attempt to constrain the buffers allocated for the socket
  2968. * to the desired size to stay below system TCP buffer limits.
  2969. */
  2970. static void
  2971. set_constrained_socket_buffers(int sock, int size)
  2972. {
  2973. void *sz = (void*)&size;
  2974. socklen_t sz_sz = (socklen_t) sizeof(size);
  2975. if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, sz, sz_sz) < 0) {
  2976. int e = tor_socket_errno(sock);
  2977. log_warn(LD_NET, "setsockopt() to constrain send "
  2978. "buffer to %d bytes failed: %s", size, tor_socket_strerror(e));
  2979. }
  2980. if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, sz, sz_sz) < 0) {
  2981. int e = tor_socket_errno(sock);
  2982. log_warn(LD_NET, "setsockopt() to constrain recv "
  2983. "buffer to %d bytes failed: %s", size, tor_socket_strerror(e));
  2984. }
  2985. }
  2986. /** Process new bytes that have arrived on conn-\>inbuf.
  2987. *
  2988. * This function just passes conn to the connection-specific
  2989. * connection_*_process_inbuf() function. It also passes in
  2990. * package_partial if wanted.
  2991. */
  2992. static int
  2993. connection_process_inbuf(connection_t *conn, int package_partial)
  2994. {
  2995. tor_assert(conn);
  2996. switch (conn->type) {
  2997. case CONN_TYPE_OR:
  2998. return connection_or_process_inbuf(TO_OR_CONN(conn));
  2999. case CONN_TYPE_EXIT:
  3000. case CONN_TYPE_AP:
  3001. return connection_edge_process_inbuf(TO_EDGE_CONN(conn),
  3002. package_partial);
  3003. case CONN_TYPE_DIR:
  3004. return connection_dir_process_inbuf(TO_DIR_CONN(conn));
  3005. case CONN_TYPE_CPUWORKER:
  3006. return connection_cpu_process_inbuf(conn);
  3007. case CONN_TYPE_CONTROL:
  3008. return connection_control_process_inbuf(TO_CONTROL_CONN(conn));
  3009. default:
  3010. log_err(LD_BUG,"got unexpected conn type %d.", conn->type);
  3011. tor_fragile_assert();
  3012. return -1;
  3013. }
  3014. }
  3015. /** Called whenever we've written data on a connection. */
  3016. static int
  3017. connection_flushed_some(connection_t *conn)
  3018. {
  3019. int r = 0;
  3020. tor_assert(!conn->in_flushed_some);
  3021. conn->in_flushed_some = 1;
  3022. if (conn->type == CONN_TYPE_DIR &&
  3023. conn->state == DIR_CONN_STATE_SERVER_WRITING) {
  3024. r = connection_dirserv_flushed_some(TO_DIR_CONN(conn));
  3025. } else if (conn->type == CONN_TYPE_OR) {
  3026. r = connection_or_flushed_some(TO_OR_CONN(conn));
  3027. } else if (CONN_IS_EDGE(conn)) {
  3028. r = connection_edge_flushed_some(TO_EDGE_CONN(conn));
  3029. }
  3030. conn->in_flushed_some = 0;
  3031. return r;
  3032. }
  3033. /** We just finished flushing bytes from conn-\>outbuf, and there
  3034. * are no more bytes remaining.
  3035. *
  3036. * This function just passes conn to the connection-specific
  3037. * connection_*_finished_flushing() function.
  3038. */
  3039. static int
  3040. connection_finished_flushing(connection_t *conn)
  3041. {
  3042. tor_assert(conn);
  3043. /* If the connection is closed, don't try to do anything more here. */
  3044. if (CONN_IS_CLOSED(conn))
  3045. return 0;
  3046. // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
  3047. switch (conn->type) {
  3048. case CONN_TYPE_OR:
  3049. return connection_or_finished_flushing(TO_OR_CONN(conn));
  3050. case CONN_TYPE_AP:
  3051. case CONN_TYPE_EXIT:
  3052. return connection_edge_finished_flushing(TO_EDGE_CONN(conn));
  3053. case CONN_TYPE_DIR:
  3054. return connection_dir_finished_flushing(TO_DIR_CONN(conn));
  3055. case CONN_TYPE_CPUWORKER:
  3056. return connection_cpu_finished_flushing(conn);
  3057. case CONN_TYPE_CONTROL:
  3058. return connection_control_finished_flushing(TO_CONTROL_CONN(conn));
  3059. default:
  3060. log_err(LD_BUG,"got unexpected conn type %d.", conn->type);
  3061. tor_fragile_assert();
  3062. return -1;
  3063. }
  3064. }
  3065. /** Called when our attempt to connect() to another server has just
  3066. * succeeded.
  3067. *
  3068. * This function just passes conn to the connection-specific
  3069. * connection_*_finished_connecting() function.
  3070. */
  3071. static int
  3072. connection_finished_connecting(connection_t *conn)
  3073. {
  3074. tor_assert(conn);
  3075. switch (conn->type)
  3076. {
  3077. case CONN_TYPE_OR:
  3078. return connection_or_finished_connecting(TO_OR_CONN(conn));
  3079. case CONN_TYPE_EXIT:
  3080. return connection_edge_finished_connecting(TO_EDGE_CONN(conn));
  3081. case CONN_TYPE_DIR:
  3082. return connection_dir_finished_connecting(TO_DIR_CONN(conn));
  3083. default:
  3084. log_err(LD_BUG,"got unexpected conn type %d.", conn->type);
  3085. tor_fragile_assert();
  3086. return -1;
  3087. }
  3088. }
  3089. /** Callback: invoked when a connection reaches an EOF event. */
  3090. static int
  3091. connection_reached_eof(connection_t *conn)
  3092. {
  3093. switch (conn->type) {
  3094. case CONN_TYPE_OR:
  3095. return connection_or_reached_eof(TO_OR_CONN(conn));
  3096. case CONN_TYPE_AP:
  3097. case CONN_TYPE_EXIT:
  3098. return connection_edge_reached_eof(TO_EDGE_CONN(conn));
  3099. case CONN_TYPE_DIR:
  3100. return connection_dir_reached_eof(TO_DIR_CONN(conn));
  3101. case CONN_TYPE_CPUWORKER:
  3102. return connection_cpu_reached_eof(conn);
  3103. case CONN_TYPE_CONTROL:
  3104. return connection_control_reached_eof(TO_CONTROL_CONN(conn));
  3105. default:
  3106. log_err(LD_BUG,"got unexpected conn type %d.", conn->type);
  3107. tor_fragile_assert();
  3108. return -1;
  3109. }
  3110. }
  3111. /** Log how many bytes are used by buffers of different kinds and sizes. */
  3112. void
  3113. connection_dump_buffer_mem_stats(int severity)
  3114. {
  3115. uint64_t used_by_type[_CONN_TYPE_MAX+1];
  3116. uint64_t alloc_by_type[_CONN_TYPE_MAX+1];
  3117. int n_conns_by_type[_CONN_TYPE_MAX+1];
  3118. uint64_t total_alloc = 0;
  3119. uint64_t total_used = 0;
  3120. int i;
  3121. smartlist_t *conns = get_connection_array();
  3122. memset(used_by_type, 0, sizeof(used_by_type));
  3123. memset(alloc_by_type, 0, sizeof(alloc_by_type));
  3124. memset(n_conns_by_type, 0, sizeof(n_conns_by_type));
  3125. SMARTLIST_FOREACH(conns, connection_t *, c,
  3126. {
  3127. int tp = c->type;
  3128. ++n_conns_by_type[tp];
  3129. if (c->inbuf) {
  3130. used_by_type[tp] += buf_datalen(c->inbuf);
  3131. alloc_by_type[tp] += buf_allocation(c->inbuf);
  3132. }
  3133. if (c->outbuf) {
  3134. used_by_type[tp] += buf_datalen(c->outbuf);
  3135. alloc_by_type[tp] += buf_allocation(c->outbuf);
  3136. }
  3137. });
  3138. for (i=0; i <= _CONN_TYPE_MAX; ++i) {
  3139. total_used += used_by_type[i];
  3140. total_alloc += alloc_by_type[i];
  3141. }
  3142. log(severity, LD_GENERAL,
  3143. "In buffers for %d connections: "U64_FORMAT" used/"U64_FORMAT" allocated",
  3144. smartlist_len(conns),
  3145. U64_PRINTF_ARG(total_used), U64_PRINTF_ARG(total_alloc));
  3146. for (i=_CONN_TYPE_MIN; i <= _CONN_TYPE_MAX; ++i) {
  3147. if (!n_conns_by_type[i])
  3148. continue;
  3149. log(severity, LD_GENERAL,
  3150. " For %d %s connections: "U64_FORMAT" used/"U64_FORMAT" allocated",
  3151. n_conns_by_type[i], conn_type_to_string(i),
  3152. U64_PRINTF_ARG(used_by_type[i]), U64_PRINTF_ARG(alloc_by_type[i]));
  3153. }
  3154. }
  3155. /** Verify that connection <b>conn</b> has all of its invariants
  3156. * correct. Trigger an assert if anything is invalid.
  3157. */
  3158. void
  3159. assert_connection_ok(connection_t *conn, time_t now)
  3160. {
  3161. (void) now; /* XXXX unused. */
  3162. tor_assert(conn);
  3163. tor_assert(conn->type >= _CONN_TYPE_MIN);
  3164. tor_assert(conn->type <= _CONN_TYPE_MAX);
  3165. switch (conn->type) {
  3166. case CONN_TYPE_OR:
  3167. tor_assert(conn->magic == OR_CONNECTION_MAGIC);
  3168. break;
  3169. case CONN_TYPE_AP:
  3170. case CONN_TYPE_EXIT:
  3171. tor_assert(conn->magic == EDGE_CONNECTION_MAGIC);
  3172. break;
  3173. case CONN_TYPE_DIR:
  3174. tor_assert(conn->magic == DIR_CONNECTION_MAGIC);
  3175. break;
  3176. case CONN_TYPE_CONTROL:
  3177. tor_assert(conn->magic == CONTROL_CONNECTION_MAGIC);
  3178. break;
  3179. default:
  3180. tor_assert(conn->magic == BASE_CONNECTION_MAGIC);
  3181. break;
  3182. }
  3183. if (conn->linked_conn) {
  3184. tor_assert(conn->linked_conn->linked_conn == conn);
  3185. tor_assert(conn->linked);
  3186. }
  3187. if (conn->linked)
  3188. tor_assert(conn->s < 0);
  3189. if (conn->outbuf_flushlen > 0) {
  3190. tor_assert(connection_is_writing(conn) || conn->write_blocked_on_bw ||
  3191. (CONN_IS_EDGE(conn) && TO_EDGE_CONN(conn)->edge_blocked_on_circ));
  3192. }
  3193. if (conn->hold_open_until_flushed)
  3194. tor_assert(conn->marked_for_close);
  3195. /* XXXX check: read_blocked_on_bw, write_blocked_on_bw, s, conn_array_index,
  3196. * marked_for_close. */
  3197. /* buffers */
  3198. if (!connection_is_listener(conn)) {
  3199. assert_buf_ok(conn->inbuf);
  3200. assert_buf_ok(conn->outbuf);
  3201. }
  3202. if (conn->type == CONN_TYPE_OR) {
  3203. or_connection_t *or_conn = TO_OR_CONN(conn);
  3204. if (conn->state == OR_CONN_STATE_OPEN) {
  3205. /* tor_assert(conn->bandwidth > 0); */
  3206. /* the above isn't necessarily true: if we just did a TLS
  3207. * handshake but we didn't recognize the other peer, or it
  3208. * gave a bad cert/etc, then we won't have assigned bandwidth,
  3209. * yet it will be open. -RD
  3210. */
  3211. // tor_assert(conn->read_bucket >= 0);
  3212. }
  3213. // tor_assert(conn->addr && conn->port);
  3214. tor_assert(conn->address);
  3215. if (conn->state > OR_CONN_STATE_PROXY_HANDSHAKING)
  3216. tor_assert(or_conn->tls);
  3217. }
  3218. if (CONN_IS_EDGE(conn)) {
  3219. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  3220. if (edge_conn->chosen_exit_optional || edge_conn->chosen_exit_retries) {
  3221. tor_assert(conn->type == CONN_TYPE_AP);
  3222. tor_assert(edge_conn->chosen_exit_name);
  3223. }
  3224. /* XXX unchecked: package window, deliver window. */
  3225. if (conn->type == CONN_TYPE_AP) {
  3226. tor_assert(edge_conn->socks_request);
  3227. if (conn->state == AP_CONN_STATE_OPEN) {
  3228. tor_assert(edge_conn->socks_request->has_finished);
  3229. if (!conn->marked_for_close) {
  3230. tor_assert(edge_conn->cpath_layer);
  3231. assert_cpath_layer_ok(edge_conn->cpath_layer);
  3232. }
  3233. }
  3234. }
  3235. if (conn->type == CONN_TYPE_EXIT) {
  3236. tor_assert(conn->purpose == EXIT_PURPOSE_CONNECT ||
  3237. conn->purpose == EXIT_PURPOSE_RESOLVE);
  3238. }
  3239. } else if (conn->type == CONN_TYPE_DIR) {
  3240. } else {
  3241. /* Purpose is only used for dir and exit types currently */
  3242. tor_assert(!conn->purpose);
  3243. }
  3244. switch (conn->type)
  3245. {
  3246. case CONN_TYPE_OR_LISTENER:
  3247. case CONN_TYPE_AP_LISTENER:
  3248. case CONN_TYPE_AP_TRANS_LISTENER:
  3249. case CONN_TYPE_AP_NATD_LISTENER:
  3250. case CONN_TYPE_DIR_LISTENER:
  3251. case CONN_TYPE_CONTROL_LISTENER:
  3252. case CONN_TYPE_AP_DNS_LISTENER:
  3253. tor_assert(conn->state == LISTENER_STATE_READY);
  3254. break;
  3255. case CONN_TYPE_OR:
  3256. tor_assert(conn->state >= _OR_CONN_STATE_MIN);
  3257. tor_assert(conn->state <= _OR_CONN_STATE_MAX);
  3258. tor_assert(TO_OR_CONN(conn)->n_circuits >= 0);
  3259. break;
  3260. case CONN_TYPE_EXIT:
  3261. tor_assert(conn->state >= _EXIT_CONN_STATE_MIN);
  3262. tor_assert(conn->state <= _EXIT_CONN_STATE_MAX);
  3263. tor_assert(conn->purpose >= _EXIT_PURPOSE_MIN);
  3264. tor_assert(conn->purpose <= _EXIT_PURPOSE_MAX);
  3265. break;
  3266. case CONN_TYPE_AP:
  3267. tor_assert(conn->state >= _AP_CONN_STATE_MIN);
  3268. tor_assert(conn->state <= _AP_CONN_STATE_MAX);
  3269. tor_assert(TO_EDGE_CONN(conn)->socks_request);
  3270. break;
  3271. case CONN_TYPE_DIR:
  3272. tor_assert(conn->state >= _DIR_CONN_STATE_MIN);
  3273. tor_assert(conn->state <= _DIR_CONN_STATE_MAX);
  3274. tor_assert(conn->purpose >= _DIR_PURPOSE_MIN);
  3275. tor_assert(conn->purpose <= _DIR_PURPOSE_MAX);
  3276. break;
  3277. case CONN_TYPE_CPUWORKER:
  3278. tor_assert(conn->state >= _CPUWORKER_STATE_MIN);
  3279. tor_assert(conn->state <= _CPUWORKER_STATE_MAX);
  3280. break;
  3281. case CONN_TYPE_CONTROL:
  3282. tor_assert(conn->state >= _CONTROL_CONN_STATE_MIN);
  3283. tor_assert(conn->state <= _CONTROL_CONN_STATE_MAX);
  3284. break;
  3285. default:
  3286. tor_assert(0);
  3287. }
  3288. }