stop wasting cpu time on authdirservers
[tor.git] / src / or / connection.c
blob3ea4fd6bab9f4a92a32f7984da2bf9b84f7962f0
1 /* Copyright 2001,2002,2003 Roger Dingledine, Matej Pfajfar. */
2 /* See LICENSE for licensing information */
3 /* $Id$ */
5 /**
6 * \file connection.c
7 * \brief General high-level functions to handle reading and writing
8 * on connections.
9 **/
11 #include "or.h"
13 /********* START VARIABLES **********/
15 extern or_options_t options; /* command-line and config-file options */
16 extern int shutting_down; /* whether we should refuse new connections */
18 /** Array of strings to make conn-\>type human-readable. */
19 char *conn_type_to_string[] = {
20 "", /* 0 */
21 "OP listener", /* 1 */
22 "OP", /* 2 */
23 "OR listener", /* 3 */
24 "OR", /* 4 */
25 "Exit", /* 5 */
26 "App listener",/* 6 */
27 "App", /* 7 */
28 "Dir listener",/* 8 */
29 "Dir", /* 9 */
30 "DNS worker", /* 10 */
31 "CPU worker", /* 11 */
34 /** Array of string arrays to make {conn-\>type,conn-\>state} human-readable. */
35 char *conn_state_to_string[][_CONN_TYPE_MAX+1] = {
36 { NULL }, /* no type associated with 0 */
37 { NULL }, /* op listener, obsolete */
38 { NULL }, /* op, obsolete */
39 { "ready" }, /* or listener, 0 */
40 { "", /* OR, 0 */
41 "connect()ing", /* 1 */
42 "handshaking", /* 2 */
43 "open" }, /* 3 */
44 { "", /* exit, 0 */
45 "waiting for dest info", /* 1 */
46 "connecting", /* 2 */
47 "open", /* 3 */
48 "resolve failed" }, /* 4 */
49 { "ready" }, /* app listener, 0 */
50 { "", /* 0 */
51 "", /* 1 */
52 "", /* 2 */
53 "", /* 3 */
54 "", /* 4 */
55 "awaiting dest info", /* app, 5 */
56 "waiting for rendezvous desc", /* 6 */
57 "waiting for safe circuit", /* 7 */
58 "waiting for connected", /* 8 */
59 "open" }, /* 9 */
60 { "ready" }, /* dir listener, 0 */
61 { "", /* dir, 0 */
62 "connecting", /* 1 */
63 "client sending", /* 2 */
64 "client reading", /* 3 */
65 "awaiting command", /* 4 */
66 "writing" }, /* 5 */
67 { "", /* dns worker, 0 */
68 "idle", /* 1 */
69 "busy" }, /* 2 */
70 { "", /* cpu worker, 0 */
71 "idle", /* 1 */
72 "busy with onion", /* 2 */
73 "busy with handshake" }, /* 3 */
76 /********* END VARIABLES ************/
78 static int connection_create_listener(const char *bindaddress,
79 uint16_t bindport, int type);
80 static int connection_init_accepted_conn(connection_t *conn);
81 static int connection_handle_listener_read(connection_t *conn, int new_type);
82 static int connection_receiver_bucket_should_increase(connection_t *conn);
83 static int connection_finished_flushing(connection_t *conn);
84 static int connection_finished_connecting(connection_t *conn);
85 static int connection_read_to_buf(connection_t *conn);
86 static int connection_process_inbuf(connection_t *conn);
88 /**************************************************************/
90 /** Allocate space for a new connection_t. This function just initializes
91 * conn; you must call connection_add() to link it into the main array.
93 * Set conn-\>type to <b>type</b>. Set conn-\>s and conn-\>poll_index to
94 * -1 to signify they are not yet assigned.
96 * If conn is not a listener type, allocate buffers for it. If it's
97 * an AP type, allocate space to store the socks_request.
99 * Assign a pseudorandom next_circ_id between 0 and 2**15.
101 * Initialize conn's timestamps to now.
103 connection_t *connection_new(int type) {
104 connection_t *conn;
105 time_t now = time(NULL);
107 conn = tor_malloc_zero(sizeof(connection_t));
108 conn->magic = CONNECTION_MAGIC;
109 conn->s = -1; /* give it a default of 'not used' */
110 conn->poll_index = -1; /* also default to 'not used' */
112 conn->type = type;
113 if(!connection_is_listener(conn)) { /* listeners never use their buf */
114 conn->inbuf = buf_new();
115 conn->outbuf = buf_new();
117 if (type == CONN_TYPE_AP) {
118 conn->socks_request = tor_malloc_zero(sizeof(socks_request_t));
121 conn->next_circ_id = crypto_pseudo_rand_int(1<<15);
123 conn->timestamp_created = now;
124 conn->timestamp_lastread = now;
125 conn->timestamp_lastwritten = now;
127 return conn;
130 /** Deallocate memory used by <b>conn</b>. Deallocate its buffers if necessary,
131 * close its socket if necessary, and mark the directory as dirty if <b>conn</b>
132 * is an OR or OP connection.
134 void connection_free(connection_t *conn) {
135 tor_assert(conn);
136 tor_assert(conn->magic == CONNECTION_MAGIC);
138 if(!connection_is_listener(conn)) {
139 buf_free(conn->inbuf);
140 buf_free(conn->outbuf);
142 tor_free(conn->address);
144 if(connection_speaks_cells(conn)) {
145 if(conn->state == OR_CONN_STATE_OPEN)
146 directory_set_dirty();
147 if (conn->tls)
148 tor_tls_free(conn->tls);
151 if (conn->identity_pkey)
152 crypto_free_pk_env(conn->identity_pkey);
153 tor_free(conn->nickname);
154 tor_free(conn->socks_request);
156 if(conn->s >= 0) {
157 log_fn(LOG_INFO,"closing fd %d.",conn->s);
158 tor_close_socket(conn->s);
160 memset(conn, 0xAA, sizeof(connection_t)); /* poison memory */
161 free(conn);
164 /** Call connection_free() on every connection in our array.
165 * This is used by cpuworkers and dnsworkers when they fork,
166 * so they don't keep resources held open (especially sockets).
168 void connection_free_all(void) {
169 int i, n;
170 connection_t **carray;
172 get_connection_array(&carray,&n);
173 for(i=0;i<n;i++)
174 connection_free(carray[i]);
177 void connection_about_to_close_connection(connection_t *conn)
180 assert(conn->marked_for_close);
182 if(conn->type == CONN_TYPE_AP || conn->type == CONN_TYPE_EXIT) {
183 if(!conn->has_sent_end)
184 log_fn(LOG_WARN,"Edge connection hasn't sent end yet? Bug.");
187 switch(conn->type) {
188 case CONN_TYPE_DIR:
189 if(conn->purpose == DIR_PURPOSE_FETCH_RENDDESC)
190 rend_client_desc_fetched(conn->rend_query, 0);
191 break;
192 case CONN_TYPE_OR:
193 /* Remember why we're closing this connection. */
194 if (conn->state != OR_CONN_STATE_OPEN) {
195 /* XXX Nick: this still isn't right, because it might be
196 * dying even though we didn't initiate the connect. Can
197 * you look at this more? -RD XXXX008 -NM*/
198 if(conn->nickname)
199 rep_hist_note_connect_failed(conn->identity_digest, time(NULL));
200 } else if (0) { // XXX reason == CLOSE_REASON_UNUSED_OR_CONN) {
201 rep_hist_note_disconnect(conn->identity_digest, time(NULL));
202 } else {
203 rep_hist_note_connection_died(conn->identity_digest, time(NULL));
205 break;
206 case CONN_TYPE_AP:
207 if (conn->socks_request->has_finished == 0) {
208 log_fn(LOG_INFO,"Cleaning up AP -- sending socks reject.");
209 connection_ap_handshake_socks_reply(conn, NULL, 0, 0);
210 conn->socks_request->has_finished = 1;
211 conn->hold_open_until_flushed = 1;
213 break;
214 case CONN_TYPE_EXIT:
215 if (conn->state == EXIT_CONN_STATE_RESOLVING) {
216 circuit_detach_stream(circuit_get_by_conn(conn), conn);
217 connection_dns_remove(conn);
219 break;
220 case CONN_TYPE_DNSWORKER:
221 if (conn->state == DNSWORKER_STATE_BUSY) {
222 dns_cancel_pending_resolve(conn->address);
224 break;
228 /** Close the underlying socket for <b>conn</b>, so we don't try to
229 * flush it. Must be used in conjunction with (right before)
230 * connection_mark_for_close().
232 void connection_close_immediate(connection_t *conn)
234 assert_connection_ok(conn,0);
235 if (conn->s < 0) {
236 log_fn(LOG_WARN,"Attempt to close already-closed connection.");
237 return;
239 if (conn->outbuf_flushlen) {
240 log_fn(LOG_INFO,"fd %d, type %s, state %d, %d bytes on outbuf.",
241 conn->s, CONN_TYPE_TO_STRING(conn->type),
242 conn->state, conn->outbuf_flushlen);
244 tor_close_socket(conn->s);
245 conn->s = -1;
246 if(!connection_is_listener(conn)) {
247 buf_clear(conn->outbuf);
248 conn->outbuf_flushlen = 0;
252 /** Mark <b>conn</b> to be closed next time we loop through
253 * conn_close_if_marked() in main.c. Do any cleanup needed:
254 * - Directory conns that fail to fetch a rendezvous descriptor need
255 * to inform pending rendezvous streams.
256 * - OR conns need to call rep_hist_note_*() to record status.
257 * - AP conns need to send a socks reject if necessary.
258 * - Exit conns need to call connection_dns_remove() if necessary.
259 * - AP and Exit conns need to send an end cell if they can.
260 * - DNS conns need to fail any resolves that are pending on them.
263 _connection_mark_for_close(connection_t *conn)
265 assert_connection_ok(conn,0);
267 if (conn->marked_for_close) {
268 log(LOG_WARN, "Double mark-for-close on connection.");
269 return -1;
272 conn->marked_for_close = 1;
274 /* in case we're going to be held-open-til-flushed, reset
275 * the number of seconds since last successful write, so
276 * we get our whole 15 seconds */
277 conn->timestamp_lastwritten = time(NULL);
279 return 0;
282 /** Find each connection that has hold_open_until_flushed set to
283 * 1 but hasn't written in the past 15 seconds, and set
284 * hold_open_until_flushed to 0. This means it will get cleaned
285 * up in the next loop through close_if_marked() in main.c.
287 void connection_expire_held_open(void)
289 connection_t **carray, *conn;
290 int n, i;
291 time_t now;
293 now = time(NULL);
295 get_connection_array(&carray, &n);
296 for (i = 0; i < n; ++i) {
297 conn = carray[i];
298 /* If we've been holding the connection open, but we haven't written
299 * for 15 seconds...
301 if (conn->hold_open_until_flushed) {
302 tor_assert(conn->marked_for_close);
303 if (now - conn->timestamp_lastwritten >= 15) {
304 log_fn(LOG_WARN,"Giving up on marked_for_close conn that's been flushing for 15s (fd %d, type %s, state %d).",
305 conn->s, CONN_TYPE_TO_STRING(conn->type), conn->state);
306 conn->hold_open_until_flushed = 0;
312 /** Bind a new non-blocking socket listening to
313 * <b>bindaddress</b>:<b>bindport</b>, and add this new connection
314 * (of type <b>type</b>) to the connection array.
316 * If <b>bindaddress</b> includes a port, we bind on that port; otherwise, we
317 * use bindport.
319 static int connection_create_listener(const char *bindaddress, uint16_t bindport, int type) {
320 struct sockaddr_in bindaddr; /* where to bind */
321 connection_t *conn;
322 char *hostname, *cp;
323 int usePort;
324 int s; /* the socket we're going to make */
325 int one=1;
328 cp = strchr(bindaddress, ':');
329 if (cp) {
330 hostname = tor_strndup(bindaddress, cp-bindaddress);
331 usePort = atoi(cp+1);
332 } else {
333 hostname = tor_strdup(bindaddress);
334 usePort = bindport;
337 memset(&bindaddr,0,sizeof(struct sockaddr_in));
338 bindaddr.sin_family = AF_INET;
339 bindaddr.sin_port = htons((uint16_t) usePort);
340 if(tor_lookup_hostname(hostname, &(bindaddr.sin_addr.s_addr)) != 0) {
341 log_fn(LOG_WARN,"Can't resolve BindAddress %s",hostname);
342 tor_free(hostname);
343 return -1;
345 tor_free(hostname);
347 s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
348 if (s < 0) {
349 log_fn(LOG_WARN,"Socket creation failed.");
350 return -1;
353 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*) &one, sizeof(one));
355 if(bind(s,(struct sockaddr *)&bindaddr,sizeof(bindaddr)) < 0) {
356 log_fn(LOG_WARN,"Could not bind to port %u: %s",usePort,
357 tor_socket_strerror(tor_socket_errno(s)));
358 return -1;
361 if(listen(s,SOMAXCONN) < 0) {
362 log_fn(LOG_WARN,"Could not listen on port %u: %s",usePort,
363 tor_socket_strerror(tor_socket_errno(s)));
364 return -1;
367 set_socket_nonblocking(s);
369 conn = connection_new(type);
370 conn->s = s;
372 if(connection_add(conn) < 0) { /* no space, forget it */
373 log_fn(LOG_WARN,"connection_add failed. Giving up.");
374 connection_free(conn);
375 return -1;
378 log_fn(LOG_DEBUG,"%s listening on port %u.",conn_type_to_string[type], usePort);
380 conn->state = LISTENER_STATE_READY;
381 connection_start_reading(conn);
383 return 0;
386 /** The listener connection <b>conn</b> told poll() it wanted to read.
387 * Call accept() on conn-\>s, and add the new connection if necessary.
389 static int connection_handle_listener_read(connection_t *conn, int new_type) {
390 int news; /* the new socket */
391 connection_t *newconn;
392 struct sockaddr_in remote; /* information about the remote peer when connecting to other routers */
393 int remotelen = sizeof(struct sockaddr_in); /* length of the remote address */
395 news = accept(conn->s,(struct sockaddr *)&remote,&remotelen);
396 if (news == -1) { /* accept() error */
397 if(ERRNO_IS_EAGAIN(tor_socket_errno(conn->s))) {
398 return 0; /* he hung up before we could accept(). that's fine. */
400 /* else there was a real error. */
401 log_fn(LOG_WARN,"accept() failed. Closing listener.");
402 connection_mark_for_close(conn);
403 return -1;
405 log(LOG_INFO,"Connection accepted on socket %d (child of fd %d).",news, conn->s);
407 if(shutting_down && new_type != CONN_TYPE_DIR) {
408 /* allow directory connections even while we're shutting down */
409 log(LOG_INFO,"But we're shutting down, so closing (type %d).", new_type);
410 tor_close_socket(news);
411 return 0;
414 set_socket_nonblocking(news);
416 /* process entrance policies here, before we even create the connection */
417 if(new_type == CONN_TYPE_AP) {
418 /* check sockspolicy to see if we should accept it */
419 if(socks_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
420 log_fn(LOG_WARN,"Denying socks connection from untrusted address %s.",
421 inet_ntoa(remote.sin_addr));
422 tor_close_socket(news);
423 return 0;
427 newconn = connection_new(new_type);
428 newconn->s = news;
430 newconn->address = tor_strdup(inet_ntoa(remote.sin_addr)); /* remember the remote address */
431 newconn->addr = ntohl(remote.sin_addr.s_addr);
432 newconn->port = ntohs(remote.sin_port);
434 if(connection_add(newconn) < 0) { /* no space, forget it */
435 connection_free(newconn);
436 return 0; /* no need to tear down the parent */
439 if(connection_init_accepted_conn(newconn) < 0) {
440 connection_mark_for_close(newconn);
441 return 0;
443 return 0;
446 /** Initialize states for newly accepted connection <b>conn</b>.
447 * If conn is an OR, start the tls handshake.
449 static int connection_init_accepted_conn(connection_t *conn) {
451 connection_start_reading(conn);
453 switch(conn->type) {
454 case CONN_TYPE_OR:
455 return connection_tls_start_handshake(conn, 1);
456 case CONN_TYPE_AP:
457 conn->state = AP_CONN_STATE_SOCKS_WAIT;
458 break;
459 case CONN_TYPE_DIR:
460 conn->purpose = DIR_PURPOSE_SERVER;
461 conn->state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
462 break;
464 return 0;
467 /** Take conn, make a nonblocking socket; try to connect to
468 * addr:port (they arrive in *host order*). If fail, return -1. Else
469 * assign s to conn->\s: if connected return 1, if EAGAIN return 0.
471 * address is used to make the logs useful.
473 * On success, add conn to the list of polled connections.
475 int connection_connect(connection_t *conn, char *address, uint32_t addr, uint16_t port) {
476 int s;
477 struct sockaddr_in dest_addr;
479 s=socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
480 if (s < 0) {
481 log_fn(LOG_WARN,"Error creating network socket.");
482 return -1;
484 set_socket_nonblocking(s);
486 memset(&dest_addr,0,sizeof(dest_addr));
487 dest_addr.sin_family = AF_INET;
488 dest_addr.sin_port = htons(port);
489 dest_addr.sin_addr.s_addr = htonl(addr);
491 log_fn(LOG_DEBUG,"Connecting to %s:%u.",address,port);
493 if(connect(s,(struct sockaddr *)&dest_addr,sizeof(dest_addr)) < 0) {
494 if(!ERRNO_IS_CONN_EINPROGRESS(tor_socket_errno(s))) {
495 /* yuck. kill it. */
496 log_fn(LOG_INFO,"Connect() to %s:%u failed: %s",address,port,
497 tor_socket_strerror(tor_socket_errno(s)));
498 tor_close_socket(s);
499 return -1;
500 } else {
501 /* it's in progress. set state appropriately and return. */
502 conn->s = s;
503 if(connection_add(conn) < 0) /* no space, forget it */
504 return -1;
505 log_fn(LOG_DEBUG,"connect in progress, socket %d.",s);
506 return 0;
510 /* it succeeded. we're connected. */
511 log_fn(LOG_INFO,"Connection to %s:%u established.",address,port);
512 conn->s = s;
513 if(connection_add(conn) < 0) /* no space, forget it */
514 return -1;
515 return 1;
518 /** If there exist any listeners of type <b>type</b> in the connection
519 * array, mark them for close.
521 static void listener_close_if_present(int type) {
522 connection_t *conn;
523 connection_t **carray;
524 int i,n;
525 tor_assert(type == CONN_TYPE_OR_LISTENER ||
526 type == CONN_TYPE_AP_LISTENER ||
527 type == CONN_TYPE_DIR_LISTENER);
528 get_connection_array(&carray,&n);
529 for(i=0;i<n;i++) {
530 conn = carray[i];
531 if (conn->type == type && !conn->marked_for_close) {
532 connection_close_immediate(conn);
533 connection_mark_for_close(conn);
538 static int retry_listeners(int type, struct config_line_t *cfg,
539 int port_option, const char *default_addr)
541 listener_close_if_present(type);
542 if (port_option) {
543 if (!cfg) {
544 if (connection_create_listener(default_addr, (uint16_t) port_option,
545 type)<0)
546 return -1;
547 } else {
548 for ( ; cfg; cfg = cfg->next) {
549 if (connection_create_listener(cfg->value, (uint16_t) port_option,
550 type)<0)
551 return -1;
555 return 0;
558 /** (Re)launch listeners for each port you should have open.
560 int retry_all_listeners(void) {
562 if (retry_listeners(CONN_TYPE_OR_LISTENER, options.ORBindAddress,
563 options.ORPort, "0.0.0.0")<0)
564 return -1;
565 if (retry_listeners(CONN_TYPE_DIR_LISTENER, options.DirBindAddress,
566 options.DirPort, "0.0.0.0")<0)
567 return -1;
568 if (retry_listeners(CONN_TYPE_AP_LISTENER, options.SocksBindAddress,
569 options.SocksPort, "127.0.0.1")<0)
570 return -1;
572 return 0;
575 extern int global_read_bucket;
577 /** How many bytes at most can we read onto this connection? */
578 int connection_bucket_read_limit(connection_t *conn) {
579 int at_most;
581 if(options.LinkPadding) {
582 at_most = global_read_bucket;
583 } else {
584 /* do a rudimentary round-robin so one circuit can't hog a connection */
585 if(connection_speaks_cells(conn)) {
586 at_most = 32*(CELL_NETWORK_SIZE);
587 } else {
588 at_most = 32*(RELAY_PAYLOAD_SIZE);
591 if(at_most > global_read_bucket)
592 at_most = global_read_bucket;
595 if(connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN)
596 if(at_most > conn->receiver_bucket)
597 at_most = conn->receiver_bucket;
599 return at_most;
602 /** We just read num_read onto conn. Decrement buckets appropriately. */
603 void connection_bucket_decrement(connection_t *conn, int num_read) {
604 global_read_bucket -= num_read; tor_assert(global_read_bucket >= 0);
605 if(connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
606 conn->receiver_bucket -= num_read; tor_assert(conn->receiver_bucket >= 0);
608 if(global_read_bucket == 0) {
609 log_fn(LOG_DEBUG,"global bucket exhausted. Pausing.");
610 conn->wants_to_read = 1;
611 connection_stop_reading(conn);
612 return;
614 if(connection_speaks_cells(conn) &&
615 conn->state == OR_CONN_STATE_OPEN &&
616 conn->receiver_bucket == 0) {
617 log_fn(LOG_DEBUG,"receiver bucket exhausted. Pausing.");
618 conn->wants_to_read = 1;
619 connection_stop_reading(conn);
623 /** Keep a timeval to know when time has passed enough to refill buckets */
624 static struct timeval current_time;
626 /** Initiatialize the global read bucket to options.BandwidthBurst,
627 * and current_time to the current time. */
628 void connection_bucket_init(void) {
629 tor_gettimeofday(&current_time);
630 global_read_bucket = options.BandwidthBurst; /* start it at max traffic */
633 /** Some time has passed; increment buckets appropriately. */
634 void connection_bucket_refill(struct timeval *now) {
635 int i, n;
636 connection_t *conn;
637 connection_t **carray;
639 if(now->tv_sec <= current_time.tv_sec)
640 return; /* wait until the second has rolled over */
642 current_time.tv_sec = now->tv_sec; /* update current_time */
643 /* (ignore usecs for now) */
645 /* refill the global bucket */
646 if(global_read_bucket < options.BandwidthBurst) {
647 global_read_bucket += options.BandwidthRate;
648 log_fn(LOG_DEBUG,"global_read_bucket now %d.", global_read_bucket);
651 /* refill the per-connection buckets */
652 get_connection_array(&carray,&n);
653 for(i=0;i<n;i++) {
654 conn = carray[i];
656 if(connection_receiver_bucket_should_increase(conn)) {
657 conn->receiver_bucket += conn->bandwidth;
658 //log_fn(LOG_DEBUG,"Receiver bucket %d now %d.", i, conn->receiver_bucket);
661 if(conn->wants_to_read == 1 /* it's marked to turn reading back on now */
662 && global_read_bucket > 0 /* and we're allowed to read */
663 && (!connection_speaks_cells(conn) ||
664 conn->state != OR_CONN_STATE_OPEN ||
665 conn->receiver_bucket > 0)) {
666 /* and either a non-cell conn or a cell conn with non-empty bucket */
667 log_fn(LOG_DEBUG,"waking up conn (fd %d)",conn->s);
668 conn->wants_to_read = 0;
669 connection_start_reading(conn);
670 if(conn->wants_to_write == 1) {
671 conn->wants_to_write = 0;
672 connection_start_writing(conn);
678 /** Is the receiver bucket for connection <b>conn</b> low enough that we
679 * should add another pile of tokens to it?
681 static int connection_receiver_bucket_should_increase(connection_t *conn) {
682 tor_assert(conn);
684 if(!connection_speaks_cells(conn))
685 return 0; /* edge connections don't use receiver_buckets */
686 if(conn->state != OR_CONN_STATE_OPEN)
687 return 0; /* only open connections play the rate limiting game */
689 tor_assert(conn->bandwidth > 0);
690 if(conn->receiver_bucket > 9*conn->bandwidth)
691 return 0;
693 return 1;
696 /** Read bytes from conn->\s and process them.
698 * This function gets called from conn_read() in main.c, either
699 * when poll() has declared that conn wants to read, or (for OR conns)
700 * when there are pending TLS bytes.
702 * It calls connection_read_to_buf() to bring in any new bytes,
703 * and then calls connection_process_inbuf() to process them.
705 * Mark the connection and return -1 if you want to close it, else
706 * return 0.
708 int connection_handle_read(connection_t *conn) {
710 conn->timestamp_lastread = time(NULL);
712 switch(conn->type) {
713 case CONN_TYPE_OR_LISTENER:
714 return connection_handle_listener_read(conn, CONN_TYPE_OR);
715 case CONN_TYPE_AP_LISTENER:
716 return connection_handle_listener_read(conn, CONN_TYPE_AP);
717 case CONN_TYPE_DIR_LISTENER:
718 return connection_handle_listener_read(conn, CONN_TYPE_DIR);
721 if(connection_read_to_buf(conn) < 0) {
722 /* There's a read error; kill the connection.*/
723 connection_close_immediate(conn); /* Don't flush; connection is dead. */
724 conn->has_sent_end = 1; /* XXX have we already sent the end? really? */
725 connection_mark_for_close(conn);
726 if(conn->type == CONN_TYPE_DIR &&
727 conn->state == DIR_CONN_STATE_CONNECTING) {
728 /* it's a directory server and connecting failed: forget about this router */
729 /* XXX I suspect pollerr may make Windows not get to this point. :( */
730 router_mark_as_down(conn->identity_digest);
731 if(conn->purpose == DIR_PURPOSE_FETCH_DIR && !all_directory_servers_down()) {
732 log_fn(LOG_INFO,"Giving up on dirserver %s; trying another.", conn->nickname);
733 directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 0);
736 return -1;
738 if(connection_process_inbuf(conn) < 0) {
739 // log_fn(LOG_DEBUG,"connection_process_inbuf returned -1.");
740 return -1;
742 return 0;
745 /** Pull in new bytes from conn-\>s onto conn-\>inbuf, either
746 * directly or via TLS. Reduce the token buckets by the number of
747 * bytes read.
749 * Return -1 if we want to break conn, else return 0.
751 static int connection_read_to_buf(connection_t *conn) {
752 int result;
753 int at_most;
755 /* how many bytes are we allowed to read? */
756 at_most = connection_bucket_read_limit(conn);
758 if(connection_speaks_cells(conn) && conn->state != OR_CONN_STATE_CONNECTING) {
759 if(conn->state == OR_CONN_STATE_HANDSHAKING) {
760 /* continue handshaking even if global token bucket is empty */
761 return connection_tls_continue_handshake(conn);
764 log_fn(LOG_DEBUG,"%d: starting, inbuf_datalen %d (%d pending in tls object). at_most %d.",
765 conn->s,(int)buf_datalen(conn->inbuf),tor_tls_get_pending_bytes(conn->tls), at_most);
767 /* else open, or closing */
768 result = read_to_buf_tls(conn->tls, at_most, conn->inbuf);
770 switch(result) {
771 case TOR_TLS_ERROR:
772 case TOR_TLS_CLOSE:
773 log_fn(LOG_INFO,"tls error. breaking (nickname %s, address %s).",
774 conn->nickname ? conn->nickname : "not set", conn->address);
775 return -1; /* XXX deal with close better */
776 case TOR_TLS_WANTWRITE:
777 connection_start_writing(conn);
778 return 0;
779 case TOR_TLS_WANTREAD: /* we're already reading */
780 case TOR_TLS_DONE: /* no data read, so nothing to process */
781 result = 0;
782 break; /* so we call bucket_decrement below */
784 } else {
785 result = read_to_buf(conn->s, at_most, conn->inbuf,
786 &conn->inbuf_reached_eof);
788 // log(LOG_DEBUG,"connection_read_to_buf(): read_to_buf returned %d.",read_result);
790 if(result < 0)
791 return -1;
794 if(result > 0 && !is_local_IP(conn->addr)) { /* remember it */
795 rep_hist_note_bytes_read(result, time(NULL));
798 connection_bucket_decrement(conn, result);
799 return 0;
802 /** A pass-through to fetch_from_buf. */
803 int connection_fetch_from_buf(char *string, int len, connection_t *conn) {
804 return fetch_from_buf(string, len, conn->inbuf);
807 /** Return conn-\>outbuf_flushlen: how many bytes conn wants to flush
808 * from its outbuf. */
809 int connection_wants_to_flush(connection_t *conn) {
810 return conn->outbuf_flushlen;
813 /** Are there too many bytes on edge connection <b>conn</b>'s outbuf to
814 * send back a relay-level sendme yet? Return 1 if so, 0 if not. Used by
815 * connection_edge_consider_sending_sendme().
817 int connection_outbuf_too_full(connection_t *conn) {
818 return (conn->outbuf_flushlen > 10*CELL_PAYLOAD_SIZE);
821 /** Try to flush more bytes onto conn-\>s.
823 * This function gets called either from conn_write() in main.c
824 * when poll() has declared that conn wants to write, or below
825 * from connection_write_to_buf() when an entire TLS record is ready.
827 * Update conn-\>timestamp_lastwritten to now, and call flush_buf
828 * or flush_buf_tls appropriately. If it succeeds and there no more
829 * more bytes on conn->outbuf, then call connection_finished_flushing
830 * on it too.
832 * Mark the connection and return -1 if you want to close it, else
833 * return 0.
835 int connection_handle_write(connection_t *conn) {
836 int e, len=sizeof(e);
837 int result;
838 time_t now = time(NULL);
840 tor_assert(!connection_is_listener(conn));
842 conn->timestamp_lastwritten = now;
844 /* Sometimes, "writeable" means "connected". */
845 if (connection_state_is_connecting(conn)) {
846 if (getsockopt(conn->s, SOL_SOCKET, SO_ERROR, (void*)&e, &len) < 0) {
847 log_fn(LOG_WARN,"getsockopt() syscall failed?! Please report to tor-ops.");
848 connection_close_immediate(conn);
849 connection_mark_for_close(conn);
850 return -1;
852 if(e) {
853 /* some sort of error, but maybe just inprogress still */
854 errno = e; /* XXX008 this is a kludge. maybe we should rearrange
855 our error-hunting functions? E.g. pass errno to
856 tor_socket_errno(). */
857 if(!ERRNO_IS_CONN_EINPROGRESS(tor_socket_errno(conn->s))) {
858 log_fn(LOG_INFO,"in-progress connect failed. Removing.");
859 connection_close_immediate(conn);
860 connection_mark_for_close(conn);
861 /* it's safe to pass OPs to router_mark_as_down(), since it just
862 * ignores unrecognized routers
864 if (conn->type == CONN_TYPE_OR)
865 router_mark_as_down(conn->identity_digest);
866 return -1;
867 } else {
868 return 0; /* no change, see if next time is better */
871 /* The connection is successful. */
872 return connection_finished_connecting(conn);
875 if (connection_speaks_cells(conn)) {
876 if (conn->state == OR_CONN_STATE_HANDSHAKING) {
877 connection_stop_writing(conn);
878 if(connection_tls_continue_handshake(conn) < 0) {
879 connection_close_immediate(conn); /* Don't flush; connection is dead. */
880 connection_mark_for_close(conn);
881 return -1;
883 return 0;
886 /* else open, or closing */
887 result = flush_buf_tls(conn->tls, conn->outbuf, &conn->outbuf_flushlen);
888 switch(result) {
889 case TOR_TLS_ERROR:
890 case TOR_TLS_CLOSE:
891 log_fn(LOG_INFO,"tls error. breaking.");
892 connection_close_immediate(conn); /* Don't flush; connection is dead. */
893 connection_mark_for_close(conn);
894 return -1; /* XXX deal with close better */
895 case TOR_TLS_WANTWRITE:
896 log_fn(LOG_DEBUG,"wanted write.");
897 /* we're already writing */
898 return 0;
899 case TOR_TLS_WANTREAD:
900 /* Make sure to avoid a loop if the receive buckets are empty. */
901 log_fn(LOG_DEBUG,"wanted read.");
902 if(!connection_is_reading(conn)) {
903 connection_stop_writing(conn);
904 conn->wants_to_write = 1;
905 /* we'll start reading again when the next second arrives,
906 * and then also start writing again.
909 /* else no problem, we're already reading */
910 return 0;
911 /* case TOR_TLS_DONE:
912 * for TOR_TLS_DONE, fall through to check if the flushlen
913 * is empty, so we can stop writing.
916 } else {
917 result = flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen);
918 if (result < 0) {
919 connection_close_immediate(conn); /* Don't flush; connection is dead. */
920 conn->has_sent_end = 1;
921 connection_mark_for_close(conn);
922 return -1;
926 if(result > 0 && !is_local_IP(conn->addr)) { /* remember it */
927 rep_hist_note_bytes_written(result, now);
930 if(!connection_wants_to_flush(conn)) { /* it's done flushing */
931 if(connection_finished_flushing(conn) < 0) {
932 /* already marked */
933 return -1;
937 return 0;
940 /** Append <b>len</b> bytes of <b>string</b> onto <b>conn</b>'s
941 * outbuf, and ask it to start writing.
943 void connection_write_to_buf(const char *string, int len, connection_t *conn) {
945 if(!len || conn->marked_for_close)
946 return;
948 if(write_to_buf(string, len, conn->outbuf) < 0) {
949 if(conn->type == CONN_TYPE_AP || conn->type == CONN_TYPE_EXIT) {
950 /* if it failed, it means we have our package/delivery windows set
951 wrong compared to our max outbuf size. close the whole circuit. */
952 log_fn(LOG_WARN,"write_to_buf failed. Closing circuit (fd %d).", conn->s);
953 circuit_mark_for_close(circuit_get_by_conn(conn));
954 } else {
955 log_fn(LOG_WARN,"write_to_buf failed. Closing connection (fd %d).", conn->s);
956 connection_mark_for_close(conn);
958 return;
961 connection_start_writing(conn);
962 conn->outbuf_flushlen += len;
965 /** Return the conn to addr/port that has the most recent
966 * timestamp_created, or NULL if no such conn exists. */
967 connection_t *connection_exact_get_by_addr_port(uint32_t addr, uint16_t port) {
968 int i, n;
969 connection_t *conn, *best=NULL;
970 connection_t **carray;
972 get_connection_array(&carray,&n);
973 for(i=0;i<n;i++) {
974 conn = carray[i];
975 if(conn->addr == addr && conn->port == port && !conn->marked_for_close &&
976 (!best || best->timestamp_created < conn->timestamp_created))
977 best = conn;
979 return best;
982 connection_t *connection_get_by_identity_digest(const char *digest, int type)
984 int i, n;
985 connection_t *conn, *best=NULL;
986 connection_t **carray;
988 get_connection_array(&carray,&n);
989 for(i=0;i<n;i++) {
990 conn = carray[i];
991 if (conn->type != type)
992 continue;
993 if (!memcmp(conn->identity_digest, digest, DIGEST_LEN)
994 && !conn->marked_for_close
995 && (!best || best->timestamp_created < conn->timestamp_created))
996 best = conn;
998 return best;
1001 /** Return a connection of type <b>type</b> that is not marked for
1002 * close.
1004 connection_t *connection_get_by_type(int type) {
1005 int i, n;
1006 connection_t *conn;
1007 connection_t **carray;
1009 get_connection_array(&carray,&n);
1010 for(i=0;i<n;i++) {
1011 conn = carray[i];
1012 if(conn->type == type && !conn->marked_for_close)
1013 return conn;
1015 return NULL;
1018 /** Return a connection of type <b>type</b> that is in state <b>state</b>,
1019 * and that is not marked for close.
1021 connection_t *connection_get_by_type_state(int type, int state) {
1022 int i, n;
1023 connection_t *conn;
1024 connection_t **carray;
1026 get_connection_array(&carray,&n);
1027 for(i=0;i<n;i++) {
1028 conn = carray[i];
1029 if(conn->type == type && conn->state == state && !conn->marked_for_close)
1030 return conn;
1032 return NULL;
1035 /** Return the connection of type <b>type</b> that is in state
1036 * <b>state</b>, that was written to least recently, and that is not
1037 * marked for close.
1039 connection_t *connection_get_by_type_state_lastwritten(int type, int state) {
1040 int i, n;
1041 connection_t *conn, *best=NULL;
1042 connection_t **carray;
1044 get_connection_array(&carray,&n);
1045 for(i=0;i<n;i++) {
1046 conn = carray[i];
1047 if(conn->type == type && conn->state == state && !conn->marked_for_close)
1048 if(!best || conn->timestamp_lastwritten < best->timestamp_lastwritten)
1049 best = conn;
1051 return best;
1054 /** Return a connection of type <b>type</b> that has rendquery equal
1055 * to <b>rendquery</b>, and that is not marked for close.
1057 connection_t *connection_get_by_type_rendquery(int type, const char *rendquery) {
1058 int i, n;
1059 connection_t *conn;
1060 connection_t **carray;
1062 get_connection_array(&carray,&n);
1063 for(i=0;i<n;i++) {
1064 conn = carray[i];
1065 if(conn->type == type &&
1066 !conn->marked_for_close &&
1067 !rend_cmp_service_ids(rendquery, conn->rend_query))
1068 return conn;
1070 return NULL;
1073 /** Return 1 if <b>conn</b> is a listener conn, else return 0. */
1074 int connection_is_listener(connection_t *conn) {
1075 if(conn->type == CONN_TYPE_OR_LISTENER ||
1076 conn->type == CONN_TYPE_AP_LISTENER ||
1077 conn->type == CONN_TYPE_DIR_LISTENER)
1078 return 1;
1079 return 0;
1082 /** Return 1 if <b>conn</b> is in state "open" and is not marked
1083 * for close, else return 0.
1085 int connection_state_is_open(connection_t *conn) {
1086 tor_assert(conn);
1088 if(conn->marked_for_close)
1089 return 0;
1091 if((conn->type == CONN_TYPE_OR && conn->state == OR_CONN_STATE_OPEN) ||
1092 (conn->type == CONN_TYPE_AP && conn->state == AP_CONN_STATE_OPEN) ||
1093 (conn->type == CONN_TYPE_EXIT && conn->state == EXIT_CONN_STATE_OPEN))
1094 return 1;
1096 return 0;
1099 /** Return 1 if conn is in 'connecting' state, else return 0. */
1100 int connection_state_is_connecting(connection_t *conn) {
1101 tor_assert(conn);
1103 if (conn->marked_for_close)
1104 return 0;
1105 switch (conn->type)
1107 case CONN_TYPE_OR:
1108 return conn->state == OR_CONN_STATE_CONNECTING;
1109 case CONN_TYPE_EXIT:
1110 return conn->state == EXIT_CONN_STATE_CONNECTING;
1111 case CONN_TYPE_DIR:
1112 return conn->state == DIR_CONN_STATE_CONNECTING;
1115 return 0;
1118 /** Write a destroy cell with circ ID <b>circ_id</b> onto OR connection
1119 * <b>conn</b>.
1121 * Return 0.
1123 int connection_send_destroy(uint16_t circ_id, connection_t *conn) {
1124 cell_t cell;
1126 tor_assert(conn);
1127 tor_assert(connection_speaks_cells(conn));
1129 memset(&cell, 0, sizeof(cell_t));
1130 cell.circ_id = circ_id;
1131 cell.command = CELL_DESTROY;
1132 log_fn(LOG_INFO,"Sending destroy (circID %d).", circ_id);
1133 connection_or_write_cell_to_buf(&cell, conn);
1134 return 0;
1137 /** Process new bytes that have arrived on conn-\>inbuf.
1139 * This function just passes conn to the connection-specific
1140 * connection_*_process_inbuf() function.
1142 static int connection_process_inbuf(connection_t *conn) {
1144 tor_assert(conn);
1146 switch(conn->type) {
1147 case CONN_TYPE_OR:
1148 return connection_or_process_inbuf(conn);
1149 case CONN_TYPE_EXIT:
1150 case CONN_TYPE_AP:
1151 return connection_edge_process_inbuf(conn);
1152 case CONN_TYPE_DIR:
1153 return connection_dir_process_inbuf(conn);
1154 case CONN_TYPE_DNSWORKER:
1155 return connection_dns_process_inbuf(conn);
1156 case CONN_TYPE_CPUWORKER:
1157 return connection_cpu_process_inbuf(conn);
1158 default:
1159 log_fn(LOG_WARN,"got unexpected conn->type %d.", conn->type);
1160 return -1;
1164 /** We just finished flushing bytes from conn-\>outbuf, and there
1165 * are no more bytes remaining.
1167 * This function just passes conn to the connection-specific
1168 * connection_*_finished_flushing() function.
1170 static int connection_finished_flushing(connection_t *conn) {
1172 tor_assert(conn);
1174 // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
1176 switch(conn->type) {
1177 case CONN_TYPE_OR:
1178 return connection_or_finished_flushing(conn);
1179 case CONN_TYPE_AP:
1180 case CONN_TYPE_EXIT:
1181 return connection_edge_finished_flushing(conn);
1182 case CONN_TYPE_DIR:
1183 return connection_dir_finished_flushing(conn);
1184 case CONN_TYPE_DNSWORKER:
1185 return connection_dns_finished_flushing(conn);
1186 case CONN_TYPE_CPUWORKER:
1187 return connection_cpu_finished_flushing(conn);
1188 default:
1189 log_fn(LOG_WARN,"got unexpected conn->type %d.", conn->type);
1190 return -1;
1194 /** Called when our attempt to connect() to another server has just
1195 * succeeded.
1197 * This function just passes conn to the connection-specific
1198 * connection_*_finished_connecting() function.
1200 static int connection_finished_connecting(connection_t *conn)
1202 tor_assert(conn);
1203 switch (conn->type)
1205 case CONN_TYPE_OR:
1206 return connection_or_finished_connecting(conn);
1207 case CONN_TYPE_EXIT:
1208 return connection_edge_finished_connecting(conn);
1209 case CONN_TYPE_DIR:
1210 return connection_dir_finished_connecting(conn);
1211 default:
1212 tor_assert(0);
1213 return -1;
1217 /** Verify that connection <b>conn</b> has all of its invariants
1218 * correct. Trigger an assert if anything is invalid.
1220 void assert_connection_ok(connection_t *conn, time_t now)
1222 tor_assert(conn);
1223 tor_assert(conn->magic == CONNECTION_MAGIC);
1224 tor_assert(conn->type >= _CONN_TYPE_MIN);
1225 tor_assert(conn->type <= _CONN_TYPE_MAX);
1227 if(conn->outbuf_flushlen > 0) {
1228 tor_assert(connection_is_writing(conn) || conn->wants_to_write);
1231 if(conn->hold_open_until_flushed)
1232 tor_assert(conn->marked_for_close);
1234 /* XXX check: wants_to_read, wants_to_write, s, poll_index,
1235 * marked_for_close. */
1237 /* buffers */
1238 if (!connection_is_listener(conn)) {
1239 assert_buf_ok(conn->inbuf);
1240 assert_buf_ok(conn->outbuf);
1243 #if 0 /* computers often go back in time; no way to know */
1244 tor_assert(!now || conn->timestamp_lastread <= now);
1245 tor_assert(!now || conn->timestamp_lastwritten <= now);
1246 tor_assert(conn->timestamp_created <= conn->timestamp_lastread);
1247 tor_assert(conn->timestamp_created <= conn->timestamp_lastwritten);
1248 #endif
1250 /* XXX Fix this; no longer so.*/
1251 #if 0
1252 if(conn->type != CONN_TYPE_OR && conn->type != CONN_TYPE_DIR)
1253 tor_assert(!conn->pkey);
1254 /* pkey is set if we're a dir client, or if we're an OR in state OPEN
1255 * connected to another OR.
1257 #endif
1259 if (conn->type != CONN_TYPE_OR) {
1260 tor_assert(!conn->tls);
1261 } else {
1262 if(conn->state == OR_CONN_STATE_OPEN) {
1263 /* tor_assert(conn->bandwidth > 0); */
1264 /* the above isn't necessarily true: if we just did a TLS
1265 * handshake but we didn't recognize the other peer, or it
1266 * gave a bad cert/etc, then we won't have assigned bandwidth,
1267 * yet it will be open. -RD
1269 tor_assert(conn->receiver_bucket >= 0);
1271 tor_assert(conn->addr && conn->port);
1272 tor_assert(conn->address);
1273 if (conn->state != OR_CONN_STATE_CONNECTING)
1274 tor_assert(conn->tls);
1277 if (conn->type != CONN_TYPE_EXIT && conn->type != CONN_TYPE_AP) {
1278 tor_assert(!conn->stream_id);
1279 tor_assert(!conn->next_stream);
1280 tor_assert(!conn->cpath_layer);
1281 tor_assert(!conn->package_window);
1282 tor_assert(!conn->deliver_window);
1283 tor_assert(!conn->done_sending);
1284 tor_assert(!conn->done_receiving);
1285 } else {
1286 /* XXX unchecked: package window, deliver window. */
1288 if (conn->type == CONN_TYPE_AP) {
1289 tor_assert(conn->socks_request);
1290 if (conn->state == AP_CONN_STATE_OPEN) {
1291 tor_assert(conn->socks_request->has_finished);
1292 tor_assert(conn->cpath_layer);
1293 assert_cpath_layer_ok(conn->cpath_layer);
1295 } else {
1296 tor_assert(!conn->socks_request);
1298 if (conn->type == CONN_TYPE_EXIT) {
1299 tor_assert(conn->purpose == EXIT_PURPOSE_CONNECT ||
1300 conn->purpose == EXIT_PURPOSE_RESOLVE);
1301 } else if(conn->type != CONN_TYPE_DIR) {
1302 tor_assert(!conn->purpose); /* only used for dir types currently */
1305 switch(conn->type)
1307 case CONN_TYPE_OR_LISTENER:
1308 case CONN_TYPE_AP_LISTENER:
1309 case CONN_TYPE_DIR_LISTENER:
1310 tor_assert(conn->state == LISTENER_STATE_READY);
1311 break;
1312 case CONN_TYPE_OR:
1313 tor_assert(conn->state >= _OR_CONN_STATE_MIN &&
1314 conn->state <= _OR_CONN_STATE_MAX);
1315 break;
1316 case CONN_TYPE_EXIT:
1317 tor_assert(conn->state >= _EXIT_CONN_STATE_MIN &&
1318 conn->state <= _EXIT_CONN_STATE_MAX);
1319 break;
1320 case CONN_TYPE_AP:
1321 tor_assert(conn->state >= _AP_CONN_STATE_MIN &&
1322 conn->state <= _AP_CONN_STATE_MAX);
1323 tor_assert(conn->socks_request);
1324 break;
1325 case CONN_TYPE_DIR:
1326 tor_assert(conn->state >= _DIR_CONN_STATE_MIN &&
1327 conn->state <= _DIR_CONN_STATE_MAX);
1328 tor_assert(conn->purpose >= _DIR_PURPOSE_MIN &&
1329 conn->purpose <= _DIR_PURPOSE_MAX);
1330 break;
1331 case CONN_TYPE_DNSWORKER:
1332 tor_assert(conn->state == DNSWORKER_STATE_IDLE ||
1333 conn->state == DNSWORKER_STATE_BUSY);
1334 break;
1335 case CONN_TYPE_CPUWORKER:
1336 tor_assert(conn->state >= _CPUWORKER_STATE_MIN &&
1337 conn->state <= _CPUWORKER_STATE_MAX);
1338 break;
1339 default:
1340 tor_assert(0);
1345 Local Variables:
1346 mode:c
1347 indent-tabs-mode:nil
1348 c-basic-offset:2
1349 End: