connection.c 64 KB

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