connection.c 150 KB

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