connection.c 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075
  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 *addr;
  779. uint16_t port;
  780. if (! parse_addr_port(wanted->value, &addr, NULL, &port)) {
  781. if (! port)
  782. port = port_option;
  783. if (port == conn->port && !strcasecmp(addr, conn->address)) {
  784. line = wanted;
  785. break;
  786. }
  787. }
  788. });
  789. if (! line) {
  790. /* This one isn't configured. Close it. */
  791. log_fn(LOG_NOTICE, "Closing %s on %s:%d",
  792. conn_type_to_string(type), conn->address, conn->port);
  793. if (replaced_conns) {
  794. smartlist_add(replaced_conns, conn);
  795. } else {
  796. connection_close_immediate(conn);
  797. connection_mark_for_close(conn);
  798. }
  799. } else {
  800. /* It's configured; we don't need to launch it. */
  801. log_fn(LOG_INFO, "Already have %s on %s:%d",
  802. conn_type_to_string(type), conn->address, conn->port);
  803. smartlist_remove(launch, line);
  804. }
  805. }
  806. /* Now open all the listeners that are configured but not opened. */
  807. i = 0;
  808. SMARTLIST_FOREACH(launch, config_line_t *, cfg,
  809. {
  810. conn = connection_create_listener(cfg->value, (uint16_t) port_option,
  811. type);
  812. if (!conn) {
  813. i = -1;
  814. } else {
  815. if (new_conns)
  816. smartlist_add(new_conns, conn);
  817. }
  818. });
  819. if (free_launch_elts) {
  820. SMARTLIST_FOREACH(launch, config_line_t *, cfg,
  821. config_free_lines(cfg));
  822. }
  823. smartlist_free(launch);
  824. return i;
  825. }
  826. /** (Re)launch listeners for each port you should have open. If
  827. * <b>force</b> is true, close and relaunch all listeners. If <b>force</b>
  828. * is false, then only relaunch listeners when we have the wrong number of
  829. * connections for a given type.
  830. *
  831. * Add all old conns that should be closed to <b>replaced_conns</b>.
  832. * Add all new connections to <b>new_conns</b>.
  833. */
  834. int
  835. retry_all_listeners(int force, smartlist_t *replaced_conns,
  836. smartlist_t *new_conns)
  837. {
  838. or_options_t *options = get_options();
  839. if (server_mode(options) &&
  840. retry_listeners(CONN_TYPE_OR_LISTENER, options->ORBindAddress,
  841. options->ORPort, "0.0.0.0", force,
  842. replaced_conns, new_conns)<0)
  843. return -1;
  844. if (retry_listeners(CONN_TYPE_DIR_LISTENER, options->DirBindAddress,
  845. options->DirPort, "0.0.0.0", force,
  846. replaced_conns, new_conns)<0)
  847. return -1;
  848. if (retry_listeners(CONN_TYPE_AP_LISTENER, options->SocksBindAddress,
  849. options->SocksPort, "127.0.0.1", force,
  850. replaced_conns, new_conns)<0)
  851. return -1;
  852. if (retry_listeners(CONN_TYPE_CONTROL_LISTENER, NULL,
  853. options->ControlPort, "127.0.0.1", force,
  854. replaced_conns, new_conns)<0)
  855. return -1;
  856. return 0;
  857. }
  858. extern int global_read_bucket, global_write_bucket;
  859. /** How many bytes at most can we read onto this connection? */
  860. static int
  861. connection_bucket_read_limit(connection_t *conn)
  862. {
  863. int at_most;
  864. /* do a rudimentary round-robin so one circuit can't hog a connection */
  865. if (connection_speaks_cells(conn)) {
  866. at_most = 32*(CELL_NETWORK_SIZE);
  867. } else {
  868. at_most = 32*(RELAY_PAYLOAD_SIZE);
  869. }
  870. if (at_most > global_read_bucket)
  871. at_most = global_read_bucket;
  872. if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN)
  873. if (at_most > conn->receiver_bucket)
  874. at_most = conn->receiver_bucket;
  875. if (at_most < 0)
  876. return 0;
  877. return at_most;
  878. }
  879. /** We just read num_read onto conn. Decrement buckets appropriately. */
  880. static void
  881. connection_read_bucket_decrement(connection_t *conn, int num_read)
  882. {
  883. global_read_bucket -= num_read; //tor_assert(global_read_bucket >= 0);
  884. if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
  885. conn->receiver_bucket -= num_read; //tor_assert(conn->receiver_bucket >= 0);
  886. }
  887. }
  888. /** DOCDOC */
  889. static void
  890. connection_consider_empty_buckets(connection_t *conn)
  891. {
  892. if (global_read_bucket <= 0) {
  893. LOG_FN_CONN(conn, (LOG_DEBUG,"global bucket exhausted. Pausing."));
  894. conn->wants_to_read = 1;
  895. connection_stop_reading(conn);
  896. return;
  897. }
  898. if (connection_speaks_cells(conn) &&
  899. conn->state == OR_CONN_STATE_OPEN &&
  900. conn->receiver_bucket <= 0) {
  901. LOG_FN_CONN(conn, (LOG_DEBUG,"receiver bucket exhausted. Pausing."));
  902. conn->wants_to_read = 1;
  903. connection_stop_reading(conn);
  904. }
  905. }
  906. /** Initialize the global read bucket to options->BandwidthBurst,
  907. * and current_time to the current time. */
  908. void
  909. connection_bucket_init(void)
  910. {
  911. or_options_t *options = get_options();
  912. global_read_bucket = (int)options->BandwidthBurst; /* start it at max traffic */
  913. global_write_bucket = (int)options->BandwidthBurst; /* start it at max traffic */
  914. }
  915. /** A second has rolled over; increment buckets appropriately. */
  916. void
  917. connection_bucket_refill(struct timeval *now)
  918. {
  919. int i, n;
  920. connection_t *conn;
  921. connection_t **carray;
  922. or_options_t *options = get_options();
  923. /* refill the global buckets */
  924. if (global_read_bucket < (int)options->BandwidthBurst) {
  925. global_read_bucket += (int)options->BandwidthRate;
  926. log_fn(LOG_DEBUG,"global_read_bucket now %d.", global_read_bucket);
  927. }
  928. if (global_write_bucket < (int)options->BandwidthBurst) {
  929. global_write_bucket += (int)options->BandwidthRate;
  930. log_fn(LOG_DEBUG,"global_write_bucket now %d.", global_write_bucket);
  931. }
  932. /* refill the per-connection buckets */
  933. get_connection_array(&carray,&n);
  934. for (i=0;i<n;i++) {
  935. conn = carray[i];
  936. if (connection_receiver_bucket_should_increase(conn)) {
  937. conn->receiver_bucket = conn->bandwidth;
  938. //log_fn(LOG_DEBUG,"Receiver bucket %d now %d.", i, conn->receiver_bucket);
  939. }
  940. if (conn->wants_to_read == 1 /* it's marked to turn reading back on now */
  941. && global_read_bucket > 0 /* and we're allowed to read */
  942. && global_write_bucket > 0 /* and we're allowed to write (XXXX,
  943. * not the best place to check this.) */
  944. && (!connection_speaks_cells(conn) ||
  945. conn->state != OR_CONN_STATE_OPEN ||
  946. conn->receiver_bucket > 0)) {
  947. /* and either a non-cell conn or a cell conn with non-empty bucket */
  948. LOG_FN_CONN(conn, (LOG_DEBUG,"waking up conn (fd %d)",conn->s));
  949. conn->wants_to_read = 0;
  950. connection_start_reading(conn);
  951. if (conn->wants_to_write == 1) {
  952. conn->wants_to_write = 0;
  953. connection_start_writing(conn);
  954. }
  955. }
  956. }
  957. }
  958. /** Is the receiver bucket for connection <b>conn</b> low enough that we
  959. * should add another pile of tokens to it?
  960. */
  961. static int
  962. connection_receiver_bucket_should_increase(connection_t *conn)
  963. {
  964. tor_assert(conn);
  965. if (!connection_speaks_cells(conn))
  966. return 0; /* edge connections don't use receiver_buckets */
  967. if (conn->state != OR_CONN_STATE_OPEN)
  968. return 0; /* only open connections play the rate limiting game */
  969. if (conn->receiver_bucket >= conn->bandwidth)
  970. return 0;
  971. return 1;
  972. }
  973. /** Read bytes from conn-\>s and process them.
  974. *
  975. * This function gets called from conn_read() in main.c, either
  976. * when poll() has declared that conn wants to read, or (for OR conns)
  977. * when there are pending TLS bytes.
  978. *
  979. * It calls connection_read_to_buf() to bring in any new bytes,
  980. * and then calls connection_process_inbuf() to process them.
  981. *
  982. * Mark the connection and return -1 if you want to close it, else
  983. * return 0.
  984. */
  985. int
  986. connection_handle_read(connection_t *conn)
  987. {
  988. int max_to_read=-1, try_to_read;
  989. if (conn->marked_for_close)
  990. return 0; /* do nothing */
  991. conn->timestamp_lastread = time(NULL);
  992. switch (conn->type) {
  993. case CONN_TYPE_OR_LISTENER:
  994. return connection_handle_listener_read(conn, CONN_TYPE_OR);
  995. case CONN_TYPE_AP_LISTENER:
  996. return connection_handle_listener_read(conn, CONN_TYPE_AP);
  997. case CONN_TYPE_DIR_LISTENER:
  998. return connection_handle_listener_read(conn, CONN_TYPE_DIR);
  999. case CONN_TYPE_CONTROL_LISTENER:
  1000. return connection_handle_listener_read(conn, CONN_TYPE_CONTROL);
  1001. }
  1002. loop_again:
  1003. try_to_read = max_to_read;
  1004. tor_assert(!conn->marked_for_close);
  1005. if (connection_read_to_buf(conn, &max_to_read) < 0) {
  1006. /* There's a read error; kill the connection.*/
  1007. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  1008. if (CONN_IS_EDGE(conn)) {
  1009. connection_edge_end_errno(conn, conn->cpath_layer);
  1010. if (conn->socks_request) /* broken, so don't send a socks reply back */
  1011. conn->socks_request->has_finished = 1;
  1012. }
  1013. connection_mark_for_close(conn);
  1014. return -1;
  1015. }
  1016. if (CONN_IS_EDGE(conn) &&
  1017. try_to_read != max_to_read) {
  1018. /* instruct it not to try to package partial cells. */
  1019. if (connection_process_inbuf(conn, 0) < 0) {
  1020. return -1;
  1021. }
  1022. if (!conn->marked_for_close &&
  1023. connection_is_reading(conn) &&
  1024. !conn->inbuf_reached_eof &&
  1025. max_to_read > 0)
  1026. goto loop_again; /* try reading again, in case more is here now */
  1027. }
  1028. /* one last try, packaging partial cells and all. */
  1029. if (!conn->marked_for_close &&
  1030. connection_process_inbuf(conn, 1) < 0) {
  1031. return -1;
  1032. }
  1033. if (!conn->marked_for_close &&
  1034. conn->inbuf_reached_eof &&
  1035. connection_reached_eof(conn) < 0) {
  1036. return -1;
  1037. }
  1038. return 0;
  1039. }
  1040. /** Pull in new bytes from conn-\>s onto conn-\>inbuf, either
  1041. * directly or via TLS. Reduce the token buckets by the number of
  1042. * bytes read.
  1043. *
  1044. * If *max_to_read is -1, then decide it ourselves, else go with the
  1045. * value passed to us. When returning, if it's changed, subtract the
  1046. * number of bytes we read from *max_to_read.
  1047. *
  1048. * Return -1 if we want to break conn, else return 0.
  1049. */
  1050. static int
  1051. connection_read_to_buf(connection_t *conn, int *max_to_read)
  1052. {
  1053. int result, at_most = *max_to_read;
  1054. size_t bytes_in_buf, more_to_read;
  1055. if (at_most == -1) { /* we need to initialize it */
  1056. /* how many bytes are we allowed to read? */
  1057. at_most = connection_bucket_read_limit(conn);
  1058. }
  1059. bytes_in_buf = buf_capacity(conn->inbuf) - buf_datalen(conn->inbuf);
  1060. again:
  1061. if ((size_t)at_most > bytes_in_buf && bytes_in_buf >= 1024) {
  1062. more_to_read = at_most - bytes_in_buf;
  1063. at_most = bytes_in_buf;
  1064. } else {
  1065. more_to_read = 0;
  1066. }
  1067. if (connection_speaks_cells(conn) && conn->state > OR_CONN_STATE_PROXY_READING) {
  1068. int pending;
  1069. if (conn->state == OR_CONN_STATE_HANDSHAKING) {
  1070. /* continue handshaking even if global token bucket is empty */
  1071. return connection_tls_continue_handshake(conn);
  1072. }
  1073. log_fn(LOG_DEBUG,"%d: starting, inbuf_datalen %d (%d pending in tls object). at_most %d.",
  1074. conn->s,(int)buf_datalen(conn->inbuf),tor_tls_get_pending_bytes(conn->tls), at_most);
  1075. /* else open, or closing */
  1076. result = read_to_buf_tls(conn->tls, at_most, conn->inbuf);
  1077. switch (result) {
  1078. case TOR_TLS_CLOSE:
  1079. log_fn(LOG_INFO,"TLS connection closed on read. Closing. (Nickname %s, address %s",
  1080. conn->nickname ? conn->nickname : "not set", conn->address);
  1081. return -1;
  1082. case TOR_TLS_ERROR:
  1083. log_fn(LOG_INFO,"tls error. breaking (nickname %s, address %s).",
  1084. conn->nickname ? conn->nickname : "not set", conn->address);
  1085. return -1;
  1086. case TOR_TLS_WANTWRITE:
  1087. connection_start_writing(conn);
  1088. return 0;
  1089. case TOR_TLS_WANTREAD: /* we're already reading */
  1090. case TOR_TLS_DONE: /* no data read, so nothing to process */
  1091. result = 0;
  1092. break; /* so we call bucket_decrement below */
  1093. default:
  1094. break;
  1095. }
  1096. pending = tor_tls_get_pending_bytes(conn->tls);
  1097. if (pending) {
  1098. /* XXXX If we have any pending bytes, read them now. This *can*
  1099. * take us over our read allotment, but really we shouldn't be
  1100. * believing that SSL bytes are the same as TCP bytes anyway. */
  1101. int r2 = read_to_buf_tls(conn->tls, pending, conn->inbuf);
  1102. if (r2<0) {
  1103. log_fn(LOG_WARN, "Bug: apparently, reading pending bytes can fail.");
  1104. return -1;
  1105. } else {
  1106. result += r2;
  1107. }
  1108. }
  1109. } else {
  1110. CONN_LOG_PROTECT(conn,
  1111. result = read_to_buf(conn->s, at_most, conn->inbuf,
  1112. &conn->inbuf_reached_eof));
  1113. // log_fn(LOG_DEBUG,"read_to_buf returned %d.",read_result);
  1114. if (result < 0)
  1115. return -1;
  1116. }
  1117. if (result > 0) { /* change *max_to_read */
  1118. *max_to_read = at_most - result;
  1119. }
  1120. if (result > 0 && !is_local_IP(conn->addr)) { /* remember it */
  1121. rep_hist_note_bytes_read(result, time(NULL));
  1122. connection_read_bucket_decrement(conn, result);
  1123. }
  1124. if (more_to_read && result == at_most) {
  1125. bytes_in_buf = buf_capacity(conn->inbuf) - buf_datalen(conn->inbuf);
  1126. tor_assert(bytes_in_buf < 1024);
  1127. at_most = more_to_read;
  1128. goto again;
  1129. }
  1130. /* Call even if result is 0, since the global read bucket may
  1131. * have reached 0 on a different conn, and this guy needs to
  1132. * know to stop reading. */
  1133. connection_consider_empty_buckets(conn);
  1134. return 0;
  1135. }
  1136. /** A pass-through to fetch_from_buf. */
  1137. int
  1138. connection_fetch_from_buf(char *string, size_t len, connection_t *conn)
  1139. {
  1140. return fetch_from_buf(string, len, conn->inbuf);
  1141. }
  1142. /** Return conn-\>outbuf_flushlen: how many bytes conn wants to flush
  1143. * from its outbuf. */
  1144. int
  1145. connection_wants_to_flush(connection_t *conn)
  1146. {
  1147. return conn->outbuf_flushlen;
  1148. }
  1149. /** Are there too many bytes on edge connection <b>conn</b>'s outbuf to
  1150. * send back a relay-level sendme yet? Return 1 if so, 0 if not. Used by
  1151. * connection_edge_consider_sending_sendme().
  1152. */
  1153. int
  1154. connection_outbuf_too_full(connection_t *conn)
  1155. {
  1156. return (conn->outbuf_flushlen > 10*CELL_PAYLOAD_SIZE);
  1157. }
  1158. /** Try to flush more bytes onto conn-\>s.
  1159. *
  1160. * This function gets called either from conn_write() in main.c
  1161. * when poll() has declared that conn wants to write, or below
  1162. * from connection_write_to_buf() when an entire TLS record is ready.
  1163. *
  1164. * Update conn-\>timestamp_lastwritten to now, and call flush_buf
  1165. * or flush_buf_tls appropriately. If it succeeds and there no more
  1166. * more bytes on conn->outbuf, then call connection_finished_flushing
  1167. * on it too.
  1168. *
  1169. * Mark the connection and return -1 if you want to close it, else
  1170. * return 0.
  1171. */
  1172. int
  1173. connection_handle_write(connection_t *conn)
  1174. {
  1175. int e;
  1176. socklen_t len=sizeof(e);
  1177. int result;
  1178. time_t now = time(NULL);
  1179. tor_assert(!connection_is_listener(conn));
  1180. if (conn->marked_for_close)
  1181. return 0; /* do nothing */
  1182. conn->timestamp_lastwritten = now;
  1183. /* Sometimes, "writable" means "connected". */
  1184. if (connection_state_is_connecting(conn)) {
  1185. if (getsockopt(conn->s, SOL_SOCKET, SO_ERROR, (void*)&e, &len) < 0) {
  1186. log_fn(LOG_WARN,"getsockopt() syscall failed?! Please report to tor-ops.");
  1187. if (CONN_IS_EDGE(conn))
  1188. connection_edge_end_errno(conn, conn->cpath_layer);
  1189. connection_mark_for_close(conn);
  1190. return -1;
  1191. }
  1192. if (e) {
  1193. /* some sort of error, but maybe just inprogress still */
  1194. if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
  1195. log_fn(LOG_INFO,"in-progress connect failed. Removing.");
  1196. if (CONN_IS_EDGE(conn))
  1197. connection_edge_end_errno(conn, conn->cpath_layer);
  1198. connection_close_immediate(conn);
  1199. connection_mark_for_close(conn);
  1200. /* it's safe to pass OPs to router_mark_as_down(), since it just
  1201. * ignores unrecognized routers
  1202. */
  1203. if (conn->type == CONN_TYPE_OR && !get_options()->HttpsProxy)
  1204. router_mark_as_down(conn->identity_digest);
  1205. return -1;
  1206. } else {
  1207. return 0; /* no change, see if next time is better */
  1208. }
  1209. }
  1210. /* The connection is successful. */
  1211. if (connection_finished_connecting(conn)<0)
  1212. return -1;
  1213. }
  1214. if (connection_speaks_cells(conn) && conn->state > OR_CONN_STATE_PROXY_READING) {
  1215. if (conn->state == OR_CONN_STATE_HANDSHAKING) {
  1216. connection_stop_writing(conn);
  1217. if (connection_tls_continue_handshake(conn) < 0) {
  1218. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  1219. connection_mark_for_close(conn);
  1220. return -1;
  1221. }
  1222. return 0;
  1223. }
  1224. /* else open, or closing */
  1225. result = flush_buf_tls(conn->tls, conn->outbuf, &conn->outbuf_flushlen);
  1226. switch (result) {
  1227. case TOR_TLS_ERROR:
  1228. case TOR_TLS_CLOSE:
  1229. log_fn(LOG_INFO,result==TOR_TLS_ERROR?
  1230. "tls error. breaking.":"TLS connection closed on flush");
  1231. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  1232. connection_mark_for_close(conn);
  1233. return -1;
  1234. case TOR_TLS_WANTWRITE:
  1235. log_fn(LOG_DEBUG,"wanted write.");
  1236. /* we're already writing */
  1237. return 0;
  1238. case TOR_TLS_WANTREAD:
  1239. /* Make sure to avoid a loop if the receive buckets are empty. */
  1240. log_fn(LOG_DEBUG,"wanted read.");
  1241. if (!connection_is_reading(conn)) {
  1242. connection_stop_writing(conn);
  1243. conn->wants_to_write = 1;
  1244. /* we'll start reading again when the next second arrives,
  1245. * and then also start writing again.
  1246. */
  1247. }
  1248. /* else no problem, we're already reading */
  1249. return 0;
  1250. /* case TOR_TLS_DONE:
  1251. * for TOR_TLS_DONE, fall through to check if the flushlen
  1252. * is empty, so we can stop writing.
  1253. */
  1254. }
  1255. } else {
  1256. CONN_LOG_PROTECT(conn,
  1257. result = flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen));
  1258. if (result < 0) {
  1259. if (CONN_IS_EDGE(conn))
  1260. connection_edge_end_errno(conn, conn->cpath_layer);
  1261. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  1262. connection_mark_for_close(conn);
  1263. return -1;
  1264. }
  1265. }
  1266. if (result > 0 && !is_local_IP(conn->addr)) { /* remember it */
  1267. rep_hist_note_bytes_written(result, now);
  1268. global_write_bucket -= result;
  1269. }
  1270. if (!connection_wants_to_flush(conn)) { /* it's done flushing */
  1271. if (connection_finished_flushing(conn) < 0) {
  1272. /* already marked */
  1273. return -1;
  1274. }
  1275. }
  1276. return 0;
  1277. }
  1278. /* DOCDOC */
  1279. void
  1280. _connection_controller_force_write(connection_t *conn)
  1281. {
  1282. /* XXX This is hideous code duplication, but raising it seems a little
  1283. * tricky for now. Think more about this one. We only call it for
  1284. * EVENT_ERR_MSG, so messing with buckets a little isn't such a big problem.
  1285. */
  1286. int result;
  1287. tor_assert(conn);
  1288. tor_assert(!conn->tls);
  1289. tor_assert(conn->type == CONN_TYPE_CONTROL);
  1290. if (conn->marked_for_close || conn->s < 0)
  1291. return;
  1292. CONN_LOG_PROTECT(conn,
  1293. result = flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen));
  1294. if (result < 0) {
  1295. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  1296. connection_mark_for_close(conn);
  1297. return;
  1298. }
  1299. if (result > 0 && !is_local_IP(conn->addr)) { /* remember it */
  1300. rep_hist_note_bytes_written(result, time(NULL));
  1301. global_write_bucket -= result;
  1302. }
  1303. if (!connection_wants_to_flush(conn)) { /* it's done flushing */
  1304. if (connection_finished_flushing(conn) < 0) {
  1305. /* already marked */
  1306. return;
  1307. }
  1308. }
  1309. }
  1310. /** Append <b>len</b> bytes of <b>string</b> onto <b>conn</b>'s
  1311. * outbuf, and ask it to start writing.
  1312. */
  1313. void
  1314. connection_write_to_buf(const char *string, size_t len, connection_t *conn)
  1315. {
  1316. int r;
  1317. if (!len)
  1318. return;
  1319. /* if it's marked for close, only allow write if we mean to flush it */
  1320. if (conn->marked_for_close && !conn->hold_open_until_flushed)
  1321. return;
  1322. CONN_LOG_PROTECT(conn, r = write_to_buf(string, len, conn->outbuf));
  1323. if (r < 0) {
  1324. if (CONN_IS_EDGE(conn)) {
  1325. /* if it failed, it means we have our package/delivery windows set
  1326. wrong compared to our max outbuf size. close the whole circuit. */
  1327. log_fn(LOG_WARN,"write_to_buf failed. Closing circuit (fd %d).", conn->s);
  1328. circuit_mark_for_close(circuit_get_by_edge_conn(conn));
  1329. } else {
  1330. log_fn(LOG_WARN,"write_to_buf failed. Closing connection (fd %d).", conn->s);
  1331. connection_mark_for_close(conn);
  1332. }
  1333. return;
  1334. }
  1335. connection_start_writing(conn);
  1336. conn->outbuf_flushlen += len;
  1337. }
  1338. /** Return the conn to addr/port that has the most recent
  1339. * timestamp_created, or NULL if no such conn exists. */
  1340. connection_t *
  1341. connection_or_exact_get_by_addr_port(uint32_t addr, uint16_t port)
  1342. {
  1343. int i, n;
  1344. connection_t *conn, *best=NULL;
  1345. connection_t **carray;
  1346. get_connection_array(&carray,&n);
  1347. for (i=0;i<n;i++) {
  1348. conn = carray[i];
  1349. if (conn->type == CONN_TYPE_OR &&
  1350. conn->addr == addr &&
  1351. conn->port == port &&
  1352. !conn->marked_for_close &&
  1353. (!best || best->timestamp_created < conn->timestamp_created))
  1354. best = conn;
  1355. }
  1356. return best;
  1357. }
  1358. /** Return a connection with give type, address, port, and purpose or NULL if
  1359. * no such connection exists. */
  1360. connection_t *
  1361. connection_get_by_type_addr_port_purpose(int type, uint32_t addr, uint16_t port,
  1362. int purpose)
  1363. {
  1364. int i, n;
  1365. connection_t *conn;
  1366. connection_t **carray;
  1367. get_connection_array(&carray,&n);
  1368. for (i=0;i<n;i++) {
  1369. conn = carray[i];
  1370. if (conn->type == type &&
  1371. conn->addr == addr &&
  1372. conn->port == port &&
  1373. conn->purpose == purpose &&
  1374. !conn->marked_for_close)
  1375. return conn;
  1376. }
  1377. return NULL;
  1378. }
  1379. connection_t *
  1380. connection_get_by_identity_digest(const char *digest, int type)
  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 != type)
  1389. continue;
  1390. if (!memcmp(conn->identity_digest, digest, DIGEST_LEN) &&
  1391. !conn->marked_for_close &&
  1392. (!best || best->timestamp_created < conn->timestamp_created))
  1393. best = conn;
  1394. }
  1395. return best;
  1396. }
  1397. /** Return the connection with id <b>id</b> if it is not already
  1398. * marked for close.
  1399. */
  1400. connection_t *
  1401. connection_get_by_global_id(uint32_t id)
  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->global_identifier == id) {
  1410. if (!conn->marked_for_close)
  1411. return conn;
  1412. else
  1413. return NULL;
  1414. }
  1415. }
  1416. return NULL;
  1417. }
  1418. /** Return a connection of type <b>type</b> that is not marked for
  1419. * close.
  1420. */
  1421. connection_t *
  1422. connection_get_by_type(int type)
  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->type == type && !conn->marked_for_close)
  1431. return conn;
  1432. }
  1433. return NULL;
  1434. }
  1435. /** Return a connection of type <b>type</b> that is in state <b>state</b>,
  1436. * and that is not marked for close.
  1437. */
  1438. connection_t *
  1439. connection_get_by_type_state(int type, int state)
  1440. {
  1441. int i, n;
  1442. connection_t *conn;
  1443. connection_t **carray;
  1444. get_connection_array(&carray,&n);
  1445. for (i=0;i<n;i++) {
  1446. conn = carray[i];
  1447. if (conn->type == type && conn->state == state && !conn->marked_for_close)
  1448. return conn;
  1449. }
  1450. return NULL;
  1451. }
  1452. /** Return the connection of type <b>type</b> that is in state
  1453. * <b>state</b>, that was written to least recently, and that is not
  1454. * marked for close.
  1455. */
  1456. connection_t *
  1457. connection_get_by_type_state_lastwritten(int type, int state)
  1458. {
  1459. int i, n;
  1460. connection_t *conn, *best=NULL;
  1461. connection_t **carray;
  1462. get_connection_array(&carray,&n);
  1463. for (i=0;i<n;i++) {
  1464. conn = carray[i];
  1465. if (conn->type == type && conn->state == state && !conn->marked_for_close)
  1466. if (!best || conn->timestamp_lastwritten < best->timestamp_lastwritten)
  1467. best = conn;
  1468. }
  1469. return best;
  1470. }
  1471. /** Return a connection of type <b>type</b> that has rendquery equal
  1472. * to <b>rendquery</b>, and that is not marked for close. If state
  1473. * is non-zero, conn must be of that state too.
  1474. */
  1475. connection_t *
  1476. connection_get_by_type_state_rendquery(int type, int state, const char *rendquery) {
  1477. int i, n;
  1478. connection_t *conn;
  1479. connection_t **carray;
  1480. get_connection_array(&carray,&n);
  1481. for (i=0;i<n;i++) {
  1482. conn = carray[i];
  1483. if (conn->type == type &&
  1484. !conn->marked_for_close &&
  1485. (!state || state == conn->state) &&
  1486. !rend_cmp_service_ids(rendquery, conn->rend_query))
  1487. return conn;
  1488. }
  1489. return NULL;
  1490. }
  1491. /** Return an open, non-marked connection of a given type and purpose, or NULL
  1492. * if no such connection exists. */
  1493. connection_t *
  1494. connection_get_by_type_purpose(int type, int purpose)
  1495. {
  1496. int i, n;
  1497. connection_t *conn;
  1498. connection_t **carray;
  1499. get_connection_array(&carray,&n);
  1500. for (i=0;i<n;i++) {
  1501. conn = carray[i];
  1502. if (conn->type == type &&
  1503. !conn->marked_for_close &&
  1504. (purpose == conn->purpose))
  1505. return conn;
  1506. }
  1507. return NULL;
  1508. }
  1509. /** Return 1 if <b>conn</b> is a listener conn, else return 0. */
  1510. int
  1511. connection_is_listener(connection_t *conn)
  1512. {
  1513. if (conn->type == CONN_TYPE_OR_LISTENER ||
  1514. conn->type == CONN_TYPE_AP_LISTENER ||
  1515. conn->type == CONN_TYPE_DIR_LISTENER ||
  1516. conn->type == CONN_TYPE_CONTROL_LISTENER)
  1517. return 1;
  1518. return 0;
  1519. }
  1520. /** Return 1 if <b>conn</b> is in state "open" and is not marked
  1521. * for close, else return 0.
  1522. */
  1523. int
  1524. connection_state_is_open(connection_t *conn)
  1525. {
  1526. tor_assert(conn);
  1527. if (conn->marked_for_close)
  1528. return 0;
  1529. if ((conn->type == CONN_TYPE_OR && conn->state == OR_CONN_STATE_OPEN) ||
  1530. (conn->type == CONN_TYPE_AP && conn->state == AP_CONN_STATE_OPEN) ||
  1531. (conn->type == CONN_TYPE_EXIT && conn->state == EXIT_CONN_STATE_OPEN) ||
  1532. (conn->type == CONN_TYPE_CONTROL &&
  1533. (conn->state == CONTROL_CONN_STATE_OPEN_V0 ||
  1534. conn->state == CONTROL_CONN_STATE_OPEN_V1)))
  1535. return 1;
  1536. return 0;
  1537. }
  1538. /** Return 1 if conn is in 'connecting' state, else return 0. */
  1539. int
  1540. connection_state_is_connecting(connection_t *conn)
  1541. {
  1542. tor_assert(conn);
  1543. if (conn->marked_for_close)
  1544. return 0;
  1545. switch (conn->type)
  1546. {
  1547. case CONN_TYPE_OR:
  1548. return conn->state == OR_CONN_STATE_CONNECTING;
  1549. case CONN_TYPE_EXIT:
  1550. return conn->state == EXIT_CONN_STATE_CONNECTING;
  1551. case CONN_TYPE_DIR:
  1552. return conn->state == DIR_CONN_STATE_CONNECTING;
  1553. }
  1554. return 0;
  1555. }
  1556. /** Write a destroy cell with circ ID <b>circ_id</b> onto OR connection
  1557. * <b>conn</b>.
  1558. *
  1559. * Return 0.
  1560. */
  1561. int
  1562. connection_send_destroy(uint16_t circ_id, connection_t *conn)
  1563. {
  1564. cell_t cell;
  1565. tor_assert(conn);
  1566. tor_assert(connection_speaks_cells(conn));
  1567. memset(&cell, 0, sizeof(cell_t));
  1568. cell.circ_id = circ_id;
  1569. cell.command = CELL_DESTROY;
  1570. log_fn(LOG_INFO,"Sending destroy (circID %d).", circ_id);
  1571. connection_or_write_cell_to_buf(&cell, conn);
  1572. return 0;
  1573. }
  1574. /** Alloocates a base64'ed authenticator for use in http or https
  1575. * auth, based on the input string <b>authenticator</b>. Returns it
  1576. * if success, else returns NULL. */
  1577. char *
  1578. alloc_http_authenticator(const char *authenticator)
  1579. {
  1580. /* an authenticator in Basic authentication
  1581. * is just the string "username:password" */
  1582. const int authenticator_length = strlen(authenticator);
  1583. /* The base64_encode function needs a minimum buffer length
  1584. * of 66 bytes. */
  1585. const int base64_authenticator_length = (authenticator_length/48+1)*66;
  1586. char *base64_authenticator = tor_malloc(base64_authenticator_length);
  1587. if (base64_encode(base64_authenticator, base64_authenticator_length,
  1588. authenticator, authenticator_length) < 0) {
  1589. tor_free(base64_authenticator); /* free and set to null */
  1590. } else {
  1591. /* remove extra \n at end of encoding */
  1592. base64_authenticator[strlen(base64_authenticator) - 1] = 0;
  1593. }
  1594. return base64_authenticator;
  1595. }
  1596. /** DOCDOC
  1597. * XXXX ipv6 NM
  1598. */
  1599. static void
  1600. client_check_address_changed(int sock)
  1601. {
  1602. uint32_t iface_ip, ip_out;
  1603. struct sockaddr_in out_addr;
  1604. socklen_t out_addr_len = sizeof(out_addr);
  1605. uint32_t *ip;
  1606. if (!last_interface_ip)
  1607. get_interface_address(&last_interface_ip);
  1608. if (!outgoing_addrs)
  1609. outgoing_addrs = smartlist_create();
  1610. if (getsockname(sock, (struct sockaddr*)&out_addr, &out_addr_len)<0) {
  1611. int e = tor_socket_errno(sock);
  1612. log_fn(LOG_WARN, "getsockname() failed: %s", tor_socket_strerror(e));
  1613. return;
  1614. }
  1615. /* Okay. If we've used this address previously, we're okay. */
  1616. ip_out = ntohl(out_addr.sin_addr.s_addr);
  1617. SMARTLIST_FOREACH(outgoing_addrs, uint32_t*, ip,
  1618. if (*ip == ip_out) return;
  1619. );
  1620. /* Uh-oh. We haven't connected from this address before. Has the interface
  1621. * address changed? */
  1622. if (get_interface_address(&iface_ip)<0)
  1623. return;
  1624. ip = tor_malloc(sizeof(uint32_t));
  1625. *ip = ip_out;
  1626. if (iface_ip == last_interface_ip) {
  1627. /* Nope, it hasn't changed. Add this address to the list. */
  1628. smartlist_add(outgoing_addrs, ip);
  1629. } else {
  1630. /* The interface changed. We're a client, so we need to regenerate our
  1631. * keys. First, reset the state. */
  1632. log_fn(LOG_NOTICE, "Our IP has changed. Rotating keys...");
  1633. last_interface_ip = iface_ip;
  1634. SMARTLIST_FOREACH(outgoing_addrs, void*, ip, tor_free(ip));
  1635. smartlist_clear(outgoing_addrs);
  1636. smartlist_add(outgoing_addrs, ip);
  1637. /* Okay, now change our keys. */
  1638. init_keys(); /* XXXX NM return value-- safe to ignore? */
  1639. }
  1640. }
  1641. /** Process new bytes that have arrived on conn-\>inbuf.
  1642. *
  1643. * This function just passes conn to the connection-specific
  1644. * connection_*_process_inbuf() function. It also passes in
  1645. * package_partial if wanted.
  1646. */
  1647. static int
  1648. connection_process_inbuf(connection_t *conn, int package_partial)
  1649. {
  1650. tor_assert(conn);
  1651. switch (conn->type) {
  1652. case CONN_TYPE_OR:
  1653. return connection_or_process_inbuf(conn);
  1654. case CONN_TYPE_EXIT:
  1655. case CONN_TYPE_AP:
  1656. return connection_edge_process_inbuf(conn, package_partial);
  1657. case CONN_TYPE_DIR:
  1658. return connection_dir_process_inbuf(conn);
  1659. case CONN_TYPE_DNSWORKER:
  1660. return connection_dns_process_inbuf(conn);
  1661. case CONN_TYPE_CPUWORKER:
  1662. return connection_cpu_process_inbuf(conn);
  1663. case CONN_TYPE_CONTROL:
  1664. return connection_control_process_inbuf(conn);
  1665. default:
  1666. log_fn(LOG_WARN,"Bug: got unexpected conn type %d.", conn->type);
  1667. tor_fragile_assert();
  1668. return -1;
  1669. }
  1670. }
  1671. /** We just finished flushing bytes from conn-\>outbuf, and there
  1672. * are no more bytes remaining.
  1673. *
  1674. * This function just passes conn to the connection-specific
  1675. * connection_*_finished_flushing() function.
  1676. */
  1677. static int
  1678. connection_finished_flushing(connection_t *conn)
  1679. {
  1680. tor_assert(conn);
  1681. // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
  1682. switch (conn->type) {
  1683. case CONN_TYPE_OR:
  1684. return connection_or_finished_flushing(conn);
  1685. case CONN_TYPE_AP:
  1686. case CONN_TYPE_EXIT:
  1687. return connection_edge_finished_flushing(conn);
  1688. case CONN_TYPE_DIR:
  1689. return connection_dir_finished_flushing(conn);
  1690. case CONN_TYPE_DNSWORKER:
  1691. return connection_dns_finished_flushing(conn);
  1692. case CONN_TYPE_CPUWORKER:
  1693. return connection_cpu_finished_flushing(conn);
  1694. case CONN_TYPE_CONTROL:
  1695. return connection_control_finished_flushing(conn);
  1696. default:
  1697. log_fn(LOG_WARN,"Bug: got unexpected conn type %d.", conn->type);
  1698. tor_fragile_assert();
  1699. return -1;
  1700. }
  1701. }
  1702. /** Called when our attempt to connect() to another server has just
  1703. * succeeded.
  1704. *
  1705. * This function just passes conn to the connection-specific
  1706. * connection_*_finished_connecting() function.
  1707. */
  1708. static int
  1709. connection_finished_connecting(connection_t *conn)
  1710. {
  1711. tor_assert(conn);
  1712. switch (conn->type)
  1713. {
  1714. case CONN_TYPE_OR:
  1715. return connection_or_finished_connecting(conn);
  1716. case CONN_TYPE_EXIT:
  1717. return connection_edge_finished_connecting(conn);
  1718. case CONN_TYPE_DIR:
  1719. return connection_dir_finished_connecting(conn);
  1720. default:
  1721. log_fn(LOG_WARN,"Bug: got unexpected conn type %d.", conn->type);
  1722. tor_fragile_assert();
  1723. return -1;
  1724. }
  1725. }
  1726. /** Callback: invoked when a connection reaches an EOF event. */
  1727. static int
  1728. connection_reached_eof(connection_t *conn)
  1729. {
  1730. switch (conn->type) {
  1731. case CONN_TYPE_OR:
  1732. return connection_or_reached_eof(conn);
  1733. case CONN_TYPE_AP:
  1734. case CONN_TYPE_EXIT:
  1735. return connection_edge_reached_eof(conn);
  1736. case CONN_TYPE_DIR:
  1737. return connection_dir_reached_eof(conn);
  1738. case CONN_TYPE_DNSWORKER:
  1739. return connection_dns_reached_eof(conn);
  1740. case CONN_TYPE_CPUWORKER:
  1741. return connection_cpu_reached_eof(conn);
  1742. case CONN_TYPE_CONTROL:
  1743. return connection_control_reached_eof(conn);
  1744. default:
  1745. log_fn(LOG_WARN,"Bug: got unexpected conn type %d.", conn->type);
  1746. tor_fragile_assert();
  1747. return -1;
  1748. }
  1749. }
  1750. /** Verify that connection <b>conn</b> has all of its invariants
  1751. * correct. Trigger an assert if anything is invalid.
  1752. */
  1753. void
  1754. assert_connection_ok(connection_t *conn, time_t now)
  1755. {
  1756. tor_assert(conn);
  1757. tor_assert(conn->magic == CONNECTION_MAGIC);
  1758. tor_assert(conn->type >= _CONN_TYPE_MIN);
  1759. tor_assert(conn->type <= _CONN_TYPE_MAX);
  1760. if (conn->outbuf_flushlen > 0) {
  1761. tor_assert(connection_is_writing(conn) || conn->wants_to_write);
  1762. }
  1763. if (conn->hold_open_until_flushed)
  1764. tor_assert(conn->marked_for_close);
  1765. /* XXX check: wants_to_read, wants_to_write, s, poll_index,
  1766. * marked_for_close. */
  1767. /* buffers */
  1768. if (!connection_is_listener(conn)) {
  1769. assert_buf_ok(conn->inbuf);
  1770. assert_buf_ok(conn->outbuf);
  1771. }
  1772. /* XXX Fix this; no longer so.*/
  1773. #if 0
  1774. if (conn->type != CONN_TYPE_OR && conn->type != CONN_TYPE_DIR)
  1775. tor_assert(!conn->pkey);
  1776. /* pkey is set if we're a dir client, or if we're an OR in state OPEN
  1777. * connected to another OR.
  1778. */
  1779. #endif
  1780. if (conn->type != CONN_TYPE_OR) {
  1781. tor_assert(!conn->tls);
  1782. } else {
  1783. if (conn->state == OR_CONN_STATE_OPEN) {
  1784. /* tor_assert(conn->bandwidth > 0); */
  1785. /* the above isn't necessarily true: if we just did a TLS
  1786. * handshake but we didn't recognize the other peer, or it
  1787. * gave a bad cert/etc, then we won't have assigned bandwidth,
  1788. * yet it will be open. -RD
  1789. */
  1790. // tor_assert(conn->receiver_bucket >= 0);
  1791. }
  1792. // tor_assert(conn->addr && conn->port);
  1793. tor_assert(conn->address);
  1794. if (conn->state > OR_CONN_STATE_PROXY_READING)
  1795. tor_assert(conn->tls);
  1796. }
  1797. if (! CONN_IS_EDGE(conn)) {
  1798. tor_assert(!conn->stream_id);
  1799. tor_assert(!conn->next_stream);
  1800. tor_assert(!conn->cpath_layer);
  1801. tor_assert(!conn->package_window);
  1802. tor_assert(!conn->deliver_window);
  1803. #if 0
  1804. tor_assert(!conn->done_sending);
  1805. tor_assert(!conn->done_receiving);
  1806. #endif
  1807. } else {
  1808. /* XXX unchecked: package window, deliver window. */
  1809. }
  1810. if (conn->type == CONN_TYPE_AP) {
  1811. tor_assert(conn->socks_request);
  1812. if (conn->state == AP_CONN_STATE_OPEN) {
  1813. tor_assert(conn->socks_request->has_finished);
  1814. if (!conn->marked_for_close) {
  1815. tor_assert(conn->cpath_layer);
  1816. assert_cpath_layer_ok(conn->cpath_layer);
  1817. }
  1818. }
  1819. } else {
  1820. tor_assert(!conn->socks_request);
  1821. }
  1822. if (conn->type == CONN_TYPE_EXIT) {
  1823. tor_assert(conn->purpose == EXIT_PURPOSE_CONNECT ||
  1824. conn->purpose == EXIT_PURPOSE_RESOLVE);
  1825. } else if (conn->type != CONN_TYPE_DIR) {
  1826. tor_assert(!conn->purpose); /* only used for dir types currently */
  1827. }
  1828. if (conn->type != CONN_TYPE_DIR) {
  1829. tor_assert(!conn->requested_resource);
  1830. }
  1831. switch (conn->type)
  1832. {
  1833. case CONN_TYPE_OR_LISTENER:
  1834. case CONN_TYPE_AP_LISTENER:
  1835. case CONN_TYPE_DIR_LISTENER:
  1836. case CONN_TYPE_CONTROL_LISTENER:
  1837. tor_assert(conn->state == LISTENER_STATE_READY);
  1838. break;
  1839. case CONN_TYPE_OR:
  1840. tor_assert(conn->state >= _OR_CONN_STATE_MIN);
  1841. tor_assert(conn->state <= _OR_CONN_STATE_MAX);
  1842. break;
  1843. case CONN_TYPE_EXIT:
  1844. tor_assert(conn->state >= _EXIT_CONN_STATE_MIN);
  1845. tor_assert(conn->state <= _EXIT_CONN_STATE_MAX);
  1846. break;
  1847. case CONN_TYPE_AP:
  1848. tor_assert(conn->state >= _AP_CONN_STATE_MIN);
  1849. tor_assert(conn->state <= _AP_CONN_STATE_MAX);
  1850. tor_assert(conn->socks_request);
  1851. break;
  1852. case CONN_TYPE_DIR:
  1853. tor_assert(conn->state >= _DIR_CONN_STATE_MIN);
  1854. tor_assert(conn->state <= _DIR_CONN_STATE_MAX);
  1855. tor_assert(conn->purpose >= _DIR_PURPOSE_MIN);
  1856. tor_assert(conn->purpose <= _DIR_PURPOSE_MAX);
  1857. break;
  1858. case CONN_TYPE_DNSWORKER:
  1859. tor_assert(conn->state == DNSWORKER_STATE_IDLE ||
  1860. conn->state == DNSWORKER_STATE_BUSY);
  1861. break;
  1862. case CONN_TYPE_CPUWORKER:
  1863. tor_assert(conn->state >= _CPUWORKER_STATE_MIN);
  1864. tor_assert(conn->state <= _CPUWORKER_STATE_MAX);
  1865. break;
  1866. case CONN_TYPE_CONTROL:
  1867. tor_assert(conn->state >= _CONTROL_CONN_STATE_MIN);
  1868. tor_assert(conn->state <= _CONTROL_CONN_STATE_MAX);
  1869. break;
  1870. default:
  1871. tor_assert(0);
  1872. }
  1873. }