connection.c 134 KB

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