connection.c 115 KB

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