connection.c 139 KB

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