connection.c 64 KB

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