connection.c 82 KB

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