connection.c 115 KB

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