connection.c 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, 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_receiver_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: return "Transparent listener";
  43. case CONN_TYPE_AP: return "Socks";
  44. case CONN_TYPE_DIR_LISTENER: return "Directory listener";
  45. case CONN_TYPE_DIR: return "Directory";
  46. case CONN_TYPE_DNSWORKER: return "DNS worker";
  47. case CONN_TYPE_CPUWORKER: return "CPU worker";
  48. case CONN_TYPE_CONTROL_LISTENER: return "Control listener";
  49. case CONN_TYPE_CONTROL: return "Control";
  50. default:
  51. log_warn(LD_BUG, "Bug: unknown connection type %d", type);
  52. tor_snprintf(buf, sizeof(buf), "unknown [%d]", type);
  53. return buf;
  54. }
  55. }
  56. /**
  57. * Return the human-readable name for the connection state <b>state</b>
  58. * for the connection type <b>type</b>
  59. */
  60. const char *
  61. conn_state_to_string(int type, int state)
  62. {
  63. static char buf[96];
  64. switch (type) {
  65. case CONN_TYPE_OR_LISTENER:
  66. case CONN_TYPE_AP_LISTENER:
  67. case CONN_TYPE_AP_TRANS_LISTENER:
  68. case CONN_TYPE_DIR_LISTENER:
  69. case CONN_TYPE_CONTROL_LISTENER:
  70. if (state == LISTENER_STATE_READY)
  71. return "ready";
  72. break;
  73. case CONN_TYPE_OR:
  74. switch (state) {
  75. case OR_CONN_STATE_CONNECTING: return "connect()ing";
  76. case OR_CONN_STATE_PROXY_FLUSHING: return "proxy flushing";
  77. case OR_CONN_STATE_PROXY_READING: return "proxy reading";
  78. case OR_CONN_STATE_HANDSHAKING: return "handshaking";
  79. case OR_CONN_STATE_OPEN: return "open";
  80. }
  81. break;
  82. case CONN_TYPE_EXIT:
  83. switch (state) {
  84. case EXIT_CONN_STATE_RESOLVING: return "waiting for dest info";
  85. case EXIT_CONN_STATE_CONNECTING: return "connecting";
  86. case EXIT_CONN_STATE_OPEN: return "open";
  87. case EXIT_CONN_STATE_RESOLVEFAILED: return "resolve failed";
  88. }
  89. break;
  90. case CONN_TYPE_AP:
  91. switch (state) {
  92. case AP_CONN_STATE_ORIGDST_WAIT:
  93. case AP_CONN_STATE_SOCKS_WAIT: return "waiting for dest info";
  94. case AP_CONN_STATE_RENDDESC_WAIT: return "waiting for rendezvous desc";
  95. case AP_CONN_STATE_CONTROLLER_WAIT: return "waiting for controller";
  96. case AP_CONN_STATE_CIRCUIT_WAIT: return "waiting for safe circuit";
  97. case AP_CONN_STATE_CONNECT_WAIT: return "waiting for connect";
  98. case AP_CONN_STATE_RESOLVE_WAIT: return "waiting for resolve";
  99. case AP_CONN_STATE_OPEN: return "open";
  100. }
  101. break;
  102. case CONN_TYPE_DIR:
  103. switch (state) {
  104. case DIR_CONN_STATE_CONNECTING: return "connecting";
  105. case DIR_CONN_STATE_CLIENT_SENDING: return "client sending";
  106. case DIR_CONN_STATE_CLIENT_READING: return "client reading";
  107. case DIR_CONN_STATE_SERVER_COMMAND_WAIT: return "waiting for command";
  108. case DIR_CONN_STATE_SERVER_WRITING: return "writing";
  109. }
  110. break;
  111. case CONN_TYPE_DNSWORKER:
  112. switch (state) {
  113. case DNSWORKER_STATE_IDLE: return "idle";
  114. case DNSWORKER_STATE_BUSY: return "busy";
  115. }
  116. break;
  117. case CONN_TYPE_CPUWORKER:
  118. switch (state) {
  119. case CPUWORKER_STATE_IDLE: return "idle";
  120. case CPUWORKER_STATE_BUSY_ONION: return "busy with onion";
  121. }
  122. break;
  123. case CONN_TYPE_CONTROL:
  124. switch (state) {
  125. case CONTROL_CONN_STATE_OPEN_V0: return "open (protocol v0)";
  126. case CONTROL_CONN_STATE_OPEN_V1: return "open (protocol v1)";
  127. case CONTROL_CONN_STATE_NEEDAUTH_V0:
  128. return "waiting for authentication (protocol unknown)";
  129. case CONTROL_CONN_STATE_NEEDAUTH_V1:
  130. return "waiting for authentication (protocol v1)";
  131. }
  132. break;
  133. }
  134. log_warn(LD_BUG, "Bug: unknown connection state %d (type %d)", state, type);
  135. tor_snprintf(buf, sizeof(buf),
  136. "unknown state [%d] on unknown [%s] connection",
  137. state, conn_type_to_string(type));
  138. return buf;
  139. }
  140. /** Allocate space for a new connection_t. This function just initializes
  141. * conn; you must call connection_add() to link it into the main array.
  142. *
  143. * Set conn-\>type to <b>type</b>. Set conn-\>s and conn-\>conn_array_index to
  144. * -1 to signify they are not yet assigned.
  145. *
  146. * If conn is not a listener type, allocate buffers for it. If it's
  147. * an AP type, allocate space to store the socks_request.
  148. *
  149. * Assign a pseudorandom next_circ_id between 0 and 2**15.
  150. *
  151. * Initialize conn's timestamps to now.
  152. */
  153. connection_t *
  154. connection_new(int type)
  155. {
  156. static uint32_t n_connections_allocated = 1;
  157. connection_t *conn;
  158. time_t now = time(NULL);
  159. size_t length;
  160. uint32_t magic;
  161. switch (type) {
  162. case CONN_TYPE_OR:
  163. length = sizeof(or_connection_t);
  164. magic = OR_CONNECTION_MAGIC;
  165. break;
  166. case CONN_TYPE_EXIT:
  167. case CONN_TYPE_AP:
  168. length = sizeof(edge_connection_t);
  169. magic = EDGE_CONNECTION_MAGIC;
  170. break;
  171. case CONN_TYPE_DIR:
  172. length = sizeof(dir_connection_t);
  173. magic = DIR_CONNECTION_MAGIC;
  174. break;
  175. case CONN_TYPE_CONTROL:
  176. length = sizeof(control_connection_t);
  177. magic = CONTROL_CONNECTION_MAGIC;
  178. break;
  179. default:
  180. length = sizeof(connection_t);
  181. magic = BASE_CONNECTION_MAGIC;
  182. break;
  183. }
  184. conn = tor_malloc_zero(length);
  185. conn->magic = magic;
  186. conn->s = -1; /* give it a default of 'not used' */
  187. conn->conn_array_index = -1; /* also default to 'not used' */
  188. conn->type = type;
  189. if (!connection_is_listener(conn)) { /* listeners never use their buf */
  190. conn->inbuf = buf_new();
  191. conn->outbuf = buf_new();
  192. }
  193. if (type == CONN_TYPE_AP) {
  194. TO_EDGE_CONN(conn)->socks_request =
  195. tor_malloc_zero(sizeof(socks_request_t));
  196. }
  197. if (CONN_IS_EDGE(conn)) {
  198. TO_EDGE_CONN(conn)->global_identifier = n_connections_allocated++;
  199. }
  200. if (type == CONN_TYPE_OR)
  201. TO_OR_CONN(conn)->next_circ_id = crypto_rand_int(1<<15);
  202. conn->timestamp_created = now;
  203. conn->timestamp_lastread = now;
  204. conn->timestamp_lastwritten = now;
  205. return conn;
  206. }
  207. /** Tell libevent that we don't care about <b>conn</b> any more. */
  208. void
  209. connection_unregister(connection_t *conn)
  210. {
  211. if (conn->read_event) {
  212. if (event_del(conn->read_event))
  213. log_warn(LD_BUG, "Error removing read event for %d", conn->s);
  214. tor_free(conn->read_event);
  215. }
  216. if (conn->write_event) {
  217. if (event_del(conn->write_event))
  218. log_warn(LD_BUG, "Error removing write event for %d", conn->s);
  219. tor_free(conn->write_event);
  220. }
  221. }
  222. /** Deallocate memory used by <b>conn</b>. Deallocate its buffers if
  223. * necessary, close its socket if necessary, and mark the directory as dirty
  224. * if <b>conn</b> is an OR or OP connection.
  225. */
  226. static void
  227. _connection_free(connection_t *conn)
  228. {
  229. void *mem;
  230. switch (conn->type) {
  231. case CONN_TYPE_OR:
  232. tor_assert(conn->magic == OR_CONNECTION_MAGIC);
  233. mem = TO_OR_CONN(conn);
  234. break;
  235. case CONN_TYPE_AP:
  236. case CONN_TYPE_EXIT:
  237. tor_assert(conn->magic == EDGE_CONNECTION_MAGIC);
  238. mem = TO_EDGE_CONN(conn);
  239. break;
  240. case CONN_TYPE_DIR:
  241. tor_assert(conn->magic == DIR_CONNECTION_MAGIC);
  242. mem = TO_DIR_CONN(conn);
  243. break;
  244. case CONN_TYPE_CONTROL:
  245. tor_assert(conn->magic == CONTROL_CONNECTION_MAGIC);
  246. mem = TO_CONTROL_CONN(conn);
  247. break;
  248. default:
  249. tor_assert(conn->magic == BASE_CONNECTION_MAGIC);
  250. mem = conn;
  251. break;
  252. }
  253. if (!connection_is_listener(conn)) {
  254. buf_free(conn->inbuf);
  255. buf_free(conn->outbuf);
  256. }
  257. tor_free(conn->address);
  258. if (connection_speaks_cells(conn)) {
  259. or_connection_t *or_conn = TO_OR_CONN(conn);
  260. if (or_conn->tls) {
  261. tor_tls_free(or_conn->tls);
  262. or_conn->tls = NULL;
  263. }
  264. tor_free(or_conn->nickname);
  265. }
  266. if (CONN_IS_EDGE(conn)) {
  267. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  268. tor_free(edge_conn->chosen_exit_name);
  269. tor_free(edge_conn->socks_request);
  270. }
  271. if (conn->type == CONN_TYPE_CONTROL) {
  272. control_connection_t *control_conn = TO_CONTROL_CONN(conn);
  273. tor_free(control_conn->incoming_cmd);
  274. }
  275. tor_free(conn->read_event); /* Probably already freed by connection_free. */
  276. tor_free(conn->write_event); /* Probably already freed by connection_free. */
  277. if (conn->type == CONN_TYPE_DIR) {
  278. dir_connection_t *dir_conn = TO_DIR_CONN(conn);
  279. tor_free(dir_conn->requested_resource);
  280. if (dir_conn->zlib_state)
  281. tor_zlib_free(dir_conn->zlib_state);
  282. if (dir_conn->fingerprint_stack) {
  283. SMARTLIST_FOREACH(dir_conn->fingerprint_stack, char *, cp, tor_free(cp));
  284. smartlist_free(dir_conn->fingerprint_stack);
  285. }
  286. if (dir_conn->cached_dir)
  287. cached_dir_decref(dir_conn->cached_dir);
  288. }
  289. if (conn->s >= 0) {
  290. log_debug(LD_NET,"closing fd %d.",conn->s);
  291. tor_close_socket(conn->s);
  292. }
  293. if (conn->type == CONN_TYPE_OR &&
  294. !tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest)) {
  295. log_warn(LD_BUG, "called on OR conn with non-zeroed identity_digest");
  296. connection_or_remove_from_identity_map(TO_OR_CONN(conn));
  297. }
  298. memset(conn, 0xAA, sizeof(connection_t)); /* poison memory */
  299. tor_free(mem);
  300. }
  301. /** Make sure <b>conn</b> isn't in any of the global conn lists; then free it.
  302. */
  303. void
  304. connection_free(connection_t *conn)
  305. {
  306. tor_assert(conn);
  307. tor_assert(!connection_is_on_closeable_list(conn));
  308. tor_assert(!connection_in_array(conn));
  309. if (connection_speaks_cells(conn)) {
  310. if (conn->state == OR_CONN_STATE_OPEN)
  311. directory_set_dirty();
  312. if (!tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest)) {
  313. connection_or_remove_from_identity_map(TO_OR_CONN(conn));
  314. }
  315. }
  316. if (conn->type == CONN_TYPE_CONTROL) {
  317. TO_CONTROL_CONN(conn)->event_mask = 0;
  318. control_update_global_event_mask();
  319. }
  320. connection_unregister(conn);
  321. _connection_free(conn);
  322. }
  323. /** Call _connection_free() on every connection in our array, and release all
  324. * storage helpd by connection.c. This is used by cpuworkers and dnsworkers
  325. * when they fork, so they don't keep resources held open (especially
  326. * sockets).
  327. *
  328. * Don't do the checks in connection_free(), because they will
  329. * fail.
  330. */
  331. void
  332. connection_free_all(void)
  333. {
  334. int i, n;
  335. connection_t **carray;
  336. get_connection_array(&carray,&n);
  337. /* We don't want to log any messages to controllers. */
  338. for (i=0;i<n;i++)
  339. if (carray[i]->type == CONN_TYPE_CONTROL)
  340. TO_CONTROL_CONN(carray[i])->event_mask = 0;
  341. control_update_global_event_mask();
  342. /* Unlink everything from the identity map. */
  343. connection_or_clear_identity_map();
  344. for (i=0;i<n;i++)
  345. _connection_free(carray[i]);
  346. if (outgoing_addrs) {
  347. SMARTLIST_FOREACH(outgoing_addrs, void*, addr, tor_free(addr));
  348. smartlist_free(outgoing_addrs);
  349. outgoing_addrs = NULL;
  350. }
  351. }
  352. /** Do any cleanup needed:
  353. * - Directory conns that failed to fetch a rendezvous descriptor
  354. * need to inform pending rendezvous streams.
  355. * - OR conns need to call rep_hist_note_*() to record status.
  356. * - AP conns need to send a socks reject if necessary.
  357. * - Exit conns need to call connection_dns_remove() if necessary.
  358. * - AP and Exit conns need to send an end cell if they can.
  359. * - DNS conns need to fail any resolves that are pending on them.
  360. */
  361. void
  362. connection_about_to_close_connection(connection_t *conn)
  363. {
  364. circuit_t *circ;
  365. dir_connection_t *dir_conn;
  366. or_connection_t *or_conn;
  367. edge_connection_t *edge_conn;
  368. assert(conn->marked_for_close);
  369. if (CONN_IS_EDGE(conn)) {
  370. if (!conn->edge_has_sent_end) {
  371. log_warn(LD_BUG, "Harmless bug: Edge connection (marked at %s:%d) "
  372. "hasn't sent end yet?",
  373. conn->marked_for_close_file, conn->marked_for_close);
  374. tor_fragile_assert();
  375. }
  376. }
  377. switch (conn->type) {
  378. case CONN_TYPE_DIR:
  379. dir_conn = TO_DIR_CONN(conn);
  380. if (conn->state < DIR_CONN_STATE_CLIENT_FINISHED) {
  381. /* It's a directory connection and connecting or fetching
  382. * failed: forget about this router, and maybe try again. */
  383. connection_dir_request_failed(dir_conn);
  384. // XXX if it's rend desc we may want to retry -RD
  385. }
  386. if (conn->purpose == DIR_PURPOSE_FETCH_RENDDESC)
  387. rend_client_desc_here(dir_conn->rend_query); /* give it a try */
  388. break;
  389. case CONN_TYPE_OR:
  390. or_conn = TO_OR_CONN(conn);
  391. /* Remember why we're closing this connection. */
  392. if (conn->state != OR_CONN_STATE_OPEN) {
  393. if (connection_or_nonopen_was_started_here(or_conn)) {
  394. rep_hist_note_connect_failed(or_conn->identity_digest, time(NULL));
  395. entry_guard_register_connect_status(or_conn->identity_digest, 0);
  396. router_set_status(or_conn->identity_digest, 0);
  397. control_event_or_conn_status(or_conn, OR_CONN_EVENT_FAILED);
  398. }
  399. } else if (conn->hold_open_until_flushed) {
  400. /* XXXX009 We used to have an arg that told us whether we closed the
  401. * connection on purpose or not. Can we use hold_open_until_flushed
  402. * instead? We only set it when we are intentionally closing a
  403. * connection. -NM
  404. *
  405. * (Of course, now things we set to close which expire rather than
  406. * flushing still get noted as dead, not disconnected. But this is an
  407. * improvement. -NM
  408. */
  409. rep_hist_note_disconnect(or_conn->identity_digest, time(NULL));
  410. control_event_or_conn_status(or_conn, OR_CONN_EVENT_CLOSED);
  411. } else if (or_conn->identity_digest) {
  412. rep_hist_note_connection_died(or_conn->identity_digest, time(NULL));
  413. control_event_or_conn_status(or_conn, OR_CONN_EVENT_CLOSED);
  414. }
  415. break;
  416. case CONN_TYPE_AP:
  417. edge_conn = TO_EDGE_CONN(conn);
  418. if (edge_conn->socks_request->has_finished == 0) {
  419. /* since conn gets removed right after this function finishes,
  420. * there's no point trying to send back a reply at this point. */
  421. log_warn(LD_BUG,"Bug: Closing stream (marked at %s:%d) without sending"
  422. " back a socks reply.",
  423. conn->marked_for_close_file, conn->marked_for_close);
  424. } else {
  425. control_event_stream_status(edge_conn, STREAM_EVENT_CLOSED);
  426. }
  427. break;
  428. case CONN_TYPE_EXIT:
  429. edge_conn = TO_EDGE_CONN(conn);
  430. if (conn->state == EXIT_CONN_STATE_RESOLVING) {
  431. circ = circuit_get_by_edge_conn(edge_conn);
  432. if (circ)
  433. circuit_detach_stream(circ, edge_conn);
  434. connection_dns_remove(edge_conn);
  435. }
  436. break;
  437. case CONN_TYPE_DNSWORKER:
  438. if (conn->state == DNSWORKER_STATE_BUSY) {
  439. dns_cancel_pending_resolve(conn->address);
  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,"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. */
  732. static int
  733. connection_init_accepted_conn(connection_t *conn, uint8_t listener_type)
  734. {
  735. connection_start_reading(conn);
  736. switch (conn->type) {
  737. case CONN_TYPE_OR:
  738. control_event_or_conn_status(TO_OR_CONN(conn), OR_CONN_EVENT_NEW);
  739. return connection_tls_start_handshake(TO_OR_CONN(conn), 1);
  740. case CONN_TYPE_AP:
  741. switch (listener_type) {
  742. case CONN_TYPE_AP_LISTENER:
  743. conn->state = AP_CONN_STATE_SOCKS_WAIT;
  744. break;
  745. case CONN_TYPE_AP_TRANS_LISTENER:
  746. conn->state = AP_CONN_STATE_ORIGDST_WAIT;
  747. break;
  748. }
  749. break;
  750. case CONN_TYPE_DIR:
  751. conn->purpose = DIR_PURPOSE_SERVER;
  752. conn->state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
  753. break;
  754. case CONN_TYPE_CONTROL:
  755. conn->state = CONTROL_CONN_STATE_NEEDAUTH_V0;
  756. break;
  757. }
  758. return 0;
  759. }
  760. /** Take conn, make a nonblocking socket; try to connect to
  761. * addr:port (they arrive in *host order*). If fail, return -1. Else
  762. * assign s to conn-\>s: if connected return 1, if EAGAIN return 0.
  763. *
  764. * address is used to make the logs useful.
  765. *
  766. * On success, add conn to the list of polled connections.
  767. */
  768. int
  769. connection_connect(connection_t *conn, char *address,
  770. uint32_t addr, uint16_t port)
  771. {
  772. int s, inprogress = 0;
  773. struct sockaddr_in dest_addr;
  774. or_options_t *options = get_options();
  775. s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
  776. if (s < 0) {
  777. log_warn(LD_NET,"Error creating network socket: %s",
  778. tor_socket_strerror(tor_socket_errno(-1)));
  779. return -1;
  780. }
  781. if (options->OutboundBindAddress) {
  782. struct sockaddr_in ext_addr;
  783. memset(&ext_addr, 0, sizeof(ext_addr));
  784. ext_addr.sin_family = AF_INET;
  785. ext_addr.sin_port = 0;
  786. if (!tor_inet_aton(options->OutboundBindAddress, &ext_addr.sin_addr)) {
  787. log_warn(LD_CONFIG,"Outbound bind address '%s' didn't parse. Ignoring.",
  788. options->OutboundBindAddress);
  789. } else {
  790. if (bind(s, (struct sockaddr*)&ext_addr, sizeof(ext_addr)) < 0) {
  791. log_warn(LD_NET,"Error binding network socket: %s",
  792. tor_socket_strerror(tor_socket_errno(s)));
  793. tor_close_socket(s);
  794. return -1;
  795. }
  796. }
  797. }
  798. set_socket_nonblocking(s);
  799. memset(&dest_addr,0,sizeof(dest_addr));
  800. dest_addr.sin_family = AF_INET;
  801. dest_addr.sin_port = htons(port);
  802. dest_addr.sin_addr.s_addr = htonl(addr);
  803. log_debug(LD_NET,"Connecting to %s:%u.",escaped_safe_str(address),port);
  804. if (connect(s,(struct sockaddr *)&dest_addr,sizeof(dest_addr)) < 0) {
  805. int e = tor_socket_errno(s);
  806. if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
  807. /* yuck. kill it. */
  808. log_info(LD_NET,
  809. "connect() to %s:%u failed: %s",escaped_safe_str(address),
  810. port, tor_socket_strerror(e));
  811. tor_close_socket(s);
  812. return -1;
  813. } else {
  814. inprogress = 1;
  815. }
  816. }
  817. if (!server_mode(options))
  818. client_check_address_changed(s);
  819. /* it succeeded. we're connected. */
  820. log_fn(inprogress?LOG_DEBUG:LOG_INFO, LD_NET,
  821. "Connection to %s:%u %s (sock %d).",escaped_safe_str(address),
  822. port, inprogress?"in progress":"established", s);
  823. conn->s = s;
  824. if (connection_add(conn) < 0) /* no space, forget it */
  825. return -1;
  826. return inprogress ? 0 : 1;
  827. }
  828. /**
  829. * Launch any configured listener connections of type <b>type</b>. (A
  830. * listener is configured if <b>port_option</b> is non-zero. If any
  831. * ListenAddress configuration options are given in <b>cfg</b>, create a
  832. * connection binding to each one. Otherwise, create a single
  833. * connection binding to the address <b>default_addr</b>.)
  834. *
  835. * If <b>force</b> is true, close and re-open all listener connections.
  836. * Otherwise, only relaunch the listeners of this type if the number of
  837. * existing connections is not as configured (e.g., because one died),
  838. * or if the existing connections do not match those configured.
  839. *
  840. * Add all old conns that should be closed to <b>replaced_conns</b>.
  841. * Add all new connections to <b>new_conns</b>.
  842. */
  843. static int
  844. retry_listeners(int type, config_line_t *cfg,
  845. int port_option, const char *default_addr, int force,
  846. smartlist_t *replaced_conns,
  847. smartlist_t *new_conns,
  848. int never_open_conns)
  849. {
  850. smartlist_t *launch = smartlist_create();
  851. int free_launch_elts = 1;
  852. config_line_t *c;
  853. int n_conn, i;
  854. connection_t *conn;
  855. connection_t **carray;
  856. config_line_t *line;
  857. if (cfg && port_option) {
  858. for (c = cfg; c; c = c->next) {
  859. smartlist_add(launch, c);
  860. }
  861. free_launch_elts = 0;
  862. } else if (port_option) {
  863. line = tor_malloc_zero(sizeof(config_line_t));
  864. line->key = tor_strdup("");
  865. line->value = tor_strdup(default_addr);
  866. smartlist_add(launch, line);
  867. }
  868. /*
  869. SMARTLIST_FOREACH(launch, config_line_t *, l,
  870. log_fn(LOG_NOTICE, "#%s#%s", l->key, l->value));
  871. */
  872. get_connection_array(&carray,&n_conn);
  873. for (i=0; i < n_conn; ++i) {
  874. conn = carray[i];
  875. if (conn->type != type || conn->marked_for_close)
  876. continue;
  877. if (force) {
  878. /* It's a listener, and we're relaunching all listeners of this
  879. * type. Close this one. */
  880. log_notice(LD_NET, "Force-closing listener %s on %s:%d",
  881. conn_type_to_string(type), conn->address, conn->port);
  882. connection_close_immediate(conn);
  883. connection_mark_for_close(conn);
  884. continue;
  885. }
  886. /* Okay, so this is a listener. Is it configured? */
  887. line = NULL;
  888. SMARTLIST_FOREACH(launch, config_line_t *, wanted,
  889. {
  890. char *address=NULL;
  891. uint16_t port;
  892. if (!parse_addr_port(LOG_WARN, wanted->value, &address, NULL, &port)) {
  893. int addr_matches = !strcasecmp(address, conn->address);
  894. tor_free(address);
  895. if (! port)
  896. port = port_option;
  897. if (port == conn->port && addr_matches) {
  898. line = wanted;
  899. break;
  900. }
  901. }
  902. });
  903. if (! line) {
  904. /* This one isn't configured. Close it. */
  905. log_notice(LD_NET, "Closing no-longer-configured %s on %s:%d",
  906. conn_type_to_string(type), conn->address, conn->port);
  907. if (replaced_conns) {
  908. smartlist_add(replaced_conns, conn);
  909. } else {
  910. connection_close_immediate(conn);
  911. connection_mark_for_close(conn);
  912. }
  913. } else {
  914. /* It's configured; we don't need to launch it. */
  915. // log_debug(LD_NET, "Already have %s on %s:%d",
  916. // conn_type_to_string(type), conn->address, conn->port);
  917. smartlist_remove(launch, line);
  918. if (free_launch_elts)
  919. config_free_lines(line);
  920. }
  921. }
  922. /* Now open all the listeners that are configured but not opened. */
  923. i = 0;
  924. if (!never_open_conns) {
  925. SMARTLIST_FOREACH(launch, config_line_t *, cfg,
  926. {
  927. conn = connection_create_listener(cfg->value, (uint16_t) port_option,
  928. type);
  929. if (!conn) {
  930. i = -1;
  931. } else {
  932. if (new_conns)
  933. smartlist_add(new_conns, conn);
  934. }
  935. });
  936. }
  937. if (free_launch_elts) {
  938. SMARTLIST_FOREACH(launch, config_line_t *, cfg,
  939. config_free_lines(cfg));
  940. }
  941. smartlist_free(launch);
  942. return i;
  943. }
  944. /** (Re)launch listeners for each port you should have open. If
  945. * <b>force</b> is true, close and relaunch all listeners. If <b>force</b>
  946. * is false, then only relaunch listeners when we have the wrong number of
  947. * connections for a given type.
  948. *
  949. * Add all old conns that should be closed to <b>replaced_conns</b>.
  950. * Add all new connections to <b>new_conns</b>.
  951. */
  952. int
  953. retry_all_listeners(int force, smartlist_t *replaced_conns,
  954. smartlist_t *new_conns)
  955. {
  956. or_options_t *options = get_options();
  957. if (retry_listeners(CONN_TYPE_OR_LISTENER, options->ORListenAddress,
  958. options->ORPort, "0.0.0.0", force,
  959. replaced_conns, new_conns, options->ClientOnly)<0)
  960. return -1;
  961. if (retry_listeners(CONN_TYPE_DIR_LISTENER, options->DirListenAddress,
  962. options->DirPort, "0.0.0.0", force,
  963. replaced_conns, new_conns, 0)<0)
  964. return -1;
  965. if (retry_listeners(CONN_TYPE_AP_LISTENER, options->SocksListenAddress,
  966. options->SocksPort, "127.0.0.1", force,
  967. replaced_conns, new_conns, 0)<0)
  968. return -1;
  969. if (retry_listeners(CONN_TYPE_AP_TRANS_LISTENER, options->TransListenAddress,
  970. options->TransPort, "127.0.0.1", force,
  971. replaced_conns, new_conns, 0)<0)
  972. return -1;
  973. if (retry_listeners(CONN_TYPE_CONTROL_LISTENER,
  974. options->ControlListenAddress,
  975. options->ControlPort, "127.0.0.1", force,
  976. replaced_conns, new_conns, 0)<0)
  977. return -1;
  978. return 0;
  979. }
  980. extern int global_read_bucket, global_write_bucket;
  981. /** How many bytes at most can we read onto this connection? */
  982. static int
  983. connection_bucket_read_limit(connection_t *conn)
  984. {
  985. int at_most;
  986. int base = connection_speaks_cells(conn) ?
  987. CELL_NETWORK_SIZE : RELAY_PAYLOAD_SIZE;
  988. /* Do a rudimentary round-robin so one circuit can't hog a connection.
  989. * Pick at most 32 cells, at least 4 cells if possible, and if we're in
  990. * the middle pick 1/8 of the available bandwidth. */
  991. at_most = global_read_bucket / 8;
  992. at_most -= (at_most % base); /* round down */
  993. if (at_most > 32*base) /* 16 KB */
  994. at_most = 32*base;
  995. else if (at_most < 4*base) /* 2 KB */
  996. at_most = 4*base;
  997. if (at_most > global_read_bucket)
  998. at_most = global_read_bucket;
  999. if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
  1000. or_connection_t *or_conn = TO_OR_CONN(conn);
  1001. if (at_most > or_conn->receiver_bucket)
  1002. at_most = or_conn->receiver_bucket;
  1003. }
  1004. if (at_most < 0)
  1005. return 0;
  1006. return at_most;
  1007. }
  1008. /** How many bytes at most can we write onto this connection? */
  1009. int
  1010. connection_bucket_write_limit(connection_t *conn)
  1011. {
  1012. unsigned int at_most;
  1013. /* do a rudimentary round-robin so one circuit can't hog a connection */
  1014. if (connection_speaks_cells(conn)) {
  1015. at_most = 32*(CELL_NETWORK_SIZE);
  1016. } else {
  1017. at_most = 32*(RELAY_PAYLOAD_SIZE);
  1018. }
  1019. if (at_most > conn->outbuf_flushlen)
  1020. at_most = conn->outbuf_flushlen;
  1021. #if 0 /* don't enable til we actually do write limiting */
  1022. if (at_most > global_write_bucket)
  1023. at_most = global_write_bucket;
  1024. #endif
  1025. return at_most;
  1026. }
  1027. /** Return 1 if the global write bucket has no bytes in it,
  1028. * or return 0 if it does. */
  1029. int
  1030. global_write_bucket_empty(void)
  1031. {
  1032. return global_write_bucket <= 0;
  1033. }
  1034. /** We just read num_read onto conn. Decrement buckets appropriately. */
  1035. static void
  1036. connection_read_bucket_decrement(connection_t *conn, int num_read)
  1037. {
  1038. global_read_bucket -= num_read;
  1039. if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
  1040. TO_OR_CONN(conn)->receiver_bucket -= num_read;
  1041. }
  1042. }
  1043. /** If we have exhaused our global read bucket, or the read bucket for conn,
  1044. * stop reading. */
  1045. static void
  1046. connection_consider_empty_buckets(connection_t *conn)
  1047. {
  1048. if (global_read_bucket <= 0) {
  1049. LOG_FN_CONN(conn, (LOG_DEBUG,LD_NET,"global bucket exhausted. Pausing."));
  1050. conn->wants_to_read = 1;
  1051. connection_stop_reading(conn);
  1052. return;
  1053. }
  1054. if (connection_speaks_cells(conn) &&
  1055. conn->state == OR_CONN_STATE_OPEN &&
  1056. TO_OR_CONN(conn)->receiver_bucket <= 0) {
  1057. LOG_FN_CONN(conn,
  1058. (LOG_DEBUG,LD_NET,"receiver bucket exhausted. Pausing."));
  1059. conn->wants_to_read = 1;
  1060. connection_stop_reading(conn);
  1061. }
  1062. }
  1063. /** Initialize the global read bucket to options->BandwidthBurst. */
  1064. void
  1065. connection_bucket_init(void)
  1066. {
  1067. or_options_t *options = get_options();
  1068. /* start it at max traffic */
  1069. global_read_bucket = (int)options->BandwidthBurst;
  1070. global_write_bucket = (int)options->BandwidthBurst;
  1071. }
  1072. /** A second has rolled over; increment buckets appropriately. */
  1073. void
  1074. connection_bucket_refill(struct timeval *now)
  1075. {
  1076. int i, n;
  1077. connection_t *conn;
  1078. connection_t **carray;
  1079. or_options_t *options = get_options();
  1080. /* Not used, but it should be! We might have rolled over more than one
  1081. * second! XXXX */
  1082. (void) now;
  1083. /* refill the global buckets */
  1084. if (global_read_bucket < (int)options->BandwidthBurst) {
  1085. global_read_bucket += (int)options->BandwidthRate;
  1086. log_debug(LD_NET,"global_read_bucket now %d.", global_read_bucket);
  1087. }
  1088. if (global_write_bucket < (int)options->BandwidthBurst) {
  1089. global_write_bucket += (int)options->BandwidthRate;
  1090. log_debug(LD_NET,"global_write_bucket now %d.", global_write_bucket);
  1091. }
  1092. /* refill the per-connection buckets */
  1093. get_connection_array(&carray,&n);
  1094. for (i=0;i<n;i++) {
  1095. conn = carray[i];
  1096. if (connection_speaks_cells(conn)) {
  1097. or_connection_t *or_conn = TO_OR_CONN(conn);
  1098. if (connection_receiver_bucket_should_increase(or_conn)) {
  1099. or_conn->receiver_bucket += or_conn->bandwidthrate;
  1100. if (or_conn->receiver_bucket > or_conn->bandwidthburst)
  1101. or_conn->receiver_bucket = or_conn->bandwidthburst;
  1102. //log_fn(LOG_DEBUG,"Receiver bucket %d now %d.", i,
  1103. // conn->receiver_bucket);
  1104. }
  1105. }
  1106. if (conn->wants_to_read == 1 /* it's marked to turn reading back on now */
  1107. && global_read_bucket > 0 /* and we're allowed to read */
  1108. && global_write_bucket > 0 /* and we're allowed to write (XXXX,
  1109. * not the best place to check this.) */
  1110. && (!connection_speaks_cells(conn) ||
  1111. conn->state != OR_CONN_STATE_OPEN ||
  1112. TO_OR_CONN(conn)->receiver_bucket > 0)) {
  1113. /* and either a non-cell conn or a cell conn with non-empty bucket */
  1114. LOG_FN_CONN(conn, (LOG_DEBUG,LD_NET,"waking up conn (fd %d)",conn->s));
  1115. conn->wants_to_read = 0;
  1116. connection_start_reading(conn);
  1117. if (conn->wants_to_write == 1) {
  1118. conn->wants_to_write = 0;
  1119. connection_start_writing(conn);
  1120. }
  1121. }
  1122. }
  1123. }
  1124. /** Is the receiver bucket for connection <b>conn</b> low enough that we
  1125. * should add another pile of tokens to it?
  1126. */
  1127. static int
  1128. connection_receiver_bucket_should_increase(or_connection_t *conn)
  1129. {
  1130. tor_assert(conn);
  1131. if (conn->_base.state != OR_CONN_STATE_OPEN)
  1132. return 0; /* only open connections play the rate limiting game */
  1133. if (conn->receiver_bucket >= conn->bandwidthburst)
  1134. return 0;
  1135. return 1;
  1136. }
  1137. /** Read bytes from conn-\>s and process them.
  1138. *
  1139. * This function gets called from conn_read() in main.c, either
  1140. * when poll() has declared that conn wants to read, or (for OR conns)
  1141. * when there are pending TLS bytes.
  1142. *
  1143. * It calls connection_read_to_buf() to bring in any new bytes,
  1144. * and then calls connection_process_inbuf() to process them.
  1145. *
  1146. * Mark the connection and return -1 if you want to close it, else
  1147. * return 0.
  1148. */
  1149. int
  1150. connection_handle_read(connection_t *conn)
  1151. {
  1152. int max_to_read=-1, try_to_read;
  1153. if (conn->marked_for_close)
  1154. return 0; /* do nothing */
  1155. conn->timestamp_lastread = time(NULL);
  1156. switch (conn->type) {
  1157. case CONN_TYPE_OR_LISTENER:
  1158. return connection_handle_listener_read(conn, CONN_TYPE_OR);
  1159. case CONN_TYPE_AP_LISTENER:
  1160. case CONN_TYPE_AP_TRANS_LISTENER:
  1161. return connection_handle_listener_read(conn, CONN_TYPE_AP);
  1162. case CONN_TYPE_DIR_LISTENER:
  1163. return connection_handle_listener_read(conn, CONN_TYPE_DIR);
  1164. case CONN_TYPE_CONTROL_LISTENER:
  1165. return connection_handle_listener_read(conn, CONN_TYPE_CONTROL);
  1166. }
  1167. loop_again:
  1168. try_to_read = max_to_read;
  1169. tor_assert(!conn->marked_for_close);
  1170. if (connection_read_to_buf(conn, &max_to_read) < 0) {
  1171. /* There's a read error; kill the connection.*/
  1172. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  1173. if (CONN_IS_EDGE(conn)) {
  1174. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  1175. connection_edge_end_errno(edge_conn, edge_conn->cpath_layer);
  1176. if (edge_conn->socks_request) /* broken, don't send a socks reply back */
  1177. edge_conn->socks_request->has_finished = 1;
  1178. }
  1179. connection_mark_for_close(conn);
  1180. return -1;
  1181. }
  1182. if (CONN_IS_EDGE(conn) && try_to_read != max_to_read) {
  1183. /* instruct it not to try to package partial cells. */
  1184. if (connection_process_inbuf(conn, 0) < 0) {
  1185. return -1;
  1186. }
  1187. if (!conn->marked_for_close &&
  1188. connection_is_reading(conn) &&
  1189. !conn->inbuf_reached_eof &&
  1190. max_to_read > 0)
  1191. goto loop_again; /* try reading again, in case more is here now */
  1192. }
  1193. /* one last try, packaging partial cells and all. */
  1194. if (!conn->marked_for_close &&
  1195. connection_process_inbuf(conn, 1) < 0) {
  1196. return -1;
  1197. }
  1198. if (!conn->marked_for_close &&
  1199. conn->inbuf_reached_eof &&
  1200. connection_reached_eof(conn) < 0) {
  1201. return -1;
  1202. }
  1203. return 0;
  1204. }
  1205. /** Pull in new bytes from conn-\>s onto conn-\>inbuf, either
  1206. * directly or via TLS. Reduce the token buckets by the number of
  1207. * bytes read.
  1208. *
  1209. * If *max_to_read is -1, then decide it ourselves, else go with the
  1210. * value passed to us. When returning, if it's changed, subtract the
  1211. * number of bytes we read from *max_to_read.
  1212. *
  1213. * Return -1 if we want to break conn, else return 0.
  1214. */
  1215. static int
  1216. connection_read_to_buf(connection_t *conn, int *max_to_read)
  1217. {
  1218. int result, at_most = *max_to_read;
  1219. size_t bytes_in_buf, more_to_read;
  1220. if (at_most == -1) { /* we need to initialize it */
  1221. /* how many bytes are we allowed to read? */
  1222. at_most = connection_bucket_read_limit(conn);
  1223. }
  1224. bytes_in_buf = buf_capacity(conn->inbuf) - buf_datalen(conn->inbuf);
  1225. again:
  1226. if ((size_t)at_most > bytes_in_buf && bytes_in_buf >= 1024) {
  1227. more_to_read = at_most - bytes_in_buf;
  1228. at_most = bytes_in_buf;
  1229. } else {
  1230. more_to_read = 0;
  1231. }
  1232. if (connection_speaks_cells(conn) &&
  1233. conn->state > OR_CONN_STATE_PROXY_READING) {
  1234. int pending;
  1235. or_connection_t *or_conn = TO_OR_CONN(conn);
  1236. if (conn->state == OR_CONN_STATE_HANDSHAKING) {
  1237. /* continue handshaking even if global token bucket is empty */
  1238. return connection_tls_continue_handshake(or_conn);
  1239. }
  1240. log_debug(LD_NET,
  1241. "%d: starting, inbuf_datalen %d (%d pending in tls object)."
  1242. " at_most %d.",
  1243. conn->s,(int)buf_datalen(conn->inbuf),
  1244. tor_tls_get_pending_bytes(or_conn->tls), at_most);
  1245. /* else open, or closing */
  1246. result = read_to_buf_tls(or_conn->tls, at_most, conn->inbuf);
  1247. switch (result) {
  1248. case TOR_TLS_CLOSE:
  1249. log_info(LD_NET,"TLS connection closed on read. Closing. "
  1250. "(Nickname %s, address %s",
  1251. or_conn->nickname ? or_conn->nickname : "not set",
  1252. conn->address);
  1253. return -1;
  1254. case TOR_TLS_ERROR:
  1255. log_info(LD_NET,"tls error. breaking (nickname %s, address %s).",
  1256. or_conn->nickname ? or_conn->nickname : "not set",
  1257. conn->address);
  1258. return -1;
  1259. case TOR_TLS_WANTWRITE:
  1260. connection_start_writing(conn);
  1261. return 0;
  1262. case TOR_TLS_WANTREAD: /* we're already reading */
  1263. case TOR_TLS_DONE: /* no data read, so nothing to process */
  1264. result = 0;
  1265. break; /* so we call bucket_decrement below */
  1266. default:
  1267. break;
  1268. }
  1269. pending = tor_tls_get_pending_bytes(or_conn->tls);
  1270. if (pending) {
  1271. /* XXXX If we have any pending bytes, read them now. This *can*
  1272. * take us over our read allotment, but really we shouldn't be
  1273. * believing that SSL bytes are the same as TCP bytes anyway. */
  1274. int r2 = read_to_buf_tls(or_conn->tls, pending, conn->inbuf);
  1275. if (r2<0) {
  1276. log_warn(LD_BUG, "Bug: apparently, reading pending bytes can fail.");
  1277. return -1;
  1278. } else {
  1279. result += r2;
  1280. }
  1281. }
  1282. } else {
  1283. int reached_eof = 0;
  1284. CONN_LOG_PROTECT(conn,
  1285. result = read_to_buf(conn->s, at_most, conn->inbuf, &reached_eof));
  1286. if (reached_eof)
  1287. conn->inbuf_reached_eof = 1;
  1288. // log_fn(LOG_DEBUG,"read_to_buf returned %d.",read_result);
  1289. if (result < 0)
  1290. return -1;
  1291. }
  1292. if (result > 0) { /* change *max_to_read */
  1293. *max_to_read = at_most - result;
  1294. }
  1295. if (result > 0 && !is_local_IP(conn->addr)) { /* remember it */
  1296. rep_hist_note_bytes_read(result, time(NULL));
  1297. connection_read_bucket_decrement(conn, result);
  1298. }
  1299. if (more_to_read && result == at_most) {
  1300. bytes_in_buf = buf_capacity(conn->inbuf) - buf_datalen(conn->inbuf);
  1301. tor_assert(bytes_in_buf < 1024);
  1302. at_most = more_to_read;
  1303. goto again;
  1304. }
  1305. /* Call even if result is 0, since the global read bucket may
  1306. * have reached 0 on a different conn, and this guy needs to
  1307. * know to stop reading. */
  1308. connection_consider_empty_buckets(conn);
  1309. return 0;
  1310. }
  1311. /** A pass-through to fetch_from_buf. */
  1312. int
  1313. connection_fetch_from_buf(char *string, size_t len, connection_t *conn)
  1314. {
  1315. return fetch_from_buf(string, len, conn->inbuf);
  1316. }
  1317. /** Return conn-\>outbuf_flushlen: how many bytes conn wants to flush
  1318. * from its outbuf. */
  1319. int
  1320. connection_wants_to_flush(connection_t *conn)
  1321. {
  1322. return conn->outbuf_flushlen;
  1323. }
  1324. /** Are there too many bytes on edge connection <b>conn</b>'s outbuf to
  1325. * send back a relay-level sendme yet? Return 1 if so, 0 if not. Used by
  1326. * connection_edge_consider_sending_sendme().
  1327. */
  1328. int
  1329. connection_outbuf_too_full(connection_t *conn)
  1330. {
  1331. return (conn->outbuf_flushlen > 10*CELL_PAYLOAD_SIZE);
  1332. }
  1333. /** Try to flush more bytes onto conn-\>s.
  1334. *
  1335. * This function gets called either from conn_write() in main.c
  1336. * when poll() has declared that conn wants to write, or below
  1337. * from connection_write_to_buf() when an entire TLS record is ready.
  1338. *
  1339. * Update conn-\>timestamp_lastwritten to now, and call flush_buf
  1340. * or flush_buf_tls appropriately. If it succeeds and there no more
  1341. * more bytes on conn->outbuf, then call connection_finished_flushing
  1342. * on it too.
  1343. *
  1344. * Mark the connection and return -1 if you want to close it, else
  1345. * return 0.
  1346. */
  1347. int
  1348. connection_handle_write(connection_t *conn)
  1349. {
  1350. int e;
  1351. socklen_t len=sizeof(e);
  1352. int result;
  1353. int max_to_write;
  1354. time_t now = time(NULL);
  1355. tor_assert(!connection_is_listener(conn));
  1356. if (conn->marked_for_close)
  1357. return 0; /* do nothing */
  1358. conn->timestamp_lastwritten = now;
  1359. /* Sometimes, "writable" means "connected". */
  1360. if (connection_state_is_connecting(conn)) {
  1361. if (getsockopt(conn->s, SOL_SOCKET, SO_ERROR, (void*)&e, &len) < 0) {
  1362. log_warn(LD_BUG,
  1363. "getsockopt() syscall failed?! Please report to tor-ops.");
  1364. if (CONN_IS_EDGE(conn))
  1365. connection_edge_end_errno(TO_EDGE_CONN(conn),
  1366. TO_EDGE_CONN(conn)->cpath_layer);
  1367. connection_mark_for_close(conn);
  1368. return -1;
  1369. }
  1370. if (e) {
  1371. /* some sort of error, but maybe just inprogress still */
  1372. if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
  1373. log_info(LD_NET,"in-progress connect failed. Removing.");
  1374. if (CONN_IS_EDGE(conn))
  1375. connection_edge_end_errno(TO_EDGE_CONN(conn),
  1376. TO_EDGE_CONN(conn)->cpath_layer);
  1377. connection_close_immediate(conn);
  1378. connection_mark_for_close(conn);
  1379. /* it's safe to pass OPs to router_set_status(), since it just
  1380. * ignores unrecognized routers
  1381. */
  1382. if (conn->type == CONN_TYPE_OR && !get_options()->HttpsProxy)
  1383. router_set_status(TO_OR_CONN(conn)->identity_digest, 0);
  1384. return -1;
  1385. } else {
  1386. return 0; /* no change, see if next time is better */
  1387. }
  1388. }
  1389. /* The connection is successful. */
  1390. if (connection_finished_connecting(conn)<0)
  1391. return -1;
  1392. }
  1393. max_to_write = connection_bucket_write_limit(conn);
  1394. if (connection_speaks_cells(conn) &&
  1395. conn->state > OR_CONN_STATE_PROXY_READING) {
  1396. or_connection_t *or_conn = TO_OR_CONN(conn);
  1397. if (conn->state == OR_CONN_STATE_HANDSHAKING) {
  1398. connection_stop_writing(conn);
  1399. if (connection_tls_continue_handshake(or_conn) < 0) {
  1400. /* Don't flush; connection is dead. */
  1401. connection_close_immediate(conn);
  1402. connection_mark_for_close(conn);
  1403. return -1;
  1404. }
  1405. return 0;
  1406. }
  1407. /* else open, or closing */
  1408. result = flush_buf_tls(or_conn->tls, conn->outbuf,
  1409. max_to_write, &conn->outbuf_flushlen);
  1410. switch (result) {
  1411. case TOR_TLS_ERROR:
  1412. case TOR_TLS_CLOSE:
  1413. log_info(LD_NET,result==TOR_TLS_ERROR?
  1414. "tls error. breaking.":"TLS connection closed on flush");
  1415. /* Don't flush; connection is dead. */
  1416. connection_close_immediate(conn);
  1417. connection_mark_for_close(conn);
  1418. return -1;
  1419. case TOR_TLS_WANTWRITE:
  1420. log_debug(LD_NET,"wanted write.");
  1421. /* we're already writing */
  1422. return 0;
  1423. case TOR_TLS_WANTREAD:
  1424. /* Make sure to avoid a loop if the receive buckets are empty. */
  1425. log_debug(LD_NET,"wanted read.");
  1426. if (!connection_is_reading(conn)) {
  1427. connection_stop_writing(conn);
  1428. conn->wants_to_write = 1;
  1429. /* we'll start reading again when the next second arrives,
  1430. * and then also start writing again.
  1431. */
  1432. }
  1433. /* else no problem, we're already reading */
  1434. return 0;
  1435. /* case TOR_TLS_DONE:
  1436. * for TOR_TLS_DONE, fall through to check if the flushlen
  1437. * is empty, so we can stop writing.
  1438. */
  1439. }
  1440. } else {
  1441. CONN_LOG_PROTECT(conn,
  1442. result = flush_buf(conn->s, conn->outbuf,
  1443. max_to_write, &conn->outbuf_flushlen));
  1444. if (result < 0) {
  1445. if (CONN_IS_EDGE(conn))
  1446. connection_edge_end_errno(TO_EDGE_CONN(conn),
  1447. TO_EDGE_CONN(conn)->cpath_layer);
  1448. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  1449. connection_mark_for_close(conn);
  1450. return -1;
  1451. }
  1452. }
  1453. if (result > 0) {
  1454. if (!is_local_IP(conn->addr)) { /* remember it */
  1455. rep_hist_note_bytes_written(result, time(NULL));
  1456. global_write_bucket -= result;
  1457. }
  1458. if (connection_flushed_some(conn) < 0)
  1459. connection_mark_for_close(conn);
  1460. }
  1461. if (!connection_wants_to_flush(conn)) { /* it's done flushing */
  1462. if (connection_finished_flushing(conn) < 0) {
  1463. /* already marked */
  1464. return -1;
  1465. }
  1466. }
  1467. return 0;
  1468. }
  1469. /* A controller event has just happened with such urgency that we
  1470. * need to write it onto controller <b>conn</b> immediately. */
  1471. void
  1472. _connection_controller_force_write(control_connection_t *control_conn)
  1473. {
  1474. /* XXX This is hideous code duplication, but raising it seems a little
  1475. * tricky for now. Think more about this one. We only call it for
  1476. * EVENT_ERR_MSG, so messing with buckets a little isn't such a big problem.
  1477. */
  1478. int result;
  1479. connection_t *conn;
  1480. tor_assert(control_conn);
  1481. conn = TO_CONN(control_conn);
  1482. if (conn->marked_for_close || conn->s < 0)
  1483. return;
  1484. CONN_LOG_PROTECT(conn,
  1485. result = flush_buf(conn->s, conn->outbuf,
  1486. conn->outbuf_flushlen, &conn->outbuf_flushlen));
  1487. if (result < 0) {
  1488. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  1489. connection_mark_for_close(conn);
  1490. return;
  1491. }
  1492. if (result > 0) {
  1493. if (!is_local_IP(conn->addr)) { /* remember it */
  1494. rep_hist_note_bytes_written(result, time(NULL));
  1495. global_write_bucket -= result;
  1496. }
  1497. if (connection_flushed_some(conn) < 0)
  1498. connection_mark_for_close(conn);
  1499. }
  1500. if (!connection_wants_to_flush(conn)) { /* it's done flushing */
  1501. if (connection_finished_flushing(conn) < 0) {
  1502. /* already marked */
  1503. return;
  1504. }
  1505. }
  1506. }
  1507. /** Append <b>len</b> bytes of <b>string</b> onto <b>conn</b>'s
  1508. * outbuf, and ask it to start writing.
  1509. */
  1510. void
  1511. connection_write_to_buf(const char *string, size_t len, connection_t *conn)
  1512. {
  1513. int r;
  1514. if (!len)
  1515. return;
  1516. /* if it's marked for close, only allow write if we mean to flush it */
  1517. if (conn->marked_for_close && !conn->hold_open_until_flushed)
  1518. return;
  1519. CONN_LOG_PROTECT(conn, r = write_to_buf(string, len, conn->outbuf));
  1520. if (r < 0) {
  1521. if (CONN_IS_EDGE(conn)) {
  1522. /* if it failed, it means we have our package/delivery windows set
  1523. wrong compared to our max outbuf size. close the whole circuit. */
  1524. log_warn(LD_NET,
  1525. "write_to_buf failed. Closing circuit (fd %d).", conn->s);
  1526. circuit_mark_for_close(circuit_get_by_edge_conn(TO_EDGE_CONN(conn)),
  1527. END_CIRC_REASON_INTERNAL);
  1528. } else {
  1529. log_warn(LD_NET,
  1530. "write_to_buf failed. Closing connection (fd %d).", conn->s);
  1531. connection_mark_for_close(conn);
  1532. }
  1533. return;
  1534. }
  1535. connection_start_writing(conn);
  1536. conn->outbuf_flushlen += len;
  1537. }
  1538. void
  1539. connection_write_to_buf_zlib(dir_connection_t *dir_conn,
  1540. const char *data, size_t data_len,
  1541. int done)
  1542. {
  1543. int r;
  1544. size_t old_datalen;
  1545. connection_t *conn;
  1546. if (!data_len)
  1547. return;
  1548. conn = TO_CONN(dir_conn);
  1549. /* if it's marked for close, only allow write if we mean to flush it */
  1550. if (conn->marked_for_close && !conn->hold_open_until_flushed)
  1551. return;
  1552. old_datalen = buf_datalen(conn->outbuf);
  1553. /* XXXX TOO much duplicate code! XXXX012NM */
  1554. CONN_LOG_PROTECT(conn, r = write_to_buf_zlib(
  1555. conn->outbuf, dir_conn->zlib_state,
  1556. data, data_len, done));
  1557. if (r < 0) {
  1558. log_warn(LD_NET,
  1559. "write_to_buf failed. Closing connection (fd %d).", conn->s);
  1560. connection_mark_for_close(conn);
  1561. return;
  1562. }
  1563. connection_start_writing(conn);
  1564. conn->outbuf_flushlen += buf_datalen(conn->outbuf) - old_datalen;
  1565. }
  1566. /** Return the conn to addr/port that has the most recent
  1567. * timestamp_created, or NULL if no such conn exists. */
  1568. or_connection_t *
  1569. connection_or_exact_get_by_addr_port(uint32_t addr, uint16_t port)
  1570. {
  1571. int i, n;
  1572. connection_t *conn;
  1573. or_connection_t *best=NULL;
  1574. connection_t **carray;
  1575. get_connection_array(&carray,&n);
  1576. for (i=0;i<n;i++) {
  1577. conn = carray[i];
  1578. if (conn->type == CONN_TYPE_OR &&
  1579. conn->addr == addr &&
  1580. conn->port == port &&
  1581. !conn->marked_for_close &&
  1582. (!best || best->_base.timestamp_created < conn->timestamp_created))
  1583. best = TO_OR_CONN(conn);
  1584. }
  1585. return best;
  1586. }
  1587. /** Return a connection with given type, address, port, and purpose;
  1588. * or NULL if no such connection exists. */
  1589. connection_t *
  1590. connection_get_by_type_addr_port_purpose(int type,
  1591. uint32_t addr, uint16_t port,
  1592. int purpose)
  1593. {
  1594. int i, n;
  1595. connection_t *conn;
  1596. connection_t **carray;
  1597. get_connection_array(&carray,&n);
  1598. for (i=0;i<n;i++) {
  1599. conn = carray[i];
  1600. if (conn->type == type &&
  1601. conn->addr == addr &&
  1602. conn->port == port &&
  1603. conn->purpose == purpose &&
  1604. !conn->marked_for_close)
  1605. return conn;
  1606. }
  1607. return NULL;
  1608. }
  1609. /** Return the connection with id <b>id</b> if it is not already marked for
  1610. * close.
  1611. */
  1612. edge_connection_t *
  1613. connection_get_by_global_id(uint32_t id)
  1614. {
  1615. int i, n;
  1616. connection_t *conn;
  1617. connection_t **carray;
  1618. get_connection_array(&carray,&n);
  1619. for (i=0;i<n;i++) {
  1620. conn = carray[i];
  1621. if (CONN_IS_EDGE(conn) && TO_EDGE_CONN(conn)->global_identifier == id) {
  1622. if (!conn->marked_for_close)
  1623. return TO_EDGE_CONN(conn);
  1624. else
  1625. return NULL;
  1626. }
  1627. }
  1628. return NULL;
  1629. }
  1630. /** Return a connection of type <b>type</b> that is not marked for close.
  1631. */
  1632. connection_t *
  1633. connection_get_by_type(int type)
  1634. {
  1635. int i, n;
  1636. connection_t *conn;
  1637. connection_t **carray;
  1638. get_connection_array(&carray,&n);
  1639. for (i=0;i<n;i++) {
  1640. conn = carray[i];
  1641. if (conn->type == type && !conn->marked_for_close)
  1642. return conn;
  1643. }
  1644. return NULL;
  1645. }
  1646. /** Return a connection of type <b>type</b> that is in state <b>state</b>,
  1647. * and that is not marked for close.
  1648. */
  1649. connection_t *
  1650. connection_get_by_type_state(int type, int state)
  1651. {
  1652. int i, n;
  1653. connection_t *conn;
  1654. connection_t **carray;
  1655. get_connection_array(&carray,&n);
  1656. for (i=0;i<n;i++) {
  1657. conn = carray[i];
  1658. if (conn->type == type && conn->state == state && !conn->marked_for_close)
  1659. return conn;
  1660. }
  1661. return NULL;
  1662. }
  1663. /** Return the connection of type <b>type</b> that is in state
  1664. * <b>state</b>, that was written to least recently, and that is not
  1665. * marked for close.
  1666. */
  1667. connection_t *
  1668. connection_get_by_type_state_lastwritten(int type, int state)
  1669. {
  1670. int i, n;
  1671. connection_t *conn, *best=NULL;
  1672. connection_t **carray;
  1673. get_connection_array(&carray,&n);
  1674. for (i=0;i<n;i++) {
  1675. conn = carray[i];
  1676. if (conn->type == type && conn->state == state && !conn->marked_for_close)
  1677. if (!best || conn->timestamp_lastwritten < best->timestamp_lastwritten)
  1678. best = conn;
  1679. }
  1680. return best;
  1681. }
  1682. /** Return a connection of type <b>type</b> that has rendquery equal
  1683. * to <b>rendquery</b>, and that is not marked for close. If state
  1684. * is non-zero, conn must be of that state too.
  1685. */
  1686. connection_t *
  1687. connection_get_by_type_state_rendquery(int type, int state,
  1688. const char *rendquery)
  1689. {
  1690. int i, n;
  1691. connection_t *conn;
  1692. connection_t **carray;
  1693. tor_assert(type == CONN_TYPE_DIR ||
  1694. type == CONN_TYPE_AP || type == CONN_TYPE_EXIT);
  1695. get_connection_array(&carray,&n);
  1696. for (i=0;i<n;i++) {
  1697. conn = carray[i];
  1698. if (conn->type == type &&
  1699. !conn->marked_for_close &&
  1700. (!state || state == conn->state)) {
  1701. if (type == CONN_TYPE_DIR &&
  1702. rend_cmp_service_ids(rendquery, TO_DIR_CONN(conn)->rend_query))
  1703. return conn;
  1704. else if (CONN_IS_EDGE(conn) &&
  1705. rend_cmp_service_ids(rendquery, TO_EDGE_CONN(conn)->rend_query))
  1706. return conn;
  1707. }
  1708. }
  1709. return NULL;
  1710. }
  1711. /** Return an open, non-marked connection of a given type and purpose, or NULL
  1712. * if no such connection exists. */
  1713. connection_t *
  1714. connection_get_by_type_purpose(int type, int purpose)
  1715. {
  1716. int i, n;
  1717. connection_t *conn;
  1718. connection_t **carray;
  1719. get_connection_array(&carray,&n);
  1720. for (i=0;i<n;i++) {
  1721. conn = carray[i];
  1722. if (conn->type == type &&
  1723. !conn->marked_for_close &&
  1724. (purpose == conn->purpose))
  1725. return conn;
  1726. }
  1727. return NULL;
  1728. }
  1729. /** Return 1 if <b>conn</b> is a listener conn, else return 0. */
  1730. int
  1731. connection_is_listener(connection_t *conn)
  1732. {
  1733. if (conn->type == CONN_TYPE_OR_LISTENER ||
  1734. conn->type == CONN_TYPE_AP_LISTENER ||
  1735. conn->type == CONN_TYPE_AP_TRANS_LISTENER ||
  1736. conn->type == CONN_TYPE_DIR_LISTENER ||
  1737. conn->type == CONN_TYPE_CONTROL_LISTENER)
  1738. return 1;
  1739. return 0;
  1740. }
  1741. /** Return 1 if <b>conn</b> is in state "open" and is not marked
  1742. * for close, else return 0.
  1743. */
  1744. int
  1745. connection_state_is_open(connection_t *conn)
  1746. {
  1747. tor_assert(conn);
  1748. if (conn->marked_for_close)
  1749. return 0;
  1750. if ((conn->type == CONN_TYPE_OR && conn->state == OR_CONN_STATE_OPEN) ||
  1751. (conn->type == CONN_TYPE_AP && conn->state == AP_CONN_STATE_OPEN) ||
  1752. (conn->type == CONN_TYPE_EXIT && conn->state == EXIT_CONN_STATE_OPEN) ||
  1753. (conn->type == CONN_TYPE_CONTROL &&
  1754. (conn->state == CONTROL_CONN_STATE_OPEN_V0 ||
  1755. conn->state == CONTROL_CONN_STATE_OPEN_V1)))
  1756. return 1;
  1757. return 0;
  1758. }
  1759. /** Return 1 if conn is in 'connecting' state, else return 0. */
  1760. int
  1761. connection_state_is_connecting(connection_t *conn)
  1762. {
  1763. tor_assert(conn);
  1764. if (conn->marked_for_close)
  1765. return 0;
  1766. switch (conn->type)
  1767. {
  1768. case CONN_TYPE_OR:
  1769. return conn->state == OR_CONN_STATE_CONNECTING;
  1770. case CONN_TYPE_EXIT:
  1771. return conn->state == EXIT_CONN_STATE_CONNECTING;
  1772. case CONN_TYPE_DIR:
  1773. return conn->state == DIR_CONN_STATE_CONNECTING;
  1774. }
  1775. return 0;
  1776. }
  1777. /** Alloocates a base64'ed authenticator for use in http or https
  1778. * auth, based on the input string <b>authenticator</b>. Returns it
  1779. * if success, else returns NULL. */
  1780. char *
  1781. alloc_http_authenticator(const char *authenticator)
  1782. {
  1783. /* an authenticator in Basic authentication
  1784. * is just the string "username:password" */
  1785. const int authenticator_length = strlen(authenticator);
  1786. /* The base64_encode function needs a minimum buffer length
  1787. * of 66 bytes. */
  1788. const int base64_authenticator_length = (authenticator_length/48+1)*66;
  1789. char *base64_authenticator = tor_malloc(base64_authenticator_length);
  1790. if (base64_encode(base64_authenticator, base64_authenticator_length,
  1791. authenticator, authenticator_length) < 0) {
  1792. tor_free(base64_authenticator); /* free and set to null */
  1793. } else {
  1794. /* remove extra \n at end of encoding */
  1795. base64_authenticator[strlen(base64_authenticator) - 1] = 0;
  1796. }
  1797. return base64_authenticator;
  1798. }
  1799. /** Given a socket handle, check whether the local address (sockname) of the
  1800. * socket is one that we've connected from before. If so, double-check
  1801. * whether our address has changed and we need to generate keys. If we do,
  1802. * call init_keys().
  1803. */
  1804. /* XXXX Handle IPv6, eventually. */
  1805. static void
  1806. client_check_address_changed(int sock)
  1807. {
  1808. uint32_t iface_ip, ip_out;
  1809. struct sockaddr_in out_addr;
  1810. socklen_t out_addr_len = sizeof(out_addr);
  1811. uint32_t *ip;
  1812. if (!last_interface_ip)
  1813. get_interface_address(LOG_INFO, &last_interface_ip);
  1814. if (!outgoing_addrs)
  1815. outgoing_addrs = smartlist_create();
  1816. if (getsockname(sock, (struct sockaddr*)&out_addr, &out_addr_len)<0) {
  1817. int e = tor_socket_errno(sock);
  1818. log_warn(LD_NET, "getsockname() to check for address change failed: %s",
  1819. tor_socket_strerror(e));
  1820. return;
  1821. }
  1822. /* Okay. If we've used this address previously, we're okay. */
  1823. ip_out = ntohl(out_addr.sin_addr.s_addr);
  1824. SMARTLIST_FOREACH(outgoing_addrs, uint32_t*, ip,
  1825. if (*ip == ip_out) return;
  1826. );
  1827. /* Uh-oh. We haven't connected from this address before. Has the interface
  1828. * address changed? */
  1829. if (get_interface_address(LOG_INFO, &iface_ip)<0)
  1830. return;
  1831. ip = tor_malloc(sizeof(uint32_t));
  1832. *ip = ip_out;
  1833. if (iface_ip == last_interface_ip) {
  1834. /* Nope, it hasn't changed. Add this address to the list. */
  1835. smartlist_add(outgoing_addrs, ip);
  1836. } else {
  1837. /* The interface changed. We're a client, so we need to regenerate our
  1838. * keys. First, reset the state. */
  1839. log(LOG_NOTICE, LD_NET, "Our IP has changed. Rotating keys...");
  1840. last_interface_ip = iface_ip;
  1841. SMARTLIST_FOREACH(outgoing_addrs, void*, ip, tor_free(ip));
  1842. smartlist_clear(outgoing_addrs);
  1843. smartlist_add(outgoing_addrs, ip);
  1844. /* Okay, now change our keys. */
  1845. init_keys(); /* XXXX NM return value-- safe to ignore? */
  1846. }
  1847. }
  1848. /** Process new bytes that have arrived on conn-\>inbuf.
  1849. *
  1850. * This function just passes conn to the connection-specific
  1851. * connection_*_process_inbuf() function. It also passes in
  1852. * package_partial if wanted.
  1853. */
  1854. static int
  1855. connection_process_inbuf(connection_t *conn, int package_partial)
  1856. {
  1857. tor_assert(conn);
  1858. switch (conn->type) {
  1859. case CONN_TYPE_OR:
  1860. return connection_or_process_inbuf(TO_OR_CONN(conn));
  1861. case CONN_TYPE_EXIT:
  1862. case CONN_TYPE_AP:
  1863. return connection_edge_process_inbuf(TO_EDGE_CONN(conn),
  1864. package_partial);
  1865. case CONN_TYPE_DIR:
  1866. return connection_dir_process_inbuf(TO_DIR_CONN(conn));
  1867. case CONN_TYPE_DNSWORKER:
  1868. return connection_dns_process_inbuf(conn);
  1869. case CONN_TYPE_CPUWORKER:
  1870. return connection_cpu_process_inbuf(conn);
  1871. case CONN_TYPE_CONTROL:
  1872. return connection_control_process_inbuf(TO_CONTROL_CONN(conn));
  1873. default:
  1874. log_err(LD_BUG,"Bug: got unexpected conn type %d.", conn->type);
  1875. tor_fragile_assert();
  1876. return -1;
  1877. }
  1878. }
  1879. /** Called whenever we've written data on a connection. */
  1880. static int
  1881. connection_flushed_some(connection_t *conn)
  1882. {
  1883. if (conn->type == CONN_TYPE_DIR &&
  1884. conn->state == DIR_CONN_STATE_SERVER_WRITING)
  1885. return connection_dirserv_flushed_some(TO_DIR_CONN(conn));
  1886. else
  1887. return 0;
  1888. }
  1889. /** We just finished flushing bytes from conn-\>outbuf, and there
  1890. * are no more bytes remaining.
  1891. *
  1892. * This function just passes conn to the connection-specific
  1893. * connection_*_finished_flushing() function.
  1894. */
  1895. static int
  1896. connection_finished_flushing(connection_t *conn)
  1897. {
  1898. tor_assert(conn);
  1899. // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
  1900. switch (conn->type) {
  1901. case CONN_TYPE_OR:
  1902. return connection_or_finished_flushing(TO_OR_CONN(conn));
  1903. case CONN_TYPE_AP:
  1904. case CONN_TYPE_EXIT:
  1905. return connection_edge_finished_flushing(TO_EDGE_CONN(conn));
  1906. case CONN_TYPE_DIR:
  1907. return connection_dir_finished_flushing(TO_DIR_CONN(conn));
  1908. case CONN_TYPE_DNSWORKER:
  1909. return connection_dns_finished_flushing(conn);
  1910. case CONN_TYPE_CPUWORKER:
  1911. return connection_cpu_finished_flushing(conn);
  1912. case CONN_TYPE_CONTROL:
  1913. return connection_control_finished_flushing(TO_CONTROL_CONN(conn));
  1914. default:
  1915. log_err(LD_BUG,"Bug: got unexpected conn type %d.", conn->type);
  1916. tor_fragile_assert();
  1917. return -1;
  1918. }
  1919. }
  1920. /** Called when our attempt to connect() to another server has just
  1921. * succeeded.
  1922. *
  1923. * This function just passes conn to the connection-specific
  1924. * connection_*_finished_connecting() function.
  1925. */
  1926. static int
  1927. connection_finished_connecting(connection_t *conn)
  1928. {
  1929. tor_assert(conn);
  1930. switch (conn->type)
  1931. {
  1932. case CONN_TYPE_OR:
  1933. return connection_or_finished_connecting(TO_OR_CONN(conn));
  1934. case CONN_TYPE_EXIT:
  1935. return connection_edge_finished_connecting(TO_EDGE_CONN(conn));
  1936. case CONN_TYPE_DIR:
  1937. return connection_dir_finished_connecting(TO_DIR_CONN(conn));
  1938. default:
  1939. log_err(LD_BUG,"Bug: got unexpected conn type %d.", conn->type);
  1940. tor_fragile_assert();
  1941. return -1;
  1942. }
  1943. }
  1944. /** Callback: invoked when a connection reaches an EOF event. */
  1945. static int
  1946. connection_reached_eof(connection_t *conn)
  1947. {
  1948. switch (conn->type) {
  1949. case CONN_TYPE_OR:
  1950. return connection_or_reached_eof(TO_OR_CONN(conn));
  1951. case CONN_TYPE_AP:
  1952. case CONN_TYPE_EXIT:
  1953. return connection_edge_reached_eof(TO_EDGE_CONN(conn));
  1954. case CONN_TYPE_DIR:
  1955. return connection_dir_reached_eof(TO_DIR_CONN(conn));
  1956. case CONN_TYPE_DNSWORKER:
  1957. return connection_dns_reached_eof(conn);
  1958. case CONN_TYPE_CPUWORKER:
  1959. return connection_cpu_reached_eof(conn);
  1960. case CONN_TYPE_CONTROL:
  1961. return connection_control_reached_eof(TO_CONTROL_CONN(conn));
  1962. default:
  1963. log_err(LD_BUG,"Bug: got unexpected conn type %d.", conn->type);
  1964. tor_fragile_assert();
  1965. return -1;
  1966. }
  1967. }
  1968. /** Verify that connection <b>conn</b> has all of its invariants
  1969. * correct. Trigger an assert if anything is invalid.
  1970. */
  1971. void
  1972. assert_connection_ok(connection_t *conn, time_t now)
  1973. {
  1974. (void) now; /* XXXX unused. */
  1975. tor_assert(conn);
  1976. tor_assert(conn->type >= _CONN_TYPE_MIN);
  1977. tor_assert(conn->type <= _CONN_TYPE_MAX);
  1978. switch (conn->type) {
  1979. case CONN_TYPE_OR:
  1980. tor_assert(conn->magic == OR_CONNECTION_MAGIC);
  1981. break;
  1982. case CONN_TYPE_AP:
  1983. case CONN_TYPE_EXIT:
  1984. tor_assert(conn->magic == EDGE_CONNECTION_MAGIC);
  1985. break;
  1986. case CONN_TYPE_DIR:
  1987. tor_assert(conn->magic == DIR_CONNECTION_MAGIC);
  1988. break;
  1989. case CONN_TYPE_CONTROL:
  1990. tor_assert(conn->magic == CONTROL_CONNECTION_MAGIC);
  1991. break;
  1992. default:
  1993. tor_assert(conn->magic == BASE_CONNECTION_MAGIC);
  1994. break;
  1995. }
  1996. if (conn->outbuf_flushlen > 0) {
  1997. tor_assert(connection_is_writing(conn) || conn->wants_to_write);
  1998. }
  1999. if (conn->hold_open_until_flushed)
  2000. tor_assert(conn->marked_for_close);
  2001. /* XXX check: wants_to_read, wants_to_write, s, conn_array_index,
  2002. * marked_for_close. */
  2003. /* buffers */
  2004. if (!connection_is_listener(conn)) {
  2005. assert_buf_ok(conn->inbuf);
  2006. assert_buf_ok(conn->outbuf);
  2007. }
  2008. /* XXX Fix this; no longer so.*/
  2009. #if 0
  2010. if (conn->type != CONN_TYPE_OR && conn->type != CONN_TYPE_DIR)
  2011. tor_assert(!conn->pkey);
  2012. /* pkey is set if we're a dir client, or if we're an OR in state OPEN
  2013. * connected to another OR.
  2014. */
  2015. #endif
  2016. if (conn->chosen_exit_optional) {
  2017. tor_assert(conn->type == CONN_TYPE_AP);
  2018. tor_assert((TO_EDGE_CONN(conn))->chosen_exit_name);
  2019. }
  2020. if (conn->type == CONN_TYPE_OR) {
  2021. or_connection_t *or_conn = TO_OR_CONN(conn);
  2022. if (conn->state == OR_CONN_STATE_OPEN) {
  2023. /* tor_assert(conn->bandwidth > 0); */
  2024. /* the above isn't necessarily true: if we just did a TLS
  2025. * handshake but we didn't recognize the other peer, or it
  2026. * gave a bad cert/etc, then we won't have assigned bandwidth,
  2027. * yet it will be open. -RD
  2028. */
  2029. // tor_assert(conn->receiver_bucket >= 0);
  2030. }
  2031. // tor_assert(conn->addr && conn->port);
  2032. tor_assert(conn->address);
  2033. if (conn->state > OR_CONN_STATE_PROXY_READING)
  2034. tor_assert(or_conn->tls);
  2035. }
  2036. if (CONN_IS_EDGE(conn)) {
  2037. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  2038. /* XXX unchecked: package window, deliver window. */
  2039. if (conn->type == CONN_TYPE_AP) {
  2040. tor_assert(edge_conn->socks_request);
  2041. if (conn->state == AP_CONN_STATE_OPEN) {
  2042. tor_assert(edge_conn->socks_request->has_finished);
  2043. if (!conn->marked_for_close) {
  2044. tor_assert(edge_conn->cpath_layer);
  2045. assert_cpath_layer_ok(edge_conn->cpath_layer);
  2046. }
  2047. }
  2048. }
  2049. if (conn->type == CONN_TYPE_EXIT) {
  2050. tor_assert(conn->purpose == EXIT_PURPOSE_CONNECT ||
  2051. conn->purpose == EXIT_PURPOSE_RESOLVE);
  2052. }
  2053. } else if (conn->type != CONN_TYPE_DIR) {
  2054. /* Purpose is only used for dir and exit types currently */
  2055. tor_assert(!conn->purpose);
  2056. }
  2057. switch (conn->type)
  2058. {
  2059. case CONN_TYPE_OR_LISTENER:
  2060. case CONN_TYPE_AP_LISTENER:
  2061. case CONN_TYPE_AP_TRANS_LISTENER:
  2062. case CONN_TYPE_DIR_LISTENER:
  2063. case CONN_TYPE_CONTROL_LISTENER:
  2064. tor_assert(conn->state == LISTENER_STATE_READY);
  2065. break;
  2066. case CONN_TYPE_OR:
  2067. tor_assert(conn->state >= _OR_CONN_STATE_MIN);
  2068. tor_assert(conn->state <= _OR_CONN_STATE_MAX);
  2069. tor_assert(TO_OR_CONN(conn)->n_circuits >= 0);
  2070. break;
  2071. case CONN_TYPE_EXIT:
  2072. tor_assert(conn->state >= _EXIT_CONN_STATE_MIN);
  2073. tor_assert(conn->state <= _EXIT_CONN_STATE_MAX);
  2074. tor_assert(conn->purpose >= _EXIT_PURPOSE_MIN);
  2075. tor_assert(conn->purpose <= _EXIT_PURPOSE_MAX);
  2076. break;
  2077. case CONN_TYPE_AP:
  2078. tor_assert(conn->state >= _AP_CONN_STATE_MIN);
  2079. tor_assert(conn->state <= _AP_CONN_STATE_MAX);
  2080. tor_assert(TO_EDGE_CONN(conn)->socks_request);
  2081. break;
  2082. case CONN_TYPE_DIR:
  2083. tor_assert(conn->state >= _DIR_CONN_STATE_MIN);
  2084. tor_assert(conn->state <= _DIR_CONN_STATE_MAX);
  2085. tor_assert(conn->purpose >= _DIR_PURPOSE_MIN);
  2086. tor_assert(conn->purpose <= _DIR_PURPOSE_MAX);
  2087. break;
  2088. case CONN_TYPE_DNSWORKER:
  2089. tor_assert(conn->state >= _DNSWORKER_STATE_MIN);
  2090. tor_assert(conn->state <= _DNSWORKER_STATE_MAX);
  2091. break;
  2092. case CONN_TYPE_CPUWORKER:
  2093. tor_assert(conn->state >= _CPUWORKER_STATE_MIN);
  2094. tor_assert(conn->state <= _CPUWORKER_STATE_MAX);
  2095. break;
  2096. case CONN_TYPE_CONTROL:
  2097. tor_assert(conn->state >= _CONTROL_CONN_STATE_MIN);
  2098. tor_assert(conn->state <= _CONTROL_CONN_STATE_MAX);
  2099. break;
  2100. default:
  2101. tor_assert(0);
  2102. }
  2103. }