connection.c 43 KB

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