connection.c 115 KB

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