connection.c 46 KB

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