connection.c 81 KB

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