connection.c 116 KB

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