connection.c 71 KB

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