connection.c 134 KB

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