1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2012, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
9 * \brief General high-level functions to handle reading and writing
15 #include "circuitbuild.h"
16 #include "circuitlist.h"
17 #include "circuituse.h"
19 #include "connection.h"
20 #include "connection_edge.h"
21 #include "connection_or.h"
23 #include "cpuworker.h"
24 #include "directory.h"
33 #include "rendclient.h"
34 #include "rendcommon.h"
37 #include "transports.h"
38 #include "routerparse.h"
40 #ifdef USE_BUFFEREVENTS
41 #include <event2/event.h>
48 static connection_t
*connection_listener_new(
49 const struct sockaddr
*listensockaddr
,
50 socklen_t listensocklen
, int type
,
52 const port_cfg_t
*portcfg
);
53 static void connection_init(time_t now
, connection_t
*conn
, int type
,
55 static int connection_init_accepted_conn(connection_t
*conn
,
56 const listener_connection_t
*listener
);
57 static int connection_handle_listener_read(connection_t
*conn
, int new_type
);
58 #ifndef USE_BUFFEREVENTS
59 static int connection_bucket_should_increase(int bucket
,
60 or_connection_t
*conn
);
62 static int connection_finished_flushing(connection_t
*conn
);
63 static int connection_flushed_some(connection_t
*conn
);
64 static int connection_finished_connecting(connection_t
*conn
);
65 static int connection_reached_eof(connection_t
*conn
);
66 static int connection_read_to_buf(connection_t
*conn
, ssize_t
*max_to_read
,
68 static int connection_process_inbuf(connection_t
*conn
, int package_partial
);
69 static void client_check_address_changed(tor_socket_t sock
);
70 static void set_constrained_socket_buffers(tor_socket_t sock
, int size
);
72 static const char *connection_proxy_state_to_string(int state
);
73 static int connection_read_https_proxy_response(connection_t
*conn
);
74 static void connection_send_socks5_connect(connection_t
*conn
);
75 static const char *proxy_type_to_string(int proxy_type
);
76 static int get_proxy_type(void);
78 /** The last addresses that our network interface seemed to have been
79 * binding to. We use this as one way to detect when our IP changes.
81 * XXX024 We should really use the entire list of interfaces here.
83 static tor_addr_t
*last_interface_ipv4
= NULL
;
84 /* DOCDOC last_interface_ipv6 */
85 static tor_addr_t
*last_interface_ipv6
= NULL
;
86 /** A list of tor_addr_t for addresses we've used in outgoing connections.
87 * Used to detect IP address changes. */
88 static smartlist_t
*outgoing_addrs
= NULL
;
90 #define CASE_ANY_LISTENER_TYPE \
91 case CONN_TYPE_OR_LISTENER: \
92 case CONN_TYPE_AP_LISTENER: \
93 case CONN_TYPE_DIR_LISTENER: \
94 case CONN_TYPE_CONTROL_LISTENER: \
95 case CONN_TYPE_AP_TRANS_LISTENER: \
96 case CONN_TYPE_AP_NATD_LISTENER: \
97 case CONN_TYPE_AP_DNS_LISTENER
99 /**************************************************************/
102 * Return the human-readable name for the connection type <b>type</b>
105 conn_type_to_string(int type
)
109 case CONN_TYPE_OR_LISTENER
: return "OR listener";
110 case CONN_TYPE_OR
: return "OR";
111 case CONN_TYPE_EXIT
: return "Exit";
112 case CONN_TYPE_AP_LISTENER
: return "Socks listener";
113 case CONN_TYPE_AP_TRANS_LISTENER
:
114 return "Transparent pf/netfilter listener";
115 case CONN_TYPE_AP_NATD_LISTENER
: return "Transparent natd listener";
116 case CONN_TYPE_AP_DNS_LISTENER
: return "DNS listener";
117 case CONN_TYPE_AP
: return "Socks";
118 case CONN_TYPE_DIR_LISTENER
: return "Directory listener";
119 case CONN_TYPE_DIR
: return "Directory";
120 case CONN_TYPE_CPUWORKER
: return "CPU worker";
121 case CONN_TYPE_CONTROL_LISTENER
: return "Control listener";
122 case CONN_TYPE_CONTROL
: return "Control";
124 log_warn(LD_BUG
, "unknown connection type %d", type
);
125 tor_snprintf(buf
, sizeof(buf
), "unknown [%d]", type
);
131 * Return the human-readable name for the connection state <b>state</b>
132 * for the connection type <b>type</b>
135 conn_state_to_string(int type
, int state
)
139 CASE_ANY_LISTENER_TYPE
:
140 if (state
== LISTENER_STATE_READY
)
145 case OR_CONN_STATE_CONNECTING
: return "connect()ing";
146 case OR_CONN_STATE_PROXY_HANDSHAKING
: return "handshaking (proxy)";
147 case OR_CONN_STATE_TLS_HANDSHAKING
: return "handshaking (TLS)";
148 case OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING
:
149 return "renegotiating (TLS, v2 handshake)";
150 case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING
:
151 return "waiting for renegotiation or V3 handshake";
152 case OR_CONN_STATE_OR_HANDSHAKING_V2
:
153 return "handshaking (Tor, v2 handshake)";
154 case OR_CONN_STATE_OR_HANDSHAKING_V3
:
155 return "handshaking (Tor, v3 handshake)";
156 case OR_CONN_STATE_OPEN
: return "open";
161 case EXIT_CONN_STATE_RESOLVING
: return "waiting for dest info";
162 case EXIT_CONN_STATE_CONNECTING
: return "connecting";
163 case EXIT_CONN_STATE_OPEN
: return "open";
164 case EXIT_CONN_STATE_RESOLVEFAILED
: return "resolve failed";
169 case AP_CONN_STATE_SOCKS_WAIT
: return "waiting for socks info";
170 case AP_CONN_STATE_NATD_WAIT
: return "waiting for natd dest info";
171 case AP_CONN_STATE_RENDDESC_WAIT
: return "waiting for rendezvous desc";
172 case AP_CONN_STATE_CONTROLLER_WAIT
: return "waiting for controller";
173 case AP_CONN_STATE_CIRCUIT_WAIT
: return "waiting for circuit";
174 case AP_CONN_STATE_CONNECT_WAIT
: return "waiting for connect response";
175 case AP_CONN_STATE_RESOLVE_WAIT
: return "waiting for resolve response";
176 case AP_CONN_STATE_OPEN
: return "open";
181 case DIR_CONN_STATE_CONNECTING
: return "connecting";
182 case DIR_CONN_STATE_CLIENT_SENDING
: return "client sending";
183 case DIR_CONN_STATE_CLIENT_READING
: return "client reading";
184 case DIR_CONN_STATE_CLIENT_FINISHED
: return "client finished";
185 case DIR_CONN_STATE_SERVER_COMMAND_WAIT
: return "waiting for command";
186 case DIR_CONN_STATE_SERVER_WRITING
: return "writing";
189 case CONN_TYPE_CPUWORKER
:
191 case CPUWORKER_STATE_IDLE
: return "idle";
192 case CPUWORKER_STATE_BUSY_ONION
: return "busy with onion";
195 case CONN_TYPE_CONTROL
:
197 case CONTROL_CONN_STATE_OPEN
: return "open (protocol v1)";
198 case CONTROL_CONN_STATE_NEEDAUTH
:
199 return "waiting for authentication (protocol v1)";
204 log_warn(LD_BUG
, "unknown connection state %d (type %d)", state
, type
);
205 tor_snprintf(buf
, sizeof(buf
),
206 "unknown state [%d] on unknown [%s] connection",
207 state
, conn_type_to_string(type
));
211 #ifdef USE_BUFFEREVENTS
212 /** Return true iff the connection's type is one that can use a
213 bufferevent-based implementation. */
215 connection_type_uses_bufferevent(connection_t
*conn
)
217 switch (conn
->type
) {
221 case CONN_TYPE_CONTROL
:
223 case CONN_TYPE_CPUWORKER
:
231 /** Allocate and return a new dir_connection_t, initialized as by
232 * connection_init(). */
234 dir_connection_new(int socket_family
)
236 dir_connection_t
*dir_conn
= tor_malloc_zero(sizeof(dir_connection_t
));
237 connection_init(time(NULL
), TO_CONN(dir_conn
), CONN_TYPE_DIR
, socket_family
);
241 /** Allocate and return a new or_connection_t, initialized as by
242 * connection_init(). */
244 or_connection_new(int socket_family
)
246 or_connection_t
*or_conn
= tor_malloc_zero(sizeof(or_connection_t
));
247 time_t now
= time(NULL
);
248 connection_init(now
, TO_CONN(or_conn
), CONN_TYPE_OR
, socket_family
);
250 or_conn
->timestamp_last_added_nonpadding
= time(NULL
);
251 or_conn
->next_circ_id
= crypto_rand_int(1<<15);
253 or_conn
->active_circuit_pqueue
= smartlist_new();
254 or_conn
->active_circuit_pqueue_last_recalibrated
= cell_ewma_get_tick();
259 /** Allocate and return a new entry_connection_t, initialized as by
260 * connection_init(). */
262 entry_connection_new(int type
, int socket_family
)
264 entry_connection_t
*entry_conn
= tor_malloc_zero(sizeof(entry_connection_t
));
265 tor_assert(type
== CONN_TYPE_AP
);
266 connection_init(time(NULL
), ENTRY_TO_CONN(entry_conn
), type
, socket_family
);
267 entry_conn
->socks_request
= socks_request_new();
271 /** Allocate and return a new edge_connection_t, initialized as by
272 * connection_init(). */
274 edge_connection_new(int type
, int socket_family
)
276 edge_connection_t
*edge_conn
= tor_malloc_zero(sizeof(edge_connection_t
));
277 tor_assert(type
== CONN_TYPE_EXIT
);
278 connection_init(time(NULL
), TO_CONN(edge_conn
), type
, socket_family
);
282 /** Allocate and return a new control_connection_t, initialized as by
283 * connection_init(). */
284 control_connection_t
*
285 control_connection_new(int socket_family
)
287 control_connection_t
*control_conn
=
288 tor_malloc_zero(sizeof(control_connection_t
));
289 connection_init(time(NULL
),
290 TO_CONN(control_conn
), CONN_TYPE_CONTROL
, socket_family
);
291 log_notice(LD_CONTROL
, "New control connection opened.");
295 /** Allocate and return a new listener_connection_t, initialized as by
296 * connection_init(). */
297 listener_connection_t
*
298 listener_connection_new(int type
, int socket_family
)
300 listener_connection_t
*listener_conn
=
301 tor_malloc_zero(sizeof(listener_connection_t
));
302 connection_init(time(NULL
), TO_CONN(listener_conn
), type
, socket_family
);
303 return listener_conn
;
306 /** Allocate, initialize, and return a new connection_t subtype of <b>type</b>
307 * to make or receive connections of address family <b>socket_family</b>. The
308 * type should be one of the CONN_TYPE_* constants. */
310 connection_new(int type
, int socket_family
)
314 return TO_CONN(or_connection_new(socket_family
));
317 return TO_CONN(edge_connection_new(type
, socket_family
));
320 return ENTRY_TO_CONN(entry_connection_new(type
, socket_family
));
323 return TO_CONN(dir_connection_new(socket_family
));
325 case CONN_TYPE_CONTROL
:
326 return TO_CONN(control_connection_new(socket_family
));
328 CASE_ANY_LISTENER_TYPE
:
329 return TO_CONN(listener_connection_new(type
, socket_family
));
332 connection_t
*conn
= tor_malloc_zero(sizeof(connection_t
));
333 connection_init(time(NULL
), conn
, type
, socket_family
);
339 /** Initializes conn. (you must call connection_add() to link it into the main
342 * Set conn-\>type to <b>type</b>. Set conn-\>s and conn-\>conn_array_index to
343 * -1 to signify they are not yet assigned.
345 * If conn is not a listener type, allocate buffers for it. If it's
346 * an AP type, allocate space to store the socks_request.
348 * Assign a pseudorandom next_circ_id between 0 and 2**15.
350 * Initialize conn's timestamps to now.
353 connection_init(time_t now
, connection_t
*conn
, int type
, int socket_family
)
355 static uint64_t n_connections_allocated
= 1;
359 conn
->magic
= OR_CONNECTION_MAGIC
;
362 conn
->magic
= EDGE_CONNECTION_MAGIC
;
365 conn
->magic
= ENTRY_CONNECTION_MAGIC
;
368 conn
->magic
= DIR_CONNECTION_MAGIC
;
370 case CONN_TYPE_CONTROL
:
371 conn
->magic
= CONTROL_CONNECTION_MAGIC
;
373 CASE_ANY_LISTENER_TYPE
:
374 conn
->magic
= LISTENER_CONNECTION_MAGIC
;
377 conn
->magic
= BASE_CONNECTION_MAGIC
;
381 conn
->s
= TOR_INVALID_SOCKET
; /* give it a default of 'not used' */
382 conn
->conn_array_index
= -1; /* also default to 'not used' */
383 conn
->global_identifier
= n_connections_allocated
++;
386 conn
->socket_family
= socket_family
;
387 #ifndef USE_BUFFEREVENTS
388 if (!connection_is_listener(conn
)) {
389 /* listeners never use their buf */
390 conn
->inbuf
= buf_new();
391 conn
->outbuf
= buf_new();
395 conn
->timestamp_created
= now
;
396 conn
->timestamp_lastread
= now
;
397 conn
->timestamp_lastwritten
= now
;
400 /** Create a link between <b>conn_a</b> and <b>conn_b</b>. */
402 connection_link_connections(connection_t
*conn_a
, connection_t
*conn_b
)
404 tor_assert(! SOCKET_OK(conn_a
->s
));
405 tor_assert(! SOCKET_OK(conn_b
->s
));
409 conn_a
->linked_conn
= conn_b
;
410 conn_b
->linked_conn
= conn_a
;
413 /** Deallocate memory used by <b>conn</b>. Deallocate its buffers if
414 * necessary, close its socket if necessary, and mark the directory as dirty
415 * if <b>conn</b> is an OR or OP connection.
418 _connection_free(connection_t
*conn
)
425 switch (conn
->type
) {
427 tor_assert(conn
->magic
== OR_CONNECTION_MAGIC
);
428 mem
= TO_OR_CONN(conn
);
429 memlen
= sizeof(or_connection_t
);
432 tor_assert(conn
->magic
== ENTRY_CONNECTION_MAGIC
);
433 mem
= TO_ENTRY_CONN(conn
);
434 memlen
= sizeof(entry_connection_t
);
437 tor_assert(conn
->magic
== EDGE_CONNECTION_MAGIC
);
438 mem
= TO_EDGE_CONN(conn
);
439 memlen
= sizeof(edge_connection_t
);
442 tor_assert(conn
->magic
== DIR_CONNECTION_MAGIC
);
443 mem
= TO_DIR_CONN(conn
);
444 memlen
= sizeof(dir_connection_t
);
446 case CONN_TYPE_CONTROL
:
447 tor_assert(conn
->magic
== CONTROL_CONNECTION_MAGIC
);
448 mem
= TO_CONTROL_CONN(conn
);
449 memlen
= sizeof(control_connection_t
);
451 CASE_ANY_LISTENER_TYPE
:
452 tor_assert(conn
->magic
== LISTENER_CONNECTION_MAGIC
);
453 mem
= TO_LISTENER_CONN(conn
);
454 memlen
= sizeof(listener_connection_t
);
457 tor_assert(conn
->magic
== BASE_CONNECTION_MAGIC
);
459 memlen
= sizeof(connection_t
);
464 log_info(LD_GENERAL
, "Freeing linked %s connection [%s] with %d "
465 "bytes on inbuf, %d on outbuf.",
466 conn_type_to_string(conn
->type
),
467 conn_state_to_string(conn
->type
, conn
->state
),
468 (int)connection_get_inbuf_len(conn
),
469 (int)connection_get_outbuf_len(conn
));
472 if (!connection_is_listener(conn
)) {
473 buf_free(conn
->inbuf
);
474 buf_free(conn
->outbuf
);
476 if (conn
->socket_family
== AF_UNIX
) {
477 /* For now only control ports can be Unix domain sockets
478 * and listeners at the same time */
479 tor_assert(conn
->type
== CONN_TYPE_CONTROL_LISTENER
);
481 if (unlink(conn
->address
) < 0 && errno
!= ENOENT
) {
482 log_warn(LD_NET
, "Could not unlink %s: %s", conn
->address
,
488 tor_free(conn
->address
);
490 if (connection_speaks_cells(conn
)) {
491 or_connection_t
*or_conn
= TO_OR_CONN(conn
);
492 tor_tls_free(or_conn
->tls
);
494 or_handshake_state_free(or_conn
->handshake_state
);
495 or_conn
->handshake_state
= NULL
;
496 smartlist_free(or_conn
->active_circuit_pqueue
);
497 tor_free(or_conn
->nickname
);
499 if (conn
->type
== CONN_TYPE_AP
) {
500 entry_connection_t
*entry_conn
= TO_ENTRY_CONN(conn
);
501 tor_free(entry_conn
->chosen_exit_name
);
502 tor_free(entry_conn
->original_dest_address
);
503 if (entry_conn
->socks_request
)
504 socks_request_free(entry_conn
->socks_request
);
505 if (entry_conn
->pending_optimistic_data
) {
506 generic_buffer_free(entry_conn
->pending_optimistic_data
);
508 if (entry_conn
->sending_optimistic_data
) {
509 generic_buffer_free(entry_conn
->sending_optimistic_data
);
512 if (CONN_IS_EDGE(conn
)) {
513 rend_data_free(TO_EDGE_CONN(conn
)->rend_data
);
515 if (conn
->type
== CONN_TYPE_CONTROL
) {
516 control_connection_t
*control_conn
= TO_CONTROL_CONN(conn
);
517 tor_free(control_conn
->safecookie_client_hash
);
518 tor_free(control_conn
->incoming_cmd
);
521 tor_free(conn
->read_event
); /* Probably already freed by connection_free. */
522 tor_free(conn
->write_event
); /* Probably already freed by connection_free. */
523 IF_HAS_BUFFEREVENT(conn
, {
524 /* This was a workaround to handle bugs in some old versions of libevent
525 * where callbacks can occur after calling bufferevent_free(). Setting
526 * the callbacks to NULL prevented this. It shouldn't be necessary any
527 * more, but let's not tempt fate for now. */
528 bufferevent_setcb(conn
->bufev
, NULL
, NULL
, NULL
, NULL
);
529 bufferevent_free(conn
->bufev
);
533 if (conn
->type
== CONN_TYPE_DIR
) {
534 dir_connection_t
*dir_conn
= TO_DIR_CONN(conn
);
535 tor_free(dir_conn
->requested_resource
);
537 tor_zlib_free(dir_conn
->zlib_state
);
538 if (dir_conn
->fingerprint_stack
) {
539 SMARTLIST_FOREACH(dir_conn
->fingerprint_stack
, char *, cp
, tor_free(cp
));
540 smartlist_free(dir_conn
->fingerprint_stack
);
543 cached_dir_decref(dir_conn
->cached_dir
);
544 rend_data_free(dir_conn
->rend_data
);
547 if (SOCKET_OK(conn
->s
)) {
548 log_debug(LD_NET
,"closing fd %d.",(int)conn
->s
);
549 tor_close_socket(conn
->s
);
550 conn
->s
= TOR_INVALID_SOCKET
;
553 if (conn
->type
== CONN_TYPE_OR
&&
554 !tor_digest_is_zero(TO_OR_CONN(conn
)->identity_digest
)) {
555 log_warn(LD_BUG
, "called on OR conn with non-zeroed identity_digest");
556 connection_or_remove_from_identity_map(TO_OR_CONN(conn
));
558 #ifdef USE_BUFFEREVENTS
559 if (conn
->type
== CONN_TYPE_OR
&& TO_OR_CONN(conn
)->bucket_cfg
) {
560 ev_token_bucket_cfg_free(TO_OR_CONN(conn
)->bucket_cfg
);
561 TO_OR_CONN(conn
)->bucket_cfg
= NULL
;
565 memset(mem
, 0xCC, memlen
); /* poison memory */
569 /** Make sure <b>conn</b> isn't in any of the global conn lists; then free it.
572 connection_free(connection_t
*conn
)
576 tor_assert(!connection_is_on_closeable_list(conn
));
577 tor_assert(!connection_in_array(conn
));
578 if (conn
->linked_conn
) {
579 log_err(LD_BUG
, "Called with conn->linked_conn still set.");
580 tor_fragile_assert();
581 conn
->linked_conn
->linked_conn
= NULL
;
582 if (! conn
->linked_conn
->marked_for_close
&&
583 conn
->linked_conn
->reading_from_linked_conn
)
584 connection_start_reading(conn
->linked_conn
);
585 conn
->linked_conn
= NULL
;
587 if (connection_speaks_cells(conn
)) {
588 if (!tor_digest_is_zero(TO_OR_CONN(conn
)->identity_digest
)) {
589 connection_or_remove_from_identity_map(TO_OR_CONN(conn
));
592 if (conn
->type
== CONN_TYPE_CONTROL
) {
593 connection_control_closed(TO_CONTROL_CONN(conn
));
595 connection_unregister_events(conn
);
596 _connection_free(conn
);
600 * Called when we're about to finally unlink and free a connection:
601 * perform necessary accounting and cleanup
602 * - Directory conns that failed to fetch a rendezvous descriptor
603 * need to inform pending rendezvous streams.
604 * - OR conns need to call rep_hist_note_*() to record status.
605 * - AP conns need to send a socks reject if necessary.
606 * - Exit conns need to call connection_dns_remove() if necessary.
607 * - AP and Exit conns need to send an end cell if they can.
608 * - DNS conns need to fail any resolves that are pending on them.
609 * - OR and edge connections need to be unlinked from circuits.
612 connection_about_to_close_connection(connection_t
*conn
)
614 tor_assert(conn
->marked_for_close
);
616 switch (conn
->type
) {
618 connection_dir_about_to_close(TO_DIR_CONN(conn
));
621 connection_or_about_to_close(TO_OR_CONN(conn
));
624 connection_ap_about_to_close(TO_ENTRY_CONN(conn
));
627 connection_exit_about_to_close(TO_EDGE_CONN(conn
));
632 /** Return true iff connection_close_immediate() has been called on this
634 #define CONN_IS_CLOSED(c) \
635 ((c)->linked ? ((c)->linked_conn_is_closed) : (! SOCKET_OK(c->s)))
637 /** Close the underlying socket for <b>conn</b>, so we don't try to
638 * flush it. Must be used in conjunction with (right before)
639 * connection_mark_for_close().
642 connection_close_immediate(connection_t
*conn
)
644 assert_connection_ok(conn
,0);
645 if (CONN_IS_CLOSED(conn
)) {
646 log_err(LD_BUG
,"Attempt to close already-closed connection.");
647 tor_fragile_assert();
650 if (conn
->outbuf_flushlen
) {
651 log_info(LD_NET
,"fd %d, type %s, state %s, %d bytes on outbuf.",
652 (int)conn
->s
, conn_type_to_string(conn
->type
),
653 conn_state_to_string(conn
->type
, conn
->state
),
654 (int)conn
->outbuf_flushlen
);
657 connection_unregister_events(conn
);
659 if (SOCKET_OK(conn
->s
))
660 tor_close_socket(conn
->s
);
661 conn
->s
= TOR_INVALID_SOCKET
;
663 conn
->linked_conn_is_closed
= 1;
665 buf_clear(conn
->outbuf
);
666 conn
->outbuf_flushlen
= 0;
669 /** Mark <b>conn</b> to be closed next time we loop through
670 * conn_close_if_marked() in main.c. */
672 _connection_mark_for_close(connection_t
*conn
, int line
, const char *file
)
674 assert_connection_ok(conn
,0);
676 tor_assert(line
< 1<<16); /* marked_for_close can only fit a uint16_t. */
679 if (conn
->marked_for_close
) {
680 log(LOG_WARN
,LD_BUG
,"Duplicate call to connection_mark_for_close at %s:%d"
681 " (first at %s:%d)", file
, line
, conn
->marked_for_close_file
,
682 conn
->marked_for_close
);
683 tor_fragile_assert();
687 conn
->marked_for_close
= line
;
688 conn
->marked_for_close_file
= file
;
689 add_connection_to_closeable_list(conn
);
691 /* in case we're going to be held-open-til-flushed, reset
692 * the number of seconds since last successful write, so
693 * we get our whole 15 seconds */
694 conn
->timestamp_lastwritten
= time(NULL
);
697 /** Find each connection that has hold_open_until_flushed set to
698 * 1 but hasn't written in the past 15 seconds, and set
699 * hold_open_until_flushed to 0. This means it will get cleaned
700 * up in the next loop through close_if_marked() in main.c.
703 connection_expire_held_open(void)
706 smartlist_t
*conns
= get_connection_array();
710 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
712 /* If we've been holding the connection open, but we haven't written
715 if (conn
->hold_open_until_flushed
) {
716 tor_assert(conn
->marked_for_close
);
717 if (now
- conn
->timestamp_lastwritten
>= 15) {
719 if (conn
->type
== CONN_TYPE_EXIT
||
720 (conn
->type
== CONN_TYPE_DIR
&&
721 conn
->purpose
== DIR_PURPOSE_SERVER
))
724 severity
= LOG_NOTICE
;
725 log_fn(severity
, LD_NET
,
726 "Giving up on marked_for_close conn that's been flushing "
727 "for 15s (fd %d, type %s, state %s).",
728 (int)conn
->s
, conn_type_to_string(conn
->type
),
729 conn_state_to_string(conn
->type
, conn
->state
));
730 conn
->hold_open_until_flushed
= 0;
736 #if defined(HAVE_SYS_UN_H) || defined(RUNNING_DOXYGEN)
737 /** Create an AF_UNIX listenaddr struct.
738 * <b>listenaddress</b> provides the path to the Unix socket.
740 * Eventually <b>listenaddress</b> will also optionally contain user, group,
741 * and file permissions for the new socket. But not yet. XXX
742 * Also, since we do not create the socket here the information doesn't help
745 * If not NULL <b>readable_address</b> will contain a copy of the path part of
746 * <b>listenaddress</b>.
748 * The listenaddr struct has to be freed by the caller.
750 static struct sockaddr_un
*
751 create_unix_sockaddr(const char *listenaddress
, char **readable_address
,
754 struct sockaddr_un
*sockaddr
= NULL
;
756 sockaddr
= tor_malloc_zero(sizeof(struct sockaddr_un
));
757 sockaddr
->sun_family
= AF_UNIX
;
758 if (strlcpy(sockaddr
->sun_path
, listenaddress
, sizeof(sockaddr
->sun_path
))
759 >= sizeof(sockaddr
->sun_path
)) {
760 log_warn(LD_CONFIG
, "Unix socket path '%s' is too long to fit.",
761 escaped(listenaddress
));
766 if (readable_address
)
767 *readable_address
= tor_strdup(listenaddress
);
769 *len_out
= sizeof(struct sockaddr_un
);
773 static struct sockaddr
*
774 create_unix_sockaddr(const char *listenaddress
, char **readable_address
,
778 (void)readable_address
;
779 log_fn(LOG_ERR
, LD_BUG
,
780 "Unix domain sockets not supported, yet we tried to create one.");
782 tor_fragile_assert();
785 #endif /* HAVE_SYS_UN_H */
787 /** Warn that an accept or a connect has failed because we're running up
788 * against our ulimit. Rate-limit these warnings so that we don't spam
791 warn_too_many_conns(void)
793 #define WARN_TOO_MANY_CONNS_INTERVAL (6*60*60)
794 static ratelim_t last_warned
= RATELIM_INIT(WARN_TOO_MANY_CONNS_INTERVAL
);
796 if ((m
= rate_limit_log(&last_warned
, approx_time()))) {
797 int n_conns
= get_n_open_sockets();
798 log_warn(LD_NET
,"Failing because we have %d connections already. Please "
799 "raise your ulimit -n.%s", n_conns
, m
);
801 control_event_general_status(LOG_WARN
, "TOO_MANY_CONNECTIONS CURRENT=%d",
807 /** Check whether we should be willing to open an AF_UNIX socket in
808 * <b>path</b>. Return 0 if we should go ahead and -1 if we shouldn't. */
810 check_location_for_unix_socket(const or_options_t
*options
, const char *path
)
813 char *p
= tor_strdup(path
);
814 cpd_check_t flags
= CPD_CHECK_MODE_ONLY
;
815 if (get_parent_directory(p
)<0)
818 if (options
->ControlSocketsGroupWritable
)
819 flags
|= CPD_GROUP_OK
;
821 if (check_private_dir(p
, flags
, options
->User
) < 0) {
822 char *escpath
, *escdir
;
823 escpath
= esc_for_log(path
);
824 escdir
= esc_for_log(p
);
825 log_warn(LD_GENERAL
, "Before Tor can create a control socket in %s, the "
826 "directory %s needs to exist, and to be accessible only by the "
827 "user%s account that is running Tor. (On some Unix systems, "
828 "anybody who can list a socket can connect to it, so Tor is "
829 "being careful.)", escpath
, escdir
,
830 options
->ControlSocketsGroupWritable
? " and group" : "");
843 /** Tell the TCP stack that it shouldn't wait for a long time after
844 * <b>sock</b> has closed before reusing its port. */
846 make_socket_reuseable(tor_socket_t sock
)
853 /* REUSEADDR on normal places means you can rebind to the port
854 * right after somebody else has let it go. But REUSEADDR on win32
855 * means you can bind to the port _even when somebody else
856 * already has it bound_. So, don't do that on Win32. */
857 setsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
, (void*) &one
,
858 (socklen_t
)sizeof(one
));
862 /** Bind a new non-blocking socket listening to the socket described
863 * by <b>listensockaddr</b>.
865 * <b>address</b> is only used for logging purposes and to add the information
868 static connection_t
*
869 connection_listener_new(const struct sockaddr
*listensockaddr
,
871 int type
, const char *address
,
872 const port_cfg_t
*port_cfg
)
874 listener_connection_t
*lis_conn
;
876 tor_socket_t s
; /* the socket we're going to make */
877 or_options_t
const *options
= get_options();
878 #if defined(HAVE_PWD_H) && defined(HAVE_SYS_UN_H)
879 struct passwd
*pw
= NULL
;
881 uint16_t usePort
= 0, gotPort
= 0;
882 int start_reading
= 0;
883 static int global_next_session_group
= SESSION_GROUP_FIRST_AUTO
;
886 if (get_n_open_sockets() >= get_options()->_ConnLimit
-1) {
887 warn_too_many_conns();
891 if (listensockaddr
->sa_family
== AF_INET
||
892 listensockaddr
->sa_family
== AF_INET6
) {
893 int is_tcp
= (type
!= CONN_TYPE_AP_DNS_LISTENER
);
897 tor_addr_from_sockaddr(&addr
, listensockaddr
, &usePort
);
899 log_notice(LD_NET
, "Opening %s on %s:%d",
900 conn_type_to_string(type
), fmt_addr(&addr
), usePort
);
902 s
= tor_open_socket(tor_addr_family(&addr
),
903 is_tcp
? SOCK_STREAM
: SOCK_DGRAM
,
904 is_tcp
? IPPROTO_TCP
: IPPROTO_UDP
);
906 log_warn(LD_NET
,"Socket creation failed: %s",
907 tor_socket_strerror(tor_socket_errno(-1)));
911 make_socket_reuseable(s
);
914 if (listensockaddr
->sa_family
== AF_INET6
) {
916 /* In Redmond, this kind of thing passes for standards-conformance. */
921 /* We need to set IPV6_V6ONLY so that this socket can't get used for
922 * IPv4 connections. */
923 if (setsockopt(s
,IPPROTO_IPV6
, IPV6_V6ONLY
,
924 (void*)&one
, sizeof(one
))<0) {
925 int e
= tor_socket_errno(s
);
926 log_warn(LD_NET
, "Error setting IPV6_V6ONLY flag: %s",
927 tor_socket_strerror(e
));
928 /* Keep going; probably not harmful. */
933 if (bind(s
,listensockaddr
,socklen
) < 0) {
934 const char *helpfulhint
= "";
935 int e
= tor_socket_errno(s
);
936 if (ERRNO_IS_EADDRINUSE(e
))
937 helpfulhint
= ". Is Tor already running?";
938 log_warn(LD_NET
, "Could not bind to %s:%u: %s%s", address
, usePort
,
939 tor_socket_strerror(e
), helpfulhint
);
945 if (listen(s
,SOMAXCONN
) < 0) {
946 log_warn(LD_NET
, "Could not listen on %s:%u: %s", address
, usePort
,
947 tor_socket_strerror(tor_socket_errno(s
)));
957 struct sockaddr_storage ss
;
958 socklen_t ss_len
=sizeof(ss
);
959 if (getsockname(s
, (struct sockaddr
*)&ss
, &ss_len
)<0) {
960 log_warn(LD_NET
, "getsockname() couldn't learn address for %s: %s",
961 conn_type_to_string(type
),
962 tor_socket_strerror(tor_socket_errno(s
)));
965 tor_addr_from_sockaddr(&addr2
, (struct sockaddr
*)&ss
, &gotPort
);
968 } else if (listensockaddr
->sa_family
== AF_UNIX
) {
971 /* For now only control ports can be Unix domain sockets
972 * and listeners at the same time */
973 tor_assert(type
== CONN_TYPE_CONTROL_LISTENER
);
975 if (check_location_for_unix_socket(options
, address
) < 0)
978 log_notice(LD_NET
, "Opening %s on %s",
979 conn_type_to_string(type
), address
);
981 tor_addr_make_unspec(&addr
);
983 if (unlink(address
) < 0 && errno
!= ENOENT
) {
984 log_warn(LD_NET
, "Could not unlink %s: %s", address
,
988 s
= tor_open_socket(AF_UNIX
, SOCK_STREAM
, 0);
989 if (! SOCKET_OK(s
)) {
990 log_warn(LD_NET
,"Socket creation failed: %s.", strerror(errno
));
994 if (bind(s
, listensockaddr
, (socklen_t
)sizeof(struct sockaddr_un
)) == -1) {
995 log_warn(LD_NET
,"Bind to %s failed: %s.", address
,
996 tor_socket_strerror(tor_socket_errno(s
)));
1000 if (options
->User
) {
1001 pw
= getpwnam(options
->User
);
1003 log_warn(LD_NET
,"Unable to chown() %s socket: user %s not found.",
1004 address
, options
->User
);
1005 } else if (chown(address
, pw
->pw_uid
, pw
->pw_gid
) < 0) {
1006 log_warn(LD_NET
,"Unable to chown() %s socket: %s.",
1007 address
, strerror(errno
));
1012 if (options
->ControlSocketsGroupWritable
) {
1013 /* We need to use chmod; fchmod doesn't work on sockets on all
1015 if (chmod(address
, 0660) < 0) {
1016 log_warn(LD_FS
,"Unable to make %s group-writable.", address
);
1017 tor_close_socket(s
);
1022 if (listen(s
,SOMAXCONN
) < 0) {
1023 log_warn(LD_NET
, "Could not listen on %s: %s", address
,
1024 tor_socket_strerror(tor_socket_errno(s
)));
1025 tor_close_socket(s
);
1030 #endif /* HAVE_SYS_UN_H */
1032 log_err(LD_BUG
,"Got unexpected address family %d.",
1033 listensockaddr
->sa_family
);
1037 set_socket_nonblocking(s
);
1039 lis_conn
= listener_connection_new(type
, listensockaddr
->sa_family
);
1040 conn
= TO_CONN(lis_conn
);
1041 conn
->socket_family
= listensockaddr
->sa_family
;
1043 conn
->address
= tor_strdup(address
);
1044 conn
->port
= gotPort
;
1045 tor_addr_copy(&conn
->addr
, &addr
);
1047 if (port_cfg
->isolation_flags
) {
1048 lis_conn
->isolation_flags
= port_cfg
->isolation_flags
;
1049 if (port_cfg
->session_group
>= 0) {
1050 lis_conn
->session_group
= port_cfg
->session_group
;
1052 /* This can wrap after around INT_MAX listeners are opened. But I don't
1053 * believe that matters, since you would need to open a ridiculous
1054 * number of listeners while keeping the early ones open before you ever
1055 * hit this. An OR with a dozen ports open, for example, would have to
1056 * close and re-open its listeners every second for 4 years nonstop.
1058 lis_conn
->session_group
= global_next_session_group
--;
1062 if (connection_add(conn
) < 0) { /* no space, forget it */
1063 log_warn(LD_NET
,"connection_add for listener failed. Giving up.");
1064 connection_free(conn
);
1068 log_fn(usePort
==gotPort
? LOG_DEBUG
: LOG_NOTICE
, LD_NET
,
1069 "%s listening on port %u.",
1070 conn_type_to_string(type
), gotPort
);
1072 conn
->state
= LISTENER_STATE_READY
;
1073 if (start_reading
) {
1074 connection_start_reading(conn
);
1076 tor_assert(type
== CONN_TYPE_AP_DNS_LISTENER
);
1077 dnsserv_configure_listener(conn
);
1086 /** Do basic sanity checking on a newly received socket. Return 0
1087 * if it looks ok, else return -1.
1089 * Notably, some TCP stacks can erroneously have accept() return successfully
1090 * with socklen 0, when the client sends an RST before the accept call (as
1091 * nmap does). We want to detect that, and not go on with the connection.
1094 check_sockaddr(struct sockaddr
*sa
, int len
, int level
)
1098 if (sa
->sa_family
== AF_INET
) {
1099 struct sockaddr_in
*sin
=(struct sockaddr_in
*)sa
;
1100 if (len
!= sizeof(struct sockaddr_in
)) {
1101 log_fn(level
, LD_NET
, "Length of address not as expected: %d vs %d",
1102 len
,(int)sizeof(struct sockaddr_in
));
1105 if (sin
->sin_addr
.s_addr
== 0 || sin
->sin_port
== 0) {
1106 log_fn(level
, LD_NET
,
1107 "Address for new connection has address/port equal to zero.");
1110 } else if (sa
->sa_family
== AF_INET6
) {
1111 struct sockaddr_in6
*sin6
=(struct sockaddr_in6
*)sa
;
1112 if (len
!= sizeof(struct sockaddr_in6
)) {
1113 log_fn(level
, LD_NET
, "Length of address not as expected: %d vs %d",
1114 len
,(int)sizeof(struct sockaddr_in6
));
1117 if (tor_mem_is_zero((void*)sin6
->sin6_addr
.s6_addr
, 16) ||
1118 sin6
->sin6_port
== 0) {
1119 log_fn(level
, LD_NET
,
1120 "Address for new connection has address/port equal to zero.");
1129 /** Check whether the socket family from an accepted socket <b>got</b> is the
1130 * same as the one that <b>listener</b> is waiting for. If it isn't, log
1131 * a useful message and return -1. Else return 0.
1133 * This is annoying, but can apparently happen on some Darwins. */
1135 check_sockaddr_family_match(sa_family_t got
, connection_t
*listener
)
1137 if (got
!= listener
->socket_family
) {
1138 log_info(LD_BUG
, "A listener connection returned a socket with a "
1139 "mismatched family. %s for addr_family %d gave us a socket "
1140 "with address family %d. Dropping.",
1141 conn_type_to_string(listener
->type
),
1142 (int)listener
->socket_family
,
1149 /** The listener connection <b>conn</b> told poll() it wanted to read.
1150 * Call accept() on conn-\>s, and add the new connection if necessary.
1153 connection_handle_listener_read(connection_t
*conn
, int new_type
)
1155 tor_socket_t news
; /* the new socket */
1156 connection_t
*newconn
;
1157 /* information about the remote peer when connecting to other routers */
1158 struct sockaddr_storage addrbuf
;
1159 struct sockaddr
*remote
= (struct sockaddr
*)&addrbuf
;
1160 /* length of the remote address. Must be whatever accept() needs. */
1161 socklen_t remotelen
= (socklen_t
)sizeof(addrbuf
);
1162 const or_options_t
*options
= get_options();
1164 tor_assert((size_t)remotelen
>= sizeof(struct sockaddr_in
));
1165 memset(&addrbuf
, 0, sizeof(addrbuf
));
1167 news
= tor_accept_socket(conn
->s
,remote
,&remotelen
);
1168 if (!SOCKET_OK(news
)) { /* accept() error */
1169 int e
= tor_socket_errno(conn
->s
);
1170 if (ERRNO_IS_ACCEPT_EAGAIN(e
)) {
1171 return 0; /* he hung up before we could accept(). that's fine. */
1172 } else if (ERRNO_IS_ACCEPT_RESOURCE_LIMIT(e
)) {
1173 warn_too_many_conns();
1176 /* else there was a real error. */
1177 log_warn(LD_NET
,"accept() failed: %s. Closing listener.",
1178 tor_socket_strerror(e
));
1179 connection_mark_for_close(conn
);
1183 "Connection accepted on socket %d (child of fd %d).",
1184 (int)news
,(int)conn
->s
);
1186 make_socket_reuseable(news
);
1187 set_socket_nonblocking(news
);
1189 if (options
->ConstrainedSockets
)
1190 set_constrained_socket_buffers(news
, (int)options
->ConstrainedSockSize
);
1192 if (check_sockaddr_family_match(remote
->sa_family
, conn
) < 0) {
1193 tor_close_socket(news
);
1197 if (conn
->socket_family
== AF_INET
|| conn
->socket_family
== AF_INET6
) {
1200 if (check_sockaddr(remote
, remotelen
, LOG_INFO
)<0) {
1202 "accept() returned a strange address; closing connection.");
1203 tor_close_socket(news
);
1207 if (check_sockaddr_family_match(remote
->sa_family
, conn
) < 0) {
1208 tor_close_socket(news
);
1212 tor_addr_from_sockaddr(&addr
, remote
, &port
);
1214 /* process entrance policies here, before we even create the connection */
1215 if (new_type
== CONN_TYPE_AP
) {
1216 /* check sockspolicy to see if we should accept it */
1217 if (socks_policy_permits_address(&addr
) == 0) {
1219 "Denying socks connection from untrusted address %s.",
1221 tor_close_socket(news
);
1225 if (new_type
== CONN_TYPE_DIR
) {
1226 /* check dirpolicy to see if we should accept it */
1227 if (dir_policy_permits_address(&addr
) == 0) {
1228 log_notice(LD_DIRSERV
,"Denying dir connection from address %s.",
1230 tor_close_socket(news
);
1235 newconn
= connection_new(new_type
, conn
->socket_family
);
1238 /* remember the remote address */
1239 tor_addr_copy(&newconn
->addr
, &addr
);
1240 newconn
->port
= port
;
1241 newconn
->address
= tor_dup_addr(&addr
);
1243 } else if (conn
->socket_family
== AF_UNIX
) {
1244 /* For now only control ports can be Unix domain sockets
1245 * and listeners at the same time */
1246 tor_assert(conn
->type
== CONN_TYPE_CONTROL_LISTENER
);
1248 newconn
= connection_new(new_type
, conn
->socket_family
);
1251 /* remember the remote address -- do we have anything sane to put here? */
1252 tor_addr_make_unspec(&newconn
->addr
);
1254 newconn
->address
= tor_strdup(conn
->address
);
1259 if (connection_add(newconn
) < 0) { /* no space, forget it */
1260 connection_free(newconn
);
1261 return 0; /* no need to tear down the parent */
1264 if (connection_init_accepted_conn(newconn
, TO_LISTENER_CONN(conn
)) < 0) {
1265 if (! newconn
->marked_for_close
)
1266 connection_mark_for_close(newconn
);
1272 /** Initialize states for newly accepted connection <b>conn</b>.
1273 * If conn is an OR, start the TLS handshake.
1274 * If conn is a transparent AP, get its original destination
1275 * and place it in circuit_wait.
1278 connection_init_accepted_conn(connection_t
*conn
,
1279 const listener_connection_t
*listener
)
1281 connection_start_reading(conn
);
1283 switch (conn
->type
) {
1285 control_event_or_conn_status(TO_OR_CONN(conn
), OR_CONN_EVENT_NEW
, 0);
1286 return connection_tls_start_handshake(TO_OR_CONN(conn
), 1);
1288 TO_ENTRY_CONN(conn
)->isolation_flags
= listener
->isolation_flags
;
1289 TO_ENTRY_CONN(conn
)->session_group
= listener
->session_group
;
1290 TO_ENTRY_CONN(conn
)->nym_epoch
= get_signewnym_epoch();
1291 TO_ENTRY_CONN(conn
)->socks_request
->listener_type
= listener
->_base
.type
;
1292 switch (TO_CONN(listener
)->type
) {
1293 case CONN_TYPE_AP_LISTENER
:
1294 conn
->state
= AP_CONN_STATE_SOCKS_WAIT
;
1296 case CONN_TYPE_AP_TRANS_LISTENER
:
1297 TO_ENTRY_CONN(conn
)->is_transparent_ap
= 1;
1298 conn
->state
= AP_CONN_STATE_CIRCUIT_WAIT
;
1299 return connection_ap_process_transparent(TO_ENTRY_CONN(conn
));
1300 case CONN_TYPE_AP_NATD_LISTENER
:
1301 TO_ENTRY_CONN(conn
)->is_transparent_ap
= 1;
1302 conn
->state
= AP_CONN_STATE_NATD_WAIT
;
1307 conn
->purpose
= DIR_PURPOSE_SERVER
;
1308 conn
->state
= DIR_CONN_STATE_SERVER_COMMAND_WAIT
;
1310 case CONN_TYPE_CONTROL
:
1311 conn
->state
= CONTROL_CONN_STATE_NEEDAUTH
;
1317 /** Take conn, make a nonblocking socket; try to connect to
1318 * addr:port (they arrive in *host order*). If fail, return -1 and if
1319 * applicable put your best guess about errno into *<b>socket_error</b>.
1320 * Else assign s to conn-\>s: if connected return 1, if EAGAIN return 0.
1322 * address is used to make the logs useful.
1324 * On success, add conn to the list of polled connections.
1327 connection_connect(connection_t
*conn
, const char *address
,
1328 const tor_addr_t
*addr
, uint16_t port
, int *socket_error
)
1332 struct sockaddr_storage addrbuf
;
1333 struct sockaddr
*dest_addr
;
1335 const or_options_t
*options
= get_options();
1336 int protocol_family
;
1338 if (get_n_open_sockets() >= get_options()->_ConnLimit
-1) {
1339 warn_too_many_conns();
1340 *socket_error
= ENOBUFS
;
1344 if (tor_addr_family(addr
) == AF_INET6
)
1345 protocol_family
= PF_INET6
;
1347 protocol_family
= PF_INET
;
1349 if (get_options()->DisableNetwork
) {
1350 /* We should never even try to connect anyplace if DisableNetwork is set.
1351 * Warn if we do, and refuse to make the connection. */
1352 static ratelim_t disablenet_violated
= RATELIM_INIT(30*60);
1355 *socket_error
= WSAENETUNREACH
;
1357 *socket_error
= ENETUNREACH
;
1359 if ((m
= rate_limit_log(&disablenet_violated
, approx_time()))) {
1360 log_warn(LD_BUG
, "Tried to open a socket with DisableNetwork set.%s", m
);
1363 tor_fragile_assert();
1367 s
= tor_open_socket(protocol_family
,SOCK_STREAM
,IPPROTO_TCP
);
1368 if (! SOCKET_OK(s
)) {
1369 *socket_error
= tor_socket_errno(-1);
1370 log_warn(LD_NET
,"Error creating network socket: %s",
1371 tor_socket_strerror(*socket_error
));
1375 make_socket_reuseable(s
);
1377 if (options
->OutboundBindAddress
&& !tor_addr_is_loopback(addr
)) {
1378 struct sockaddr_in ext_addr
;
1380 memset(&ext_addr
, 0, sizeof(ext_addr
));
1381 ext_addr
.sin_family
= AF_INET
;
1382 ext_addr
.sin_port
= 0;
1383 if (!tor_inet_aton(options
->OutboundBindAddress
, &ext_addr
.sin_addr
)) {
1384 log_warn(LD_CONFIG
,"Outbound bind address '%s' didn't parse. Ignoring.",
1385 options
->OutboundBindAddress
);
1387 if (bind(s
, (struct sockaddr
*)&ext_addr
,
1388 (socklen_t
)sizeof(ext_addr
)) < 0) {
1389 *socket_error
= tor_socket_errno(s
);
1390 log_warn(LD_NET
,"Error binding network socket: %s",
1391 tor_socket_strerror(*socket_error
));
1392 tor_close_socket(s
);
1398 set_socket_nonblocking(s
);
1400 if (options
->ConstrainedSockets
)
1401 set_constrained_socket_buffers(s
, (int)options
->ConstrainedSockSize
);
1403 memset(&addrbuf
,0,sizeof(addrbuf
));
1404 dest_addr
= (struct sockaddr
*) &addrbuf
;
1405 dest_addr_len
= tor_addr_to_sockaddr(addr
, port
, dest_addr
, sizeof(addrbuf
));
1406 tor_assert(dest_addr_len
> 0);
1408 log_debug(LD_NET
, "Connecting to %s:%u.",
1409 escaped_safe_str_client(address
), port
);
1411 if (connect(s
, dest_addr
, (socklen_t
)dest_addr_len
) < 0) {
1412 int e
= tor_socket_errno(s
);
1413 if (!ERRNO_IS_CONN_EINPROGRESS(e
)) {
1414 /* yuck. kill it. */
1417 "connect() to %s:%u failed: %s",
1418 escaped_safe_str_client(address
),
1419 port
, tor_socket_strerror(e
));
1420 tor_close_socket(s
);
1427 /* it succeeded. we're connected. */
1428 log_fn(inprogress
?LOG_DEBUG
:LOG_INFO
, LD_NET
,
1429 "Connection to %s:%u %s (sock %d).",
1430 escaped_safe_str_client(address
),
1431 port
, inprogress
?"in progress":"established", s
);
1433 if (connection_add_connecting(conn
) < 0) {
1434 /* no space, forget it */
1435 *socket_error
= ENOBUFS
;
1438 return inprogress
? 0 : 1;
1441 /** Convert state number to string representation for logging purposes.
1444 connection_proxy_state_to_string(int state
)
1446 static const char *unknown
= "???";
1447 static const char *states
[] = {
1450 "PROXY_HTTPS_WANT_CONNECT_OK",
1451 "PROXY_SOCKS4_WANT_CONNECT_OK",
1452 "PROXY_SOCKS5_WANT_AUTH_METHOD_NONE",
1453 "PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929",
1454 "PROXY_SOCKS5_WANT_AUTH_RFC1929_OK",
1455 "PROXY_SOCKS5_WANT_CONNECT_OK",
1459 if (state
< PROXY_NONE
|| state
> PROXY_CONNECTED
)
1462 return states
[state
];
1465 /** Write a proxy request of <b>type</b> (socks4, socks5, https) to conn
1466 * for conn->addr:conn->port, authenticating with the auth details given
1467 * in the configuration (if available). SOCKS 5 and HTTP CONNECT proxies
1468 * support authentication.
1470 * Returns -1 if conn->addr is incompatible with the proxy protocol, and
1473 * Use connection_read_proxy_handshake() to complete the handshake.
1476 connection_proxy_connect(connection_t
*conn
, int type
)
1478 const or_options_t
*options
;
1482 options
= get_options();
1485 case PROXY_CONNECT
: {
1487 char *base64_authenticator
=NULL
;
1488 const char *authenticator
= options
->HTTPSProxyAuthenticator
;
1490 /* Send HTTP CONNECT and authentication (if available) in
1493 if (authenticator
) {
1494 base64_authenticator
= alloc_http_authenticator(authenticator
);
1495 if (!base64_authenticator
)
1496 log_warn(LD_OR
, "Encoding https authenticator failed");
1499 if (base64_authenticator
) {
1500 const char *addr
= fmt_addr(&conn
->addr
);
1501 tor_snprintf(buf
, sizeof(buf
), "CONNECT %s:%d HTTP/1.1\r\n"
1503 "Proxy-Authorization: Basic %s\r\n\r\n",
1506 base64_authenticator
);
1507 tor_free(base64_authenticator
);
1509 tor_snprintf(buf
, sizeof(buf
), "CONNECT %s:%d HTTP/1.0\r\n\r\n",
1510 fmt_addr(&conn
->addr
), conn
->port
);
1513 connection_write_to_buf(buf
, strlen(buf
), conn
);
1514 conn
->proxy_state
= PROXY_HTTPS_WANT_CONNECT_OK
;
1518 case PROXY_SOCKS4
: {
1519 unsigned char buf
[9];
1523 /* Send a SOCKS4 connect request with empty user id */
1525 if (tor_addr_family(&conn
->addr
) != AF_INET
) {
1526 log_warn(LD_NET
, "SOCKS4 client is incompatible with IPv6");
1530 ip4addr
= tor_addr_to_ipv4n(&conn
->addr
);
1531 portn
= htons(conn
->port
);
1533 buf
[0] = 4; /* version */
1534 buf
[1] = SOCKS_COMMAND_CONNECT
; /* command */
1535 memcpy(buf
+ 2, &portn
, 2); /* port */
1536 memcpy(buf
+ 4, &ip4addr
, 4); /* addr */
1537 buf
[8] = 0; /* userid (empty) */
1539 connection_write_to_buf((char *)buf
, sizeof(buf
), conn
);
1540 conn
->proxy_state
= PROXY_SOCKS4_WANT_CONNECT_OK
;
1544 case PROXY_SOCKS5
: {
1545 unsigned char buf
[4]; /* fields: vers, num methods, method list */
1547 /* Send a SOCKS5 greeting (connect request must wait) */
1549 buf
[0] = 5; /* version */
1551 /* number of auth methods */
1552 if (options
->Socks5ProxyUsername
) {
1554 buf
[2] = 0x00; /* no authentication */
1555 buf
[3] = 0x02; /* rfc1929 Username/Passwd auth */
1556 conn
->proxy_state
= PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929
;
1559 buf
[2] = 0x00; /* no authentication */
1560 conn
->proxy_state
= PROXY_SOCKS5_WANT_AUTH_METHOD_NONE
;
1563 connection_write_to_buf((char *)buf
, 2 + buf
[1], conn
);
1568 log_err(LD_BUG
, "Invalid proxy protocol, %d", type
);
1569 tor_fragile_assert();
1573 log_debug(LD_NET
, "set state %s",
1574 connection_proxy_state_to_string(conn
->proxy_state
));
1579 /** Read conn's inbuf. If the http response from the proxy is all
1580 * here, make sure it's good news, then return 1. If it's bad news,
1581 * return -1. Else return 0 and hope for better luck next time.
1584 connection_read_https_proxy_response(connection_t
*conn
)
1591 switch (fetch_from_buf_http(conn
->inbuf
,
1592 &headers
, MAX_HEADERS_SIZE
,
1593 NULL
, NULL
, 10000, 0)) {
1594 case -1: /* overflow */
1595 log_warn(LD_PROTOCOL
,
1596 "Your https proxy sent back an oversized response. Closing.");
1599 log_info(LD_NET
,"https proxy response not all here yet. Waiting.");
1601 /* case 1, fall through */
1604 if (parse_http_response(headers
, &status_code
, &date_header
,
1605 NULL
, &reason
) < 0) {
1607 "Unparseable headers from proxy (connecting to '%s'). Closing.",
1612 if (!reason
) reason
= tor_strdup("[no reason given]");
1614 if (status_code
== 200) {
1616 "HTTPS connect to '%s' successful! (200 %s) Starting TLS.",
1617 conn
->address
, escaped(reason
));
1621 /* else, bad news on the status code */
1622 switch (status_code
) {
1625 "The https proxy refused to allow connection to %s "
1626 "(status code %d, %s). Closing.",
1627 conn
->address
, status_code
, escaped(reason
));
1631 "The https proxy sent back an unexpected status code %d (%s). "
1633 status_code
, escaped(reason
));
1640 /** Send SOCKS5 CONNECT command to <b>conn</b>, copying <b>conn->addr</b>
1641 * and <b>conn->port</b> into the request.
1644 connection_send_socks5_connect(connection_t
*conn
)
1646 unsigned char buf
[1024];
1648 uint16_t port
= htons(conn
->port
);
1650 buf
[0] = 5; /* version */
1651 buf
[1] = SOCKS_COMMAND_CONNECT
; /* command */
1652 buf
[2] = 0; /* reserved */
1654 if (tor_addr_family(&conn
->addr
) == AF_INET
) {
1655 uint32_t addr
= tor_addr_to_ipv4n(&conn
->addr
);
1659 memcpy(buf
+ 4, &addr
, 4);
1660 memcpy(buf
+ 8, &port
, 2);
1661 } else { /* AF_INET6 */
1664 memcpy(buf
+ 4, tor_addr_to_in6(&conn
->addr
), 16);
1665 memcpy(buf
+ 20, &port
, 2);
1668 connection_write_to_buf((char *)buf
, reqsize
, conn
);
1670 conn
->proxy_state
= PROXY_SOCKS5_WANT_CONNECT_OK
;
1673 /** Wrapper around fetch_from_(buf/evbuffer)_socks_client: see those functions
1674 * for documentation of its behavior. */
1676 connection_fetch_from_buf_socks_client(connection_t
*conn
,
1677 int state
, char **reason
)
1679 IF_HAS_BUFFEREVENT(conn
, {
1680 struct evbuffer
*input
= bufferevent_get_input(conn
->bufev
);
1681 return fetch_from_evbuffer_socks_client(input
, state
, reason
);
1682 }) ELSE_IF_NO_BUFFEREVENT
{
1683 return fetch_from_buf_socks_client(conn
->inbuf
, state
, reason
);
1687 /** Call this from connection_*_process_inbuf() to advance the proxy
1690 * No matter what proxy protocol is used, if this function returns 1, the
1691 * handshake is complete, and the data remaining on inbuf may contain the
1692 * start of the communication with the requested server.
1694 * Returns 0 if the current buffer contains an incomplete response, and -1
1698 connection_read_proxy_handshake(connection_t
*conn
)
1701 char *reason
= NULL
;
1703 log_debug(LD_NET
, "enter state %s",
1704 connection_proxy_state_to_string(conn
->proxy_state
));
1706 switch (conn
->proxy_state
) {
1707 case PROXY_HTTPS_WANT_CONNECT_OK
:
1708 ret
= connection_read_https_proxy_response(conn
);
1710 conn
->proxy_state
= PROXY_CONNECTED
;
1713 case PROXY_SOCKS4_WANT_CONNECT_OK
:
1714 ret
= connection_fetch_from_buf_socks_client(conn
,
1718 conn
->proxy_state
= PROXY_CONNECTED
;
1721 case PROXY_SOCKS5_WANT_AUTH_METHOD_NONE
:
1722 ret
= connection_fetch_from_buf_socks_client(conn
,
1725 /* no auth needed, do connect */
1727 connection_send_socks5_connect(conn
);
1732 case PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929
:
1733 ret
= connection_fetch_from_buf_socks_client(conn
,
1737 /* send auth if needed, otherwise do connect */
1739 connection_send_socks5_connect(conn
);
1741 } else if (ret
== 2) {
1742 unsigned char buf
[1024];
1743 size_t reqsize
, usize
, psize
;
1744 const char *user
, *pass
;
1746 user
= get_options()->Socks5ProxyUsername
;
1747 pass
= get_options()->Socks5ProxyPassword
;
1748 tor_assert(user
&& pass
);
1750 /* XXX len of user and pass must be <= 255 !!! */
1751 usize
= strlen(user
);
1752 psize
= strlen(pass
);
1753 tor_assert(usize
<= 255 && psize
<= 255);
1754 reqsize
= 3 + usize
+ psize
;
1756 buf
[0] = 1; /* negotiation version */
1758 memcpy(buf
+ 2, user
, usize
);
1759 buf
[2 + usize
] = psize
;
1760 memcpy(buf
+ 3 + usize
, pass
, psize
);
1762 connection_write_to_buf((char *)buf
, reqsize
, conn
);
1764 conn
->proxy_state
= PROXY_SOCKS5_WANT_AUTH_RFC1929_OK
;
1769 case PROXY_SOCKS5_WANT_AUTH_RFC1929_OK
:
1770 ret
= connection_fetch_from_buf_socks_client(conn
,
1773 /* send the connect request */
1775 connection_send_socks5_connect(conn
);
1780 case PROXY_SOCKS5_WANT_CONNECT_OK
:
1781 ret
= connection_fetch_from_buf_socks_client(conn
,
1785 conn
->proxy_state
= PROXY_CONNECTED
;
1789 log_err(LD_BUG
, "Invalid proxy_state for reading, %d",
1791 tor_fragile_assert();
1796 log_debug(LD_NET
, "leaving state %s",
1797 connection_proxy_state_to_string(conn
->proxy_state
));
1801 log_warn(LD_NET
, "Proxy Client: unable to connect to %s:%d (%s)",
1802 conn
->address
, conn
->port
, escaped(reason
));
1805 log_warn(LD_NET
, "Proxy Client: unable to connect to %s:%d",
1806 conn
->address
, conn
->port
);
1808 } else if (ret
== 1) {
1809 log_info(LD_NET
, "Proxy Client: connection to %s:%d successful",
1810 conn
->address
, conn
->port
);
1816 /** Given a list of listener connections in <b>old_conns</b>, and list of
1817 * port_cfg_t entries in <b>ports</b>, open a new listener for every port in
1818 * <b>ports</b> that does not already have a listener in <b>old_conns</b>.
1820 * Remove from <b>old_conns</b> every connection that has a corresponding
1821 * entry in <b>ports</b>. Add to <b>new_conns</b> new every connection we
1824 * If <b>control_listeners_only</b> is true, then we only open control
1825 * listeners, and we do not remove any noncontrol listeners from old_conns.
1827 * Return 0 on success, -1 on failure.
1830 retry_listener_ports(smartlist_t
*old_conns
,
1831 const smartlist_t
*ports
,
1832 smartlist_t
*new_conns
,
1833 int control_listeners_only
)
1835 smartlist_t
*launch
= smartlist_new();
1838 if (control_listeners_only
) {
1839 SMARTLIST_FOREACH(ports
, port_cfg_t
*, p
, {
1840 if (p
->type
== CONN_TYPE_CONTROL_LISTENER
)
1841 smartlist_add(launch
, p
);
1844 smartlist_add_all(launch
, ports
);
1847 /* Iterate through old_conns, comparing it to launch: remove from both lists
1848 * each pair of elements that corresponds to the same port. */
1849 SMARTLIST_FOREACH_BEGIN(old_conns
, connection_t
*, conn
) {
1850 const port_cfg_t
*found_port
= NULL
;
1852 /* Okay, so this is a listener. Is it configured? */
1853 SMARTLIST_FOREACH_BEGIN(launch
, const port_cfg_t
*, wanted
) {
1854 if (conn
->type
!= wanted
->type
)
1856 if ((conn
->socket_family
!= AF_UNIX
&& wanted
->is_unix_addr
) ||
1857 (conn
->socket_family
== AF_UNIX
&& ! wanted
->is_unix_addr
))
1860 if (wanted
->no_listen
)
1861 continue; /* We don't want to open a listener for this one */
1863 if (wanted
->is_unix_addr
) {
1864 if (conn
->socket_family
== AF_UNIX
&&
1865 !strcmp(wanted
->unix_addr
, conn
->address
)) {
1866 found_port
= wanted
;
1871 if (wanted
->port
== CFG_AUTO_PORT
) {
1874 port_matches
= (wanted
->port
== conn
->port
);
1876 if (port_matches
&& tor_addr_eq(&wanted
->addr
, &conn
->addr
)) {
1877 found_port
= wanted
;
1881 } SMARTLIST_FOREACH_END(wanted
);
1884 /* This listener is already running; we don't need to launch it. */
1885 //log_debug(LD_NET, "Already have %s on %s:%d",
1886 // conn_type_to_string(found_port->type), conn->address, conn->port);
1887 smartlist_remove(launch
, found_port
);
1888 /* And we can remove the connection from old_conns too. */
1889 SMARTLIST_DEL_CURRENT(old_conns
, conn
);
1891 } SMARTLIST_FOREACH_END(conn
);
1893 /* Now open all the listeners that are configured but not opened. */
1894 SMARTLIST_FOREACH_BEGIN(launch
, const port_cfg_t
*, port
) {
1895 struct sockaddr
*listensockaddr
;
1896 socklen_t listensocklen
= 0;
1899 int real_port
= port
->port
== CFG_AUTO_PORT
? 0 : port
->port
;
1900 tor_assert(real_port
<= UINT16_MAX
);
1901 if (port
->no_listen
)
1904 if (port
->is_unix_addr
) {
1905 listensockaddr
= (struct sockaddr
*)
1906 create_unix_sockaddr(port
->unix_addr
,
1907 &address
, &listensocklen
);
1909 listensockaddr
= tor_malloc(sizeof(struct sockaddr_storage
));
1910 listensocklen
= tor_addr_to_sockaddr(&port
->addr
,
1913 sizeof(struct sockaddr_storage
));
1914 address
= tor_dup_addr(&port
->addr
);
1917 if (listensockaddr
) {
1918 conn
= connection_listener_new(listensockaddr
, listensocklen
,
1919 port
->type
, address
, port
);
1920 tor_free(listensockaddr
);
1930 smartlist_add(new_conns
, conn
);
1932 } SMARTLIST_FOREACH_END(port
);
1934 smartlist_free(launch
);
1939 /** Launch listeners for each port you should have open. Only launch
1940 * listeners who are not already open, and only close listeners we no longer
1943 * Add all old conns that should be closed to <b>replaced_conns</b>.
1944 * Add all new connections to <b>new_conns</b>.
1946 * If <b>close_all_noncontrol</b> is true, then we only open control
1947 * listeners, and we close all other listeners.
1950 retry_all_listeners(smartlist_t
*replaced_conns
,
1951 smartlist_t
*new_conns
, int close_all_noncontrol
)
1953 smartlist_t
*listeners
= smartlist_new();
1954 const or_options_t
*options
= get_options();
1956 const uint16_t old_or_port
= router_get_advertised_or_port(options
);
1957 const uint16_t old_dir_port
= router_get_advertised_dir_port(options
, 0);
1959 SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t
*, conn
) {
1960 if (connection_is_listener(conn
) && !conn
->marked_for_close
)
1961 smartlist_add(listeners
, conn
);
1962 } SMARTLIST_FOREACH_END(conn
);
1964 if (retry_listener_ports(listeners
,
1965 get_configured_ports(),
1967 close_all_noncontrol
) < 0)
1970 /* Any members that were still in 'listeners' don't correspond to
1971 * any configured port. Kill 'em. */
1972 SMARTLIST_FOREACH_BEGIN(listeners
, connection_t
*, conn
) {
1973 log_notice(LD_NET
, "Closing no-longer-configured %s on %s:%d",
1974 conn_type_to_string(conn
->type
), conn
->address
, conn
->port
);
1975 if (replaced_conns
) {
1976 smartlist_add(replaced_conns
, conn
);
1978 connection_close_immediate(conn
);
1979 connection_mark_for_close(conn
);
1981 } SMARTLIST_FOREACH_END(conn
);
1983 smartlist_free(listeners
);
1985 /* XXXprop186 should take all advertised ports into account */
1986 if (old_or_port
!= router_get_advertised_or_port(options
) ||
1987 old_dir_port
!= router_get_advertised_dir_port(options
, 0)) {
1988 /* Our chosen ORPort or DirPort is not what it used to be: the
1989 * descriptor we had (if any) should be regenerated. (We won't
1990 * automatically notice this because of changes in the option,
1991 * since the value could be "auto".) */
1992 mark_my_descriptor_dirty("Chosen Or/DirPort changed");
1998 /** Mark every listener of type other than CONTROL_LISTENER to be closed. */
2000 connection_mark_all_noncontrol_listeners(void)
2002 SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t
*, conn
) {
2003 if (conn
->marked_for_close
)
2005 if (conn
->type
== CONN_TYPE_CONTROL_LISTENER
)
2007 if (connection_is_listener(conn
))
2008 connection_mark_for_close(conn
);
2009 } SMARTLIST_FOREACH_END(conn
);
2012 /** Mark every external connection not used for controllers for close. */
2014 connection_mark_all_noncontrol_connections(void)
2016 SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t
*, conn
) {
2017 if (conn
->marked_for_close
)
2019 switch (conn
->type
) {
2020 case CONN_TYPE_CPUWORKER
:
2021 case CONN_TYPE_CONTROL_LISTENER
:
2022 case CONN_TYPE_CONTROL
:
2025 connection_mark_unattached_ap(TO_ENTRY_CONN(conn
),
2026 END_STREAM_REASON_HIBERNATING
);
2029 connection_mark_for_close(conn
);
2032 } SMARTLIST_FOREACH_END(conn
);
2035 /** Return 1 if we should apply rate limiting to <b>conn</b>, and 0
2037 * Right now this just checks if it's an internal IP address or an
2038 * internal connection. We also check if the connection uses pluggable
2039 * transports, since we should then limit it even if it comes from an
2040 * internal IP address. */
2042 connection_is_rate_limited(connection_t
*conn
)
2044 const or_options_t
*options
= get_options();
2046 return 0; /* Internal connection */
2047 else if (! options
->CountPrivateBandwidth
&&
2048 (tor_addr_family(&conn
->addr
) == AF_UNSPEC
|| /* no address */
2049 tor_addr_is_internal(&conn
->addr
, 0)))
2050 return 0; /* Internal address */
2055 #ifdef USE_BUFFEREVENTS
2056 static struct bufferevent_rate_limit_group
*global_rate_limit
= NULL
;
2058 extern int global_read_bucket
, global_write_bucket
;
2059 extern int global_relayed_read_bucket
, global_relayed_write_bucket
;
2061 /** Did either global write bucket run dry last second? If so,
2062 * we are likely to run dry again this second, so be stingy with the
2063 * tokens we just put in. */
2064 static int write_buckets_empty_last_second
= 0;
2067 /** How many seconds of no active local circuits will make the
2068 * connection revert to the "relayed" bandwidth class? */
2069 #define CLIENT_IDLE_TIME_FOR_PRIORITY 30
2071 #ifndef USE_BUFFEREVENTS
2072 /** Return 1 if <b>conn</b> should use tokens from the "relayed"
2073 * bandwidth rates, else 0. Currently, only OR conns with bandwidth
2074 * class 1, and directory conns that are serving data out, count.
2077 connection_counts_as_relayed_traffic(connection_t
*conn
, time_t now
)
2079 if (conn
->type
== CONN_TYPE_OR
&&
2080 TO_OR_CONN(conn
)->client_used
+ CLIENT_IDLE_TIME_FOR_PRIORITY
< now
)
2082 if (conn
->type
== CONN_TYPE_DIR
&& DIR_CONN_IS_SERVER(conn
))
2087 /** Helper function to decide how many bytes out of <b>global_bucket</b>
2088 * we're willing to use for this transaction. <b>base</b> is the size
2089 * of a cell on the network; <b>priority</b> says whether we should
2090 * write many of them or just a few; and <b>conn_bucket</b> (if
2091 * non-negative) provides an upper limit for our answer. */
2093 connection_bucket_round_robin(int base
, int priority
,
2094 ssize_t global_bucket
, ssize_t conn_bucket
)
2097 ssize_t num_bytes_high
= (priority
? 32 : 16) * base
;
2098 ssize_t num_bytes_low
= (priority
? 4 : 2) * base
;
2100 /* Do a rudimentary round-robin so one circuit can't hog a connection.
2101 * Pick at most 32 cells, at least 4 cells if possible, and if we're in
2102 * the middle pick 1/8 of the available bandwidth. */
2103 at_most
= global_bucket
/ 8;
2104 at_most
-= (at_most
% base
); /* round down */
2105 if (at_most
> num_bytes_high
) /* 16 KB, or 8 KB for low-priority */
2106 at_most
= num_bytes_high
;
2107 else if (at_most
< num_bytes_low
) /* 2 KB, or 1 KB for low-priority */
2108 at_most
= num_bytes_low
;
2110 if (at_most
> global_bucket
)
2111 at_most
= global_bucket
;
2113 if (conn_bucket
>= 0 && at_most
> conn_bucket
)
2114 at_most
= conn_bucket
;
2121 /** How many bytes at most can we read onto this connection? */
2123 connection_bucket_read_limit(connection_t
*conn
, time_t now
)
2125 int base
= connection_speaks_cells(conn
) ?
2126 CELL_NETWORK_SIZE
: RELAY_PAYLOAD_SIZE
;
2127 int priority
= conn
->type
!= CONN_TYPE_DIR
;
2128 int conn_bucket
= -1;
2129 int global_bucket
= global_read_bucket
;
2131 if (connection_speaks_cells(conn
)) {
2132 or_connection_t
*or_conn
= TO_OR_CONN(conn
);
2133 if (conn
->state
== OR_CONN_STATE_OPEN
)
2134 conn_bucket
= or_conn
->read_bucket
;
2137 if (!connection_is_rate_limited(conn
)) {
2138 /* be willing to read on local conns even if our buckets are empty */
2139 return conn_bucket
>=0 ? conn_bucket
: 1<<14;
2142 if (connection_counts_as_relayed_traffic(conn
, now
) &&
2143 global_relayed_read_bucket
<= global_read_bucket
)
2144 global_bucket
= global_relayed_read_bucket
;
2146 return connection_bucket_round_robin(base
, priority
,
2147 global_bucket
, conn_bucket
);
2150 /** How many bytes at most can we write onto this connection? */
2152 connection_bucket_write_limit(connection_t
*conn
, time_t now
)
2154 int base
= connection_speaks_cells(conn
) ?
2155 CELL_NETWORK_SIZE
: RELAY_PAYLOAD_SIZE
;
2156 int priority
= conn
->type
!= CONN_TYPE_DIR
;
2157 int conn_bucket
= (int)conn
->outbuf_flushlen
;
2158 int global_bucket
= global_write_bucket
;
2160 if (!connection_is_rate_limited(conn
)) {
2161 /* be willing to write to local conns even if our buckets are empty */
2162 return conn
->outbuf_flushlen
;
2165 if (connection_speaks_cells(conn
)) {
2166 /* use the per-conn write limit if it's lower, but if it's less
2167 * than zero just use zero */
2168 or_connection_t
*or_conn
= TO_OR_CONN(conn
);
2169 if (conn
->state
== OR_CONN_STATE_OPEN
)
2170 if (or_conn
->write_bucket
< conn_bucket
)
2171 conn_bucket
= or_conn
->write_bucket
>= 0 ?
2172 or_conn
->write_bucket
: 0;
2175 if (connection_counts_as_relayed_traffic(conn
, now
) &&
2176 global_relayed_write_bucket
<= global_write_bucket
)
2177 global_bucket
= global_relayed_write_bucket
;
2179 return connection_bucket_round_robin(base
, priority
,
2180 global_bucket
, conn_bucket
);
2184 connection_bucket_read_limit(connection_t
*conn
, time_t now
)
2187 return bufferevent_get_max_to_read(conn
->bufev
);
2190 connection_bucket_write_limit(connection_t
*conn
, time_t now
)
2193 return bufferevent_get_max_to_write(conn
->bufev
);
2197 /** Return 1 if the global write buckets are low enough that we
2198 * shouldn't send <b>attempt</b> bytes of low-priority directory stuff
2199 * out to <b>conn</b>. Else return 0.
2201 * Priority is 1 for v1 requests (directories and running-routers),
2202 * and 2 for v2 requests (statuses and descriptors). But see FFFF in
2203 * directory_handle_command_get() for why we don't use priority 2 yet.
2205 * There are a lot of parameters we could use here:
2206 * - global_relayed_write_bucket. Low is bad.
2207 * - global_write_bucket. Low is bad.
2208 * - bandwidthrate. Low is bad.
2209 * - bandwidthburst. Not a big factor?
2210 * - attempt. High is bad.
2211 * - total bytes queued on outbufs. High is bad. But I'm wary of
2212 * using this, since a few slow-flushing queues will pump up the
2213 * number without meaning what we meant to mean. What we really
2214 * mean is "total directory bytes added to outbufs recently", but
2215 * that's harder to quantify and harder to keep track of.
2218 global_write_bucket_low(connection_t
*conn
, size_t attempt
, int priority
)
2220 #ifdef USE_BUFFEREVENTS
2221 ssize_t smaller_bucket
= bufferevent_get_max_to_write(conn
->bufev
);
2223 int smaller_bucket
= global_write_bucket
< global_relayed_write_bucket
?
2224 global_write_bucket
: global_relayed_write_bucket
;
2226 if (authdir_mode(get_options()) && priority
>1)
2227 return 0; /* there's always room to answer v2 if we're an auth dir */
2229 if (!connection_is_rate_limited(conn
))
2230 return 0; /* local conns don't get limited */
2232 if (smaller_bucket
< (int)attempt
)
2233 return 1; /* not enough space no matter the priority */
2235 #ifndef USE_BUFFEREVENTS
2236 if (write_buckets_empty_last_second
)
2237 return 1; /* we're already hitting our limits, no more please */
2240 if (priority
== 1) { /* old-style v1 query */
2241 /* Could we handle *two* of these requests within the next two seconds? */
2242 const or_options_t
*options
= get_options();
2243 int64_t can_write
= (int64_t)smaller_bucket
2244 + 2*(options
->RelayBandwidthRate
? options
->RelayBandwidthRate
:
2245 options
->BandwidthRate
);
2246 if (can_write
< 2*(int64_t)attempt
)
2248 } else { /* v2 query */
2249 /* no further constraints yet */
2254 /** Helper: adjusts our bandwidth history and informs the controller as
2255 * appropriate, given that we have just read <b>num_read</b> bytes and written
2256 * <b>num_written</b> bytes on <b>conn</b>. */
2258 record_num_bytes_transferred_impl(connection_t
*conn
,
2259 time_t now
, size_t num_read
, size_t num_written
)
2261 /* Count bytes of answering direct and tunneled directory requests */
2262 if (conn
->type
== CONN_TYPE_DIR
&& conn
->purpose
== DIR_PURPOSE_SERVER
) {
2264 rep_hist_note_dir_bytes_read(num_read
, now
);
2265 if (num_written
> 0)
2266 rep_hist_note_dir_bytes_written(num_written
, now
);
2269 if (!connection_is_rate_limited(conn
))
2270 return; /* local IPs are free */
2272 if (conn
->type
== CONN_TYPE_OR
)
2273 rep_hist_note_or_conn_bytes(conn
->global_identifier
, num_read
,
2277 rep_hist_note_bytes_read(num_read
, now
);
2279 if (num_written
> 0) {
2280 rep_hist_note_bytes_written(num_written
, now
);
2282 if (conn
->type
== CONN_TYPE_EXIT
)
2283 rep_hist_note_exit_bytes(conn
->port
, num_written
, num_read
);
2286 #ifdef USE_BUFFEREVENTS
2287 /** Wrapper around fetch_from_(buf/evbuffer)_socks_client: see those functions
2288 * for documentation of its behavior. */
2290 record_num_bytes_transferred(connection_t
*conn
,
2291 time_t now
, size_t num_read
, size_t num_written
)
2293 /* XXX024 check if this is necessary */
2294 if (num_written
>= INT_MAX
|| num_read
>= INT_MAX
) {
2295 log_err(LD_BUG
, "Value out of range. num_read=%lu, num_written=%lu, "
2296 "connection type=%s, state=%s",
2297 (unsigned long)num_read
, (unsigned long)num_written
,
2298 conn_type_to_string(conn
->type
),
2299 conn_state_to_string(conn
->type
, conn
->state
));
2300 if (num_written
>= INT_MAX
) num_written
= 1;
2301 if (num_read
>= INT_MAX
) num_read
= 1;
2302 tor_fragile_assert();
2305 record_num_bytes_transferred_impl(conn
,now
,num_read
,num_written
);
2309 #ifndef USE_BUFFEREVENTS
2310 /** We just read <b>num_read</b> and wrote <b>num_written</b> bytes
2311 * onto <b>conn</b>. Decrement buckets appropriately. */
2313 connection_buckets_decrement(connection_t
*conn
, time_t now
,
2314 size_t num_read
, size_t num_written
)
2316 if (num_written
>= INT_MAX
|| num_read
>= INT_MAX
) {
2317 log_err(LD_BUG
, "Value out of range. num_read=%lu, num_written=%lu, "
2318 "connection type=%s, state=%s",
2319 (unsigned long)num_read
, (unsigned long)num_written
,
2320 conn_type_to_string(conn
->type
),
2321 conn_state_to_string(conn
->type
, conn
->state
));
2322 if (num_written
>= INT_MAX
) num_written
= 1;
2323 if (num_read
>= INT_MAX
) num_read
= 1;
2324 tor_fragile_assert();
2327 record_num_bytes_transferred_impl(conn
, now
, num_read
, num_written
);
2329 if (!connection_is_rate_limited(conn
))
2330 return; /* local IPs are free */
2332 if (connection_counts_as_relayed_traffic(conn
, now
)) {
2333 global_relayed_read_bucket
-= (int)num_read
;
2334 global_relayed_write_bucket
-= (int)num_written
;
2336 global_read_bucket
-= (int)num_read
;
2337 global_write_bucket
-= (int)num_written
;
2338 if (connection_speaks_cells(conn
) && conn
->state
== OR_CONN_STATE_OPEN
) {
2339 TO_OR_CONN(conn
)->read_bucket
-= (int)num_read
;
2340 TO_OR_CONN(conn
)->write_bucket
-= (int)num_written
;
2344 /** If we have exhausted our global buckets, or the buckets for conn,
2347 connection_consider_empty_read_buckets(connection_t
*conn
)
2351 if (global_read_bucket
<= 0) {
2352 reason
= "global read bucket exhausted. Pausing.";
2353 } else if (connection_counts_as_relayed_traffic(conn
, approx_time()) &&
2354 global_relayed_read_bucket
<= 0) {
2355 reason
= "global relayed read bucket exhausted. Pausing.";
2356 } else if (connection_speaks_cells(conn
) &&
2357 conn
->state
== OR_CONN_STATE_OPEN
&&
2358 TO_OR_CONN(conn
)->read_bucket
<= 0) {
2359 reason
= "connection read bucket exhausted. Pausing.";
2361 return; /* all good, no need to stop it */
2363 LOG_FN_CONN(conn
, (LOG_DEBUG
, LD_NET
, "%s", reason
));
2364 conn
->read_blocked_on_bw
= 1;
2365 connection_stop_reading(conn
);
2368 /** If we have exhausted our global buckets, or the buckets for conn,
2371 connection_consider_empty_write_buckets(connection_t
*conn
)
2375 if (global_write_bucket
<= 0) {
2376 reason
= "global write bucket exhausted. Pausing.";
2377 } else if (connection_counts_as_relayed_traffic(conn
, approx_time()) &&
2378 global_relayed_write_bucket
<= 0) {
2379 reason
= "global relayed write bucket exhausted. Pausing.";
2380 } else if (connection_speaks_cells(conn
) &&
2381 conn
->state
== OR_CONN_STATE_OPEN
&&
2382 TO_OR_CONN(conn
)->write_bucket
<= 0) {
2383 reason
= "connection write bucket exhausted. Pausing.";
2385 return; /* all good, no need to stop it */
2387 LOG_FN_CONN(conn
, (LOG_DEBUG
, LD_NET
, "%s", reason
));
2388 conn
->write_blocked_on_bw
= 1;
2389 connection_stop_writing(conn
);
2392 /** Initialize the global read bucket to options-\>BandwidthBurst. */
2394 connection_bucket_init(void)
2396 const or_options_t
*options
= get_options();
2397 /* start it at max traffic */
2398 global_read_bucket
= (int)options
->BandwidthBurst
;
2399 global_write_bucket
= (int)options
->BandwidthBurst
;
2400 if (options
->RelayBandwidthRate
) {
2401 global_relayed_read_bucket
= (int)options
->RelayBandwidthBurst
;
2402 global_relayed_write_bucket
= (int)options
->RelayBandwidthBurst
;
2404 global_relayed_read_bucket
= (int)options
->BandwidthBurst
;
2405 global_relayed_write_bucket
= (int)options
->BandwidthBurst
;
2409 /** Refill a single <b>bucket</b> called <b>name</b> with bandwidth rate per
2410 * second <b>rate</b> and bandwidth burst <b>burst</b>, assuming that
2411 * <b>milliseconds_elapsed</b> milliseconds have passed since the last
2414 connection_bucket_refill_helper(int *bucket
, int rate
, int burst
,
2415 int milliseconds_elapsed
,
2418 int starting_bucket
= *bucket
;
2419 if (starting_bucket
< burst
&& milliseconds_elapsed
> 0) {
2420 int64_t incr
= (((int64_t)rate
) * milliseconds_elapsed
) / 1000;
2421 if ((burst
- starting_bucket
) < incr
) {
2422 *bucket
= burst
; /* We would overflow the bucket; just set it to
2425 *bucket
+= (int)incr
;
2426 if (*bucket
> burst
|| *bucket
< starting_bucket
) {
2427 /* If we overflow the burst, or underflow our starting bucket,
2428 * cap the bucket value to burst. */
2429 /* XXXX this might be redundant now, but it doesn't show up
2430 * in profiles. Remove it after analysis. */
2434 log(LOG_DEBUG
, LD_NET
,"%s now %d.", name
, *bucket
);
2438 /** Time has passed; increment buckets appropriately. */
2440 connection_bucket_refill(int milliseconds_elapsed
, time_t now
)
2442 const or_options_t
*options
= get_options();
2443 smartlist_t
*conns
= get_connection_array();
2444 int bandwidthrate
, bandwidthburst
, relayrate
, relayburst
;
2446 bandwidthrate
= (int)options
->BandwidthRate
;
2447 bandwidthburst
= (int)options
->BandwidthBurst
;
2449 if (options
->RelayBandwidthRate
) {
2450 relayrate
= (int)options
->RelayBandwidthRate
;
2451 relayburst
= (int)options
->RelayBandwidthBurst
;
2453 relayrate
= bandwidthrate
;
2454 relayburst
= bandwidthburst
;
2457 tor_assert(milliseconds_elapsed
>= 0);
2459 write_buckets_empty_last_second
=
2460 global_relayed_write_bucket
<= 0 || global_write_bucket
<= 0;
2462 /* refill the global buckets */
2463 connection_bucket_refill_helper(&global_read_bucket
,
2464 bandwidthrate
, bandwidthburst
,
2465 milliseconds_elapsed
,
2466 "global_read_bucket");
2467 connection_bucket_refill_helper(&global_write_bucket
,
2468 bandwidthrate
, bandwidthburst
,
2469 milliseconds_elapsed
,
2470 "global_write_bucket");
2471 connection_bucket_refill_helper(&global_relayed_read_bucket
,
2472 relayrate
, relayburst
,
2473 milliseconds_elapsed
,
2474 "global_relayed_read_bucket");
2475 connection_bucket_refill_helper(&global_relayed_write_bucket
,
2476 relayrate
, relayburst
,
2477 milliseconds_elapsed
,
2478 "global_relayed_write_bucket");
2480 /* refill the per-connection buckets */
2481 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
2483 if (connection_speaks_cells(conn
)) {
2484 or_connection_t
*or_conn
= TO_OR_CONN(conn
);
2485 int orbandwidthrate
= or_conn
->bandwidthrate
;
2486 int orbandwidthburst
= or_conn
->bandwidthburst
;
2487 if (connection_bucket_should_increase(or_conn
->read_bucket
, or_conn
)) {
2488 connection_bucket_refill_helper(&or_conn
->read_bucket
,
2491 milliseconds_elapsed
,
2492 "or_conn->read_bucket");
2494 if (connection_bucket_should_increase(or_conn
->write_bucket
, or_conn
)) {
2495 connection_bucket_refill_helper(&or_conn
->write_bucket
,
2498 milliseconds_elapsed
,
2499 "or_conn->write_bucket");
2503 if (conn
->read_blocked_on_bw
== 1 /* marked to turn reading back on now */
2504 && global_read_bucket
> 0 /* and we're allowed to read */
2505 && (!connection_counts_as_relayed_traffic(conn
, now
) ||
2506 global_relayed_read_bucket
> 0) /* even if we're relayed traffic */
2507 && (!connection_speaks_cells(conn
) ||
2508 conn
->state
!= OR_CONN_STATE_OPEN
||
2509 TO_OR_CONN(conn
)->read_bucket
> 0)) {
2510 /* and either a non-cell conn or a cell conn with non-empty bucket */
2511 LOG_FN_CONN(conn
, (LOG_DEBUG
,LD_NET
,
2512 "waking up conn (fd %d) for read", (int)conn
->s
));
2513 conn
->read_blocked_on_bw
= 0;
2514 connection_start_reading(conn
);
2517 if (conn
->write_blocked_on_bw
== 1
2518 && global_write_bucket
> 0 /* and we're allowed to write */
2519 && (!connection_counts_as_relayed_traffic(conn
, now
) ||
2520 global_relayed_write_bucket
> 0) /* even if it's relayed traffic */
2521 && (!connection_speaks_cells(conn
) ||
2522 conn
->state
!= OR_CONN_STATE_OPEN
||
2523 TO_OR_CONN(conn
)->write_bucket
> 0)) {
2524 LOG_FN_CONN(conn
, (LOG_DEBUG
,LD_NET
,
2525 "waking up conn (fd %d) for write", (int)conn
->s
));
2526 conn
->write_blocked_on_bw
= 0;
2527 connection_start_writing(conn
);
2532 /** Is the <b>bucket</b> for connection <b>conn</b> low enough that we
2533 * should add another pile of tokens to it?
2536 connection_bucket_should_increase(int bucket
, or_connection_t
*conn
)
2540 if (conn
->_base
.state
!= OR_CONN_STATE_OPEN
)
2541 return 0; /* only open connections play the rate limiting game */
2542 if (bucket
>= conn
->bandwidthburst
)
2549 connection_buckets_decrement(connection_t
*conn
, time_t now
,
2550 size_t num_read
, size_t num_written
)
2556 /* Libevent does this for us. */
2560 connection_bucket_refill(int seconds_elapsed
, time_t now
)
2562 (void) seconds_elapsed
;
2564 /* Libevent does this for us. */
2567 connection_bucket_init(void)
2569 const or_options_t
*options
= get_options();
2570 const struct timeval
*tick
= tor_libevent_get_one_tick_timeout();
2571 struct ev_token_bucket_cfg
*bucket_cfg
;
2573 uint64_t rate
, burst
;
2574 if (options
->RelayBandwidthRate
) {
2575 rate
= options
->RelayBandwidthRate
;
2576 burst
= options
->RelayBandwidthBurst
;
2578 rate
= options
->BandwidthRate
;
2579 burst
= options
->BandwidthBurst
;
2582 /* This can't overflow, since TokenBucketRefillInterval <= 1000,
2583 * and rate started out less than INT32_MAX. */
2584 rate
= (rate
* options
->TokenBucketRefillInterval
) / 1000;
2586 bucket_cfg
= ev_token_bucket_cfg_new((uint32_t)rate
, (uint32_t)burst
,
2587 (uint32_t)rate
, (uint32_t)burst
,
2590 if (!global_rate_limit
) {
2592 bufferevent_rate_limit_group_new(tor_libevent_get_base(), bucket_cfg
);
2594 bufferevent_rate_limit_group_set_cfg(global_rate_limit
, bucket_cfg
);
2596 ev_token_bucket_cfg_free(bucket_cfg
);
2600 connection_get_rate_limit_totals(uint64_t *read_out
, uint64_t *written_out
)
2602 if (global_rate_limit
== NULL
) {
2603 *read_out
= *written_out
= 0;
2605 bufferevent_rate_limit_group_get_totals(
2606 global_rate_limit
, read_out
, written_out
);
2610 /** Perform whatever operations are needed on <b>conn</b> to enable
2613 connection_enable_rate_limiting(connection_t
*conn
)
2616 if (!global_rate_limit
)
2617 connection_bucket_init();
2618 tor_add_bufferevent_to_rate_limit_group(conn
->bufev
, global_rate_limit
);
2623 connection_consider_empty_write_buckets(connection_t
*conn
)
2628 connection_consider_empty_read_buckets(connection_t
*conn
)
2634 /** Read bytes from conn-\>s and process them.
2636 * It calls connection_read_to_buf() to bring in any new bytes,
2637 * and then calls connection_process_inbuf() to process them.
2639 * Mark the connection and return -1 if you want to close it, else
2643 connection_handle_read_impl(connection_t
*conn
)
2645 ssize_t max_to_read
=-1, try_to_read
;
2646 size_t before
, n_read
= 0;
2647 int socket_error
= 0;
2649 if (conn
->marked_for_close
)
2650 return 0; /* do nothing */
2652 conn
->timestamp_lastread
= approx_time();
2654 switch (conn
->type
) {
2655 case CONN_TYPE_OR_LISTENER
:
2656 return connection_handle_listener_read(conn
, CONN_TYPE_OR
);
2657 case CONN_TYPE_AP_LISTENER
:
2658 case CONN_TYPE_AP_TRANS_LISTENER
:
2659 case CONN_TYPE_AP_NATD_LISTENER
:
2660 return connection_handle_listener_read(conn
, CONN_TYPE_AP
);
2661 case CONN_TYPE_DIR_LISTENER
:
2662 return connection_handle_listener_read(conn
, CONN_TYPE_DIR
);
2663 case CONN_TYPE_CONTROL_LISTENER
:
2664 return connection_handle_listener_read(conn
, CONN_TYPE_CONTROL
);
2665 case CONN_TYPE_AP_DNS_LISTENER
:
2666 /* This should never happen; eventdns.c handles the reads here. */
2667 tor_fragile_assert();
2672 try_to_read
= max_to_read
;
2673 tor_assert(!conn
->marked_for_close
);
2675 before
= buf_datalen(conn
->inbuf
);
2676 if (connection_read_to_buf(conn
, &max_to_read
, &socket_error
) < 0) {
2677 /* There's a read error; kill the connection.*/
2678 if (conn
->type
== CONN_TYPE_OR
&&
2679 conn
->state
== OR_CONN_STATE_CONNECTING
) {
2680 connection_or_connect_failed(TO_OR_CONN(conn
),
2681 errno_to_orconn_end_reason(socket_error
),
2682 tor_socket_strerror(socket_error
));
2684 if (CONN_IS_EDGE(conn
)) {
2685 edge_connection_t
*edge_conn
= TO_EDGE_CONN(conn
);
2686 connection_edge_end_errno(edge_conn
);
2687 if (conn
->type
== CONN_TYPE_AP
&& TO_ENTRY_CONN(conn
)->socks_request
) {
2688 /* broken, don't send a socks reply back */
2689 TO_ENTRY_CONN(conn
)->socks_request
->has_finished
= 1;
2692 connection_close_immediate(conn
); /* Don't flush; connection is dead. */
2693 connection_mark_for_close(conn
);
2696 n_read
+= buf_datalen(conn
->inbuf
) - before
;
2697 if (CONN_IS_EDGE(conn
) && try_to_read
!= max_to_read
) {
2698 /* instruct it not to try to package partial cells. */
2699 if (connection_process_inbuf(conn
, 0) < 0) {
2702 if (!conn
->marked_for_close
&&
2703 connection_is_reading(conn
) &&
2704 !conn
->inbuf_reached_eof
&&
2706 goto loop_again
; /* try reading again, in case more is here now */
2708 /* one last try, packaging partial cells and all. */
2709 if (!conn
->marked_for_close
&&
2710 connection_process_inbuf(conn
, 1) < 0) {
2713 if (conn
->linked_conn
) {
2714 /* The other side's handle_write() will never actually get called, so
2715 * we need to invoke the appropriate callbacks ourself. */
2716 connection_t
*linked
= conn
->linked_conn
;
2719 /* Probably a no-op, since linked conns typically don't count for
2720 * bandwidth rate limiting. But do it anyway so we can keep stats
2721 * accurately. Note that since we read the bytes from conn, and
2722 * we're writing the bytes onto the linked connection, we count
2723 * these as <i>written</i> bytes. */
2724 connection_buckets_decrement(linked
, approx_time(), 0, n_read
);
2726 if (connection_flushed_some(linked
) < 0)
2727 connection_mark_for_close(linked
);
2728 if (!connection_wants_to_flush(linked
))
2729 connection_finished_flushing(linked
);
2732 if (!buf_datalen(linked
->outbuf
) && conn
->active_on_link
)
2733 connection_stop_reading_from_linked_conn(conn
);
2735 /* If we hit the EOF, call connection_reached_eof(). */
2736 if (!conn
->marked_for_close
&&
2737 conn
->inbuf_reached_eof
&&
2738 connection_reached_eof(conn
) < 0) {
2744 /* DOCDOC connection_handle_read */
2746 connection_handle_read(connection_t
*conn
)
2750 tor_gettimeofday_cache_clear();
2751 res
= connection_handle_read_impl(conn
);
2755 /** Pull in new bytes from conn-\>s or conn-\>linked_conn onto conn-\>inbuf,
2756 * either directly or via TLS. Reduce the token buckets by the number of bytes
2759 * If *max_to_read is -1, then decide it ourselves, else go with the
2760 * value passed to us. When returning, if it's changed, subtract the
2761 * number of bytes we read from *max_to_read.
2763 * Return -1 if we want to break conn, else return 0.
2766 connection_read_to_buf(connection_t
*conn
, ssize_t
*max_to_read
,
2770 ssize_t at_most
= *max_to_read
;
2771 size_t slack_in_buf
, more_to_read
;
2772 size_t n_read
= 0, n_written
= 0;
2774 if (at_most
== -1) { /* we need to initialize it */
2775 /* how many bytes are we allowed to read? */
2776 at_most
= connection_bucket_read_limit(conn
, approx_time());
2779 slack_in_buf
= buf_slack(conn
->inbuf
);
2781 if ((size_t)at_most
> slack_in_buf
&& slack_in_buf
>= 1024) {
2782 more_to_read
= at_most
- slack_in_buf
;
2783 at_most
= slack_in_buf
;
2788 if (connection_speaks_cells(conn
) &&
2789 conn
->state
> OR_CONN_STATE_PROXY_HANDSHAKING
) {
2791 or_connection_t
*or_conn
= TO_OR_CONN(conn
);
2792 size_t initial_size
;
2793 if (conn
->state
== OR_CONN_STATE_TLS_HANDSHAKING
||
2794 conn
->state
== OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING
) {
2795 /* continue handshaking even if global token bucket is empty */
2796 return connection_tls_continue_handshake(or_conn
);
2800 "%d: starting, inbuf_datalen %ld (%d pending in tls object)."
2802 (int)conn
->s
,(long)buf_datalen(conn
->inbuf
),
2803 tor_tls_get_pending_bytes(or_conn
->tls
), (long)at_most
);
2805 initial_size
= buf_datalen(conn
->inbuf
);
2806 /* else open, or closing */
2807 result
= read_to_buf_tls(or_conn
->tls
, at_most
, conn
->inbuf
);
2808 if (TOR_TLS_IS_ERROR(result
) || result
== TOR_TLS_CLOSE
)
2809 or_conn
->tls_error
= result
;
2811 or_conn
->tls_error
= 0;
2815 case TOR_TLS_ERROR_IO
:
2816 log_debug(LD_NET
,"TLS connection closed %son read. Closing. "
2817 "(Nickname %s, address %s)",
2818 result
== TOR_TLS_CLOSE
? "cleanly " : "",
2819 or_conn
->nickname
? or_conn
->nickname
: "not set",
2822 CASE_TOR_TLS_ERROR_ANY_NONIO
:
2823 log_debug(LD_NET
,"tls error [%s]. breaking (nickname %s, address %s).",
2824 tor_tls_err_to_string(result
),
2825 or_conn
->nickname
? or_conn
->nickname
: "not set",
2828 case TOR_TLS_WANTWRITE
:
2829 connection_start_writing(conn
);
2831 case TOR_TLS_WANTREAD
: /* we're already reading */
2832 case TOR_TLS_DONE
: /* no data read, so nothing to process */
2834 break; /* so we call bucket_decrement below */
2838 pending
= tor_tls_get_pending_bytes(or_conn
->tls
);
2840 /* If we have any pending bytes, we read them now. This *can*
2841 * take us over our read allotment, but really we shouldn't be
2842 * believing that SSL bytes are the same as TCP bytes anyway. */
2843 int r2
= read_to_buf_tls(or_conn
->tls
, pending
, conn
->inbuf
);
2845 log_warn(LD_BUG
, "apparently, reading pending bytes can fail.");
2849 result
= (int)(buf_datalen(conn
->inbuf
)-initial_size
);
2850 tor_tls_get_n_raw_bytes(or_conn
->tls
, &n_read
, &n_written
);
2851 log_debug(LD_GENERAL
, "After TLS read of %d: %ld read, %ld written",
2852 result
, (long)n_read
, (long)n_written
);
2853 } else if (conn
->linked
) {
2854 if (conn
->linked_conn
) {
2855 result
= move_buf_to_buf(conn
->inbuf
, conn
->linked_conn
->outbuf
,
2856 &conn
->linked_conn
->outbuf_flushlen
);
2860 //log_notice(LD_GENERAL, "Moved %d bytes on an internal link!", result);
2861 /* If the other side has disappeared, or if it's been marked for close and
2862 * we flushed its outbuf, then we should set our inbuf_reached_eof. */
2863 if (!conn
->linked_conn
||
2864 (conn
->linked_conn
->marked_for_close
&&
2865 buf_datalen(conn
->linked_conn
->outbuf
) == 0))
2866 conn
->inbuf_reached_eof
= 1;
2868 n_read
= (size_t) result
;
2870 /* !connection_speaks_cells, !conn->linked_conn. */
2871 int reached_eof
= 0;
2872 CONN_LOG_PROTECT(conn
,
2873 result
= read_to_buf(conn
->s
, at_most
, conn
->inbuf
, &reached_eof
,
2876 conn
->inbuf_reached_eof
= 1;
2878 // log_fn(LOG_DEBUG,"read_to_buf returned %d.",read_result);
2882 n_read
= (size_t) result
;
2886 /* change *max_to_read */
2887 *max_to_read
= at_most
- n_read
;
2889 /* Update edge_conn->n_read */
2890 if (conn
->type
== CONN_TYPE_AP
) {
2891 edge_connection_t
*edge_conn
= TO_EDGE_CONN(conn
);
2892 /* Check for overflow: */
2893 if (PREDICT_LIKELY(UINT32_MAX
- edge_conn
->n_read
> n_read
))
2894 edge_conn
->n_read
+= (int)n_read
;
2896 edge_conn
->n_read
= UINT32_MAX
;
2900 connection_buckets_decrement(conn
, approx_time(), n_read
, n_written
);
2902 if (more_to_read
&& result
== at_most
) {
2903 slack_in_buf
= buf_slack(conn
->inbuf
);
2904 at_most
= more_to_read
;
2908 /* Call even if result is 0, since the global read bucket may
2909 * have reached 0 on a different conn, and this guy needs to
2910 * know to stop reading. */
2911 connection_consider_empty_read_buckets(conn
);
2912 if (n_written
> 0 && connection_is_writing(conn
))
2913 connection_consider_empty_write_buckets(conn
);
2918 #ifdef USE_BUFFEREVENTS
2919 /* XXXX These generic versions could be simplified by making them
2922 /** Callback: Invoked whenever bytes are added to or drained from an input
2923 * evbuffer. Used to track the number of bytes read. */
2925 evbuffer_inbuf_callback(struct evbuffer
*buf
,
2926 const struct evbuffer_cb_info
*info
, void *arg
)
2928 connection_t
*conn
= arg
;
2930 /* XXXX These need to get real counts on the non-nested TLS case. - NM */
2931 if (info
->n_added
) {
2932 time_t now
= approx_time();
2933 conn
->timestamp_lastread
= now
;
2934 record_num_bytes_transferred(conn
, now
, info
->n_added
, 0);
2935 connection_consider_empty_read_buckets(conn
);
2936 if (conn
->type
== CONN_TYPE_AP
) {
2937 edge_connection_t
*edge_conn
= TO_EDGE_CONN(conn
);
2938 /*XXXX024 check for overflow*/
2939 edge_conn
->n_read
+= (int)info
->n_added
;
2944 /** Callback: Invoked whenever bytes are added to or drained from an output
2945 * evbuffer. Used to track the number of bytes written. */
2947 evbuffer_outbuf_callback(struct evbuffer
*buf
,
2948 const struct evbuffer_cb_info
*info
, void *arg
)
2950 connection_t
*conn
= arg
;
2952 if (info
->n_deleted
) {
2953 time_t now
= approx_time();
2954 conn
->timestamp_lastwritten
= now
;
2955 record_num_bytes_transferred(conn
, now
, 0, info
->n_deleted
);
2956 connection_consider_empty_write_buckets(conn
);
2957 if (conn
->type
== CONN_TYPE_AP
) {
2958 edge_connection_t
*edge_conn
= TO_EDGE_CONN(conn
);
2959 /*XXXX024 check for overflow*/
2960 edge_conn
->n_written
+= (int)info
->n_deleted
;
2965 /** Callback: invoked whenever a bufferevent has read data. */
2967 connection_handle_read_cb(struct bufferevent
*bufev
, void *arg
)
2969 connection_t
*conn
= arg
;
2971 if (!conn
->marked_for_close
) {
2972 if (connection_process_inbuf(conn
, 1)<0) /* XXXX Always 1? */
2973 if (!conn
->marked_for_close
)
2974 connection_mark_for_close(conn
);
2978 /** Callback: invoked whenever a bufferevent has written data. */
2980 connection_handle_write_cb(struct bufferevent
*bufev
, void *arg
)
2982 connection_t
*conn
= arg
;
2983 struct evbuffer
*output
;
2984 if (connection_flushed_some(conn
)<0) {
2985 if (!conn
->marked_for_close
)
2986 connection_mark_for_close(conn
);
2990 output
= bufferevent_get_output(bufev
);
2991 if (!evbuffer_get_length(output
)) {
2992 connection_finished_flushing(conn
);
2993 if (conn
->marked_for_close
&& conn
->hold_open_until_flushed
) {
2994 conn
->hold_open_until_flushed
= 0;
2997 bufferevent_flush(conn
->bufev
, EV_WRITE
, BEV_FINISHED
);
3003 /** Callback: invoked whenever a bufferevent has had an event (like a
3004 * connection, or an eof, or an error) occur. */
3006 connection_handle_event_cb(struct bufferevent
*bufev
, short event
, void *arg
)
3008 connection_t
*conn
= arg
;
3010 if (conn
->marked_for_close
)
3013 if (event
& BEV_EVENT_CONNECTED
) {
3014 tor_assert(connection_state_is_connecting(conn
));
3015 if (connection_finished_connecting(conn
)<0)
3018 if (event
& BEV_EVENT_EOF
) {
3019 if (!conn
->marked_for_close
) {
3020 conn
->inbuf_reached_eof
= 1;
3021 if (connection_reached_eof(conn
)<0)
3025 if (event
& BEV_EVENT_ERROR
) {
3026 int socket_error
= evutil_socket_geterror(conn
->s
);
3027 if (conn
->type
== CONN_TYPE_OR
&&
3028 conn
->state
== OR_CONN_STATE_CONNECTING
) {
3029 connection_or_connect_failed(TO_OR_CONN(conn
),
3030 errno_to_orconn_end_reason(socket_error
),
3031 tor_socket_strerror(socket_error
));
3032 } else if (CONN_IS_EDGE(conn
)) {
3033 edge_connection_t
*edge_conn
= TO_EDGE_CONN(conn
);
3034 if (!edge_conn
->edge_has_sent_end
)
3035 connection_edge_end_errno(edge_conn
);
3036 if (conn
->type
== CONN_TYPE_AP
&& TO_ENTRY_CONN(conn
)->socks_request
) {
3037 /* broken, don't send a socks reply back */
3038 TO_ENTRY_CONN(conn
)->socks_request
->has_finished
= 1;
3041 connection_close_immediate(conn
); /* Connection is dead. */
3042 if (!conn
->marked_for_close
)
3043 connection_mark_for_close(conn
);
3047 /** Set up the generic callbacks for the bufferevent on <b>conn</b>. */
3049 connection_configure_bufferevent_callbacks(connection_t
*conn
)
3051 struct bufferevent
*bufev
;
3052 struct evbuffer
*input
, *output
;
3053 tor_assert(conn
->bufev
);
3054 bufev
= conn
->bufev
;
3055 bufferevent_setcb(bufev
,
3056 connection_handle_read_cb
,
3057 connection_handle_write_cb
,
3058 connection_handle_event_cb
,
3060 /* Set a fairly high write low-watermark so that we get the write callback
3061 called whenever data is written to bring us under 128K. Leave the
3062 high-watermark at 0.
3064 bufferevent_setwatermark(bufev
, EV_WRITE
, 128*1024, 0);
3066 input
= bufferevent_get_input(bufev
);
3067 output
= bufferevent_get_output(bufev
);
3068 evbuffer_add_cb(input
, evbuffer_inbuf_callback
, conn
);
3069 evbuffer_add_cb(output
, evbuffer_outbuf_callback
, conn
);
3073 /** A pass-through to fetch_from_buf. */
3075 connection_fetch_from_buf(char *string
, size_t len
, connection_t
*conn
)
3077 IF_HAS_BUFFEREVENT(conn
, {
3078 /* XXX overflow -seb */
3079 return (int)bufferevent_read(conn
->bufev
, string
, len
);
3080 }) ELSE_IF_NO_BUFFEREVENT
{
3081 return fetch_from_buf(string
, len
, conn
->inbuf
);
3085 /** As fetch_from_buf_line(), but read from a connection's input buffer. */
3087 connection_fetch_from_buf_line(connection_t
*conn
, char *data
,
3090 IF_HAS_BUFFEREVENT(conn
, {
3093 struct evbuffer
*input
= bufferevent_get_input(conn
->bufev
);
3094 struct evbuffer_ptr ptr
=
3095 evbuffer_search_eol(input
, NULL
, &eol_len
, EVBUFFER_EOL_LF
);
3097 return 0; /* No EOL found. */
3098 if ((size_t)ptr
.pos
+eol_len
>= *data_len
) {
3099 return -1; /* Too long */
3101 *data_len
= ptr
.pos
+eol_len
;
3102 r
= evbuffer_remove(input
, data
, ptr
.pos
+eol_len
);
3104 data
[ptr
.pos
+eol_len
] = '\0';
3106 }) ELSE_IF_NO_BUFFEREVENT
{
3107 return fetch_from_buf_line(conn
->inbuf
, data
, data_len
);
3111 /** As fetch_from_buf_http, but fetches from a conncetion's input buffer_t or
3112 * its bufferevent as appropriate. */
3114 connection_fetch_from_buf_http(connection_t
*conn
,
3115 char **headers_out
, size_t max_headerlen
,
3116 char **body_out
, size_t *body_used
,
3117 size_t max_bodylen
, int force_complete
)
3119 IF_HAS_BUFFEREVENT(conn
, {
3120 struct evbuffer
*input
= bufferevent_get_input(conn
->bufev
);
3121 return fetch_from_evbuffer_http(input
, headers_out
, max_headerlen
,
3122 body_out
, body_used
, max_bodylen
, force_complete
);
3123 }) ELSE_IF_NO_BUFFEREVENT
{
3124 return fetch_from_buf_http(conn
->inbuf
, headers_out
, max_headerlen
,
3125 body_out
, body_used
, max_bodylen
, force_complete
);
3129 /** Return conn-\>outbuf_flushlen: how many bytes conn wants to flush
3130 * from its outbuf. */
3132 connection_wants_to_flush(connection_t
*conn
)
3134 return conn
->outbuf_flushlen
> 0;
3137 /** Are there too many bytes on edge connection <b>conn</b>'s outbuf to
3138 * send back a relay-level sendme yet? Return 1 if so, 0 if not. Used by
3139 * connection_edge_consider_sending_sendme().
3142 connection_outbuf_too_full(connection_t
*conn
)
3144 return (conn
->outbuf_flushlen
> 10*CELL_PAYLOAD_SIZE
);
3147 /** Try to flush more bytes onto <b>conn</b>-\>s.
3149 * This function gets called either from conn_write() in main.c
3150 * when poll() has declared that conn wants to write, or below
3151 * from connection_write_to_buf() when an entire TLS record is ready.
3153 * Update <b>conn</b>-\>timestamp_lastwritten to now, and call flush_buf
3154 * or flush_buf_tls appropriately. If it succeeds and there are no more
3155 * more bytes on <b>conn</b>-\>outbuf, then call connection_finished_flushing
3158 * If <b>force</b>, then write as many bytes as possible, ignoring bandwidth
3159 * limits. (Used for flushing messages to controller connections on fatal
3162 * Mark the connection and return -1 if you want to close it, else
3166 connection_handle_write_impl(connection_t
*conn
, int force
)
3169 socklen_t len
=(socklen_t
)sizeof(e
);
3171 ssize_t max_to_write
;
3172 time_t now
= approx_time();
3173 size_t n_read
= 0, n_written
= 0;
3175 tor_assert(!connection_is_listener(conn
));
3177 if (conn
->marked_for_close
|| !SOCKET_OK(conn
->s
))
3178 return 0; /* do nothing */
3180 if (conn
->in_flushed_some
) {
3181 log_warn(LD_BUG
, "called recursively from inside conn->in_flushed_some");
3185 conn
->timestamp_lastwritten
= now
;
3187 /* Sometimes, "writable" means "connected". */
3188 if (connection_state_is_connecting(conn
)) {
3189 if (getsockopt(conn
->s
, SOL_SOCKET
, SO_ERROR
, (void*)&e
, &len
) < 0) {
3190 log_warn(LD_BUG
, "getsockopt() syscall failed");
3191 if (CONN_IS_EDGE(conn
))
3192 connection_edge_end_errno(TO_EDGE_CONN(conn
));
3193 connection_mark_for_close(conn
);
3197 /* some sort of error, but maybe just inprogress still */
3198 if (!ERRNO_IS_CONN_EINPROGRESS(e
)) {
3199 log_info(LD_NET
,"in-progress connect failed. Removing. (%s)",
3200 tor_socket_strerror(e
));
3201 if (CONN_IS_EDGE(conn
))
3202 connection_edge_end_errno(TO_EDGE_CONN(conn
));
3203 if (conn
->type
== CONN_TYPE_OR
)
3204 connection_or_connect_failed(TO_OR_CONN(conn
),
3205 errno_to_orconn_end_reason(e
),
3206 tor_socket_strerror(e
));
3208 connection_close_immediate(conn
);
3209 connection_mark_for_close(conn
);
3212 return 0; /* no change, see if next time is better */
3215 /* The connection is successful. */
3216 if (connection_finished_connecting(conn
)<0)
3220 max_to_write
= force
? (ssize_t
)conn
->outbuf_flushlen
3221 : connection_bucket_write_limit(conn
, now
);
3223 if (connection_speaks_cells(conn
) &&
3224 conn
->state
> OR_CONN_STATE_PROXY_HANDSHAKING
) {
3225 or_connection_t
*or_conn
= TO_OR_CONN(conn
);
3226 if (conn
->state
== OR_CONN_STATE_TLS_HANDSHAKING
||
3227 conn
->state
== OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING
) {
3228 connection_stop_writing(conn
);
3229 if (connection_tls_continue_handshake(or_conn
) < 0) {
3230 /* Don't flush; connection is dead. */
3231 connection_close_immediate(conn
);
3232 connection_mark_for_close(conn
);
3236 } else if (conn
->state
== OR_CONN_STATE_TLS_SERVER_RENEGOTIATING
) {
3237 return connection_handle_read(conn
);
3240 /* else open, or closing */
3241 result
= flush_buf_tls(or_conn
->tls
, conn
->outbuf
,
3242 max_to_write
, &conn
->outbuf_flushlen
);
3244 /* If we just flushed the last bytes, check if this tunneled dir
3245 * request is done. */
3246 /* XXXX move this to flushed_some or finished_flushing -NM */
3247 if (buf_datalen(conn
->outbuf
) == 0 && conn
->dirreq_id
)
3248 geoip_change_dirreq_state(conn
->dirreq_id
, DIRREQ_TUNNELED
,
3249 DIRREQ_OR_CONN_BUFFER_FLUSHED
);
3252 CASE_TOR_TLS_ERROR_ANY
:
3254 log_info(LD_NET
,result
!=TOR_TLS_CLOSE
?
3255 "tls error. breaking.":"TLS connection closed on flush");
3256 /* Don't flush; connection is dead. */
3257 connection_close_immediate(conn
);
3258 connection_mark_for_close(conn
);
3260 case TOR_TLS_WANTWRITE
:
3261 log_debug(LD_NET
,"wanted write.");
3262 /* we're already writing */
3264 case TOR_TLS_WANTREAD
:
3265 /* Make sure to avoid a loop if the receive buckets are empty. */
3266 log_debug(LD_NET
,"wanted read.");
3267 if (!connection_is_reading(conn
)) {
3268 connection_stop_writing(conn
);
3269 conn
->write_blocked_on_bw
= 1;
3270 /* we'll start reading again when we get more tokens in our
3271 * read bucket; then we'll start writing again too.
3274 /* else no problem, we're already reading */
3276 /* case TOR_TLS_DONE:
3277 * for TOR_TLS_DONE, fall through to check if the flushlen
3278 * is empty, so we can stop writing.
3282 tor_tls_get_n_raw_bytes(or_conn
->tls
, &n_read
, &n_written
);
3283 log_debug(LD_GENERAL
, "After TLS write of %d: %ld read, %ld written",
3284 result
, (long)n_read
, (long)n_written
);
3286 CONN_LOG_PROTECT(conn
,
3287 result
= flush_buf(conn
->s
, conn
->outbuf
,
3288 max_to_write
, &conn
->outbuf_flushlen
));
3290 if (CONN_IS_EDGE(conn
))
3291 connection_edge_end_errno(TO_EDGE_CONN(conn
));
3293 connection_close_immediate(conn
); /* Don't flush; connection is dead. */
3294 connection_mark_for_close(conn
);
3297 n_written
= (size_t) result
;
3300 if (n_written
&& conn
->type
== CONN_TYPE_AP
) {
3301 edge_connection_t
*edge_conn
= TO_EDGE_CONN(conn
);
3303 /* Check for overflow: */
3304 if (PREDICT_LIKELY(UINT32_MAX
- edge_conn
->n_written
> n_written
))
3305 edge_conn
->n_written
+= (int)n_written
;
3307 edge_conn
->n_written
= UINT32_MAX
;
3310 connection_buckets_decrement(conn
, approx_time(), n_read
, n_written
);
3313 /* If we wrote any bytes from our buffer, then call the appropriate
3315 if (connection_flushed_some(conn
) < 0)
3316 connection_mark_for_close(conn
);
3319 if (!connection_wants_to_flush(conn
)) { /* it's done flushing */
3320 if (connection_finished_flushing(conn
) < 0) {
3321 /* already marked */
3327 /* Call even if result is 0, since the global write bucket may
3328 * have reached 0 on a different conn, and this guy needs to
3329 * know to stop writing. */
3330 connection_consider_empty_write_buckets(conn
);
3331 if (n_read
> 0 && connection_is_reading(conn
))
3332 connection_consider_empty_read_buckets(conn
);
3337 /* DOCDOC connection_handle_write */
3339 connection_handle_write(connection_t
*conn
, int force
)
3342 tor_gettimeofday_cache_clear();
3343 res
= connection_handle_write_impl(conn
, force
);
3348 * Try to flush data that's waiting for a write on <b>conn</b>. Return
3349 * -1 on failure, 0 on success.
3351 * Don't use this function for regular writing; the buffers/bufferevents
3352 * system should be good enough at scheduling writes there. Instead, this
3353 * function is for cases when we're about to exit or something and we want
3354 * to report it right away.
3357 connection_flush(connection_t
*conn
)
3359 IF_HAS_BUFFEREVENT(conn
, {
3360 int r
= bufferevent_flush(conn
->bufev
, EV_WRITE
, BEV_FLUSH
);
3361 return (r
< 0) ? -1 : 0;
3363 return connection_handle_write(conn
, 1);
3366 /** OpenSSL TLS record size is 16383; this is close. The goal here is to
3367 * push data out as soon as we know there's enough for a TLS record, so
3368 * during periods of high load we won't read entire megabytes from
3369 * input before pushing any data out. It also has the feature of not
3370 * growing huge outbufs unless something is slow. */
3371 #define MIN_TLS_FLUSHLEN 15872
3373 /** Append <b>len</b> bytes of <b>string</b> onto <b>conn</b>'s
3374 * outbuf, and ask it to start writing.
3376 * If <b>zlib</b> is nonzero, this is a directory connection that should get
3377 * its contents compressed or decompressed as they're written. If zlib is
3378 * negative, this is the last data to be compressed, and the connection's zlib
3379 * state should be flushed.
3381 * If it's an OR conn and an entire TLS record is ready, then try to
3382 * flush the record now. Similarly, if it's a local control connection
3383 * and a 64k chunk is ready, try to flush it all, so we don't end up with
3384 * many megabytes of controller info queued at once.
3387 _connection_write_to_buf_impl(const char *string
, size_t len
,
3388 connection_t
*conn
, int zlib
)
3390 /* XXXX This function really needs to return -1 on failure. */
3393 if (!len
&& !(zlib
<0))
3395 /* if it's marked for close, only allow write if we mean to flush it */
3396 if (conn
->marked_for_close
&& !conn
->hold_open_until_flushed
)
3399 IF_HAS_BUFFEREVENT(conn
, {
3401 int done
= zlib
< 0;
3402 r
= write_to_evbuffer_zlib(bufferevent_get_output(conn
->bufev
),
3403 TO_DIR_CONN(conn
)->zlib_state
,
3406 r
= bufferevent_write(conn
->bufev
, string
, len
);
3409 /* XXXX mark for close? */
3410 log_warn(LD_NET
, "bufferevent_write failed! That shouldn't happen.");
3415 old_datalen
= buf_datalen(conn
->outbuf
);
3417 dir_connection_t
*dir_conn
= TO_DIR_CONN(conn
);
3418 int done
= zlib
< 0;
3419 CONN_LOG_PROTECT(conn
, r
= write_to_buf_zlib(conn
->outbuf
,
3420 dir_conn
->zlib_state
,
3421 string
, len
, done
));
3423 CONN_LOG_PROTECT(conn
, r
= write_to_buf(string
, len
, conn
->outbuf
));
3426 if (CONN_IS_EDGE(conn
)) {
3427 /* if it failed, it means we have our package/delivery windows set
3428 wrong compared to our max outbuf size. close the whole circuit. */
3430 "write_to_buf failed. Closing circuit (fd %d).", (int)conn
->s
);
3431 circuit_mark_for_close(circuit_get_by_edge_conn(TO_EDGE_CONN(conn
)),
3432 END_CIRC_REASON_INTERNAL
);
3435 "write_to_buf failed. Closing connection (fd %d).",
3437 connection_mark_for_close(conn
);
3442 /* If we receive optimistic data in the EXIT_CONN_STATE_RESOLVING
3443 * state, we don't want to try to write it right away, since
3444 * conn->write_event won't be set yet. Otherwise, write data from
3445 * this conn as the socket is available. */
3446 if (conn
->write_event
) {
3447 connection_start_writing(conn
);
3450 conn
->outbuf_flushlen
+= buf_datalen(conn
->outbuf
) - old_datalen
;
3453 conn
->outbuf_flushlen
+= len
;
3455 /* Should we try flushing the outbuf now? */
3456 if (conn
->in_flushed_some
) {
3457 /* Don't flush the outbuf when the reason we're writing more stuff is
3458 * _because_ we flushed the outbuf. That's unfair. */
3462 if (conn
->type
== CONN_TYPE_OR
&&
3463 conn
->outbuf_flushlen
-len
< MIN_TLS_FLUSHLEN
&&
3464 conn
->outbuf_flushlen
>= MIN_TLS_FLUSHLEN
) {
3465 /* We just pushed outbuf_flushlen to MIN_TLS_FLUSHLEN or above;
3466 * we can send out a full TLS frame now if we like. */
3467 extra
= conn
->outbuf_flushlen
- MIN_TLS_FLUSHLEN
;
3468 conn
->outbuf_flushlen
= MIN_TLS_FLUSHLEN
;
3469 } else if (conn
->type
== CONN_TYPE_CONTROL
&&
3470 !connection_is_rate_limited(conn
) &&
3471 conn
->outbuf_flushlen
-len
< 1<<16 &&
3472 conn
->outbuf_flushlen
>= 1<<16) {
3473 /* just try to flush all of it */
3475 return; /* no need to try flushing */
3477 if (connection_handle_write(conn
, 0) < 0) {
3478 if (!conn
->marked_for_close
) {
3479 /* this connection is broken. remove it. */
3480 log_warn(LD_BUG
, "unhandled error on write for "
3481 "conn (type %d, fd %d); removing",
3482 conn
->type
, (int)conn
->s
);
3483 tor_fragile_assert();
3484 /* do a close-immediate here, so we don't try to flush */
3485 connection_close_immediate(conn
);
3490 conn
->outbuf_flushlen
+= extra
;
3491 connection_start_writing(conn
);
3496 /** Return a connection with given type, address, port, and purpose;
3497 * or NULL if no such connection exists. */
3499 connection_get_by_type_addr_port_purpose(int type
,
3500 const tor_addr_t
*addr
, uint16_t port
,
3503 smartlist_t
*conns
= get_connection_array();
3504 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
3506 if (conn
->type
== type
&&
3507 tor_addr_eq(&conn
->addr
, addr
) &&
3508 conn
->port
== port
&&
3509 conn
->purpose
== purpose
&&
3510 !conn
->marked_for_close
)
3516 /** Return the stream with id <b>id</b> if it is not already marked for
3520 connection_get_by_global_id(uint64_t id
)
3522 smartlist_t
*conns
= get_connection_array();
3523 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
3525 if (conn
->global_identifier
== id
)
3531 /** Return a connection of type <b>type</b> that is not marked for close.
3534 connection_get_by_type(int type
)
3536 smartlist_t
*conns
= get_connection_array();
3537 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
3539 if (conn
->type
== type
&& !conn
->marked_for_close
)
3545 /** Return a connection of type <b>type</b> that is in state <b>state</b>,
3546 * and that is not marked for close.
3549 connection_get_by_type_state(int type
, int state
)
3551 smartlist_t
*conns
= get_connection_array();
3552 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
3554 if (conn
->type
== type
&& conn
->state
== state
&& !conn
->marked_for_close
)
3560 /** Return a connection of type <b>type</b> that has rendquery equal
3561 * to <b>rendquery</b>, and that is not marked for close. If state
3562 * is non-zero, conn must be of that state too.
3565 connection_get_by_type_state_rendquery(int type
, int state
,
3566 const char *rendquery
)
3568 smartlist_t
*conns
= get_connection_array();
3570 tor_assert(type
== CONN_TYPE_DIR
||
3571 type
== CONN_TYPE_AP
|| type
== CONN_TYPE_EXIT
);
3572 tor_assert(rendquery
);
3574 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, conn
) {
3575 if (conn
->type
== type
&&
3576 !conn
->marked_for_close
&&
3577 (!state
|| state
== conn
->state
)) {
3578 if (type
== CONN_TYPE_DIR
&&
3579 TO_DIR_CONN(conn
)->rend_data
&&
3580 !rend_cmp_service_ids(rendquery
,
3581 TO_DIR_CONN(conn
)->rend_data
->onion_address
))
3583 else if (CONN_IS_EDGE(conn
) &&
3584 TO_EDGE_CONN(conn
)->rend_data
&&
3585 !rend_cmp_service_ids(rendquery
,
3586 TO_EDGE_CONN(conn
)->rend_data
->onion_address
))
3589 } SMARTLIST_FOREACH_END(conn
);
3593 /** Return a directory connection (if any one exists) that is fetching
3594 * the item described by <b>state</b>/<b>resource</b> */
3596 connection_dir_get_by_purpose_and_resource(int purpose
,
3597 const char *resource
)
3599 smartlist_t
*conns
= get_connection_array();
3601 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, conn
) {
3602 dir_connection_t
*dirconn
;
3603 if (conn
->type
!= CONN_TYPE_DIR
|| conn
->marked_for_close
||
3604 conn
->purpose
!= purpose
)
3606 dirconn
= TO_DIR_CONN(conn
);
3607 if (dirconn
->requested_resource
== NULL
) {
3608 if (resource
== NULL
)
3610 } else if (resource
) {
3611 if (0 == strcmp(resource
, dirconn
->requested_resource
))
3614 } SMARTLIST_FOREACH_END(conn
);
3619 /** Return an open, non-marked connection of a given type and purpose, or NULL
3620 * if no such connection exists. */
3622 connection_get_by_type_purpose(int type
, int purpose
)
3624 smartlist_t
*conns
= get_connection_array();
3625 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
3627 if (conn
->type
== type
&&
3628 !conn
->marked_for_close
&&
3629 (purpose
== conn
->purpose
))
3635 /** Return 1 if <b>conn</b> is a listener conn, else return 0. */
3637 connection_is_listener(connection_t
*conn
)
3639 if (conn
->type
== CONN_TYPE_OR_LISTENER
||
3640 conn
->type
== CONN_TYPE_AP_LISTENER
||
3641 conn
->type
== CONN_TYPE_AP_TRANS_LISTENER
||
3642 conn
->type
== CONN_TYPE_AP_DNS_LISTENER
||
3643 conn
->type
== CONN_TYPE_AP_NATD_LISTENER
||
3644 conn
->type
== CONN_TYPE_DIR_LISTENER
||
3645 conn
->type
== CONN_TYPE_CONTROL_LISTENER
)
3650 /** Return 1 if <b>conn</b> is in state "open" and is not marked
3651 * for close, else return 0.
3654 connection_state_is_open(connection_t
*conn
)
3658 if (conn
->marked_for_close
)
3661 if ((conn
->type
== CONN_TYPE_OR
&& conn
->state
== OR_CONN_STATE_OPEN
) ||
3662 (conn
->type
== CONN_TYPE_AP
&& conn
->state
== AP_CONN_STATE_OPEN
) ||
3663 (conn
->type
== CONN_TYPE_EXIT
&& conn
->state
== EXIT_CONN_STATE_OPEN
) ||
3664 (conn
->type
== CONN_TYPE_CONTROL
&&
3665 conn
->state
== CONTROL_CONN_STATE_OPEN
))
3671 /** Return 1 if conn is in 'connecting' state, else return 0. */
3673 connection_state_is_connecting(connection_t
*conn
)
3677 if (conn
->marked_for_close
)
3682 return conn
->state
== OR_CONN_STATE_CONNECTING
;
3683 case CONN_TYPE_EXIT
:
3684 return conn
->state
== EXIT_CONN_STATE_CONNECTING
;
3686 return conn
->state
== DIR_CONN_STATE_CONNECTING
;
3692 /** Allocates a base64'ed authenticator for use in http or https
3693 * auth, based on the input string <b>authenticator</b>. Returns it
3694 * if success, else returns NULL. */
3696 alloc_http_authenticator(const char *authenticator
)
3698 /* an authenticator in Basic authentication
3699 * is just the string "username:password" */
3700 const size_t authenticator_length
= strlen(authenticator
);
3701 /* The base64_encode function needs a minimum buffer length
3703 const size_t base64_authenticator_length
= (authenticator_length
/48+1)*66;
3704 char *base64_authenticator
= tor_malloc(base64_authenticator_length
);
3705 if (base64_encode(base64_authenticator
, base64_authenticator_length
,
3706 authenticator
, authenticator_length
) < 0) {
3707 tor_free(base64_authenticator
); /* free and set to null */
3710 ssize_t len
= strlen(base64_authenticator
);
3712 /* remove all newline occurrences within the string */
3713 for (i
=0; i
< len
; ++i
) {
3714 if ('\n' != base64_authenticator
[i
]) {
3715 base64_authenticator
[j
] = base64_authenticator
[i
];
3719 base64_authenticator
[j
]='\0';
3721 return base64_authenticator
;
3724 /** Given a socket handle, check whether the local address (sockname) of the
3725 * socket is one that we've connected from before. If so, double-check
3726 * whether our address has changed and we need to generate keys. If we do,
3730 client_check_address_changed(tor_socket_t sock
)
3732 struct sockaddr_storage out_sockaddr
;
3733 socklen_t out_addr_len
= (socklen_t
) sizeof(out_sockaddr
);
3734 tor_addr_t out_addr
, iface_addr
;
3735 tor_addr_t
**last_interface_ip_ptr
;
3738 if (!outgoing_addrs
)
3739 outgoing_addrs
= smartlist_new();
3741 if (getsockname(sock
, (struct sockaddr
*)&out_sockaddr
, &out_addr_len
)<0) {
3742 int e
= tor_socket_errno(sock
);
3743 log_warn(LD_NET
, "getsockname() to check for address change failed: %s",
3744 tor_socket_strerror(e
));
3747 tor_addr_from_sockaddr(&out_addr
, (struct sockaddr
*)&out_sockaddr
, NULL
);
3748 family
= tor_addr_family(&out_addr
);
3750 if (family
== AF_INET
)
3751 last_interface_ip_ptr
= &last_interface_ipv4
;
3752 else if (family
== AF_INET6
)
3753 last_interface_ip_ptr
= &last_interface_ipv6
;
3757 if (! *last_interface_ip_ptr
) {
3758 tor_addr_t
*a
= tor_malloc_zero(sizeof(tor_addr_t
));
3759 if (get_interface_address6(LOG_INFO
, family
, a
)==0) {
3760 *last_interface_ip_ptr
= a
;
3766 /* If we've used this address previously, we're okay. */
3767 SMARTLIST_FOREACH(outgoing_addrs
, const tor_addr_t
*, a_ptr
,
3768 if (tor_addr_eq(a_ptr
, &out_addr
))
3772 /* Uh-oh. We haven't connected from this address before. Has the interface
3773 * address changed? */
3774 if (get_interface_address6(LOG_INFO
, family
, &iface_addr
)<0)
3777 if (tor_addr_eq(&iface_addr
, *last_interface_ip_ptr
)) {
3778 /* Nope, it hasn't changed. Add this address to the list. */
3779 smartlist_add(outgoing_addrs
, tor_memdup(&out_addr
, sizeof(tor_addr_t
)));
3781 /* The interface changed. We're a client, so we need to regenerate our
3782 * keys. First, reset the state. */
3783 log(LOG_NOTICE
, LD_NET
, "Our IP address has changed. Rotating keys...");
3784 tor_addr_copy(*last_interface_ip_ptr
, &iface_addr
);
3785 SMARTLIST_FOREACH(outgoing_addrs
, tor_addr_t
*, a_ptr
, tor_free(a_ptr
));
3786 smartlist_clear(outgoing_addrs
);
3787 smartlist_add(outgoing_addrs
, tor_memdup(&out_addr
, sizeof(tor_addr_t
)));
3788 /* Okay, now change our keys. */
3789 ip_address_changed(1);
3793 /** Some systems have limited system buffers for recv and xmit on
3794 * sockets allocated in a virtual server or similar environment. For a Tor
3795 * server this can produce the "Error creating network socket: No buffer
3796 * space available" error once all available TCP buffer space is consumed.
3797 * This method will attempt to constrain the buffers allocated for the socket
3798 * to the desired size to stay below system TCP buffer limits.
3801 set_constrained_socket_buffers(tor_socket_t sock
, int size
)
3803 void *sz
= (void*)&size
;
3804 socklen_t sz_sz
= (socklen_t
) sizeof(size
);
3805 if (setsockopt(sock
, SOL_SOCKET
, SO_SNDBUF
, sz
, sz_sz
) < 0) {
3806 int e
= tor_socket_errno(sock
);
3807 log_warn(LD_NET
, "setsockopt() to constrain send "
3808 "buffer to %d bytes failed: %s", size
, tor_socket_strerror(e
));
3810 if (setsockopt(sock
, SOL_SOCKET
, SO_RCVBUF
, sz
, sz_sz
) < 0) {
3811 int e
= tor_socket_errno(sock
);
3812 log_warn(LD_NET
, "setsockopt() to constrain recv "
3813 "buffer to %d bytes failed: %s", size
, tor_socket_strerror(e
));
3817 /** Process new bytes that have arrived on conn-\>inbuf.
3819 * This function just passes conn to the connection-specific
3820 * connection_*_process_inbuf() function. It also passes in
3821 * package_partial if wanted.
3824 connection_process_inbuf(connection_t
*conn
, int package_partial
)
3828 switch (conn
->type
) {
3830 return connection_or_process_inbuf(TO_OR_CONN(conn
));
3831 case CONN_TYPE_EXIT
:
3833 return connection_edge_process_inbuf(TO_EDGE_CONN(conn
),
3836 return connection_dir_process_inbuf(TO_DIR_CONN(conn
));
3837 case CONN_TYPE_CPUWORKER
:
3838 return connection_cpu_process_inbuf(conn
);
3839 case CONN_TYPE_CONTROL
:
3840 return connection_control_process_inbuf(TO_CONTROL_CONN(conn
));
3842 log_err(LD_BUG
,"got unexpected conn type %d.", conn
->type
);
3843 tor_fragile_assert();
3848 /** Called whenever we've written data on a connection. */
3850 connection_flushed_some(connection_t
*conn
)
3853 tor_assert(!conn
->in_flushed_some
);
3854 conn
->in_flushed_some
= 1;
3855 if (conn
->type
== CONN_TYPE_DIR
&&
3856 conn
->state
== DIR_CONN_STATE_SERVER_WRITING
) {
3857 r
= connection_dirserv_flushed_some(TO_DIR_CONN(conn
));
3858 } else if (conn
->type
== CONN_TYPE_OR
) {
3859 r
= connection_or_flushed_some(TO_OR_CONN(conn
));
3860 } else if (CONN_IS_EDGE(conn
)) {
3861 r
= connection_edge_flushed_some(TO_EDGE_CONN(conn
));
3863 conn
->in_flushed_some
= 0;
3867 /** We just finished flushing bytes from conn-\>outbuf, and there
3868 * are no more bytes remaining.
3870 * This function just passes conn to the connection-specific
3871 * connection_*_finished_flushing() function.
3874 connection_finished_flushing(connection_t
*conn
)
3878 /* If the connection is closed, don't try to do anything more here. */
3879 if (CONN_IS_CLOSED(conn
))
3882 // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
3884 IF_HAS_NO_BUFFEREVENT(conn
)
3885 connection_stop_writing(conn
);
3887 switch (conn
->type
) {
3889 return connection_or_finished_flushing(TO_OR_CONN(conn
));
3891 case CONN_TYPE_EXIT
:
3892 return connection_edge_finished_flushing(TO_EDGE_CONN(conn
));
3894 return connection_dir_finished_flushing(TO_DIR_CONN(conn
));
3895 case CONN_TYPE_CPUWORKER
:
3896 return connection_cpu_finished_flushing(conn
);
3897 case CONN_TYPE_CONTROL
:
3898 return connection_control_finished_flushing(TO_CONTROL_CONN(conn
));
3900 log_err(LD_BUG
,"got unexpected conn type %d.", conn
->type
);
3901 tor_fragile_assert();
3906 /** Called when our attempt to connect() to another server has just
3909 * This function just passes conn to the connection-specific
3910 * connection_*_finished_connecting() function.
3913 connection_finished_connecting(connection_t
*conn
)
3917 if (!server_mode(get_options())) {
3918 /* See whether getsockname() says our address changed. We need to do this
3919 * now that the connection has finished, because getsockname() on Windows
3920 * won't work until then. */
3921 client_check_address_changed(conn
->s
);
3927 return connection_or_finished_connecting(TO_OR_CONN(conn
));
3928 case CONN_TYPE_EXIT
:
3929 return connection_edge_finished_connecting(TO_EDGE_CONN(conn
));
3931 return connection_dir_finished_connecting(TO_DIR_CONN(conn
));
3933 log_err(LD_BUG
,"got unexpected conn type %d.", conn
->type
);
3934 tor_fragile_assert();
3939 /** Callback: invoked when a connection reaches an EOF event. */
3941 connection_reached_eof(connection_t
*conn
)
3943 switch (conn
->type
) {
3945 return connection_or_reached_eof(TO_OR_CONN(conn
));
3947 case CONN_TYPE_EXIT
:
3948 return connection_edge_reached_eof(TO_EDGE_CONN(conn
));
3950 return connection_dir_reached_eof(TO_DIR_CONN(conn
));
3951 case CONN_TYPE_CPUWORKER
:
3952 return connection_cpu_reached_eof(conn
);
3953 case CONN_TYPE_CONTROL
:
3954 return connection_control_reached_eof(TO_CONTROL_CONN(conn
));
3956 log_err(LD_BUG
,"got unexpected conn type %d.", conn
->type
);
3957 tor_fragile_assert();
3962 /** Log how many bytes are used by buffers of different kinds and sizes. */
3964 connection_dump_buffer_mem_stats(int severity
)
3966 uint64_t used_by_type
[_CONN_TYPE_MAX
+1];
3967 uint64_t alloc_by_type
[_CONN_TYPE_MAX
+1];
3968 int n_conns_by_type
[_CONN_TYPE_MAX
+1];
3969 uint64_t total_alloc
= 0;
3970 uint64_t total_used
= 0;
3972 smartlist_t
*conns
= get_connection_array();
3974 memset(used_by_type
, 0, sizeof(used_by_type
));
3975 memset(alloc_by_type
, 0, sizeof(alloc_by_type
));
3976 memset(n_conns_by_type
, 0, sizeof(n_conns_by_type
));
3978 SMARTLIST_FOREACH(conns
, connection_t
*, c
,
3981 ++n_conns_by_type
[tp
];
3983 used_by_type
[tp
] += buf_datalen(c
->inbuf
);
3984 alloc_by_type
[tp
] += buf_allocation(c
->inbuf
);
3987 used_by_type
[tp
] += buf_datalen(c
->outbuf
);
3988 alloc_by_type
[tp
] += buf_allocation(c
->outbuf
);
3991 for (i
=0; i
<= _CONN_TYPE_MAX
; ++i
) {
3992 total_used
+= used_by_type
[i
];
3993 total_alloc
+= alloc_by_type
[i
];
3996 log(severity
, LD_GENERAL
,
3997 "In buffers for %d connections: "U64_FORMAT
" used/"U64_FORMAT
" allocated",
3998 smartlist_len(conns
),
3999 U64_PRINTF_ARG(total_used
), U64_PRINTF_ARG(total_alloc
));
4000 for (i
=_CONN_TYPE_MIN
; i
<= _CONN_TYPE_MAX
; ++i
) {
4001 if (!n_conns_by_type
[i
])
4003 log(severity
, LD_GENERAL
,
4004 " For %d %s connections: "U64_FORMAT
" used/"U64_FORMAT
" allocated",
4005 n_conns_by_type
[i
], conn_type_to_string(i
),
4006 U64_PRINTF_ARG(used_by_type
[i
]), U64_PRINTF_ARG(alloc_by_type
[i
]));
4010 /** Verify that connection <b>conn</b> has all of its invariants
4011 * correct. Trigger an assert if anything is invalid.
4014 assert_connection_ok(connection_t
*conn
, time_t now
)
4016 (void) now
; /* XXXX unused. */
4018 tor_assert(conn
->type
>= _CONN_TYPE_MIN
);
4019 tor_assert(conn
->type
<= _CONN_TYPE_MAX
);
4021 #ifdef USE_BUFFEREVENTS
4023 tor_assert(conn
->read_event
== NULL
);
4024 tor_assert(conn
->write_event
== NULL
);
4025 tor_assert(conn
->inbuf
== NULL
);
4026 tor_assert(conn
->outbuf
== NULL
);
4030 switch (conn
->type
) {
4032 tor_assert(conn
->magic
== OR_CONNECTION_MAGIC
);
4035 tor_assert(conn
->magic
== ENTRY_CONNECTION_MAGIC
);
4037 case CONN_TYPE_EXIT
:
4038 tor_assert(conn
->magic
== EDGE_CONNECTION_MAGIC
);
4041 tor_assert(conn
->magic
== DIR_CONNECTION_MAGIC
);
4043 case CONN_TYPE_CONTROL
:
4044 tor_assert(conn
->magic
== CONTROL_CONNECTION_MAGIC
);
4046 CASE_ANY_LISTENER_TYPE
:
4047 tor_assert(conn
->magic
== LISTENER_CONNECTION_MAGIC
);
4050 tor_assert(conn
->magic
== BASE_CONNECTION_MAGIC
);
4054 if (conn
->linked_conn
) {
4055 tor_assert(conn
->linked_conn
->linked_conn
== conn
);
4056 tor_assert(conn
->linked
);
4059 tor_assert(!SOCKET_OK(conn
->s
));
4061 if (conn
->outbuf_flushlen
> 0) {
4062 /* With optimistic data, we may have queued data in
4063 * EXIT_CONN_STATE_RESOLVING while the conn is not yet marked to writing.
4065 tor_assert((conn
->type
== CONN_TYPE_EXIT
&&
4066 conn
->state
== EXIT_CONN_STATE_RESOLVING
) ||
4067 connection_is_writing(conn
) ||
4068 conn
->write_blocked_on_bw
||
4069 (CONN_IS_EDGE(conn
) &&
4070 TO_EDGE_CONN(conn
)->edge_blocked_on_circ
));
4073 if (conn
->hold_open_until_flushed
)
4074 tor_assert(conn
->marked_for_close
);
4076 /* XXXX check: read_blocked_on_bw, write_blocked_on_bw, s, conn_array_index,
4077 * marked_for_close. */
4081 assert_buf_ok(conn
->inbuf
);
4083 assert_buf_ok(conn
->outbuf
);
4085 if (conn
->type
== CONN_TYPE_OR
) {
4086 or_connection_t
*or_conn
= TO_OR_CONN(conn
);
4087 if (conn
->state
== OR_CONN_STATE_OPEN
) {
4088 /* tor_assert(conn->bandwidth > 0); */
4089 /* the above isn't necessarily true: if we just did a TLS
4090 * handshake but we didn't recognize the other peer, or it
4091 * gave a bad cert/etc, then we won't have assigned bandwidth,
4092 * yet it will be open. -RD
4094 // tor_assert(conn->read_bucket >= 0);
4096 // tor_assert(conn->addr && conn->port);
4097 tor_assert(conn
->address
);
4098 if (conn
->state
> OR_CONN_STATE_PROXY_HANDSHAKING
)
4099 tor_assert(or_conn
->tls
);
4102 if (CONN_IS_EDGE(conn
)) {
4103 /* XXX unchecked: package window, deliver window. */
4104 if (conn
->type
== CONN_TYPE_AP
) {
4105 entry_connection_t
*entry_conn
= TO_ENTRY_CONN(conn
);
4106 if (entry_conn
->chosen_exit_optional
|| entry_conn
->chosen_exit_retries
)
4107 tor_assert(entry_conn
->chosen_exit_name
);
4109 tor_assert(entry_conn
->socks_request
);
4110 if (conn
->state
== AP_CONN_STATE_OPEN
) {
4111 tor_assert(entry_conn
->socks_request
->has_finished
);
4112 if (!conn
->marked_for_close
) {
4113 tor_assert(ENTRY_TO_EDGE_CONN(entry_conn
)->cpath_layer
);
4114 assert_cpath_layer_ok(ENTRY_TO_EDGE_CONN(entry_conn
)->cpath_layer
);
4118 if (conn
->type
== CONN_TYPE_EXIT
) {
4119 tor_assert(conn
->purpose
== EXIT_PURPOSE_CONNECT
||
4120 conn
->purpose
== EXIT_PURPOSE_RESOLVE
);
4122 } else if (conn
->type
== CONN_TYPE_DIR
) {
4124 /* Purpose is only used for dir and exit types currently */
4125 tor_assert(!conn
->purpose
);
4130 CASE_ANY_LISTENER_TYPE
:
4131 tor_assert(conn
->state
== LISTENER_STATE_READY
);
4134 tor_assert(conn
->state
>= _OR_CONN_STATE_MIN
);
4135 tor_assert(conn
->state
<= _OR_CONN_STATE_MAX
);
4136 tor_assert(TO_OR_CONN(conn
)->n_circuits
>= 0);
4138 case CONN_TYPE_EXIT
:
4139 tor_assert(conn
->state
>= _EXIT_CONN_STATE_MIN
);
4140 tor_assert(conn
->state
<= _EXIT_CONN_STATE_MAX
);
4141 tor_assert(conn
->purpose
>= _EXIT_PURPOSE_MIN
);
4142 tor_assert(conn
->purpose
<= _EXIT_PURPOSE_MAX
);
4145 tor_assert(conn
->state
>= _AP_CONN_STATE_MIN
);
4146 tor_assert(conn
->state
<= _AP_CONN_STATE_MAX
);
4147 tor_assert(TO_ENTRY_CONN(conn
)->socks_request
);
4150 tor_assert(conn
->state
>= _DIR_CONN_STATE_MIN
);
4151 tor_assert(conn
->state
<= _DIR_CONN_STATE_MAX
);
4152 tor_assert(conn
->purpose
>= _DIR_PURPOSE_MIN
);
4153 tor_assert(conn
->purpose
<= _DIR_PURPOSE_MAX
);
4155 case CONN_TYPE_CPUWORKER
:
4156 tor_assert(conn
->state
>= _CPUWORKER_STATE_MIN
);
4157 tor_assert(conn
->state
<= _CPUWORKER_STATE_MAX
);
4159 case CONN_TYPE_CONTROL
:
4160 tor_assert(conn
->state
>= _CONTROL_CONN_STATE_MIN
);
4161 tor_assert(conn
->state
<= _CONTROL_CONN_STATE_MAX
);
4168 /** Fills <b>addr</b> and <b>port</b> with the details of the global
4169 * proxy server we are using.
4170 * <b>conn</b> contains the connection we are using the proxy for.
4172 * Return 0 on success, -1 on failure.
4175 get_proxy_addrport(tor_addr_t
*addr
, uint16_t *port
, int *proxy_type
,
4176 const connection_t
*conn
)
4178 const or_options_t
*options
= get_options();
4180 if (options
->HTTPSProxy
) {
4181 tor_addr_copy(addr
, &options
->HTTPSProxyAddr
);
4182 *port
= options
->HTTPSProxyPort
;
4183 *proxy_type
= PROXY_CONNECT
;
4185 } else if (options
->Socks4Proxy
) {
4186 tor_addr_copy(addr
, &options
->Socks4ProxyAddr
);
4187 *port
= options
->Socks4ProxyPort
;
4188 *proxy_type
= PROXY_SOCKS4
;
4190 } else if (options
->Socks5Proxy
) {
4191 tor_addr_copy(addr
, &options
->Socks5ProxyAddr
);
4192 *port
= options
->Socks5ProxyPort
;
4193 *proxy_type
= PROXY_SOCKS5
;
4195 } else if (options
->ClientTransportPlugin
||
4197 const transport_t
*transport
= NULL
;
4199 r
= find_transport_by_bridge_addrport(&conn
->addr
, conn
->port
, &transport
);
4202 if (transport
) { /* transport found */
4203 tor_addr_copy(addr
, &transport
->addr
);
4204 *port
= transport
->port
;
4205 *proxy_type
= transport
->socks_version
;
4210 *proxy_type
= PROXY_NONE
;
4214 /** Returns the global proxy type used by tor. */
4216 get_proxy_type(void)
4218 const or_options_t
*options
= get_options();
4220 if (options
->HTTPSProxy
)
4221 return PROXY_CONNECT
;
4222 else if (options
->Socks4Proxy
)
4223 return PROXY_SOCKS4
;
4224 else if (options
->Socks5Proxy
)
4225 return PROXY_SOCKS5
;
4226 else if (options
->ClientTransportPlugin
)
4227 return PROXY_PLUGGABLE
;
4232 /** Log a failed connection to a proxy server.
4233 * <b>conn</b> is the connection we use the proxy server for. */
4235 log_failed_proxy_connection(connection_t
*conn
)
4237 tor_addr_t proxy_addr
;
4238 uint16_t proxy_port
;
4241 if (get_proxy_addrport(&proxy_addr
, &proxy_port
, &proxy_type
, conn
) != 0)
4242 return; /* if we have no proxy set up, leave this function. */
4245 "The connection to the %s proxy server at %s:%u just failed. "
4246 "Make sure that the proxy server is up and running.",
4247 proxy_type_to_string(get_proxy_type()), fmt_addr(&proxy_addr
),
4251 /** Return string representation of <b>proxy_type</b>. */
4253 proxy_type_to_string(int proxy_type
)
4255 switch (proxy_type
) {
4256 case PROXY_CONNECT
: return "HTTP";
4257 case PROXY_SOCKS4
: return "SOCKS4";
4258 case PROXY_SOCKS5
: return "SOCKS5";
4259 case PROXY_PLUGGABLE
: return "pluggable transports SOCKS";
4260 case PROXY_NONE
: return "NULL";
4261 default: tor_assert(0);
4263 return NULL
; /*Unreached*/
4266 /** Call _connection_free() on every connection in our array, and release all
4267 * storage held by connection.c. This is used by cpuworkers and dnsworkers
4268 * when they fork, so they don't keep resources held open (especially
4271 * Don't do the checks in connection_free(), because they will
4275 connection_free_all(void)
4277 smartlist_t
*conns
= get_connection_array();
4279 /* We don't want to log any messages to controllers. */
4280 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
4281 if (conn
->type
== CONN_TYPE_CONTROL
)
4282 TO_CONTROL_CONN(conn
)->event_mask
= 0);
4284 control_update_global_event_mask();
4286 /* Unlink everything from the identity map. */
4287 connection_or_clear_identity_map();
4289 /* Clear out our list of broken connections */
4290 clear_broken_connection_map(0);
4292 SMARTLIST_FOREACH(conns
, connection_t
*, conn
, _connection_free(conn
));
4294 if (outgoing_addrs
) {
4295 SMARTLIST_FOREACH(outgoing_addrs
, tor_addr_t
*, addr
, tor_free(addr
));
4296 smartlist_free(outgoing_addrs
);
4297 outgoing_addrs
= NULL
;
4300 #ifdef USE_BUFFEREVENTS
4301 if (global_rate_limit
)
4302 bufferevent_rate_limit_group_free(global_rate_limit
);