connection.c 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2007, Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char connection_c_id[] =
  7. "$Id$";
  8. /**
  9. * \file connection.c
  10. * \brief General high-level functions to handle reading and writing
  11. * on connections.
  12. **/
  13. #include "or.h"
  14. static connection_t *connection_create_listener(const char *listenaddress,
  15. uint16_t listenport, int type);
  16. static int connection_init_accepted_conn(connection_t *conn,
  17. uint8_t listener_type);
  18. static int connection_handle_listener_read(connection_t *conn, int new_type);
  19. static int connection_read_bucket_should_increase(or_connection_t *conn);
  20. static int connection_finished_flushing(connection_t *conn);
  21. static int connection_flushed_some(connection_t *conn);
  22. static int connection_finished_connecting(connection_t *conn);
  23. static int connection_reached_eof(connection_t *conn);
  24. static int connection_read_to_buf(connection_t *conn, int *max_to_read);
  25. static int connection_process_inbuf(connection_t *conn, int package_partial);
  26. static void client_check_address_changed(int sock);
  27. static uint32_t last_interface_ip = 0;
  28. static smartlist_t *outgoing_addrs = NULL;
  29. /**************************************************************/
  30. /**
  31. * Return the human-readable name for the connection type <b>type</b>
  32. */
  33. const char *
  34. conn_type_to_string(int type)
  35. {
  36. static char buf[64];
  37. switch (type) {
  38. case CONN_TYPE_OR_LISTENER: return "OR listener";
  39. case CONN_TYPE_OR: return "OR";
  40. case CONN_TYPE_EXIT: return "Exit";
  41. case CONN_TYPE_AP_LISTENER: return "Socks listener";
  42. case CONN_TYPE_AP_TRANS_LISTENER:
  43. return "Transparent pf/netfilter listener";
  44. case CONN_TYPE_AP_NATD_LISTENER: return "Transparent natd listener";
  45. case CONN_TYPE_AP: return "Socks";
  46. case CONN_TYPE_DIR_LISTENER: return "Directory listener";
  47. case CONN_TYPE_DIR: return "Directory";
  48. case CONN_TYPE_DNSWORKER: return "DNS worker";
  49. case CONN_TYPE_CPUWORKER: return "CPU worker";
  50. case CONN_TYPE_CONTROL_LISTENER: return "Control listener";
  51. case CONN_TYPE_CONTROL: return "Control";
  52. default:
  53. log_warn(LD_BUG, "Bug: unknown connection type %d", type);
  54. tor_snprintf(buf, sizeof(buf), "unknown [%d]", type);
  55. return buf;
  56. }
  57. }
  58. /**
  59. * Return the human-readable name for the connection state <b>state</b>
  60. * for the connection type <b>type</b>
  61. */
  62. const char *
  63. conn_state_to_string(int type, int state)
  64. {
  65. static char buf[96];
  66. switch (type) {
  67. case CONN_TYPE_OR_LISTENER:
  68. case CONN_TYPE_AP_LISTENER:
  69. case CONN_TYPE_AP_TRANS_LISTENER:
  70. case CONN_TYPE_AP_NATD_LISTENER:
  71. case CONN_TYPE_DIR_LISTENER:
  72. case CONN_TYPE_CONTROL_LISTENER:
  73. if (state == LISTENER_STATE_READY)
  74. return "ready";
  75. break;
  76. case CONN_TYPE_OR:
  77. switch (state) {
  78. case OR_CONN_STATE_CONNECTING: return "connect()ing";
  79. case OR_CONN_STATE_PROXY_FLUSHING: return "proxy flushing";
  80. case OR_CONN_STATE_PROXY_READING: return "proxy reading";
  81. case OR_CONN_STATE_HANDSHAKING: return "handshaking";
  82. case OR_CONN_STATE_OPEN: return "open";
  83. }
  84. break;
  85. case CONN_TYPE_EXIT:
  86. switch (state) {
  87. case EXIT_CONN_STATE_RESOLVING: return "waiting for dest info";
  88. case EXIT_CONN_STATE_CONNECTING: return "connecting";
  89. case EXIT_CONN_STATE_OPEN: return "open";
  90. case EXIT_CONN_STATE_RESOLVEFAILED: return "resolve failed";
  91. }
  92. break;
  93. case CONN_TYPE_AP:
  94. switch (state) {
  95. case AP_CONN_STATE_SOCKS_WAIT: return "waiting for socks info";
  96. case AP_CONN_STATE_NATD_WAIT: return "waiting for natd dest info";
  97. case AP_CONN_STATE_RENDDESC_WAIT: return "waiting for rendezvous desc";
  98. case AP_CONN_STATE_CONTROLLER_WAIT: return "waiting for controller";
  99. case AP_CONN_STATE_CIRCUIT_WAIT: return "waiting for circuit";
  100. case AP_CONN_STATE_CONNECT_WAIT: return "waiting for connect response";
  101. case AP_CONN_STATE_RESOLVE_WAIT: return "waiting for resolve response";
  102. case AP_CONN_STATE_OPEN: return "open";
  103. }
  104. break;
  105. case CONN_TYPE_DIR:
  106. switch (state) {
  107. case DIR_CONN_STATE_CONNECTING: return "connecting";
  108. case DIR_CONN_STATE_CLIENT_SENDING: return "client sending";
  109. case DIR_CONN_STATE_CLIENT_READING: return "client reading";
  110. case DIR_CONN_STATE_SERVER_COMMAND_WAIT: return "waiting for command";
  111. case DIR_CONN_STATE_SERVER_WRITING: return "writing";
  112. }
  113. break;
  114. case CONN_TYPE_DNSWORKER:
  115. switch (state) {
  116. case DNSWORKER_STATE_IDLE: return "idle";
  117. case DNSWORKER_STATE_BUSY: return "busy";
  118. }
  119. break;
  120. case CONN_TYPE_CPUWORKER:
  121. switch (state) {
  122. case CPUWORKER_STATE_IDLE: return "idle";
  123. case CPUWORKER_STATE_BUSY_ONION: return "busy with onion";
  124. }
  125. break;
  126. case CONN_TYPE_CONTROL:
  127. switch (state) {
  128. case CONTROL_CONN_STATE_OPEN_V0: return "open (protocol v0)";
  129. case CONTROL_CONN_STATE_OPEN_V1: return "open (protocol v1)";
  130. case CONTROL_CONN_STATE_NEEDAUTH_V0:
  131. return "waiting for authentication (protocol unknown)";
  132. case CONTROL_CONN_STATE_NEEDAUTH_V1:
  133. return "waiting for authentication (protocol v1)";
  134. }
  135. break;
  136. }
  137. log_warn(LD_BUG, "Bug: unknown connection state %d (type %d)", state, type);
  138. tor_snprintf(buf, sizeof(buf),
  139. "unknown state [%d] on unknown [%s] connection",
  140. state, conn_type_to_string(type));
  141. return buf;
  142. }
  143. /** Allocate space for a new connection_t. This function just initializes
  144. * conn; you must call connection_add() to link it into the main array.
  145. *
  146. * Set conn-\>type to <b>type</b>. Set conn-\>s and conn-\>conn_array_index to
  147. * -1 to signify they are not yet assigned.
  148. *
  149. * If conn is not a listener type, allocate buffers for it. If it's
  150. * an AP type, allocate space to store the socks_request.
  151. *
  152. * Assign a pseudorandom next_circ_id between 0 and 2**15.
  153. *
  154. * Initialize conn's timestamps to now.
  155. */
  156. connection_t *
  157. connection_new(int type)
  158. {
  159. static uint32_t n_connections_allocated = 1;
  160. connection_t *conn;
  161. time_t now = time(NULL);
  162. size_t length;
  163. uint32_t magic;
  164. switch (type) {
  165. case CONN_TYPE_OR:
  166. length = sizeof(or_connection_t);
  167. magic = OR_CONNECTION_MAGIC;
  168. break;
  169. case CONN_TYPE_EXIT:
  170. case CONN_TYPE_AP:
  171. length = sizeof(edge_connection_t);
  172. magic = EDGE_CONNECTION_MAGIC;
  173. break;
  174. case CONN_TYPE_DIR:
  175. length = sizeof(dir_connection_t);
  176. magic = DIR_CONNECTION_MAGIC;
  177. break;
  178. case CONN_TYPE_CONTROL:
  179. length = sizeof(control_connection_t);
  180. magic = CONTROL_CONNECTION_MAGIC;
  181. break;
  182. default:
  183. length = sizeof(connection_t);
  184. magic = BASE_CONNECTION_MAGIC;
  185. break;
  186. }
  187. conn = tor_malloc_zero(length);
  188. conn->magic = magic;
  189. conn->s = -1; /* give it a default of 'not used' */
  190. conn->conn_array_index = -1; /* also default to 'not used' */
  191. conn->type = type;
  192. if (!connection_is_listener(conn)) { /* listeners never use their buf */
  193. conn->inbuf = buf_new();
  194. conn->outbuf = buf_new();
  195. }
  196. if (type == CONN_TYPE_AP) {
  197. TO_EDGE_CONN(conn)->socks_request =
  198. tor_malloc_zero(sizeof(socks_request_t));
  199. }
  200. if (CONN_IS_EDGE(conn)) {
  201. TO_EDGE_CONN(conn)->global_identifier = n_connections_allocated++;
  202. }
  203. if (type == CONN_TYPE_OR)
  204. TO_OR_CONN(conn)->next_circ_id = crypto_rand_int(1<<15);
  205. conn->timestamp_created = now;
  206. conn->timestamp_lastread = now;
  207. conn->timestamp_lastwritten = now;
  208. return conn;
  209. }
  210. /** Tell libevent that we don't care about <b>conn</b> any more. */
  211. void
  212. connection_unregister(connection_t *conn)
  213. {
  214. if (conn->read_event) {
  215. if (event_del(conn->read_event))
  216. log_warn(LD_BUG, "Error removing read event for %d", conn->s);
  217. tor_free(conn->read_event);
  218. }
  219. if (conn->write_event) {
  220. if (event_del(conn->write_event))
  221. log_warn(LD_BUG, "Error removing write event for %d", conn->s);
  222. tor_free(conn->write_event);
  223. }
  224. }
  225. /** Deallocate memory used by <b>conn</b>. Deallocate its buffers if
  226. * necessary, close its socket if necessary, and mark the directory as dirty
  227. * if <b>conn</b> is an OR or OP connection.
  228. */
  229. static void
  230. _connection_free(connection_t *conn)
  231. {
  232. void *mem;
  233. switch (conn->type) {
  234. case CONN_TYPE_OR:
  235. tor_assert(conn->magic == OR_CONNECTION_MAGIC);
  236. mem = TO_OR_CONN(conn);
  237. break;
  238. case CONN_TYPE_AP:
  239. case CONN_TYPE_EXIT:
  240. tor_assert(conn->magic == EDGE_CONNECTION_MAGIC);
  241. mem = TO_EDGE_CONN(conn);
  242. break;
  243. case CONN_TYPE_DIR:
  244. tor_assert(conn->magic == DIR_CONNECTION_MAGIC);
  245. mem = TO_DIR_CONN(conn);
  246. break;
  247. case CONN_TYPE_CONTROL:
  248. tor_assert(conn->magic == CONTROL_CONNECTION_MAGIC);
  249. mem = TO_CONTROL_CONN(conn);
  250. break;
  251. default:
  252. tor_assert(conn->magic == BASE_CONNECTION_MAGIC);
  253. mem = conn;
  254. break;
  255. }
  256. if (!connection_is_listener(conn)) {
  257. buf_free(conn->inbuf);
  258. buf_free(conn->outbuf);
  259. }
  260. tor_free(conn->address);
  261. if (connection_speaks_cells(conn)) {
  262. or_connection_t *or_conn = TO_OR_CONN(conn);
  263. if (or_conn->tls) {
  264. tor_tls_free(or_conn->tls);
  265. or_conn->tls = NULL;
  266. }
  267. tor_free(or_conn->nickname);
  268. }
  269. if (CONN_IS_EDGE(conn)) {
  270. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  271. tor_free(edge_conn->chosen_exit_name);
  272. tor_free(edge_conn->socks_request);
  273. }
  274. if (conn->type == CONN_TYPE_CONTROL) {
  275. control_connection_t *control_conn = TO_CONTROL_CONN(conn);
  276. tor_free(control_conn->incoming_cmd);
  277. }
  278. tor_free(conn->read_event); /* Probably already freed by connection_free. */
  279. tor_free(conn->write_event); /* Probably already freed by connection_free. */
  280. if (conn->type == CONN_TYPE_DIR) {
  281. dir_connection_t *dir_conn = TO_DIR_CONN(conn);
  282. tor_free(dir_conn->requested_resource);
  283. if (dir_conn->zlib_state)
  284. tor_zlib_free(dir_conn->zlib_state);
  285. if (dir_conn->fingerprint_stack) {
  286. SMARTLIST_FOREACH(dir_conn->fingerprint_stack, char *, cp, tor_free(cp));
  287. smartlist_free(dir_conn->fingerprint_stack);
  288. }
  289. if (dir_conn->cached_dir)
  290. cached_dir_decref(dir_conn->cached_dir);
  291. }
  292. if (conn->s >= 0) {
  293. log_debug(LD_NET,"closing fd %d.",conn->s);
  294. tor_close_socket(conn->s);
  295. }
  296. if (conn->type == CONN_TYPE_OR &&
  297. !tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest)) {
  298. log_warn(LD_BUG, "called on OR conn with non-zeroed identity_digest");
  299. connection_or_remove_from_identity_map(TO_OR_CONN(conn));
  300. }
  301. memset(conn, 0xAA, sizeof(connection_t)); /* poison memory */
  302. tor_free(mem);
  303. }
  304. /** Make sure <b>conn</b> isn't in any of the global conn lists; then free it.
  305. */
  306. void
  307. connection_free(connection_t *conn)
  308. {
  309. tor_assert(conn);
  310. tor_assert(!connection_is_on_closeable_list(conn));
  311. tor_assert(!connection_in_array(conn));
  312. if (connection_speaks_cells(conn)) {
  313. if (conn->state == OR_CONN_STATE_OPEN)
  314. directory_set_dirty();
  315. if (!tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest)) {
  316. connection_or_remove_from_identity_map(TO_OR_CONN(conn));
  317. }
  318. }
  319. if (conn->type == CONN_TYPE_CONTROL) {
  320. TO_CONTROL_CONN(conn)->event_mask = 0;
  321. control_update_global_event_mask();
  322. }
  323. connection_unregister(conn);
  324. _connection_free(conn);
  325. }
  326. /** Call _connection_free() on every connection in our array, and release all
  327. * storage helpd by connection.c. This is used by cpuworkers and dnsworkers
  328. * when they fork, so they don't keep resources held open (especially
  329. * sockets).
  330. *
  331. * Don't do the checks in connection_free(), because they will
  332. * fail.
  333. */
  334. void
  335. connection_free_all(void)
  336. {
  337. int i, n;
  338. connection_t **carray;
  339. get_connection_array(&carray,&n);
  340. /* We don't want to log any messages to controllers. */
  341. for (i=0;i<n;i++)
  342. if (carray[i]->type == CONN_TYPE_CONTROL)
  343. TO_CONTROL_CONN(carray[i])->event_mask = 0;
  344. control_update_global_event_mask();
  345. /* Unlink everything from the identity map. */
  346. connection_or_clear_identity_map();
  347. for (i=0;i<n;i++)
  348. _connection_free(carray[i]);
  349. if (outgoing_addrs) {
  350. SMARTLIST_FOREACH(outgoing_addrs, void*, addr, tor_free(addr));
  351. smartlist_free(outgoing_addrs);
  352. outgoing_addrs = NULL;
  353. }
  354. }
  355. /** Do any cleanup needed:
  356. * - Directory conns that failed to fetch a rendezvous descriptor
  357. * need to inform pending rendezvous streams.
  358. * - OR conns need to call rep_hist_note_*() to record status.
  359. * - AP conns need to send a socks reject if necessary.
  360. * - Exit conns need to call connection_dns_remove() if necessary.
  361. * - AP and Exit conns need to send an end cell if they can.
  362. * - DNS conns need to fail any resolves that are pending on them.
  363. * - OR and edge connections need to be unlinked from circuits.
  364. */
  365. void
  366. connection_about_to_close_connection(connection_t *conn)
  367. {
  368. circuit_t *circ;
  369. dir_connection_t *dir_conn;
  370. or_connection_t *or_conn;
  371. edge_connection_t *edge_conn;
  372. time_t now = time(NULL);
  373. assert(conn->marked_for_close);
  374. if (CONN_IS_EDGE(conn)) {
  375. if (!conn->edge_has_sent_end) {
  376. log_warn(LD_BUG, "Harmless bug: Edge connection (marked at %s:%d) "
  377. "hasn't sent end yet?",
  378. conn->marked_for_close_file, conn->marked_for_close);
  379. tor_fragile_assert();
  380. }
  381. }
  382. switch (conn->type) {
  383. case CONN_TYPE_DIR:
  384. dir_conn = TO_DIR_CONN(conn);
  385. if (conn->state < DIR_CONN_STATE_CLIENT_FINISHED) {
  386. /* It's a directory connection and connecting or fetching
  387. * failed: forget about this router, and maybe try again. */
  388. connection_dir_request_failed(dir_conn);
  389. // XXX if it's rend desc we may want to retry -RD
  390. }
  391. if (conn->purpose == DIR_PURPOSE_FETCH_RENDDESC)
  392. rend_client_desc_here(dir_conn->rend_query); /* give it a try */
  393. /* If this is from BEGIN_DIR, unlink it from the edge_conn and
  394. * the or_conn. */
  395. if (dir_conn->bridge_conn)
  396. connection_dirserv_unlink_from_bridge(dir_conn);
  397. break;
  398. case CONN_TYPE_OR:
  399. or_conn = TO_OR_CONN(conn);
  400. /* Remember why we're closing this connection. */
  401. if (conn->state != OR_CONN_STATE_OPEN) {
  402. if (connection_or_nonopen_was_started_here(or_conn)) {
  403. rep_hist_note_connect_failed(or_conn->identity_digest, now);
  404. entry_guard_register_connect_status(or_conn->identity_digest,0,now);
  405. router_set_status(or_conn->identity_digest, 0);
  406. control_event_or_conn_status(or_conn, OR_CONN_EVENT_FAILED,
  407. control_tls_error_to_reason(or_conn->tls_error));
  408. }
  409. /* Inform any pending (not attached) circs that they should
  410. * give up. */
  411. circuit_n_conn_done(TO_OR_CONN(conn), 0);
  412. } else if (conn->hold_open_until_flushed) {
  413. /* We only set hold_open_until_flushed when we're intentionally
  414. * closing a connection. */
  415. rep_hist_note_disconnect(or_conn->identity_digest, now);
  416. control_event_or_conn_status(or_conn, OR_CONN_EVENT_CLOSED,
  417. control_tls_error_to_reason(or_conn->tls_error));
  418. } else if (or_conn->identity_digest) {
  419. rep_hist_note_connection_died(or_conn->identity_digest, now);
  420. control_event_or_conn_status(or_conn, OR_CONN_EVENT_CLOSED,
  421. control_tls_error_to_reason(or_conn->tls_error));
  422. }
  423. /* Remove any dir_conns that are blocked on this one. Non-blocked
  424. * ones will die when the circuits do. */
  425. while (or_conn->blocked_dir_connections) {
  426. dir_connection_t *dir_conn = or_conn->blocked_dir_connections;
  427. connection_dirserv_unlink_from_bridge(dir_conn);
  428. tor_assert(or_conn->blocked_dir_connections != dir_conn);
  429. }
  430. /* Now close all the attached circuits on it. */
  431. circuit_unlink_all_from_or_conn(TO_OR_CONN(conn),
  432. END_CIRC_REASON_OR_CONN_CLOSED);
  433. break;
  434. case CONN_TYPE_AP:
  435. edge_conn = TO_EDGE_CONN(conn);
  436. if (edge_conn->socks_request->has_finished == 0) {
  437. /* since conn gets removed right after this function finishes,
  438. * there's no point trying to send back a reply at this point. */
  439. log_warn(LD_BUG,"Bug: Closing stream (marked at %s:%d) without sending"
  440. " back a socks reply.",
  441. conn->marked_for_close_file, conn->marked_for_close);
  442. }
  443. if (!edge_conn->end_reason) {
  444. log_warn(LD_BUG,"Bug: Closing stream (marked at %s:%d) without having"
  445. " set end_reason.",
  446. conn->marked_for_close_file, conn->marked_for_close);
  447. }
  448. control_event_stream_status(edge_conn, STREAM_EVENT_CLOSED,
  449. edge_conn->end_reason);
  450. circ = circuit_get_by_edge_conn(edge_conn);
  451. if (circ)
  452. circuit_detach_stream(circ, edge_conn);
  453. break;
  454. case CONN_TYPE_EXIT:
  455. edge_conn = TO_EDGE_CONN(conn);
  456. circ = circuit_get_by_edge_conn(edge_conn);
  457. if (circ)
  458. circuit_detach_stream(circ, edge_conn);
  459. if (conn->state == EXIT_CONN_STATE_RESOLVING) {
  460. connection_dns_remove(edge_conn);
  461. }
  462. /* If we're relaying a dirserv connection, clean up any pointers */
  463. if (edge_conn->bridge_for_conn)
  464. connection_dirserv_unlink_from_bridge(edge_conn->bridge_for_conn);
  465. break;
  466. case CONN_TYPE_DNSWORKER:
  467. if (conn->state == DNSWORKER_STATE_BUSY) {
  468. dns_cancel_pending_resolve(conn->address);
  469. }
  470. break;
  471. }
  472. }
  473. /** Close the underlying socket for <b>conn</b>, so we don't try to
  474. * flush it. Must be used in conjunction with (right before)
  475. * connection_mark_for_close().
  476. */
  477. void
  478. connection_close_immediate(connection_t *conn)
  479. {
  480. assert_connection_ok(conn,0);
  481. if (conn->s < 0) {
  482. log_err(LD_BUG,"Bug: Attempt to close already-closed connection.");
  483. tor_fragile_assert();
  484. return;
  485. }
  486. if (conn->outbuf_flushlen) {
  487. log_info(LD_NET,"fd %d, type %s, state %s, %d bytes on outbuf.",
  488. conn->s, conn_type_to_string(conn->type),
  489. conn_state_to_string(conn->type, conn->state),
  490. (int)conn->outbuf_flushlen);
  491. }
  492. connection_unregister(conn);
  493. tor_close_socket(conn->s);
  494. conn->s = -1;
  495. if (!connection_is_listener(conn)) {
  496. buf_clear(conn->outbuf);
  497. conn->outbuf_flushlen = 0;
  498. }
  499. }
  500. /** Mark <b>conn</b> to be closed next time we loop through
  501. * conn_close_if_marked() in main.c. */
  502. void
  503. _connection_mark_for_close(connection_t *conn, int line, const char *file)
  504. {
  505. assert_connection_ok(conn,0);
  506. tor_assert(line);
  507. tor_assert(file);
  508. if (conn->marked_for_close) {
  509. log(LOG_WARN,LD_BUG,"Duplicate call to connection_mark_for_close at %s:%d"
  510. " (first at %s:%d)", file, line, conn->marked_for_close_file,
  511. conn->marked_for_close);
  512. tor_fragile_assert();
  513. return;
  514. }
  515. conn->marked_for_close = line;
  516. conn->marked_for_close_file = file;
  517. add_connection_to_closeable_list(conn);
  518. /* in case we're going to be held-open-til-flushed, reset
  519. * the number of seconds since last successful write, so
  520. * we get our whole 15 seconds */
  521. conn->timestamp_lastwritten = time(NULL);
  522. }
  523. /** Find each connection that has hold_open_until_flushed set to
  524. * 1 but hasn't written in the past 15 seconds, and set
  525. * hold_open_until_flushed to 0. This means it will get cleaned
  526. * up in the next loop through close_if_marked() in main.c.
  527. */
  528. void
  529. connection_expire_held_open(void)
  530. {
  531. connection_t **carray, *conn;
  532. int n, i;
  533. time_t now;
  534. now = time(NULL);
  535. get_connection_array(&carray, &n);
  536. for (i = 0; i < n; ++i) {
  537. conn = carray[i];
  538. /* If we've been holding the connection open, but we haven't written
  539. * for 15 seconds...
  540. */
  541. if (conn->hold_open_until_flushed) {
  542. tor_assert(conn->marked_for_close);
  543. if (now - conn->timestamp_lastwritten >= 15) {
  544. int severity;
  545. if (conn->type == CONN_TYPE_EXIT ||
  546. (conn->type == CONN_TYPE_DIR &&
  547. conn->purpose == DIR_PURPOSE_SERVER))
  548. severity = LOG_INFO;
  549. else
  550. severity = LOG_NOTICE;
  551. log_fn(severity, LD_NET,
  552. "Giving up on marked_for_close conn that's been flushing "
  553. "for 15s (fd %d, type %s, state %s).",
  554. conn->s, conn_type_to_string(conn->type),
  555. conn_state_to_string(conn->type, conn->state));
  556. conn->hold_open_until_flushed = 0;
  557. }
  558. }
  559. }
  560. }
  561. /** Bind a new non-blocking socket listening to
  562. * <b>listenaddress</b>:<b>listenport</b>, and add this new connection
  563. * (of type <b>type</b>) to the connection array.
  564. *
  565. * If <b>listenaddress</b> includes a port, we bind on that port;
  566. * otherwise, we use listenport.
  567. */
  568. static connection_t *
  569. connection_create_listener(const char *listenaddress, uint16_t listenport,
  570. int type)
  571. {
  572. struct sockaddr_in listenaddr; /* where to bind */
  573. char *address = NULL;
  574. connection_t *conn;
  575. uint16_t usePort;
  576. uint32_t addr;
  577. int s; /* the socket we're going to make */
  578. #ifndef MS_WINDOWS
  579. int one=1;
  580. #endif
  581. memset(&listenaddr,0,sizeof(struct sockaddr_in));
  582. if (parse_addr_port(LOG_WARN, listenaddress, &address, &addr, &usePort)<0) {
  583. log_warn(LD_CONFIG,
  584. "Error parsing/resolving ListenAddress %s", listenaddress);
  585. return NULL;
  586. }
  587. if (usePort==0)
  588. usePort = listenport;
  589. listenaddr.sin_addr.s_addr = htonl(addr);
  590. listenaddr.sin_family = AF_INET;
  591. listenaddr.sin_port = htons((uint16_t) usePort);
  592. log_notice(LD_NET, "Opening %s on %s:%d",
  593. conn_type_to_string(type), address, usePort);
  594. s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
  595. if (s < 0) {
  596. log_warn(LD_NET,"Socket creation failed.");
  597. goto err;
  598. }
  599. #ifndef MS_WINDOWS
  600. /* REUSEADDR on normal places means you can rebind to the port
  601. * right after somebody else has let it go. But REUSEADDR on win32
  602. * means you can bind to the port _even when somebody else
  603. * already has it bound_. So, don't do that on Win32. */
  604. setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*) &one, sizeof(one));
  605. #endif
  606. if (bind(s,(struct sockaddr *)&listenaddr,sizeof(listenaddr)) < 0) {
  607. const char *helpfulhint = "";
  608. int e = tor_socket_errno(s);
  609. if (ERRNO_IS_EADDRINUSE(e))
  610. helpfulhint = ". Is Tor already running?";
  611. log_warn(LD_NET, "Could not bind to %s:%u: %s%s", address, usePort,
  612. tor_socket_strerror(e), helpfulhint);
  613. tor_close_socket(s);
  614. goto err;
  615. }
  616. if (listen(s,SOMAXCONN) < 0) {
  617. log_warn(LD_NET, "Could not listen on %s:%u: %s", address, usePort,
  618. tor_socket_strerror(tor_socket_errno(s)));
  619. tor_close_socket(s);
  620. goto err;
  621. }
  622. set_socket_nonblocking(s);
  623. conn = connection_new(type);
  624. conn->s = s;
  625. conn->address = address;
  626. address = NULL;
  627. conn->port = usePort;
  628. if (connection_add(conn) < 0) { /* no space, forget it */
  629. log_warn(LD_NET,"connection_add for listener failed. Giving up.");
  630. connection_free(conn);
  631. goto err;
  632. }
  633. log_debug(LD_NET,"%s listening on port %u.",
  634. conn_type_to_string(type), usePort);
  635. conn->state = LISTENER_STATE_READY;
  636. connection_start_reading(conn);
  637. return conn;
  638. err:
  639. tor_free(address);
  640. return NULL;
  641. }
  642. /** Do basic sanity checking on a newly received socket. Return 0
  643. * if it looks ok, else return -1. */
  644. static int
  645. check_sockaddr_in(struct sockaddr *sa, int len, int level)
  646. {
  647. int ok = 1;
  648. struct sockaddr_in *sin=(struct sockaddr_in*)sa;
  649. if (len != sizeof(struct sockaddr_in)) {
  650. log_fn(level, LD_NET, "Length of address not as expected: %d vs %d",
  651. len,(int)sizeof(struct sockaddr_in));
  652. ok = 0;
  653. }
  654. if (sa->sa_family != AF_INET) {
  655. log_fn(level, LD_NET, "Family of address not as expected: %d vs %d",
  656. sa->sa_family, AF_INET);
  657. ok = 0;
  658. }
  659. if (sin->sin_addr.s_addr == 0 || sin->sin_port == 0) {
  660. log_fn(level, LD_NET,
  661. "Address for new connection has address/port equal to zero.");
  662. ok = 0;
  663. }
  664. return ok ? 0 : -1;
  665. }
  666. /** The listener connection <b>conn</b> told poll() it wanted to read.
  667. * Call accept() on conn-\>s, and add the new connection if necessary.
  668. */
  669. static int
  670. connection_handle_listener_read(connection_t *conn, int new_type)
  671. {
  672. int news; /* the new socket */
  673. connection_t *newconn;
  674. /* information about the remote peer when connecting to other routers */
  675. struct sockaddr_in remote;
  676. char addrbuf[256];
  677. /* length of the remote address. Must be whatever accept() needs. */
  678. socklen_t remotelen = 256;
  679. char tmpbuf[INET_NTOA_BUF_LEN];
  680. tor_assert((size_t)remotelen >= sizeof(struct sockaddr_in));
  681. memset(addrbuf, 0, sizeof(addrbuf));
  682. news = accept(conn->s,(struct sockaddr *)&addrbuf,&remotelen);
  683. if (news < 0) { /* accept() error */
  684. int e = tor_socket_errno(conn->s);
  685. if (ERRNO_IS_ACCEPT_EAGAIN(e)) {
  686. return 0; /* he hung up before we could accept(). that's fine. */
  687. } else if (ERRNO_IS_ACCEPT_RESOURCE_LIMIT(e)) {
  688. log_notice(LD_NET,"accept failed: %s. Dropping incoming connection.",
  689. tor_socket_strerror(e));
  690. return 0;
  691. }
  692. /* else there was a real error. */
  693. log_warn(LD_NET,"accept() failed: %s. Closing listener.",
  694. tor_socket_strerror(e));
  695. connection_mark_for_close(conn);
  696. return -1;
  697. }
  698. log_debug(LD_NET,
  699. "Connection accepted on socket %d (child of fd %d).",
  700. news,conn->s);
  701. set_socket_nonblocking(news);
  702. if (check_sockaddr_in((struct sockaddr*)addrbuf, remotelen, LOG_INFO)<0) {
  703. log_info(LD_NET,
  704. "accept() returned a strange address; trying getsockname().");
  705. remotelen=256;
  706. memset(addrbuf, 0, sizeof(addrbuf));
  707. if (getsockname(news, (struct sockaddr*)addrbuf, &remotelen)<0) {
  708. int e = tor_socket_errno(news);
  709. log_warn(LD_NET, "getsockname() for new connection failed: %s",
  710. tor_socket_strerror(e));
  711. } else {
  712. if (check_sockaddr_in((struct sockaddr*)addrbuf, remotelen,
  713. LOG_WARN) < 0) {
  714. log_warn(LD_NET,"Something's wrong with this conn. Closing it.");
  715. tor_close_socket(news);
  716. return 0;
  717. }
  718. }
  719. }
  720. memcpy(&remote, addrbuf, sizeof(struct sockaddr_in));
  721. /* process entrance policies here, before we even create the connection */
  722. if (new_type == CONN_TYPE_AP) {
  723. /* check sockspolicy to see if we should accept it */
  724. if (socks_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
  725. tor_inet_ntoa(&remote.sin_addr, tmpbuf, sizeof(tmpbuf));
  726. log_notice(LD_APP,"Denying socks connection from untrusted address %s.",
  727. tmpbuf);
  728. tor_close_socket(news);
  729. return 0;
  730. }
  731. }
  732. if (new_type == CONN_TYPE_DIR) {
  733. /* check dirpolicy to see if we should accept it */
  734. if (dir_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
  735. tor_inet_ntoa(&remote.sin_addr, tmpbuf, sizeof(tmpbuf));
  736. log_notice(LD_DIRSERV,"Denying dir connection from address %s.",
  737. tmpbuf);
  738. tor_close_socket(news);
  739. return 0;
  740. }
  741. }
  742. newconn = connection_new(new_type);
  743. newconn->s = news;
  744. /* remember the remote address */
  745. newconn->addr = ntohl(remote.sin_addr.s_addr);
  746. newconn->port = ntohs(remote.sin_port);
  747. newconn->address = tor_dup_addr(newconn->addr);
  748. if (connection_add(newconn) < 0) { /* no space, forget it */
  749. connection_free(newconn);
  750. return 0; /* no need to tear down the parent */
  751. }
  752. if (connection_init_accepted_conn(newconn, conn->type) < 0) {
  753. connection_mark_for_close(newconn);
  754. return 0;
  755. }
  756. return 0;
  757. }
  758. /** Initialize states for newly accepted connection <b>conn</b>.
  759. * If conn is an OR, start the tls handshake.
  760. * If conn is a transparent AP, get its original destination
  761. * and place it in circuit_wait.
  762. */
  763. static int
  764. connection_init_accepted_conn(connection_t *conn, uint8_t listener_type)
  765. {
  766. connection_start_reading(conn);
  767. switch (conn->type) {
  768. case CONN_TYPE_OR:
  769. control_event_or_conn_status(TO_OR_CONN(conn), OR_CONN_EVENT_NEW, 0);
  770. return connection_tls_start_handshake(TO_OR_CONN(conn), 1);
  771. case CONN_TYPE_AP:
  772. switch (listener_type) {
  773. case CONN_TYPE_AP_LISTENER:
  774. conn->state = AP_CONN_STATE_SOCKS_WAIT;
  775. break;
  776. case CONN_TYPE_AP_TRANS_LISTENER:
  777. conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  778. return connection_ap_process_transparent(TO_EDGE_CONN(conn));
  779. case CONN_TYPE_AP_NATD_LISTENER:
  780. conn->state = AP_CONN_STATE_NATD_WAIT;
  781. break;
  782. }
  783. break;
  784. case CONN_TYPE_DIR:
  785. conn->purpose = DIR_PURPOSE_SERVER;
  786. conn->state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
  787. break;
  788. case CONN_TYPE_CONTROL:
  789. conn->state = CONTROL_CONN_STATE_NEEDAUTH_V0;
  790. break;
  791. }
  792. return 0;
  793. }
  794. /** Take conn, make a nonblocking socket; try to connect to
  795. * addr:port (they arrive in *host order*). If fail, return -1. Else
  796. * assign s to conn-\>s: if connected return 1, if EAGAIN return 0.
  797. *
  798. * address is used to make the logs useful.
  799. *
  800. * On success, add conn to the list of polled connections.
  801. */
  802. int
  803. connection_connect(connection_t *conn, const char *address,
  804. uint32_t addr, uint16_t port)
  805. {
  806. int s, inprogress = 0;
  807. struct sockaddr_in dest_addr;
  808. or_options_t *options = get_options();
  809. s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
  810. if (s < 0) {
  811. log_warn(LD_NET,"Error creating network socket: %s",
  812. tor_socket_strerror(tor_socket_errno(-1)));
  813. return -1;
  814. }
  815. if (options->OutboundBindAddress) {
  816. struct sockaddr_in ext_addr;
  817. memset(&ext_addr, 0, sizeof(ext_addr));
  818. ext_addr.sin_family = AF_INET;
  819. ext_addr.sin_port = 0;
  820. if (!tor_inet_aton(options->OutboundBindAddress, &ext_addr.sin_addr)) {
  821. log_warn(LD_CONFIG,"Outbound bind address '%s' didn't parse. Ignoring.",
  822. options->OutboundBindAddress);
  823. } else {
  824. if (bind(s, (struct sockaddr*)&ext_addr, sizeof(ext_addr)) < 0) {
  825. log_warn(LD_NET,"Error binding network socket: %s",
  826. tor_socket_strerror(tor_socket_errno(s)));
  827. tor_close_socket(s);
  828. return -1;
  829. }
  830. }
  831. }
  832. set_socket_nonblocking(s);
  833. memset(&dest_addr,0,sizeof(dest_addr));
  834. dest_addr.sin_family = AF_INET;
  835. dest_addr.sin_port = htons(port);
  836. dest_addr.sin_addr.s_addr = htonl(addr);
  837. log_debug(LD_NET,"Connecting to %s:%u.",escaped_safe_str(address),port);
  838. if (connect(s,(struct sockaddr *)&dest_addr,sizeof(dest_addr)) < 0) {
  839. int e = tor_socket_errno(s);
  840. if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
  841. /* yuck. kill it. */
  842. log_info(LD_NET,
  843. "connect() to %s:%u failed: %s",escaped_safe_str(address),
  844. port, tor_socket_strerror(e));
  845. tor_close_socket(s);
  846. return -1;
  847. } else {
  848. inprogress = 1;
  849. }
  850. }
  851. if (!server_mode(options))
  852. client_check_address_changed(s);
  853. /* it succeeded. we're connected. */
  854. log_fn(inprogress?LOG_DEBUG:LOG_INFO, LD_NET,
  855. "Connection to %s:%u %s (sock %d).",escaped_safe_str(address),
  856. port, inprogress?"in progress":"established", s);
  857. conn->s = s;
  858. if (connection_add(conn) < 0) /* no space, forget it */
  859. return -1;
  860. return inprogress ? 0 : 1;
  861. }
  862. /**
  863. * Launch any configured listener connections of type <b>type</b>. (A
  864. * listener is configured if <b>port_option</b> is non-zero. If any
  865. * ListenAddress configuration options are given in <b>cfg</b>, create a
  866. * connection binding to each one. Otherwise, create a single
  867. * connection binding to the address <b>default_addr</b>.)
  868. *
  869. * If <b>force</b> is true, close and re-open all listener connections.
  870. * Otherwise, only relaunch the listeners of this type if the number of
  871. * existing connections is not as configured (e.g., because one died),
  872. * or if the existing connections do not match those configured.
  873. *
  874. * Add all old conns that should be closed to <b>replaced_conns</b>.
  875. * Add all new connections to <b>new_conns</b>.
  876. */
  877. static int
  878. retry_listeners(int type, config_line_t *cfg,
  879. int port_option, const char *default_addr, int force,
  880. smartlist_t *replaced_conns,
  881. smartlist_t *new_conns,
  882. int never_open_conns)
  883. {
  884. smartlist_t *launch = smartlist_create();
  885. int free_launch_elts = 1;
  886. config_line_t *c;
  887. int n_conn, i;
  888. connection_t *conn;
  889. connection_t **carray;
  890. config_line_t *line;
  891. if (cfg && port_option) {
  892. for (c = cfg; c; c = c->next) {
  893. smartlist_add(launch, c);
  894. }
  895. free_launch_elts = 0;
  896. } else if (port_option) {
  897. line = tor_malloc_zero(sizeof(config_line_t));
  898. line->key = tor_strdup("");
  899. line->value = tor_strdup(default_addr);
  900. smartlist_add(launch, line);
  901. }
  902. /*
  903. SMARTLIST_FOREACH(launch, config_line_t *, l,
  904. log_fn(LOG_NOTICE, "#%s#%s", l->key, l->value));
  905. */
  906. get_connection_array(&carray,&n_conn);
  907. for (i=0; i < n_conn; ++i) {
  908. conn = carray[i];
  909. if (conn->type != type || conn->marked_for_close)
  910. continue;
  911. if (force) {
  912. /* It's a listener, and we're relaunching all listeners of this
  913. * type. Close this one. */
  914. log_notice(LD_NET, "Force-closing listener %s on %s:%d",
  915. conn_type_to_string(type), conn->address, conn->port);
  916. connection_close_immediate(conn);
  917. connection_mark_for_close(conn);
  918. continue;
  919. }
  920. /* Okay, so this is a listener. Is it configured? */
  921. line = NULL;
  922. SMARTLIST_FOREACH(launch, config_line_t *, wanted,
  923. {
  924. char *address=NULL;
  925. uint16_t port;
  926. if (!parse_addr_port(LOG_WARN, wanted->value, &address, NULL, &port)) {
  927. int addr_matches = !strcasecmp(address, conn->address);
  928. tor_free(address);
  929. if (! port)
  930. port = port_option;
  931. if (port == conn->port && addr_matches) {
  932. line = wanted;
  933. break;
  934. }
  935. }
  936. });
  937. if (! line) {
  938. /* This one isn't configured. Close it. */
  939. log_notice(LD_NET, "Closing no-longer-configured %s on %s:%d",
  940. conn_type_to_string(type), conn->address, conn->port);
  941. if (replaced_conns) {
  942. smartlist_add(replaced_conns, conn);
  943. } else {
  944. connection_close_immediate(conn);
  945. connection_mark_for_close(conn);
  946. }
  947. } else {
  948. /* It's configured; we don't need to launch it. */
  949. // log_debug(LD_NET, "Already have %s on %s:%d",
  950. // conn_type_to_string(type), conn->address, conn->port);
  951. smartlist_remove(launch, line);
  952. if (free_launch_elts)
  953. config_free_lines(line);
  954. }
  955. }
  956. /* Now open all the listeners that are configured but not opened. */
  957. i = 0;
  958. if (!never_open_conns) {
  959. SMARTLIST_FOREACH(launch, config_line_t *, cfg,
  960. {
  961. conn = connection_create_listener(cfg->value, (uint16_t) port_option,
  962. type);
  963. if (!conn) {
  964. i = -1;
  965. } else {
  966. if (new_conns)
  967. smartlist_add(new_conns, conn);
  968. }
  969. });
  970. }
  971. if (free_launch_elts) {
  972. SMARTLIST_FOREACH(launch, config_line_t *, cfg,
  973. config_free_lines(cfg));
  974. }
  975. smartlist_free(launch);
  976. return i;
  977. }
  978. /** (Re)launch listeners for each port you should have open. If
  979. * <b>force</b> is true, close and relaunch all listeners. If <b>force</b>
  980. * is false, then only relaunch listeners when we have the wrong number of
  981. * connections for a given type.
  982. *
  983. * Add all old conns that should be closed to <b>replaced_conns</b>.
  984. * Add all new connections to <b>new_conns</b>.
  985. */
  986. int
  987. retry_all_listeners(int force, smartlist_t *replaced_conns,
  988. smartlist_t *new_conns)
  989. {
  990. or_options_t *options = get_options();
  991. if (retry_listeners(CONN_TYPE_OR_LISTENER, options->ORListenAddress,
  992. options->ORPort, "0.0.0.0", force,
  993. replaced_conns, new_conns, options->ClientOnly)<0)
  994. return -1;
  995. if (retry_listeners(CONN_TYPE_DIR_LISTENER, options->DirListenAddress,
  996. options->DirPort, "0.0.0.0", force,
  997. replaced_conns, new_conns, 0)<0)
  998. return -1;
  999. if (retry_listeners(CONN_TYPE_AP_LISTENER, options->SocksListenAddress,
  1000. options->SocksPort, "127.0.0.1", force,
  1001. replaced_conns, new_conns, 0)<0)
  1002. return -1;
  1003. if (retry_listeners(CONN_TYPE_AP_TRANS_LISTENER, options->TransListenAddress,
  1004. options->TransPort, "127.0.0.1", force,
  1005. replaced_conns, new_conns, 0)<0)
  1006. return -1;
  1007. if (retry_listeners(CONN_TYPE_AP_NATD_LISTENER, options->NatdListenAddress,
  1008. options->NatdPort, "127.0.0.1", force,
  1009. replaced_conns, new_conns, 0)<0)
  1010. return -1;
  1011. if (retry_listeners(CONN_TYPE_CONTROL_LISTENER,
  1012. options->ControlListenAddress,
  1013. options->ControlPort, "127.0.0.1", force,
  1014. replaced_conns, new_conns, 0)<0)
  1015. return -1;
  1016. return 0;
  1017. }
  1018. /** Return 1 if we should apply rate limiting to <b>conn</b>,
  1019. * and 0 otherwise. Right now this just checks if it's an internal
  1020. * IP address. */
  1021. static int
  1022. connection_is_rate_limited(connection_t *conn)
  1023. {
  1024. return !is_internal_IP(conn->addr, 0);
  1025. }
  1026. extern int global_read_bucket, global_write_bucket;
  1027. /** Did our global write bucket run dry last second? If so, we are
  1028. * likely to run dry again this second, so be stingy with the tokens
  1029. * we just put in. */
  1030. static int global_write_bucket_empty_last_second = 0;
  1031. /** Helper function to decide how many bytes out of <b>global_bucket</b>
  1032. * we're willing to use for this transaction. <b>base</b> is the size
  1033. * of a cell on the network; <b>priority</b> says whether we should
  1034. * write many of them or just a few; and <b>conn_bucket</b> (if
  1035. * non-negative) provides an upper limit for our answer. */
  1036. static int
  1037. connection_bucket_round_robin(int base, int priority,
  1038. int global_bucket, int conn_bucket)
  1039. {
  1040. int at_most;
  1041. int num_bytes_high = (priority ? 32 : 16) * base;
  1042. int num_bytes_low = (priority ? 4 : 2) * base;
  1043. /* Do a rudimentary round-robin so one circuit can't hog a connection.
  1044. * Pick at most 32 cells, at least 4 cells if possible, and if we're in
  1045. * the middle pick 1/8 of the available bandwidth. */
  1046. at_most = global_bucket / 8;
  1047. at_most -= (at_most % base); /* round down */
  1048. if (at_most > num_bytes_high) /* 16 KB, or 8 KB for low-priority */
  1049. at_most = num_bytes_high;
  1050. else if (at_most < num_bytes_low) /* 2 KB, or 1 KB for low-priority */
  1051. at_most = num_bytes_low;
  1052. if (at_most > global_bucket)
  1053. at_most = global_bucket;
  1054. if (conn_bucket >= 0 && at_most > conn_bucket)
  1055. at_most = conn_bucket;
  1056. if (at_most < 0)
  1057. return 0;
  1058. return at_most;
  1059. }
  1060. /** How many bytes at most can we read onto this connection? */
  1061. static int
  1062. connection_bucket_read_limit(connection_t *conn)
  1063. {
  1064. int base = connection_speaks_cells(conn) ?
  1065. CELL_NETWORK_SIZE : RELAY_PAYLOAD_SIZE;
  1066. int priority = conn->type != CONN_TYPE_DIR;
  1067. int conn_bucket = -1;
  1068. if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
  1069. or_connection_t *or_conn = TO_OR_CONN(conn);
  1070. conn_bucket = or_conn->read_bucket;
  1071. }
  1072. if (!connection_is_rate_limited(conn)) {
  1073. /* be willing to read on local conns even if our buckets are empty */
  1074. return conn_bucket>=0 ? conn_bucket : 1<<14;
  1075. }
  1076. return connection_bucket_round_robin(base, priority,
  1077. global_read_bucket, conn_bucket);
  1078. }
  1079. /** How many bytes at most can we write onto this connection? */
  1080. int
  1081. connection_bucket_write_limit(connection_t *conn)
  1082. {
  1083. int base = connection_speaks_cells(conn) ?
  1084. CELL_NETWORK_SIZE : RELAY_PAYLOAD_SIZE;
  1085. int priority = conn->type != CONN_TYPE_DIR;
  1086. if (!connection_is_rate_limited(conn)) {
  1087. /* be willing to write to local conns even if our buckets are empty */
  1088. return conn->outbuf_flushlen;
  1089. }
  1090. return connection_bucket_round_robin(base, priority, global_write_bucket,
  1091. conn->outbuf_flushlen);
  1092. }
  1093. /** Return 1 if the global write bucket is low enough that we shouldn't
  1094. * send <b>attempt</b> bytes of low-priority directory stuff out to
  1095. * <b>conn</b>. Else return 0.
  1096. * Priority is 1 for v1 requests (directories and running-routers),
  1097. * and 2 for v2 requests (statuses and descriptors). But see FFFF in
  1098. * directory_handle_command_get() for why we don't use priority 2 yet.
  1099. *
  1100. * There are a lot of parameters we could use here:
  1101. * - global_write_bucket. Low is bad.
  1102. * - bandwidthrate. Low is bad.
  1103. * - bandwidthburst. Not a big factor?
  1104. * - attempt. High is bad.
  1105. * - total bytes queued on outbufs. High is bad. But I'm wary of
  1106. * using this, since a few slow-flushing queues will pump up the
  1107. * number without meaning what we meant to mean. What we really
  1108. * mean is "total directory bytes added to outbufs recently", but
  1109. * that's harder to quantify and harder to keep track of.
  1110. */
  1111. int
  1112. global_write_bucket_low(connection_t *conn, size_t attempt, int priority)
  1113. {
  1114. if (authdir_mode(get_options()) && priority>1)
  1115. return 0; /* there's always room to answer v2 if we're an auth dir */
  1116. if (!connection_is_rate_limited(conn))
  1117. return 0; /* local conns don't get limited */
  1118. if (global_write_bucket < (int)attempt)
  1119. return 1; /* not enough space no matter the priority */
  1120. if (global_write_bucket_empty_last_second)
  1121. return 1; /* we're already hitting our limits, no more please */
  1122. if (priority == 1) { /* old-style v1 query */
  1123. /* Could we handle *two* of these requests within the next two seconds? */
  1124. int64_t can_write = (int64_t)global_write_bucket
  1125. + 2*get_options()->BandwidthRate;
  1126. if (can_write < 2*(int64_t)attempt)
  1127. return 1;
  1128. } else { /* v2 query */
  1129. /* no further constraints yet */
  1130. }
  1131. return 0;
  1132. }
  1133. /** We just read num_read onto conn. Decrement buckets appropriately. */
  1134. static void
  1135. connection_read_bucket_decrement(connection_t *conn, int num_read)
  1136. {
  1137. global_read_bucket -= num_read;
  1138. if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
  1139. TO_OR_CONN(conn)->read_bucket -= num_read;
  1140. }
  1141. }
  1142. /** If we have exhausted our global buckets, or the buckets for conn,
  1143. * stop reading. */
  1144. static void
  1145. connection_consider_empty_read_buckets(connection_t *conn)
  1146. {
  1147. if (global_read_bucket <= 0) {
  1148. LOG_FN_CONN(conn, (LOG_DEBUG,LD_NET,
  1149. "global read bucket exhausted. Pausing."));
  1150. conn->wants_to_read = 1;
  1151. connection_stop_reading(conn);
  1152. return;
  1153. }
  1154. if (connection_speaks_cells(conn) &&
  1155. conn->state == OR_CONN_STATE_OPEN &&
  1156. TO_OR_CONN(conn)->read_bucket <= 0) {
  1157. LOG_FN_CONN(conn,
  1158. (LOG_DEBUG,LD_NET,"read bucket exhausted. Pausing."));
  1159. conn->wants_to_read = 1;
  1160. connection_stop_reading(conn);
  1161. }
  1162. }
  1163. /** If we have exhausted our global buckets, or the buckets for conn,
  1164. * stop writing. */
  1165. static void
  1166. connection_consider_empty_write_buckets(connection_t *conn)
  1167. {
  1168. if (global_write_bucket <= 0) {
  1169. LOG_FN_CONN(conn, (LOG_DEBUG,LD_NET,
  1170. "global write bucket exhausted. Pausing."));
  1171. conn->wants_to_write = 1;
  1172. connection_stop_writing(conn);
  1173. return;
  1174. }
  1175. #if 0
  1176. if (connection_speaks_cells(conn) &&
  1177. conn->state == OR_CONN_STATE_OPEN &&
  1178. TO_OR_CONN(conn)->write_bucket <= 0) {
  1179. LOG_FN_CONN(conn,
  1180. (LOG_DEBUG,LD_NET,"write bucket exhausted. Pausing."));
  1181. conn->wants_to_write = 1;
  1182. connection_stop_writing(conn);
  1183. }
  1184. #endif
  1185. }
  1186. /** Initialize the global read bucket to options->BandwidthBurst. */
  1187. void
  1188. connection_bucket_init(void)
  1189. {
  1190. or_options_t *options = get_options();
  1191. /* start it at max traffic */
  1192. global_read_bucket = (int)options->BandwidthBurst;
  1193. global_write_bucket = (int)options->BandwidthBurst;
  1194. }
  1195. /** A second has rolled over; increment buckets appropriately. */
  1196. void
  1197. connection_bucket_refill(int seconds_elapsed)
  1198. {
  1199. int i, n;
  1200. connection_t *conn;
  1201. connection_t **carray;
  1202. or_options_t *options = get_options();
  1203. tor_assert(seconds_elapsed >= 0);
  1204. /* refill the global buckets */
  1205. if (global_read_bucket < (int)options->BandwidthBurst) {
  1206. global_read_bucket += (int)options->BandwidthRate*seconds_elapsed;
  1207. if (global_read_bucket > (int)options->BandwidthBurst)
  1208. global_read_bucket = (int)options->BandwidthBurst;
  1209. log(LOG_DEBUG, LD_NET,"global_read_bucket now %d.", global_read_bucket);
  1210. }
  1211. if (global_write_bucket < (int)options->BandwidthBurst) {
  1212. global_write_bucket_empty_last_second = global_write_bucket == 0;
  1213. global_write_bucket += (int)options->BandwidthRate*seconds_elapsed;
  1214. if (global_write_bucket > (int)options->BandwidthBurst)
  1215. global_write_bucket = (int)options->BandwidthBurst;
  1216. log(LOG_DEBUG, LD_NET,"global_write_bucket now %d.", global_write_bucket);
  1217. }
  1218. /* refill the per-connection buckets */
  1219. get_connection_array(&carray,&n);
  1220. for (i=0;i<n;i++) {
  1221. conn = carray[i];
  1222. if (connection_speaks_cells(conn)) {
  1223. or_connection_t *or_conn = TO_OR_CONN(conn);
  1224. if (connection_read_bucket_should_increase(or_conn)) {
  1225. or_conn->read_bucket += or_conn->bandwidthrate*seconds_elapsed;
  1226. if (or_conn->read_bucket > or_conn->bandwidthburst)
  1227. or_conn->read_bucket = or_conn->bandwidthburst;
  1228. //log_fn(LOG_DEBUG,"Receiver bucket %d now %d.", i,
  1229. // conn->read_bucket);
  1230. }
  1231. }
  1232. if (conn->wants_to_read == 1 /* it's marked to turn reading back on now */
  1233. && global_read_bucket > 0 /* and we're allowed to read */
  1234. && (!connection_speaks_cells(conn) ||
  1235. conn->state != OR_CONN_STATE_OPEN ||
  1236. TO_OR_CONN(conn)->read_bucket > 0)) {
  1237. /* and either a non-cell conn or a cell conn with non-empty bucket */
  1238. LOG_FN_CONN(conn, (LOG_DEBUG,LD_NET,
  1239. "waking up conn (fd %d) for read",conn->s));
  1240. conn->wants_to_read = 0;
  1241. connection_start_reading(conn);
  1242. }
  1243. if (conn->wants_to_write == 1 &&
  1244. global_write_bucket > 0) { /* and we're allowed to write */
  1245. LOG_FN_CONN(conn, (LOG_DEBUG,LD_NET,
  1246. "waking up conn (fd %d) for write",conn->s));
  1247. conn->wants_to_write = 0;
  1248. connection_start_writing(conn);
  1249. }
  1250. }
  1251. }
  1252. /** Is the receiver bucket for connection <b>conn</b> low enough that we
  1253. * should add another pile of tokens to it?
  1254. */
  1255. static int
  1256. connection_read_bucket_should_increase(or_connection_t *conn)
  1257. {
  1258. tor_assert(conn);
  1259. if (conn->_base.state != OR_CONN_STATE_OPEN)
  1260. return 0; /* only open connections play the rate limiting game */
  1261. if (conn->read_bucket >= conn->bandwidthburst)
  1262. return 0;
  1263. return 1;
  1264. }
  1265. /** Read bytes from conn-\>s and process them.
  1266. *
  1267. * This function gets called from conn_read() in main.c, either
  1268. * when poll() has declared that conn wants to read, or (for OR conns)
  1269. * when there are pending TLS bytes.
  1270. *
  1271. * It calls connection_read_to_buf() to bring in any new bytes,
  1272. * and then calls connection_process_inbuf() to process them.
  1273. *
  1274. * Mark the connection and return -1 if you want to close it, else
  1275. * return 0.
  1276. */
  1277. int
  1278. connection_handle_read(connection_t *conn)
  1279. {
  1280. int max_to_read=-1, try_to_read;
  1281. if (conn->marked_for_close)
  1282. return 0; /* do nothing */
  1283. conn->timestamp_lastread = time(NULL);
  1284. switch (conn->type) {
  1285. case CONN_TYPE_OR_LISTENER:
  1286. return connection_handle_listener_read(conn, CONN_TYPE_OR);
  1287. case CONN_TYPE_AP_LISTENER:
  1288. case CONN_TYPE_AP_TRANS_LISTENER:
  1289. case CONN_TYPE_AP_NATD_LISTENER:
  1290. return connection_handle_listener_read(conn, CONN_TYPE_AP);
  1291. case CONN_TYPE_DIR_LISTENER:
  1292. return connection_handle_listener_read(conn, CONN_TYPE_DIR);
  1293. case CONN_TYPE_CONTROL_LISTENER:
  1294. return connection_handle_listener_read(conn, CONN_TYPE_CONTROL);
  1295. }
  1296. loop_again:
  1297. try_to_read = max_to_read;
  1298. tor_assert(!conn->marked_for_close);
  1299. if (connection_read_to_buf(conn, &max_to_read) < 0) {
  1300. /* There's a read error; kill the connection.*/
  1301. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  1302. if (CONN_IS_EDGE(conn)) {
  1303. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  1304. connection_edge_end_errno(edge_conn, edge_conn->cpath_layer);
  1305. if (edge_conn->socks_request) /* broken, don't send a socks reply back */
  1306. edge_conn->socks_request->has_finished = 1;
  1307. }
  1308. connection_mark_for_close(conn);
  1309. return -1;
  1310. }
  1311. if (CONN_IS_EDGE(conn) && try_to_read != max_to_read) {
  1312. /* instruct it not to try to package partial cells. */
  1313. if (connection_process_inbuf(conn, 0) < 0) {
  1314. return -1;
  1315. }
  1316. if (!conn->marked_for_close &&
  1317. connection_is_reading(conn) &&
  1318. !conn->inbuf_reached_eof &&
  1319. max_to_read > 0)
  1320. goto loop_again; /* try reading again, in case more is here now */
  1321. }
  1322. /* one last try, packaging partial cells and all. */
  1323. if (!conn->marked_for_close &&
  1324. connection_process_inbuf(conn, 1) < 0) {
  1325. return -1;
  1326. }
  1327. if (!conn->marked_for_close &&
  1328. conn->inbuf_reached_eof &&
  1329. connection_reached_eof(conn) < 0) {
  1330. return -1;
  1331. }
  1332. return 0;
  1333. }
  1334. /** Pull in new bytes from conn-\>s onto conn-\>inbuf, either
  1335. * directly or via TLS. Reduce the token buckets by the number of
  1336. * bytes read.
  1337. *
  1338. * If *max_to_read is -1, then decide it ourselves, else go with the
  1339. * value passed to us. When returning, if it's changed, subtract the
  1340. * number of bytes we read from *max_to_read.
  1341. *
  1342. * Return -1 if we want to break conn, else return 0.
  1343. */
  1344. static int
  1345. connection_read_to_buf(connection_t *conn, int *max_to_read)
  1346. {
  1347. int result, at_most = *max_to_read;
  1348. size_t bytes_in_buf, more_to_read;
  1349. size_t n_read = 0, n_written = 0;
  1350. if (at_most == -1) { /* we need to initialize it */
  1351. /* how many bytes are we allowed to read? */
  1352. at_most = connection_bucket_read_limit(conn);
  1353. }
  1354. bytes_in_buf = buf_capacity(conn->inbuf) - buf_datalen(conn->inbuf);
  1355. again:
  1356. if ((size_t)at_most > bytes_in_buf && bytes_in_buf >= 1024) {
  1357. more_to_read = at_most - bytes_in_buf;
  1358. at_most = bytes_in_buf;
  1359. } else {
  1360. more_to_read = 0;
  1361. }
  1362. if (connection_speaks_cells(conn) &&
  1363. conn->state > OR_CONN_STATE_PROXY_READING) {
  1364. int pending;
  1365. or_connection_t *or_conn = TO_OR_CONN(conn);
  1366. if (conn->state == OR_CONN_STATE_HANDSHAKING) {
  1367. /* continue handshaking even if global token bucket is empty */
  1368. return connection_tls_continue_handshake(or_conn);
  1369. }
  1370. log_debug(LD_NET,
  1371. "%d: starting, inbuf_datalen %d (%d pending in tls object)."
  1372. " at_most %d.",
  1373. conn->s,(int)buf_datalen(conn->inbuf),
  1374. tor_tls_get_pending_bytes(or_conn->tls), at_most);
  1375. /* else open, or closing */
  1376. result = read_to_buf_tls(or_conn->tls, at_most, conn->inbuf);
  1377. if (TOR_TLS_IS_ERROR(result) || result == TOR_TLS_CLOSE)
  1378. or_conn->tls_error = result;
  1379. else
  1380. or_conn->tls_error = 0;
  1381. switch (result) {
  1382. case TOR_TLS_CLOSE:
  1383. log_info(LD_NET,"TLS connection closed on read. Closing. "
  1384. "(Nickname %s, address %s",
  1385. or_conn->nickname ? or_conn->nickname : "not set",
  1386. conn->address);
  1387. return result;
  1388. CASE_TOR_TLS_ERROR_ANY:
  1389. log_info(LD_NET,"tls error. breaking (nickname %s, address %s).",
  1390. or_conn->nickname ? or_conn->nickname : "not set",
  1391. conn->address);
  1392. return result;
  1393. case TOR_TLS_WANTWRITE:
  1394. connection_start_writing(conn);
  1395. return 0;
  1396. case TOR_TLS_WANTREAD: /* we're already reading */
  1397. case TOR_TLS_DONE: /* no data read, so nothing to process */
  1398. result = 0;
  1399. break; /* so we call bucket_decrement below */
  1400. default:
  1401. break;
  1402. }
  1403. pending = tor_tls_get_pending_bytes(or_conn->tls);
  1404. if (pending) {
  1405. /* If we have any pending bytes, we read them now. This *can*
  1406. * take us over our read allotment, but really we shouldn't be
  1407. * believing that SSL bytes are the same as TCP bytes anyway. */
  1408. int r2 = read_to_buf_tls(or_conn->tls, pending, conn->inbuf);
  1409. if (r2<0) {
  1410. log_warn(LD_BUG, "Bug: apparently, reading pending bytes can fail.");
  1411. return -1;
  1412. } else {
  1413. result += r2;
  1414. }
  1415. }
  1416. tor_tls_get_n_raw_bytes(or_conn->tls, &n_read, &n_written);
  1417. log_debug(LD_GENERAL, "After TLS read of %d: %ld read, %ld written",
  1418. result, (long)n_read, (long)n_written);
  1419. } else {
  1420. int reached_eof = 0;
  1421. CONN_LOG_PROTECT(conn,
  1422. result = read_to_buf(conn->s, at_most, conn->inbuf, &reached_eof));
  1423. if (reached_eof)
  1424. conn->inbuf_reached_eof = 1;
  1425. // log_fn(LOG_DEBUG,"read_to_buf returned %d.",read_result);
  1426. if (result < 0)
  1427. return -1;
  1428. n_read = (size_t) result;
  1429. }
  1430. if (n_read > 0) { /* change *max_to_read */
  1431. *max_to_read = at_most - n_read;
  1432. }
  1433. if (CONN_IS_EDGE(conn)) {
  1434. if (conn->type == CONN_TYPE_AP) {
  1435. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  1436. edge_conn->n_read += n_read;
  1437. }
  1438. }
  1439. if (connection_is_rate_limited(conn)) {
  1440. /* For non-local IPs, remember if we flushed any bytes over the wire. */
  1441. time_t now = time(NULL);
  1442. if (n_read > 0) {
  1443. rep_hist_note_bytes_read(n_read, now);
  1444. connection_read_bucket_decrement(conn, n_read);
  1445. }
  1446. if (n_written > 0) {
  1447. rep_hist_note_bytes_written(n_written, now);
  1448. global_write_bucket -= n_written;
  1449. }
  1450. }
  1451. if (more_to_read && result == at_most) {
  1452. bytes_in_buf = buf_capacity(conn->inbuf) - buf_datalen(conn->inbuf);
  1453. tor_assert(bytes_in_buf < 1024);
  1454. at_most = more_to_read;
  1455. goto again;
  1456. }
  1457. /* Call even if result is 0, since the global read bucket may
  1458. * have reached 0 on a different conn, and this guy needs to
  1459. * know to stop reading. */
  1460. connection_consider_empty_read_buckets(conn);
  1461. if (n_written > 0 && connection_is_writing(conn))
  1462. connection_consider_empty_write_buckets(conn);
  1463. return 0;
  1464. }
  1465. /** A pass-through to fetch_from_buf. */
  1466. int
  1467. connection_fetch_from_buf(char *string, size_t len, connection_t *conn)
  1468. {
  1469. return fetch_from_buf(string, len, conn->inbuf);
  1470. }
  1471. /** Return conn-\>outbuf_flushlen: how many bytes conn wants to flush
  1472. * from its outbuf. */
  1473. int
  1474. connection_wants_to_flush(connection_t *conn)
  1475. {
  1476. return conn->outbuf_flushlen;
  1477. }
  1478. /** Are there too many bytes on edge connection <b>conn</b>'s outbuf to
  1479. * send back a relay-level sendme yet? Return 1 if so, 0 if not. Used by
  1480. * connection_edge_consider_sending_sendme().
  1481. */
  1482. int
  1483. connection_outbuf_too_full(connection_t *conn)
  1484. {
  1485. return (conn->outbuf_flushlen > 10*CELL_PAYLOAD_SIZE);
  1486. }
  1487. /** Try to flush more bytes onto conn-\>s.
  1488. *
  1489. * This function gets called either from conn_write() in main.c
  1490. * when poll() has declared that conn wants to write, or below
  1491. * from connection_write_to_buf() when an entire TLS record is ready.
  1492. *
  1493. * Update conn-\>timestamp_lastwritten to now, and call flush_buf
  1494. * or flush_buf_tls appropriately. If it succeeds and there are no more
  1495. * more bytes on conn->outbuf, then call connection_finished_flushing
  1496. * on it too.
  1497. *
  1498. * If <b>force</b>, then write as many bytes as possible, ignoring bandwidth
  1499. * limits. (Used for flushing messages to controller connections on fatal
  1500. * errors.)
  1501. *
  1502. * Mark the connection and return -1 if you want to close it, else
  1503. * return 0.
  1504. */
  1505. int
  1506. connection_handle_write(connection_t *conn, int force)
  1507. {
  1508. int e;
  1509. socklen_t len=sizeof(e);
  1510. int result;
  1511. int max_to_write;
  1512. time_t now = time(NULL);
  1513. size_t n_read = 0, n_written = 0;
  1514. tor_assert(!connection_is_listener(conn));
  1515. if (conn->marked_for_close || conn->s < 0)
  1516. return 0; /* do nothing */
  1517. conn->timestamp_lastwritten = now;
  1518. /* Sometimes, "writable" means "connected". */
  1519. if (connection_state_is_connecting(conn)) {
  1520. if (getsockopt(conn->s, SOL_SOCKET, SO_ERROR, (void*)&e, &len) < 0) {
  1521. log_warn(LD_BUG,
  1522. "getsockopt() syscall failed?! Please report to tor-ops.");
  1523. if (CONN_IS_EDGE(conn))
  1524. connection_edge_end_errno(TO_EDGE_CONN(conn),
  1525. TO_EDGE_CONN(conn)->cpath_layer);
  1526. connection_mark_for_close(conn);
  1527. return -1;
  1528. }
  1529. if (e) {
  1530. /* some sort of error, but maybe just inprogress still */
  1531. if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
  1532. log_info(LD_NET,"in-progress connect failed. Removing.");
  1533. if (CONN_IS_EDGE(conn))
  1534. connection_edge_end_errno(TO_EDGE_CONN(conn),
  1535. TO_EDGE_CONN(conn)->cpath_layer);
  1536. connection_close_immediate(conn);
  1537. connection_mark_for_close(conn);
  1538. /* it's safe to pass OPs to router_set_status(), since it just
  1539. * ignores unrecognized routers
  1540. */
  1541. if (conn->type == CONN_TYPE_OR && !get_options()->HttpsProxy)
  1542. router_set_status(TO_OR_CONN(conn)->identity_digest, 0);
  1543. return -1;
  1544. } else {
  1545. return 0; /* no change, see if next time is better */
  1546. }
  1547. }
  1548. /* The connection is successful. */
  1549. if (connection_finished_connecting(conn)<0)
  1550. return -1;
  1551. }
  1552. max_to_write = force ? (int)conn->outbuf_flushlen
  1553. : connection_bucket_write_limit(conn);
  1554. if (connection_speaks_cells(conn) &&
  1555. conn->state > OR_CONN_STATE_PROXY_READING) {
  1556. or_connection_t *or_conn = TO_OR_CONN(conn);
  1557. if (conn->state == OR_CONN_STATE_HANDSHAKING) {
  1558. connection_stop_writing(conn);
  1559. if (connection_tls_continue_handshake(or_conn) < 0) {
  1560. /* Don't flush; connection is dead. */
  1561. connection_close_immediate(conn);
  1562. connection_mark_for_close(conn);
  1563. return -1;
  1564. }
  1565. return 0;
  1566. }
  1567. /* else open, or closing */
  1568. result = flush_buf_tls(or_conn->tls, conn->outbuf,
  1569. max_to_write, &conn->outbuf_flushlen);
  1570. switch (result) {
  1571. CASE_TOR_TLS_ERROR_ANY:
  1572. case TOR_TLS_CLOSE:
  1573. log_info(LD_NET,result!=TOR_TLS_CLOSE?
  1574. "tls error. breaking.":"TLS connection closed on flush");
  1575. /* Don't flush; connection is dead. */
  1576. connection_close_immediate(conn);
  1577. connection_mark_for_close(conn);
  1578. return -1;
  1579. case TOR_TLS_WANTWRITE:
  1580. log_debug(LD_NET,"wanted write.");
  1581. /* we're already writing */
  1582. return 0;
  1583. case TOR_TLS_WANTREAD:
  1584. /* Make sure to avoid a loop if the receive buckets are empty. */
  1585. log_debug(LD_NET,"wanted read.");
  1586. if (!connection_is_reading(conn)) {
  1587. connection_stop_writing(conn);
  1588. conn->wants_to_write = 1;
  1589. /* we'll start reading again when the next second arrives,
  1590. * and then also start writing again.
  1591. */
  1592. }
  1593. /* else no problem, we're already reading */
  1594. return 0;
  1595. /* case TOR_TLS_DONE:
  1596. * for TOR_TLS_DONE, fall through to check if the flushlen
  1597. * is empty, so we can stop writing.
  1598. */
  1599. }
  1600. tor_tls_get_n_raw_bytes(or_conn->tls, &n_read, &n_written);
  1601. log_debug(LD_GENERAL, "After TLS write of %d: %ld read, %ld written",
  1602. result, (long)n_read, (long)n_written);
  1603. } else {
  1604. CONN_LOG_PROTECT(conn,
  1605. result = flush_buf(conn->s, conn->outbuf,
  1606. max_to_write, &conn->outbuf_flushlen));
  1607. if (result < 0) {
  1608. if (CONN_IS_EDGE(conn))
  1609. connection_edge_end_errno(TO_EDGE_CONN(conn),
  1610. TO_EDGE_CONN(conn)->cpath_layer);
  1611. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  1612. connection_mark_for_close(conn);
  1613. return -1;
  1614. }
  1615. n_written = (size_t) result;
  1616. }
  1617. if (CONN_IS_EDGE(conn)) {
  1618. if (conn->type == CONN_TYPE_AP) {
  1619. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  1620. edge_conn->n_written += n_written;
  1621. }
  1622. }
  1623. if (connection_is_rate_limited(conn)) {
  1624. /* For non-local IPs, remember if we flushed any bytes over the wire. */
  1625. time_t now = time(NULL);
  1626. if (n_written > 0) {
  1627. rep_hist_note_bytes_written(n_written, now);
  1628. global_write_bucket -= n_written;
  1629. }
  1630. if (n_read > 0) {
  1631. rep_hist_note_bytes_read(n_read, now);
  1632. connection_read_bucket_decrement(conn, n_read);
  1633. }
  1634. }
  1635. if (result > 0) {
  1636. /* If we wrote any bytes from our buffer, then call the appropriate
  1637. * functions. */
  1638. if (connection_flushed_some(conn) < 0)
  1639. connection_mark_for_close(conn);
  1640. }
  1641. if (!connection_wants_to_flush(conn)) { /* it's done flushing */
  1642. if (connection_finished_flushing(conn) < 0) {
  1643. /* already marked */
  1644. return -1;
  1645. }
  1646. return 0;
  1647. }
  1648. /* Call even if result is 0, since the global write bucket may
  1649. * have reached 0 on a different conn, and this guy needs to
  1650. * know to stop writing. */
  1651. connection_consider_empty_write_buckets(conn);
  1652. if (n_read > 0 && connection_is_reading(conn))
  1653. connection_consider_empty_read_buckets(conn);
  1654. return 0;
  1655. }
  1656. /** Openssl TLS record size is 16383; this is close. The goal here is to
  1657. * push data out as soon as we know there's enough for a TLS record, so
  1658. * during periods of high load we won't read entire megabytes from
  1659. * input before pushing any data out. It also has the feature of not
  1660. * growing huge outbufs unless something is slow. */
  1661. #define MIN_TLS_FLUSHLEN 15872
  1662. /** Append <b>len</b> bytes of <b>string</b> onto <b>conn</b>'s
  1663. * outbuf, and ask it to start writing.
  1664. *
  1665. * If <b>zlib</b> is nonzero, this is a directory connection that should get
  1666. * its contents compressed or decompressed as they're written. If zlib is
  1667. * negative, this is the last data to be compressed, and the connection's zlib
  1668. * state should be flushed.
  1669. *
  1670. * If it's an OR conn and an entire TLS record is ready, then try to
  1671. * flush the record now. Similarly, if it's a local control connection
  1672. * and a 64k chunk is ready, try to flush it all, so we don't end up with
  1673. * many megabytes of controller info queued at once.
  1674. */
  1675. void
  1676. _connection_write_to_buf_impl(const char *string, size_t len,
  1677. connection_t *conn, int zlib)
  1678. {
  1679. int r;
  1680. size_t old_datalen;
  1681. if (!len)
  1682. return;
  1683. /* if it's marked for close, only allow write if we mean to flush it */
  1684. if (conn->marked_for_close && !conn->hold_open_until_flushed)
  1685. return;
  1686. old_datalen = buf_datalen(conn->outbuf);
  1687. if (zlib) {
  1688. dir_connection_t *dir_conn = TO_DIR_CONN(conn);
  1689. int done = zlib < 0;
  1690. CONN_LOG_PROTECT(conn, r = write_to_buf_zlib(conn->outbuf,
  1691. dir_conn->zlib_state,
  1692. string, len, done));
  1693. } else {
  1694. CONN_LOG_PROTECT(conn, r = write_to_buf(string, len, conn->outbuf));
  1695. }
  1696. if (r < 0) {
  1697. if (CONN_IS_EDGE(conn)) {
  1698. /* if it failed, it means we have our package/delivery windows set
  1699. wrong compared to our max outbuf size. close the whole circuit. */
  1700. log_warn(LD_NET,
  1701. "write_to_buf failed. Closing circuit (fd %d).", conn->s);
  1702. circuit_mark_for_close(circuit_get_by_edge_conn(TO_EDGE_CONN(conn)),
  1703. END_CIRC_REASON_INTERNAL);
  1704. } else {
  1705. log_warn(LD_NET,
  1706. "write_to_buf failed. Closing connection (fd %d).", conn->s);
  1707. connection_mark_for_close(conn);
  1708. }
  1709. return;
  1710. }
  1711. connection_start_writing(conn);
  1712. if (zlib) {
  1713. conn->outbuf_flushlen += buf_datalen(conn->outbuf) - old_datalen;
  1714. } else {
  1715. int extra = 0;
  1716. conn->outbuf_flushlen += len;
  1717. if (conn->type == CONN_TYPE_OR &&
  1718. conn->outbuf_flushlen-len < MIN_TLS_FLUSHLEN &&
  1719. conn->outbuf_flushlen >= MIN_TLS_FLUSHLEN) {
  1720. extra = conn->outbuf_flushlen - MIN_TLS_FLUSHLEN;
  1721. conn->outbuf_flushlen = MIN_TLS_FLUSHLEN;
  1722. } else if (conn->type == CONN_TYPE_CONTROL &&
  1723. !connection_is_rate_limited(conn) &&
  1724. conn->outbuf_flushlen-len < 1<<16 &&
  1725. conn->outbuf_flushlen >= 1<<16) {
  1726. /* just try to flush all of it */
  1727. } else
  1728. return; /* no need to try flushing */
  1729. if (connection_handle_write(conn, 0) < 0) {
  1730. if (!conn->marked_for_close) {
  1731. /* this connection is broken. remove it. */
  1732. log_warn(LD_BUG, "Bug: unhandled error on write for "
  1733. "conn (type %d, fd %d); removing",
  1734. conn->type, conn->s);
  1735. tor_fragile_assert();
  1736. /* do a close-immediate here, so we don't try to flush */
  1737. connection_close_immediate(conn);
  1738. }
  1739. return;
  1740. }
  1741. if (extra) {
  1742. conn->outbuf_flushlen += extra;
  1743. connection_start_writing(conn);
  1744. }
  1745. }
  1746. }
  1747. /** Return the conn to addr/port that has the most recent
  1748. * timestamp_created, or NULL if no such conn exists. */
  1749. or_connection_t *
  1750. connection_or_exact_get_by_addr_port(uint32_t addr, uint16_t port)
  1751. {
  1752. int i, n;
  1753. connection_t *conn;
  1754. or_connection_t *best=NULL;
  1755. connection_t **carray;
  1756. get_connection_array(&carray,&n);
  1757. for (i=0;i<n;i++) {
  1758. conn = carray[i];
  1759. if (conn->type == CONN_TYPE_OR &&
  1760. conn->addr == addr &&
  1761. conn->port == port &&
  1762. !conn->marked_for_close &&
  1763. (!best || best->_base.timestamp_created < conn->timestamp_created))
  1764. best = TO_OR_CONN(conn);
  1765. }
  1766. return best;
  1767. }
  1768. /** Return a connection with given type, address, port, and purpose;
  1769. * or NULL if no such connection exists. */
  1770. connection_t *
  1771. connection_get_by_type_addr_port_purpose(int type,
  1772. uint32_t addr, uint16_t port,
  1773. int purpose)
  1774. {
  1775. int i, n;
  1776. connection_t *conn;
  1777. connection_t **carray;
  1778. get_connection_array(&carray,&n);
  1779. for (i=0;i<n;i++) {
  1780. conn = carray[i];
  1781. if (conn->type == type &&
  1782. conn->addr == addr &&
  1783. conn->port == port &&
  1784. conn->purpose == purpose &&
  1785. !conn->marked_for_close)
  1786. return conn;
  1787. }
  1788. return NULL;
  1789. }
  1790. /** Return the stream with id <b>id</b> if it is not already marked for
  1791. * close.
  1792. */
  1793. edge_connection_t *
  1794. connection_get_by_global_id(uint32_t id)
  1795. {
  1796. int i, n;
  1797. connection_t *conn;
  1798. connection_t **carray;
  1799. get_connection_array(&carray,&n);
  1800. for (i=0;i<n;i++) {
  1801. conn = carray[i];
  1802. if (CONN_IS_EDGE(conn) && TO_EDGE_CONN(conn)->global_identifier == id) {
  1803. if (!conn->marked_for_close)
  1804. return TO_EDGE_CONN(conn);
  1805. else
  1806. return NULL;
  1807. }
  1808. }
  1809. return NULL;
  1810. }
  1811. /** Return a connection of type <b>type</b> that is not marked for close.
  1812. */
  1813. connection_t *
  1814. connection_get_by_type(int type)
  1815. {
  1816. int i, n;
  1817. connection_t *conn;
  1818. connection_t **carray;
  1819. get_connection_array(&carray,&n);
  1820. for (i=0;i<n;i++) {
  1821. conn = carray[i];
  1822. if (conn->type == type && !conn->marked_for_close)
  1823. return conn;
  1824. }
  1825. return NULL;
  1826. }
  1827. /** Return a connection of type <b>type</b> that is in state <b>state</b>,
  1828. * and that is not marked for close.
  1829. */
  1830. connection_t *
  1831. connection_get_by_type_state(int type, int state)
  1832. {
  1833. int i, n;
  1834. connection_t *conn;
  1835. connection_t **carray;
  1836. get_connection_array(&carray,&n);
  1837. for (i=0;i<n;i++) {
  1838. conn = carray[i];
  1839. if (conn->type == type && conn->state == state && !conn->marked_for_close)
  1840. return conn;
  1841. }
  1842. return NULL;
  1843. }
  1844. /** Return the connection of type <b>type</b> that is in state
  1845. * <b>state</b>, that was written to least recently, and that is not
  1846. * marked for close.
  1847. */
  1848. connection_t *
  1849. connection_get_by_type_state_lastwritten(int type, int state)
  1850. {
  1851. int i, n;
  1852. connection_t *conn, *best=NULL;
  1853. connection_t **carray;
  1854. get_connection_array(&carray,&n);
  1855. for (i=0;i<n;i++) {
  1856. conn = carray[i];
  1857. if (conn->type == type && conn->state == state && !conn->marked_for_close)
  1858. if (!best || conn->timestamp_lastwritten < best->timestamp_lastwritten)
  1859. best = conn;
  1860. }
  1861. return best;
  1862. }
  1863. /** Return a connection of type <b>type</b> that has rendquery equal
  1864. * to <b>rendquery</b>, and that is not marked for close. If state
  1865. * is non-zero, conn must be of that state too.
  1866. */
  1867. connection_t *
  1868. connection_get_by_type_state_rendquery(int type, int state,
  1869. const char *rendquery)
  1870. {
  1871. int i, n;
  1872. connection_t *conn;
  1873. connection_t **carray;
  1874. tor_assert(type == CONN_TYPE_DIR ||
  1875. type == CONN_TYPE_AP || type == CONN_TYPE_EXIT);
  1876. get_connection_array(&carray,&n);
  1877. for (i=0;i<n;i++) {
  1878. conn = carray[i];
  1879. if (conn->type == type &&
  1880. !conn->marked_for_close &&
  1881. (!state || state == conn->state)) {
  1882. if (type == CONN_TYPE_DIR &&
  1883. rend_cmp_service_ids(rendquery, TO_DIR_CONN(conn)->rend_query))
  1884. return conn;
  1885. else if (CONN_IS_EDGE(conn) &&
  1886. rend_cmp_service_ids(rendquery, TO_EDGE_CONN(conn)->rend_query))
  1887. return conn;
  1888. }
  1889. }
  1890. return NULL;
  1891. }
  1892. /** Return an open, non-marked connection of a given type and purpose, or NULL
  1893. * if no such connection exists. */
  1894. connection_t *
  1895. connection_get_by_type_purpose(int type, int purpose)
  1896. {
  1897. int i, n;
  1898. connection_t *conn;
  1899. connection_t **carray;
  1900. get_connection_array(&carray,&n);
  1901. for (i=0;i<n;i++) {
  1902. conn = carray[i];
  1903. if (conn->type == type &&
  1904. !conn->marked_for_close &&
  1905. (purpose == conn->purpose))
  1906. return conn;
  1907. }
  1908. return NULL;
  1909. }
  1910. /** Return 1 if <b>conn</b> is a listener conn, else return 0. */
  1911. int
  1912. connection_is_listener(connection_t *conn)
  1913. {
  1914. if (conn->type == CONN_TYPE_OR_LISTENER ||
  1915. conn->type == CONN_TYPE_AP_LISTENER ||
  1916. conn->type == CONN_TYPE_AP_TRANS_LISTENER ||
  1917. conn->type == CONN_TYPE_AP_NATD_LISTENER ||
  1918. conn->type == CONN_TYPE_DIR_LISTENER ||
  1919. conn->type == CONN_TYPE_CONTROL_LISTENER)
  1920. return 1;
  1921. return 0;
  1922. }
  1923. /** Return 1 if <b>conn</b> is in state "open" and is not marked
  1924. * for close, else return 0.
  1925. */
  1926. int
  1927. connection_state_is_open(connection_t *conn)
  1928. {
  1929. tor_assert(conn);
  1930. if (conn->marked_for_close)
  1931. return 0;
  1932. if ((conn->type == CONN_TYPE_OR && conn->state == OR_CONN_STATE_OPEN) ||
  1933. (conn->type == CONN_TYPE_AP && conn->state == AP_CONN_STATE_OPEN) ||
  1934. (conn->type == CONN_TYPE_EXIT && conn->state == EXIT_CONN_STATE_OPEN) ||
  1935. (conn->type == CONN_TYPE_CONTROL &&
  1936. (conn->state == CONTROL_CONN_STATE_OPEN_V0 ||
  1937. conn->state == CONTROL_CONN_STATE_OPEN_V1)))
  1938. return 1;
  1939. return 0;
  1940. }
  1941. /** Return 1 if conn is in 'connecting' state, else return 0. */
  1942. int
  1943. connection_state_is_connecting(connection_t *conn)
  1944. {
  1945. tor_assert(conn);
  1946. if (conn->marked_for_close)
  1947. return 0;
  1948. switch (conn->type)
  1949. {
  1950. case CONN_TYPE_OR:
  1951. return conn->state == OR_CONN_STATE_CONNECTING;
  1952. case CONN_TYPE_EXIT:
  1953. return conn->state == EXIT_CONN_STATE_CONNECTING;
  1954. case CONN_TYPE_DIR:
  1955. return conn->state == DIR_CONN_STATE_CONNECTING;
  1956. }
  1957. return 0;
  1958. }
  1959. /** Allocates a base64'ed authenticator for use in http or https
  1960. * auth, based on the input string <b>authenticator</b>. Returns it
  1961. * if success, else returns NULL. */
  1962. char *
  1963. alloc_http_authenticator(const char *authenticator)
  1964. {
  1965. /* an authenticator in Basic authentication
  1966. * is just the string "username:password" */
  1967. const int authenticator_length = strlen(authenticator);
  1968. /* The base64_encode function needs a minimum buffer length
  1969. * of 66 bytes. */
  1970. const int base64_authenticator_length = (authenticator_length/48+1)*66;
  1971. char *base64_authenticator = tor_malloc(base64_authenticator_length);
  1972. if (base64_encode(base64_authenticator, base64_authenticator_length,
  1973. authenticator, authenticator_length) < 0) {
  1974. tor_free(base64_authenticator); /* free and set to null */
  1975. } else {
  1976. /* remove extra \n at end of encoding */
  1977. base64_authenticator[strlen(base64_authenticator) - 1] = 0;
  1978. }
  1979. return base64_authenticator;
  1980. }
  1981. /** Given a socket handle, check whether the local address (sockname) of the
  1982. * socket is one that we've connected from before. If so, double-check
  1983. * whether our address has changed and we need to generate keys. If we do,
  1984. * call init_keys().
  1985. */
  1986. static void
  1987. client_check_address_changed(int sock)
  1988. {
  1989. uint32_t iface_ip, ip_out;
  1990. struct sockaddr_in out_addr;
  1991. socklen_t out_addr_len = sizeof(out_addr);
  1992. uint32_t *ip;
  1993. if (!last_interface_ip)
  1994. get_interface_address(LOG_INFO, &last_interface_ip);
  1995. if (!outgoing_addrs)
  1996. outgoing_addrs = smartlist_create();
  1997. if (getsockname(sock, (struct sockaddr*)&out_addr, &out_addr_len)<0) {
  1998. int e = tor_socket_errno(sock);
  1999. log_warn(LD_NET, "getsockname() to check for address change failed: %s",
  2000. tor_socket_strerror(e));
  2001. return;
  2002. }
  2003. /* Okay. If we've used this address previously, we're okay. */
  2004. ip_out = ntohl(out_addr.sin_addr.s_addr);
  2005. SMARTLIST_FOREACH(outgoing_addrs, uint32_t*, ip,
  2006. if (*ip == ip_out) return;
  2007. );
  2008. /* Uh-oh. We haven't connected from this address before. Has the interface
  2009. * address changed? */
  2010. if (get_interface_address(LOG_INFO, &iface_ip)<0)
  2011. return;
  2012. ip = tor_malloc(sizeof(uint32_t));
  2013. *ip = ip_out;
  2014. if (iface_ip == last_interface_ip) {
  2015. /* Nope, it hasn't changed. Add this address to the list. */
  2016. smartlist_add(outgoing_addrs, ip);
  2017. } else {
  2018. /* The interface changed. We're a client, so we need to regenerate our
  2019. * keys. First, reset the state. */
  2020. log(LOG_NOTICE, LD_NET, "Our IP has changed. Rotating keys...");
  2021. last_interface_ip = iface_ip;
  2022. SMARTLIST_FOREACH(outgoing_addrs, void*, ip, tor_free(ip));
  2023. smartlist_clear(outgoing_addrs);
  2024. smartlist_add(outgoing_addrs, ip);
  2025. /* Okay, now change our keys. */
  2026. ip_address_changed(1);
  2027. }
  2028. }
  2029. /** Process new bytes that have arrived on conn-\>inbuf.
  2030. *
  2031. * This function just passes conn to the connection-specific
  2032. * connection_*_process_inbuf() function. It also passes in
  2033. * package_partial if wanted.
  2034. */
  2035. static int
  2036. connection_process_inbuf(connection_t *conn, int package_partial)
  2037. {
  2038. tor_assert(conn);
  2039. switch (conn->type) {
  2040. case CONN_TYPE_OR:
  2041. return connection_or_process_inbuf(TO_OR_CONN(conn));
  2042. case CONN_TYPE_EXIT:
  2043. case CONN_TYPE_AP:
  2044. return connection_edge_process_inbuf(TO_EDGE_CONN(conn),
  2045. package_partial);
  2046. case CONN_TYPE_DIR:
  2047. return connection_dir_process_inbuf(TO_DIR_CONN(conn));
  2048. case CONN_TYPE_DNSWORKER:
  2049. return connection_dns_process_inbuf(conn);
  2050. case CONN_TYPE_CPUWORKER:
  2051. return connection_cpu_process_inbuf(conn);
  2052. case CONN_TYPE_CONTROL:
  2053. return connection_control_process_inbuf(TO_CONTROL_CONN(conn));
  2054. default:
  2055. log_err(LD_BUG,"Bug: got unexpected conn type %d.", conn->type);
  2056. tor_fragile_assert();
  2057. return -1;
  2058. }
  2059. }
  2060. /** Called whenever we've written data on a connection. */
  2061. static int
  2062. connection_flushed_some(connection_t *conn)
  2063. {
  2064. if (conn->type == CONN_TYPE_DIR &&
  2065. conn->state == DIR_CONN_STATE_SERVER_WRITING)
  2066. return connection_dirserv_flushed_some(TO_DIR_CONN(conn));
  2067. else if (conn->type == CONN_TYPE_OR)
  2068. return connection_or_flushed_some(TO_OR_CONN(conn));
  2069. else
  2070. return 0;
  2071. }
  2072. /** We just finished flushing bytes from conn-\>outbuf, and there
  2073. * are no more bytes remaining.
  2074. *
  2075. * This function just passes conn to the connection-specific
  2076. * connection_*_finished_flushing() function.
  2077. */
  2078. static int
  2079. connection_finished_flushing(connection_t *conn)
  2080. {
  2081. tor_assert(conn);
  2082. // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
  2083. switch (conn->type) {
  2084. case CONN_TYPE_OR:
  2085. return connection_or_finished_flushing(TO_OR_CONN(conn));
  2086. case CONN_TYPE_AP:
  2087. case CONN_TYPE_EXIT:
  2088. return connection_edge_finished_flushing(TO_EDGE_CONN(conn));
  2089. case CONN_TYPE_DIR:
  2090. return connection_dir_finished_flushing(TO_DIR_CONN(conn));
  2091. case CONN_TYPE_DNSWORKER:
  2092. return connection_dns_finished_flushing(conn);
  2093. case CONN_TYPE_CPUWORKER:
  2094. return connection_cpu_finished_flushing(conn);
  2095. case CONN_TYPE_CONTROL:
  2096. return connection_control_finished_flushing(TO_CONTROL_CONN(conn));
  2097. default:
  2098. log_err(LD_BUG,"Bug: got unexpected conn type %d.", conn->type);
  2099. tor_fragile_assert();
  2100. return -1;
  2101. }
  2102. }
  2103. /** Called when our attempt to connect() to another server has just
  2104. * succeeded.
  2105. *
  2106. * This function just passes conn to the connection-specific
  2107. * connection_*_finished_connecting() function.
  2108. */
  2109. static int
  2110. connection_finished_connecting(connection_t *conn)
  2111. {
  2112. tor_assert(conn);
  2113. switch (conn->type)
  2114. {
  2115. case CONN_TYPE_OR:
  2116. return connection_or_finished_connecting(TO_OR_CONN(conn));
  2117. case CONN_TYPE_EXIT:
  2118. return connection_edge_finished_connecting(TO_EDGE_CONN(conn));
  2119. case CONN_TYPE_DIR:
  2120. return connection_dir_finished_connecting(TO_DIR_CONN(conn));
  2121. default:
  2122. log_err(LD_BUG,"Bug: got unexpected conn type %d.", conn->type);
  2123. tor_fragile_assert();
  2124. return -1;
  2125. }
  2126. }
  2127. /** Callback: invoked when a connection reaches an EOF event. */
  2128. static int
  2129. connection_reached_eof(connection_t *conn)
  2130. {
  2131. switch (conn->type) {
  2132. case CONN_TYPE_OR:
  2133. return connection_or_reached_eof(TO_OR_CONN(conn));
  2134. case CONN_TYPE_AP:
  2135. case CONN_TYPE_EXIT:
  2136. return connection_edge_reached_eof(TO_EDGE_CONN(conn));
  2137. case CONN_TYPE_DIR:
  2138. return connection_dir_reached_eof(TO_DIR_CONN(conn));
  2139. case CONN_TYPE_DNSWORKER:
  2140. return connection_dns_reached_eof(conn);
  2141. case CONN_TYPE_CPUWORKER:
  2142. return connection_cpu_reached_eof(conn);
  2143. case CONN_TYPE_CONTROL:
  2144. return connection_control_reached_eof(TO_CONTROL_CONN(conn));
  2145. default:
  2146. log_err(LD_BUG,"Bug: got unexpected conn type %d.", conn->type);
  2147. tor_fragile_assert();
  2148. return -1;
  2149. }
  2150. }
  2151. /** Verify that connection <b>conn</b> has all of its invariants
  2152. * correct. Trigger an assert if anything is invalid.
  2153. */
  2154. void
  2155. assert_connection_ok(connection_t *conn, time_t now)
  2156. {
  2157. (void) now; /* XXXX unused. */
  2158. tor_assert(conn);
  2159. tor_assert(conn->type >= _CONN_TYPE_MIN);
  2160. tor_assert(conn->type <= _CONN_TYPE_MAX);
  2161. switch (conn->type) {
  2162. case CONN_TYPE_OR:
  2163. tor_assert(conn->magic == OR_CONNECTION_MAGIC);
  2164. break;
  2165. case CONN_TYPE_AP:
  2166. case CONN_TYPE_EXIT:
  2167. tor_assert(conn->magic == EDGE_CONNECTION_MAGIC);
  2168. break;
  2169. case CONN_TYPE_DIR:
  2170. tor_assert(conn->magic == DIR_CONNECTION_MAGIC);
  2171. break;
  2172. case CONN_TYPE_CONTROL:
  2173. tor_assert(conn->magic == CONTROL_CONNECTION_MAGIC);
  2174. break;
  2175. default:
  2176. tor_assert(conn->magic == BASE_CONNECTION_MAGIC);
  2177. break;
  2178. }
  2179. if (conn->outbuf_flushlen > 0) {
  2180. tor_assert(connection_is_writing(conn) || conn->wants_to_write ||
  2181. (conn->type == CONN_TYPE_DIR &&
  2182. TO_DIR_CONN(conn)->is_blocked_on_or_conn));
  2183. }
  2184. if (conn->hold_open_until_flushed)
  2185. tor_assert(conn->marked_for_close);
  2186. /* XXXX check: wants_to_read, wants_to_write, s, conn_array_index,
  2187. * marked_for_close. */
  2188. /* buffers */
  2189. if (!connection_is_listener(conn)) {
  2190. assert_buf_ok(conn->inbuf);
  2191. assert_buf_ok(conn->outbuf);
  2192. }
  2193. /* XXXX Fix this; no longer so.*/
  2194. #if 0
  2195. if (conn->type != CONN_TYPE_OR && conn->type != CONN_TYPE_DIR)
  2196. tor_assert(!conn->pkey);
  2197. /* pkey is set if we're a dir client, or if we're an OR in state OPEN
  2198. * connected to another OR.
  2199. */
  2200. #endif
  2201. if (conn->chosen_exit_optional) {
  2202. tor_assert(conn->type == CONN_TYPE_AP);
  2203. tor_assert((TO_EDGE_CONN(conn))->chosen_exit_name);
  2204. }
  2205. if (conn->type == CONN_TYPE_OR) {
  2206. or_connection_t *or_conn = TO_OR_CONN(conn);
  2207. if (conn->state == OR_CONN_STATE_OPEN) {
  2208. /* tor_assert(conn->bandwidth > 0); */
  2209. /* the above isn't necessarily true: if we just did a TLS
  2210. * handshake but we didn't recognize the other peer, or it
  2211. * gave a bad cert/etc, then we won't have assigned bandwidth,
  2212. * yet it will be open. -RD
  2213. */
  2214. // tor_assert(conn->read_bucket >= 0);
  2215. }
  2216. // tor_assert(conn->addr && conn->port);
  2217. tor_assert(conn->address);
  2218. if (conn->state > OR_CONN_STATE_PROXY_READING)
  2219. tor_assert(or_conn->tls);
  2220. }
  2221. if (CONN_IS_EDGE(conn)) {
  2222. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  2223. /* XXX unchecked: package window, deliver window. */
  2224. if (conn->type == CONN_TYPE_AP) {
  2225. tor_assert(edge_conn->socks_request);
  2226. if (conn->state == AP_CONN_STATE_OPEN) {
  2227. tor_assert(edge_conn->socks_request->has_finished);
  2228. if (!conn->marked_for_close) {
  2229. tor_assert(edge_conn->cpath_layer);
  2230. assert_cpath_layer_ok(edge_conn->cpath_layer);
  2231. }
  2232. }
  2233. }
  2234. if (conn->type == CONN_TYPE_EXIT) {
  2235. tor_assert(conn->purpose == EXIT_PURPOSE_CONNECT ||
  2236. conn->purpose == EXIT_PURPOSE_RESOLVE);
  2237. }
  2238. if (edge_conn->bridge_for_conn) {
  2239. tor_assert(conn->type == CONN_TYPE_EXIT);
  2240. tor_assert(edge_conn->bridge_for_conn->bridge_conn == edge_conn);
  2241. }
  2242. } else if (conn->type == CONN_TYPE_DIR) {
  2243. dir_connection_t *dir_conn = TO_DIR_CONN(conn);
  2244. if (dir_conn->bridge_conn) {
  2245. tor_assert(DIR_CONN_IS_SERVER(conn));
  2246. tor_assert(dir_conn->bridge_conn->bridge_for_conn == dir_conn);
  2247. if (dir_conn->bridge_conn->on_circuit) {
  2248. dir_connection_t *d;
  2249. or_connection_t *or_conn;
  2250. tor_assert(!CIRCUIT_IS_ORIGIN(dir_conn->bridge_conn->on_circuit));
  2251. or_conn = TO_OR_CIRCUIT(dir_conn->bridge_conn->on_circuit)->p_conn;
  2252. if (dir_conn->is_blocked_on_or_conn)
  2253. tor_assert(or_conn);
  2254. for (d = or_conn->blocked_dir_connections; d;
  2255. d = d->next_blocked_on_same_or_conn) {
  2256. if (d == dir_conn) {
  2257. tor_assert(dir_conn->is_blocked_on_or_conn == 1);
  2258. break;
  2259. }
  2260. }
  2261. if (!d)
  2262. tor_assert(!dir_conn->is_blocked_on_or_conn);
  2263. }
  2264. }
  2265. } else {
  2266. /* Purpose is only used for dir and exit types currently */
  2267. tor_assert(!conn->purpose);
  2268. }
  2269. switch (conn->type)
  2270. {
  2271. case CONN_TYPE_OR_LISTENER:
  2272. case CONN_TYPE_AP_LISTENER:
  2273. case CONN_TYPE_AP_TRANS_LISTENER:
  2274. case CONN_TYPE_AP_NATD_LISTENER:
  2275. case CONN_TYPE_DIR_LISTENER:
  2276. case CONN_TYPE_CONTROL_LISTENER:
  2277. tor_assert(conn->state == LISTENER_STATE_READY);
  2278. break;
  2279. case CONN_TYPE_OR:
  2280. tor_assert(conn->state >= _OR_CONN_STATE_MIN);
  2281. tor_assert(conn->state <= _OR_CONN_STATE_MAX);
  2282. tor_assert(TO_OR_CONN(conn)->n_circuits >= 0);
  2283. break;
  2284. case CONN_TYPE_EXIT:
  2285. tor_assert(conn->state >= _EXIT_CONN_STATE_MIN);
  2286. tor_assert(conn->state <= _EXIT_CONN_STATE_MAX);
  2287. tor_assert(conn->purpose >= _EXIT_PURPOSE_MIN);
  2288. tor_assert(conn->purpose <= _EXIT_PURPOSE_MAX);
  2289. break;
  2290. case CONN_TYPE_AP:
  2291. tor_assert(conn->state >= _AP_CONN_STATE_MIN);
  2292. tor_assert(conn->state <= _AP_CONN_STATE_MAX);
  2293. tor_assert(TO_EDGE_CONN(conn)->socks_request);
  2294. break;
  2295. case CONN_TYPE_DIR:
  2296. tor_assert(conn->state >= _DIR_CONN_STATE_MIN);
  2297. tor_assert(conn->state <= _DIR_CONN_STATE_MAX);
  2298. tor_assert(conn->purpose >= _DIR_PURPOSE_MIN);
  2299. tor_assert(conn->purpose <= _DIR_PURPOSE_MAX);
  2300. break;
  2301. case CONN_TYPE_DNSWORKER:
  2302. tor_assert(conn->state >= _DNSWORKER_STATE_MIN);
  2303. tor_assert(conn->state <= _DNSWORKER_STATE_MAX);
  2304. break;
  2305. case CONN_TYPE_CPUWORKER:
  2306. tor_assert(conn->state >= _CPUWORKER_STATE_MIN);
  2307. tor_assert(conn->state <= _CPUWORKER_STATE_MAX);
  2308. break;
  2309. case CONN_TYPE_CONTROL:
  2310. tor_assert(conn->state >= _CONTROL_CONN_STATE_MIN);
  2311. tor_assert(conn->state <= _CONTROL_CONN_STATE_MAX);
  2312. break;
  2313. default:
  2314. tor_assert(0);
  2315. }
  2316. }