connection.c 145 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427
  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-2013, 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. /*
  14. * Define this so we get channel internal functions, since we're implementing
  15. * part of a subclass (channel_tls_t).
  16. */
  17. #define TOR_CHANNEL_INTERNAL_
  18. #include "channel.h"
  19. #include "channeltls.h"
  20. #include "circuitbuild.h"
  21. #include "circuitlist.h"
  22. #include "circuituse.h"
  23. #include "config.h"
  24. #include "connection.h"
  25. #include "connection_edge.h"
  26. #include "connection_or.h"
  27. #include "control.h"
  28. #include "cpuworker.h"
  29. #include "directory.h"
  30. #include "dirserv.h"
  31. #include "dns.h"
  32. #include "dnsserv.h"
  33. #include "entrynodes.h"
  34. #include "geoip.h"
  35. #include "main.h"
  36. #include "policies.h"
  37. #include "reasons.h"
  38. #include "relay.h"
  39. #include "rendclient.h"
  40. #include "rendcommon.h"
  41. #include "rephist.h"
  42. #include "router.h"
  43. #include "transports.h"
  44. #include "routerparse.h"
  45. #ifdef USE_BUFFEREVENTS
  46. #include <event2/event.h>
  47. #endif
  48. #ifdef HAVE_PWD_H
  49. #include <pwd.h>
  50. #endif
  51. static connection_t *connection_listener_new(
  52. const struct sockaddr *listensockaddr,
  53. socklen_t listensocklen, int type,
  54. const char *address,
  55. const port_cfg_t *portcfg);
  56. static void connection_init(time_t now, connection_t *conn, int type,
  57. int socket_family);
  58. static int connection_init_accepted_conn(connection_t *conn,
  59. const listener_connection_t *listener);
  60. static int connection_handle_listener_read(connection_t *conn, int new_type);
  61. #ifndef USE_BUFFEREVENTS
  62. static int connection_bucket_should_increase(int bucket,
  63. or_connection_t *conn);
  64. #endif
  65. static int connection_finished_flushing(connection_t *conn);
  66. static int connection_flushed_some(connection_t *conn);
  67. static int connection_finished_connecting(connection_t *conn);
  68. static int connection_reached_eof(connection_t *conn);
  69. static int connection_read_to_buf(connection_t *conn, ssize_t *max_to_read,
  70. int *socket_error);
  71. static int connection_process_inbuf(connection_t *conn, int package_partial);
  72. static void client_check_address_changed(tor_socket_t sock);
  73. static void set_constrained_socket_buffers(tor_socket_t sock, int size);
  74. static const char *connection_proxy_state_to_string(int state);
  75. static int connection_read_https_proxy_response(connection_t *conn);
  76. static void connection_send_socks5_connect(connection_t *conn);
  77. static const char *proxy_type_to_string(int proxy_type);
  78. static int get_proxy_type(void);
  79. /** The last addresses that our network interface seemed to have been
  80. * binding to. We use this as one way to detect when our IP changes.
  81. *
  82. * XXX024 We should really use the entire list of interfaces here.
  83. **/
  84. static tor_addr_t *last_interface_ipv4 = NULL;
  85. /* DOCDOC last_interface_ipv6 */
  86. static tor_addr_t *last_interface_ipv6 = NULL;
  87. /** A list of tor_addr_t for addresses we've used in outgoing connections.
  88. * Used to detect IP address changes. */
  89. static smartlist_t *outgoing_addrs = NULL;
  90. #define CASE_ANY_LISTENER_TYPE \
  91. case CONN_TYPE_OR_LISTENER: \
  92. case CONN_TYPE_AP_LISTENER: \
  93. case CONN_TYPE_DIR_LISTENER: \
  94. case CONN_TYPE_CONTROL_LISTENER: \
  95. case CONN_TYPE_AP_TRANS_LISTENER: \
  96. case CONN_TYPE_AP_NATD_LISTENER: \
  97. case CONN_TYPE_AP_DNS_LISTENER
  98. /**************************************************************/
  99. /**
  100. * Return the human-readable name for the connection type <b>type</b>
  101. */
  102. const char *
  103. conn_type_to_string(int type)
  104. {
  105. static char buf[64];
  106. switch (type) {
  107. case CONN_TYPE_OR_LISTENER: return "OR listener";
  108. case CONN_TYPE_OR: return "OR";
  109. case CONN_TYPE_EXIT: return "Exit";
  110. case CONN_TYPE_AP_LISTENER: return "Socks listener";
  111. case CONN_TYPE_AP_TRANS_LISTENER:
  112. return "Transparent pf/netfilter listener";
  113. case CONN_TYPE_AP_NATD_LISTENER: return "Transparent natd listener";
  114. case CONN_TYPE_AP_DNS_LISTENER: return "DNS listener";
  115. case CONN_TYPE_AP: return "Socks";
  116. case CONN_TYPE_DIR_LISTENER: return "Directory listener";
  117. case CONN_TYPE_DIR: return "Directory";
  118. case CONN_TYPE_CPUWORKER: return "CPU worker";
  119. case CONN_TYPE_CONTROL_LISTENER: return "Control listener";
  120. case CONN_TYPE_CONTROL: return "Control";
  121. default:
  122. log_warn(LD_BUG, "unknown connection type %d", type);
  123. tor_snprintf(buf, sizeof(buf), "unknown [%d]", type);
  124. return buf;
  125. }
  126. }
  127. /**
  128. * Return the human-readable name for the connection state <b>state</b>
  129. * for the connection type <b>type</b>
  130. */
  131. const char *
  132. conn_state_to_string(int type, int state)
  133. {
  134. static char buf[96];
  135. switch (type) {
  136. CASE_ANY_LISTENER_TYPE:
  137. if (state == LISTENER_STATE_READY)
  138. return "ready";
  139. break;
  140. case CONN_TYPE_OR:
  141. switch (state) {
  142. case OR_CONN_STATE_CONNECTING: return "connect()ing";
  143. case OR_CONN_STATE_PROXY_HANDSHAKING: return "handshaking (proxy)";
  144. case OR_CONN_STATE_TLS_HANDSHAKING: return "handshaking (TLS)";
  145. case OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING:
  146. return "renegotiating (TLS, v2 handshake)";
  147. case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING:
  148. return "waiting for renegotiation or V3 handshake";
  149. case OR_CONN_STATE_OR_HANDSHAKING_V2:
  150. return "handshaking (Tor, v2 handshake)";
  151. case OR_CONN_STATE_OR_HANDSHAKING_V3:
  152. return "handshaking (Tor, v3 handshake)";
  153. case OR_CONN_STATE_OPEN: return "open";
  154. }
  155. break;
  156. case CONN_TYPE_EXIT:
  157. switch (state) {
  158. case EXIT_CONN_STATE_RESOLVING: return "waiting for dest info";
  159. case EXIT_CONN_STATE_CONNECTING: return "connecting";
  160. case EXIT_CONN_STATE_OPEN: return "open";
  161. case EXIT_CONN_STATE_RESOLVEFAILED: return "resolve failed";
  162. }
  163. break;
  164. case CONN_TYPE_AP:
  165. switch (state) {
  166. case AP_CONN_STATE_SOCKS_WAIT: return "waiting for socks info";
  167. case AP_CONN_STATE_NATD_WAIT: return "waiting for natd dest info";
  168. case AP_CONN_STATE_RENDDESC_WAIT: return "waiting for rendezvous desc";
  169. case AP_CONN_STATE_CONTROLLER_WAIT: return "waiting for controller";
  170. case AP_CONN_STATE_CIRCUIT_WAIT: return "waiting for circuit";
  171. case AP_CONN_STATE_CONNECT_WAIT: return "waiting for connect response";
  172. case AP_CONN_STATE_RESOLVE_WAIT: return "waiting for resolve response";
  173. case AP_CONN_STATE_OPEN: return "open";
  174. }
  175. break;
  176. case CONN_TYPE_DIR:
  177. switch (state) {
  178. case DIR_CONN_STATE_CONNECTING: return "connecting";
  179. case DIR_CONN_STATE_CLIENT_SENDING: return "client sending";
  180. case DIR_CONN_STATE_CLIENT_READING: return "client reading";
  181. case DIR_CONN_STATE_CLIENT_FINISHED: return "client finished";
  182. case DIR_CONN_STATE_SERVER_COMMAND_WAIT: return "waiting for command";
  183. case DIR_CONN_STATE_SERVER_WRITING: return "writing";
  184. }
  185. break;
  186. case CONN_TYPE_CPUWORKER:
  187. switch (state) {
  188. case CPUWORKER_STATE_IDLE: return "idle";
  189. case CPUWORKER_STATE_BUSY_ONION: return "busy with onion";
  190. }
  191. break;
  192. case CONN_TYPE_CONTROL:
  193. switch (state) {
  194. case CONTROL_CONN_STATE_OPEN: return "open (protocol v1)";
  195. case CONTROL_CONN_STATE_NEEDAUTH:
  196. return "waiting for authentication (protocol v1)";
  197. }
  198. break;
  199. }
  200. log_warn(LD_BUG, "unknown connection state %d (type %d)", state, type);
  201. tor_snprintf(buf, sizeof(buf),
  202. "unknown state [%d] on unknown [%s] connection",
  203. state, conn_type_to_string(type));
  204. return buf;
  205. }
  206. #ifdef USE_BUFFEREVENTS
  207. /** Return true iff the connection's type is one that can use a
  208. bufferevent-based implementation. */
  209. int
  210. connection_type_uses_bufferevent(connection_t *conn)
  211. {
  212. switch (conn->type) {
  213. case CONN_TYPE_AP:
  214. case CONN_TYPE_EXIT:
  215. case CONN_TYPE_DIR:
  216. case CONN_TYPE_CONTROL:
  217. case CONN_TYPE_OR:
  218. case CONN_TYPE_CPUWORKER:
  219. return 1;
  220. default:
  221. return 0;
  222. }
  223. }
  224. #endif
  225. /** Allocate and return a new dir_connection_t, initialized as by
  226. * connection_init(). */
  227. dir_connection_t *
  228. dir_connection_new(int socket_family)
  229. {
  230. dir_connection_t *dir_conn = tor_malloc_zero(sizeof(dir_connection_t));
  231. connection_init(time(NULL), TO_CONN(dir_conn), CONN_TYPE_DIR, socket_family);
  232. return dir_conn;
  233. }
  234. /** Allocate and return a new or_connection_t, initialized as by
  235. * connection_init().
  236. *
  237. * Set timestamp_last_added_nonpadding to now.
  238. *
  239. * Assign a pseudorandom next_circ_id between 0 and 2**15.
  240. *
  241. * Initialize active_circuit_pqueue.
  242. *
  243. * Set active_circuit_pqueue_last_recalibrated to current cell_ewma tick.
  244. */
  245. or_connection_t *
  246. or_connection_new(int socket_family)
  247. {
  248. or_connection_t *or_conn = tor_malloc_zero(sizeof(or_connection_t));
  249. time_t now = time(NULL);
  250. connection_init(now, TO_CONN(or_conn), CONN_TYPE_OR, socket_family);
  251. or_conn->timestamp_last_added_nonpadding = time(NULL);
  252. return or_conn;
  253. }
  254. /** Allocate and return a new entry_connection_t, initialized as by
  255. * connection_init().
  256. *
  257. * Allocate space to store the socks_request.
  258. */
  259. entry_connection_t *
  260. entry_connection_new(int type, int socket_family)
  261. {
  262. entry_connection_t *entry_conn = tor_malloc_zero(sizeof(entry_connection_t));
  263. tor_assert(type == CONN_TYPE_AP);
  264. connection_init(time(NULL), ENTRY_TO_CONN(entry_conn), type, socket_family);
  265. entry_conn->socks_request = socks_request_new();
  266. /* If this is coming from a listener, we'll set it up based on the listener
  267. * in a little while. Otherwise, we're doing this as a linked connection
  268. * of some kind, and we should set it up here based on the socket family */
  269. if (socket_family == AF_INET)
  270. entry_conn->ipv4_traffic_ok = 1;
  271. else if (socket_family == AF_INET6)
  272. entry_conn->ipv6_traffic_ok = 1;
  273. return entry_conn;
  274. }
  275. /** Allocate and return a new edge_connection_t, initialized as by
  276. * connection_init(). */
  277. edge_connection_t *
  278. edge_connection_new(int type, int socket_family)
  279. {
  280. edge_connection_t *edge_conn = tor_malloc_zero(sizeof(edge_connection_t));
  281. tor_assert(type == CONN_TYPE_EXIT);
  282. connection_init(time(NULL), TO_CONN(edge_conn), type, socket_family);
  283. return edge_conn;
  284. }
  285. /** Allocate and return a new control_connection_t, initialized as by
  286. * connection_init(). */
  287. control_connection_t *
  288. control_connection_new(int socket_family)
  289. {
  290. control_connection_t *control_conn =
  291. tor_malloc_zero(sizeof(control_connection_t));
  292. connection_init(time(NULL),
  293. TO_CONN(control_conn), CONN_TYPE_CONTROL, socket_family);
  294. log_notice(LD_CONTROL, "New control connection opened.");
  295. return control_conn;
  296. }
  297. /** Allocate and return a new listener_connection_t, initialized as by
  298. * connection_init(). */
  299. listener_connection_t *
  300. listener_connection_new(int type, int socket_family)
  301. {
  302. listener_connection_t *listener_conn =
  303. tor_malloc_zero(sizeof(listener_connection_t));
  304. connection_init(time(NULL), TO_CONN(listener_conn), type, socket_family);
  305. return listener_conn;
  306. }
  307. /** Allocate, initialize, and return a new connection_t subtype of <b>type</b>
  308. * to make or receive connections of address family <b>socket_family</b>. The
  309. * type should be one of the CONN_TYPE_* constants. */
  310. connection_t *
  311. connection_new(int type, int socket_family)
  312. {
  313. switch (type) {
  314. case CONN_TYPE_OR:
  315. return TO_CONN(or_connection_new(socket_family));
  316. case CONN_TYPE_EXIT:
  317. return TO_CONN(edge_connection_new(type, socket_family));
  318. case CONN_TYPE_AP:
  319. return ENTRY_TO_CONN(entry_connection_new(type, socket_family));
  320. case CONN_TYPE_DIR:
  321. return TO_CONN(dir_connection_new(socket_family));
  322. case CONN_TYPE_CONTROL:
  323. return TO_CONN(control_connection_new(socket_family));
  324. CASE_ANY_LISTENER_TYPE:
  325. return TO_CONN(listener_connection_new(type, socket_family));
  326. default: {
  327. connection_t *conn = tor_malloc_zero(sizeof(connection_t));
  328. connection_init(time(NULL), conn, type, socket_family);
  329. return conn;
  330. }
  331. }
  332. }
  333. /** Initializes conn. (you must call connection_add() to link it into the main
  334. * array).
  335. *
  336. * Set conn-\>magic to the correct value.
  337. *
  338. * Set conn-\>type to <b>type</b>. Set conn-\>s and conn-\>conn_array_index to
  339. * -1 to signify they are not yet assigned.
  340. *
  341. * Initialize conn's timestamps to now.
  342. */
  343. static void
  344. connection_init(time_t now, connection_t *conn, int type, int socket_family)
  345. {
  346. static uint64_t n_connections_allocated = 1;
  347. switch (type) {
  348. case CONN_TYPE_OR:
  349. conn->magic = OR_CONNECTION_MAGIC;
  350. break;
  351. case CONN_TYPE_EXIT:
  352. conn->magic = EDGE_CONNECTION_MAGIC;
  353. break;
  354. case CONN_TYPE_AP:
  355. conn->magic = ENTRY_CONNECTION_MAGIC;
  356. break;
  357. case CONN_TYPE_DIR:
  358. conn->magic = DIR_CONNECTION_MAGIC;
  359. break;
  360. case CONN_TYPE_CONTROL:
  361. conn->magic = CONTROL_CONNECTION_MAGIC;
  362. break;
  363. CASE_ANY_LISTENER_TYPE:
  364. conn->magic = LISTENER_CONNECTION_MAGIC;
  365. break;
  366. default:
  367. conn->magic = BASE_CONNECTION_MAGIC;
  368. break;
  369. }
  370. conn->s = TOR_INVALID_SOCKET; /* give it a default of 'not used' */
  371. conn->conn_array_index = -1; /* also default to 'not used' */
  372. conn->global_identifier = n_connections_allocated++;
  373. conn->type = type;
  374. conn->socket_family = socket_family;
  375. #ifndef USE_BUFFEREVENTS
  376. if (!connection_is_listener(conn)) {
  377. /* listeners never use their buf */
  378. conn->inbuf = buf_new();
  379. conn->outbuf = buf_new();
  380. }
  381. #endif
  382. conn->timestamp_created = now;
  383. conn->timestamp_lastread = now;
  384. conn->timestamp_lastwritten = now;
  385. }
  386. /** Create a link between <b>conn_a</b> and <b>conn_b</b>. */
  387. void
  388. connection_link_connections(connection_t *conn_a, connection_t *conn_b)
  389. {
  390. tor_assert(! SOCKET_OK(conn_a->s));
  391. tor_assert(! SOCKET_OK(conn_b->s));
  392. conn_a->linked = 1;
  393. conn_b->linked = 1;
  394. conn_a->linked_conn = conn_b;
  395. conn_b->linked_conn = conn_a;
  396. }
  397. /** Deallocate memory used by <b>conn</b>. Deallocate its buffers if
  398. * necessary, close its socket if necessary, and mark the directory as dirty
  399. * if <b>conn</b> is an OR or OP connection.
  400. */
  401. static void
  402. connection_free_(connection_t *conn)
  403. {
  404. void *mem;
  405. size_t memlen;
  406. if (!conn)
  407. return;
  408. switch (conn->type) {
  409. case CONN_TYPE_OR:
  410. tor_assert(conn->magic == OR_CONNECTION_MAGIC);
  411. mem = TO_OR_CONN(conn);
  412. memlen = sizeof(or_connection_t);
  413. break;
  414. case CONN_TYPE_AP:
  415. tor_assert(conn->magic == ENTRY_CONNECTION_MAGIC);
  416. mem = TO_ENTRY_CONN(conn);
  417. memlen = sizeof(entry_connection_t);
  418. break;
  419. case CONN_TYPE_EXIT:
  420. tor_assert(conn->magic == EDGE_CONNECTION_MAGIC);
  421. mem = TO_EDGE_CONN(conn);
  422. memlen = sizeof(edge_connection_t);
  423. break;
  424. case CONN_TYPE_DIR:
  425. tor_assert(conn->magic == DIR_CONNECTION_MAGIC);
  426. mem = TO_DIR_CONN(conn);
  427. memlen = sizeof(dir_connection_t);
  428. break;
  429. case CONN_TYPE_CONTROL:
  430. tor_assert(conn->magic == CONTROL_CONNECTION_MAGIC);
  431. mem = TO_CONTROL_CONN(conn);
  432. memlen = sizeof(control_connection_t);
  433. break;
  434. CASE_ANY_LISTENER_TYPE:
  435. tor_assert(conn->magic == LISTENER_CONNECTION_MAGIC);
  436. mem = TO_LISTENER_CONN(conn);
  437. memlen = sizeof(listener_connection_t);
  438. break;
  439. default:
  440. tor_assert(conn->magic == BASE_CONNECTION_MAGIC);
  441. mem = conn;
  442. memlen = sizeof(connection_t);
  443. break;
  444. }
  445. if (conn->linked) {
  446. log_info(LD_GENERAL, "Freeing linked %s connection [%s] with %d "
  447. "bytes on inbuf, %d on outbuf.",
  448. conn_type_to_string(conn->type),
  449. conn_state_to_string(conn->type, conn->state),
  450. (int)connection_get_inbuf_len(conn),
  451. (int)connection_get_outbuf_len(conn));
  452. }
  453. if (!connection_is_listener(conn)) {
  454. buf_free(conn->inbuf);
  455. buf_free(conn->outbuf);
  456. } else {
  457. if (conn->socket_family == AF_UNIX) {
  458. /* For now only control ports can be Unix domain sockets
  459. * and listeners at the same time */
  460. tor_assert(conn->type == CONN_TYPE_CONTROL_LISTENER);
  461. if (unlink(conn->address) < 0 && errno != ENOENT) {
  462. log_warn(LD_NET, "Could not unlink %s: %s", conn->address,
  463. strerror(errno));
  464. }
  465. }
  466. }
  467. tor_free(conn->address);
  468. if (connection_speaks_cells(conn)) {
  469. or_connection_t *or_conn = TO_OR_CONN(conn);
  470. tor_tls_free(or_conn->tls);
  471. or_conn->tls = NULL;
  472. or_handshake_state_free(or_conn->handshake_state);
  473. or_conn->handshake_state = NULL;
  474. tor_free(or_conn->nickname);
  475. }
  476. if (conn->type == CONN_TYPE_AP) {
  477. entry_connection_t *entry_conn = TO_ENTRY_CONN(conn);
  478. tor_free(entry_conn->chosen_exit_name);
  479. tor_free(entry_conn->original_dest_address);
  480. if (entry_conn->socks_request)
  481. socks_request_free(entry_conn->socks_request);
  482. if (entry_conn->pending_optimistic_data) {
  483. generic_buffer_free(entry_conn->pending_optimistic_data);
  484. }
  485. if (entry_conn->sending_optimistic_data) {
  486. generic_buffer_free(entry_conn->sending_optimistic_data);
  487. }
  488. }
  489. if (CONN_IS_EDGE(conn)) {
  490. rend_data_free(TO_EDGE_CONN(conn)->rend_data);
  491. }
  492. if (conn->type == CONN_TYPE_CONTROL) {
  493. control_connection_t *control_conn = TO_CONTROL_CONN(conn);
  494. tor_free(control_conn->safecookie_client_hash);
  495. tor_free(control_conn->incoming_cmd);
  496. }
  497. tor_free(conn->read_event); /* Probably already freed by connection_free. */
  498. tor_free(conn->write_event); /* Probably already freed by connection_free. */
  499. IF_HAS_BUFFEREVENT(conn, {
  500. /* This was a workaround to handle bugs in some old versions of libevent
  501. * where callbacks can occur after calling bufferevent_free(). Setting
  502. * the callbacks to NULL prevented this. It shouldn't be necessary any
  503. * more, but let's not tempt fate for now. */
  504. bufferevent_setcb(conn->bufev, NULL, NULL, NULL, NULL);
  505. bufferevent_free(conn->bufev);
  506. conn->bufev = NULL;
  507. });
  508. if (conn->type == CONN_TYPE_DIR) {
  509. dir_connection_t *dir_conn = TO_DIR_CONN(conn);
  510. tor_free(dir_conn->requested_resource);
  511. tor_zlib_free(dir_conn->zlib_state);
  512. if (dir_conn->fingerprint_stack) {
  513. SMARTLIST_FOREACH(dir_conn->fingerprint_stack, char *, cp, tor_free(cp));
  514. smartlist_free(dir_conn->fingerprint_stack);
  515. }
  516. cached_dir_decref(dir_conn->cached_dir);
  517. rend_data_free(dir_conn->rend_data);
  518. }
  519. if (SOCKET_OK(conn->s)) {
  520. log_debug(LD_NET,"closing fd %d.",(int)conn->s);
  521. tor_close_socket(conn->s);
  522. conn->s = TOR_INVALID_SOCKET;
  523. }
  524. if (conn->type == CONN_TYPE_OR &&
  525. !tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest)) {
  526. log_warn(LD_BUG, "called on OR conn with non-zeroed identity_digest");
  527. connection_or_remove_from_identity_map(TO_OR_CONN(conn));
  528. }
  529. #ifdef USE_BUFFEREVENTS
  530. if (conn->type == CONN_TYPE_OR && TO_OR_CONN(conn)->bucket_cfg) {
  531. ev_token_bucket_cfg_free(TO_OR_CONN(conn)->bucket_cfg);
  532. TO_OR_CONN(conn)->bucket_cfg = NULL;
  533. }
  534. #endif
  535. memwipe(mem, 0xCC, memlen); /* poison memory */
  536. tor_free(mem);
  537. }
  538. /** Make sure <b>conn</b> isn't in any of the global conn lists; then free it.
  539. */
  540. void
  541. connection_free(connection_t *conn)
  542. {
  543. if (!conn)
  544. return;
  545. tor_assert(!connection_is_on_closeable_list(conn));
  546. tor_assert(!connection_in_array(conn));
  547. if (conn->linked_conn) {
  548. log_err(LD_BUG, "Called with conn->linked_conn still set.");
  549. tor_fragile_assert();
  550. conn->linked_conn->linked_conn = NULL;
  551. if (! conn->linked_conn->marked_for_close &&
  552. conn->linked_conn->reading_from_linked_conn)
  553. connection_start_reading(conn->linked_conn);
  554. conn->linked_conn = NULL;
  555. }
  556. if (connection_speaks_cells(conn)) {
  557. if (!tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest)) {
  558. connection_or_remove_from_identity_map(TO_OR_CONN(conn));
  559. }
  560. }
  561. if (conn->type == CONN_TYPE_CONTROL) {
  562. connection_control_closed(TO_CONTROL_CONN(conn));
  563. }
  564. connection_unregister_events(conn);
  565. connection_free_(conn);
  566. }
  567. /**
  568. * Called when we're about to finally unlink and free a connection:
  569. * perform necessary accounting and cleanup
  570. * - Directory conns that failed to fetch a rendezvous descriptor
  571. * need to inform pending rendezvous streams.
  572. * - OR conns need to call rep_hist_note_*() to record status.
  573. * - AP conns need to send a socks reject if necessary.
  574. * - Exit conns need to call connection_dns_remove() if necessary.
  575. * - AP and Exit conns need to send an end cell if they can.
  576. * - DNS conns need to fail any resolves that are pending on them.
  577. * - OR and edge connections need to be unlinked from circuits.
  578. */
  579. void
  580. connection_about_to_close_connection(connection_t *conn)
  581. {
  582. tor_assert(conn->marked_for_close);
  583. switch (conn->type) {
  584. case CONN_TYPE_DIR:
  585. connection_dir_about_to_close(TO_DIR_CONN(conn));
  586. break;
  587. case CONN_TYPE_OR:
  588. connection_or_about_to_close(TO_OR_CONN(conn));
  589. break;
  590. case CONN_TYPE_AP:
  591. connection_ap_about_to_close(TO_ENTRY_CONN(conn));
  592. break;
  593. case CONN_TYPE_EXIT:
  594. connection_exit_about_to_close(TO_EDGE_CONN(conn));
  595. break;
  596. }
  597. }
  598. /** Return true iff connection_close_immediate() has been called on this
  599. * connection. */
  600. #define CONN_IS_CLOSED(c) \
  601. ((c)->linked ? ((c)->linked_conn_is_closed) : (! SOCKET_OK(c->s)))
  602. /** Close the underlying socket for <b>conn</b>, so we don't try to
  603. * flush it. Must be used in conjunction with (right before)
  604. * connection_mark_for_close().
  605. */
  606. void
  607. connection_close_immediate(connection_t *conn)
  608. {
  609. assert_connection_ok(conn,0);
  610. if (CONN_IS_CLOSED(conn)) {
  611. log_err(LD_BUG,"Attempt to close already-closed connection.");
  612. tor_fragile_assert();
  613. return;
  614. }
  615. if (conn->outbuf_flushlen) {
  616. log_info(LD_NET,"fd %d, type %s, state %s, %d bytes on outbuf.",
  617. (int)conn->s, conn_type_to_string(conn->type),
  618. conn_state_to_string(conn->type, conn->state),
  619. (int)conn->outbuf_flushlen);
  620. }
  621. connection_unregister_events(conn);
  622. if (SOCKET_OK(conn->s))
  623. tor_close_socket(conn->s);
  624. conn->s = TOR_INVALID_SOCKET;
  625. if (conn->linked)
  626. conn->linked_conn_is_closed = 1;
  627. if (conn->outbuf)
  628. buf_clear(conn->outbuf);
  629. conn->outbuf_flushlen = 0;
  630. }
  631. /** Mark <b>conn</b> to be closed next time we loop through
  632. * conn_close_if_marked() in main.c. */
  633. void
  634. connection_mark_for_close_(connection_t *conn, int line, const char *file)
  635. {
  636. assert_connection_ok(conn,0);
  637. tor_assert(line);
  638. tor_assert(line < 1<<16); /* marked_for_close can only fit a uint16_t. */
  639. tor_assert(file);
  640. if (conn->type == CONN_TYPE_OR) {
  641. /*
  642. * An or_connection should have been closed through one of the channel-
  643. * aware functions in connection_or.c. We'll assume this is an error
  644. * close and do that, and log a bug warning.
  645. */
  646. log_warn(LD_CHANNEL | LD_BUG,
  647. "Something tried to close an or_connection_t without going "
  648. "through channels at %s:%d",
  649. file, line);
  650. connection_or_close_for_error(TO_OR_CONN(conn), 0);
  651. } else {
  652. /* Pass it down to the real function */
  653. connection_mark_for_close_internal_(conn, line, file);
  654. }
  655. }
  656. /** Mark <b>conn</b> to be closed next time we loop through
  657. * conn_close_if_marked() in main.c; the _internal version bypasses the
  658. * CONN_TYPE_OR checks; this should be called when you either are sure that
  659. * if this is an or_connection_t the controlling channel has been notified
  660. * (e.g. with connection_or_notify_error()), or you actually are the
  661. * connection_or_close_for_error() or connection_or_close_normally function.
  662. * For all other cases, use connection_mark_and_flush() instead, which
  663. * checks for or_connection_t properly, instead. See below.
  664. */
  665. void
  666. connection_mark_for_close_internal_(connection_t *conn,
  667. int line, const char *file)
  668. {
  669. assert_connection_ok(conn,0);
  670. tor_assert(line);
  671. tor_assert(line < 1<<16); /* marked_for_close can only fit a uint16_t. */
  672. tor_assert(file);
  673. if (conn->marked_for_close) {
  674. log(LOG_WARN,LD_BUG,"Duplicate call to connection_mark_for_close at %s:%d"
  675. " (first at %s:%d)", file, line, conn->marked_for_close_file,
  676. conn->marked_for_close);
  677. tor_fragile_assert();
  678. return;
  679. }
  680. if (conn->type == CONN_TYPE_OR) {
  681. /*
  682. * Bad news if this happens without telling the controlling channel; do
  683. * this so we can find things that call this wrongly when the asserts hit.
  684. */
  685. log_debug(LD_CHANNEL,
  686. "Calling connection_mark_for_close_internal_() on an OR conn "
  687. "at %s:%d",
  688. file, line);
  689. }
  690. conn->marked_for_close = line;
  691. conn->marked_for_close_file = file;
  692. add_connection_to_closeable_list(conn);
  693. /* in case we're going to be held-open-til-flushed, reset
  694. * the number of seconds since last successful write, so
  695. * we get our whole 15 seconds */
  696. conn->timestamp_lastwritten = time(NULL);
  697. }
  698. /** Find each connection that has hold_open_until_flushed set to
  699. * 1 but hasn't written in the past 15 seconds, and set
  700. * hold_open_until_flushed to 0. This means it will get cleaned
  701. * up in the next loop through close_if_marked() in main.c.
  702. */
  703. void
  704. connection_expire_held_open(void)
  705. {
  706. time_t now;
  707. smartlist_t *conns = get_connection_array();
  708. now = time(NULL);
  709. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  710. /* If we've been holding the connection open, but we haven't written
  711. * for 15 seconds...
  712. */
  713. if (conn->hold_open_until_flushed) {
  714. tor_assert(conn->marked_for_close);
  715. if (now - conn->timestamp_lastwritten >= 15) {
  716. int severity;
  717. if (conn->type == CONN_TYPE_EXIT ||
  718. (conn->type == CONN_TYPE_DIR &&
  719. conn->purpose == DIR_PURPOSE_SERVER))
  720. severity = LOG_INFO;
  721. else
  722. severity = LOG_NOTICE;
  723. log_fn(severity, LD_NET,
  724. "Giving up on marked_for_close conn that's been flushing "
  725. "for 15s (fd %d, type %s, state %s).",
  726. (int)conn->s, conn_type_to_string(conn->type),
  727. conn_state_to_string(conn->type, conn->state));
  728. conn->hold_open_until_flushed = 0;
  729. }
  730. }
  731. } SMARTLIST_FOREACH_END(conn);
  732. }
  733. #if defined(HAVE_SYS_UN_H) || defined(RUNNING_DOXYGEN)
  734. /** Create an AF_UNIX listenaddr struct.
  735. * <b>listenaddress</b> provides the path to the Unix socket.
  736. *
  737. * Eventually <b>listenaddress</b> will also optionally contain user, group,
  738. * and file permissions for the new socket. But not yet. XXX
  739. * Also, since we do not create the socket here the information doesn't help
  740. * here.
  741. *
  742. * If not NULL <b>readable_address</b> will contain a copy of the path part of
  743. * <b>listenaddress</b>.
  744. *
  745. * The listenaddr struct has to be freed by the caller.
  746. */
  747. static struct sockaddr_un *
  748. create_unix_sockaddr(const char *listenaddress, char **readable_address,
  749. socklen_t *len_out)
  750. {
  751. struct sockaddr_un *sockaddr = NULL;
  752. sockaddr = tor_malloc_zero(sizeof(struct sockaddr_un));
  753. sockaddr->sun_family = AF_UNIX;
  754. if (strlcpy(sockaddr->sun_path, listenaddress, sizeof(sockaddr->sun_path))
  755. >= sizeof(sockaddr->sun_path)) {
  756. log_warn(LD_CONFIG, "Unix socket path '%s' is too long to fit.",
  757. escaped(listenaddress));
  758. tor_free(sockaddr);
  759. return NULL;
  760. }
  761. if (readable_address)
  762. *readable_address = tor_strdup(listenaddress);
  763. *len_out = sizeof(struct sockaddr_un);
  764. return sockaddr;
  765. }
  766. #else
  767. static struct sockaddr *
  768. create_unix_sockaddr(const char *listenaddress, char **readable_address,
  769. socklen_t *len_out)
  770. {
  771. (void)listenaddress;
  772. (void)readable_address;
  773. log_fn(LOG_ERR, LD_BUG,
  774. "Unix domain sockets not supported, yet we tried to create one.");
  775. *len_out = 0;
  776. tor_fragile_assert();
  777. return NULL;
  778. }
  779. #endif /* HAVE_SYS_UN_H */
  780. /** Warn that an accept or a connect has failed because we're running up
  781. * against our ulimit. Rate-limit these warnings so that we don't spam
  782. * the log. */
  783. static void
  784. warn_too_many_conns(void)
  785. {
  786. #define WARN_TOO_MANY_CONNS_INTERVAL (6*60*60)
  787. static ratelim_t last_warned = RATELIM_INIT(WARN_TOO_MANY_CONNS_INTERVAL);
  788. char *m;
  789. if ((m = rate_limit_log(&last_warned, approx_time()))) {
  790. int n_conns = get_n_open_sockets();
  791. log_warn(LD_NET,"Failing because we have %d connections already. Please "
  792. "raise your ulimit -n.%s", n_conns, m);
  793. tor_free(m);
  794. control_event_general_status(LOG_WARN, "TOO_MANY_CONNECTIONS CURRENT=%d",
  795. n_conns);
  796. }
  797. }
  798. #ifdef HAVE_SYS_UN_H
  799. /** Check whether we should be willing to open an AF_UNIX socket in
  800. * <b>path</b>. Return 0 if we should go ahead and -1 if we shouldn't. */
  801. static int
  802. check_location_for_unix_socket(const or_options_t *options, const char *path)
  803. {
  804. int r = -1;
  805. char *p = tor_strdup(path);
  806. cpd_check_t flags = CPD_CHECK_MODE_ONLY;
  807. if (get_parent_directory(p)<0)
  808. goto done;
  809. if (options->ControlSocketsGroupWritable)
  810. flags |= CPD_GROUP_OK;
  811. if (check_private_dir(p, flags, options->User) < 0) {
  812. char *escpath, *escdir;
  813. escpath = esc_for_log(path);
  814. escdir = esc_for_log(p);
  815. log_warn(LD_GENERAL, "Before Tor can create a control socket in %s, the "
  816. "directory %s needs to exist, and to be accessible only by the "
  817. "user%s account that is running Tor. (On some Unix systems, "
  818. "anybody who can list a socket can connect to it, so Tor is "
  819. "being careful.)", escpath, escdir,
  820. options->ControlSocketsGroupWritable ? " and group" : "");
  821. tor_free(escpath);
  822. tor_free(escdir);
  823. goto done;
  824. }
  825. r = 0;
  826. done:
  827. tor_free(p);
  828. return r;
  829. }
  830. #endif
  831. /** Tell the TCP stack that it shouldn't wait for a long time after
  832. * <b>sock</b> has closed before reusing its port. */
  833. static void
  834. make_socket_reuseable(tor_socket_t sock)
  835. {
  836. #ifdef _WIN32
  837. (void) sock;
  838. #else
  839. int one=1;
  840. /* REUSEADDR on normal places means you can rebind to the port
  841. * right after somebody else has let it go. But REUSEADDR on win32
  842. * means you can bind to the port _even when somebody else
  843. * already has it bound_. So, don't do that on Win32. */
  844. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*) &one,
  845. (socklen_t)sizeof(one));
  846. #endif
  847. }
  848. /** Bind a new non-blocking socket listening to the socket described
  849. * by <b>listensockaddr</b>.
  850. *
  851. * <b>address</b> is only used for logging purposes and to add the information
  852. * to the conn.
  853. */
  854. static connection_t *
  855. connection_listener_new(const struct sockaddr *listensockaddr,
  856. socklen_t socklen,
  857. int type, const char *address,
  858. const port_cfg_t *port_cfg)
  859. {
  860. listener_connection_t *lis_conn;
  861. connection_t *conn;
  862. tor_socket_t s; /* the socket we're going to make */
  863. or_options_t const *options = get_options();
  864. #if defined(HAVE_PWD_H) && defined(HAVE_SYS_UN_H)
  865. struct passwd *pw = NULL;
  866. #endif
  867. uint16_t usePort = 0, gotPort = 0;
  868. int start_reading = 0;
  869. static int global_next_session_group = SESSION_GROUP_FIRST_AUTO;
  870. tor_addr_t addr;
  871. if (get_n_open_sockets() >= get_options()->ConnLimit_-1) {
  872. warn_too_many_conns();
  873. return NULL;
  874. }
  875. if (listensockaddr->sa_family == AF_INET ||
  876. listensockaddr->sa_family == AF_INET6) {
  877. int is_tcp = (type != CONN_TYPE_AP_DNS_LISTENER);
  878. if (is_tcp)
  879. start_reading = 1;
  880. tor_addr_from_sockaddr(&addr, listensockaddr, &usePort);
  881. log_notice(LD_NET, "Opening %s on %s",
  882. conn_type_to_string(type), fmt_addrport(&addr, usePort));
  883. s = tor_open_socket(tor_addr_family(&addr),
  884. is_tcp ? SOCK_STREAM : SOCK_DGRAM,
  885. is_tcp ? IPPROTO_TCP: IPPROTO_UDP);
  886. if (!SOCKET_OK(s)) {
  887. log_warn(LD_NET,"Socket creation failed: %s",
  888. tor_socket_strerror(tor_socket_errno(-1)));
  889. goto err;
  890. }
  891. make_socket_reuseable(s);
  892. #ifdef IPV6_V6ONLY
  893. if (listensockaddr->sa_family == AF_INET6) {
  894. #ifdef _WIN32
  895. /* In Redmond, this kind of thing passes for standards-conformance. */
  896. DWORD one = 1;
  897. #else
  898. int one = 1;
  899. #endif
  900. /* We need to set IPV6_V6ONLY so that this socket can't get used for
  901. * IPv4 connections. */
  902. if (setsockopt(s,IPPROTO_IPV6, IPV6_V6ONLY,
  903. (void*)&one, sizeof(one))<0) {
  904. int e = tor_socket_errno(s);
  905. log_warn(LD_NET, "Error setting IPV6_V6ONLY flag: %s",
  906. tor_socket_strerror(e));
  907. /* Keep going; probably not harmful. */
  908. }
  909. }
  910. #endif
  911. if (bind(s,listensockaddr,socklen) < 0) {
  912. const char *helpfulhint = "";
  913. int e = tor_socket_errno(s);
  914. if (ERRNO_IS_EADDRINUSE(e))
  915. helpfulhint = ". Is Tor already running?";
  916. log_warn(LD_NET, "Could not bind to %s:%u: %s%s", address, usePort,
  917. tor_socket_strerror(e), helpfulhint);
  918. tor_close_socket(s);
  919. goto err;
  920. }
  921. if (is_tcp) {
  922. if (listen(s,SOMAXCONN) < 0) {
  923. log_warn(LD_NET, "Could not listen on %s:%u: %s", address, usePort,
  924. tor_socket_strerror(tor_socket_errno(s)));
  925. tor_close_socket(s);
  926. goto err;
  927. }
  928. }
  929. if (usePort != 0) {
  930. gotPort = usePort;
  931. } else {
  932. tor_addr_t addr2;
  933. struct sockaddr_storage ss;
  934. socklen_t ss_len=sizeof(ss);
  935. if (getsockname(s, (struct sockaddr*)&ss, &ss_len)<0) {
  936. log_warn(LD_NET, "getsockname() couldn't learn address for %s: %s",
  937. conn_type_to_string(type),
  938. tor_socket_strerror(tor_socket_errno(s)));
  939. gotPort = 0;
  940. }
  941. tor_addr_from_sockaddr(&addr2, (struct sockaddr*)&ss, &gotPort);
  942. }
  943. #ifdef HAVE_SYS_UN_H
  944. } else if (listensockaddr->sa_family == AF_UNIX) {
  945. start_reading = 1;
  946. /* For now only control ports can be Unix domain sockets
  947. * and listeners at the same time */
  948. tor_assert(type == CONN_TYPE_CONTROL_LISTENER);
  949. if (check_location_for_unix_socket(options, address) < 0)
  950. goto err;
  951. log_notice(LD_NET, "Opening %s on %s",
  952. conn_type_to_string(type), address);
  953. tor_addr_make_unspec(&addr);
  954. if (unlink(address) < 0 && errno != ENOENT) {
  955. log_warn(LD_NET, "Could not unlink %s: %s", address,
  956. strerror(errno));
  957. goto err;
  958. }
  959. s = tor_open_socket(AF_UNIX, SOCK_STREAM, 0);
  960. if (! SOCKET_OK(s)) {
  961. log_warn(LD_NET,"Socket creation failed: %s.", strerror(errno));
  962. goto err;
  963. }
  964. if (bind(s, listensockaddr, (socklen_t)sizeof(struct sockaddr_un)) == -1) {
  965. log_warn(LD_NET,"Bind to %s failed: %s.", address,
  966. tor_socket_strerror(tor_socket_errno(s)));
  967. goto err;
  968. }
  969. #ifdef HAVE_PWD_H
  970. if (options->User) {
  971. pw = getpwnam(options->User);
  972. if (pw == NULL) {
  973. log_warn(LD_NET,"Unable to chown() %s socket: user %s not found.",
  974. address, options->User);
  975. } else if (chown(address, pw->pw_uid, pw->pw_gid) < 0) {
  976. log_warn(LD_NET,"Unable to chown() %s socket: %s.",
  977. address, strerror(errno));
  978. goto err;
  979. }
  980. }
  981. #endif
  982. if (options->ControlSocketsGroupWritable) {
  983. /* We need to use chmod; fchmod doesn't work on sockets on all
  984. * platforms. */
  985. if (chmod(address, 0660) < 0) {
  986. log_warn(LD_FS,"Unable to make %s group-writable.", address);
  987. tor_close_socket(s);
  988. goto err;
  989. }
  990. }
  991. if (listen(s,SOMAXCONN) < 0) {
  992. log_warn(LD_NET, "Could not listen on %s: %s", address,
  993. tor_socket_strerror(tor_socket_errno(s)));
  994. tor_close_socket(s);
  995. goto err;
  996. }
  997. #else
  998. (void)options;
  999. #endif /* HAVE_SYS_UN_H */
  1000. } else {
  1001. log_err(LD_BUG,"Got unexpected address family %d.",
  1002. listensockaddr->sa_family);
  1003. tor_assert(0);
  1004. }
  1005. set_socket_nonblocking(s);
  1006. lis_conn = listener_connection_new(type, listensockaddr->sa_family);
  1007. conn = TO_CONN(lis_conn);
  1008. conn->socket_family = listensockaddr->sa_family;
  1009. conn->s = s;
  1010. conn->address = tor_strdup(address);
  1011. conn->port = gotPort;
  1012. tor_addr_copy(&conn->addr, &addr);
  1013. if (port_cfg->isolation_flags) {
  1014. lis_conn->isolation_flags = port_cfg->isolation_flags;
  1015. if (port_cfg->session_group >= 0) {
  1016. lis_conn->session_group = port_cfg->session_group;
  1017. } else {
  1018. /* This can wrap after around INT_MAX listeners are opened. But I don't
  1019. * believe that matters, since you would need to open a ridiculous
  1020. * number of listeners while keeping the early ones open before you ever
  1021. * hit this. An OR with a dozen ports open, for example, would have to
  1022. * close and re-open its listeners every second for 4 years nonstop.
  1023. */
  1024. lis_conn->session_group = global_next_session_group--;
  1025. }
  1026. }
  1027. if (type == CONN_TYPE_AP_LISTENER) {
  1028. lis_conn->socks_ipv4_traffic = port_cfg->ipv4_traffic;
  1029. lis_conn->socks_ipv6_traffic = port_cfg->ipv6_traffic;
  1030. lis_conn->socks_prefer_ipv6 = port_cfg->prefer_ipv6;
  1031. } else {
  1032. lis_conn->socks_ipv4_traffic = 1;
  1033. lis_conn->socks_ipv6_traffic = 1;
  1034. }
  1035. lis_conn->cache_ipv4_answers = port_cfg->cache_ipv4_answers;
  1036. lis_conn->cache_ipv6_answers = port_cfg->cache_ipv6_answers;
  1037. lis_conn->use_cached_ipv4_answers = port_cfg->use_cached_ipv4_answers;
  1038. lis_conn->use_cached_ipv6_answers = port_cfg->use_cached_ipv6_answers;
  1039. lis_conn->prefer_ipv6_virtaddr = port_cfg->prefer_ipv6_virtaddr;
  1040. if (connection_add(conn) < 0) { /* no space, forget it */
  1041. log_warn(LD_NET,"connection_add for listener failed. Giving up.");
  1042. connection_free(conn);
  1043. goto err;
  1044. }
  1045. log_fn(usePort==gotPort ? LOG_DEBUG : LOG_NOTICE, LD_NET,
  1046. "%s listening on port %u.",
  1047. conn_type_to_string(type), gotPort);
  1048. conn->state = LISTENER_STATE_READY;
  1049. if (start_reading) {
  1050. connection_start_reading(conn);
  1051. } else {
  1052. tor_assert(type == CONN_TYPE_AP_DNS_LISTENER);
  1053. dnsserv_configure_listener(conn);
  1054. }
  1055. return conn;
  1056. err:
  1057. return NULL;
  1058. }
  1059. /** Do basic sanity checking on a newly received socket. Return 0
  1060. * if it looks ok, else return -1.
  1061. *
  1062. * Notably, some TCP stacks can erroneously have accept() return successfully
  1063. * with socklen 0, when the client sends an RST before the accept call (as
  1064. * nmap does). We want to detect that, and not go on with the connection.
  1065. */
  1066. static int
  1067. check_sockaddr(const struct sockaddr *sa, int len, int level)
  1068. {
  1069. int ok = 1;
  1070. if (sa->sa_family == AF_INET) {
  1071. struct sockaddr_in *sin=(struct sockaddr_in*)sa;
  1072. if (len != sizeof(struct sockaddr_in)) {
  1073. log_fn(level, LD_NET, "Length of address not as expected: %d vs %d",
  1074. len,(int)sizeof(struct sockaddr_in));
  1075. ok = 0;
  1076. }
  1077. if (sin->sin_addr.s_addr == 0 || sin->sin_port == 0) {
  1078. log_fn(level, LD_NET,
  1079. "Address for new connection has address/port equal to zero.");
  1080. ok = 0;
  1081. }
  1082. } else if (sa->sa_family == AF_INET6) {
  1083. struct sockaddr_in6 *sin6=(struct sockaddr_in6*)sa;
  1084. if (len != sizeof(struct sockaddr_in6)) {
  1085. log_fn(level, LD_NET, "Length of address not as expected: %d vs %d",
  1086. len,(int)sizeof(struct sockaddr_in6));
  1087. ok = 0;
  1088. }
  1089. if (tor_mem_is_zero((void*)sin6->sin6_addr.s6_addr, 16) ||
  1090. sin6->sin6_port == 0) {
  1091. log_fn(level, LD_NET,
  1092. "Address for new connection has address/port equal to zero.");
  1093. ok = 0;
  1094. }
  1095. } else {
  1096. ok = 0;
  1097. }
  1098. return ok ? 0 : -1;
  1099. }
  1100. /** Check whether the socket family from an accepted socket <b>got</b> is the
  1101. * same as the one that <b>listener</b> is waiting for. If it isn't, log
  1102. * a useful message and return -1. Else return 0.
  1103. *
  1104. * This is annoying, but can apparently happen on some Darwins. */
  1105. static int
  1106. check_sockaddr_family_match(sa_family_t got, connection_t *listener)
  1107. {
  1108. if (got != listener->socket_family) {
  1109. log_info(LD_BUG, "A listener connection returned a socket with a "
  1110. "mismatched family. %s for addr_family %d gave us a socket "
  1111. "with address family %d. Dropping.",
  1112. conn_type_to_string(listener->type),
  1113. (int)listener->socket_family,
  1114. (int)got);
  1115. return -1;
  1116. }
  1117. return 0;
  1118. }
  1119. /** The listener connection <b>conn</b> told poll() it wanted to read.
  1120. * Call accept() on conn-\>s, and add the new connection if necessary.
  1121. */
  1122. static int
  1123. connection_handle_listener_read(connection_t *conn, int new_type)
  1124. {
  1125. tor_socket_t news; /* the new socket */
  1126. connection_t *newconn;
  1127. /* information about the remote peer when connecting to other routers */
  1128. struct sockaddr_storage addrbuf;
  1129. struct sockaddr *remote = (struct sockaddr*)&addrbuf;
  1130. /* length of the remote address. Must be whatever accept() needs. */
  1131. socklen_t remotelen = (socklen_t)sizeof(addrbuf);
  1132. const or_options_t *options = get_options();
  1133. tor_assert((size_t)remotelen >= sizeof(struct sockaddr_in));
  1134. memset(&addrbuf, 0, sizeof(addrbuf));
  1135. news = tor_accept_socket(conn->s,remote,&remotelen);
  1136. if (!SOCKET_OK(news)) { /* accept() error */
  1137. int e = tor_socket_errno(conn->s);
  1138. if (ERRNO_IS_ACCEPT_EAGAIN(e)) {
  1139. return 0; /* he hung up before we could accept(). that's fine. */
  1140. } else if (ERRNO_IS_ACCEPT_RESOURCE_LIMIT(e)) {
  1141. warn_too_many_conns();
  1142. return 0;
  1143. }
  1144. /* else there was a real error. */
  1145. log_warn(LD_NET,"accept() failed: %s. Closing listener.",
  1146. tor_socket_strerror(e));
  1147. connection_mark_for_close(conn);
  1148. return -1;
  1149. }
  1150. log_debug(LD_NET,
  1151. "Connection accepted on socket %d (child of fd %d).",
  1152. (int)news,(int)conn->s);
  1153. make_socket_reuseable(news);
  1154. set_socket_nonblocking(news);
  1155. if (options->ConstrainedSockets)
  1156. set_constrained_socket_buffers(news, (int)options->ConstrainedSockSize);
  1157. if (check_sockaddr_family_match(remote->sa_family, conn) < 0) {
  1158. tor_close_socket(news);
  1159. return 0;
  1160. }
  1161. if (conn->socket_family == AF_INET || conn->socket_family == AF_INET6) {
  1162. tor_addr_t addr;
  1163. uint16_t port;
  1164. if (check_sockaddr(remote, remotelen, LOG_INFO)<0) {
  1165. log_info(LD_NET,
  1166. "accept() returned a strange address; closing connection.");
  1167. tor_close_socket(news);
  1168. return 0;
  1169. }
  1170. tor_addr_from_sockaddr(&addr, remote, &port);
  1171. /* process entrance policies here, before we even create the connection */
  1172. if (new_type == CONN_TYPE_AP) {
  1173. /* check sockspolicy to see if we should accept it */
  1174. if (socks_policy_permits_address(&addr) == 0) {
  1175. log_notice(LD_APP,
  1176. "Denying socks connection from untrusted address %s.",
  1177. fmt_and_decorate_addr(&addr));
  1178. tor_close_socket(news);
  1179. return 0;
  1180. }
  1181. }
  1182. if (new_type == CONN_TYPE_DIR) {
  1183. /* check dirpolicy to see if we should accept it */
  1184. if (dir_policy_permits_address(&addr) == 0) {
  1185. log_notice(LD_DIRSERV,"Denying dir connection from address %s.",
  1186. fmt_and_decorate_addr(&addr));
  1187. tor_close_socket(news);
  1188. return 0;
  1189. }
  1190. }
  1191. newconn = connection_new(new_type, conn->socket_family);
  1192. newconn->s = news;
  1193. /* remember the remote address */
  1194. tor_addr_copy(&newconn->addr, &addr);
  1195. newconn->port = port;
  1196. newconn->address = tor_dup_addr(&addr);
  1197. } else if (conn->socket_family == AF_UNIX) {
  1198. /* For now only control ports can be Unix domain sockets
  1199. * and listeners at the same time */
  1200. tor_assert(conn->type == CONN_TYPE_CONTROL_LISTENER);
  1201. newconn = connection_new(new_type, conn->socket_family);
  1202. newconn->s = news;
  1203. /* remember the remote address -- do we have anything sane to put here? */
  1204. tor_addr_make_unspec(&newconn->addr);
  1205. newconn->port = 1;
  1206. newconn->address = tor_strdup(conn->address);
  1207. } else {
  1208. tor_assert(0);
  1209. };
  1210. if (connection_add(newconn) < 0) { /* no space, forget it */
  1211. connection_free(newconn);
  1212. return 0; /* no need to tear down the parent */
  1213. }
  1214. if (connection_init_accepted_conn(newconn, TO_LISTENER_CONN(conn)) < 0) {
  1215. if (! newconn->marked_for_close)
  1216. connection_mark_for_close(newconn);
  1217. return 0;
  1218. }
  1219. return 0;
  1220. }
  1221. /** Initialize states for newly accepted connection <b>conn</b>.
  1222. * If conn is an OR, start the TLS handshake.
  1223. * If conn is a transparent AP, get its original destination
  1224. * and place it in circuit_wait.
  1225. */
  1226. static int
  1227. connection_init_accepted_conn(connection_t *conn,
  1228. const listener_connection_t *listener)
  1229. {
  1230. int rv;
  1231. connection_start_reading(conn);
  1232. switch (conn->type) {
  1233. case CONN_TYPE_OR:
  1234. control_event_or_conn_status(TO_OR_CONN(conn), OR_CONN_EVENT_NEW, 0);
  1235. rv = connection_tls_start_handshake(TO_OR_CONN(conn), 1);
  1236. if (rv < 0) {
  1237. connection_or_close_for_error(TO_OR_CONN(conn), 0);
  1238. }
  1239. return rv;
  1240. break;
  1241. case CONN_TYPE_AP:
  1242. TO_ENTRY_CONN(conn)->isolation_flags = listener->isolation_flags;
  1243. TO_ENTRY_CONN(conn)->session_group = listener->session_group;
  1244. TO_ENTRY_CONN(conn)->nym_epoch = get_signewnym_epoch();
  1245. TO_ENTRY_CONN(conn)->socks_request->listener_type = listener->base_.type;
  1246. TO_ENTRY_CONN(conn)->ipv4_traffic_ok = listener->socks_ipv4_traffic;
  1247. TO_ENTRY_CONN(conn)->ipv6_traffic_ok = listener->socks_ipv6_traffic;
  1248. TO_ENTRY_CONN(conn)->prefer_ipv6_traffic = listener->socks_prefer_ipv6;
  1249. TO_ENTRY_CONN(conn)->cache_ipv4_answers = listener->cache_ipv4_answers;
  1250. TO_ENTRY_CONN(conn)->cache_ipv6_answers = listener->cache_ipv6_answers;
  1251. TO_ENTRY_CONN(conn)->use_cached_ipv4_answers =
  1252. listener->use_cached_ipv4_answers;
  1253. TO_ENTRY_CONN(conn)->use_cached_ipv6_answers =
  1254. listener->use_cached_ipv6_answers;
  1255. TO_ENTRY_CONN(conn)->prefer_ipv6_virtaddr =
  1256. listener->prefer_ipv6_virtaddr;
  1257. switch (TO_CONN(listener)->type) {
  1258. case CONN_TYPE_AP_LISTENER:
  1259. conn->state = AP_CONN_STATE_SOCKS_WAIT;
  1260. break;
  1261. case CONN_TYPE_AP_TRANS_LISTENER:
  1262. TO_ENTRY_CONN(conn)->is_transparent_ap = 1;
  1263. conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  1264. return connection_ap_process_transparent(TO_ENTRY_CONN(conn));
  1265. case CONN_TYPE_AP_NATD_LISTENER:
  1266. TO_ENTRY_CONN(conn)->is_transparent_ap = 1;
  1267. conn->state = AP_CONN_STATE_NATD_WAIT;
  1268. break;
  1269. }
  1270. break;
  1271. case CONN_TYPE_DIR:
  1272. conn->purpose = DIR_PURPOSE_SERVER;
  1273. conn->state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
  1274. break;
  1275. case CONN_TYPE_CONTROL:
  1276. conn->state = CONTROL_CONN_STATE_NEEDAUTH;
  1277. break;
  1278. }
  1279. return 0;
  1280. }
  1281. /** Take conn, make a nonblocking socket; try to connect to
  1282. * addr:port (they arrive in *host order*). If fail, return -1 and if
  1283. * applicable put your best guess about errno into *<b>socket_error</b>.
  1284. * Else assign s to conn-\>s: if connected return 1, if EAGAIN return 0.
  1285. *
  1286. * address is used to make the logs useful.
  1287. *
  1288. * On success, add conn to the list of polled connections.
  1289. */
  1290. int
  1291. connection_connect(connection_t *conn, const char *address,
  1292. const tor_addr_t *addr, uint16_t port, int *socket_error)
  1293. {
  1294. tor_socket_t s;
  1295. int inprogress = 0;
  1296. struct sockaddr_storage addrbuf;
  1297. struct sockaddr *dest_addr;
  1298. int dest_addr_len;
  1299. const or_options_t *options = get_options();
  1300. int protocol_family;
  1301. if (get_n_open_sockets() >= get_options()->ConnLimit_-1) {
  1302. warn_too_many_conns();
  1303. *socket_error = SOCK_ERRNO(ENOBUFS);
  1304. return -1;
  1305. }
  1306. if (tor_addr_family(addr) == AF_INET6)
  1307. protocol_family = PF_INET6;
  1308. else
  1309. protocol_family = PF_INET;
  1310. if (get_options()->DisableNetwork) {
  1311. /* We should never even try to connect anyplace if DisableNetwork is set.
  1312. * Warn if we do, and refuse to make the connection. */
  1313. static ratelim_t disablenet_violated = RATELIM_INIT(30*60);
  1314. char *m;
  1315. #ifdef _WIN32
  1316. *socket_error = WSAENETUNREACH;
  1317. #else
  1318. *socket_error = ENETUNREACH;
  1319. #endif
  1320. if ((m = rate_limit_log(&disablenet_violated, approx_time()))) {
  1321. log_warn(LD_BUG, "Tried to open a socket with DisableNetwork set.%s", m);
  1322. tor_free(m);
  1323. }
  1324. tor_fragile_assert();
  1325. return -1;
  1326. }
  1327. s = tor_open_socket(protocol_family,SOCK_STREAM,IPPROTO_TCP);
  1328. if (! SOCKET_OK(s)) {
  1329. *socket_error = tor_socket_errno(-1);
  1330. log_warn(LD_NET,"Error creating network socket: %s",
  1331. tor_socket_strerror(*socket_error));
  1332. return -1;
  1333. }
  1334. make_socket_reuseable(s);
  1335. if (!tor_addr_is_loopback(addr)) {
  1336. const tor_addr_t *ext_addr = NULL;
  1337. if (protocol_family == AF_INET &&
  1338. !tor_addr_is_null(&options->OutboundBindAddressIPv4_))
  1339. ext_addr = &options->OutboundBindAddressIPv4_;
  1340. else if (protocol_family == AF_INET6 &&
  1341. !tor_addr_is_null(&options->OutboundBindAddressIPv6_))
  1342. ext_addr = &options->OutboundBindAddressIPv6_;
  1343. if (ext_addr) {
  1344. struct sockaddr_storage ext_addr_sa;
  1345. socklen_t ext_addr_len = 0;
  1346. memset(&ext_addr_sa, 0, sizeof(ext_addr_sa));
  1347. ext_addr_len = tor_addr_to_sockaddr(ext_addr, 0,
  1348. (struct sockaddr *) &ext_addr_sa,
  1349. sizeof(ext_addr_sa));
  1350. if (ext_addr_len == 0) {
  1351. log_warn(LD_NET,
  1352. "Error converting OutboundBindAddress %s into sockaddr. "
  1353. "Ignoring.", fmt_and_decorate_addr(ext_addr));
  1354. } else {
  1355. if (bind(s, (struct sockaddr *) &ext_addr_sa, ext_addr_len) < 0) {
  1356. *socket_error = tor_socket_errno(s);
  1357. log_warn(LD_NET,"Error binding network socket to %s: %s",
  1358. fmt_and_decorate_addr(ext_addr),
  1359. tor_socket_strerror(*socket_error));
  1360. tor_close_socket(s);
  1361. return -1;
  1362. }
  1363. }
  1364. }
  1365. }
  1366. set_socket_nonblocking(s);
  1367. if (options->ConstrainedSockets)
  1368. set_constrained_socket_buffers(s, (int)options->ConstrainedSockSize);
  1369. memset(&addrbuf,0,sizeof(addrbuf));
  1370. dest_addr = (struct sockaddr*) &addrbuf;
  1371. dest_addr_len = tor_addr_to_sockaddr(addr, port, dest_addr, sizeof(addrbuf));
  1372. tor_assert(dest_addr_len > 0);
  1373. log_debug(LD_NET, "Connecting to %s:%u.",
  1374. escaped_safe_str_client(address), port);
  1375. if (connect(s, dest_addr, (socklen_t)dest_addr_len) < 0) {
  1376. int e = tor_socket_errno(s);
  1377. if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
  1378. /* yuck. kill it. */
  1379. *socket_error = e;
  1380. log_info(LD_NET,
  1381. "connect() to %s:%u failed: %s",
  1382. escaped_safe_str_client(address),
  1383. port, tor_socket_strerror(e));
  1384. tor_close_socket(s);
  1385. return -1;
  1386. } else {
  1387. inprogress = 1;
  1388. }
  1389. }
  1390. /* it succeeded. we're connected. */
  1391. log_fn(inprogress?LOG_DEBUG:LOG_INFO, LD_NET,
  1392. "Connection to %s:%u %s (sock "TOR_SOCKET_T_FORMAT").",
  1393. escaped_safe_str_client(address),
  1394. port, inprogress?"in progress":"established", s);
  1395. conn->s = s;
  1396. if (connection_add_connecting(conn) < 0) {
  1397. /* no space, forget it */
  1398. *socket_error = SOCK_ERRNO(ENOBUFS);
  1399. return -1;
  1400. }
  1401. return inprogress ? 0 : 1;
  1402. }
  1403. /** Convert state number to string representation for logging purposes.
  1404. */
  1405. static const char *
  1406. connection_proxy_state_to_string(int state)
  1407. {
  1408. static const char *unknown = "???";
  1409. static const char *states[] = {
  1410. "PROXY_NONE",
  1411. "PROXY_INFANT",
  1412. "PROXY_HTTPS_WANT_CONNECT_OK",
  1413. "PROXY_SOCKS4_WANT_CONNECT_OK",
  1414. "PROXY_SOCKS5_WANT_AUTH_METHOD_NONE",
  1415. "PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929",
  1416. "PROXY_SOCKS5_WANT_AUTH_RFC1929_OK",
  1417. "PROXY_SOCKS5_WANT_CONNECT_OK",
  1418. "PROXY_CONNECTED",
  1419. };
  1420. if (state < PROXY_NONE || state > PROXY_CONNECTED)
  1421. return unknown;
  1422. return states[state];
  1423. }
  1424. /** Write a proxy request of <b>type</b> (socks4, socks5, https) to conn
  1425. * for conn->addr:conn->port, authenticating with the auth details given
  1426. * in the configuration (if available). SOCKS 5 and HTTP CONNECT proxies
  1427. * support authentication.
  1428. *
  1429. * Returns -1 if conn->addr is incompatible with the proxy protocol, and
  1430. * 0 otherwise.
  1431. *
  1432. * Use connection_read_proxy_handshake() to complete the handshake.
  1433. */
  1434. int
  1435. connection_proxy_connect(connection_t *conn, int type)
  1436. {
  1437. const or_options_t *options;
  1438. tor_assert(conn);
  1439. options = get_options();
  1440. switch (type) {
  1441. case PROXY_CONNECT: {
  1442. char buf[1024];
  1443. char *base64_authenticator=NULL;
  1444. const char *authenticator = options->HTTPSProxyAuthenticator;
  1445. /* Send HTTP CONNECT and authentication (if available) in
  1446. * one request */
  1447. if (authenticator) {
  1448. base64_authenticator = alloc_http_authenticator(authenticator);
  1449. if (!base64_authenticator)
  1450. log_warn(LD_OR, "Encoding https authenticator failed");
  1451. }
  1452. if (base64_authenticator) {
  1453. const char *addrport = fmt_addrport(&conn->addr, conn->port);
  1454. tor_snprintf(buf, sizeof(buf), "CONNECT %s HTTP/1.1\r\n"
  1455. "Host: %s\r\n"
  1456. "Proxy-Authorization: Basic %s\r\n\r\n",
  1457. addrport,
  1458. addrport,
  1459. base64_authenticator);
  1460. tor_free(base64_authenticator);
  1461. } else {
  1462. tor_snprintf(buf, sizeof(buf), "CONNECT %s HTTP/1.0\r\n\r\n",
  1463. fmt_addrport(&conn->addr, conn->port));
  1464. }
  1465. connection_write_to_buf(buf, strlen(buf), conn);
  1466. conn->proxy_state = PROXY_HTTPS_WANT_CONNECT_OK;
  1467. break;
  1468. }
  1469. case PROXY_SOCKS4: {
  1470. unsigned char buf[9];
  1471. uint16_t portn;
  1472. uint32_t ip4addr;
  1473. /* Send a SOCKS4 connect request with empty user id */
  1474. if (tor_addr_family(&conn->addr) != AF_INET) {
  1475. log_warn(LD_NET, "SOCKS4 client is incompatible with IPv6");
  1476. return -1;
  1477. }
  1478. ip4addr = tor_addr_to_ipv4n(&conn->addr);
  1479. portn = htons(conn->port);
  1480. buf[0] = 4; /* version */
  1481. buf[1] = SOCKS_COMMAND_CONNECT; /* command */
  1482. memcpy(buf + 2, &portn, 2); /* port */
  1483. memcpy(buf + 4, &ip4addr, 4); /* addr */
  1484. buf[8] = 0; /* userid (empty) */
  1485. connection_write_to_buf((char *)buf, sizeof(buf), conn);
  1486. conn->proxy_state = PROXY_SOCKS4_WANT_CONNECT_OK;
  1487. break;
  1488. }
  1489. case PROXY_SOCKS5: {
  1490. unsigned char buf[4]; /* fields: vers, num methods, method list */
  1491. /* Send a SOCKS5 greeting (connect request must wait) */
  1492. buf[0] = 5; /* version */
  1493. /* number of auth methods */
  1494. if (options->Socks5ProxyUsername) {
  1495. buf[1] = 2;
  1496. buf[2] = 0x00; /* no authentication */
  1497. buf[3] = 0x02; /* rfc1929 Username/Passwd auth */
  1498. conn->proxy_state = PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929;
  1499. } else {
  1500. buf[1] = 1;
  1501. buf[2] = 0x00; /* no authentication */
  1502. conn->proxy_state = PROXY_SOCKS5_WANT_AUTH_METHOD_NONE;
  1503. }
  1504. connection_write_to_buf((char *)buf, 2 + buf[1], conn);
  1505. break;
  1506. }
  1507. default:
  1508. log_err(LD_BUG, "Invalid proxy protocol, %d", type);
  1509. tor_fragile_assert();
  1510. return -1;
  1511. }
  1512. log_debug(LD_NET, "set state %s",
  1513. connection_proxy_state_to_string(conn->proxy_state));
  1514. return 0;
  1515. }
  1516. /** Read conn's inbuf. If the http response from the proxy is all
  1517. * here, make sure it's good news, then return 1. If it's bad news,
  1518. * return -1. Else return 0 and hope for better luck next time.
  1519. */
  1520. static int
  1521. connection_read_https_proxy_response(connection_t *conn)
  1522. {
  1523. char *headers;
  1524. char *reason=NULL;
  1525. int status_code;
  1526. time_t date_header;
  1527. switch (fetch_from_buf_http(conn->inbuf,
  1528. &headers, MAX_HEADERS_SIZE,
  1529. NULL, NULL, 10000, 0)) {
  1530. case -1: /* overflow */
  1531. log_warn(LD_PROTOCOL,
  1532. "Your https proxy sent back an oversized response. Closing.");
  1533. return -1;
  1534. case 0:
  1535. log_info(LD_NET,"https proxy response not all here yet. Waiting.");
  1536. return 0;
  1537. /* case 1, fall through */
  1538. }
  1539. if (parse_http_response(headers, &status_code, &date_header,
  1540. NULL, &reason) < 0) {
  1541. log_warn(LD_NET,
  1542. "Unparseable headers from proxy (connecting to '%s'). Closing.",
  1543. conn->address);
  1544. tor_free(headers);
  1545. return -1;
  1546. }
  1547. if (!reason) reason = tor_strdup("[no reason given]");
  1548. if (status_code == 200) {
  1549. log_info(LD_NET,
  1550. "HTTPS connect to '%s' successful! (200 %s) Starting TLS.",
  1551. conn->address, escaped(reason));
  1552. tor_free(reason);
  1553. return 1;
  1554. }
  1555. /* else, bad news on the status code */
  1556. switch (status_code) {
  1557. case 403:
  1558. log_warn(LD_NET,
  1559. "The https proxy refused to allow connection to %s "
  1560. "(status code %d, %s). Closing.",
  1561. conn->address, status_code, escaped(reason));
  1562. break;
  1563. default:
  1564. log_warn(LD_NET,
  1565. "The https proxy sent back an unexpected status code %d (%s). "
  1566. "Closing.",
  1567. status_code, escaped(reason));
  1568. break;
  1569. }
  1570. tor_free(reason);
  1571. return -1;
  1572. }
  1573. /** Send SOCKS5 CONNECT command to <b>conn</b>, copying <b>conn->addr</b>
  1574. * and <b>conn->port</b> into the request.
  1575. */
  1576. static void
  1577. connection_send_socks5_connect(connection_t *conn)
  1578. {
  1579. unsigned char buf[1024];
  1580. size_t reqsize = 6;
  1581. uint16_t port = htons(conn->port);
  1582. buf[0] = 5; /* version */
  1583. buf[1] = SOCKS_COMMAND_CONNECT; /* command */
  1584. buf[2] = 0; /* reserved */
  1585. if (tor_addr_family(&conn->addr) == AF_INET) {
  1586. uint32_t addr = tor_addr_to_ipv4n(&conn->addr);
  1587. buf[3] = 1;
  1588. reqsize += 4;
  1589. memcpy(buf + 4, &addr, 4);
  1590. memcpy(buf + 8, &port, 2);
  1591. } else { /* AF_INET6 */
  1592. buf[3] = 4;
  1593. reqsize += 16;
  1594. memcpy(buf + 4, tor_addr_to_in6(&conn->addr), 16);
  1595. memcpy(buf + 20, &port, 2);
  1596. }
  1597. connection_write_to_buf((char *)buf, reqsize, conn);
  1598. conn->proxy_state = PROXY_SOCKS5_WANT_CONNECT_OK;
  1599. }
  1600. /** Wrapper around fetch_from_(buf/evbuffer)_socks_client: see those functions
  1601. * for documentation of its behavior. */
  1602. static int
  1603. connection_fetch_from_buf_socks_client(connection_t *conn,
  1604. int state, char **reason)
  1605. {
  1606. IF_HAS_BUFFEREVENT(conn, {
  1607. struct evbuffer *input = bufferevent_get_input(conn->bufev);
  1608. return fetch_from_evbuffer_socks_client(input, state, reason);
  1609. }) ELSE_IF_NO_BUFFEREVENT {
  1610. return fetch_from_buf_socks_client(conn->inbuf, state, reason);
  1611. }
  1612. }
  1613. /** Call this from connection_*_process_inbuf() to advance the proxy
  1614. * handshake.
  1615. *
  1616. * No matter what proxy protocol is used, if this function returns 1, the
  1617. * handshake is complete, and the data remaining on inbuf may contain the
  1618. * start of the communication with the requested server.
  1619. *
  1620. * Returns 0 if the current buffer contains an incomplete response, and -1
  1621. * on error.
  1622. */
  1623. int
  1624. connection_read_proxy_handshake(connection_t *conn)
  1625. {
  1626. int ret = 0;
  1627. char *reason = NULL;
  1628. log_debug(LD_NET, "enter state %s",
  1629. connection_proxy_state_to_string(conn->proxy_state));
  1630. switch (conn->proxy_state) {
  1631. case PROXY_HTTPS_WANT_CONNECT_OK:
  1632. ret = connection_read_https_proxy_response(conn);
  1633. if (ret == 1)
  1634. conn->proxy_state = PROXY_CONNECTED;
  1635. break;
  1636. case PROXY_SOCKS4_WANT_CONNECT_OK:
  1637. ret = connection_fetch_from_buf_socks_client(conn,
  1638. conn->proxy_state,
  1639. &reason);
  1640. if (ret == 1)
  1641. conn->proxy_state = PROXY_CONNECTED;
  1642. break;
  1643. case PROXY_SOCKS5_WANT_AUTH_METHOD_NONE:
  1644. ret = connection_fetch_from_buf_socks_client(conn,
  1645. conn->proxy_state,
  1646. &reason);
  1647. /* no auth needed, do connect */
  1648. if (ret == 1) {
  1649. connection_send_socks5_connect(conn);
  1650. ret = 0;
  1651. }
  1652. break;
  1653. case PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929:
  1654. ret = connection_fetch_from_buf_socks_client(conn,
  1655. conn->proxy_state,
  1656. &reason);
  1657. /* send auth if needed, otherwise do connect */
  1658. if (ret == 1) {
  1659. connection_send_socks5_connect(conn);
  1660. ret = 0;
  1661. } else if (ret == 2) {
  1662. unsigned char buf[1024];
  1663. size_t reqsize, usize, psize;
  1664. const char *user, *pass;
  1665. user = get_options()->Socks5ProxyUsername;
  1666. pass = get_options()->Socks5ProxyPassword;
  1667. tor_assert(user && pass);
  1668. /* XXX len of user and pass must be <= 255 !!! */
  1669. usize = strlen(user);
  1670. psize = strlen(pass);
  1671. tor_assert(usize <= 255 && psize <= 255);
  1672. reqsize = 3 + usize + psize;
  1673. buf[0] = 1; /* negotiation version */
  1674. buf[1] = usize;
  1675. memcpy(buf + 2, user, usize);
  1676. buf[2 + usize] = psize;
  1677. memcpy(buf + 3 + usize, pass, psize);
  1678. connection_write_to_buf((char *)buf, reqsize, conn);
  1679. conn->proxy_state = PROXY_SOCKS5_WANT_AUTH_RFC1929_OK;
  1680. ret = 0;
  1681. }
  1682. break;
  1683. case PROXY_SOCKS5_WANT_AUTH_RFC1929_OK:
  1684. ret = connection_fetch_from_buf_socks_client(conn,
  1685. conn->proxy_state,
  1686. &reason);
  1687. /* send the connect request */
  1688. if (ret == 1) {
  1689. connection_send_socks5_connect(conn);
  1690. ret = 0;
  1691. }
  1692. break;
  1693. case PROXY_SOCKS5_WANT_CONNECT_OK:
  1694. ret = connection_fetch_from_buf_socks_client(conn,
  1695. conn->proxy_state,
  1696. &reason);
  1697. if (ret == 1)
  1698. conn->proxy_state = PROXY_CONNECTED;
  1699. break;
  1700. default:
  1701. log_err(LD_BUG, "Invalid proxy_state for reading, %d",
  1702. conn->proxy_state);
  1703. tor_fragile_assert();
  1704. ret = -1;
  1705. break;
  1706. }
  1707. log_debug(LD_NET, "leaving state %s",
  1708. connection_proxy_state_to_string(conn->proxy_state));
  1709. if (ret < 0) {
  1710. if (reason) {
  1711. log_warn(LD_NET, "Proxy Client: unable to connect to %s:%d (%s)",
  1712. conn->address, conn->port, escaped(reason));
  1713. tor_free(reason);
  1714. } else {
  1715. log_warn(LD_NET, "Proxy Client: unable to connect to %s:%d",
  1716. conn->address, conn->port);
  1717. }
  1718. } else if (ret == 1) {
  1719. log_info(LD_NET, "Proxy Client: connection to %s:%d successful",
  1720. conn->address, conn->port);
  1721. }
  1722. return ret;
  1723. }
  1724. /** Given a list of listener connections in <b>old_conns</b>, and list of
  1725. * port_cfg_t entries in <b>ports</b>, open a new listener for every port in
  1726. * <b>ports</b> that does not already have a listener in <b>old_conns</b>.
  1727. *
  1728. * Remove from <b>old_conns</b> every connection that has a corresponding
  1729. * entry in <b>ports</b>. Add to <b>new_conns</b> new every connection we
  1730. * launch.
  1731. *
  1732. * If <b>control_listeners_only</b> is true, then we only open control
  1733. * listeners, and we do not remove any noncontrol listeners from old_conns.
  1734. *
  1735. * Return 0 on success, -1 on failure.
  1736. **/
  1737. static int
  1738. retry_listener_ports(smartlist_t *old_conns,
  1739. const smartlist_t *ports,
  1740. smartlist_t *new_conns,
  1741. int control_listeners_only)
  1742. {
  1743. smartlist_t *launch = smartlist_new();
  1744. int r = 0;
  1745. if (control_listeners_only) {
  1746. SMARTLIST_FOREACH(ports, port_cfg_t *, p, {
  1747. if (p->type == CONN_TYPE_CONTROL_LISTENER)
  1748. smartlist_add(launch, p);
  1749. });
  1750. } else {
  1751. smartlist_add_all(launch, ports);
  1752. }
  1753. /* Iterate through old_conns, comparing it to launch: remove from both lists
  1754. * each pair of elements that corresponds to the same port. */
  1755. SMARTLIST_FOREACH_BEGIN(old_conns, connection_t *, conn) {
  1756. const port_cfg_t *found_port = NULL;
  1757. /* Okay, so this is a listener. Is it configured? */
  1758. SMARTLIST_FOREACH_BEGIN(launch, const port_cfg_t *, wanted) {
  1759. if (conn->type != wanted->type)
  1760. continue;
  1761. if ((conn->socket_family != AF_UNIX && wanted->is_unix_addr) ||
  1762. (conn->socket_family == AF_UNIX && ! wanted->is_unix_addr))
  1763. continue;
  1764. if (wanted->no_listen)
  1765. continue; /* We don't want to open a listener for this one */
  1766. if (wanted->is_unix_addr) {
  1767. if (conn->socket_family == AF_UNIX &&
  1768. !strcmp(wanted->unix_addr, conn->address)) {
  1769. found_port = wanted;
  1770. break;
  1771. }
  1772. } else {
  1773. int port_matches;
  1774. if (wanted->port == CFG_AUTO_PORT) {
  1775. port_matches = 1;
  1776. } else {
  1777. port_matches = (wanted->port == conn->port);
  1778. }
  1779. if (port_matches && tor_addr_eq(&wanted->addr, &conn->addr)) {
  1780. found_port = wanted;
  1781. break;
  1782. }
  1783. }
  1784. } SMARTLIST_FOREACH_END(wanted);
  1785. if (found_port) {
  1786. /* This listener is already running; we don't need to launch it. */
  1787. //log_debug(LD_NET, "Already have %s on %s:%d",
  1788. // conn_type_to_string(found_port->type), conn->address, conn->port);
  1789. smartlist_remove(launch, found_port);
  1790. /* And we can remove the connection from old_conns too. */
  1791. SMARTLIST_DEL_CURRENT(old_conns, conn);
  1792. }
  1793. } SMARTLIST_FOREACH_END(conn);
  1794. /* Now open all the listeners that are configured but not opened. */
  1795. SMARTLIST_FOREACH_BEGIN(launch, const port_cfg_t *, port) {
  1796. struct sockaddr *listensockaddr;
  1797. socklen_t listensocklen = 0;
  1798. char *address=NULL;
  1799. connection_t *conn;
  1800. int real_port = port->port == CFG_AUTO_PORT ? 0 : port->port;
  1801. tor_assert(real_port <= UINT16_MAX);
  1802. if (port->no_listen)
  1803. continue;
  1804. if (port->is_unix_addr) {
  1805. listensockaddr = (struct sockaddr *)
  1806. create_unix_sockaddr(port->unix_addr,
  1807. &address, &listensocklen);
  1808. } else {
  1809. listensockaddr = tor_malloc(sizeof(struct sockaddr_storage));
  1810. listensocklen = tor_addr_to_sockaddr(&port->addr,
  1811. real_port,
  1812. listensockaddr,
  1813. sizeof(struct sockaddr_storage));
  1814. address = tor_dup_addr(&port->addr);
  1815. }
  1816. if (listensockaddr) {
  1817. conn = connection_listener_new(listensockaddr, listensocklen,
  1818. port->type, address, port);
  1819. tor_free(listensockaddr);
  1820. tor_free(address);
  1821. } else {
  1822. conn = NULL;
  1823. }
  1824. if (!conn) {
  1825. r = -1;
  1826. } else {
  1827. if (new_conns)
  1828. smartlist_add(new_conns, conn);
  1829. }
  1830. } SMARTLIST_FOREACH_END(port);
  1831. smartlist_free(launch);
  1832. return r;
  1833. }
  1834. /** Launch listeners for each port you should have open. Only launch
  1835. * listeners who are not already open, and only close listeners we no longer
  1836. * want.
  1837. *
  1838. * Add all old conns that should be closed to <b>replaced_conns</b>.
  1839. * Add all new connections to <b>new_conns</b>.
  1840. *
  1841. * If <b>close_all_noncontrol</b> is true, then we only open control
  1842. * listeners, and we close all other listeners.
  1843. */
  1844. int
  1845. retry_all_listeners(smartlist_t *replaced_conns,
  1846. smartlist_t *new_conns, int close_all_noncontrol)
  1847. {
  1848. smartlist_t *listeners = smartlist_new();
  1849. const or_options_t *options = get_options();
  1850. int retval = 0;
  1851. const uint16_t old_or_port = router_get_advertised_or_port(options);
  1852. const uint16_t old_dir_port = router_get_advertised_dir_port(options, 0);
  1853. SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t *, conn) {
  1854. if (connection_is_listener(conn) && !conn->marked_for_close)
  1855. smartlist_add(listeners, conn);
  1856. } SMARTLIST_FOREACH_END(conn);
  1857. if (retry_listener_ports(listeners,
  1858. get_configured_ports(),
  1859. new_conns,
  1860. close_all_noncontrol) < 0)
  1861. retval = -1;
  1862. /* Any members that were still in 'listeners' don't correspond to
  1863. * any configured port. Kill 'em. */
  1864. SMARTLIST_FOREACH_BEGIN(listeners, connection_t *, conn) {
  1865. log_notice(LD_NET, "Closing no-longer-configured %s on %s:%d",
  1866. conn_type_to_string(conn->type), conn->address, conn->port);
  1867. if (replaced_conns) {
  1868. smartlist_add(replaced_conns, conn);
  1869. } else {
  1870. connection_close_immediate(conn);
  1871. connection_mark_for_close(conn);
  1872. }
  1873. } SMARTLIST_FOREACH_END(conn);
  1874. smartlist_free(listeners);
  1875. /* XXXprop186 should take all advertised ports into account */
  1876. if (old_or_port != router_get_advertised_or_port(options) ||
  1877. old_dir_port != router_get_advertised_dir_port(options, 0)) {
  1878. /* Our chosen ORPort or DirPort is not what it used to be: the
  1879. * descriptor we had (if any) should be regenerated. (We won't
  1880. * automatically notice this because of changes in the option,
  1881. * since the value could be "auto".) */
  1882. mark_my_descriptor_dirty("Chosen Or/DirPort changed");
  1883. }
  1884. return retval;
  1885. }
  1886. /** Mark every listener of type other than CONTROL_LISTENER to be closed. */
  1887. void
  1888. connection_mark_all_noncontrol_listeners(void)
  1889. {
  1890. SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t *, conn) {
  1891. if (conn->marked_for_close)
  1892. continue;
  1893. if (conn->type == CONN_TYPE_CONTROL_LISTENER)
  1894. continue;
  1895. if (connection_is_listener(conn))
  1896. connection_mark_for_close(conn);
  1897. } SMARTLIST_FOREACH_END(conn);
  1898. }
  1899. /** Mark every external connection not used for controllers for close. */
  1900. void
  1901. connection_mark_all_noncontrol_connections(void)
  1902. {
  1903. SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t *, conn) {
  1904. if (conn->marked_for_close)
  1905. continue;
  1906. switch (conn->type) {
  1907. case CONN_TYPE_CPUWORKER:
  1908. case CONN_TYPE_CONTROL_LISTENER:
  1909. case CONN_TYPE_CONTROL:
  1910. break;
  1911. case CONN_TYPE_AP:
  1912. connection_mark_unattached_ap(TO_ENTRY_CONN(conn),
  1913. END_STREAM_REASON_HIBERNATING);
  1914. break;
  1915. default:
  1916. connection_mark_for_close(conn);
  1917. break;
  1918. }
  1919. } SMARTLIST_FOREACH_END(conn);
  1920. }
  1921. /** Return 1 if we should apply rate limiting to <b>conn</b>, and 0
  1922. * otherwise.
  1923. * Right now this just checks if it's an internal IP address or an
  1924. * internal connection. We also should, but don't, check if the connection
  1925. * uses pluggable transports, since we should then limit it even if it
  1926. * comes from an internal IP address. */
  1927. static int
  1928. connection_is_rate_limited(connection_t *conn)
  1929. {
  1930. const or_options_t *options = get_options();
  1931. if (conn->linked)
  1932. return 0; /* Internal connection */
  1933. else if (! options->CountPrivateBandwidth &&
  1934. (tor_addr_family(&conn->addr) == AF_UNSPEC || /* no address */
  1935. tor_addr_is_internal(&conn->addr, 0)))
  1936. return 0; /* Internal address */
  1937. else
  1938. return 1;
  1939. }
  1940. #ifdef USE_BUFFEREVENTS
  1941. static struct bufferevent_rate_limit_group *global_rate_limit = NULL;
  1942. #else
  1943. extern int global_read_bucket, global_write_bucket;
  1944. extern int global_relayed_read_bucket, global_relayed_write_bucket;
  1945. /** Did either global write bucket run dry last second? If so,
  1946. * we are likely to run dry again this second, so be stingy with the
  1947. * tokens we just put in. */
  1948. static int write_buckets_empty_last_second = 0;
  1949. #endif
  1950. /** How many seconds of no active local circuits will make the
  1951. * connection revert to the "relayed" bandwidth class? */
  1952. #define CLIENT_IDLE_TIME_FOR_PRIORITY 30
  1953. #ifndef USE_BUFFEREVENTS
  1954. /** Return 1 if <b>conn</b> should use tokens from the "relayed"
  1955. * bandwidth rates, else 0. Currently, only OR conns with bandwidth
  1956. * class 1, and directory conns that are serving data out, count.
  1957. */
  1958. static int
  1959. connection_counts_as_relayed_traffic(connection_t *conn, time_t now)
  1960. {
  1961. if (conn->type == CONN_TYPE_OR &&
  1962. connection_or_client_used(TO_OR_CONN(conn)) +
  1963. CLIENT_IDLE_TIME_FOR_PRIORITY < now)
  1964. return 1;
  1965. if (conn->type == CONN_TYPE_DIR && DIR_CONN_IS_SERVER(conn))
  1966. return 1;
  1967. return 0;
  1968. }
  1969. /** Helper function to decide how many bytes out of <b>global_bucket</b>
  1970. * we're willing to use for this transaction. <b>base</b> is the size
  1971. * of a cell on the network; <b>priority</b> says whether we should
  1972. * write many of them or just a few; and <b>conn_bucket</b> (if
  1973. * non-negative) provides an upper limit for our answer. */
  1974. static ssize_t
  1975. connection_bucket_round_robin(int base, int priority,
  1976. ssize_t global_bucket, ssize_t conn_bucket)
  1977. {
  1978. ssize_t at_most;
  1979. ssize_t num_bytes_high = (priority ? 32 : 16) * base;
  1980. ssize_t num_bytes_low = (priority ? 4 : 2) * base;
  1981. /* Do a rudimentary round-robin so one circuit can't hog a connection.
  1982. * Pick at most 32 cells, at least 4 cells if possible, and if we're in
  1983. * the middle pick 1/8 of the available bandwidth. */
  1984. at_most = global_bucket / 8;
  1985. at_most -= (at_most % base); /* round down */
  1986. if (at_most > num_bytes_high) /* 16 KB, or 8 KB for low-priority */
  1987. at_most = num_bytes_high;
  1988. else if (at_most < num_bytes_low) /* 2 KB, or 1 KB for low-priority */
  1989. at_most = num_bytes_low;
  1990. if (at_most > global_bucket)
  1991. at_most = global_bucket;
  1992. if (conn_bucket >= 0 && at_most > conn_bucket)
  1993. at_most = conn_bucket;
  1994. if (at_most < 0)
  1995. return 0;
  1996. return at_most;
  1997. }
  1998. /** How many bytes at most can we read onto this connection? */
  1999. static ssize_t
  2000. connection_bucket_read_limit(connection_t *conn, time_t now)
  2001. {
  2002. int base = connection_speaks_cells(conn) ?
  2003. CELL_NETWORK_SIZE : RELAY_PAYLOAD_SIZE;
  2004. int priority = conn->type != CONN_TYPE_DIR;
  2005. int conn_bucket = -1;
  2006. int global_bucket = global_read_bucket;
  2007. if (connection_speaks_cells(conn)) {
  2008. or_connection_t *or_conn = TO_OR_CONN(conn);
  2009. if (conn->state == OR_CONN_STATE_OPEN)
  2010. conn_bucket = or_conn->read_bucket;
  2011. }
  2012. if (!connection_is_rate_limited(conn)) {
  2013. /* be willing to read on local conns even if our buckets are empty */
  2014. return conn_bucket>=0 ? conn_bucket : 1<<14;
  2015. }
  2016. if (connection_counts_as_relayed_traffic(conn, now) &&
  2017. global_relayed_read_bucket <= global_read_bucket)
  2018. global_bucket = global_relayed_read_bucket;
  2019. return connection_bucket_round_robin(base, priority,
  2020. global_bucket, conn_bucket);
  2021. }
  2022. /** How many bytes at most can we write onto this connection? */
  2023. ssize_t
  2024. connection_bucket_write_limit(connection_t *conn, time_t now)
  2025. {
  2026. int base = connection_speaks_cells(conn) ?
  2027. CELL_NETWORK_SIZE : RELAY_PAYLOAD_SIZE;
  2028. int priority = conn->type != CONN_TYPE_DIR;
  2029. int conn_bucket = (int)conn->outbuf_flushlen;
  2030. int global_bucket = global_write_bucket;
  2031. if (!connection_is_rate_limited(conn)) {
  2032. /* be willing to write to local conns even if our buckets are empty */
  2033. return conn->outbuf_flushlen;
  2034. }
  2035. if (connection_speaks_cells(conn)) {
  2036. /* use the per-conn write limit if it's lower, but if it's less
  2037. * than zero just use zero */
  2038. or_connection_t *or_conn = TO_OR_CONN(conn);
  2039. if (conn->state == OR_CONN_STATE_OPEN)
  2040. if (or_conn->write_bucket < conn_bucket)
  2041. conn_bucket = or_conn->write_bucket >= 0 ?
  2042. or_conn->write_bucket : 0;
  2043. }
  2044. if (connection_counts_as_relayed_traffic(conn, now) &&
  2045. global_relayed_write_bucket <= global_write_bucket)
  2046. global_bucket = global_relayed_write_bucket;
  2047. return connection_bucket_round_robin(base, priority,
  2048. global_bucket, conn_bucket);
  2049. }
  2050. #else
  2051. static ssize_t
  2052. connection_bucket_read_limit(connection_t *conn, time_t now)
  2053. {
  2054. (void) now;
  2055. return bufferevent_get_max_to_read(conn->bufev);
  2056. }
  2057. ssize_t
  2058. connection_bucket_write_limit(connection_t *conn, time_t now)
  2059. {
  2060. (void) now;
  2061. return bufferevent_get_max_to_write(conn->bufev);
  2062. }
  2063. #endif
  2064. /** Return 1 if the global write buckets are low enough that we
  2065. * shouldn't send <b>attempt</b> bytes of low-priority directory stuff
  2066. * out to <b>conn</b>. Else return 0.
  2067. * Priority is 1 for v1 requests (directories and running-routers),
  2068. * and 2 for v2 requests (statuses and descriptors). But see FFFF in
  2069. * directory_handle_command_get() for why we don't use priority 2 yet.
  2070. *
  2071. * There are a lot of parameters we could use here:
  2072. * - global_relayed_write_bucket. Low is bad.
  2073. * - global_write_bucket. Low is bad.
  2074. * - bandwidthrate. Low is bad.
  2075. * - bandwidthburst. Not a big factor?
  2076. * - attempt. High is bad.
  2077. * - total bytes queued on outbufs. High is bad. But I'm wary of
  2078. * using this, since a few slow-flushing queues will pump up the
  2079. * number without meaning what we meant to mean. What we really
  2080. * mean is "total directory bytes added to outbufs recently", but
  2081. * that's harder to quantify and harder to keep track of.
  2082. */
  2083. int
  2084. global_write_bucket_low(connection_t *conn, size_t attempt, int priority)
  2085. {
  2086. #ifdef USE_BUFFEREVENTS
  2087. ssize_t smaller_bucket = bufferevent_get_max_to_write(conn->bufev);
  2088. #else
  2089. int smaller_bucket = global_write_bucket < global_relayed_write_bucket ?
  2090. global_write_bucket : global_relayed_write_bucket;
  2091. #endif
  2092. if (authdir_mode(get_options()) && priority>1)
  2093. return 0; /* there's always room to answer v2 if we're an auth dir */
  2094. if (!connection_is_rate_limited(conn))
  2095. return 0; /* local conns don't get limited */
  2096. if (smaller_bucket < (int)attempt)
  2097. return 1; /* not enough space no matter the priority */
  2098. #ifndef USE_BUFFEREVENTS
  2099. if (write_buckets_empty_last_second)
  2100. return 1; /* we're already hitting our limits, no more please */
  2101. #endif
  2102. if (priority == 1) { /* old-style v1 query */
  2103. /* Could we handle *two* of these requests within the next two seconds? */
  2104. const or_options_t *options = get_options();
  2105. int64_t can_write = (int64_t)smaller_bucket
  2106. + 2*(options->RelayBandwidthRate ? options->RelayBandwidthRate :
  2107. options->BandwidthRate);
  2108. if (can_write < 2*(int64_t)attempt)
  2109. return 1;
  2110. } else { /* v2 query */
  2111. /* no further constraints yet */
  2112. }
  2113. return 0;
  2114. }
  2115. /** Helper: adjusts our bandwidth history and informs the controller as
  2116. * appropriate, given that we have just read <b>num_read</b> bytes and written
  2117. * <b>num_written</b> bytes on <b>conn</b>. */
  2118. static void
  2119. record_num_bytes_transferred_impl(connection_t *conn,
  2120. time_t now, size_t num_read, size_t num_written)
  2121. {
  2122. /* Count bytes of answering direct and tunneled directory requests */
  2123. if (conn->type == CONN_TYPE_DIR && conn->purpose == DIR_PURPOSE_SERVER) {
  2124. if (num_read > 0)
  2125. rep_hist_note_dir_bytes_read(num_read, now);
  2126. if (num_written > 0)
  2127. rep_hist_note_dir_bytes_written(num_written, now);
  2128. }
  2129. if (!connection_is_rate_limited(conn))
  2130. return; /* local IPs are free */
  2131. if (conn->type == CONN_TYPE_OR)
  2132. rep_hist_note_or_conn_bytes(conn->global_identifier, num_read,
  2133. num_written, now);
  2134. if (num_read > 0) {
  2135. rep_hist_note_bytes_read(num_read, now);
  2136. }
  2137. if (num_written > 0) {
  2138. rep_hist_note_bytes_written(num_written, now);
  2139. }
  2140. if (conn->type == CONN_TYPE_EXIT)
  2141. rep_hist_note_exit_bytes(conn->port, num_written, num_read);
  2142. }
  2143. #ifdef USE_BUFFEREVENTS
  2144. /** Wrapper around fetch_from_(buf/evbuffer)_socks_client: see those functions
  2145. * for documentation of its behavior. */
  2146. static void
  2147. record_num_bytes_transferred(connection_t *conn,
  2148. time_t now, size_t num_read, size_t num_written)
  2149. {
  2150. /* XXX024 check if this is necessary */
  2151. if (num_written >= INT_MAX || num_read >= INT_MAX) {
  2152. log_err(LD_BUG, "Value out of range. num_read=%lu, num_written=%lu, "
  2153. "connection type=%s, state=%s",
  2154. (unsigned long)num_read, (unsigned long)num_written,
  2155. conn_type_to_string(conn->type),
  2156. conn_state_to_string(conn->type, conn->state));
  2157. if (num_written >= INT_MAX) num_written = 1;
  2158. if (num_read >= INT_MAX) num_read = 1;
  2159. tor_fragile_assert();
  2160. }
  2161. record_num_bytes_transferred_impl(conn,now,num_read,num_written);
  2162. }
  2163. #endif
  2164. #ifndef USE_BUFFEREVENTS
  2165. /** We just read <b>num_read</b> and wrote <b>num_written</b> bytes
  2166. * onto <b>conn</b>. Decrement buckets appropriately. */
  2167. static void
  2168. connection_buckets_decrement(connection_t *conn, time_t now,
  2169. size_t num_read, size_t num_written)
  2170. {
  2171. if (num_written >= INT_MAX || num_read >= INT_MAX) {
  2172. log_err(LD_BUG, "Value out of range. num_read=%lu, num_written=%lu, "
  2173. "connection type=%s, state=%s",
  2174. (unsigned long)num_read, (unsigned long)num_written,
  2175. conn_type_to_string(conn->type),
  2176. conn_state_to_string(conn->type, conn->state));
  2177. if (num_written >= INT_MAX) num_written = 1;
  2178. if (num_read >= INT_MAX) num_read = 1;
  2179. tor_fragile_assert();
  2180. }
  2181. record_num_bytes_transferred_impl(conn, now, num_read, num_written);
  2182. if (!connection_is_rate_limited(conn))
  2183. return; /* local IPs are free */
  2184. if (connection_counts_as_relayed_traffic(conn, now)) {
  2185. global_relayed_read_bucket -= (int)num_read;
  2186. global_relayed_write_bucket -= (int)num_written;
  2187. }
  2188. global_read_bucket -= (int)num_read;
  2189. global_write_bucket -= (int)num_written;
  2190. if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
  2191. TO_OR_CONN(conn)->read_bucket -= (int)num_read;
  2192. TO_OR_CONN(conn)->write_bucket -= (int)num_written;
  2193. }
  2194. }
  2195. /** If we have exhausted our global buckets, or the buckets for conn,
  2196. * stop reading. */
  2197. static void
  2198. connection_consider_empty_read_buckets(connection_t *conn)
  2199. {
  2200. const char *reason;
  2201. if (global_read_bucket <= 0) {
  2202. reason = "global read bucket exhausted. Pausing.";
  2203. } else if (connection_counts_as_relayed_traffic(conn, approx_time()) &&
  2204. global_relayed_read_bucket <= 0) {
  2205. reason = "global relayed read bucket exhausted. Pausing.";
  2206. } else if (connection_speaks_cells(conn) &&
  2207. conn->state == OR_CONN_STATE_OPEN &&
  2208. TO_OR_CONN(conn)->read_bucket <= 0) {
  2209. reason = "connection read bucket exhausted. Pausing.";
  2210. } else
  2211. return; /* all good, no need to stop it */
  2212. LOG_FN_CONN(conn, (LOG_DEBUG, LD_NET, "%s", reason));
  2213. conn->read_blocked_on_bw = 1;
  2214. connection_stop_reading(conn);
  2215. }
  2216. /** If we have exhausted our global buckets, or the buckets for conn,
  2217. * stop writing. */
  2218. static void
  2219. connection_consider_empty_write_buckets(connection_t *conn)
  2220. {
  2221. const char *reason;
  2222. if (global_write_bucket <= 0) {
  2223. reason = "global write bucket exhausted. Pausing.";
  2224. } else if (connection_counts_as_relayed_traffic(conn, approx_time()) &&
  2225. global_relayed_write_bucket <= 0) {
  2226. reason = "global relayed write bucket exhausted. Pausing.";
  2227. } else if (connection_speaks_cells(conn) &&
  2228. conn->state == OR_CONN_STATE_OPEN &&
  2229. TO_OR_CONN(conn)->write_bucket <= 0) {
  2230. reason = "connection write bucket exhausted. Pausing.";
  2231. } else
  2232. return; /* all good, no need to stop it */
  2233. LOG_FN_CONN(conn, (LOG_DEBUG, LD_NET, "%s", reason));
  2234. conn->write_blocked_on_bw = 1;
  2235. connection_stop_writing(conn);
  2236. }
  2237. /** Initialize the global read bucket to options-\>BandwidthBurst. */
  2238. void
  2239. connection_bucket_init(void)
  2240. {
  2241. const or_options_t *options = get_options();
  2242. /* start it at max traffic */
  2243. global_read_bucket = (int)options->BandwidthBurst;
  2244. global_write_bucket = (int)options->BandwidthBurst;
  2245. if (options->RelayBandwidthRate) {
  2246. global_relayed_read_bucket = (int)options->RelayBandwidthBurst;
  2247. global_relayed_write_bucket = (int)options->RelayBandwidthBurst;
  2248. } else {
  2249. global_relayed_read_bucket = (int)options->BandwidthBurst;
  2250. global_relayed_write_bucket = (int)options->BandwidthBurst;
  2251. }
  2252. }
  2253. /** Refill a single <b>bucket</b> called <b>name</b> with bandwidth rate per
  2254. * second <b>rate</b> and bandwidth burst <b>burst</b>, assuming that
  2255. * <b>milliseconds_elapsed</b> milliseconds have passed since the last
  2256. * call. */
  2257. static void
  2258. connection_bucket_refill_helper(int *bucket, int rate, int burst,
  2259. int milliseconds_elapsed,
  2260. const char *name)
  2261. {
  2262. int starting_bucket = *bucket;
  2263. if (starting_bucket < burst && milliseconds_elapsed > 0) {
  2264. int64_t incr = (((int64_t)rate) * milliseconds_elapsed) / 1000;
  2265. if ((burst - starting_bucket) < incr) {
  2266. *bucket = burst; /* We would overflow the bucket; just set it to
  2267. * the maximum. */
  2268. } else {
  2269. *bucket += (int)incr;
  2270. if (*bucket > burst || *bucket < starting_bucket) {
  2271. /* If we overflow the burst, or underflow our starting bucket,
  2272. * cap the bucket value to burst. */
  2273. /* XXXX this might be redundant now, but it doesn't show up
  2274. * in profiles. Remove it after analysis. */
  2275. *bucket = burst;
  2276. }
  2277. }
  2278. log(LOG_DEBUG, LD_NET,"%s now %d.", name, *bucket);
  2279. }
  2280. }
  2281. /** Time has passed; increment buckets appropriately. */
  2282. void
  2283. connection_bucket_refill(int milliseconds_elapsed, time_t now)
  2284. {
  2285. const or_options_t *options = get_options();
  2286. smartlist_t *conns = get_connection_array();
  2287. int bandwidthrate, bandwidthburst, relayrate, relayburst;
  2288. bandwidthrate = (int)options->BandwidthRate;
  2289. bandwidthburst = (int)options->BandwidthBurst;
  2290. if (options->RelayBandwidthRate) {
  2291. relayrate = (int)options->RelayBandwidthRate;
  2292. relayburst = (int)options->RelayBandwidthBurst;
  2293. } else {
  2294. relayrate = bandwidthrate;
  2295. relayburst = bandwidthburst;
  2296. }
  2297. tor_assert(milliseconds_elapsed >= 0);
  2298. write_buckets_empty_last_second =
  2299. global_relayed_write_bucket <= 0 || global_write_bucket <= 0;
  2300. /* refill the global buckets */
  2301. connection_bucket_refill_helper(&global_read_bucket,
  2302. bandwidthrate, bandwidthburst,
  2303. milliseconds_elapsed,
  2304. "global_read_bucket");
  2305. connection_bucket_refill_helper(&global_write_bucket,
  2306. bandwidthrate, bandwidthburst,
  2307. milliseconds_elapsed,
  2308. "global_write_bucket");
  2309. connection_bucket_refill_helper(&global_relayed_read_bucket,
  2310. relayrate, relayburst,
  2311. milliseconds_elapsed,
  2312. "global_relayed_read_bucket");
  2313. connection_bucket_refill_helper(&global_relayed_write_bucket,
  2314. relayrate, relayburst,
  2315. milliseconds_elapsed,
  2316. "global_relayed_write_bucket");
  2317. /* refill the per-connection buckets */
  2318. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  2319. if (connection_speaks_cells(conn)) {
  2320. or_connection_t *or_conn = TO_OR_CONN(conn);
  2321. int orbandwidthrate = or_conn->bandwidthrate;
  2322. int orbandwidthburst = or_conn->bandwidthburst;
  2323. if (connection_bucket_should_increase(or_conn->read_bucket, or_conn)) {
  2324. connection_bucket_refill_helper(&or_conn->read_bucket,
  2325. orbandwidthrate,
  2326. orbandwidthburst,
  2327. milliseconds_elapsed,
  2328. "or_conn->read_bucket");
  2329. }
  2330. if (connection_bucket_should_increase(or_conn->write_bucket, or_conn)) {
  2331. connection_bucket_refill_helper(&or_conn->write_bucket,
  2332. orbandwidthrate,
  2333. orbandwidthburst,
  2334. milliseconds_elapsed,
  2335. "or_conn->write_bucket");
  2336. }
  2337. }
  2338. if (conn->read_blocked_on_bw == 1 /* marked to turn reading back on now */
  2339. && global_read_bucket > 0 /* and we're allowed to read */
  2340. && (!connection_counts_as_relayed_traffic(conn, now) ||
  2341. global_relayed_read_bucket > 0) /* even if we're relayed traffic */
  2342. && (!connection_speaks_cells(conn) ||
  2343. conn->state != OR_CONN_STATE_OPEN ||
  2344. TO_OR_CONN(conn)->read_bucket > 0)) {
  2345. /* and either a non-cell conn or a cell conn with non-empty bucket */
  2346. LOG_FN_CONN(conn, (LOG_DEBUG,LD_NET,
  2347. "waking up conn (fd %d) for read", (int)conn->s));
  2348. conn->read_blocked_on_bw = 0;
  2349. connection_start_reading(conn);
  2350. }
  2351. if (conn->write_blocked_on_bw == 1
  2352. && global_write_bucket > 0 /* and we're allowed to write */
  2353. && (!connection_counts_as_relayed_traffic(conn, now) ||
  2354. global_relayed_write_bucket > 0) /* even if it's relayed traffic */
  2355. && (!connection_speaks_cells(conn) ||
  2356. conn->state != OR_CONN_STATE_OPEN ||
  2357. TO_OR_CONN(conn)->write_bucket > 0)) {
  2358. LOG_FN_CONN(conn, (LOG_DEBUG,LD_NET,
  2359. "waking up conn (fd %d) for write", (int)conn->s));
  2360. conn->write_blocked_on_bw = 0;
  2361. connection_start_writing(conn);
  2362. }
  2363. } SMARTLIST_FOREACH_END(conn);
  2364. }
  2365. /** Is the <b>bucket</b> for connection <b>conn</b> low enough that we
  2366. * should add another pile of tokens to it?
  2367. */
  2368. static int
  2369. connection_bucket_should_increase(int bucket, or_connection_t *conn)
  2370. {
  2371. tor_assert(conn);
  2372. if (conn->base_.state != OR_CONN_STATE_OPEN)
  2373. return 0; /* only open connections play the rate limiting game */
  2374. if (bucket >= conn->bandwidthburst)
  2375. return 0;
  2376. return 1;
  2377. }
  2378. #else
  2379. static void
  2380. connection_buckets_decrement(connection_t *conn, time_t now,
  2381. size_t num_read, size_t num_written)
  2382. {
  2383. (void) conn;
  2384. (void) now;
  2385. (void) num_read;
  2386. (void) num_written;
  2387. /* Libevent does this for us. */
  2388. }
  2389. void
  2390. connection_bucket_refill(int seconds_elapsed, time_t now)
  2391. {
  2392. (void) seconds_elapsed;
  2393. (void) now;
  2394. /* Libevent does this for us. */
  2395. }
  2396. void
  2397. connection_bucket_init(void)
  2398. {
  2399. const or_options_t *options = get_options();
  2400. const struct timeval *tick = tor_libevent_get_one_tick_timeout();
  2401. struct ev_token_bucket_cfg *bucket_cfg;
  2402. uint64_t rate, burst;
  2403. if (options->RelayBandwidthRate) {
  2404. rate = options->RelayBandwidthRate;
  2405. burst = options->RelayBandwidthBurst;
  2406. } else {
  2407. rate = options->BandwidthRate;
  2408. burst = options->BandwidthBurst;
  2409. }
  2410. /* This can't overflow, since TokenBucketRefillInterval <= 1000,
  2411. * and rate started out less than INT32_MAX. */
  2412. rate = (rate * options->TokenBucketRefillInterval) / 1000;
  2413. bucket_cfg = ev_token_bucket_cfg_new((uint32_t)rate, (uint32_t)burst,
  2414. (uint32_t)rate, (uint32_t)burst,
  2415. tick);
  2416. if (!global_rate_limit) {
  2417. global_rate_limit =
  2418. bufferevent_rate_limit_group_new(tor_libevent_get_base(), bucket_cfg);
  2419. } else {
  2420. bufferevent_rate_limit_group_set_cfg(global_rate_limit, bucket_cfg);
  2421. }
  2422. ev_token_bucket_cfg_free(bucket_cfg);
  2423. }
  2424. void
  2425. connection_get_rate_limit_totals(uint64_t *read_out, uint64_t *written_out)
  2426. {
  2427. if (global_rate_limit == NULL) {
  2428. *read_out = *written_out = 0;
  2429. } else {
  2430. bufferevent_rate_limit_group_get_totals(
  2431. global_rate_limit, read_out, written_out);
  2432. }
  2433. }
  2434. /** Perform whatever operations are needed on <b>conn</b> to enable
  2435. * rate-limiting. */
  2436. void
  2437. connection_enable_rate_limiting(connection_t *conn)
  2438. {
  2439. if (conn->bufev) {
  2440. if (!global_rate_limit)
  2441. connection_bucket_init();
  2442. tor_add_bufferevent_to_rate_limit_group(conn->bufev, global_rate_limit);
  2443. }
  2444. }
  2445. static void
  2446. connection_consider_empty_write_buckets(connection_t *conn)
  2447. {
  2448. (void) conn;
  2449. }
  2450. static void
  2451. connection_consider_empty_read_buckets(connection_t *conn)
  2452. {
  2453. (void) conn;
  2454. }
  2455. #endif
  2456. /** Read bytes from conn-\>s and process them.
  2457. *
  2458. * It calls connection_read_to_buf() to bring in any new bytes,
  2459. * and then calls connection_process_inbuf() to process them.
  2460. *
  2461. * Mark the connection and return -1 if you want to close it, else
  2462. * return 0.
  2463. */
  2464. static int
  2465. connection_handle_read_impl(connection_t *conn)
  2466. {
  2467. ssize_t max_to_read=-1, try_to_read;
  2468. size_t before, n_read = 0;
  2469. int socket_error = 0;
  2470. if (conn->marked_for_close)
  2471. return 0; /* do nothing */
  2472. conn->timestamp_lastread = approx_time();
  2473. switch (conn->type) {
  2474. case CONN_TYPE_OR_LISTENER:
  2475. return connection_handle_listener_read(conn, CONN_TYPE_OR);
  2476. case CONN_TYPE_AP_LISTENER:
  2477. case CONN_TYPE_AP_TRANS_LISTENER:
  2478. case CONN_TYPE_AP_NATD_LISTENER:
  2479. return connection_handle_listener_read(conn, CONN_TYPE_AP);
  2480. case CONN_TYPE_DIR_LISTENER:
  2481. return connection_handle_listener_read(conn, CONN_TYPE_DIR);
  2482. case CONN_TYPE_CONTROL_LISTENER:
  2483. return connection_handle_listener_read(conn, CONN_TYPE_CONTROL);
  2484. case CONN_TYPE_AP_DNS_LISTENER:
  2485. /* This should never happen; eventdns.c handles the reads here. */
  2486. tor_fragile_assert();
  2487. return 0;
  2488. }
  2489. loop_again:
  2490. try_to_read = max_to_read;
  2491. tor_assert(!conn->marked_for_close);
  2492. before = buf_datalen(conn->inbuf);
  2493. if (connection_read_to_buf(conn, &max_to_read, &socket_error) < 0) {
  2494. /* There's a read error; kill the connection.*/
  2495. if (conn->type == CONN_TYPE_OR) {
  2496. connection_or_notify_error(TO_OR_CONN(conn),
  2497. socket_error != 0 ?
  2498. errno_to_orconn_end_reason(socket_error) :
  2499. END_OR_CONN_REASON_CONNRESET,
  2500. socket_error != 0 ?
  2501. tor_socket_strerror(socket_error) :
  2502. "(unknown, errno was 0)");
  2503. }
  2504. if (CONN_IS_EDGE(conn)) {
  2505. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  2506. connection_edge_end_errno(edge_conn);
  2507. if (conn->type == CONN_TYPE_AP && TO_ENTRY_CONN(conn)->socks_request) {
  2508. /* broken, don't send a socks reply back */
  2509. TO_ENTRY_CONN(conn)->socks_request->has_finished = 1;
  2510. }
  2511. }
  2512. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  2513. /*
  2514. * This can bypass normal channel checking since we did
  2515. * connection_or_notify_error() above.
  2516. */
  2517. connection_mark_for_close_internal(conn);
  2518. return -1;
  2519. }
  2520. n_read += buf_datalen(conn->inbuf) - before;
  2521. if (CONN_IS_EDGE(conn) && try_to_read != max_to_read) {
  2522. /* instruct it not to try to package partial cells. */
  2523. if (connection_process_inbuf(conn, 0) < 0) {
  2524. return -1;
  2525. }
  2526. if (!conn->marked_for_close &&
  2527. connection_is_reading(conn) &&
  2528. !conn->inbuf_reached_eof &&
  2529. max_to_read > 0)
  2530. goto loop_again; /* try reading again, in case more is here now */
  2531. }
  2532. /* one last try, packaging partial cells and all. */
  2533. if (!conn->marked_for_close &&
  2534. connection_process_inbuf(conn, 1) < 0) {
  2535. return -1;
  2536. }
  2537. if (conn->linked_conn) {
  2538. /* The other side's handle_write() will never actually get called, so
  2539. * we need to invoke the appropriate callbacks ourself. */
  2540. connection_t *linked = conn->linked_conn;
  2541. if (n_read) {
  2542. /* Probably a no-op, since linked conns typically don't count for
  2543. * bandwidth rate limiting. But do it anyway so we can keep stats
  2544. * accurately. Note that since we read the bytes from conn, and
  2545. * we're writing the bytes onto the linked connection, we count
  2546. * these as <i>written</i> bytes. */
  2547. connection_buckets_decrement(linked, approx_time(), 0, n_read);
  2548. if (connection_flushed_some(linked) < 0)
  2549. connection_mark_for_close(linked);
  2550. if (!connection_wants_to_flush(linked))
  2551. connection_finished_flushing(linked);
  2552. }
  2553. if (!buf_datalen(linked->outbuf) && conn->active_on_link)
  2554. connection_stop_reading_from_linked_conn(conn);
  2555. }
  2556. /* If we hit the EOF, call connection_reached_eof(). */
  2557. if (!conn->marked_for_close &&
  2558. conn->inbuf_reached_eof &&
  2559. connection_reached_eof(conn) < 0) {
  2560. return -1;
  2561. }
  2562. return 0;
  2563. }
  2564. /* DOCDOC connection_handle_read */
  2565. int
  2566. connection_handle_read(connection_t *conn)
  2567. {
  2568. int res;
  2569. tor_gettimeofday_cache_clear();
  2570. res = connection_handle_read_impl(conn);
  2571. return res;
  2572. }
  2573. /** Pull in new bytes from conn-\>s or conn-\>linked_conn onto conn-\>inbuf,
  2574. * either directly or via TLS. Reduce the token buckets by the number of bytes
  2575. * read.
  2576. *
  2577. * If *max_to_read is -1, then decide it ourselves, else go with the
  2578. * value passed to us. When returning, if it's changed, subtract the
  2579. * number of bytes we read from *max_to_read.
  2580. *
  2581. * Return -1 if we want to break conn, else return 0.
  2582. */
  2583. static int
  2584. connection_read_to_buf(connection_t *conn, ssize_t *max_to_read,
  2585. int *socket_error)
  2586. {
  2587. int result;
  2588. ssize_t at_most = *max_to_read;
  2589. size_t slack_in_buf, more_to_read;
  2590. size_t n_read = 0, n_written = 0;
  2591. if (at_most == -1) { /* we need to initialize it */
  2592. /* how many bytes are we allowed to read? */
  2593. at_most = connection_bucket_read_limit(conn, approx_time());
  2594. }
  2595. slack_in_buf = buf_slack(conn->inbuf);
  2596. again:
  2597. if ((size_t)at_most > slack_in_buf && slack_in_buf >= 1024) {
  2598. more_to_read = at_most - slack_in_buf;
  2599. at_most = slack_in_buf;
  2600. } else {
  2601. more_to_read = 0;
  2602. }
  2603. if (connection_speaks_cells(conn) &&
  2604. conn->state > OR_CONN_STATE_PROXY_HANDSHAKING) {
  2605. int pending;
  2606. or_connection_t *or_conn = TO_OR_CONN(conn);
  2607. size_t initial_size;
  2608. if (conn->state == OR_CONN_STATE_TLS_HANDSHAKING ||
  2609. conn->state == OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING) {
  2610. /* continue handshaking even if global token bucket is empty */
  2611. return connection_tls_continue_handshake(or_conn);
  2612. }
  2613. log_debug(LD_NET,
  2614. "%d: starting, inbuf_datalen %ld (%d pending in tls object)."
  2615. " at_most %ld.",
  2616. (int)conn->s,(long)buf_datalen(conn->inbuf),
  2617. tor_tls_get_pending_bytes(or_conn->tls), (long)at_most);
  2618. initial_size = buf_datalen(conn->inbuf);
  2619. /* else open, or closing */
  2620. result = read_to_buf_tls(or_conn->tls, at_most, conn->inbuf);
  2621. if (TOR_TLS_IS_ERROR(result) || result == TOR_TLS_CLOSE)
  2622. or_conn->tls_error = result;
  2623. else
  2624. or_conn->tls_error = 0;
  2625. switch (result) {
  2626. case TOR_TLS_CLOSE:
  2627. case TOR_TLS_ERROR_IO:
  2628. log_debug(LD_NET,"TLS connection closed %son read. Closing. "
  2629. "(Nickname %s, address %s)",
  2630. result == TOR_TLS_CLOSE ? "cleanly " : "",
  2631. or_conn->nickname ? or_conn->nickname : "not set",
  2632. conn->address);
  2633. return result;
  2634. CASE_TOR_TLS_ERROR_ANY_NONIO:
  2635. log_debug(LD_NET,"tls error [%s]. breaking (nickname %s, address %s).",
  2636. tor_tls_err_to_string(result),
  2637. or_conn->nickname ? or_conn->nickname : "not set",
  2638. conn->address);
  2639. return result;
  2640. case TOR_TLS_WANTWRITE:
  2641. connection_start_writing(conn);
  2642. return 0;
  2643. case TOR_TLS_WANTREAD: /* we're already reading */
  2644. case TOR_TLS_DONE: /* no data read, so nothing to process */
  2645. result = 0;
  2646. break; /* so we call bucket_decrement below */
  2647. default:
  2648. break;
  2649. }
  2650. pending = tor_tls_get_pending_bytes(or_conn->tls);
  2651. if (pending) {
  2652. /* If we have any pending bytes, we read them now. This *can*
  2653. * take us over our read allotment, but really we shouldn't be
  2654. * believing that SSL bytes are the same as TCP bytes anyway. */
  2655. int r2 = read_to_buf_tls(or_conn->tls, pending, conn->inbuf);
  2656. if (r2<0) {
  2657. log_warn(LD_BUG, "apparently, reading pending bytes can fail.");
  2658. return -1;
  2659. }
  2660. }
  2661. result = (int)(buf_datalen(conn->inbuf)-initial_size);
  2662. tor_tls_get_n_raw_bytes(or_conn->tls, &n_read, &n_written);
  2663. log_debug(LD_GENERAL, "After TLS read of %d: %ld read, %ld written",
  2664. result, (long)n_read, (long)n_written);
  2665. } else if (conn->linked) {
  2666. if (conn->linked_conn) {
  2667. result = move_buf_to_buf(conn->inbuf, conn->linked_conn->outbuf,
  2668. &conn->linked_conn->outbuf_flushlen);
  2669. } else {
  2670. result = 0;
  2671. }
  2672. //log_notice(LD_GENERAL, "Moved %d bytes on an internal link!", result);
  2673. /* If the other side has disappeared, or if it's been marked for close and
  2674. * we flushed its outbuf, then we should set our inbuf_reached_eof. */
  2675. if (!conn->linked_conn ||
  2676. (conn->linked_conn->marked_for_close &&
  2677. buf_datalen(conn->linked_conn->outbuf) == 0))
  2678. conn->inbuf_reached_eof = 1;
  2679. n_read = (size_t) result;
  2680. } else {
  2681. /* !connection_speaks_cells, !conn->linked_conn. */
  2682. int reached_eof = 0;
  2683. CONN_LOG_PROTECT(conn,
  2684. result = read_to_buf(conn->s, at_most, conn->inbuf, &reached_eof,
  2685. socket_error));
  2686. if (reached_eof)
  2687. conn->inbuf_reached_eof = 1;
  2688. // log_fn(LOG_DEBUG,"read_to_buf returned %d.",read_result);
  2689. if (result < 0)
  2690. return -1;
  2691. n_read = (size_t) result;
  2692. }
  2693. if (n_read > 0) {
  2694. /* change *max_to_read */
  2695. *max_to_read = at_most - n_read;
  2696. /* Update edge_conn->n_read */
  2697. if (conn->type == CONN_TYPE_AP) {
  2698. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  2699. /* Check for overflow: */
  2700. if (PREDICT_LIKELY(UINT32_MAX - edge_conn->n_read > n_read))
  2701. edge_conn->n_read += (int)n_read;
  2702. else
  2703. edge_conn->n_read = UINT32_MAX;
  2704. }
  2705. }
  2706. connection_buckets_decrement(conn, approx_time(), n_read, n_written);
  2707. if (more_to_read && result == at_most) {
  2708. slack_in_buf = buf_slack(conn->inbuf);
  2709. at_most = more_to_read;
  2710. goto again;
  2711. }
  2712. /* Call even if result is 0, since the global read bucket may
  2713. * have reached 0 on a different conn, and this guy needs to
  2714. * know to stop reading. */
  2715. connection_consider_empty_read_buckets(conn);
  2716. if (n_written > 0 && connection_is_writing(conn))
  2717. connection_consider_empty_write_buckets(conn);
  2718. return 0;
  2719. }
  2720. #ifdef USE_BUFFEREVENTS
  2721. /* XXXX These generic versions could be simplified by making them
  2722. type-specific */
  2723. /** Callback: Invoked whenever bytes are added to or drained from an input
  2724. * evbuffer. Used to track the number of bytes read. */
  2725. static void
  2726. evbuffer_inbuf_callback(struct evbuffer *buf,
  2727. const struct evbuffer_cb_info *info, void *arg)
  2728. {
  2729. connection_t *conn = arg;
  2730. (void) buf;
  2731. /* XXXX These need to get real counts on the non-nested TLS case. - NM */
  2732. if (info->n_added) {
  2733. time_t now = approx_time();
  2734. conn->timestamp_lastread = now;
  2735. record_num_bytes_transferred(conn, now, info->n_added, 0);
  2736. connection_consider_empty_read_buckets(conn);
  2737. if (conn->type == CONN_TYPE_AP) {
  2738. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  2739. /*XXXX024 check for overflow*/
  2740. edge_conn->n_read += (int)info->n_added;
  2741. }
  2742. }
  2743. }
  2744. /** Callback: Invoked whenever bytes are added to or drained from an output
  2745. * evbuffer. Used to track the number of bytes written. */
  2746. static void
  2747. evbuffer_outbuf_callback(struct evbuffer *buf,
  2748. const struct evbuffer_cb_info *info, void *arg)
  2749. {
  2750. connection_t *conn = arg;
  2751. (void)buf;
  2752. if (info->n_deleted) {
  2753. time_t now = approx_time();
  2754. conn->timestamp_lastwritten = now;
  2755. record_num_bytes_transferred(conn, now, 0, info->n_deleted);
  2756. connection_consider_empty_write_buckets(conn);
  2757. if (conn->type == CONN_TYPE_AP) {
  2758. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  2759. /*XXXX024 check for overflow*/
  2760. edge_conn->n_written += (int)info->n_deleted;
  2761. }
  2762. }
  2763. }
  2764. /** Callback: invoked whenever a bufferevent has read data. */
  2765. void
  2766. connection_handle_read_cb(struct bufferevent *bufev, void *arg)
  2767. {
  2768. connection_t *conn = arg;
  2769. (void) bufev;
  2770. if (!conn->marked_for_close) {
  2771. if (connection_process_inbuf(conn, 1)<0) /* XXXX Always 1? */
  2772. if (!conn->marked_for_close)
  2773. connection_mark_for_close(conn);
  2774. }
  2775. }
  2776. /** Callback: invoked whenever a bufferevent has written data. */
  2777. void
  2778. connection_handle_write_cb(struct bufferevent *bufev, void *arg)
  2779. {
  2780. connection_t *conn = arg;
  2781. struct evbuffer *output;
  2782. if (connection_flushed_some(conn)<0) {
  2783. if (!conn->marked_for_close)
  2784. connection_mark_for_close(conn);
  2785. return;
  2786. }
  2787. output = bufferevent_get_output(bufev);
  2788. if (!evbuffer_get_length(output)) {
  2789. connection_finished_flushing(conn);
  2790. if (conn->marked_for_close && conn->hold_open_until_flushed) {
  2791. conn->hold_open_until_flushed = 0;
  2792. if (conn->linked) {
  2793. /* send eof */
  2794. bufferevent_flush(conn->bufev, EV_WRITE, BEV_FINISHED);
  2795. }
  2796. }
  2797. }
  2798. }
  2799. /** Callback: invoked whenever a bufferevent has had an event (like a
  2800. * connection, or an eof, or an error) occur. */
  2801. void
  2802. connection_handle_event_cb(struct bufferevent *bufev, short event, void *arg)
  2803. {
  2804. connection_t *conn = arg;
  2805. (void) bufev;
  2806. if (conn->marked_for_close)
  2807. return;
  2808. if (event & BEV_EVENT_CONNECTED) {
  2809. tor_assert(connection_state_is_connecting(conn));
  2810. if (connection_finished_connecting(conn)<0)
  2811. return;
  2812. }
  2813. if (event & BEV_EVENT_EOF) {
  2814. if (!conn->marked_for_close) {
  2815. conn->inbuf_reached_eof = 1;
  2816. if (connection_reached_eof(conn)<0)
  2817. return;
  2818. }
  2819. }
  2820. if (event & BEV_EVENT_ERROR) {
  2821. int socket_error = evutil_socket_geterror(conn->s);
  2822. if (conn->type == CONN_TYPE_OR &&
  2823. conn->state == OR_CONN_STATE_CONNECTING) {
  2824. connection_or_connect_failed(TO_OR_CONN(conn),
  2825. errno_to_orconn_end_reason(socket_error),
  2826. tor_socket_strerror(socket_error));
  2827. } else if (CONN_IS_EDGE(conn)) {
  2828. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  2829. if (!edge_conn->edge_has_sent_end)
  2830. connection_edge_end_errno(edge_conn);
  2831. if (conn->type == CONN_TYPE_AP && TO_ENTRY_CONN(conn)->socks_request) {
  2832. /* broken, don't send a socks reply back */
  2833. TO_ENTRY_CONN(conn)->socks_request->has_finished = 1;
  2834. }
  2835. }
  2836. connection_close_immediate(conn); /* Connection is dead. */
  2837. if (!conn->marked_for_close)
  2838. connection_mark_for_close(conn);
  2839. }
  2840. }
  2841. /** Set up the generic callbacks for the bufferevent on <b>conn</b>. */
  2842. void
  2843. connection_configure_bufferevent_callbacks(connection_t *conn)
  2844. {
  2845. struct bufferevent *bufev;
  2846. struct evbuffer *input, *output;
  2847. tor_assert(conn->bufev);
  2848. bufev = conn->bufev;
  2849. bufferevent_setcb(bufev,
  2850. connection_handle_read_cb,
  2851. connection_handle_write_cb,
  2852. connection_handle_event_cb,
  2853. conn);
  2854. /* Set a fairly high write low-watermark so that we get the write callback
  2855. called whenever data is written to bring us under 128K. Leave the
  2856. high-watermark at 0.
  2857. */
  2858. bufferevent_setwatermark(bufev, EV_WRITE, 128*1024, 0);
  2859. input = bufferevent_get_input(bufev);
  2860. output = bufferevent_get_output(bufev);
  2861. evbuffer_add_cb(input, evbuffer_inbuf_callback, conn);
  2862. evbuffer_add_cb(output, evbuffer_outbuf_callback, conn);
  2863. }
  2864. #endif
  2865. /** A pass-through to fetch_from_buf. */
  2866. int
  2867. connection_fetch_from_buf(char *string, size_t len, connection_t *conn)
  2868. {
  2869. IF_HAS_BUFFEREVENT(conn, {
  2870. /* XXX overflow -seb */
  2871. return (int)bufferevent_read(conn->bufev, string, len);
  2872. }) ELSE_IF_NO_BUFFEREVENT {
  2873. return fetch_from_buf(string, len, conn->inbuf);
  2874. }
  2875. }
  2876. /** As fetch_from_buf_line(), but read from a connection's input buffer. */
  2877. int
  2878. connection_fetch_from_buf_line(connection_t *conn, char *data,
  2879. size_t *data_len)
  2880. {
  2881. IF_HAS_BUFFEREVENT(conn, {
  2882. int r;
  2883. size_t eol_len=0;
  2884. struct evbuffer *input = bufferevent_get_input(conn->bufev);
  2885. struct evbuffer_ptr ptr =
  2886. evbuffer_search_eol(input, NULL, &eol_len, EVBUFFER_EOL_LF);
  2887. if (ptr.pos == -1)
  2888. return 0; /* No EOL found. */
  2889. if ((size_t)ptr.pos+eol_len >= *data_len) {
  2890. return -1; /* Too long */
  2891. }
  2892. *data_len = ptr.pos+eol_len;
  2893. r = evbuffer_remove(input, data, ptr.pos+eol_len);
  2894. tor_assert(r >= 0);
  2895. data[ptr.pos+eol_len] = '\0';
  2896. return 1;
  2897. }) ELSE_IF_NO_BUFFEREVENT {
  2898. return fetch_from_buf_line(conn->inbuf, data, data_len);
  2899. }
  2900. }
  2901. /** As fetch_from_buf_http, but fetches from a conncetion's input buffer_t or
  2902. * its bufferevent as appropriate. */
  2903. int
  2904. connection_fetch_from_buf_http(connection_t *conn,
  2905. char **headers_out, size_t max_headerlen,
  2906. char **body_out, size_t *body_used,
  2907. size_t max_bodylen, int force_complete)
  2908. {
  2909. IF_HAS_BUFFEREVENT(conn, {
  2910. struct evbuffer *input = bufferevent_get_input(conn->bufev);
  2911. return fetch_from_evbuffer_http(input, headers_out, max_headerlen,
  2912. body_out, body_used, max_bodylen, force_complete);
  2913. }) ELSE_IF_NO_BUFFEREVENT {
  2914. return fetch_from_buf_http(conn->inbuf, headers_out, max_headerlen,
  2915. body_out, body_used, max_bodylen, force_complete);
  2916. }
  2917. }
  2918. /** Return conn-\>outbuf_flushlen: how many bytes conn wants to flush
  2919. * from its outbuf. */
  2920. int
  2921. connection_wants_to_flush(connection_t *conn)
  2922. {
  2923. return conn->outbuf_flushlen > 0;
  2924. }
  2925. /** Are there too many bytes on edge connection <b>conn</b>'s outbuf to
  2926. * send back a relay-level sendme yet? Return 1 if so, 0 if not. Used by
  2927. * connection_edge_consider_sending_sendme().
  2928. */
  2929. int
  2930. connection_outbuf_too_full(connection_t *conn)
  2931. {
  2932. return (conn->outbuf_flushlen > 10*CELL_PAYLOAD_SIZE);
  2933. }
  2934. /** Try to flush more bytes onto <b>conn</b>-\>s.
  2935. *
  2936. * This function gets called either from conn_write() in main.c
  2937. * when poll() has declared that conn wants to write, or below
  2938. * from connection_write_to_buf() when an entire TLS record is ready.
  2939. *
  2940. * Update <b>conn</b>-\>timestamp_lastwritten to now, and call flush_buf
  2941. * or flush_buf_tls appropriately. If it succeeds and there are no more
  2942. * more bytes on <b>conn</b>-\>outbuf, then call connection_finished_flushing
  2943. * on it too.
  2944. *
  2945. * If <b>force</b>, then write as many bytes as possible, ignoring bandwidth
  2946. * limits. (Used for flushing messages to controller connections on fatal
  2947. * errors.)
  2948. *
  2949. * Mark the connection and return -1 if you want to close it, else
  2950. * return 0.
  2951. */
  2952. static int
  2953. connection_handle_write_impl(connection_t *conn, int force)
  2954. {
  2955. int e;
  2956. socklen_t len=(socklen_t)sizeof(e);
  2957. int result;
  2958. ssize_t max_to_write;
  2959. time_t now = approx_time();
  2960. size_t n_read = 0, n_written = 0;
  2961. tor_assert(!connection_is_listener(conn));
  2962. if (conn->marked_for_close || !SOCKET_OK(conn->s))
  2963. return 0; /* do nothing */
  2964. if (conn->in_flushed_some) {
  2965. log_warn(LD_BUG, "called recursively from inside conn->in_flushed_some");
  2966. return 0;
  2967. }
  2968. conn->timestamp_lastwritten = now;
  2969. /* Sometimes, "writable" means "connected". */
  2970. if (connection_state_is_connecting(conn)) {
  2971. if (getsockopt(conn->s, SOL_SOCKET, SO_ERROR, (void*)&e, &len) < 0) {
  2972. log_warn(LD_BUG, "getsockopt() syscall failed");
  2973. if (CONN_IS_EDGE(conn))
  2974. connection_edge_end_errno(TO_EDGE_CONN(conn));
  2975. connection_mark_for_close(conn);
  2976. return -1;
  2977. }
  2978. if (e) {
  2979. /* some sort of error, but maybe just inprogress still */
  2980. if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
  2981. log_info(LD_NET,"in-progress connect failed. Removing. (%s)",
  2982. tor_socket_strerror(e));
  2983. if (CONN_IS_EDGE(conn))
  2984. connection_edge_end_errno(TO_EDGE_CONN(conn));
  2985. if (conn->type == CONN_TYPE_OR)
  2986. connection_or_notify_error(TO_OR_CONN(conn),
  2987. errno_to_orconn_end_reason(e),
  2988. tor_socket_strerror(e));
  2989. connection_close_immediate(conn);
  2990. /*
  2991. * This can bypass normal channel checking since we did
  2992. * connection_or_notify_error() above.
  2993. */
  2994. connection_mark_for_close_internal(conn);
  2995. return -1;
  2996. } else {
  2997. return 0; /* no change, see if next time is better */
  2998. }
  2999. }
  3000. /* The connection is successful. */
  3001. if (connection_finished_connecting(conn)<0)
  3002. return -1;
  3003. }
  3004. max_to_write = force ? (ssize_t)conn->outbuf_flushlen
  3005. : connection_bucket_write_limit(conn, now);
  3006. if (connection_speaks_cells(conn) &&
  3007. conn->state > OR_CONN_STATE_PROXY_HANDSHAKING) {
  3008. or_connection_t *or_conn = TO_OR_CONN(conn);
  3009. if (conn->state == OR_CONN_STATE_TLS_HANDSHAKING ||
  3010. conn->state == OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING) {
  3011. connection_stop_writing(conn);
  3012. if (connection_tls_continue_handshake(or_conn) < 0) {
  3013. /* Don't flush; connection is dead. */
  3014. connection_or_notify_error(or_conn,
  3015. END_OR_CONN_REASON_MISC,
  3016. "TLS error in connection_tls_"
  3017. "continue_handshake()");
  3018. connection_close_immediate(conn);
  3019. /*
  3020. * This can bypass normal channel checking since we did
  3021. * connection_or_notify_error() above.
  3022. */
  3023. connection_mark_for_close_internal(conn);
  3024. return -1;
  3025. }
  3026. return 0;
  3027. } else if (conn->state == OR_CONN_STATE_TLS_SERVER_RENEGOTIATING) {
  3028. return connection_handle_read(conn);
  3029. }
  3030. /* else open, or closing */
  3031. result = flush_buf_tls(or_conn->tls, conn->outbuf,
  3032. max_to_write, &conn->outbuf_flushlen);
  3033. /* If we just flushed the last bytes, tell the channel on the
  3034. * or_conn to check if it needs to geoip_change_dirreq_state() */
  3035. /* XXXX move this to flushed_some or finished_flushing -NM */
  3036. if (buf_datalen(conn->outbuf) == 0 && or_conn->chan)
  3037. channel_notify_flushed(TLS_CHAN_TO_BASE(or_conn->chan));
  3038. switch (result) {
  3039. CASE_TOR_TLS_ERROR_ANY:
  3040. case TOR_TLS_CLOSE:
  3041. log_info(LD_NET, result != TOR_TLS_CLOSE ?
  3042. "tls error. breaking.":"TLS connection closed on flush");
  3043. /* Don't flush; connection is dead. */
  3044. connection_or_notify_error(or_conn,
  3045. END_OR_CONN_REASON_MISC,
  3046. result != TOR_TLS_CLOSE ?
  3047. "TLS error in during flush" :
  3048. "TLS closed during flush");
  3049. connection_close_immediate(conn);
  3050. /*
  3051. * This can bypass normal channel checking since we did
  3052. * connection_or_notify_error() above.
  3053. */
  3054. connection_mark_for_close_internal(conn);
  3055. return -1;
  3056. case TOR_TLS_WANTWRITE:
  3057. log_debug(LD_NET,"wanted write.");
  3058. /* we're already writing */
  3059. return 0;
  3060. case TOR_TLS_WANTREAD:
  3061. /* Make sure to avoid a loop if the receive buckets are empty. */
  3062. log_debug(LD_NET,"wanted read.");
  3063. if (!connection_is_reading(conn)) {
  3064. connection_stop_writing(conn);
  3065. conn->write_blocked_on_bw = 1;
  3066. /* we'll start reading again when we get more tokens in our
  3067. * read bucket; then we'll start writing again too.
  3068. */
  3069. }
  3070. /* else no problem, we're already reading */
  3071. return 0;
  3072. /* case TOR_TLS_DONE:
  3073. * for TOR_TLS_DONE, fall through to check if the flushlen
  3074. * is empty, so we can stop writing.
  3075. */
  3076. }
  3077. tor_tls_get_n_raw_bytes(or_conn->tls, &n_read, &n_written);
  3078. log_debug(LD_GENERAL, "After TLS write of %d: %ld read, %ld written",
  3079. result, (long)n_read, (long)n_written);
  3080. } else {
  3081. CONN_LOG_PROTECT(conn,
  3082. result = flush_buf(conn->s, conn->outbuf,
  3083. max_to_write, &conn->outbuf_flushlen));
  3084. if (result < 0) {
  3085. if (CONN_IS_EDGE(conn))
  3086. connection_edge_end_errno(TO_EDGE_CONN(conn));
  3087. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  3088. connection_mark_for_close(conn);
  3089. return -1;
  3090. }
  3091. n_written = (size_t) result;
  3092. }
  3093. if (n_written && conn->type == CONN_TYPE_AP) {
  3094. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  3095. /* Check for overflow: */
  3096. if (PREDICT_LIKELY(UINT32_MAX - edge_conn->n_written > n_written))
  3097. edge_conn->n_written += (int)n_written;
  3098. else
  3099. edge_conn->n_written = UINT32_MAX;
  3100. }
  3101. connection_buckets_decrement(conn, approx_time(), n_read, n_written);
  3102. if (result > 0) {
  3103. /* If we wrote any bytes from our buffer, then call the appropriate
  3104. * functions. */
  3105. if (connection_flushed_some(conn) < 0) {
  3106. if (connection_speaks_cells(conn)) {
  3107. connection_or_notify_error(TO_OR_CONN(conn),
  3108. END_OR_CONN_REASON_MISC,
  3109. "Got error back from "
  3110. "connection_flushed_some()");
  3111. }
  3112. /*
  3113. * This can bypass normal channel checking since we did
  3114. * connection_or_notify_error() above.
  3115. */
  3116. connection_mark_for_close_internal(conn);
  3117. }
  3118. }
  3119. if (!connection_wants_to_flush(conn)) { /* it's done flushing */
  3120. if (connection_finished_flushing(conn) < 0) {
  3121. /* already marked */
  3122. return -1;
  3123. }
  3124. return 0;
  3125. }
  3126. /* Call even if result is 0, since the global write bucket may
  3127. * have reached 0 on a different conn, and this guy needs to
  3128. * know to stop writing. */
  3129. connection_consider_empty_write_buckets(conn);
  3130. if (n_read > 0 && connection_is_reading(conn))
  3131. connection_consider_empty_read_buckets(conn);
  3132. return 0;
  3133. }
  3134. /* DOCDOC connection_handle_write */
  3135. int
  3136. connection_handle_write(connection_t *conn, int force)
  3137. {
  3138. int res;
  3139. tor_gettimeofday_cache_clear();
  3140. res = connection_handle_write_impl(conn, force);
  3141. return res;
  3142. }
  3143. /**
  3144. * Try to flush data that's waiting for a write on <b>conn</b>. Return
  3145. * -1 on failure, 0 on success.
  3146. *
  3147. * Don't use this function for regular writing; the buffers/bufferevents
  3148. * system should be good enough at scheduling writes there. Instead, this
  3149. * function is for cases when we're about to exit or something and we want
  3150. * to report it right away.
  3151. */
  3152. int
  3153. connection_flush(connection_t *conn)
  3154. {
  3155. IF_HAS_BUFFEREVENT(conn, {
  3156. int r = bufferevent_flush(conn->bufev, EV_WRITE, BEV_FLUSH);
  3157. return (r < 0) ? -1 : 0;
  3158. });
  3159. return connection_handle_write(conn, 1);
  3160. }
  3161. /** Append <b>len</b> bytes of <b>string</b> onto <b>conn</b>'s
  3162. * outbuf, and ask it to start writing.
  3163. *
  3164. * If <b>zlib</b> is nonzero, this is a directory connection that should get
  3165. * its contents compressed or decompressed as they're written. If zlib is
  3166. * negative, this is the last data to be compressed, and the connection's zlib
  3167. * state should be flushed.
  3168. *
  3169. * If it's a local control connection and a 64k chunk is ready, try to flush
  3170. * it all, so we don't end up with many megabytes of controller info queued at
  3171. * once.
  3172. */
  3173. void
  3174. connection_write_to_buf_impl_(const char *string, size_t len,
  3175. connection_t *conn, int zlib)
  3176. {
  3177. /* XXXX This function really needs to return -1 on failure. */
  3178. int r;
  3179. size_t old_datalen;
  3180. if (!len && !(zlib<0))
  3181. return;
  3182. /* if it's marked for close, only allow write if we mean to flush it */
  3183. if (conn->marked_for_close && !conn->hold_open_until_flushed)
  3184. return;
  3185. IF_HAS_BUFFEREVENT(conn, {
  3186. if (zlib) {
  3187. int done = zlib < 0;
  3188. r = write_to_evbuffer_zlib(bufferevent_get_output(conn->bufev),
  3189. TO_DIR_CONN(conn)->zlib_state,
  3190. string, len, done);
  3191. } else {
  3192. r = bufferevent_write(conn->bufev, string, len);
  3193. }
  3194. if (r < 0) {
  3195. /* XXXX mark for close? */
  3196. log_warn(LD_NET, "bufferevent_write failed! That shouldn't happen.");
  3197. }
  3198. return;
  3199. });
  3200. old_datalen = buf_datalen(conn->outbuf);
  3201. if (zlib) {
  3202. dir_connection_t *dir_conn = TO_DIR_CONN(conn);
  3203. int done = zlib < 0;
  3204. CONN_LOG_PROTECT(conn, r = write_to_buf_zlib(conn->outbuf,
  3205. dir_conn->zlib_state,
  3206. string, len, done));
  3207. } else {
  3208. CONN_LOG_PROTECT(conn, r = write_to_buf(string, len, conn->outbuf));
  3209. }
  3210. if (r < 0) {
  3211. if (CONN_IS_EDGE(conn)) {
  3212. /* if it failed, it means we have our package/delivery windows set
  3213. wrong compared to our max outbuf size. close the whole circuit. */
  3214. log_warn(LD_NET,
  3215. "write_to_buf failed. Closing circuit (fd %d).", (int)conn->s);
  3216. circuit_mark_for_close(circuit_get_by_edge_conn(TO_EDGE_CONN(conn)),
  3217. END_CIRC_REASON_INTERNAL);
  3218. } else {
  3219. log_warn(LD_NET,
  3220. "write_to_buf failed. Closing connection (fd %d).",
  3221. (int)conn->s);
  3222. connection_mark_for_close(conn);
  3223. }
  3224. return;
  3225. }
  3226. /* If we receive optimistic data in the EXIT_CONN_STATE_RESOLVING
  3227. * state, we don't want to try to write it right away, since
  3228. * conn->write_event won't be set yet. Otherwise, write data from
  3229. * this conn as the socket is available. */
  3230. if (conn->write_event) {
  3231. connection_start_writing(conn);
  3232. }
  3233. if (zlib) {
  3234. conn->outbuf_flushlen += buf_datalen(conn->outbuf) - old_datalen;
  3235. } else {
  3236. conn->outbuf_flushlen += len;
  3237. /* Should we try flushing the outbuf now? */
  3238. if (conn->in_flushed_some) {
  3239. /* Don't flush the outbuf when the reason we're writing more stuff is
  3240. * _because_ we flushed the outbuf. That's unfair. */
  3241. return;
  3242. }
  3243. if (conn->type == CONN_TYPE_CONTROL &&
  3244. !connection_is_rate_limited(conn) &&
  3245. conn->outbuf_flushlen-len < 1<<16 &&
  3246. conn->outbuf_flushlen >= 1<<16) {
  3247. /* just try to flush all of it */
  3248. } else
  3249. return; /* no need to try flushing */
  3250. if (connection_handle_write(conn, 0) < 0) {
  3251. if (!conn->marked_for_close) {
  3252. /* this connection is broken. remove it. */
  3253. log_warn(LD_BUG, "unhandled error on write for "
  3254. "conn (type %d, fd %d); removing",
  3255. conn->type, (int)conn->s);
  3256. tor_fragile_assert();
  3257. /* do a close-immediate here, so we don't try to flush */
  3258. connection_close_immediate(conn);
  3259. }
  3260. return;
  3261. }
  3262. }
  3263. }
  3264. /** Return a connection with given type, address, port, and purpose;
  3265. * or NULL if no such connection exists. */
  3266. connection_t *
  3267. connection_get_by_type_addr_port_purpose(int type,
  3268. const tor_addr_t *addr, uint16_t port,
  3269. int purpose)
  3270. {
  3271. smartlist_t *conns = get_connection_array();
  3272. SMARTLIST_FOREACH(conns, connection_t *, conn,
  3273. {
  3274. if (conn->type == type &&
  3275. tor_addr_eq(&conn->addr, addr) &&
  3276. conn->port == port &&
  3277. conn->purpose == purpose &&
  3278. !conn->marked_for_close)
  3279. return conn;
  3280. });
  3281. return NULL;
  3282. }
  3283. /** Return the stream with id <b>id</b> if it is not already marked for
  3284. * close.
  3285. */
  3286. connection_t *
  3287. connection_get_by_global_id(uint64_t id)
  3288. {
  3289. smartlist_t *conns = get_connection_array();
  3290. SMARTLIST_FOREACH(conns, connection_t *, conn,
  3291. {
  3292. if (conn->global_identifier == id)
  3293. return conn;
  3294. });
  3295. return NULL;
  3296. }
  3297. /** Return a connection of type <b>type</b> that is not marked for close.
  3298. */
  3299. connection_t *
  3300. connection_get_by_type(int type)
  3301. {
  3302. smartlist_t *conns = get_connection_array();
  3303. SMARTLIST_FOREACH(conns, connection_t *, conn,
  3304. {
  3305. if (conn->type == type && !conn->marked_for_close)
  3306. return conn;
  3307. });
  3308. return NULL;
  3309. }
  3310. /** Return a connection of type <b>type</b> that is in state <b>state</b>,
  3311. * and that is not marked for close.
  3312. */
  3313. connection_t *
  3314. connection_get_by_type_state(int type, int state)
  3315. {
  3316. smartlist_t *conns = get_connection_array();
  3317. SMARTLIST_FOREACH(conns, connection_t *, conn,
  3318. {
  3319. if (conn->type == type && conn->state == state && !conn->marked_for_close)
  3320. return conn;
  3321. });
  3322. return NULL;
  3323. }
  3324. /** Return a connection of type <b>type</b> that has rendquery equal
  3325. * to <b>rendquery</b>, and that is not marked for close. If state
  3326. * is non-zero, conn must be of that state too.
  3327. */
  3328. connection_t *
  3329. connection_get_by_type_state_rendquery(int type, int state,
  3330. const char *rendquery)
  3331. {
  3332. smartlist_t *conns = get_connection_array();
  3333. tor_assert(type == CONN_TYPE_DIR ||
  3334. type == CONN_TYPE_AP || type == CONN_TYPE_EXIT);
  3335. tor_assert(rendquery);
  3336. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  3337. if (conn->type == type &&
  3338. !conn->marked_for_close &&
  3339. (!state || state == conn->state)) {
  3340. if (type == CONN_TYPE_DIR &&
  3341. TO_DIR_CONN(conn)->rend_data &&
  3342. !rend_cmp_service_ids(rendquery,
  3343. TO_DIR_CONN(conn)->rend_data->onion_address))
  3344. return conn;
  3345. else if (CONN_IS_EDGE(conn) &&
  3346. TO_EDGE_CONN(conn)->rend_data &&
  3347. !rend_cmp_service_ids(rendquery,
  3348. TO_EDGE_CONN(conn)->rend_data->onion_address))
  3349. return conn;
  3350. }
  3351. } SMARTLIST_FOREACH_END(conn);
  3352. return NULL;
  3353. }
  3354. /** Return a directory connection (if any one exists) that is fetching
  3355. * the item described by <b>state</b>/<b>resource</b> */
  3356. dir_connection_t *
  3357. connection_dir_get_by_purpose_and_resource(int purpose,
  3358. const char *resource)
  3359. {
  3360. smartlist_t *conns = get_connection_array();
  3361. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  3362. dir_connection_t *dirconn;
  3363. if (conn->type != CONN_TYPE_DIR || conn->marked_for_close ||
  3364. conn->purpose != purpose)
  3365. continue;
  3366. dirconn = TO_DIR_CONN(conn);
  3367. if (dirconn->requested_resource == NULL) {
  3368. if (resource == NULL)
  3369. return dirconn;
  3370. } else if (resource) {
  3371. if (0 == strcmp(resource, dirconn->requested_resource))
  3372. return dirconn;
  3373. }
  3374. } SMARTLIST_FOREACH_END(conn);
  3375. return NULL;
  3376. }
  3377. /** Return an open, non-marked connection of a given type and purpose, or NULL
  3378. * if no such connection exists. */
  3379. connection_t *
  3380. connection_get_by_type_purpose(int type, int purpose)
  3381. {
  3382. smartlist_t *conns = get_connection_array();
  3383. SMARTLIST_FOREACH(conns, connection_t *, conn,
  3384. {
  3385. if (conn->type == type &&
  3386. !conn->marked_for_close &&
  3387. (purpose == conn->purpose))
  3388. return conn;
  3389. });
  3390. return NULL;
  3391. }
  3392. /** Return 1 if <b>conn</b> is a listener conn, else return 0. */
  3393. int
  3394. connection_is_listener(connection_t *conn)
  3395. {
  3396. if (conn->type == CONN_TYPE_OR_LISTENER ||
  3397. conn->type == CONN_TYPE_AP_LISTENER ||
  3398. conn->type == CONN_TYPE_AP_TRANS_LISTENER ||
  3399. conn->type == CONN_TYPE_AP_DNS_LISTENER ||
  3400. conn->type == CONN_TYPE_AP_NATD_LISTENER ||
  3401. conn->type == CONN_TYPE_DIR_LISTENER ||
  3402. conn->type == CONN_TYPE_CONTROL_LISTENER)
  3403. return 1;
  3404. return 0;
  3405. }
  3406. /** Return 1 if <b>conn</b> is in state "open" and is not marked
  3407. * for close, else return 0.
  3408. */
  3409. int
  3410. connection_state_is_open(connection_t *conn)
  3411. {
  3412. tor_assert(conn);
  3413. if (conn->marked_for_close)
  3414. return 0;
  3415. if ((conn->type == CONN_TYPE_OR && conn->state == OR_CONN_STATE_OPEN) ||
  3416. (conn->type == CONN_TYPE_AP && conn->state == AP_CONN_STATE_OPEN) ||
  3417. (conn->type == CONN_TYPE_EXIT && conn->state == EXIT_CONN_STATE_OPEN) ||
  3418. (conn->type == CONN_TYPE_CONTROL &&
  3419. conn->state == CONTROL_CONN_STATE_OPEN))
  3420. return 1;
  3421. return 0;
  3422. }
  3423. /** Return 1 if conn is in 'connecting' state, else return 0. */
  3424. int
  3425. connection_state_is_connecting(connection_t *conn)
  3426. {
  3427. tor_assert(conn);
  3428. if (conn->marked_for_close)
  3429. return 0;
  3430. switch (conn->type)
  3431. {
  3432. case CONN_TYPE_OR:
  3433. return conn->state == OR_CONN_STATE_CONNECTING;
  3434. case CONN_TYPE_EXIT:
  3435. return conn->state == EXIT_CONN_STATE_CONNECTING;
  3436. case CONN_TYPE_DIR:
  3437. return conn->state == DIR_CONN_STATE_CONNECTING;
  3438. }
  3439. return 0;
  3440. }
  3441. /** Allocates a base64'ed authenticator for use in http or https
  3442. * auth, based on the input string <b>authenticator</b>. Returns it
  3443. * if success, else returns NULL. */
  3444. char *
  3445. alloc_http_authenticator(const char *authenticator)
  3446. {
  3447. /* an authenticator in Basic authentication
  3448. * is just the string "username:password" */
  3449. const size_t authenticator_length = strlen(authenticator);
  3450. /* The base64_encode function needs a minimum buffer length
  3451. * of 66 bytes. */
  3452. const size_t base64_authenticator_length = (authenticator_length/48+1)*66;
  3453. char *base64_authenticator = tor_malloc(base64_authenticator_length);
  3454. if (base64_encode(base64_authenticator, base64_authenticator_length,
  3455. authenticator, authenticator_length) < 0) {
  3456. tor_free(base64_authenticator); /* free and set to null */
  3457. } else {
  3458. int i = 0, j = 0;
  3459. ssize_t len = strlen(base64_authenticator);
  3460. /* remove all newline occurrences within the string */
  3461. for (i=0; i < len; ++i) {
  3462. if ('\n' != base64_authenticator[i]) {
  3463. base64_authenticator[j] = base64_authenticator[i];
  3464. ++j;
  3465. }
  3466. }
  3467. base64_authenticator[j]='\0';
  3468. }
  3469. return base64_authenticator;
  3470. }
  3471. /** Given a socket handle, check whether the local address (sockname) of the
  3472. * socket is one that we've connected from before. If so, double-check
  3473. * whether our address has changed and we need to generate keys. If we do,
  3474. * call init_keys().
  3475. */
  3476. static void
  3477. client_check_address_changed(tor_socket_t sock)
  3478. {
  3479. struct sockaddr_storage out_sockaddr;
  3480. socklen_t out_addr_len = (socklen_t) sizeof(out_sockaddr);
  3481. tor_addr_t out_addr, iface_addr;
  3482. tor_addr_t **last_interface_ip_ptr;
  3483. sa_family_t family;
  3484. if (!outgoing_addrs)
  3485. outgoing_addrs = smartlist_new();
  3486. if (getsockname(sock, (struct sockaddr*)&out_sockaddr, &out_addr_len)<0) {
  3487. int e = tor_socket_errno(sock);
  3488. log_warn(LD_NET, "getsockname() to check for address change failed: %s",
  3489. tor_socket_strerror(e));
  3490. return;
  3491. }
  3492. tor_addr_from_sockaddr(&out_addr, (struct sockaddr*)&out_sockaddr, NULL);
  3493. family = tor_addr_family(&out_addr);
  3494. if (family == AF_INET)
  3495. last_interface_ip_ptr = &last_interface_ipv4;
  3496. else if (family == AF_INET6)
  3497. last_interface_ip_ptr = &last_interface_ipv6;
  3498. else
  3499. return;
  3500. if (! *last_interface_ip_ptr) {
  3501. tor_addr_t *a = tor_malloc_zero(sizeof(tor_addr_t));
  3502. if (get_interface_address6(LOG_INFO, family, a)==0) {
  3503. *last_interface_ip_ptr = a;
  3504. } else {
  3505. tor_free(a);
  3506. }
  3507. }
  3508. /* If we've used this address previously, we're okay. */
  3509. SMARTLIST_FOREACH(outgoing_addrs, const tor_addr_t *, a_ptr,
  3510. if (tor_addr_eq(a_ptr, &out_addr))
  3511. return;
  3512. );
  3513. /* Uh-oh. We haven't connected from this address before. Has the interface
  3514. * address changed? */
  3515. if (get_interface_address6(LOG_INFO, family, &iface_addr)<0)
  3516. return;
  3517. if (tor_addr_eq(&iface_addr, *last_interface_ip_ptr)) {
  3518. /* Nope, it hasn't changed. Add this address to the list. */
  3519. smartlist_add(outgoing_addrs, tor_memdup(&out_addr, sizeof(tor_addr_t)));
  3520. } else {
  3521. /* The interface changed. We're a client, so we need to regenerate our
  3522. * keys. First, reset the state. */
  3523. log(LOG_NOTICE, LD_NET, "Our IP address has changed. Rotating keys...");
  3524. tor_addr_copy(*last_interface_ip_ptr, &iface_addr);
  3525. SMARTLIST_FOREACH(outgoing_addrs, tor_addr_t*, a_ptr, tor_free(a_ptr));
  3526. smartlist_clear(outgoing_addrs);
  3527. smartlist_add(outgoing_addrs, tor_memdup(&out_addr, sizeof(tor_addr_t)));
  3528. /* Okay, now change our keys. */
  3529. ip_address_changed(1);
  3530. }
  3531. }
  3532. /** Some systems have limited system buffers for recv and xmit on
  3533. * sockets allocated in a virtual server or similar environment. For a Tor
  3534. * server this can produce the "Error creating network socket: No buffer
  3535. * space available" error once all available TCP buffer space is consumed.
  3536. * This method will attempt to constrain the buffers allocated for the socket
  3537. * to the desired size to stay below system TCP buffer limits.
  3538. */
  3539. static void
  3540. set_constrained_socket_buffers(tor_socket_t sock, int size)
  3541. {
  3542. void *sz = (void*)&size;
  3543. socklen_t sz_sz = (socklen_t) sizeof(size);
  3544. if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, sz, sz_sz) < 0) {
  3545. int e = tor_socket_errno(sock);
  3546. log_warn(LD_NET, "setsockopt() to constrain send "
  3547. "buffer to %d bytes failed: %s", size, tor_socket_strerror(e));
  3548. }
  3549. if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, sz, sz_sz) < 0) {
  3550. int e = tor_socket_errno(sock);
  3551. log_warn(LD_NET, "setsockopt() to constrain recv "
  3552. "buffer to %d bytes failed: %s", size, tor_socket_strerror(e));
  3553. }
  3554. }
  3555. /** Process new bytes that have arrived on conn-\>inbuf.
  3556. *
  3557. * This function just passes conn to the connection-specific
  3558. * connection_*_process_inbuf() function. It also passes in
  3559. * package_partial if wanted.
  3560. */
  3561. static int
  3562. connection_process_inbuf(connection_t *conn, int package_partial)
  3563. {
  3564. tor_assert(conn);
  3565. switch (conn->type) {
  3566. case CONN_TYPE_OR:
  3567. return connection_or_process_inbuf(TO_OR_CONN(conn));
  3568. case CONN_TYPE_EXIT:
  3569. case CONN_TYPE_AP:
  3570. return connection_edge_process_inbuf(TO_EDGE_CONN(conn),
  3571. package_partial);
  3572. case CONN_TYPE_DIR:
  3573. return connection_dir_process_inbuf(TO_DIR_CONN(conn));
  3574. case CONN_TYPE_CPUWORKER:
  3575. return connection_cpu_process_inbuf(conn);
  3576. case CONN_TYPE_CONTROL:
  3577. return connection_control_process_inbuf(TO_CONTROL_CONN(conn));
  3578. default:
  3579. log_err(LD_BUG,"got unexpected conn type %d.", conn->type);
  3580. tor_fragile_assert();
  3581. return -1;
  3582. }
  3583. }
  3584. /** Called whenever we've written data on a connection. */
  3585. static int
  3586. connection_flushed_some(connection_t *conn)
  3587. {
  3588. int r = 0;
  3589. tor_assert(!conn->in_flushed_some);
  3590. conn->in_flushed_some = 1;
  3591. if (conn->type == CONN_TYPE_DIR &&
  3592. conn->state == DIR_CONN_STATE_SERVER_WRITING) {
  3593. r = connection_dirserv_flushed_some(TO_DIR_CONN(conn));
  3594. } else if (conn->type == CONN_TYPE_OR) {
  3595. r = connection_or_flushed_some(TO_OR_CONN(conn));
  3596. } else if (CONN_IS_EDGE(conn)) {
  3597. r = connection_edge_flushed_some(TO_EDGE_CONN(conn));
  3598. }
  3599. conn->in_flushed_some = 0;
  3600. return r;
  3601. }
  3602. /** We just finished flushing bytes from conn-\>outbuf, and there
  3603. * are no more bytes remaining.
  3604. *
  3605. * This function just passes conn to the connection-specific
  3606. * connection_*_finished_flushing() function.
  3607. */
  3608. static int
  3609. connection_finished_flushing(connection_t *conn)
  3610. {
  3611. tor_assert(conn);
  3612. /* If the connection is closed, don't try to do anything more here. */
  3613. if (CONN_IS_CLOSED(conn))
  3614. return 0;
  3615. // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
  3616. IF_HAS_NO_BUFFEREVENT(conn)
  3617. connection_stop_writing(conn);
  3618. switch (conn->type) {
  3619. case CONN_TYPE_OR:
  3620. return connection_or_finished_flushing(TO_OR_CONN(conn));
  3621. case CONN_TYPE_AP:
  3622. case CONN_TYPE_EXIT:
  3623. return connection_edge_finished_flushing(TO_EDGE_CONN(conn));
  3624. case CONN_TYPE_DIR:
  3625. return connection_dir_finished_flushing(TO_DIR_CONN(conn));
  3626. case CONN_TYPE_CPUWORKER:
  3627. return connection_cpu_finished_flushing(conn);
  3628. case CONN_TYPE_CONTROL:
  3629. return connection_control_finished_flushing(TO_CONTROL_CONN(conn));
  3630. default:
  3631. log_err(LD_BUG,"got unexpected conn type %d.", conn->type);
  3632. tor_fragile_assert();
  3633. return -1;
  3634. }
  3635. }
  3636. /** Called when our attempt to connect() to another server has just
  3637. * succeeded.
  3638. *
  3639. * This function just passes conn to the connection-specific
  3640. * connection_*_finished_connecting() function.
  3641. */
  3642. static int
  3643. connection_finished_connecting(connection_t *conn)
  3644. {
  3645. tor_assert(conn);
  3646. if (!server_mode(get_options())) {
  3647. /* See whether getsockname() says our address changed. We need to do this
  3648. * now that the connection has finished, because getsockname() on Windows
  3649. * won't work until then. */
  3650. client_check_address_changed(conn->s);
  3651. }
  3652. switch (conn->type)
  3653. {
  3654. case CONN_TYPE_OR:
  3655. return connection_or_finished_connecting(TO_OR_CONN(conn));
  3656. case CONN_TYPE_EXIT:
  3657. return connection_edge_finished_connecting(TO_EDGE_CONN(conn));
  3658. case CONN_TYPE_DIR:
  3659. return connection_dir_finished_connecting(TO_DIR_CONN(conn));
  3660. default:
  3661. log_err(LD_BUG,"got unexpected conn type %d.", conn->type);
  3662. tor_fragile_assert();
  3663. return -1;
  3664. }
  3665. }
  3666. /** Callback: invoked when a connection reaches an EOF event. */
  3667. static int
  3668. connection_reached_eof(connection_t *conn)
  3669. {
  3670. switch (conn->type) {
  3671. case CONN_TYPE_OR:
  3672. return connection_or_reached_eof(TO_OR_CONN(conn));
  3673. case CONN_TYPE_AP:
  3674. case CONN_TYPE_EXIT:
  3675. return connection_edge_reached_eof(TO_EDGE_CONN(conn));
  3676. case CONN_TYPE_DIR:
  3677. return connection_dir_reached_eof(TO_DIR_CONN(conn));
  3678. case CONN_TYPE_CPUWORKER:
  3679. return connection_cpu_reached_eof(conn);
  3680. case CONN_TYPE_CONTROL:
  3681. return connection_control_reached_eof(TO_CONTROL_CONN(conn));
  3682. default:
  3683. log_err(LD_BUG,"got unexpected conn type %d.", conn->type);
  3684. tor_fragile_assert();
  3685. return -1;
  3686. }
  3687. }
  3688. /** Log how many bytes are used by buffers of different kinds and sizes. */
  3689. void
  3690. connection_dump_buffer_mem_stats(int severity)
  3691. {
  3692. uint64_t used_by_type[CONN_TYPE_MAX_+1];
  3693. uint64_t alloc_by_type[CONN_TYPE_MAX_+1];
  3694. int n_conns_by_type[CONN_TYPE_MAX_+1];
  3695. uint64_t total_alloc = 0;
  3696. uint64_t total_used = 0;
  3697. int i;
  3698. smartlist_t *conns = get_connection_array();
  3699. memset(used_by_type, 0, sizeof(used_by_type));
  3700. memset(alloc_by_type, 0, sizeof(alloc_by_type));
  3701. memset(n_conns_by_type, 0, sizeof(n_conns_by_type));
  3702. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, c) {
  3703. int tp = c->type;
  3704. ++n_conns_by_type[tp];
  3705. if (c->inbuf) {
  3706. used_by_type[tp] += buf_datalen(c->inbuf);
  3707. alloc_by_type[tp] += buf_allocation(c->inbuf);
  3708. }
  3709. if (c->outbuf) {
  3710. used_by_type[tp] += buf_datalen(c->outbuf);
  3711. alloc_by_type[tp] += buf_allocation(c->outbuf);
  3712. }
  3713. } SMARTLIST_FOREACH_END(c);
  3714. for (i=0; i <= CONN_TYPE_MAX_; ++i) {
  3715. total_used += used_by_type[i];
  3716. total_alloc += alloc_by_type[i];
  3717. }
  3718. log(severity, LD_GENERAL,
  3719. "In buffers for %d connections: "U64_FORMAT" used/"U64_FORMAT" allocated",
  3720. smartlist_len(conns),
  3721. U64_PRINTF_ARG(total_used), U64_PRINTF_ARG(total_alloc));
  3722. for (i=CONN_TYPE_MIN_; i <= CONN_TYPE_MAX_; ++i) {
  3723. if (!n_conns_by_type[i])
  3724. continue;
  3725. log(severity, LD_GENERAL,
  3726. " For %d %s connections: "U64_FORMAT" used/"U64_FORMAT" allocated",
  3727. n_conns_by_type[i], conn_type_to_string(i),
  3728. U64_PRINTF_ARG(used_by_type[i]), U64_PRINTF_ARG(alloc_by_type[i]));
  3729. }
  3730. }
  3731. /** Verify that connection <b>conn</b> has all of its invariants
  3732. * correct. Trigger an assert if anything is invalid.
  3733. */
  3734. void
  3735. assert_connection_ok(connection_t *conn, time_t now)
  3736. {
  3737. (void) now; /* XXXX unused. */
  3738. tor_assert(conn);
  3739. tor_assert(conn->type >= CONN_TYPE_MIN_);
  3740. tor_assert(conn->type <= CONN_TYPE_MAX_);
  3741. #ifdef USE_BUFFEREVENTS
  3742. if (conn->bufev) {
  3743. tor_assert(conn->read_event == NULL);
  3744. tor_assert(conn->write_event == NULL);
  3745. tor_assert(conn->inbuf == NULL);
  3746. tor_assert(conn->outbuf == NULL);
  3747. }
  3748. #endif
  3749. switch (conn->type) {
  3750. case CONN_TYPE_OR:
  3751. tor_assert(conn->magic == OR_CONNECTION_MAGIC);
  3752. break;
  3753. case CONN_TYPE_AP:
  3754. tor_assert(conn->magic == ENTRY_CONNECTION_MAGIC);
  3755. break;
  3756. case CONN_TYPE_EXIT:
  3757. tor_assert(conn->magic == EDGE_CONNECTION_MAGIC);
  3758. break;
  3759. case CONN_TYPE_DIR:
  3760. tor_assert(conn->magic == DIR_CONNECTION_MAGIC);
  3761. break;
  3762. case CONN_TYPE_CONTROL:
  3763. tor_assert(conn->magic == CONTROL_CONNECTION_MAGIC);
  3764. break;
  3765. CASE_ANY_LISTENER_TYPE:
  3766. tor_assert(conn->magic == LISTENER_CONNECTION_MAGIC);
  3767. break;
  3768. default:
  3769. tor_assert(conn->magic == BASE_CONNECTION_MAGIC);
  3770. break;
  3771. }
  3772. if (conn->linked_conn) {
  3773. tor_assert(conn->linked_conn->linked_conn == conn);
  3774. tor_assert(conn->linked);
  3775. }
  3776. if (conn->linked)
  3777. tor_assert(!SOCKET_OK(conn->s));
  3778. if (conn->outbuf_flushlen > 0) {
  3779. /* With optimistic data, we may have queued data in
  3780. * EXIT_CONN_STATE_RESOLVING while the conn is not yet marked to writing.
  3781. * */
  3782. tor_assert((conn->type == CONN_TYPE_EXIT &&
  3783. conn->state == EXIT_CONN_STATE_RESOLVING) ||
  3784. connection_is_writing(conn) ||
  3785. conn->write_blocked_on_bw ||
  3786. (CONN_IS_EDGE(conn) &&
  3787. TO_EDGE_CONN(conn)->edge_blocked_on_circ));
  3788. }
  3789. if (conn->hold_open_until_flushed)
  3790. tor_assert(conn->marked_for_close);
  3791. /* XXXX check: read_blocked_on_bw, write_blocked_on_bw, s, conn_array_index,
  3792. * marked_for_close. */
  3793. /* buffers */
  3794. if (conn->inbuf)
  3795. assert_buf_ok(conn->inbuf);
  3796. if (conn->outbuf)
  3797. assert_buf_ok(conn->outbuf);
  3798. if (conn->type == CONN_TYPE_OR) {
  3799. or_connection_t *or_conn = TO_OR_CONN(conn);
  3800. if (conn->state == OR_CONN_STATE_OPEN) {
  3801. /* tor_assert(conn->bandwidth > 0); */
  3802. /* the above isn't necessarily true: if we just did a TLS
  3803. * handshake but we didn't recognize the other peer, or it
  3804. * gave a bad cert/etc, then we won't have assigned bandwidth,
  3805. * yet it will be open. -RD
  3806. */
  3807. // tor_assert(conn->read_bucket >= 0);
  3808. }
  3809. // tor_assert(conn->addr && conn->port);
  3810. tor_assert(conn->address);
  3811. if (conn->state > OR_CONN_STATE_PROXY_HANDSHAKING)
  3812. tor_assert(or_conn->tls);
  3813. }
  3814. if (CONN_IS_EDGE(conn)) {
  3815. /* XXX unchecked: package window, deliver window. */
  3816. if (conn->type == CONN_TYPE_AP) {
  3817. entry_connection_t *entry_conn = TO_ENTRY_CONN(conn);
  3818. if (entry_conn->chosen_exit_optional || entry_conn->chosen_exit_retries)
  3819. tor_assert(entry_conn->chosen_exit_name);
  3820. tor_assert(entry_conn->socks_request);
  3821. if (conn->state == AP_CONN_STATE_OPEN) {
  3822. tor_assert(entry_conn->socks_request->has_finished);
  3823. if (!conn->marked_for_close) {
  3824. tor_assert(ENTRY_TO_EDGE_CONN(entry_conn)->cpath_layer);
  3825. assert_cpath_layer_ok(ENTRY_TO_EDGE_CONN(entry_conn)->cpath_layer);
  3826. }
  3827. }
  3828. }
  3829. if (conn->type == CONN_TYPE_EXIT) {
  3830. tor_assert(conn->purpose == EXIT_PURPOSE_CONNECT ||
  3831. conn->purpose == EXIT_PURPOSE_RESOLVE);
  3832. }
  3833. } else if (conn->type == CONN_TYPE_DIR) {
  3834. } else {
  3835. /* Purpose is only used for dir and exit types currently */
  3836. tor_assert(!conn->purpose);
  3837. }
  3838. switch (conn->type)
  3839. {
  3840. CASE_ANY_LISTENER_TYPE:
  3841. tor_assert(conn->state == LISTENER_STATE_READY);
  3842. break;
  3843. case CONN_TYPE_OR:
  3844. tor_assert(conn->state >= OR_CONN_STATE_MIN_);
  3845. tor_assert(conn->state <= OR_CONN_STATE_MAX_);
  3846. break;
  3847. case CONN_TYPE_EXIT:
  3848. tor_assert(conn->state >= EXIT_CONN_STATE_MIN_);
  3849. tor_assert(conn->state <= EXIT_CONN_STATE_MAX_);
  3850. tor_assert(conn->purpose >= EXIT_PURPOSE_MIN_);
  3851. tor_assert(conn->purpose <= EXIT_PURPOSE_MAX_);
  3852. break;
  3853. case CONN_TYPE_AP:
  3854. tor_assert(conn->state >= AP_CONN_STATE_MIN_);
  3855. tor_assert(conn->state <= AP_CONN_STATE_MAX_);
  3856. tor_assert(TO_ENTRY_CONN(conn)->socks_request);
  3857. break;
  3858. case CONN_TYPE_DIR:
  3859. tor_assert(conn->state >= DIR_CONN_STATE_MIN_);
  3860. tor_assert(conn->state <= DIR_CONN_STATE_MAX_);
  3861. tor_assert(conn->purpose >= DIR_PURPOSE_MIN_);
  3862. tor_assert(conn->purpose <= DIR_PURPOSE_MAX_);
  3863. break;
  3864. case CONN_TYPE_CPUWORKER:
  3865. tor_assert(conn->state >= CPUWORKER_STATE_MIN_);
  3866. tor_assert(conn->state <= CPUWORKER_STATE_MAX_);
  3867. break;
  3868. case CONN_TYPE_CONTROL:
  3869. tor_assert(conn->state >= CONTROL_CONN_STATE_MIN_);
  3870. tor_assert(conn->state <= CONTROL_CONN_STATE_MAX_);
  3871. break;
  3872. default:
  3873. tor_assert(0);
  3874. }
  3875. }
  3876. /** Fills <b>addr</b> and <b>port</b> with the details of the global
  3877. * proxy server we are using.
  3878. * <b>conn</b> contains the connection we are using the proxy for.
  3879. *
  3880. * Return 0 on success, -1 on failure.
  3881. */
  3882. int
  3883. get_proxy_addrport(tor_addr_t *addr, uint16_t *port, int *proxy_type,
  3884. const connection_t *conn)
  3885. {
  3886. const or_options_t *options = get_options();
  3887. if (options->HTTPSProxy) {
  3888. tor_addr_copy(addr, &options->HTTPSProxyAddr);
  3889. *port = options->HTTPSProxyPort;
  3890. *proxy_type = PROXY_CONNECT;
  3891. return 0;
  3892. } else if (options->Socks4Proxy) {
  3893. tor_addr_copy(addr, &options->Socks4ProxyAddr);
  3894. *port = options->Socks4ProxyPort;
  3895. *proxy_type = PROXY_SOCKS4;
  3896. return 0;
  3897. } else if (options->Socks5Proxy) {
  3898. tor_addr_copy(addr, &options->Socks5ProxyAddr);
  3899. *port = options->Socks5ProxyPort;
  3900. *proxy_type = PROXY_SOCKS5;
  3901. return 0;
  3902. } else if (options->ClientTransportPlugin ||
  3903. options->Bridges) {
  3904. const transport_t *transport = NULL;
  3905. int r;
  3906. r = find_transport_by_bridge_addrport(&conn->addr, conn->port, &transport);
  3907. if (r<0)
  3908. return -1;
  3909. if (transport) { /* transport found */
  3910. tor_addr_copy(addr, &transport->addr);
  3911. *port = transport->port;
  3912. *proxy_type = transport->socks_version;
  3913. return 0;
  3914. }
  3915. }
  3916. *proxy_type = PROXY_NONE;
  3917. return 0;
  3918. }
  3919. /** Returns the global proxy type used by tor. */
  3920. static int
  3921. get_proxy_type(void)
  3922. {
  3923. const or_options_t *options = get_options();
  3924. if (options->HTTPSProxy)
  3925. return PROXY_CONNECT;
  3926. else if (options->Socks4Proxy)
  3927. return PROXY_SOCKS4;
  3928. else if (options->Socks5Proxy)
  3929. return PROXY_SOCKS5;
  3930. else if (options->ClientTransportPlugin)
  3931. return PROXY_PLUGGABLE;
  3932. else
  3933. return PROXY_NONE;
  3934. }
  3935. /** Log a failed connection to a proxy server.
  3936. * <b>conn</b> is the connection we use the proxy server for. */
  3937. void
  3938. log_failed_proxy_connection(connection_t *conn)
  3939. {
  3940. tor_addr_t proxy_addr;
  3941. uint16_t proxy_port;
  3942. int proxy_type;
  3943. if (get_proxy_addrport(&proxy_addr, &proxy_port, &proxy_type, conn) != 0)
  3944. return; /* if we have no proxy set up, leave this function. */
  3945. log_warn(LD_NET,
  3946. "The connection to the %s proxy server at %s just failed. "
  3947. "Make sure that the proxy server is up and running.",
  3948. proxy_type_to_string(get_proxy_type()),
  3949. fmt_addrport(&proxy_addr, proxy_port));
  3950. }
  3951. /** Return string representation of <b>proxy_type</b>. */
  3952. static const char *
  3953. proxy_type_to_string(int proxy_type)
  3954. {
  3955. switch (proxy_type) {
  3956. case PROXY_CONNECT: return "HTTP";
  3957. case PROXY_SOCKS4: return "SOCKS4";
  3958. case PROXY_SOCKS5: return "SOCKS5";
  3959. case PROXY_PLUGGABLE: return "pluggable transports SOCKS";
  3960. case PROXY_NONE: return "NULL";
  3961. default: tor_assert(0);
  3962. }
  3963. return NULL; /*Unreached*/
  3964. }
  3965. /** Call connection_free_() on every connection in our array, and release all
  3966. * storage held by connection.c. This is used by cpuworkers and dnsworkers
  3967. * when they fork, so they don't keep resources held open (especially
  3968. * sockets).
  3969. *
  3970. * Don't do the checks in connection_free(), because they will
  3971. * fail.
  3972. */
  3973. void
  3974. connection_free_all(void)
  3975. {
  3976. smartlist_t *conns = get_connection_array();
  3977. /* We don't want to log any messages to controllers. */
  3978. SMARTLIST_FOREACH(conns, connection_t *, conn,
  3979. if (conn->type == CONN_TYPE_CONTROL)
  3980. TO_CONTROL_CONN(conn)->event_mask = 0);
  3981. control_update_global_event_mask();
  3982. /* Unlink everything from the identity map. */
  3983. connection_or_clear_identity_map();
  3984. /* Clear out our list of broken connections */
  3985. clear_broken_connection_map(0);
  3986. SMARTLIST_FOREACH(conns, connection_t *, conn, connection_free_(conn));
  3987. if (outgoing_addrs) {
  3988. SMARTLIST_FOREACH(outgoing_addrs, tor_addr_t *, addr, tor_free(addr));
  3989. smartlist_free(outgoing_addrs);
  3990. outgoing_addrs = NULL;
  3991. }
  3992. tor_free(last_interface_ipv4);
  3993. tor_free(last_interface_ipv6);
  3994. #ifdef USE_BUFFEREVENTS
  3995. if (global_rate_limit)
  3996. bufferevent_rate_limit_group_free(global_rate_limit);
  3997. #endif
  3998. }