connection.c 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521
  1. /* Copyright 2001 Matej Pfajfar.
  2. * Copyright 2001-2004 Roger Dingledine.
  3. * Copyright 2004 Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. /**
  7. * \file connection.c
  8. * \brief General high-level functions to handle reading and writing
  9. * on connections.
  10. **/
  11. #include "or.h"
  12. /********* START VARIABLES **********/
  13. /** Array of strings to make conn-\>type human-readable. */
  14. const char *conn_type_to_string[] = {
  15. "", /* 0 */
  16. "OP listener", /* 1 */
  17. "OP", /* 2 */
  18. "OR listener", /* 3 */
  19. "OR", /* 4 */
  20. "Exit", /* 5 */
  21. "App listener",/* 6 */
  22. "App", /* 7 */
  23. "Dir listener",/* 8 */
  24. "Dir", /* 9 */
  25. "DNS worker", /* 10 */
  26. "CPU worker", /* 11 */
  27. "Control listener", /* 12 */
  28. "Control", /* 13 */
  29. };
  30. /** Array of string arrays to make {conn-\>type,conn-\>state} human-readable. */
  31. const char *conn_state_to_string[][_CONN_TYPE_MAX+1] = {
  32. { NULL }, /* no type associated with 0 */
  33. { NULL }, /* op listener, obsolete */
  34. { NULL }, /* op, obsolete */
  35. { "ready" }, /* or listener, 0 */
  36. { "", /* OR, 0 */
  37. "connect()ing", /* 1 */
  38. "handshaking", /* 2 */
  39. "open" }, /* 3 */
  40. { "", /* exit, 0 */
  41. "waiting for dest info", /* 1 */
  42. "connecting", /* 2 */
  43. "open", /* 3 */
  44. "resolve failed" }, /* 4 */
  45. { "ready" }, /* app listener, 0 */
  46. { "", /* 0 */
  47. "", /* 1 */
  48. "", /* 2 */
  49. "", /* 3 */
  50. "", /* 4 */
  51. "awaiting dest info", /* app, 5 */
  52. "waiting for rendezvous desc", /* 6 */
  53. "waiting for safe circuit", /* 7 */
  54. "waiting for connected", /* 8 */
  55. "open" }, /* 9 */
  56. { "ready" }, /* dir listener, 0 */
  57. { "", /* dir, 0 */
  58. "connecting", /* 1 */
  59. "client sending", /* 2 */
  60. "client reading", /* 3 */
  61. "awaiting command", /* 4 */
  62. "writing" }, /* 5 */
  63. { "", /* dns worker, 0 */
  64. "idle", /* 1 */
  65. "busy" }, /* 2 */
  66. { "", /* cpu worker, 0 */
  67. "idle", /* 1 */
  68. "busy with onion", /* 2 */
  69. "busy with handshake" }, /* 3 */
  70. { "ready" }, /* control listener, 0 */
  71. { "", /* control, 0 */
  72. "ready", /* 1 */
  73. "waiting for authentication", }, /* 2 */
  74. };
  75. /********* END VARIABLES ************/
  76. static int connection_create_listener(const char *bindaddress,
  77. uint16_t bindport, int type);
  78. static int connection_init_accepted_conn(connection_t *conn);
  79. static int connection_handle_listener_read(connection_t *conn, int new_type);
  80. static int connection_receiver_bucket_should_increase(connection_t *conn);
  81. static int connection_finished_flushing(connection_t *conn);
  82. static int connection_finished_connecting(connection_t *conn);
  83. static int connection_reached_eof(connection_t *conn);
  84. static int connection_read_to_buf(connection_t *conn, int *max_to_read);
  85. static int connection_process_inbuf(connection_t *conn, int package_partial);
  86. static int connection_bucket_read_limit(connection_t *conn);
  87. /**************************************************************/
  88. /** Allocate space for a new connection_t. This function just initializes
  89. * conn; you must call connection_add() to link it into the main array.
  90. *
  91. * Set conn-\>type to <b>type</b>. Set conn-\>s and conn-\>poll_index to
  92. * -1 to signify they are not yet assigned.
  93. *
  94. * If conn is not a listener type, allocate buffers for it. If it's
  95. * an AP type, allocate space to store the socks_request.
  96. *
  97. * Assign a pseudorandom next_circ_id between 0 and 2**15.
  98. *
  99. * Initialize conn's timestamps to now.
  100. */
  101. connection_t *connection_new(int type) {
  102. connection_t *conn;
  103. time_t now = time(NULL);
  104. conn = tor_malloc_zero(sizeof(connection_t));
  105. conn->magic = CONNECTION_MAGIC;
  106. conn->s = -1; /* give it a default of 'not used' */
  107. conn->poll_index = -1; /* also default to 'not used' */
  108. conn->type = type;
  109. if(!connection_is_listener(conn)) { /* listeners never use their buf */
  110. conn->inbuf = buf_new();
  111. conn->outbuf = buf_new();
  112. }
  113. if (type == CONN_TYPE_AP) {
  114. conn->socks_request = tor_malloc_zero(sizeof(socks_request_t));
  115. }
  116. conn->next_circ_id = crypto_pseudo_rand_int(1<<15);
  117. conn->timestamp_created = now;
  118. conn->timestamp_lastread = now;
  119. conn->timestamp_lastwritten = now;
  120. return conn;
  121. }
  122. /** Deallocate memory used by <b>conn</b>. Deallocate its buffers if necessary,
  123. * close its socket if necessary, and mark the directory as dirty if <b>conn</b>
  124. * is an OR or OP connection.
  125. */
  126. void connection_free(connection_t *conn) {
  127. tor_assert(conn);
  128. tor_assert(conn->magic == CONNECTION_MAGIC);
  129. if(!connection_is_listener(conn)) {
  130. buf_free(conn->inbuf);
  131. buf_free(conn->outbuf);
  132. }
  133. tor_free(conn->address);
  134. if(connection_speaks_cells(conn)) {
  135. if(conn->state == OR_CONN_STATE_OPEN)
  136. directory_set_dirty();
  137. if (conn->tls)
  138. tor_tls_free(conn->tls);
  139. }
  140. if (conn->identity_pkey)
  141. crypto_free_pk_env(conn->identity_pkey);
  142. tor_free(conn->nickname);
  143. tor_free(conn->socks_request);
  144. if(conn->s >= 0) {
  145. log_fn(LOG_INFO,"closing fd %d.",conn->s);
  146. tor_close_socket(conn->s);
  147. }
  148. memset(conn, 0xAA, sizeof(connection_t)); /* poison memory */
  149. tor_free(conn);
  150. }
  151. /** Call connection_free() on every connection in our array.
  152. * This is used by cpuworkers and dnsworkers when they fork,
  153. * so they don't keep resources held open (especially sockets).
  154. */
  155. void connection_free_all(void) {
  156. int i, n;
  157. connection_t **carray;
  158. get_connection_array(&carray,&n);
  159. for(i=0;i<n;i++)
  160. connection_free(carray[i]);
  161. }
  162. /** Do any cleanup needed:
  163. * - Directory conns that failed to fetch a rendezvous descriptor
  164. * need to inform pending rendezvous streams.
  165. * - OR conns need to call rep_hist_note_*() to record status.
  166. * - AP conns need to send a socks reject if necessary.
  167. * - Exit conns need to call connection_dns_remove() if necessary.
  168. * - AP and Exit conns need to send an end cell if they can.
  169. * - DNS conns need to fail any resolves that are pending on them.
  170. */
  171. void connection_about_to_close_connection(connection_t *conn)
  172. {
  173. assert(conn->marked_for_close);
  174. if(conn->type == CONN_TYPE_AP || conn->type == CONN_TYPE_EXIT) {
  175. if(!conn->has_sent_end)
  176. log_fn(LOG_WARN,"Edge connection hasn't sent end yet? Bug.");
  177. }
  178. switch(conn->type) {
  179. case CONN_TYPE_DIR:
  180. if(conn->purpose == DIR_PURPOSE_FETCH_RENDDESC)
  181. rend_client_desc_fetched(conn->rend_query, 0);
  182. break;
  183. case CONN_TYPE_OR:
  184. /* Remember why we're closing this connection. */
  185. if (conn->state != OR_CONN_STATE_OPEN) {
  186. if(connection_or_nonopen_was_started_here(conn)) {
  187. rep_hist_note_connect_failed(conn->identity_digest, time(NULL));
  188. control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED);
  189. }
  190. } else if (conn->hold_open_until_flushed) {
  191. /* XXXX009 We used to have an arg that told us whether we closed the
  192. * connection on purpose or not. Can we use hold_open_until_flushed
  193. * instead? We only set it when we are intentionally closing a
  194. * connection. -NM
  195. *
  196. * (Of course, now things we set to close which expire rather than
  197. * flushing still get noted as dead, not disconnected. But this is an
  198. * improvement. -NM
  199. */
  200. rep_hist_note_disconnect(conn->identity_digest, time(NULL));
  201. control_event_or_conn_status(conn, OR_CONN_EVENT_CLOSED);
  202. } else if(conn->identity_digest) {
  203. rep_hist_note_connection_died(conn->identity_digest, time(NULL));
  204. control_event_or_conn_status(conn, OR_CONN_EVENT_CLOSED);
  205. }
  206. break;
  207. case CONN_TYPE_AP:
  208. if (conn->socks_request->has_finished == 0) {
  209. log_fn(LOG_INFO,"Cleaning up AP -- sending socks reject.");
  210. connection_ap_handshake_socks_reply(conn, NULL, 0, -1);
  211. conn->socks_request->has_finished = 1;
  212. conn->hold_open_until_flushed = 1;
  213. } else {
  214. control_event_stream_status(conn, STREAM_EVENT_CLOSED);
  215. }
  216. break;
  217. case CONN_TYPE_EXIT:
  218. if (conn->state == EXIT_CONN_STATE_RESOLVING) {
  219. circuit_detach_stream(circuit_get_by_conn(conn), conn);
  220. connection_dns_remove(conn);
  221. }
  222. break;
  223. case CONN_TYPE_DNSWORKER:
  224. if (conn->state == DNSWORKER_STATE_BUSY) {
  225. dns_cancel_pending_resolve(conn->address);
  226. }
  227. break;
  228. }
  229. }
  230. /** Close the underlying socket for <b>conn</b>, so we don't try to
  231. * flush it. Must be used in conjunction with (right before)
  232. * connection_mark_for_close().
  233. */
  234. void connection_close_immediate(connection_t *conn)
  235. {
  236. assert_connection_ok(conn,0);
  237. if (conn->s < 0) {
  238. log_fn(LOG_WARN,"Attempt to close already-closed connection.");
  239. return;
  240. }
  241. if (conn->outbuf_flushlen) {
  242. log_fn(LOG_INFO,"fd %d, type %s, state %d, %d bytes on outbuf.",
  243. conn->s, CONN_TYPE_TO_STRING(conn->type),
  244. conn->state, (int)conn->outbuf_flushlen);
  245. }
  246. tor_close_socket(conn->s);
  247. conn->s = -1;
  248. if(!connection_is_listener(conn)) {
  249. buf_clear(conn->outbuf);
  250. conn->outbuf_flushlen = 0;
  251. }
  252. }
  253. /** Mark <b>conn</b> to be closed next time we loop through
  254. * conn_close_if_marked() in main.c. */
  255. int
  256. _connection_mark_for_close(connection_t *conn)
  257. {
  258. assert_connection_ok(conn,0);
  259. if (conn->marked_for_close) {
  260. log(LOG_WARN, "Double mark-for-close on connection.");
  261. return -1;
  262. }
  263. conn->marked_for_close = 1;
  264. /* in case we're going to be held-open-til-flushed, reset
  265. * the number of seconds since last successful write, so
  266. * we get our whole 15 seconds */
  267. conn->timestamp_lastwritten = time(NULL);
  268. return 0;
  269. }
  270. /** Find each connection that has hold_open_until_flushed set to
  271. * 1 but hasn't written in the past 15 seconds, and set
  272. * hold_open_until_flushed to 0. This means it will get cleaned
  273. * up in the next loop through close_if_marked() in main.c.
  274. */
  275. void connection_expire_held_open(void)
  276. {
  277. connection_t **carray, *conn;
  278. int n, i;
  279. time_t now;
  280. now = time(NULL);
  281. get_connection_array(&carray, &n);
  282. for (i = 0; i < n; ++i) {
  283. conn = carray[i];
  284. /* If we've been holding the connection open, but we haven't written
  285. * for 15 seconds...
  286. */
  287. if (conn->hold_open_until_flushed) {
  288. tor_assert(conn->marked_for_close);
  289. if (now - conn->timestamp_lastwritten >= 15) {
  290. log_fn(LOG_WARN,"Giving up on marked_for_close conn that's been flushing for 15s (fd %d, type %s, state %d).",
  291. conn->s, CONN_TYPE_TO_STRING(conn->type), conn->state);
  292. conn->hold_open_until_flushed = 0;
  293. }
  294. }
  295. }
  296. }
  297. /** Bind a new non-blocking socket listening to
  298. * <b>bindaddress</b>:<b>bindport</b>, and add this new connection
  299. * (of type <b>type</b>) to the connection array.
  300. *
  301. * If <b>bindaddress</b> includes a port, we bind on that port; otherwise, we
  302. * use bindport.
  303. */
  304. static int connection_create_listener(const char *bindaddress, uint16_t bindport, int type) {
  305. struct sockaddr_in bindaddr; /* where to bind */
  306. connection_t *conn;
  307. uint16_t usePort;
  308. uint32_t addr;
  309. int s; /* the socket we're going to make */
  310. int one=1;
  311. memset(&bindaddr,0,sizeof(struct sockaddr_in));
  312. if (parse_addr_port(bindaddress, NULL, &addr, &usePort)<0) {
  313. log_fn(LOG_WARN, "Error parsing/resolving BindAddress %s",bindaddress);
  314. return -1;
  315. }
  316. if (usePort==0)
  317. usePort = bindport;
  318. bindaddr.sin_addr.s_addr = htonl(addr);
  319. bindaddr.sin_family = AF_INET;
  320. bindaddr.sin_port = htons((uint16_t) usePort);
  321. s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
  322. if (s < 0) {
  323. log_fn(LOG_WARN,"Socket creation failed.");
  324. return -1;
  325. }
  326. setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*) &one, sizeof(one));
  327. if(bind(s,(struct sockaddr *)&bindaddr,sizeof(bindaddr)) < 0) {
  328. log_fn(LOG_WARN,"Could not bind to port %u: %s",usePort,
  329. tor_socket_strerror(tor_socket_errno(s)));
  330. return -1;
  331. }
  332. if(listen(s,SOMAXCONN) < 0) {
  333. log_fn(LOG_WARN,"Could not listen on port %u: %s",usePort,
  334. tor_socket_strerror(tor_socket_errno(s)));
  335. return -1;
  336. }
  337. set_socket_nonblocking(s);
  338. conn = connection_new(type);
  339. conn->s = s;
  340. if(connection_add(conn) < 0) { /* no space, forget it */
  341. log_fn(LOG_WARN,"connection_add failed. Giving up.");
  342. connection_free(conn);
  343. return -1;
  344. }
  345. log_fn(LOG_DEBUG,"%s listening on port %u.",conn_type_to_string[type], usePort);
  346. conn->state = LISTENER_STATE_READY;
  347. connection_start_reading(conn);
  348. return 0;
  349. }
  350. /** The listener connection <b>conn</b> told poll() it wanted to read.
  351. * Call accept() on conn-\>s, and add the new connection if necessary.
  352. */
  353. static int connection_handle_listener_read(connection_t *conn, int new_type) {
  354. int news; /* the new socket */
  355. connection_t *newconn;
  356. /* information about the remote peer when connecting to other routers */
  357. struct sockaddr_in remote;
  358. /* length of the remote address. Must be an int, since accept() needs that. */
  359. int remotelen = sizeof(struct sockaddr_in);
  360. news = accept(conn->s,(struct sockaddr *)&remote,&remotelen);
  361. if (news == -1) { /* accept() error */
  362. int e = tor_socket_errno(conn->s);
  363. if (ERRNO_IS_ACCEPT_EAGAIN(e)) {
  364. return 0; /* he hung up before we could accept(). that's fine. */
  365. } else if (ERRNO_IS_ACCEPT_RESOURCE_LIMIT(e)) {
  366. log_fn(LOG_WARN,"accept failed: %s. Dropping incoming connection.",
  367. tor_socket_strerror(e));
  368. return 0;
  369. }
  370. /* else there was a real error. */
  371. log_fn(LOG_WARN,"accept() failed: %s. Closing listener.",
  372. tor_socket_strerror(e));
  373. connection_mark_for_close(conn);
  374. return -1;
  375. }
  376. log(LOG_INFO,"Connection accepted on socket %d (child of fd %d).",news, conn->s);
  377. set_socket_nonblocking(news);
  378. /* process entrance policies here, before we even create the connection */
  379. if(new_type == CONN_TYPE_AP) {
  380. /* check sockspolicy to see if we should accept it */
  381. if(socks_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
  382. log_fn(LOG_WARN,"Denying socks connection from untrusted address %s.",
  383. inet_ntoa(remote.sin_addr));
  384. tor_close_socket(news);
  385. return 0;
  386. }
  387. }
  388. if(new_type == CONN_TYPE_DIR) {
  389. /* check dirpolicy to see if we should accept it */
  390. if(dir_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
  391. log_fn(LOG_WARN,"Denying dir connection from address %s.",
  392. inet_ntoa(remote.sin_addr));
  393. tor_close_socket(news);
  394. return 0;
  395. }
  396. }
  397. newconn = connection_new(new_type);
  398. newconn->s = news;
  399. newconn->address = tor_strdup(inet_ntoa(remote.sin_addr)); /* remember the remote address */
  400. newconn->addr = ntohl(remote.sin_addr.s_addr);
  401. newconn->port = ntohs(remote.sin_port);
  402. if(connection_add(newconn) < 0) { /* no space, forget it */
  403. connection_free(newconn);
  404. return 0; /* no need to tear down the parent */
  405. }
  406. if(connection_init_accepted_conn(newconn) < 0) {
  407. connection_mark_for_close(newconn);
  408. return 0;
  409. }
  410. return 0;
  411. }
  412. /** Initialize states for newly accepted connection <b>conn</b>.
  413. * If conn is an OR, start the tls handshake.
  414. */
  415. static int connection_init_accepted_conn(connection_t *conn) {
  416. connection_start_reading(conn);
  417. switch(conn->type) {
  418. case CONN_TYPE_OR:
  419. return connection_tls_start_handshake(conn, 1);
  420. case CONN_TYPE_AP:
  421. conn->state = AP_CONN_STATE_SOCKS_WAIT;
  422. break;
  423. case CONN_TYPE_DIR:
  424. conn->purpose = DIR_PURPOSE_SERVER;
  425. conn->state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
  426. break;
  427. case CONN_TYPE_CONTROL:
  428. conn->state = CONTROL_CONN_STATE_NEEDAUTH;
  429. break;
  430. }
  431. return 0;
  432. }
  433. /** Take conn, make a nonblocking socket; try to connect to
  434. * addr:port (they arrive in *host order*). If fail, return -1. Else
  435. * assign s to conn->\s: if connected return 1, if EAGAIN return 0.
  436. *
  437. * address is used to make the logs useful.
  438. *
  439. * On success, add conn to the list of polled connections.
  440. */
  441. int connection_connect(connection_t *conn, char *address, uint32_t addr, uint16_t port) {
  442. int s;
  443. struct sockaddr_in dest_addr;
  444. or_options_t *options = get_options();
  445. s=socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
  446. if (s < 0) {
  447. log_fn(LOG_WARN,"Error creating network socket: %s",
  448. tor_socket_strerror(tor_socket_errno(-1)));
  449. return -1;
  450. }
  451. if (options->OutboundBindAddress) {
  452. struct sockaddr_in ext_addr;
  453. memset(&ext_addr, 0, sizeof(ext_addr));
  454. ext_addr.sin_family = AF_INET;
  455. ext_addr.sin_port = 0;
  456. if (!tor_inet_aton(options->OutboundBindAddress, &ext_addr.sin_addr)) {
  457. log_fn(LOG_WARN,"Outbound bind address '%s' didn't parse. Ignoring.",
  458. options->OutboundBindAddress);
  459. } else {
  460. if(bind(s, (struct sockaddr*)&ext_addr, sizeof(ext_addr)) < 0) {
  461. log_fn(LOG_WARN,"Error binding network socket: %s",
  462. tor_socket_strerror(tor_socket_errno(s)));
  463. return -1;
  464. }
  465. }
  466. }
  467. set_socket_nonblocking(s);
  468. memset(&dest_addr,0,sizeof(dest_addr));
  469. dest_addr.sin_family = AF_INET;
  470. dest_addr.sin_port = htons(port);
  471. dest_addr.sin_addr.s_addr = htonl(addr);
  472. log_fn(LOG_DEBUG,"Connecting to %s:%u.",address,port);
  473. if(connect(s,(struct sockaddr *)&dest_addr,sizeof(dest_addr)) < 0) {
  474. if(!ERRNO_IS_CONN_EINPROGRESS(tor_socket_errno(s))) {
  475. /* yuck. kill it. */
  476. log_fn(LOG_INFO,"Connect() to %s:%u failed: %s",address,port,
  477. tor_socket_strerror(tor_socket_errno(s)));
  478. tor_close_socket(s);
  479. return -1;
  480. } else {
  481. /* it's in progress. set state appropriately and return. */
  482. conn->s = s;
  483. if(connection_add(conn) < 0) /* no space, forget it */
  484. return -1;
  485. log_fn(LOG_DEBUG,"connect in progress, socket %d.",s);
  486. return 0;
  487. }
  488. }
  489. /* it succeeded. we're connected. */
  490. log_fn(LOG_INFO,"Connection to %s:%u established.",address,port);
  491. conn->s = s;
  492. if(connection_add(conn) < 0) /* no space, forget it */
  493. return -1;
  494. return 1;
  495. }
  496. /** If there exist any listeners of type <b>type</b> in the connection
  497. * array, mark them for close.
  498. */
  499. static void listener_close_if_present(int type) {
  500. connection_t *conn;
  501. connection_t **carray;
  502. int i,n;
  503. tor_assert(type == CONN_TYPE_OR_LISTENER ||
  504. type == CONN_TYPE_AP_LISTENER ||
  505. type == CONN_TYPE_DIR_LISTENER ||
  506. type == CONN_TYPE_CONTROL_LISTENER);
  507. get_connection_array(&carray,&n);
  508. for(i=0;i<n;i++) {
  509. conn = carray[i];
  510. if (conn->type == type && !conn->marked_for_close) {
  511. connection_close_immediate(conn);
  512. connection_mark_for_close(conn);
  513. }
  514. }
  515. }
  516. /**
  517. * Launch any configured listener connections of type <b>type</b>. (A
  518. * listener is configured if <b>port_option</b> is non-zero. If any
  519. * BindAddress configuration options are given in <b>cfg</b>, create a
  520. * connection binding to each one. Otherwise, create a single
  521. * connection binding to the address <b>default_addr</b>.)
  522. *
  523. * If <b>force</b> is true, close and re-open all listener connections.
  524. * Otherwise, only relaunch the listeners of this type if the number of
  525. * existing connections is not as configured (e.g., because one died).
  526. */
  527. static int retry_listeners(int type, struct config_line_t *cfg,
  528. int port_option, const char *default_addr,
  529. int force)
  530. {
  531. if (!force) {
  532. int want, have, n_conn, i;
  533. struct config_line_t *c;
  534. connection_t *conn;
  535. connection_t **carray;
  536. /* How many should there be? */
  537. if (cfg && port_option) {
  538. want = 0;
  539. for (c = cfg; c; c = c->next)
  540. ++want;
  541. } else if (port_option) {
  542. want = 1;
  543. } else {
  544. want = 0;
  545. }
  546. /* How many are there actually? */
  547. have = 0;
  548. get_connection_array(&carray,&n_conn);
  549. for(i=0;i<n_conn;i++) {
  550. conn = carray[i];
  551. if (conn->type == type && !conn->marked_for_close)
  552. ++have;
  553. }
  554. /* If we have the right number of listeners, do nothing. */
  555. if (have == want)
  556. return 0;
  557. /* Otherwise, warn the user and relaunch. */
  558. log_fn(LOG_WARN,"We have %d %s(s) open, but we want %d; relaunching.",
  559. have, conn_type_to_string[type], want);
  560. }
  561. listener_close_if_present(type);
  562. if (port_option) {
  563. if (!cfg) {
  564. if (connection_create_listener(default_addr, (uint16_t) port_option,
  565. type)<0)
  566. return -1;
  567. } else {
  568. for ( ; cfg; cfg = cfg->next) {
  569. if (connection_create_listener(cfg->value, (uint16_t) port_option,
  570. type)<0)
  571. return -1;
  572. }
  573. }
  574. }
  575. return 0;
  576. }
  577. /** (Re)launch listeners for each port you should have open. If
  578. * <b>force</b> is true, close and relaunch all listeners. If <b>force</b>
  579. * is false, then only relaunch listeners when we have the wrong number of
  580. * connections for a given type.
  581. */
  582. int retry_all_listeners(int force) {
  583. or_options_t *options = get_options();
  584. if (retry_listeners(CONN_TYPE_OR_LISTENER, options->ORBindAddress,
  585. options->ORPort, "0.0.0.0", force)<0)
  586. return -1;
  587. if (retry_listeners(CONN_TYPE_DIR_LISTENER, options->DirBindAddress,
  588. options->DirPort, "0.0.0.0", force)<0)
  589. return -1;
  590. if (retry_listeners(CONN_TYPE_AP_LISTENER, options->SocksBindAddress,
  591. options->SocksPort, "127.0.0.1", force)<0)
  592. return -1;
  593. if (retry_listeners(CONN_TYPE_CONTROL_LISTENER, NULL,
  594. options->ControlPort, "127.0.0.1", force)<0)
  595. return -1;
  596. return 0;
  597. }
  598. extern int global_read_bucket, global_write_bucket;
  599. /** How many bytes at most can we read onto this connection? */
  600. static int connection_bucket_read_limit(connection_t *conn) {
  601. int at_most;
  602. /* do a rudimentary round-robin so one circuit can't hog a connection */
  603. if(connection_speaks_cells(conn)) {
  604. at_most = 32*(CELL_NETWORK_SIZE);
  605. } else {
  606. at_most = 32*(RELAY_PAYLOAD_SIZE);
  607. }
  608. if(at_most > global_read_bucket)
  609. at_most = global_read_bucket;
  610. if(connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN)
  611. if(at_most > conn->receiver_bucket)
  612. at_most = conn->receiver_bucket;
  613. return at_most;
  614. }
  615. /** We just read num_read onto conn. Decrement buckets appropriately. */
  616. static void connection_read_bucket_decrement(connection_t *conn, int num_read) {
  617. global_read_bucket -= num_read; tor_assert(global_read_bucket >= 0);
  618. if(connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
  619. conn->receiver_bucket -= num_read; tor_assert(conn->receiver_bucket >= 0);
  620. }
  621. }
  622. static void connection_consider_empty_buckets(connection_t *conn) {
  623. if(global_read_bucket == 0) {
  624. log_fn(LOG_DEBUG,"global bucket exhausted. Pausing.");
  625. conn->wants_to_read = 1;
  626. connection_stop_reading(conn);
  627. return;
  628. }
  629. if(connection_speaks_cells(conn) &&
  630. conn->state == OR_CONN_STATE_OPEN &&
  631. conn->receiver_bucket == 0) {
  632. log_fn(LOG_DEBUG,"receiver bucket exhausted. Pausing.");
  633. conn->wants_to_read = 1;
  634. connection_stop_reading(conn);
  635. }
  636. }
  637. /** Initialize the global read bucket to options->BandwidthBurst,
  638. * and current_time to the current time. */
  639. void connection_bucket_init(void) {
  640. or_options_t *options = get_options();
  641. global_read_bucket = options->BandwidthBurst; /* start it at max traffic */
  642. global_write_bucket = options->BandwidthBurst; /* start it at max traffic */
  643. }
  644. /** A second has rolled over; increment buckets appropriately. */
  645. void connection_bucket_refill(struct timeval *now) {
  646. int i, n;
  647. connection_t *conn;
  648. connection_t **carray;
  649. or_options_t *options = get_options();
  650. /* refill the global buckets */
  651. if(global_read_bucket < options->BandwidthBurst) {
  652. global_read_bucket += options->BandwidthRate;
  653. log_fn(LOG_DEBUG,"global_read_bucket now %d.", global_read_bucket);
  654. }
  655. if(global_write_bucket < options->BandwidthBurst) {
  656. global_write_bucket += options->BandwidthRate;
  657. log_fn(LOG_DEBUG,"global_write_bucket now %d.", global_write_bucket);
  658. }
  659. /* refill the per-connection buckets */
  660. get_connection_array(&carray,&n);
  661. for(i=0;i<n;i++) {
  662. conn = carray[i];
  663. if(connection_receiver_bucket_should_increase(conn)) {
  664. conn->receiver_bucket += conn->bandwidth;
  665. //log_fn(LOG_DEBUG,"Receiver bucket %d now %d.", i, conn->receiver_bucket);
  666. }
  667. if(conn->wants_to_read == 1 /* it's marked to turn reading back on now */
  668. && global_read_bucket > 0 /* and we're allowed to read */
  669. && global_write_bucket > 0 /* and we're allowed to write (XXXX,
  670. * not the best place to check this.) */
  671. && (!connection_speaks_cells(conn) ||
  672. conn->state != OR_CONN_STATE_OPEN ||
  673. conn->receiver_bucket > 0)) {
  674. /* and either a non-cell conn or a cell conn with non-empty bucket */
  675. log_fn(LOG_DEBUG,"waking up conn (fd %d)",conn->s);
  676. conn->wants_to_read = 0;
  677. connection_start_reading(conn);
  678. if(conn->wants_to_write == 1) {
  679. conn->wants_to_write = 0;
  680. connection_start_writing(conn);
  681. }
  682. }
  683. }
  684. }
  685. /** Is the receiver bucket for connection <b>conn</b> low enough that we
  686. * should add another pile of tokens to it?
  687. */
  688. static int connection_receiver_bucket_should_increase(connection_t *conn) {
  689. tor_assert(conn);
  690. if(!connection_speaks_cells(conn))
  691. return 0; /* edge connections don't use receiver_buckets */
  692. if(conn->state != OR_CONN_STATE_OPEN)
  693. return 0; /* only open connections play the rate limiting game */
  694. tor_assert(conn->bandwidth > 0);
  695. if(conn->receiver_bucket > 9*conn->bandwidth)
  696. return 0;
  697. return 1;
  698. }
  699. /** Read bytes from conn->\s and process them.
  700. *
  701. * This function gets called from conn_read() in main.c, either
  702. * when poll() has declared that conn wants to read, or (for OR conns)
  703. * when there are pending TLS bytes.
  704. *
  705. * It calls connection_read_to_buf() to bring in any new bytes,
  706. * and then calls connection_process_inbuf() to process them.
  707. *
  708. * Mark the connection and return -1 if you want to close it, else
  709. * return 0.
  710. */
  711. int connection_handle_read(connection_t *conn) {
  712. int max_to_read=-1, try_to_read;
  713. conn->timestamp_lastread = time(NULL);
  714. switch(conn->type) {
  715. case CONN_TYPE_OR_LISTENER:
  716. return connection_handle_listener_read(conn, CONN_TYPE_OR);
  717. case CONN_TYPE_AP_LISTENER:
  718. return connection_handle_listener_read(conn, CONN_TYPE_AP);
  719. case CONN_TYPE_DIR_LISTENER:
  720. return connection_handle_listener_read(conn, CONN_TYPE_DIR);
  721. case CONN_TYPE_CONTROL_LISTENER:
  722. return connection_handle_listener_read(conn, CONN_TYPE_CONTROL);
  723. }
  724. loop_again:
  725. try_to_read = max_to_read;
  726. tor_assert(!conn->marked_for_close);
  727. if (connection_read_to_buf(conn, &max_to_read) < 0) {
  728. /* There's a read error; kill the connection.*/
  729. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  730. if (conn->type == CONN_TYPE_AP || conn->type == CONN_TYPE_EXIT) {
  731. connection_edge_end(conn, (char)(connection_state_is_open(conn) ?
  732. END_STREAM_REASON_MISC : END_STREAM_REASON_CONNECTFAILED),
  733. conn->cpath_layer);
  734. }
  735. connection_mark_for_close(conn);
  736. if (conn->type == CONN_TYPE_DIR &&
  737. conn->state == DIR_CONN_STATE_CONNECTING) {
  738. /* it's a directory server and connecting failed: forget about this router */
  739. /* XXX I suspect pollerr may make Windows not get to this point. :( */
  740. router_mark_as_down(conn->identity_digest);
  741. if(conn->purpose == DIR_PURPOSE_FETCH_DIR &&
  742. !all_trusted_directory_servers_down()) {
  743. log_fn(LOG_INFO,"Giving up on dirserver %s; trying another.", conn->address);
  744. directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL);
  745. }
  746. }
  747. return -1;
  748. }
  749. if (CONN_IS_EDGE(conn) &&
  750. try_to_read != max_to_read) {
  751. /* instruct it not to try to package partial cells. */
  752. if (connection_process_inbuf(conn, 0) < 0) {
  753. return -1;
  754. }
  755. if (connection_is_reading(conn) && !conn->inbuf_reached_eof)
  756. goto loop_again; /* try reading again, in case more is here now */
  757. }
  758. /* one last try, packaging partial cells and all. */
  759. if (connection_process_inbuf(conn, 1) < 0) {
  760. return -1;
  761. }
  762. if (conn->inbuf_reached_eof && connection_reached_eof(conn) < 0) {
  763. return -1;
  764. }
  765. return 0;
  766. }
  767. /** Pull in new bytes from conn-\>s onto conn-\>inbuf, either
  768. * directly or via TLS. Reduce the token buckets by the number of
  769. * bytes read.
  770. *
  771. * If *max_to_read is -1, then decide it ourselves, else go with the
  772. * value passed to us. When returning, if it's changed, subtract the
  773. * number of bytes we read from *max_to_read.
  774. *
  775. * Return -1 if we want to break conn, else return 0.
  776. */
  777. static int connection_read_to_buf(connection_t *conn, int *max_to_read) {
  778. int result, at_most = *max_to_read;
  779. if(at_most == -1) { /* we need to initialize it */
  780. /* how many bytes are we allowed to read? */
  781. at_most = connection_bucket_read_limit(conn);
  782. }
  783. if(connection_speaks_cells(conn) && conn->state != OR_CONN_STATE_CONNECTING) {
  784. if(conn->state == OR_CONN_STATE_HANDSHAKING) {
  785. /* continue handshaking even if global token bucket is empty */
  786. return connection_tls_continue_handshake(conn);
  787. }
  788. log_fn(LOG_DEBUG,"%d: starting, inbuf_datalen %d (%d pending in tls object). at_most %d.",
  789. conn->s,(int)buf_datalen(conn->inbuf),tor_tls_get_pending_bytes(conn->tls), at_most);
  790. /* else open, or closing */
  791. result = read_to_buf_tls(conn->tls, at_most, conn->inbuf);
  792. switch(result) {
  793. case TOR_TLS_CLOSE:
  794. log_fn(LOG_INFO,"TLS connection closed on read. Closing. (Nickname %s, address %s",
  795. conn->nickname ? conn->nickname : "not set", conn->address);
  796. return -1;
  797. case TOR_TLS_ERROR:
  798. log_fn(LOG_INFO,"tls error. breaking (nickname %s, address %s).",
  799. conn->nickname ? conn->nickname : "not set", conn->address);
  800. return -1;
  801. case TOR_TLS_WANTWRITE:
  802. connection_start_writing(conn);
  803. return 0;
  804. case TOR_TLS_WANTREAD: /* we're already reading */
  805. case TOR_TLS_DONE: /* no data read, so nothing to process */
  806. result = 0;
  807. break; /* so we call bucket_decrement below */
  808. }
  809. } else {
  810. result = read_to_buf(conn->s, at_most, conn->inbuf,
  811. &conn->inbuf_reached_eof);
  812. // log(LOG_DEBUG,"connection_read_to_buf(): read_to_buf returned %d.",read_result);
  813. if(result < 0)
  814. return -1;
  815. }
  816. if (result > 0) { /* change *max_to_read */
  817. *max_to_read = at_most - result;
  818. }
  819. if (result > 0 && !is_local_IP(conn->addr)) { /* remember it */
  820. rep_hist_note_bytes_read(result, time(NULL));
  821. connection_read_bucket_decrement(conn, result);
  822. }
  823. /* Call even if result is 0, since the global read bucket may
  824. * have reached 0 on a different conn, and this guy needs to
  825. * know to stop reading. */
  826. connection_consider_empty_buckets(conn);
  827. return 0;
  828. }
  829. /** A pass-through to fetch_from_buf. */
  830. int connection_fetch_from_buf(char *string, size_t len, connection_t *conn) {
  831. return fetch_from_buf(string, len, conn->inbuf);
  832. }
  833. /** Return conn-\>outbuf_flushlen: how many bytes conn wants to flush
  834. * from its outbuf. */
  835. int connection_wants_to_flush(connection_t *conn) {
  836. return conn->outbuf_flushlen;
  837. }
  838. /** Are there too many bytes on edge connection <b>conn</b>'s outbuf to
  839. * send back a relay-level sendme yet? Return 1 if so, 0 if not. Used by
  840. * connection_edge_consider_sending_sendme().
  841. */
  842. int connection_outbuf_too_full(connection_t *conn) {
  843. return (conn->outbuf_flushlen > 10*CELL_PAYLOAD_SIZE);
  844. }
  845. /** Try to flush more bytes onto conn-\>s.
  846. *
  847. * This function gets called either from conn_write() in main.c
  848. * when poll() has declared that conn wants to write, or below
  849. * from connection_write_to_buf() when an entire TLS record is ready.
  850. *
  851. * Update conn-\>timestamp_lastwritten to now, and call flush_buf
  852. * or flush_buf_tls appropriately. If it succeeds and there no more
  853. * more bytes on conn->outbuf, then call connection_finished_flushing
  854. * on it too.
  855. *
  856. * Mark the connection and return -1 if you want to close it, else
  857. * return 0.
  858. */
  859. int connection_handle_write(connection_t *conn) {
  860. int e, len=sizeof(e);
  861. int result;
  862. time_t now = time(NULL);
  863. tor_assert(!connection_is_listener(conn));
  864. conn->timestamp_lastwritten = now;
  865. /* Sometimes, "writeable" means "connected". */
  866. if (connection_state_is_connecting(conn)) {
  867. if (getsockopt(conn->s, SOL_SOCKET, SO_ERROR, (void*)&e, &len) < 0) {
  868. log_fn(LOG_WARN,"getsockopt() syscall failed?! Please report to tor-ops.");
  869. connection_close_immediate(conn);
  870. connection_mark_for_close(conn);
  871. return -1;
  872. }
  873. if(e) {
  874. /* some sort of error, but maybe just inprogress still */
  875. if(!ERRNO_IS_CONN_EINPROGRESS(e)) {
  876. log_fn(LOG_INFO,"in-progress connect failed. Removing.");
  877. connection_close_immediate(conn);
  878. connection_mark_for_close(conn);
  879. /* it's safe to pass OPs to router_mark_as_down(), since it just
  880. * ignores unrecognized routers
  881. */
  882. if (conn->type == CONN_TYPE_OR)
  883. router_mark_as_down(conn->identity_digest);
  884. return -1;
  885. } else {
  886. return 0; /* no change, see if next time is better */
  887. }
  888. }
  889. /* The connection is successful. */
  890. return connection_finished_connecting(conn);
  891. }
  892. if (connection_speaks_cells(conn)) {
  893. if (conn->state == OR_CONN_STATE_HANDSHAKING) {
  894. connection_stop_writing(conn);
  895. if(connection_tls_continue_handshake(conn) < 0) {
  896. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  897. connection_mark_for_close(conn);
  898. return -1;
  899. }
  900. return 0;
  901. }
  902. /* else open, or closing */
  903. result = flush_buf_tls(conn->tls, conn->outbuf, &conn->outbuf_flushlen);
  904. switch(result) {
  905. case TOR_TLS_ERROR:
  906. case TOR_TLS_CLOSE:
  907. log_fn(LOG_INFO,result==TOR_TLS_ERROR?
  908. "tls error. breaking.":"TLS connection closed on flush");
  909. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  910. connection_mark_for_close(conn);
  911. return -1;
  912. case TOR_TLS_WANTWRITE:
  913. log_fn(LOG_DEBUG,"wanted write.");
  914. /* we're already writing */
  915. return 0;
  916. case TOR_TLS_WANTREAD:
  917. /* Make sure to avoid a loop if the receive buckets are empty. */
  918. log_fn(LOG_DEBUG,"wanted read.");
  919. if(!connection_is_reading(conn)) {
  920. connection_stop_writing(conn);
  921. conn->wants_to_write = 1;
  922. /* we'll start reading again when the next second arrives,
  923. * and then also start writing again.
  924. */
  925. }
  926. /* else no problem, we're already reading */
  927. return 0;
  928. /* case TOR_TLS_DONE:
  929. * for TOR_TLS_DONE, fall through to check if the flushlen
  930. * is empty, so we can stop writing.
  931. */
  932. }
  933. } else {
  934. result = flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen);
  935. if (result < 0) {
  936. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  937. conn->has_sent_end = 1;
  938. connection_mark_for_close(conn);
  939. return -1;
  940. }
  941. }
  942. if(result > 0 && !is_local_IP(conn->addr)) { /* remember it */
  943. rep_hist_note_bytes_written(result, now);
  944. global_write_bucket -= result;
  945. }
  946. if(!connection_wants_to_flush(conn)) { /* it's done flushing */
  947. if(connection_finished_flushing(conn) < 0) {
  948. /* already marked */
  949. return -1;
  950. }
  951. }
  952. return 0;
  953. }
  954. /** Append <b>len</b> bytes of <b>string</b> onto <b>conn</b>'s
  955. * outbuf, and ask it to start writing.
  956. */
  957. void connection_write_to_buf(const char *string, size_t len, connection_t *conn) {
  958. if(!len || conn->marked_for_close)
  959. return;
  960. if(write_to_buf(string, len, conn->outbuf) < 0) {
  961. if(conn->type == CONN_TYPE_AP || conn->type == CONN_TYPE_EXIT) {
  962. /* if it failed, it means we have our package/delivery windows set
  963. wrong compared to our max outbuf size. close the whole circuit. */
  964. log_fn(LOG_WARN,"write_to_buf failed. Closing circuit (fd %d).", conn->s);
  965. circuit_mark_for_close(circuit_get_by_conn(conn));
  966. } else {
  967. log_fn(LOG_WARN,"write_to_buf failed. Closing connection (fd %d).", conn->s);
  968. connection_mark_for_close(conn);
  969. }
  970. return;
  971. }
  972. connection_start_writing(conn);
  973. conn->outbuf_flushlen += len;
  974. }
  975. /** Return the conn to addr/port that has the most recent
  976. * timestamp_created, or NULL if no such conn exists. */
  977. connection_t *connection_exact_get_by_addr_port(uint32_t addr, uint16_t port) {
  978. int i, n;
  979. connection_t *conn, *best=NULL;
  980. connection_t **carray;
  981. get_connection_array(&carray,&n);
  982. for(i=0;i<n;i++) {
  983. conn = carray[i];
  984. if(conn->addr == addr && conn->port == port && !conn->marked_for_close &&
  985. (!best || best->timestamp_created < conn->timestamp_created))
  986. best = conn;
  987. }
  988. return best;
  989. }
  990. connection_t *connection_get_by_identity_digest(const char *digest, int type)
  991. {
  992. int i, n;
  993. connection_t *conn, *best=NULL;
  994. connection_t **carray;
  995. get_connection_array(&carray,&n);
  996. for(i=0;i<n;i++) {
  997. conn = carray[i];
  998. if (conn->type != type)
  999. continue;
  1000. if (!memcmp(conn->identity_digest, digest, DIGEST_LEN)
  1001. && !conn->marked_for_close
  1002. && (!best || best->timestamp_created < conn->timestamp_created))
  1003. best = conn;
  1004. }
  1005. return best;
  1006. }
  1007. /** Return a connection of type <b>type</b> that is not marked for
  1008. * close.
  1009. */
  1010. connection_t *connection_get_by_type(int type) {
  1011. int i, n;
  1012. connection_t *conn;
  1013. connection_t **carray;
  1014. get_connection_array(&carray,&n);
  1015. for(i=0;i<n;i++) {
  1016. conn = carray[i];
  1017. if(conn->type == type && !conn->marked_for_close)
  1018. return conn;
  1019. }
  1020. return NULL;
  1021. }
  1022. /** Return a connection of type <b>type</b> that is in state <b>state</b>,
  1023. * and that is not marked for close.
  1024. */
  1025. connection_t *connection_get_by_type_state(int type, int state) {
  1026. int i, n;
  1027. connection_t *conn;
  1028. connection_t **carray;
  1029. get_connection_array(&carray,&n);
  1030. for(i=0;i<n;i++) {
  1031. conn = carray[i];
  1032. if(conn->type == type && conn->state == state && !conn->marked_for_close)
  1033. return conn;
  1034. }
  1035. return NULL;
  1036. }
  1037. /** Return the connection of type <b>type</b> that is in state
  1038. * <b>state</b>, that was written to least recently, and that is not
  1039. * marked for close.
  1040. */
  1041. connection_t *connection_get_by_type_state_lastwritten(int type, int state) {
  1042. int i, n;
  1043. connection_t *conn, *best=NULL;
  1044. connection_t **carray;
  1045. get_connection_array(&carray,&n);
  1046. for(i=0;i<n;i++) {
  1047. conn = carray[i];
  1048. if(conn->type == type && conn->state == state && !conn->marked_for_close)
  1049. if(!best || conn->timestamp_lastwritten < best->timestamp_lastwritten)
  1050. best = conn;
  1051. }
  1052. return best;
  1053. }
  1054. /** Return a connection of type <b>type</b> that has rendquery equal
  1055. * to <b>rendquery</b>, and that is not marked for close.
  1056. */
  1057. connection_t *connection_get_by_type_rendquery(int type, const char *rendquery) {
  1058. int i, n;
  1059. connection_t *conn;
  1060. connection_t **carray;
  1061. get_connection_array(&carray,&n);
  1062. for(i=0;i<n;i++) {
  1063. conn = carray[i];
  1064. if(conn->type == type &&
  1065. !conn->marked_for_close &&
  1066. !rend_cmp_service_ids(rendquery, conn->rend_query))
  1067. return conn;
  1068. }
  1069. return NULL;
  1070. }
  1071. /** Return 1 if <b>conn</b> is a listener conn, else return 0. */
  1072. int connection_is_listener(connection_t *conn) {
  1073. if(conn->type == CONN_TYPE_OR_LISTENER ||
  1074. conn->type == CONN_TYPE_AP_LISTENER ||
  1075. conn->type == CONN_TYPE_DIR_LISTENER ||
  1076. conn->type == CONN_TYPE_CONTROL_LISTENER)
  1077. return 1;
  1078. return 0;
  1079. }
  1080. /** Return 1 if <b>conn</b> is in state "open" and is not marked
  1081. * for close, else return 0.
  1082. */
  1083. int connection_state_is_open(connection_t *conn) {
  1084. tor_assert(conn);
  1085. if(conn->marked_for_close)
  1086. return 0;
  1087. if((conn->type == CONN_TYPE_OR && conn->state == OR_CONN_STATE_OPEN) ||
  1088. (conn->type == CONN_TYPE_AP && conn->state == AP_CONN_STATE_OPEN) ||
  1089. (conn->type == CONN_TYPE_EXIT && conn->state == EXIT_CONN_STATE_OPEN) ||
  1090. (conn->type == CONN_TYPE_CONTROL && conn->state ==CONTROL_CONN_STATE_OPEN))
  1091. return 1;
  1092. return 0;
  1093. }
  1094. /** Return 1 if conn is in 'connecting' state, else return 0. */
  1095. int connection_state_is_connecting(connection_t *conn) {
  1096. tor_assert(conn);
  1097. if (conn->marked_for_close)
  1098. return 0;
  1099. switch (conn->type)
  1100. {
  1101. case CONN_TYPE_OR:
  1102. return conn->state == OR_CONN_STATE_CONNECTING;
  1103. case CONN_TYPE_EXIT:
  1104. return conn->state == EXIT_CONN_STATE_CONNECTING;
  1105. case CONN_TYPE_DIR:
  1106. return conn->state == DIR_CONN_STATE_CONNECTING;
  1107. }
  1108. return 0;
  1109. }
  1110. /** Write a destroy cell with circ ID <b>circ_id</b> onto OR connection
  1111. * <b>conn</b>.
  1112. *
  1113. * Return 0.
  1114. */
  1115. int connection_send_destroy(uint16_t circ_id, connection_t *conn) {
  1116. cell_t cell;
  1117. tor_assert(conn);
  1118. tor_assert(connection_speaks_cells(conn));
  1119. memset(&cell, 0, sizeof(cell_t));
  1120. cell.circ_id = circ_id;
  1121. cell.command = CELL_DESTROY;
  1122. log_fn(LOG_INFO,"Sending destroy (circID %d).", circ_id);
  1123. connection_or_write_cell_to_buf(&cell, conn);
  1124. return 0;
  1125. }
  1126. /** Process new bytes that have arrived on conn-\>inbuf.
  1127. *
  1128. * This function just passes conn to the connection-specific
  1129. * connection_*_process_inbuf() function. It also passes in
  1130. * package_partial if wanted.
  1131. */
  1132. static int connection_process_inbuf(connection_t *conn, int package_partial) {
  1133. tor_assert(conn);
  1134. switch(conn->type) {
  1135. case CONN_TYPE_OR:
  1136. return connection_or_process_inbuf(conn);
  1137. case CONN_TYPE_EXIT:
  1138. case CONN_TYPE_AP:
  1139. return connection_edge_process_inbuf(conn, package_partial);
  1140. case CONN_TYPE_DIR:
  1141. return connection_dir_process_inbuf(conn);
  1142. case CONN_TYPE_DNSWORKER:
  1143. return connection_dns_process_inbuf(conn);
  1144. case CONN_TYPE_CPUWORKER:
  1145. return connection_cpu_process_inbuf(conn);
  1146. case CONN_TYPE_CONTROL:
  1147. return connection_control_process_inbuf(conn);
  1148. default:
  1149. log_fn(LOG_WARN,"got unexpected conn type %d.", conn->type);
  1150. return -1;
  1151. }
  1152. }
  1153. /** We just finished flushing bytes from conn-\>outbuf, and there
  1154. * are no more bytes remaining.
  1155. *
  1156. * This function just passes conn to the connection-specific
  1157. * connection_*_finished_flushing() function.
  1158. */
  1159. static int connection_finished_flushing(connection_t *conn) {
  1160. tor_assert(conn);
  1161. // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
  1162. switch(conn->type) {
  1163. case CONN_TYPE_OR:
  1164. return connection_or_finished_flushing(conn);
  1165. case CONN_TYPE_AP:
  1166. case CONN_TYPE_EXIT:
  1167. return connection_edge_finished_flushing(conn);
  1168. case CONN_TYPE_DIR:
  1169. return connection_dir_finished_flushing(conn);
  1170. case CONN_TYPE_DNSWORKER:
  1171. return connection_dns_finished_flushing(conn);
  1172. case CONN_TYPE_CPUWORKER:
  1173. return connection_cpu_finished_flushing(conn);
  1174. case CONN_TYPE_CONTROL:
  1175. return connection_control_finished_flushing(conn);
  1176. default:
  1177. log_fn(LOG_WARN,"got unexpected conn type %d.", conn->type);
  1178. return -1;
  1179. }
  1180. }
  1181. /** Called when our attempt to connect() to another server has just
  1182. * succeeded.
  1183. *
  1184. * This function just passes conn to the connection-specific
  1185. * connection_*_finished_connecting() function.
  1186. */
  1187. static int connection_finished_connecting(connection_t *conn)
  1188. {
  1189. tor_assert(conn);
  1190. switch (conn->type)
  1191. {
  1192. case CONN_TYPE_OR:
  1193. return connection_or_finished_connecting(conn);
  1194. case CONN_TYPE_EXIT:
  1195. return connection_edge_finished_connecting(conn);
  1196. case CONN_TYPE_DIR:
  1197. return connection_dir_finished_connecting(conn);
  1198. default:
  1199. log_fn(LOG_WARN,"got unexpected conn type %d.", conn->type);
  1200. return -1;
  1201. }
  1202. }
  1203. static int connection_reached_eof(connection_t *conn)
  1204. {
  1205. switch (conn->type) {
  1206. case CONN_TYPE_OR:
  1207. return connection_or_reached_eof(conn);
  1208. case CONN_TYPE_AP:
  1209. case CONN_TYPE_EXIT:
  1210. return connection_edge_reached_eof(conn);
  1211. case CONN_TYPE_DIR:
  1212. return connection_dir_reached_eof(conn);
  1213. case CONN_TYPE_DNSWORKER:
  1214. return connection_dns_reached_eof(conn);
  1215. case CONN_TYPE_CPUWORKER:
  1216. return connection_cpu_reached_eof(conn);
  1217. case CONN_TYPE_CONTROL:
  1218. return connection_control_reached_eof(conn);
  1219. default:
  1220. log_fn(LOG_WARN,"got unexpected conn type %d.", conn->type);
  1221. return -1;
  1222. }
  1223. }
  1224. /** Verify that connection <b>conn</b> has all of its invariants
  1225. * correct. Trigger an assert if anything is invalid.
  1226. */
  1227. void assert_connection_ok(connection_t *conn, time_t now)
  1228. {
  1229. tor_assert(conn);
  1230. tor_assert(conn->magic == CONNECTION_MAGIC);
  1231. tor_assert(conn->type >= _CONN_TYPE_MIN);
  1232. tor_assert(conn->type <= _CONN_TYPE_MAX);
  1233. if(conn->outbuf_flushlen > 0) {
  1234. tor_assert(connection_is_writing(conn) || conn->wants_to_write);
  1235. }
  1236. if(conn->hold_open_until_flushed)
  1237. tor_assert(conn->marked_for_close);
  1238. /* XXX check: wants_to_read, wants_to_write, s, poll_index,
  1239. * marked_for_close. */
  1240. /* buffers */
  1241. if (!connection_is_listener(conn)) {
  1242. assert_buf_ok(conn->inbuf);
  1243. assert_buf_ok(conn->outbuf);
  1244. }
  1245. #if 0 /* computers often go back in time; no way to know */
  1246. tor_assert(!now || conn->timestamp_lastread <= now);
  1247. tor_assert(!now || conn->timestamp_lastwritten <= now);
  1248. tor_assert(conn->timestamp_created <= conn->timestamp_lastread);
  1249. tor_assert(conn->timestamp_created <= conn->timestamp_lastwritten);
  1250. #endif
  1251. /* XXX Fix this; no longer so.*/
  1252. #if 0
  1253. if(conn->type != CONN_TYPE_OR && conn->type != CONN_TYPE_DIR)
  1254. tor_assert(!conn->pkey);
  1255. /* pkey is set if we're a dir client, or if we're an OR in state OPEN
  1256. * connected to another OR.
  1257. */
  1258. #endif
  1259. if (conn->type != CONN_TYPE_OR) {
  1260. tor_assert(!conn->tls);
  1261. } else {
  1262. if(conn->state == OR_CONN_STATE_OPEN) {
  1263. /* tor_assert(conn->bandwidth > 0); */
  1264. /* the above isn't necessarily true: if we just did a TLS
  1265. * handshake but we didn't recognize the other peer, or it
  1266. * gave a bad cert/etc, then we won't have assigned bandwidth,
  1267. * yet it will be open. -RD
  1268. */
  1269. tor_assert(conn->receiver_bucket >= 0);
  1270. }
  1271. tor_assert(conn->addr && conn->port);
  1272. tor_assert(conn->address);
  1273. if (conn->state != OR_CONN_STATE_CONNECTING)
  1274. tor_assert(conn->tls);
  1275. }
  1276. if (conn->type != CONN_TYPE_EXIT && conn->type != CONN_TYPE_AP) {
  1277. tor_assert(!conn->stream_id);
  1278. tor_assert(!conn->next_stream);
  1279. tor_assert(!conn->cpath_layer);
  1280. tor_assert(!conn->package_window);
  1281. tor_assert(!conn->deliver_window);
  1282. tor_assert(!conn->done_sending);
  1283. tor_assert(!conn->done_receiving);
  1284. } else {
  1285. /* XXX unchecked: package window, deliver window. */
  1286. }
  1287. if (conn->type == CONN_TYPE_AP) {
  1288. tor_assert(conn->socks_request);
  1289. if (conn->state == AP_CONN_STATE_OPEN) {
  1290. tor_assert(conn->socks_request->has_finished);
  1291. tor_assert(conn->cpath_layer);
  1292. assert_cpath_layer_ok(conn->cpath_layer);
  1293. }
  1294. } else {
  1295. tor_assert(!conn->socks_request);
  1296. }
  1297. if (conn->type == CONN_TYPE_EXIT) {
  1298. tor_assert(conn->purpose == EXIT_PURPOSE_CONNECT ||
  1299. conn->purpose == EXIT_PURPOSE_RESOLVE);
  1300. } else if(conn->type != CONN_TYPE_DIR) {
  1301. tor_assert(!conn->purpose); /* only used for dir types currently */
  1302. }
  1303. switch(conn->type)
  1304. {
  1305. case CONN_TYPE_OR_LISTENER:
  1306. case CONN_TYPE_AP_LISTENER:
  1307. case CONN_TYPE_DIR_LISTENER:
  1308. case CONN_TYPE_CONTROL_LISTENER:
  1309. tor_assert(conn->state == LISTENER_STATE_READY);
  1310. break;
  1311. case CONN_TYPE_OR:
  1312. tor_assert(conn->state >= _OR_CONN_STATE_MIN);
  1313. tor_assert(conn->state <= _OR_CONN_STATE_MAX);
  1314. break;
  1315. case CONN_TYPE_EXIT:
  1316. tor_assert(conn->state >= _EXIT_CONN_STATE_MIN);
  1317. tor_assert(conn->state <= _EXIT_CONN_STATE_MAX);
  1318. break;
  1319. case CONN_TYPE_AP:
  1320. tor_assert(conn->state >= _AP_CONN_STATE_MIN);
  1321. tor_assert(conn->state <= _AP_CONN_STATE_MAX);
  1322. tor_assert(conn->socks_request);
  1323. break;
  1324. case CONN_TYPE_DIR:
  1325. tor_assert(conn->state >= _DIR_CONN_STATE_MIN);
  1326. tor_assert(conn->state <= _DIR_CONN_STATE_MAX);
  1327. tor_assert(conn->purpose >= _DIR_PURPOSE_MIN);
  1328. tor_assert(conn->purpose <= _DIR_PURPOSE_MAX);
  1329. break;
  1330. case CONN_TYPE_DNSWORKER:
  1331. tor_assert(conn->state == DNSWORKER_STATE_IDLE ||
  1332. conn->state == DNSWORKER_STATE_BUSY);
  1333. break;
  1334. case CONN_TYPE_CPUWORKER:
  1335. tor_assert(conn->state >= _CPUWORKER_STATE_MIN);
  1336. tor_assert(conn->state <= _CPUWORKER_STATE_MAX);
  1337. break;
  1338. case CONN_TYPE_CONTROL:
  1339. tor_assert(conn->state >= _CONTROL_CONN_STATE_MIN);
  1340. tor_assert(conn->state <= _CONTROL_CONN_STATE_MAX);
  1341. break;
  1342. default:
  1343. tor_assert(0);
  1344. }
  1345. }
  1346. /*
  1347. Local Variables:
  1348. mode:c
  1349. indent-tabs-mode:nil
  1350. c-basic-offset:2
  1351. End:
  1352. */