connection.c 115 KB

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