1 /* Copyright 2001,2002,2003 Roger Dingledine, Matej Pfajfar. */
2 /* See LICENSE for licensing information */
7 * \brief General high-level functions to handle reading and writing
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
[] = {
21 "OP listener", /* 1 */
23 "OR listener", /* 3 */
26 "App listener",/* 6 */
28 "Dir listener",/* 8 */
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 */
41 "connect()ing", /* 1 */
42 "handshaking", /* 2 */
45 "waiting for dest info", /* 1 */
48 "resolve failed" }, /* 4 */
49 { "ready" }, /* app listener, 0 */
55 "awaiting dest info", /* app, 5 */
56 "waiting for rendezvous desc", /* 6 */
57 "waiting for safe circuit", /* 7 */
58 "waiting for connected", /* 8 */
60 { "ready" }, /* dir listener, 0 */
63 "client sending", /* 2 */
64 "client reading", /* 3 */
65 "awaiting command", /* 4 */
67 { "", /* dns worker, 0 */
70 { "", /* cpu worker, 0 */
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
) {
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' */
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
;
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
) {
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();
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
);
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 */
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) {
170 connection_t
**carray
;
172 get_connection_array(&carray
,&n
);
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.");
189 if(conn
->purpose
== DIR_PURPOSE_FETCH_RENDDESC
)
190 rend_client_desc_fetched(conn
->rend_query
, 0);
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*/
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
));
203 rep_hist_note_connection_died(conn
->identity_digest
, time(NULL
));
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;
215 if (conn
->state
== EXIT_CONN_STATE_RESOLVING
) {
216 circuit_detach_stream(circuit_get_by_conn(conn
), conn
);
217 connection_dns_remove(conn
);
220 case CONN_TYPE_DNSWORKER
:
221 if (conn
->state
== DNSWORKER_STATE_BUSY
) {
222 dns_cancel_pending_resolve(conn
->address
);
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);
236 log_fn(LOG_WARN
,"Attempt to close already-closed connection.");
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
);
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.");
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
);
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
;
295 get_connection_array(&carray
, &n
);
296 for (i
= 0; i
< n
; ++i
) {
298 /* If we've been holding the connection open, but we haven't written
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
319 static int connection_create_listener(const char *bindaddress
, uint16_t bindport
, int type
) {
320 struct sockaddr_in bindaddr
; /* where to bind */
324 int s
; /* the socket we're going to make */
328 cp
= strchr(bindaddress
, ':');
330 hostname
= tor_strndup(bindaddress
, cp
-bindaddress
);
331 usePort
= atoi(cp
+1);
333 hostname
= tor_strdup(bindaddress
);
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
);
347 s
= socket(PF_INET
,SOCK_STREAM
,IPPROTO_TCP
);
349 log_fn(LOG_WARN
,"Socket creation failed.");
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
)));
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
)));
367 set_socket_nonblocking(s
);
369 conn
= connection_new(type
);
372 if(connection_add(conn
) < 0) { /* no space, forget it */
373 log_fn(LOG_WARN
,"connection_add failed. Giving up.");
374 connection_free(conn
);
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
);
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
);
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
);
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
);
427 newconn
= connection_new(new_type
);
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
);
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
);
455 return connection_tls_start_handshake(conn
, 1);
457 conn
->state
= AP_CONN_STATE_SOCKS_WAIT
;
460 conn
->purpose
= DIR_PURPOSE_SERVER
;
461 conn
->state
= DIR_CONN_STATE_SERVER_COMMAND_WAIT
;
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
) {
477 struct sockaddr_in dest_addr
;
479 s
=socket(PF_INET
,SOCK_STREAM
,IPPROTO_TCP
);
481 log_fn(LOG_WARN
,"Error creating network socket.");
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
))) {
496 log_fn(LOG_INFO
,"Connect() to %s:%u failed: %s",address
,port
,
497 tor_socket_strerror(tor_socket_errno(s
)));
501 /* it's in progress. set state appropriately and return. */
503 if(connection_add(conn
) < 0) /* no space, forget it */
505 log_fn(LOG_DEBUG
,"connect in progress, socket %d.",s
);
510 /* it succeeded. we're connected. */
511 log_fn(LOG_INFO
,"Connection to %s:%u established.",address
,port
);
513 if(connection_add(conn
) < 0) /* no space, forget it */
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
) {
523 connection_t
**carray
;
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
);
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
);
544 if (connection_create_listener(default_addr
, (uint16_t) port_option
,
548 for ( ; cfg
; cfg
= cfg
->next
) {
549 if (connection_create_listener(cfg
->value
, (uint16_t) port_option
,
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)
565 if (retry_listeners(CONN_TYPE_DIR_LISTENER
, options
.DirBindAddress
,
566 options
.DirPort
, "0.0.0.0")<0)
568 if (retry_listeners(CONN_TYPE_AP_LISTENER
, options
.SocksBindAddress
,
569 options
.SocksPort
, "127.0.0.1")<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
) {
581 if(options
.LinkPadding
) {
582 at_most
= global_read_bucket
;
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
);
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
;
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
);
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(¤t_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
) {
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
);
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
) {
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
)
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
708 int connection_handle_read(connection_t
*conn
) {
710 conn
->timestamp_lastread
= time(NULL
);
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);
738 if(connection_process_inbuf(conn
) < 0) {
739 // log_fn(LOG_DEBUG,"connection_process_inbuf returned -1.");
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
749 * Return -1 if we want to break conn, else return 0.
751 static int connection_read_to_buf(connection_t
*conn
) {
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
);
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
);
779 case TOR_TLS_WANTREAD
: /* we're already reading */
780 case TOR_TLS_DONE
: /* no data read, so nothing to process */
782 break; /* so we call bucket_decrement below */
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);
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
);
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
832 * Mark the connection and return -1 if you want to close it, else
835 int connection_handle_write(connection_t
*conn
) {
836 int e
, len
=sizeof(e
);
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
);
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
);
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
);
886 /* else open, or closing */
887 result
= flush_buf_tls(conn
->tls
, conn
->outbuf
, &conn
->outbuf_flushlen
);
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 */
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 */
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.
917 result
= flush_buf(conn
->s
, conn
->outbuf
, &conn
->outbuf_flushlen
);
919 connection_close_immediate(conn
); /* Don't flush; connection is dead. */
920 conn
->has_sent_end
= 1;
921 connection_mark_for_close(conn
);
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) {
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
)
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
));
955 log_fn(LOG_WARN
,"write_to_buf failed. Closing connection (fd %d).", conn
->s
);
956 connection_mark_for_close(conn
);
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
) {
969 connection_t
*conn
, *best
=NULL
;
970 connection_t
**carray
;
972 get_connection_array(&carray
,&n
);
975 if(conn
->addr
== addr
&& conn
->port
== port
&& !conn
->marked_for_close
&&
976 (!best
|| best
->timestamp_created
< conn
->timestamp_created
))
982 connection_t
*connection_get_by_identity_digest(const char *digest
, int type
)
985 connection_t
*conn
, *best
=NULL
;
986 connection_t
**carray
;
988 get_connection_array(&carray
,&n
);
991 if (conn
->type
!= type
)
993 if (!memcmp(conn
->identity_digest
, digest
, DIGEST_LEN
)
994 && !conn
->marked_for_close
995 && (!best
|| best
->timestamp_created
< conn
->timestamp_created
))
1001 /** Return a connection of type <b>type</b> that is not marked for
1004 connection_t
*connection_get_by_type(int type
) {
1007 connection_t
**carray
;
1009 get_connection_array(&carray
,&n
);
1012 if(conn
->type
== type
&& !conn
->marked_for_close
)
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
) {
1024 connection_t
**carray
;
1026 get_connection_array(&carray
,&n
);
1029 if(conn
->type
== type
&& conn
->state
== state
&& !conn
->marked_for_close
)
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
1039 connection_t
*connection_get_by_type_state_lastwritten(int type
, int state
) {
1041 connection_t
*conn
, *best
=NULL
;
1042 connection_t
**carray
;
1044 get_connection_array(&carray
,&n
);
1047 if(conn
->type
== type
&& conn
->state
== state
&& !conn
->marked_for_close
)
1048 if(!best
|| conn
->timestamp_lastwritten
< best
->timestamp_lastwritten
)
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
) {
1060 connection_t
**carray
;
1062 get_connection_array(&carray
,&n
);
1065 if(conn
->type
== type
&&
1066 !conn
->marked_for_close
&&
1067 !rend_cmp_service_ids(rendquery
, conn
->rend_query
))
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
)
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
) {
1088 if(conn
->marked_for_close
)
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
))
1099 /** Return 1 if conn is in 'connecting' state, else return 0. */
1100 int connection_state_is_connecting(connection_t
*conn
) {
1103 if (conn
->marked_for_close
)
1108 return conn
->state
== OR_CONN_STATE_CONNECTING
;
1109 case CONN_TYPE_EXIT
:
1110 return conn
->state
== EXIT_CONN_STATE_CONNECTING
;
1112 return conn
->state
== DIR_CONN_STATE_CONNECTING
;
1118 /** Write a destroy cell with circ ID <b>circ_id</b> onto OR connection
1123 int connection_send_destroy(uint16_t circ_id
, connection_t
*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
);
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
) {
1146 switch(conn
->type
) {
1148 return connection_or_process_inbuf(conn
);
1149 case CONN_TYPE_EXIT
:
1151 return connection_edge_process_inbuf(conn
);
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
);
1159 log_fn(LOG_WARN
,"got unexpected conn->type %d.", conn
->type
);
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
) {
1174 // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
1176 switch(conn
->type
) {
1178 return connection_or_finished_flushing(conn
);
1180 case CONN_TYPE_EXIT
:
1181 return connection_edge_finished_flushing(conn
);
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
);
1189 log_fn(LOG_WARN
,"got unexpected conn->type %d.", conn
->type
);
1194 /** Called when our attempt to connect() to another server has just
1197 * This function just passes conn to the connection-specific
1198 * connection_*_finished_connecting() function.
1200 static int connection_finished_connecting(connection_t
*conn
)
1206 return connection_or_finished_connecting(conn
);
1207 case CONN_TYPE_EXIT
:
1208 return connection_edge_finished_connecting(conn
);
1210 return connection_dir_finished_connecting(conn
);
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
)
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. */
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
);
1250 /* XXX Fix this; no longer so.*/
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.
1259 if (conn
->type
!= CONN_TYPE_OR
) {
1260 tor_assert(!conn
->tls
);
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
);
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
);
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 */
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
);
1313 tor_assert(conn
->state
>= _OR_CONN_STATE_MIN
&&
1314 conn
->state
<= _OR_CONN_STATE_MAX
);
1316 case CONN_TYPE_EXIT
:
1317 tor_assert(conn
->state
>= _EXIT_CONN_STATE_MIN
&&
1318 conn
->state
<= _EXIT_CONN_STATE_MAX
);
1321 tor_assert(conn
->state
>= _AP_CONN_STATE_MIN
&&
1322 conn
->state
<= _AP_CONN_STATE_MAX
);
1323 tor_assert(conn
->socks_request
);
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
);
1331 case CONN_TYPE_DNSWORKER
:
1332 tor_assert(conn
->state
== DNSWORKER_STATE_IDLE
||
1333 conn
->state
== DNSWORKER_STATE_BUSY
);
1335 case CONN_TYPE_CPUWORKER
:
1336 tor_assert(conn
->state
>= _CPUWORKER_STATE_MIN
&&
1337 conn
->state
<= _CPUWORKER_STATE_MAX
);
1347 indent-tabs-mode:nil