connection.c 119 KB

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