connection.c 140 KB

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