connection.c 113 KB

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