connection.c 139 KB

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