connection.c 138 KB

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