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-2010, 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 "routerparse.h"
39 static connection_t
*connection_create_listener(
40 struct sockaddr
*listensockaddr
,
41 socklen_t listensocklen
, int type
,
43 static void connection_init(time_t now
, connection_t
*conn
, int type
,
45 static int connection_init_accepted_conn(connection_t
*conn
,
46 uint8_t listener_type
);
47 static int connection_handle_listener_read(connection_t
*conn
, int new_type
);
48 static int connection_bucket_should_increase(int bucket
,
49 or_connection_t
*conn
);
50 static int connection_finished_flushing(connection_t
*conn
);
51 static int connection_flushed_some(connection_t
*conn
);
52 static int connection_finished_connecting(connection_t
*conn
);
53 static int connection_reached_eof(connection_t
*conn
);
54 static int connection_read_to_buf(connection_t
*conn
, int *max_to_read
,
56 static int connection_process_inbuf(connection_t
*conn
, int package_partial
);
57 static void client_check_address_changed(int sock
);
58 static void set_constrained_socket_buffers(int sock
, int size
);
60 static const char *connection_proxy_state_to_string(int state
);
61 static int connection_read_https_proxy_response(connection_t
*conn
);
62 static void connection_send_socks5_connect(connection_t
*conn
);
64 /** The last IPv4 address that our network interface seemed to have been
65 * binding to, in host order. We use this to detect when our IP changes. */
66 static uint32_t last_interface_ip
= 0;
67 /** A list of uint32_ts for addresses we've used in outgoing connections.
68 * Used to detect IP address changes. */
69 static smartlist_t
*outgoing_addrs
= NULL
;
71 /**************************************************************/
74 * Return the human-readable name for the connection type <b>type</b>
77 conn_type_to_string(int type
)
81 case CONN_TYPE_OR_LISTENER
: return "OR listener";
82 case CONN_TYPE_OR
: return "OR";
83 case CONN_TYPE_EXIT
: return "Exit";
84 case CONN_TYPE_AP_LISTENER
: return "Socks listener";
85 case CONN_TYPE_AP_TRANS_LISTENER
:
86 return "Transparent pf/netfilter listener";
87 case CONN_TYPE_AP_NATD_LISTENER
: return "Transparent natd listener";
88 case CONN_TYPE_AP_DNS_LISTENER
: return "DNS listener";
89 case CONN_TYPE_AP
: return "Socks";
90 case CONN_TYPE_DIR_LISTENER
: return "Directory listener";
91 case CONN_TYPE_DIR
: return "Directory";
92 case CONN_TYPE_CPUWORKER
: return "CPU worker";
93 case CONN_TYPE_CONTROL_LISTENER
: return "Control listener";
94 case CONN_TYPE_CONTROL
: return "Control";
96 log_warn(LD_BUG
, "unknown connection type %d", type
);
97 tor_snprintf(buf
, sizeof(buf
), "unknown [%d]", type
);
103 * Return the human-readable name for the connection state <b>state</b>
104 * for the connection type <b>type</b>
107 conn_state_to_string(int type
, int state
)
111 case CONN_TYPE_OR_LISTENER
:
112 case CONN_TYPE_AP_LISTENER
:
113 case CONN_TYPE_AP_TRANS_LISTENER
:
114 case CONN_TYPE_AP_NATD_LISTENER
:
115 case CONN_TYPE_AP_DNS_LISTENER
:
116 case CONN_TYPE_DIR_LISTENER
:
117 case CONN_TYPE_CONTROL_LISTENER
:
118 if (state
== LISTENER_STATE_READY
)
123 case OR_CONN_STATE_CONNECTING
: return "connect()ing";
124 case OR_CONN_STATE_PROXY_HANDSHAKING
: return "handshaking (proxy)";
125 case OR_CONN_STATE_TLS_HANDSHAKING
: return "handshaking (TLS)";
126 case OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING
:
127 return "renegotiating (TLS)";
128 case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING
:
129 return "waiting for renegotiation (TLS)";
130 case OR_CONN_STATE_OR_HANDSHAKING
: return "handshaking (Tor)";
131 case OR_CONN_STATE_OPEN
: return "open";
136 case EXIT_CONN_STATE_RESOLVING
: return "waiting for dest info";
137 case EXIT_CONN_STATE_CONNECTING
: return "connecting";
138 case EXIT_CONN_STATE_OPEN
: return "open";
139 case EXIT_CONN_STATE_RESOLVEFAILED
: return "resolve failed";
144 case AP_CONN_STATE_SOCKS_WAIT
: return "waiting for socks info";
145 case AP_CONN_STATE_NATD_WAIT
: return "waiting for natd dest info";
146 case AP_CONN_STATE_RENDDESC_WAIT
: return "waiting for rendezvous desc";
147 case AP_CONN_STATE_CONTROLLER_WAIT
: return "waiting for controller";
148 case AP_CONN_STATE_CIRCUIT_WAIT
: return "waiting for circuit";
149 case AP_CONN_STATE_CONNECT_WAIT
: return "waiting for connect response";
150 case AP_CONN_STATE_RESOLVE_WAIT
: return "waiting for resolve response";
151 case AP_CONN_STATE_OPEN
: return "open";
156 case DIR_CONN_STATE_CONNECTING
: return "connecting";
157 case DIR_CONN_STATE_CLIENT_SENDING
: return "client sending";
158 case DIR_CONN_STATE_CLIENT_READING
: return "client reading";
159 case DIR_CONN_STATE_CLIENT_FINISHED
: return "client finished";
160 case DIR_CONN_STATE_SERVER_COMMAND_WAIT
: return "waiting for command";
161 case DIR_CONN_STATE_SERVER_WRITING
: return "writing";
164 case CONN_TYPE_CPUWORKER
:
166 case CPUWORKER_STATE_IDLE
: return "idle";
167 case CPUWORKER_STATE_BUSY_ONION
: return "busy with onion";
170 case CONN_TYPE_CONTROL
:
172 case CONTROL_CONN_STATE_OPEN
: return "open (protocol v1)";
173 case CONTROL_CONN_STATE_NEEDAUTH
:
174 return "waiting for authentication (protocol v1)";
179 log_warn(LD_BUG
, "unknown connection state %d (type %d)", state
, type
);
180 tor_snprintf(buf
, sizeof(buf
),
181 "unknown state [%d] on unknown [%s] connection",
182 state
, conn_type_to_string(type
));
186 /** Allocate and return a new dir_connection_t, initialized as by
187 * connection_init(). */
189 dir_connection_new(int socket_family
)
191 dir_connection_t
*dir_conn
= tor_malloc_zero(sizeof(dir_connection_t
));
192 connection_init(time(NULL
), TO_CONN(dir_conn
), CONN_TYPE_DIR
, socket_family
);
196 /** Allocate and return a new or_connection_t, initialized as by
197 * connection_init(). */
199 or_connection_new(int socket_family
)
201 or_connection_t
*or_conn
= tor_malloc_zero(sizeof(or_connection_t
));
202 time_t now
= time(NULL
);
203 connection_init(now
, TO_CONN(or_conn
), CONN_TYPE_OR
, socket_family
);
205 or_conn
->timestamp_last_added_nonpadding
= time(NULL
);
206 or_conn
->next_circ_id
= crypto_rand_int(1<<15);
208 or_conn
->active_circuit_pqueue
= smartlist_create();
209 or_conn
->active_circuit_pqueue_last_recalibrated
= cell_ewma_get_tick();
214 /** Allocate and return a new edge_connection_t, initialized as by
215 * connection_init(). */
217 edge_connection_new(int type
, int socket_family
)
219 edge_connection_t
*edge_conn
= tor_malloc_zero(sizeof(edge_connection_t
));
220 tor_assert(type
== CONN_TYPE_EXIT
|| type
== CONN_TYPE_AP
);
221 connection_init(time(NULL
), TO_CONN(edge_conn
), type
, socket_family
);
222 if (type
== CONN_TYPE_AP
)
223 edge_conn
->socks_request
= tor_malloc_zero(sizeof(socks_request_t
));
227 /** Allocate and return a new control_connection_t, initialized as by
228 * connection_init(). */
229 control_connection_t
*
230 control_connection_new(int socket_family
)
232 control_connection_t
*control_conn
=
233 tor_malloc_zero(sizeof(control_connection_t
));
234 connection_init(time(NULL
),
235 TO_CONN(control_conn
), CONN_TYPE_CONTROL
, socket_family
);
236 log_notice(LD_CONTROL
, "New control connection opened.");
240 /** Allocate, initialize, and return a new connection_t subtype of <b>type</b>
241 * to make or receive connections of address family <b>socket_family</b>. The
242 * type should be one of the CONN_TYPE_* constants. */
244 connection_new(int type
, int socket_family
)
248 return TO_CONN(or_connection_new(socket_family
));
252 return TO_CONN(edge_connection_new(type
, socket_family
));
255 return TO_CONN(dir_connection_new(socket_family
));
257 case CONN_TYPE_CONTROL
:
258 return TO_CONN(control_connection_new(socket_family
));
261 connection_t
*conn
= tor_malloc_zero(sizeof(connection_t
));
262 connection_init(time(NULL
), conn
, type
, socket_family
);
268 /** Initializes conn. (you must call connection_add() to link it into the main
271 * Set conn-\>type to <b>type</b>. Set conn-\>s and conn-\>conn_array_index to
272 * -1 to signify they are not yet assigned.
274 * If conn is not a listener type, allocate buffers for it. If it's
275 * an AP type, allocate space to store the socks_request.
277 * Assign a pseudorandom next_circ_id between 0 and 2**15.
279 * Initialize conn's timestamps to now.
282 connection_init(time_t now
, connection_t
*conn
, int type
, int socket_family
)
284 static uint64_t n_connections_allocated
= 1;
288 conn
->magic
= OR_CONNECTION_MAGIC
;
292 conn
->magic
= EDGE_CONNECTION_MAGIC
;
295 conn
->magic
= DIR_CONNECTION_MAGIC
;
297 case CONN_TYPE_CONTROL
:
298 conn
->magic
= CONTROL_CONNECTION_MAGIC
;
301 conn
->magic
= BASE_CONNECTION_MAGIC
;
305 conn
->s
= -1; /* give it a default of 'not used' */
306 conn
->conn_array_index
= -1; /* also default to 'not used' */
307 conn
->global_identifier
= n_connections_allocated
++;
310 conn
->socket_family
= socket_family
;
311 if (!connection_is_listener(conn
)) { /* listeners never use their buf */
312 conn
->inbuf
= buf_new();
313 conn
->outbuf
= buf_new();
316 conn
->timestamp_created
= now
;
317 conn
->timestamp_lastread
= now
;
318 conn
->timestamp_lastwritten
= now
;
321 /** Create a link between <b>conn_a</b> and <b>conn_b</b>. */
323 connection_link_connections(connection_t
*conn_a
, connection_t
*conn_b
)
325 tor_assert(conn_a
->s
< 0);
326 tor_assert(conn_b
->s
< 0);
330 conn_a
->linked_conn
= conn_b
;
331 conn_b
->linked_conn
= conn_a
;
334 /** Deallocate memory used by <b>conn</b>. Deallocate its buffers if
335 * necessary, close its socket if necessary, and mark the directory as dirty
336 * if <b>conn</b> is an OR or OP connection.
339 _connection_free(connection_t
*conn
)
346 switch (conn
->type
) {
348 tor_assert(conn
->magic
== OR_CONNECTION_MAGIC
);
349 mem
= TO_OR_CONN(conn
);
350 memlen
= sizeof(or_connection_t
);
354 tor_assert(conn
->magic
== EDGE_CONNECTION_MAGIC
);
355 mem
= TO_EDGE_CONN(conn
);
356 memlen
= sizeof(edge_connection_t
);
359 tor_assert(conn
->magic
== DIR_CONNECTION_MAGIC
);
360 mem
= TO_DIR_CONN(conn
);
361 memlen
= sizeof(dir_connection_t
);
363 case CONN_TYPE_CONTROL
:
364 tor_assert(conn
->magic
== CONTROL_CONNECTION_MAGIC
);
365 mem
= TO_CONTROL_CONN(conn
);
366 memlen
= sizeof(control_connection_t
);
369 tor_assert(conn
->magic
== BASE_CONNECTION_MAGIC
);
371 memlen
= sizeof(connection_t
);
376 log_info(LD_GENERAL
, "Freeing linked %s connection [%s] with %d "
377 "bytes on inbuf, %d on outbuf.",
378 conn_type_to_string(conn
->type
),
379 conn_state_to_string(conn
->type
, conn
->state
),
380 (int)buf_datalen(conn
->inbuf
), (int)buf_datalen(conn
->outbuf
));
383 if (!connection_is_listener(conn
)) {
384 buf_free(conn
->inbuf
);
385 buf_free(conn
->outbuf
);
387 if (conn
->socket_family
== AF_UNIX
) {
388 /* For now only control ports can be Unix domain sockets
389 * and listeners at the same time */
390 tor_assert(conn
->type
== CONN_TYPE_CONTROL_LISTENER
);
392 if (unlink(conn
->address
) < 0 && errno
!= ENOENT
) {
393 log_warn(LD_NET
, "Could not unlink %s: %s", conn
->address
,
399 tor_free(conn
->address
);
401 if (connection_speaks_cells(conn
)) {
402 or_connection_t
*or_conn
= TO_OR_CONN(conn
);
403 tor_tls_free(or_conn
->tls
);
405 or_handshake_state_free(or_conn
->handshake_state
);
406 or_conn
->handshake_state
= NULL
;
407 smartlist_free(or_conn
->active_circuit_pqueue
);
408 tor_free(or_conn
->nickname
);
410 if (CONN_IS_EDGE(conn
)) {
411 edge_connection_t
*edge_conn
= TO_EDGE_CONN(conn
);
412 tor_free(edge_conn
->chosen_exit_name
);
413 if (edge_conn
->socks_request
) {
414 memset(edge_conn
->socks_request
, 0xcc, sizeof(socks_request_t
));
415 tor_free(edge_conn
->socks_request
);
418 rend_data_free(edge_conn
->rend_data
);
420 if (conn
->type
== CONN_TYPE_CONTROL
) {
421 control_connection_t
*control_conn
= TO_CONTROL_CONN(conn
);
422 tor_free(control_conn
->incoming_cmd
);
425 tor_free(conn
->read_event
); /* Probably already freed by connection_free. */
426 tor_free(conn
->write_event
); /* Probably already freed by connection_free. */
428 if (conn
->type
== CONN_TYPE_DIR
) {
429 dir_connection_t
*dir_conn
= TO_DIR_CONN(conn
);
430 tor_free(dir_conn
->requested_resource
);
432 tor_zlib_free(dir_conn
->zlib_state
);
433 if (dir_conn
->fingerprint_stack
) {
434 SMARTLIST_FOREACH(dir_conn
->fingerprint_stack
, char *, cp
, tor_free(cp
));
435 smartlist_free(dir_conn
->fingerprint_stack
);
438 cached_dir_decref(dir_conn
->cached_dir
);
439 rend_data_free(dir_conn
->rend_data
);
443 log_debug(LD_NET
,"closing fd %d.",conn
->s
);
444 tor_close_socket(conn
->s
);
448 if (conn
->type
== CONN_TYPE_OR
&&
449 !tor_digest_is_zero(TO_OR_CONN(conn
)->identity_digest
)) {
450 log_warn(LD_BUG
, "called on OR conn with non-zeroed identity_digest");
451 connection_or_remove_from_identity_map(TO_OR_CONN(conn
));
454 memset(mem
, 0xCC, memlen
); /* poison memory */
458 /** Make sure <b>conn</b> isn't in any of the global conn lists; then free it.
461 connection_free(connection_t
*conn
)
465 tor_assert(!connection_is_on_closeable_list(conn
));
466 tor_assert(!connection_in_array(conn
));
467 if (conn
->linked_conn
) {
468 log_err(LD_BUG
, "Called with conn->linked_conn still set.");
469 tor_fragile_assert();
470 conn
->linked_conn
->linked_conn
= NULL
;
471 if (! conn
->linked_conn
->marked_for_close
&&
472 conn
->linked_conn
->reading_from_linked_conn
)
473 connection_start_reading(conn
->linked_conn
);
474 conn
->linked_conn
= NULL
;
476 if (connection_speaks_cells(conn
)) {
477 if (!tor_digest_is_zero(TO_OR_CONN(conn
)->identity_digest
)) {
478 connection_or_remove_from_identity_map(TO_OR_CONN(conn
));
481 if (conn
->type
== CONN_TYPE_CONTROL
) {
482 TO_CONTROL_CONN(conn
)->event_mask
= 0;
483 control_update_global_event_mask();
485 connection_unregister_events(conn
);
486 _connection_free(conn
);
489 /** Call _connection_free() on every connection in our array, and release all
490 * storage held by connection.c. This is used by cpuworkers and dnsworkers
491 * when they fork, so they don't keep resources held open (especially
494 * Don't do the checks in connection_free(), because they will
498 connection_free_all(void)
500 smartlist_t
*conns
= get_connection_array();
502 /* We don't want to log any messages to controllers. */
503 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
504 if (conn
->type
== CONN_TYPE_CONTROL
)
505 TO_CONTROL_CONN(conn
)->event_mask
= 0);
507 control_update_global_event_mask();
509 /* Unlink everything from the identity map. */
510 connection_or_clear_identity_map();
512 SMARTLIST_FOREACH(conns
, connection_t
*, conn
, _connection_free(conn
));
514 if (outgoing_addrs
) {
515 SMARTLIST_FOREACH(outgoing_addrs
, void*, addr
, tor_free(addr
));
516 smartlist_free(outgoing_addrs
);
517 outgoing_addrs
= NULL
;
521 /** Do any cleanup needed:
522 * - Directory conns that failed to fetch a rendezvous descriptor
523 * need to inform pending rendezvous streams.
524 * - OR conns need to call rep_hist_note_*() to record status.
525 * - AP conns need to send a socks reject if necessary.
526 * - Exit conns need to call connection_dns_remove() if necessary.
527 * - AP and Exit conns need to send an end cell if they can.
528 * - DNS conns need to fail any resolves that are pending on them.
529 * - OR and edge connections need to be unlinked from circuits.
532 connection_about_to_close_connection(connection_t
*conn
)
535 dir_connection_t
*dir_conn
;
536 or_connection_t
*or_conn
;
537 edge_connection_t
*edge_conn
;
538 time_t now
= time(NULL
);
540 tor_assert(conn
->marked_for_close
);
542 if (CONN_IS_EDGE(conn
)) {
543 edge_conn
= TO_EDGE_CONN(conn
);
544 if (!edge_conn
->edge_has_sent_end
) {
545 log_warn(LD_BUG
, "(Harmless.) Edge connection (marked at %s:%d) "
546 "hasn't sent end yet?",
547 conn
->marked_for_close_file
, conn
->marked_for_close
);
548 tor_fragile_assert();
552 switch (conn
->type
) {
554 dir_conn
= TO_DIR_CONN(conn
);
555 if (conn
->state
< DIR_CONN_STATE_CLIENT_FINISHED
) {
556 /* It's a directory connection and connecting or fetching
557 * failed: forget about this router, and maybe try again. */
558 connection_dir_request_failed(dir_conn
);
560 /* If we were trying to fetch a v2 rend desc and did not succeed,
561 * retry as needed. (If a fetch is successful, the connection state
562 * is changed to DIR_PURPOSE_HAS_FETCHED_RENDDESC to mark that
563 * refetching is unnecessary.) */
564 if (conn
->purpose
== DIR_PURPOSE_FETCH_RENDDESC_V2
&&
565 dir_conn
->rend_data
&&
566 strlen(dir_conn
->rend_data
->onion_address
) ==
567 REND_SERVICE_ID_LEN_BASE32
)
568 rend_client_refetch_v2_renddesc(dir_conn
->rend_data
);
571 or_conn
= TO_OR_CONN(conn
);
572 /* Remember why we're closing this connection. */
573 if (conn
->state
!= OR_CONN_STATE_OPEN
) {
574 /* Inform any pending (not attached) circs that they should
576 circuit_n_conn_done(TO_OR_CONN(conn
), 0);
577 /* now mark things down as needed */
578 if (connection_or_nonopen_was_started_here(or_conn
)) {
579 or_options_t
*options
= get_options();
580 rep_hist_note_connect_failed(or_conn
->identity_digest
, now
);
581 entry_guard_register_connect_status(or_conn
->identity_digest
,0,
582 !options
->HTTPSProxy
, now
);
583 if (conn
->state
>= OR_CONN_STATE_TLS_HANDSHAKING
) {
584 int reason
= tls_error_to_orconn_end_reason(or_conn
->tls_error
);
585 control_event_or_conn_status(or_conn
, OR_CONN_EVENT_FAILED
,
587 if (!authdir_mode_tests_reachability(options
))
588 control_event_bootstrap_problem(
589 orconn_end_reason_to_control_string(reason
), reason
);
592 } else if (conn
->hold_open_until_flushed
) {
593 /* We only set hold_open_until_flushed when we're intentionally
594 * closing a connection. */
595 rep_hist_note_disconnect(or_conn
->identity_digest
, now
);
596 control_event_or_conn_status(or_conn
, OR_CONN_EVENT_CLOSED
,
597 tls_error_to_orconn_end_reason(or_conn
->tls_error
));
598 } else if (!tor_digest_is_zero(or_conn
->identity_digest
)) {
599 rep_hist_note_connection_died(or_conn
->identity_digest
, now
);
600 control_event_or_conn_status(or_conn
, OR_CONN_EVENT_CLOSED
,
601 tls_error_to_orconn_end_reason(or_conn
->tls_error
));
603 /* Now close all the attached circuits on it. */
604 circuit_unlink_all_from_or_conn(TO_OR_CONN(conn
),
605 END_CIRC_REASON_OR_CONN_CLOSED
);
608 edge_conn
= TO_EDGE_CONN(conn
);
609 if (edge_conn
->socks_request
->has_finished
== 0) {
610 /* since conn gets removed right after this function finishes,
611 * there's no point trying to send back a reply at this point. */
612 log_warn(LD_BUG
,"Closing stream (marked at %s:%d) without sending"
613 " back a socks reply.",
614 conn
->marked_for_close_file
, conn
->marked_for_close
);
616 if (!edge_conn
->end_reason
) {
617 log_warn(LD_BUG
,"Closing stream (marked at %s:%d) without having"
619 conn
->marked_for_close_file
, conn
->marked_for_close
);
621 if (edge_conn
->dns_server_request
) {
622 log_warn(LD_BUG
,"Closing stream (marked at %s:%d) without having"
623 " replied to DNS request.",
624 conn
->marked_for_close_file
, conn
->marked_for_close
);
625 dnsserv_reject_request(edge_conn
);
627 control_event_stream_bandwidth(edge_conn
);
628 control_event_stream_status(edge_conn
, STREAM_EVENT_CLOSED
,
629 edge_conn
->end_reason
);
630 circ
= circuit_get_by_edge_conn(edge_conn
);
632 circuit_detach_stream(circ
, edge_conn
);
635 edge_conn
= TO_EDGE_CONN(conn
);
636 circ
= circuit_get_by_edge_conn(edge_conn
);
638 circuit_detach_stream(circ
, edge_conn
);
639 if (conn
->state
== EXIT_CONN_STATE_RESOLVING
) {
640 connection_dns_remove(edge_conn
);
646 /** Return true iff connection_close_immediate() has been called on this
648 #define CONN_IS_CLOSED(c) \
649 ((c)->linked ? ((c)->linked_conn_is_closed) : ((c)->s < 0))
651 /** Close the underlying socket for <b>conn</b>, so we don't try to
652 * flush it. Must be used in conjunction with (right before)
653 * connection_mark_for_close().
656 connection_close_immediate(connection_t
*conn
)
658 assert_connection_ok(conn
,0);
659 if (CONN_IS_CLOSED(conn
)) {
660 log_err(LD_BUG
,"Attempt to close already-closed connection.");
661 tor_fragile_assert();
664 if (conn
->outbuf_flushlen
) {
665 log_info(LD_NET
,"fd %d, type %s, state %s, %d bytes on outbuf.",
666 conn
->s
, conn_type_to_string(conn
->type
),
667 conn_state_to_string(conn
->type
, conn
->state
),
668 (int)conn
->outbuf_flushlen
);
671 connection_unregister_events(conn
);
674 tor_close_socket(conn
->s
);
677 conn
->linked_conn_is_closed
= 1;
678 if (!connection_is_listener(conn
)) {
679 buf_clear(conn
->outbuf
);
680 conn
->outbuf_flushlen
= 0;
684 /** Mark <b>conn</b> to be closed next time we loop through
685 * conn_close_if_marked() in main.c. */
687 _connection_mark_for_close(connection_t
*conn
, int line
, const char *file
)
689 assert_connection_ok(conn
,0);
691 tor_assert(line
< 1<<16); /* marked_for_close can only fit a uint16_t. */
694 if (conn
->marked_for_close
) {
695 log(LOG_WARN
,LD_BUG
,"Duplicate call to connection_mark_for_close at %s:%d"
696 " (first at %s:%d)", file
, line
, conn
->marked_for_close_file
,
697 conn
->marked_for_close
);
698 tor_fragile_assert();
702 conn
->marked_for_close
= line
;
703 conn
->marked_for_close_file
= file
;
704 add_connection_to_closeable_list(conn
);
706 /* in case we're going to be held-open-til-flushed, reset
707 * the number of seconds since last successful write, so
708 * we get our whole 15 seconds */
709 conn
->timestamp_lastwritten
= time(NULL
);
712 /** Find each connection that has hold_open_until_flushed set to
713 * 1 but hasn't written in the past 15 seconds, and set
714 * hold_open_until_flushed to 0. This means it will get cleaned
715 * up in the next loop through close_if_marked() in main.c.
718 connection_expire_held_open(void)
721 smartlist_t
*conns
= get_connection_array();
725 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
727 /* If we've been holding the connection open, but we haven't written
730 if (conn
->hold_open_until_flushed
) {
731 tor_assert(conn
->marked_for_close
);
732 if (now
- conn
->timestamp_lastwritten
>= 15) {
734 if (conn
->type
== CONN_TYPE_EXIT
||
735 (conn
->type
== CONN_TYPE_DIR
&&
736 conn
->purpose
== DIR_PURPOSE_SERVER
))
739 severity
= LOG_NOTICE
;
740 log_fn(severity
, LD_NET
,
741 "Giving up on marked_for_close conn that's been flushing "
742 "for 15s (fd %d, type %s, state %s).",
743 conn
->s
, conn_type_to_string(conn
->type
),
744 conn_state_to_string(conn
->type
, conn
->state
));
745 conn
->hold_open_until_flushed
= 0;
751 /** Create an AF_INET listenaddr struct.
752 * <b>listenaddress</b> provides the host and optionally the port information
753 * for the new structure. If no port is provided in <b>listenaddress</b> then
754 * <b>listenport</b> is used.
756 * If not NULL <b>readable_address</b> will contain a copy of the host part of
757 * <b>listenaddress</b>.
759 * The listenaddr struct has to be freed by the caller.
761 static struct sockaddr_in
*
762 create_inet_sockaddr(const char *listenaddress
, uint16_t listenport
,
763 char **readable_address
, socklen_t
*socklen_out
) {
764 struct sockaddr_in
*listenaddr
= NULL
;
766 uint16_t usePort
= 0;
768 if (parse_addr_port(LOG_WARN
,
769 listenaddress
, readable_address
, &addr
, &usePort
)<0) {
771 "Error parsing/resolving ListenAddress %s", listenaddress
);
775 usePort
= listenport
;
777 listenaddr
= tor_malloc_zero(sizeof(struct sockaddr_in
));
778 listenaddr
->sin_addr
.s_addr
= htonl(addr
);
779 listenaddr
->sin_family
= AF_INET
;
780 listenaddr
->sin_port
= htons((uint16_t) usePort
);
782 *socklen_out
= sizeof(struct sockaddr_in
);
787 tor_free(listenaddr
);
792 /** Create an AF_UNIX listenaddr struct.
793 * <b>listenaddress</b> provides the path to the Unix socket.
795 * Eventually <b>listenaddress</b> will also optionally contain user, group,
796 * and file permissions for the new socket. But not yet. XXX
797 * Also, since we do not create the socket here the information doesn't help
800 * If not NULL <b>readable_address</b> will contain a copy of the path part of
801 * <b>listenaddress</b>.
803 * The listenaddr struct has to be freed by the caller.
805 static struct sockaddr_un
*
806 create_unix_sockaddr(const char *listenaddress
, char **readable_address
,
809 struct sockaddr_un
*sockaddr
= NULL
;
811 sockaddr
= tor_malloc_zero(sizeof(struct sockaddr_un
));
812 sockaddr
->sun_family
= AF_UNIX
;
813 strncpy(sockaddr
->sun_path
, listenaddress
, sizeof(sockaddr
->sun_path
));
815 if (readable_address
)
816 *readable_address
= tor_strdup(listenaddress
);
818 *len_out
= sizeof(struct sockaddr_un
);
822 static struct sockaddr
*
823 create_unix_sockaddr(const char *listenaddress
, char **readable_address
,
827 (void)readable_address
;
828 log_fn(LOG_ERR
, LD_BUG
,
829 "Unix domain sockets not supported, yet we tried to create one.");
833 #endif /* HAVE_SYS_UN_H */
835 /** Warn that an accept or a connect has failed because we're running up
836 * against our ulimit. Rate-limit these warnings so that we don't spam
839 warn_too_many_conns(void)
841 #define WARN_TOO_MANY_CONNS_INTERVAL (6*60*60)
842 static ratelim_t last_warned
= RATELIM_INIT(WARN_TOO_MANY_CONNS_INTERVAL
);
844 if ((m
= rate_limit_log(&last_warned
, approx_time()))) {
845 int n_conns
= get_n_open_sockets();
846 log_warn(LD_NET
,"Failing because we have %d connections already. Please "
847 "raise your ulimit -n.%s", n_conns
, m
);
849 control_event_general_status(LOG_WARN
, "TOO_MANY_CONNECTIONS CURRENT=%d",
854 /** Bind a new non-blocking socket listening to the socket described
855 * by <b>listensockaddr</b>.
857 * <b>address</b> is only used for logging purposes and to add the information
860 static connection_t
*
861 connection_create_listener(struct sockaddr
*listensockaddr
, socklen_t socklen
,
862 int type
, char* address
)
865 int s
; /* the socket we're going to make */
866 uint16_t usePort
= 0;
867 int start_reading
= 0;
869 if (get_n_open_sockets() >= get_options()->_ConnLimit
-1) {
870 warn_too_many_conns();
874 if (listensockaddr
->sa_family
== AF_INET
) {
875 int is_tcp
= (type
!= CONN_TYPE_AP_DNS_LISTENER
);
882 usePort
= ntohs( (uint16_t)
883 ((struct sockaddr_in
*)listensockaddr
)->sin_port
);
885 log_notice(LD_NET
, "Opening %s on %s:%d",
886 conn_type_to_string(type
), address
, usePort
);
888 s
= tor_open_socket(PF_INET
,
889 is_tcp
? SOCK_STREAM
: SOCK_DGRAM
,
890 is_tcp
? IPPROTO_TCP
: IPPROTO_UDP
);
892 log_warn(LD_NET
,"Socket creation failed.");
897 /* REUSEADDR on normal places means you can rebind to the port
898 * right after somebody else has let it go. But REUSEADDR on win32
899 * means you can bind to the port _even when somebody else
900 * already has it bound_. So, don't do that on Win32. */
901 setsockopt(s
, SOL_SOCKET
, SO_REUSEADDR
, (void*) &one
,
902 (socklen_t
)sizeof(one
));
905 if (bind(s
,listensockaddr
,socklen
) < 0) {
906 const char *helpfulhint
= "";
907 int e
= tor_socket_errno(s
);
908 if (ERRNO_IS_EADDRINUSE(e
))
909 helpfulhint
= ". Is Tor already running?";
910 log_warn(LD_NET
, "Could not bind to %s:%u: %s%s", address
, usePort
,
911 tor_socket_strerror(e
), helpfulhint
);
917 if (listen(s
,SOMAXCONN
) < 0) {
918 log_warn(LD_NET
, "Could not listen on %s:%u: %s", address
, usePort
,
919 tor_socket_strerror(tor_socket_errno(s
)));
925 } else if (listensockaddr
->sa_family
== AF_UNIX
) {
928 /* For now only control ports can be Unix domain sockets
929 * and listeners at the same time */
930 tor_assert(type
== CONN_TYPE_CONTROL_LISTENER
);
932 log_notice(LD_NET
, "Opening %s on %s",
933 conn_type_to_string(type
), address
);
935 if (unlink(address
) < 0 && errno
!= ENOENT
) {
936 log_warn(LD_NET
, "Could not unlink %s: %s", address
,
940 s
= tor_open_socket(AF_UNIX
, SOCK_STREAM
, 0);
942 log_warn(LD_NET
,"Socket creation failed: %s.", strerror(errno
));
946 if (bind(s
, listensockaddr
, (socklen_t
)sizeof(struct sockaddr_un
)) == -1) {
947 log_warn(LD_NET
,"Bind to %s failed: %s.", address
,
948 tor_socket_strerror(tor_socket_errno(s
)));
952 if (listen(s
,SOMAXCONN
) < 0) {
953 log_warn(LD_NET
, "Could not listen on %s: %s", address
,
954 tor_socket_strerror(tor_socket_errno(s
)));
958 #endif /* HAVE_SYS_UN_H */
960 log_err(LD_BUG
,"Got unexpected address family %d.",
961 listensockaddr
->sa_family
);
965 set_socket_nonblocking(s
);
967 conn
= connection_new(type
, listensockaddr
->sa_family
);
968 conn
->socket_family
= listensockaddr
->sa_family
;
970 conn
->address
= tor_strdup(address
);
971 conn
->port
= usePort
;
973 if (connection_add(conn
) < 0) { /* no space, forget it */
974 log_warn(LD_NET
,"connection_add for listener failed. Giving up.");
975 connection_free(conn
);
979 log_debug(LD_NET
,"%s listening on port %u.",
980 conn_type_to_string(type
), usePort
);
982 conn
->state
= LISTENER_STATE_READY
;
984 connection_start_reading(conn
);
986 tor_assert(type
== CONN_TYPE_AP_DNS_LISTENER
);
987 dnsserv_configure_listener(conn
);
996 /** Do basic sanity checking on a newly received socket. Return 0
997 * if it looks ok, else return -1. */
999 check_sockaddr(struct sockaddr
*sa
, int len
, int level
)
1003 if (sa
->sa_family
== AF_INET
) {
1004 struct sockaddr_in
*sin
=(struct sockaddr_in
*)sa
;
1005 if (len
!= sizeof(struct sockaddr_in
)) {
1006 log_fn(level
, LD_NET
, "Length of address not as expected: %d vs %d",
1007 len
,(int)sizeof(struct sockaddr_in
));
1010 if (sin
->sin_addr
.s_addr
== 0 || sin
->sin_port
== 0) {
1011 log_fn(level
, LD_NET
,
1012 "Address for new connection has address/port equal to zero.");
1015 } else if (sa
->sa_family
== AF_INET6
) {
1016 struct sockaddr_in6
*sin6
=(struct sockaddr_in6
*)sa
;
1017 if (len
!= sizeof(struct sockaddr_in6
)) {
1018 log_fn(level
, LD_NET
, "Length of address not as expected: %d vs %d",
1019 len
,(int)sizeof(struct sockaddr_in6
));
1022 if (tor_mem_is_zero((void*)sin6
->sin6_addr
.s6_addr
, 16) ||
1023 sin6
->sin6_port
== 0) {
1024 log_fn(level
, LD_NET
,
1025 "Address for new connection has address/port equal to zero.");
1034 /** Check whether the socket family from an accepted socket <b>got</b> is the
1035 * same as the one that <b>listener</b> is waiting for. If it isn't, log
1036 * a useful message and return -1. Else return 0.
1038 * This is annoying, but can apparently happen on some Darwins. */
1040 check_sockaddr_family_match(sa_family_t got
, connection_t
*listener
)
1042 if (got
!= listener
->socket_family
) {
1043 log_info(LD_BUG
, "A listener connection returned a socket with a "
1044 "mismatched family. %s for addr_family %d gave us a socket "
1045 "with address family %d. Dropping.",
1046 conn_type_to_string(listener
->type
),
1047 (int)listener
->socket_family
,
1054 /** The listener connection <b>conn</b> told poll() it wanted to read.
1055 * Call accept() on conn-\>s, and add the new connection if necessary.
1058 connection_handle_listener_read(connection_t
*conn
, int new_type
)
1060 int news
; /* the new socket */
1061 connection_t
*newconn
;
1062 /* information about the remote peer when connecting to other routers */
1064 struct sockaddr
*remote
= (struct sockaddr
*)addrbuf
;
1065 /* length of the remote address. Must be whatever accept() needs. */
1066 socklen_t remotelen
= (socklen_t
)sizeof(addrbuf
);
1067 or_options_t
*options
= get_options();
1069 tor_assert((size_t)remotelen
>= sizeof(struct sockaddr_in
));
1070 memset(addrbuf
, 0, sizeof(addrbuf
));
1072 news
= tor_accept_socket(conn
->s
,remote
,&remotelen
);
1073 if (news
< 0) { /* accept() error */
1074 int e
= tor_socket_errno(conn
->s
);
1075 if (ERRNO_IS_ACCEPT_EAGAIN(e
)) {
1076 return 0; /* he hung up before we could accept(). that's fine. */
1077 } else if (ERRNO_IS_ACCEPT_RESOURCE_LIMIT(e
)) {
1078 warn_too_many_conns();
1081 /* else there was a real error. */
1082 log_warn(LD_NET
,"accept() failed: %s. Closing listener.",
1083 tor_socket_strerror(e
));
1084 connection_mark_for_close(conn
);
1088 "Connection accepted on socket %d (child of fd %d).",
1091 set_socket_nonblocking(news
);
1093 if (options
->ConstrainedSockets
)
1094 set_constrained_socket_buffers(news
, (int)options
->ConstrainedSockSize
);
1096 if (check_sockaddr_family_match(remote
->sa_family
, conn
) < 0) {
1097 tor_close_socket(news
);
1101 if (conn
->socket_family
== AF_INET
|| conn
->socket_family
== AF_INET6
) {
1104 if (check_sockaddr(remote
, remotelen
, LOG_INFO
)<0) {
1106 "accept() returned a strange address; trying getsockname().");
1107 remotelen
=sizeof(addrbuf
);
1108 memset(addrbuf
, 0, sizeof(addrbuf
));
1109 if (getsockname(news
, remote
, &remotelen
)<0) {
1110 int e
= tor_socket_errno(news
);
1111 log_warn(LD_NET
, "getsockname() for new connection failed: %s",
1112 tor_socket_strerror(e
));
1114 if (check_sockaddr((struct sockaddr
*)addrbuf
, remotelen
,
1116 log_warn(LD_NET
,"Something's wrong with this conn. Closing it.");
1117 tor_close_socket(news
);
1123 if (check_sockaddr_family_match(remote
->sa_family
, conn
) < 0) {
1124 tor_close_socket(news
);
1128 tor_addr_from_sockaddr(&addr
, remote
, &port
);
1130 /* process entrance policies here, before we even create the connection */
1131 if (new_type
== CONN_TYPE_AP
) {
1132 /* check sockspolicy to see if we should accept it */
1133 if (socks_policy_permits_address(&addr
) == 0) {
1135 "Denying socks connection from untrusted address %s.",
1137 tor_close_socket(news
);
1141 if (new_type
== CONN_TYPE_DIR
) {
1142 /* check dirpolicy to see if we should accept it */
1143 if (dir_policy_permits_address(&addr
) == 0) {
1144 log_notice(LD_DIRSERV
,"Denying dir connection from address %s.",
1146 tor_close_socket(news
);
1151 newconn
= connection_new(new_type
, conn
->socket_family
);
1154 /* remember the remote address */
1155 tor_addr_copy(&newconn
->addr
, &addr
);
1156 newconn
->port
= port
;
1157 newconn
->address
= tor_dup_addr(&addr
);
1159 } else if (conn
->socket_family
== AF_UNIX
) {
1160 /* For now only control ports can be Unix domain sockets
1161 * and listeners at the same time */
1162 tor_assert(conn
->type
== CONN_TYPE_CONTROL_LISTENER
);
1164 newconn
= connection_new(new_type
, conn
->socket_family
);
1167 /* remember the remote address -- do we have anything sane to put here? */
1168 tor_addr_make_unspec(&newconn
->addr
);
1170 newconn
->address
= tor_strdup(conn
->address
);
1175 if (connection_add(newconn
) < 0) { /* no space, forget it */
1176 connection_free(newconn
);
1177 return 0; /* no need to tear down the parent */
1180 if (connection_init_accepted_conn(newconn
, conn
->type
) < 0) {
1181 connection_mark_for_close(newconn
);
1187 /** Initialize states for newly accepted connection <b>conn</b>.
1188 * If conn is an OR, start the TLS handshake.
1189 * If conn is a transparent AP, get its original destination
1190 * and place it in circuit_wait.
1193 connection_init_accepted_conn(connection_t
*conn
, uint8_t listener_type
)
1195 connection_start_reading(conn
);
1197 switch (conn
->type
) {
1199 control_event_or_conn_status(TO_OR_CONN(conn
), OR_CONN_EVENT_NEW
, 0);
1200 return connection_tls_start_handshake(TO_OR_CONN(conn
), 1);
1202 switch (listener_type
) {
1203 case CONN_TYPE_AP_LISTENER
:
1204 conn
->state
= AP_CONN_STATE_SOCKS_WAIT
;
1206 case CONN_TYPE_AP_TRANS_LISTENER
:
1207 conn
->state
= AP_CONN_STATE_CIRCUIT_WAIT
;
1208 return connection_ap_process_transparent(TO_EDGE_CONN(conn
));
1209 case CONN_TYPE_AP_NATD_LISTENER
:
1210 conn
->state
= AP_CONN_STATE_NATD_WAIT
;
1215 conn
->purpose
= DIR_PURPOSE_SERVER
;
1216 conn
->state
= DIR_CONN_STATE_SERVER_COMMAND_WAIT
;
1218 case CONN_TYPE_CONTROL
:
1219 conn
->state
= CONTROL_CONN_STATE_NEEDAUTH
;
1225 /** Take conn, make a nonblocking socket; try to connect to
1226 * addr:port (they arrive in *host order*). If fail, return -1 and if
1227 * applicable put your best guess about errno into *<b>socket_error</b>.
1228 * Else assign s to conn-\>s: if connected return 1, if EAGAIN return 0.
1230 * address is used to make the logs useful.
1232 * On success, add conn to the list of polled connections.
1235 connection_connect(connection_t
*conn
, const char *address
,
1236 const tor_addr_t
*addr
, uint16_t port
, int *socket_error
)
1238 int s
, inprogress
= 0;
1240 struct sockaddr
*dest_addr
= (struct sockaddr
*) addrbuf
;
1241 socklen_t dest_addr_len
;
1242 or_options_t
*options
= get_options();
1243 int protocol_family
;
1245 if (get_n_open_sockets() >= get_options()->_ConnLimit
-1) {
1246 warn_too_many_conns();
1250 if (tor_addr_family(addr
) == AF_INET6
)
1251 protocol_family
= PF_INET6
;
1253 protocol_family
= PF_INET
;
1255 s
= tor_open_socket(protocol_family
,SOCK_STREAM
,IPPROTO_TCP
);
1257 *socket_error
= tor_socket_errno(-1);
1258 log_warn(LD_NET
,"Error creating network socket: %s",
1259 tor_socket_strerror(*socket_error
));
1263 if (options
->OutboundBindAddress
&& !tor_addr_is_loopback(addr
)) {
1264 struct sockaddr_in ext_addr
;
1266 memset(&ext_addr
, 0, sizeof(ext_addr
));
1267 ext_addr
.sin_family
= AF_INET
;
1268 ext_addr
.sin_port
= 0;
1269 if (!tor_inet_aton(options
->OutboundBindAddress
, &ext_addr
.sin_addr
)) {
1270 log_warn(LD_CONFIG
,"Outbound bind address '%s' didn't parse. Ignoring.",
1271 options
->OutboundBindAddress
);
1273 if (bind(s
, (struct sockaddr
*)&ext_addr
,
1274 (socklen_t
)sizeof(ext_addr
)) < 0) {
1275 *socket_error
= tor_socket_errno(s
);
1276 log_warn(LD_NET
,"Error binding network socket: %s",
1277 tor_socket_strerror(*socket_error
));
1278 tor_close_socket(s
);
1284 set_socket_nonblocking(s
);
1286 if (options
->ConstrainedSockets
)
1287 set_constrained_socket_buffers(s
, (int)options
->ConstrainedSockSize
);
1289 memset(addrbuf
,0,sizeof(addrbuf
));
1290 dest_addr
= (struct sockaddr
*) addrbuf
;
1291 dest_addr_len
= tor_addr_to_sockaddr(addr
, port
, dest_addr
, sizeof(addrbuf
));
1292 tor_assert(dest_addr_len
> 0);
1294 log_debug(LD_NET
, "Connecting to %s:%u.",
1295 escaped_safe_str_client(address
), port
);
1297 if (connect(s
, dest_addr
, dest_addr_len
) < 0) {
1298 int e
= tor_socket_errno(s
);
1299 if (!ERRNO_IS_CONN_EINPROGRESS(e
)) {
1300 /* yuck. kill it. */
1303 "connect() to %s:%u failed: %s",
1304 escaped_safe_str_client(address
),
1305 port
, tor_socket_strerror(e
));
1306 tor_close_socket(s
);
1313 if (!server_mode(options
))
1314 client_check_address_changed(s
);
1316 /* it succeeded. we're connected. */
1317 log_fn(inprogress
?LOG_DEBUG
:LOG_INFO
, LD_NET
,
1318 "Connection to %s:%u %s (sock %d).",
1319 escaped_safe_str_client(address
),
1320 port
, inprogress
?"in progress":"established", s
);
1322 if (connection_add(conn
) < 0) /* no space, forget it */
1324 return inprogress
? 0 : 1;
1327 /** Convert state number to string representation for logging purposes.
1330 connection_proxy_state_to_string(int state
)
1332 static const char *unknown
= "???";
1333 static const char *states
[] = {
1335 "PROXY_HTTPS_WANT_CONNECT_OK",
1336 "PROXY_SOCKS4_WANT_CONNECT_OK",
1337 "PROXY_SOCKS5_WANT_AUTH_METHOD_NONE",
1338 "PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929",
1339 "PROXY_SOCKS5_WANT_AUTH_RFC1929_OK",
1340 "PROXY_SOCKS5_WANT_CONNECT_OK",
1344 if (state
< PROXY_NONE
|| state
> PROXY_CONNECTED
)
1347 return states
[state
];
1350 /** Write a proxy request of <b>type</b> (socks4, socks5, https) to conn
1351 * for conn->addr:conn->port, authenticating with the auth details given
1352 * in the configuration (if available). SOCKS 5 and HTTP CONNECT proxies
1353 * support authentication.
1355 * Returns -1 if conn->addr is incompatible with the proxy protocol, and
1358 * Use connection_read_proxy_handshake() to complete the handshake.
1361 connection_proxy_connect(connection_t
*conn
, int type
)
1363 or_options_t
*options
;
1367 options
= get_options();
1370 case PROXY_CONNECT
: {
1372 char *base64_authenticator
=NULL
;
1373 const char *authenticator
= options
->HTTPSProxyAuthenticator
;
1375 /* Send HTTP CONNECT and authentication (if available) in
1378 if (authenticator
) {
1379 base64_authenticator
= alloc_http_authenticator(authenticator
);
1380 if (!base64_authenticator
)
1381 log_warn(LD_OR
, "Encoding https authenticator failed");
1384 if (base64_authenticator
) {
1385 tor_snprintf(buf
, sizeof(buf
), "CONNECT %s:%d HTTP/1.1\r\n"
1386 "Proxy-Authorization: Basic %s\r\n\r\n",
1387 fmt_addr(&conn
->addr
),
1388 conn
->port
, base64_authenticator
);
1389 tor_free(base64_authenticator
);
1391 tor_snprintf(buf
, sizeof(buf
), "CONNECT %s:%d HTTP/1.0\r\n\r\n",
1392 fmt_addr(&conn
->addr
), conn
->port
);
1395 connection_write_to_buf(buf
, strlen(buf
), conn
);
1396 conn
->proxy_state
= PROXY_HTTPS_WANT_CONNECT_OK
;
1400 case PROXY_SOCKS4
: {
1401 unsigned char buf
[9];
1405 /* Send a SOCKS4 connect request with empty user id */
1407 if (tor_addr_family(&conn
->addr
) != AF_INET
) {
1408 log_warn(LD_NET
, "SOCKS4 client is incompatible with IPv6");
1412 ip4addr
= tor_addr_to_ipv4n(&conn
->addr
);
1413 portn
= htons(conn
->port
);
1415 buf
[0] = 4; /* version */
1416 buf
[1] = SOCKS_COMMAND_CONNECT
; /* command */
1417 memcpy(buf
+ 2, &portn
, 2); /* port */
1418 memcpy(buf
+ 4, &ip4addr
, 4); /* addr */
1419 buf
[8] = 0; /* userid (empty) */
1421 connection_write_to_buf((char *)buf
, sizeof(buf
), conn
);
1422 conn
->proxy_state
= PROXY_SOCKS4_WANT_CONNECT_OK
;
1426 case PROXY_SOCKS5
: {
1427 unsigned char buf
[4]; /* fields: vers, num methods, method list */
1429 /* Send a SOCKS5 greeting (connect request must wait) */
1431 buf
[0] = 5; /* version */
1433 /* number of auth methods */
1434 if (options
->Socks5ProxyUsername
) {
1436 buf
[2] = 0x00; /* no authentication */
1437 buf
[3] = 0x02; /* rfc1929 Username/Passwd auth */
1438 conn
->proxy_state
= PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929
;
1441 buf
[2] = 0x00; /* no authentication */
1442 conn
->proxy_state
= PROXY_SOCKS5_WANT_AUTH_METHOD_NONE
;
1445 connection_write_to_buf((char *)buf
, 2 + buf
[1], conn
);
1450 log_err(LD_BUG
, "Invalid proxy protocol, %d", type
);
1451 tor_fragile_assert();
1455 log_debug(LD_NET
, "set state %s",
1456 connection_proxy_state_to_string(conn
->proxy_state
));
1461 /** Read conn's inbuf. If the http response from the proxy is all
1462 * here, make sure it's good news, then return 1. If it's bad news,
1463 * return -1. Else return 0 and hope for better luck next time.
1466 connection_read_https_proxy_response(connection_t
*conn
)
1473 switch (fetch_from_buf_http(conn
->inbuf
,
1474 &headers
, MAX_HEADERS_SIZE
,
1475 NULL
, NULL
, 10000, 0)) {
1476 case -1: /* overflow */
1477 log_warn(LD_PROTOCOL
,
1478 "Your https proxy sent back an oversized response. Closing.");
1481 log_info(LD_NET
,"https proxy response not all here yet. Waiting.");
1483 /* case 1, fall through */
1486 if (parse_http_response(headers
, &status_code
, &date_header
,
1487 NULL
, &reason
) < 0) {
1489 "Unparseable headers from proxy (connecting to '%s'). Closing.",
1494 if (!reason
) reason
= tor_strdup("[no reason given]");
1496 if (status_code
== 200) {
1498 "HTTPS connect to '%s' successful! (200 %s) Starting TLS.",
1499 conn
->address
, escaped(reason
));
1503 /* else, bad news on the status code */
1505 "The https proxy sent back an unexpected status code %d (%s). "
1507 status_code
, escaped(reason
));
1512 /** Send SOCKS5 CONNECT command to <b>conn</b>, copying <b>conn->addr</b>
1513 * and <b>conn->port</b> into the request.
1516 connection_send_socks5_connect(connection_t
*conn
)
1518 unsigned char buf
[1024];
1520 uint16_t port
= htons(conn
->port
);
1522 buf
[0] = 5; /* version */
1523 buf
[1] = SOCKS_COMMAND_CONNECT
; /* command */
1524 buf
[2] = 0; /* reserved */
1526 if (tor_addr_family(&conn
->addr
) == AF_INET
) {
1527 uint32_t addr
= tor_addr_to_ipv4n(&conn
->addr
);
1531 memcpy(buf
+ 4, &addr
, 4);
1532 memcpy(buf
+ 8, &port
, 2);
1533 } else { /* AF_INET6 */
1536 memcpy(buf
+ 4, tor_addr_to_in6(&conn
->addr
), 16);
1537 memcpy(buf
+ 20, &port
, 2);
1540 connection_write_to_buf((char *)buf
, reqsize
, conn
);
1542 conn
->proxy_state
= PROXY_SOCKS5_WANT_CONNECT_OK
;
1545 /** Call this from connection_*_process_inbuf() to advance the proxy
1548 * No matter what proxy protocol is used, if this function returns 1, the
1549 * handshake is complete, and the data remaining on inbuf may contain the
1550 * start of the communication with the requested server.
1552 * Returns 0 if the current buffer contains an incomplete response, and -1
1556 connection_read_proxy_handshake(connection_t
*conn
)
1559 char *reason
= NULL
;
1561 log_debug(LD_NET
, "enter state %s",
1562 connection_proxy_state_to_string(conn
->proxy_state
));
1564 switch (conn
->proxy_state
) {
1565 case PROXY_HTTPS_WANT_CONNECT_OK
:
1566 ret
= connection_read_https_proxy_response(conn
);
1568 conn
->proxy_state
= PROXY_CONNECTED
;
1571 case PROXY_SOCKS4_WANT_CONNECT_OK
:
1572 ret
= fetch_from_buf_socks_client(conn
->inbuf
,
1576 conn
->proxy_state
= PROXY_CONNECTED
;
1579 case PROXY_SOCKS5_WANT_AUTH_METHOD_NONE
:
1580 ret
= fetch_from_buf_socks_client(conn
->inbuf
,
1583 /* no auth needed, do connect */
1585 connection_send_socks5_connect(conn
);
1590 case PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929
:
1591 ret
= fetch_from_buf_socks_client(conn
->inbuf
,
1595 /* send auth if needed, otherwise do connect */
1597 connection_send_socks5_connect(conn
);
1599 } else if (ret
== 2) {
1600 unsigned char buf
[1024];
1601 size_t reqsize
, usize
, psize
;
1602 const char *user
, *pass
;
1604 user
= get_options()->Socks5ProxyUsername
;
1605 pass
= get_options()->Socks5ProxyPassword
;
1606 tor_assert(user
&& pass
);
1608 /* XXX len of user and pass must be <= 255 !!! */
1609 usize
= strlen(user
);
1610 psize
= strlen(pass
);
1611 tor_assert(usize
<= 255 && psize
<= 255);
1612 reqsize
= 3 + usize
+ psize
;
1614 buf
[0] = 1; /* negotiation version */
1616 memcpy(buf
+ 2, user
, usize
);
1617 buf
[2 + usize
] = psize
;
1618 memcpy(buf
+ 3 + usize
, pass
, psize
);
1620 connection_write_to_buf((char *)buf
, reqsize
, conn
);
1622 conn
->proxy_state
= PROXY_SOCKS5_WANT_AUTH_RFC1929_OK
;
1627 case PROXY_SOCKS5_WANT_AUTH_RFC1929_OK
:
1628 ret
= fetch_from_buf_socks_client(conn
->inbuf
,
1631 /* send the connect request */
1633 connection_send_socks5_connect(conn
);
1638 case PROXY_SOCKS5_WANT_CONNECT_OK
:
1639 ret
= fetch_from_buf_socks_client(conn
->inbuf
,
1643 conn
->proxy_state
= PROXY_CONNECTED
;
1647 log_err(LD_BUG
, "Invalid proxy_state for reading, %d",
1649 tor_fragile_assert();
1654 log_debug(LD_NET
, "leaving state %s",
1655 connection_proxy_state_to_string(conn
->proxy_state
));
1659 log_warn(LD_NET
, "Proxy Client: unable to connect to %s:%d (%s)",
1660 conn
->address
, conn
->port
, escaped(reason
));
1663 log_warn(LD_NET
, "Proxy Client: unable to connect to %s:%d",
1664 conn
->address
, conn
->port
);
1666 } else if (ret
== 1) {
1667 log_info(LD_NET
, "Proxy Client: connection to %s:%d successful",
1668 conn
->address
, conn
->port
);
1675 * Launch any configured listener connections of type <b>type</b>. (A
1676 * listener is configured if <b>port_option</b> is non-zero. If any
1677 * ListenAddress configuration options are given in <b>cfg</b>, create a
1678 * connection binding to each one. Otherwise, create a single
1679 * connection binding to the address <b>default_addr</b>.)
1681 * Only launch the listeners of this type that are not already open, and
1682 * only close listeners that are no longer wanted. Existing listeners
1683 * that are still configured are not touched.
1685 * If <b>disable_all_conns</b> is set, then never open new conns, and
1686 * close the existing ones.
1688 * Add all old conns that should be closed to <b>replaced_conns</b>.
1689 * Add all new connections to <b>new_conns</b>.
1692 retry_listeners(int type
, config_line_t
*cfg
,
1693 int port_option
, const char *default_addr
,
1694 smartlist_t
*replaced_conns
,
1695 smartlist_t
*new_conns
,
1696 int disable_all_conns
,
1699 smartlist_t
*launch
= smartlist_create(), *conns
;
1700 int free_launch_elts
= 1;
1704 config_line_t
*line
;
1706 tor_assert(socket_family
== AF_INET
|| socket_family
== AF_UNIX
);
1708 if (cfg
&& port_option
) {
1709 for (c
= cfg
; c
; c
= c
->next
) {
1710 smartlist_add(launch
, c
);
1712 free_launch_elts
= 0;
1713 } else if (port_option
) {
1714 line
= tor_malloc_zero(sizeof(config_line_t
));
1715 line
->key
= tor_strdup("");
1716 line
->value
= tor_strdup(default_addr
);
1717 smartlist_add(launch
, line
);
1721 SMARTLIST_FOREACH(launch, config_line_t *, l,
1722 log_fn(LOG_NOTICE, "#%s#%s", l->key, l->value));
1725 conns
= get_connection_array();
1726 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
1728 if (conn
->type
!= type
||
1729 conn
->socket_family
!= socket_family
||
1730 conn
->marked_for_close
)
1732 /* Okay, so this is a listener. Is it configured? */
1734 SMARTLIST_FOREACH(launch
, config_line_t
*, wanted
,
1738 switch (socket_family
) {
1740 if (!parse_addr_port(LOG_WARN
,
1741 wanted
->value
, &address
, NULL
, &port
)) {
1742 int addr_matches
= !strcasecmp(address
, conn
->address
);
1746 if (port
== conn
->port
&& addr_matches
) {
1753 if (!strcasecmp(wanted
->value
, conn
->address
)) {
1762 if (!line
|| disable_all_conns
) {
1763 /* This one isn't configured. Close it. */
1764 log_notice(LD_NET
, "Closing no-longer-configured %s on %s:%d",
1765 conn_type_to_string(type
), conn
->address
, conn
->port
);
1766 if (replaced_conns
) {
1767 smartlist_add(replaced_conns
, conn
);
1769 connection_close_immediate(conn
);
1770 connection_mark_for_close(conn
);
1773 /* It's configured; we don't need to launch it. */
1774 // log_debug(LD_NET, "Already have %s on %s:%d",
1775 // conn_type_to_string(type), conn->address, conn->port);
1776 smartlist_remove(launch
, line
);
1777 if (free_launch_elts
)
1778 config_free_lines(line
);
1782 /* Now open all the listeners that are configured but not opened. */
1784 if (!disable_all_conns
) {
1785 SMARTLIST_FOREACH_BEGIN(launch
, config_line_t
*, cfg_line
) {
1786 char *address
= NULL
;
1787 struct sockaddr
*listensockaddr
;
1788 socklen_t listensocklen
= 0;
1790 switch (socket_family
) {
1792 listensockaddr
= (struct sockaddr
*)
1793 create_inet_sockaddr(cfg_line
->value
,
1794 (uint16_t) port_option
,
1795 &address
, &listensocklen
);
1798 listensockaddr
= (struct sockaddr
*)
1799 create_unix_sockaddr(cfg_line
->value
,
1800 &address
, &listensocklen
);
1806 if (listensockaddr
) {
1807 conn
= connection_create_listener(listensockaddr
, listensocklen
,
1809 tor_free(listensockaddr
);
1818 smartlist_add(new_conns
, conn
);
1820 } SMARTLIST_FOREACH_END(cfg_line
);
1823 if (free_launch_elts
) {
1824 SMARTLIST_FOREACH(launch
, config_line_t
*, cfg_line
,
1825 config_free_lines(cfg_line
));
1827 smartlist_free(launch
);
1832 /** Launch listeners for each port you should have open. Only launch
1833 * listeners who are not already open, and only close listeners we no longer
1836 * Add all old conns that should be closed to <b>replaced_conns</b>.
1837 * Add all new connections to <b>new_conns</b>.
1840 retry_all_listeners(smartlist_t
*replaced_conns
,
1841 smartlist_t
*new_conns
)
1843 or_options_t
*options
= get_options();
1845 if (retry_listeners(CONN_TYPE_OR_LISTENER
, options
->ORListenAddress
,
1846 options
->ORPort
, "0.0.0.0",
1847 replaced_conns
, new_conns
, options
->ClientOnly
,
1850 if (retry_listeners(CONN_TYPE_DIR_LISTENER
, options
->DirListenAddress
,
1851 options
->DirPort
, "0.0.0.0",
1852 replaced_conns
, new_conns
, options
->ClientOnly
,
1855 if (retry_listeners(CONN_TYPE_AP_LISTENER
, options
->SocksListenAddress
,
1856 options
->SocksPort
, "127.0.0.1",
1857 replaced_conns
, new_conns
, 0,
1860 if (retry_listeners(CONN_TYPE_AP_TRANS_LISTENER
, options
->TransListenAddress
,
1861 options
->TransPort
, "127.0.0.1",
1862 replaced_conns
, new_conns
, 0,
1865 if (retry_listeners(CONN_TYPE_AP_NATD_LISTENER
, options
->NATDListenAddress
,
1866 options
->NATDPort
, "127.0.0.1",
1867 replaced_conns
, new_conns
, 0,
1870 if (retry_listeners(CONN_TYPE_AP_DNS_LISTENER
, options
->DNSListenAddress
,
1871 options
->DNSPort
, "127.0.0.1",
1872 replaced_conns
, new_conns
, 0,
1875 if (retry_listeners(CONN_TYPE_CONTROL_LISTENER
,
1876 options
->ControlListenAddress
,
1877 options
->ControlPort
, "127.0.0.1",
1878 replaced_conns
, new_conns
, 0,
1881 if (retry_listeners(CONN_TYPE_CONTROL_LISTENER
,
1882 options
->ControlSocket
,
1883 options
->ControlSocket
? 1 : 0, NULL
,
1884 replaced_conns
, new_conns
, 0,
1891 /** Return 1 if we should apply rate limiting to <b>conn</b>,
1892 * and 0 otherwise. Right now this just checks if it's an internal
1893 * IP address or an internal connection. */
1895 connection_is_rate_limited(connection_t
*conn
)
1897 if (conn
->linked
|| /* internal connection */
1898 tor_addr_family(&conn
->addr
) == AF_UNSPEC
|| /* no address */
1899 tor_addr_is_internal(&conn
->addr
, 0)) /* internal address */
1905 extern int global_read_bucket
, global_write_bucket
;
1906 extern int global_relayed_read_bucket
, global_relayed_write_bucket
;
1908 /** Did either global write bucket run dry last second? If so,
1909 * we are likely to run dry again this second, so be stingy with the
1910 * tokens we just put in. */
1911 static int write_buckets_empty_last_second
= 0;
1913 /** How many seconds of no active local circuits will make the
1914 * connection revert to the "relayed" bandwidth class? */
1915 #define CLIENT_IDLE_TIME_FOR_PRIORITY 30
1917 /** Return 1 if <b>conn</b> should use tokens from the "relayed"
1918 * bandwidth rates, else 0. Currently, only OR conns with bandwidth
1919 * class 1, and directory conns that are serving data out, count.
1922 connection_counts_as_relayed_traffic(connection_t
*conn
, time_t now
)
1924 if (conn
->type
== CONN_TYPE_OR
&&
1925 TO_OR_CONN(conn
)->client_used
+ CLIENT_IDLE_TIME_FOR_PRIORITY
< now
)
1927 if (conn
->type
== CONN_TYPE_DIR
&& DIR_CONN_IS_SERVER(conn
))
1932 /** Helper function to decide how many bytes out of <b>global_bucket</b>
1933 * we're willing to use for this transaction. <b>base</b> is the size
1934 * of a cell on the network; <b>priority</b> says whether we should
1935 * write many of them or just a few; and <b>conn_bucket</b> (if
1936 * non-negative) provides an upper limit for our answer. */
1938 connection_bucket_round_robin(int base
, int priority
,
1939 ssize_t global_bucket
, ssize_t conn_bucket
)
1942 ssize_t num_bytes_high
= (priority
? 32 : 16) * base
;
1943 ssize_t num_bytes_low
= (priority
? 4 : 2) * base
;
1945 /* Do a rudimentary round-robin so one circuit can't hog a connection.
1946 * Pick at most 32 cells, at least 4 cells if possible, and if we're in
1947 * the middle pick 1/8 of the available bandwidth. */
1948 at_most
= global_bucket
/ 8;
1949 at_most
-= (at_most
% base
); /* round down */
1950 if (at_most
> num_bytes_high
) /* 16 KB, or 8 KB for low-priority */
1951 at_most
= num_bytes_high
;
1952 else if (at_most
< num_bytes_low
) /* 2 KB, or 1 KB for low-priority */
1953 at_most
= num_bytes_low
;
1955 if (at_most
> global_bucket
)
1956 at_most
= global_bucket
;
1958 if (conn_bucket
>= 0 && at_most
> conn_bucket
)
1959 at_most
= conn_bucket
;
1966 /** How many bytes at most can we read onto this connection? */
1968 connection_bucket_read_limit(connection_t
*conn
, time_t now
)
1970 int base
= connection_speaks_cells(conn
) ?
1971 CELL_NETWORK_SIZE
: RELAY_PAYLOAD_SIZE
;
1972 int priority
= conn
->type
!= CONN_TYPE_DIR
;
1973 int conn_bucket
= -1;
1974 int global_bucket
= global_read_bucket
;
1976 if (connection_speaks_cells(conn
)) {
1977 or_connection_t
*or_conn
= TO_OR_CONN(conn
);
1978 if (conn
->state
== OR_CONN_STATE_OPEN
)
1979 conn_bucket
= or_conn
->read_bucket
;
1982 if (!connection_is_rate_limited(conn
)) {
1983 /* be willing to read on local conns even if our buckets are empty */
1984 return conn_bucket
>=0 ? conn_bucket
: 1<<14;
1987 if (connection_counts_as_relayed_traffic(conn
, now
) &&
1988 global_relayed_read_bucket
<= global_read_bucket
)
1989 global_bucket
= global_relayed_read_bucket
;
1991 return connection_bucket_round_robin(base
, priority
,
1992 global_bucket
, conn_bucket
);
1995 /** How many bytes at most can we write onto this connection? */
1997 connection_bucket_write_limit(connection_t
*conn
, time_t now
)
1999 int base
= connection_speaks_cells(conn
) ?
2000 CELL_NETWORK_SIZE
: RELAY_PAYLOAD_SIZE
;
2001 int priority
= conn
->type
!= CONN_TYPE_DIR
;
2002 int conn_bucket
= (int)conn
->outbuf_flushlen
;
2003 int global_bucket
= global_write_bucket
;
2005 if (!connection_is_rate_limited(conn
)) {
2006 /* be willing to write to local conns even if our buckets are empty */
2007 return conn
->outbuf_flushlen
;
2010 if (connection_speaks_cells(conn
)) {
2011 /* use the per-conn write limit if it's lower, but if it's less
2012 * than zero just use zero */
2013 or_connection_t
*or_conn
= TO_OR_CONN(conn
);
2014 if (conn
->state
== OR_CONN_STATE_OPEN
)
2015 if (or_conn
->write_bucket
< conn_bucket
)
2016 conn_bucket
= or_conn
->write_bucket
>= 0 ?
2017 or_conn
->write_bucket
: 0;
2020 if (connection_counts_as_relayed_traffic(conn
, now
) &&
2021 global_relayed_write_bucket
<= global_write_bucket
)
2022 global_bucket
= global_relayed_write_bucket
;
2024 return connection_bucket_round_robin(base
, priority
,
2025 global_bucket
, conn_bucket
);
2028 /** Return 1 if the global write buckets are low enough that we
2029 * shouldn't send <b>attempt</b> bytes of low-priority directory stuff
2030 * out to <b>conn</b>. Else return 0.
2032 * Priority is 1 for v1 requests (directories and running-routers),
2033 * and 2 for v2 requests (statuses and descriptors). But see FFFF in
2034 * directory_handle_command_get() for why we don't use priority 2 yet.
2036 * There are a lot of parameters we could use here:
2037 * - global_relayed_write_bucket. Low is bad.
2038 * - global_write_bucket. Low is bad.
2039 * - bandwidthrate. Low is bad.
2040 * - bandwidthburst. Not a big factor?
2041 * - attempt. High is bad.
2042 * - total bytes queued on outbufs. High is bad. But I'm wary of
2043 * using this, since a few slow-flushing queues will pump up the
2044 * number without meaning what we meant to mean. What we really
2045 * mean is "total directory bytes added to outbufs recently", but
2046 * that's harder to quantify and harder to keep track of.
2049 global_write_bucket_low(connection_t
*conn
, size_t attempt
, int priority
)
2051 int smaller_bucket
= global_write_bucket
< global_relayed_write_bucket
?
2052 global_write_bucket
: global_relayed_write_bucket
;
2053 if (authdir_mode(get_options()) && priority
>1)
2054 return 0; /* there's always room to answer v2 if we're an auth dir */
2056 if (!connection_is_rate_limited(conn
))
2057 return 0; /* local conns don't get limited */
2059 if (smaller_bucket
< (int)attempt
)
2060 return 1; /* not enough space no matter the priority */
2062 if (write_buckets_empty_last_second
)
2063 return 1; /* we're already hitting our limits, no more please */
2065 if (priority
== 1) { /* old-style v1 query */
2066 /* Could we handle *two* of these requests within the next two seconds? */
2067 or_options_t
*options
= get_options();
2068 int64_t can_write
= (int64_t)smaller_bucket
2069 + 2*(options
->RelayBandwidthRate
? options
->RelayBandwidthRate
:
2070 options
->BandwidthRate
);
2071 if (can_write
< 2*(int64_t)attempt
)
2073 } else { /* v2 query */
2074 /* no further constraints yet */
2079 /** We just read <b>num_read</b> and wrote <b>num_written</b> bytes
2080 * onto <b>conn</b>. Decrement buckets appropriately. */
2082 connection_buckets_decrement(connection_t
*conn
, time_t now
,
2083 size_t num_read
, size_t num_written
)
2085 if (num_written
>= INT_MAX
|| num_read
>= INT_MAX
) {
2086 log_err(LD_BUG
, "Value out of range. num_read=%lu, num_written=%lu, "
2087 "connection type=%s, state=%s",
2088 (unsigned long)num_read
, (unsigned long)num_written
,
2089 conn_type_to_string(conn
->type
),
2090 conn_state_to_string(conn
->type
, conn
->state
));
2091 if (num_written
>= INT_MAX
) num_written
= 1;
2092 if (num_read
>= INT_MAX
) num_read
= 1;
2093 tor_fragile_assert();
2096 /* Count bytes of answering direct and tunneled directory requests */
2097 if (conn
->type
== CONN_TYPE_DIR
&& conn
->purpose
== DIR_PURPOSE_SERVER
) {
2099 rep_hist_note_dir_bytes_read(num_read
, now
);
2100 if (num_written
> 0)
2101 rep_hist_note_dir_bytes_written(num_written
, now
);
2104 if (!connection_is_rate_limited(conn
))
2105 return; /* local IPs are free */
2107 rep_hist_note_bytes_read(num_read
, now
);
2109 if (num_written
> 0) {
2110 rep_hist_note_bytes_written(num_written
, now
);
2112 if (conn
->type
== CONN_TYPE_EXIT
)
2113 rep_hist_note_exit_bytes(conn
->port
, num_written
, num_read
);
2115 if (connection_counts_as_relayed_traffic(conn
, now
)) {
2116 global_relayed_read_bucket
-= (int)num_read
;
2117 global_relayed_write_bucket
-= (int)num_written
;
2119 global_read_bucket
-= (int)num_read
;
2120 global_write_bucket
-= (int)num_written
;
2121 if (connection_speaks_cells(conn
) && conn
->state
== OR_CONN_STATE_OPEN
) {
2122 TO_OR_CONN(conn
)->read_bucket
-= (int)num_read
;
2123 TO_OR_CONN(conn
)->write_bucket
-= (int)num_written
;
2127 /** If we have exhausted our global buckets, or the buckets for conn,
2130 connection_consider_empty_read_buckets(connection_t
*conn
)
2134 if (global_read_bucket
<= 0) {
2135 reason
= "global read bucket exhausted. Pausing.";
2136 } else if (connection_counts_as_relayed_traffic(conn
, approx_time()) &&
2137 global_relayed_read_bucket
<= 0) {
2138 reason
= "global relayed read bucket exhausted. Pausing.";
2139 } else if (connection_speaks_cells(conn
) &&
2140 conn
->state
== OR_CONN_STATE_OPEN
&&
2141 TO_OR_CONN(conn
)->read_bucket
<= 0) {
2142 reason
= "connection read bucket exhausted. Pausing.";
2144 return; /* all good, no need to stop it */
2146 LOG_FN_CONN(conn
, (LOG_DEBUG
, LD_NET
, "%s", reason
));
2147 conn
->read_blocked_on_bw
= 1;
2148 connection_stop_reading(conn
);
2151 /** If we have exhausted our global buckets, or the buckets for conn,
2154 connection_consider_empty_write_buckets(connection_t
*conn
)
2158 if (global_write_bucket
<= 0) {
2159 reason
= "global write bucket exhausted. Pausing.";
2160 } else if (connection_counts_as_relayed_traffic(conn
, approx_time()) &&
2161 global_relayed_write_bucket
<= 0) {
2162 reason
= "global relayed write bucket exhausted. Pausing.";
2163 } else if (connection_speaks_cells(conn
) &&
2164 conn
->state
== OR_CONN_STATE_OPEN
&&
2165 TO_OR_CONN(conn
)->write_bucket
<= 0) {
2166 reason
= "connection write bucket exhausted. Pausing.";
2168 return; /* all good, no need to stop it */
2170 LOG_FN_CONN(conn
, (LOG_DEBUG
, LD_NET
, "%s", reason
));
2171 conn
->write_blocked_on_bw
= 1;
2172 connection_stop_writing(conn
);
2175 /** Initialize the global read bucket to options-\>BandwidthBurst. */
2177 connection_bucket_init(void)
2179 or_options_t
*options
= get_options();
2180 /* start it at max traffic */
2181 global_read_bucket
= (int)options
->BandwidthBurst
;
2182 global_write_bucket
= (int)options
->BandwidthBurst
;
2183 if (options
->RelayBandwidthRate
) {
2184 global_relayed_read_bucket
= (int)options
->RelayBandwidthBurst
;
2185 global_relayed_write_bucket
= (int)options
->RelayBandwidthBurst
;
2187 global_relayed_read_bucket
= (int)options
->BandwidthBurst
;
2188 global_relayed_write_bucket
= (int)options
->BandwidthBurst
;
2192 /** Refill a single <b>bucket</b> called <b>name</b> with bandwidth rate
2193 * <b>rate</b> and bandwidth burst <b>burst</b>, assuming that
2194 * <b>seconds_elapsed</b> seconds have passed since the last call.
2197 connection_bucket_refill_helper(int *bucket
, int rate
, int burst
,
2198 int seconds_elapsed
, const char *name
)
2200 int starting_bucket
= *bucket
;
2201 if (starting_bucket
< burst
&& seconds_elapsed
) {
2202 if (((burst
- starting_bucket
)/seconds_elapsed
) < rate
) {
2203 *bucket
= burst
; /* We would overflow the bucket; just set it to
2206 int incr
= rate
*seconds_elapsed
;
2208 if (*bucket
> burst
|| *bucket
< starting_bucket
) {
2209 /* If we overflow the burst, or underflow our starting bucket,
2210 * cap the bucket value to burst. */
2211 /* XXXX this might be redundant now, but it doesn't show up
2212 * in profiles. Remove it after analysis. */
2216 log(LOG_DEBUG
, LD_NET
,"%s now %d.", name
, *bucket
);
2220 /** A second has rolled over; increment buckets appropriately. */
2222 connection_bucket_refill(int seconds_elapsed
, time_t now
)
2224 or_options_t
*options
= get_options();
2225 smartlist_t
*conns
= get_connection_array();
2226 int relayrate
, relayburst
;
2228 if (options
->RelayBandwidthRate
) {
2229 relayrate
= (int)options
->RelayBandwidthRate
;
2230 relayburst
= (int)options
->RelayBandwidthBurst
;
2232 relayrate
= (int)options
->BandwidthRate
;
2233 relayburst
= (int)options
->BandwidthBurst
;
2236 tor_assert(seconds_elapsed
>= 0);
2238 write_buckets_empty_last_second
=
2239 global_relayed_write_bucket
<= 0 || global_write_bucket
<= 0;
2241 /* refill the global buckets */
2242 connection_bucket_refill_helper(&global_read_bucket
,
2243 (int)options
->BandwidthRate
,
2244 (int)options
->BandwidthBurst
,
2245 seconds_elapsed
, "global_read_bucket");
2246 connection_bucket_refill_helper(&global_write_bucket
,
2247 (int)options
->BandwidthRate
,
2248 (int)options
->BandwidthBurst
,
2249 seconds_elapsed
, "global_write_bucket");
2250 connection_bucket_refill_helper(&global_relayed_read_bucket
,
2251 relayrate
, relayburst
, seconds_elapsed
,
2252 "global_relayed_read_bucket");
2253 connection_bucket_refill_helper(&global_relayed_write_bucket
,
2254 relayrate
, relayburst
, seconds_elapsed
,
2255 "global_relayed_write_bucket");
2257 /* refill the per-connection buckets */
2258 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
2260 if (connection_speaks_cells(conn
)) {
2261 or_connection_t
*or_conn
= TO_OR_CONN(conn
);
2262 if (connection_bucket_should_increase(or_conn
->read_bucket
, or_conn
)) {
2263 connection_bucket_refill_helper(&or_conn
->read_bucket
,
2264 or_conn
->bandwidthrate
,
2265 or_conn
->bandwidthburst
,
2267 "or_conn->read_bucket");
2269 if (connection_bucket_should_increase(or_conn
->write_bucket
, or_conn
)) {
2270 connection_bucket_refill_helper(&or_conn
->write_bucket
,
2271 or_conn
->bandwidthrate
,
2272 or_conn
->bandwidthburst
,
2274 "or_conn->write_bucket");
2278 if (conn
->read_blocked_on_bw
== 1 /* marked to turn reading back on now */
2279 && global_read_bucket
> 0 /* and we're allowed to read */
2280 && (!connection_counts_as_relayed_traffic(conn
, now
) ||
2281 global_relayed_read_bucket
> 0) /* even if we're relayed traffic */
2282 && (!connection_speaks_cells(conn
) ||
2283 conn
->state
!= OR_CONN_STATE_OPEN
||
2284 TO_OR_CONN(conn
)->read_bucket
> 0)) {
2285 /* and either a non-cell conn or a cell conn with non-empty bucket */
2286 LOG_FN_CONN(conn
, (LOG_DEBUG
,LD_NET
,
2287 "waking up conn (fd %d) for read", conn
->s
));
2288 conn
->read_blocked_on_bw
= 0;
2289 connection_start_reading(conn
);
2292 if (conn
->write_blocked_on_bw
== 1
2293 && global_write_bucket
> 0 /* and we're allowed to write */
2294 && (!connection_counts_as_relayed_traffic(conn
, now
) ||
2295 global_relayed_write_bucket
> 0) /* even if it's relayed traffic */
2296 && (!connection_speaks_cells(conn
) ||
2297 conn
->state
!= OR_CONN_STATE_OPEN
||
2298 TO_OR_CONN(conn
)->write_bucket
> 0)) {
2299 LOG_FN_CONN(conn
, (LOG_DEBUG
,LD_NET
,
2300 "waking up conn (fd %d) for write", conn
->s
));
2301 conn
->write_blocked_on_bw
= 0;
2302 connection_start_writing(conn
);
2307 /** Is the <b>bucket</b> for connection <b>conn</b> low enough that we
2308 * should add another pile of tokens to it?
2311 connection_bucket_should_increase(int bucket
, or_connection_t
*conn
)
2315 if (conn
->_base
.state
!= OR_CONN_STATE_OPEN
)
2316 return 0; /* only open connections play the rate limiting game */
2317 if (bucket
>= conn
->bandwidthburst
)
2323 /** Read bytes from conn-\>s and process them.
2325 * This function gets called from conn_read() in main.c, either
2326 * when poll() has declared that conn wants to read, or (for OR conns)
2327 * when there are pending TLS bytes.
2329 * It calls connection_read_to_buf() to bring in any new bytes,
2330 * and then calls connection_process_inbuf() to process them.
2332 * Mark the connection and return -1 if you want to close it, else
2336 connection_handle_read_impl(connection_t
*conn
)
2338 int max_to_read
=-1, try_to_read
;
2339 size_t before
, n_read
= 0;
2340 int socket_error
= 0;
2342 if (conn
->marked_for_close
)
2343 return 0; /* do nothing */
2345 conn
->timestamp_lastread
= approx_time();
2347 switch (conn
->type
) {
2348 case CONN_TYPE_OR_LISTENER
:
2349 return connection_handle_listener_read(conn
, CONN_TYPE_OR
);
2350 case CONN_TYPE_AP_LISTENER
:
2351 case CONN_TYPE_AP_TRANS_LISTENER
:
2352 case CONN_TYPE_AP_NATD_LISTENER
:
2353 return connection_handle_listener_read(conn
, CONN_TYPE_AP
);
2354 case CONN_TYPE_DIR_LISTENER
:
2355 return connection_handle_listener_read(conn
, CONN_TYPE_DIR
);
2356 case CONN_TYPE_CONTROL_LISTENER
:
2357 return connection_handle_listener_read(conn
, CONN_TYPE_CONTROL
);
2358 case CONN_TYPE_AP_DNS_LISTENER
:
2359 /* This should never happen; eventdns.c handles the reads here. */
2360 tor_fragile_assert();
2365 try_to_read
= max_to_read
;
2366 tor_assert(!conn
->marked_for_close
);
2368 before
= buf_datalen(conn
->inbuf
);
2369 if (connection_read_to_buf(conn
, &max_to_read
, &socket_error
) < 0) {
2370 /* There's a read error; kill the connection.*/
2371 if (conn
->type
== CONN_TYPE_OR
&&
2372 conn
->state
== OR_CONN_STATE_CONNECTING
) {
2373 connection_or_connect_failed(TO_OR_CONN(conn
),
2374 errno_to_orconn_end_reason(socket_error
),
2375 tor_socket_strerror(socket_error
));
2377 if (CONN_IS_EDGE(conn
)) {
2378 edge_connection_t
*edge_conn
= TO_EDGE_CONN(conn
);
2379 connection_edge_end_errno(edge_conn
);
2380 if (edge_conn
->socks_request
) /* broken, don't send a socks reply back */
2381 edge_conn
->socks_request
->has_finished
= 1;
2383 connection_close_immediate(conn
); /* Don't flush; connection is dead. */
2384 connection_mark_for_close(conn
);
2387 n_read
+= buf_datalen(conn
->inbuf
) - before
;
2388 if (CONN_IS_EDGE(conn
) && try_to_read
!= max_to_read
) {
2389 /* instruct it not to try to package partial cells. */
2390 if (connection_process_inbuf(conn
, 0) < 0) {
2393 if (!conn
->marked_for_close
&&
2394 connection_is_reading(conn
) &&
2395 !conn
->inbuf_reached_eof
&&
2397 goto loop_again
; /* try reading again, in case more is here now */
2399 /* one last try, packaging partial cells and all. */
2400 if (!conn
->marked_for_close
&&
2401 connection_process_inbuf(conn
, 1) < 0) {
2404 if (conn
->linked_conn
) {
2405 /* The other side's handle_write() will never actually get called, so
2406 * we need to invoke the appropriate callbacks ourself. */
2407 connection_t
*linked
= conn
->linked_conn
;
2410 /* Probably a no-op, since linked conns typically don't count for
2411 * bandwidth rate limiting. But do it anyway so we can keep stats
2412 * accurately. Note that since we read the bytes from conn, and
2413 * we're writing the bytes onto the linked connection, we count
2414 * these as <i>written</i> bytes. */
2415 connection_buckets_decrement(linked
, approx_time(), 0, n_read
);
2417 if (connection_flushed_some(linked
) < 0)
2418 connection_mark_for_close(linked
);
2419 if (!connection_wants_to_flush(linked
))
2420 connection_finished_flushing(linked
);
2423 if (!buf_datalen(linked
->outbuf
) && conn
->active_on_link
)
2424 connection_stop_reading_from_linked_conn(conn
);
2426 /* If we hit the EOF, call connection_reached_eof(). */
2427 if (!conn
->marked_for_close
&&
2428 conn
->inbuf_reached_eof
&&
2429 connection_reached_eof(conn
) < 0) {
2436 connection_handle_read(connection_t
*conn
)
2440 tor_gettimeofday_cache_clear();
2441 res
= connection_handle_read_impl(conn
);
2445 /** Pull in new bytes from conn-\>s or conn-\>linked_conn onto conn-\>inbuf,
2446 * either directly or via TLS. Reduce the token buckets by the number of bytes
2449 * If *max_to_read is -1, then decide it ourselves, else go with the
2450 * value passed to us. When returning, if it's changed, subtract the
2451 * number of bytes we read from *max_to_read.
2453 * Return -1 if we want to break conn, else return 0.
2456 connection_read_to_buf(connection_t
*conn
, int *max_to_read
, int *socket_error
)
2459 ssize_t at_most
= *max_to_read
;
2460 size_t slack_in_buf
, more_to_read
;
2461 size_t n_read
= 0, n_written
= 0;
2463 if (at_most
== -1) { /* we need to initialize it */
2464 /* how many bytes are we allowed to read? */
2465 at_most
= connection_bucket_read_limit(conn
, approx_time());
2468 slack_in_buf
= buf_slack(conn
->inbuf
);
2470 if ((size_t)at_most
> slack_in_buf
&& slack_in_buf
>= 1024) {
2471 more_to_read
= at_most
- slack_in_buf
;
2472 at_most
= slack_in_buf
;
2477 if (connection_speaks_cells(conn
) &&
2478 conn
->state
> OR_CONN_STATE_PROXY_HANDSHAKING
) {
2480 or_connection_t
*or_conn
= TO_OR_CONN(conn
);
2481 size_t initial_size
;
2482 if (conn
->state
== OR_CONN_STATE_TLS_HANDSHAKING
||
2483 conn
->state
== OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING
) {
2484 /* continue handshaking even if global token bucket is empty */
2485 return connection_tls_continue_handshake(or_conn
);
2489 "%d: starting, inbuf_datalen %ld (%d pending in tls object)."
2491 conn
->s
,(long)buf_datalen(conn
->inbuf
),
2492 tor_tls_get_pending_bytes(or_conn
->tls
), (long)at_most
);
2494 initial_size
= buf_datalen(conn
->inbuf
);
2495 /* else open, or closing */
2496 result
= read_to_buf_tls(or_conn
->tls
, at_most
, conn
->inbuf
);
2497 if (TOR_TLS_IS_ERROR(result
) || result
== TOR_TLS_CLOSE
)
2498 or_conn
->tls_error
= result
;
2500 or_conn
->tls_error
= 0;
2504 case TOR_TLS_ERROR_IO
:
2505 log_debug(LD_NET
,"TLS connection closed %son read. Closing. "
2506 "(Nickname %s, address %s)",
2507 result
== TOR_TLS_CLOSE
? "cleanly " : "",
2508 or_conn
->nickname
? or_conn
->nickname
: "not set",
2511 CASE_TOR_TLS_ERROR_ANY_NONIO
:
2512 log_debug(LD_NET
,"tls error [%s]. breaking (nickname %s, address %s).",
2513 tor_tls_err_to_string(result
),
2514 or_conn
->nickname
? or_conn
->nickname
: "not set",
2517 case TOR_TLS_WANTWRITE
:
2518 connection_start_writing(conn
);
2520 case TOR_TLS_WANTREAD
: /* we're already reading */
2521 case TOR_TLS_DONE
: /* no data read, so nothing to process */
2523 break; /* so we call bucket_decrement below */
2527 pending
= tor_tls_get_pending_bytes(or_conn
->tls
);
2529 /* If we have any pending bytes, we read them now. This *can*
2530 * take us over our read allotment, but really we shouldn't be
2531 * believing that SSL bytes are the same as TCP bytes anyway. */
2532 int r2
= read_to_buf_tls(or_conn
->tls
, pending
, conn
->inbuf
);
2534 log_warn(LD_BUG
, "apparently, reading pending bytes can fail.");
2538 result
= (int)(buf_datalen(conn
->inbuf
)-initial_size
);
2539 tor_tls_get_n_raw_bytes(or_conn
->tls
, &n_read
, &n_written
);
2540 log_debug(LD_GENERAL
, "After TLS read of %d: %ld read, %ld written",
2541 result
, (long)n_read
, (long)n_written
);
2542 } else if (conn
->linked
) {
2543 if (conn
->linked_conn
) {
2544 result
= move_buf_to_buf(conn
->inbuf
, conn
->linked_conn
->outbuf
,
2545 &conn
->linked_conn
->outbuf_flushlen
);
2549 //log_notice(LD_GENERAL, "Moved %d bytes on an internal link!", result);
2550 /* If the other side has disappeared, or if it's been marked for close and
2551 * we flushed its outbuf, then we should set our inbuf_reached_eof. */
2552 if (!conn
->linked_conn
||
2553 (conn
->linked_conn
->marked_for_close
&&
2554 buf_datalen(conn
->linked_conn
->outbuf
) == 0))
2555 conn
->inbuf_reached_eof
= 1;
2557 n_read
= (size_t) result
;
2559 /* !connection_speaks_cells, !conn->linked_conn. */
2560 int reached_eof
= 0;
2561 CONN_LOG_PROTECT(conn
,
2562 result
= read_to_buf(conn
->s
, at_most
, conn
->inbuf
, &reached_eof
,
2565 conn
->inbuf_reached_eof
= 1;
2567 // log_fn(LOG_DEBUG,"read_to_buf returned %d.",read_result);
2571 n_read
= (size_t) result
;
2574 if (n_read
> 0) { /* change *max_to_read */
2575 /*XXXX021 check for overflow*/
2576 *max_to_read
= (int)(at_most
- n_read
);
2579 if (conn
->type
== CONN_TYPE_AP
) {
2580 edge_connection_t
*edge_conn
= TO_EDGE_CONN(conn
);
2581 /*XXXX021 check for overflow*/
2582 edge_conn
->n_read
+= (int)n_read
;
2585 connection_buckets_decrement(conn
, approx_time(), n_read
, n_written
);
2587 if (more_to_read
&& result
== at_most
) {
2588 slack_in_buf
= buf_slack(conn
->inbuf
);
2589 at_most
= more_to_read
;
2593 /* Call even if result is 0, since the global read bucket may
2594 * have reached 0 on a different conn, and this guy needs to
2595 * know to stop reading. */
2596 connection_consider_empty_read_buckets(conn
);
2597 if (n_written
> 0 && connection_is_writing(conn
))
2598 connection_consider_empty_write_buckets(conn
);
2603 /** A pass-through to fetch_from_buf. */
2605 connection_fetch_from_buf(char *string
, size_t len
, connection_t
*conn
)
2607 return fetch_from_buf(string
, len
, conn
->inbuf
);
2610 /** Return conn-\>outbuf_flushlen: how many bytes conn wants to flush
2611 * from its outbuf. */
2613 connection_wants_to_flush(connection_t
*conn
)
2615 return conn
->outbuf_flushlen
> 0;
2618 /** Are there too many bytes on edge connection <b>conn</b>'s outbuf to
2619 * send back a relay-level sendme yet? Return 1 if so, 0 if not. Used by
2620 * connection_edge_consider_sending_sendme().
2623 connection_outbuf_too_full(connection_t
*conn
)
2625 return (conn
->outbuf_flushlen
> 10*CELL_PAYLOAD_SIZE
);
2628 /** Try to flush more bytes onto conn-\>s.
2630 * This function gets called either from conn_write() in main.c
2631 * when poll() has declared that conn wants to write, or below
2632 * from connection_write_to_buf() when an entire TLS record is ready.
2634 * Update conn-\>timestamp_lastwritten to now, and call flush_buf
2635 * or flush_buf_tls appropriately. If it succeeds and there are no more
2636 * more bytes on conn->outbuf, then call connection_finished_flushing
2639 * If <b>force</b>, then write as many bytes as possible, ignoring bandwidth
2640 * limits. (Used for flushing messages to controller connections on fatal
2643 * Mark the connection and return -1 if you want to close it, else
2647 connection_handle_write_impl(connection_t
*conn
, int force
)
2650 socklen_t len
=(socklen_t
)sizeof(e
);
2652 ssize_t max_to_write
;
2653 time_t now
= approx_time();
2654 size_t n_read
= 0, n_written
= 0;
2656 tor_assert(!connection_is_listener(conn
));
2658 if (conn
->marked_for_close
|| conn
->s
< 0)
2659 return 0; /* do nothing */
2661 if (conn
->in_flushed_some
) {
2662 log_warn(LD_BUG
, "called recursively from inside conn->in_flushed_some");
2666 conn
->timestamp_lastwritten
= now
;
2668 /* Sometimes, "writable" means "connected". */
2669 if (connection_state_is_connecting(conn
)) {
2670 if (getsockopt(conn
->s
, SOL_SOCKET
, SO_ERROR
, (void*)&e
, &len
) < 0) {
2672 "getsockopt() syscall failed?! Please report to tor-ops.");
2673 if (CONN_IS_EDGE(conn
))
2674 connection_edge_end_errno(TO_EDGE_CONN(conn
));
2675 connection_mark_for_close(conn
);
2679 /* some sort of error, but maybe just inprogress still */
2680 if (!ERRNO_IS_CONN_EINPROGRESS(e
)) {
2681 log_info(LD_NET
,"in-progress connect failed. Removing. (%s)",
2682 tor_socket_strerror(e
));
2683 if (CONN_IS_EDGE(conn
))
2684 connection_edge_end_errno(TO_EDGE_CONN(conn
));
2685 if (conn
->type
== CONN_TYPE_OR
)
2686 connection_or_connect_failed(TO_OR_CONN(conn
),
2687 errno_to_orconn_end_reason(e
),
2688 tor_socket_strerror(e
));
2690 connection_close_immediate(conn
);
2691 connection_mark_for_close(conn
);
2694 return 0; /* no change, see if next time is better */
2697 /* The connection is successful. */
2698 if (connection_finished_connecting(conn
)<0)
2702 max_to_write
= force
? (ssize_t
)conn
->outbuf_flushlen
2703 : connection_bucket_write_limit(conn
, now
);
2705 if (connection_speaks_cells(conn
) &&
2706 conn
->state
> OR_CONN_STATE_PROXY_HANDSHAKING
) {
2707 or_connection_t
*or_conn
= TO_OR_CONN(conn
);
2708 if (conn
->state
== OR_CONN_STATE_TLS_HANDSHAKING
||
2709 conn
->state
== OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING
) {
2710 connection_stop_writing(conn
);
2711 if (connection_tls_continue_handshake(or_conn
) < 0) {
2712 /* Don't flush; connection is dead. */
2713 connection_close_immediate(conn
);
2714 connection_mark_for_close(conn
);
2718 } else if (conn
->state
== OR_CONN_STATE_TLS_SERVER_RENEGOTIATING
) {
2719 return connection_handle_read(conn
);
2722 /* else open, or closing */
2723 result
= flush_buf_tls(or_conn
->tls
, conn
->outbuf
,
2724 max_to_write
, &conn
->outbuf_flushlen
);
2726 /* If we just flushed the last bytes, check if this tunneled dir
2727 * request is done. */
2728 if (buf_datalen(conn
->outbuf
) == 0 && conn
->dirreq_id
)
2729 geoip_change_dirreq_state(conn
->dirreq_id
, DIRREQ_TUNNELED
,
2730 DIRREQ_OR_CONN_BUFFER_FLUSHED
);
2733 CASE_TOR_TLS_ERROR_ANY
:
2735 log_info(LD_NET
,result
!=TOR_TLS_CLOSE
?
2736 "tls error. breaking.":"TLS connection closed on flush");
2737 /* Don't flush; connection is dead. */
2738 connection_close_immediate(conn
);
2739 connection_mark_for_close(conn
);
2741 case TOR_TLS_WANTWRITE
:
2742 log_debug(LD_NET
,"wanted write.");
2743 /* we're already writing */
2745 case TOR_TLS_WANTREAD
:
2746 /* Make sure to avoid a loop if the receive buckets are empty. */
2747 log_debug(LD_NET
,"wanted read.");
2748 if (!connection_is_reading(conn
)) {
2749 connection_stop_writing(conn
);
2750 conn
->write_blocked_on_bw
= 1;
2751 /* we'll start reading again when we get more tokens in our
2752 * read bucket; then we'll start writing again too.
2755 /* else no problem, we're already reading */
2757 /* case TOR_TLS_DONE:
2758 * for TOR_TLS_DONE, fall through to check if the flushlen
2759 * is empty, so we can stop writing.
2763 tor_tls_get_n_raw_bytes(or_conn
->tls
, &n_read
, &n_written
);
2764 log_debug(LD_GENERAL
, "After TLS write of %d: %ld read, %ld written",
2765 result
, (long)n_read
, (long)n_written
);
2767 CONN_LOG_PROTECT(conn
,
2768 result
= flush_buf(conn
->s
, conn
->outbuf
,
2769 max_to_write
, &conn
->outbuf_flushlen
));
2771 if (CONN_IS_EDGE(conn
))
2772 connection_edge_end_errno(TO_EDGE_CONN(conn
));
2774 connection_close_immediate(conn
); /* Don't flush; connection is dead. */
2775 connection_mark_for_close(conn
);
2778 n_written
= (size_t) result
;
2781 if (conn
->type
== CONN_TYPE_AP
) {
2782 edge_connection_t
*edge_conn
= TO_EDGE_CONN(conn
);
2783 /*XXXX021 check for overflow.*/
2784 edge_conn
->n_written
+= (int)n_written
;
2787 connection_buckets_decrement(conn
, approx_time(), n_read
, n_written
);
2790 /* If we wrote any bytes from our buffer, then call the appropriate
2792 if (connection_flushed_some(conn
) < 0)
2793 connection_mark_for_close(conn
);
2796 if (!connection_wants_to_flush(conn
)) { /* it's done flushing */
2797 if (connection_finished_flushing(conn
) < 0) {
2798 /* already marked */
2804 /* Call even if result is 0, since the global write bucket may
2805 * have reached 0 on a different conn, and this guy needs to
2806 * know to stop writing. */
2807 connection_consider_empty_write_buckets(conn
);
2808 if (n_read
> 0 && connection_is_reading(conn
))
2809 connection_consider_empty_read_buckets(conn
);
2815 connection_handle_write(connection_t
*conn
, int force
)
2818 tor_gettimeofday_cache_clear();
2819 res
= connection_handle_write_impl(conn
, force
);
2823 /** OpenSSL TLS record size is 16383; this is close. The goal here is to
2824 * push data out as soon as we know there's enough for a TLS record, so
2825 * during periods of high load we won't read entire megabytes from
2826 * input before pushing any data out. It also has the feature of not
2827 * growing huge outbufs unless something is slow. */
2828 #define MIN_TLS_FLUSHLEN 15872
2830 /** Append <b>len</b> bytes of <b>string</b> onto <b>conn</b>'s
2831 * outbuf, and ask it to start writing.
2833 * If <b>zlib</b> is nonzero, this is a directory connection that should get
2834 * its contents compressed or decompressed as they're written. If zlib is
2835 * negative, this is the last data to be compressed, and the connection's zlib
2836 * state should be flushed.
2838 * If it's an OR conn and an entire TLS record is ready, then try to
2839 * flush the record now. Similarly, if it's a local control connection
2840 * and a 64k chunk is ready, try to flush it all, so we don't end up with
2841 * many megabytes of controller info queued at once.
2844 _connection_write_to_buf_impl(const char *string
, size_t len
,
2845 connection_t
*conn
, int zlib
)
2847 /* XXXX This function really needs to return -1 on failure. */
2850 if (!len
&& !(zlib
<0))
2852 /* if it's marked for close, only allow write if we mean to flush it */
2853 if (conn
->marked_for_close
&& !conn
->hold_open_until_flushed
)
2856 old_datalen
= buf_datalen(conn
->outbuf
);
2858 dir_connection_t
*dir_conn
= TO_DIR_CONN(conn
);
2859 int done
= zlib
< 0;
2860 CONN_LOG_PROTECT(conn
, r
= write_to_buf_zlib(conn
->outbuf
,
2861 dir_conn
->zlib_state
,
2862 string
, len
, done
));
2864 CONN_LOG_PROTECT(conn
, r
= write_to_buf(string
, len
, conn
->outbuf
));
2867 if (CONN_IS_EDGE(conn
)) {
2868 /* if it failed, it means we have our package/delivery windows set
2869 wrong compared to our max outbuf size. close the whole circuit. */
2871 "write_to_buf failed. Closing circuit (fd %d).", conn
->s
);
2872 circuit_mark_for_close(circuit_get_by_edge_conn(TO_EDGE_CONN(conn
)),
2873 END_CIRC_REASON_INTERNAL
);
2876 "write_to_buf failed. Closing connection (fd %d).", conn
->s
);
2877 connection_mark_for_close(conn
);
2882 connection_start_writing(conn
);
2884 conn
->outbuf_flushlen
+= buf_datalen(conn
->outbuf
) - old_datalen
;
2887 conn
->outbuf_flushlen
+= len
;
2889 /* Should we try flushing the outbuf now? */
2890 if (conn
->in_flushed_some
) {
2891 /* Don't flush the outbuf when the reason we're writing more stuff is
2892 * _because_ we flushed the outbuf. That's unfair. */
2896 if (conn
->type
== CONN_TYPE_OR
&&
2897 conn
->outbuf_flushlen
-len
< MIN_TLS_FLUSHLEN
&&
2898 conn
->outbuf_flushlen
>= MIN_TLS_FLUSHLEN
) {
2899 /* We just pushed outbuf_flushlen to MIN_TLS_FLUSHLEN or above;
2900 * we can send out a full TLS frame now if we like. */
2901 extra
= conn
->outbuf_flushlen
- MIN_TLS_FLUSHLEN
;
2902 conn
->outbuf_flushlen
= MIN_TLS_FLUSHLEN
;
2903 } else if (conn
->type
== CONN_TYPE_CONTROL
&&
2904 !connection_is_rate_limited(conn
) &&
2905 conn
->outbuf_flushlen
-len
< 1<<16 &&
2906 conn
->outbuf_flushlen
>= 1<<16) {
2907 /* just try to flush all of it */
2909 return; /* no need to try flushing */
2911 if (connection_handle_write(conn
, 0) < 0) {
2912 if (!conn
->marked_for_close
) {
2913 /* this connection is broken. remove it. */
2914 log_warn(LD_BUG
, "unhandled error on write for "
2915 "conn (type %d, fd %d); removing",
2916 conn
->type
, conn
->s
);
2917 tor_fragile_assert();
2918 /* do a close-immediate here, so we don't try to flush */
2919 connection_close_immediate(conn
);
2924 conn
->outbuf_flushlen
+= extra
;
2925 connection_start_writing(conn
);
2930 /** Return a connection with given type, address, port, and purpose;
2931 * or NULL if no such connection exists. */
2933 connection_get_by_type_addr_port_purpose(int type
,
2934 const tor_addr_t
*addr
, uint16_t port
,
2937 smartlist_t
*conns
= get_connection_array();
2938 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
2940 if (conn
->type
== type
&&
2941 tor_addr_eq(&conn
->addr
, addr
) &&
2942 conn
->port
== port
&&
2943 conn
->purpose
== purpose
&&
2944 !conn
->marked_for_close
)
2950 /** Return the stream with id <b>id</b> if it is not already marked for
2954 connection_get_by_global_id(uint64_t id
)
2956 smartlist_t
*conns
= get_connection_array();
2957 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
2959 if (conn
->global_identifier
== id
)
2965 /** Return a connection of type <b>type</b> that is not marked for close.
2968 connection_get_by_type(int type
)
2970 smartlist_t
*conns
= get_connection_array();
2971 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
2973 if (conn
->type
== type
&& !conn
->marked_for_close
)
2979 /** Return a connection of type <b>type</b> that is in state <b>state</b>,
2980 * and that is not marked for close.
2983 connection_get_by_type_state(int type
, int state
)
2985 smartlist_t
*conns
= get_connection_array();
2986 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
2988 if (conn
->type
== type
&& conn
->state
== state
&& !conn
->marked_for_close
)
2994 /** Return a connection of type <b>type</b> that has rendquery equal
2995 * to <b>rendquery</b>, and that is not marked for close. If state
2996 * is non-zero, conn must be of that state too.
2999 connection_get_by_type_state_rendquery(int type
, int state
,
3000 const char *rendquery
)
3002 smartlist_t
*conns
= get_connection_array();
3004 tor_assert(type
== CONN_TYPE_DIR
||
3005 type
== CONN_TYPE_AP
|| type
== CONN_TYPE_EXIT
);
3006 tor_assert(rendquery
);
3008 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
3010 if (conn
->type
== type
&&
3011 !conn
->marked_for_close
&&
3012 (!state
|| state
== conn
->state
)) {
3013 if (type
== CONN_TYPE_DIR
&&
3014 TO_DIR_CONN(conn
)->rend_data
&&
3015 !rend_cmp_service_ids(rendquery
,
3016 TO_DIR_CONN(conn
)->rend_data
->onion_address
))
3018 else if (CONN_IS_EDGE(conn
) &&
3019 TO_EDGE_CONN(conn
)->rend_data
&&
3020 !rend_cmp_service_ids(rendquery
,
3021 TO_EDGE_CONN(conn
)->rend_data
->onion_address
))
3028 /** Return an open, non-marked connection of a given type and purpose, or NULL
3029 * if no such connection exists. */
3031 connection_get_by_type_purpose(int type
, int purpose
)
3033 smartlist_t
*conns
= get_connection_array();
3034 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
3036 if (conn
->type
== type
&&
3037 !conn
->marked_for_close
&&
3038 (purpose
== conn
->purpose
))
3044 /** Return 1 if <b>conn</b> is a listener conn, else return 0. */
3046 connection_is_listener(connection_t
*conn
)
3048 if (conn
->type
== CONN_TYPE_OR_LISTENER
||
3049 conn
->type
== CONN_TYPE_AP_LISTENER
||
3050 conn
->type
== CONN_TYPE_AP_TRANS_LISTENER
||
3051 conn
->type
== CONN_TYPE_AP_DNS_LISTENER
||
3052 conn
->type
== CONN_TYPE_AP_NATD_LISTENER
||
3053 conn
->type
== CONN_TYPE_DIR_LISTENER
||
3054 conn
->type
== CONN_TYPE_CONTROL_LISTENER
)
3059 /** Return 1 if <b>conn</b> is in state "open" and is not marked
3060 * for close, else return 0.
3063 connection_state_is_open(connection_t
*conn
)
3067 if (conn
->marked_for_close
)
3070 if ((conn
->type
== CONN_TYPE_OR
&& conn
->state
== OR_CONN_STATE_OPEN
) ||
3071 (conn
->type
== CONN_TYPE_AP
&& conn
->state
== AP_CONN_STATE_OPEN
) ||
3072 (conn
->type
== CONN_TYPE_EXIT
&& conn
->state
== EXIT_CONN_STATE_OPEN
) ||
3073 (conn
->type
== CONN_TYPE_CONTROL
&&
3074 conn
->state
== CONTROL_CONN_STATE_OPEN
))
3080 /** Return 1 if conn is in 'connecting' state, else return 0. */
3082 connection_state_is_connecting(connection_t
*conn
)
3086 if (conn
->marked_for_close
)
3091 return conn
->state
== OR_CONN_STATE_CONNECTING
;
3092 case CONN_TYPE_EXIT
:
3093 return conn
->state
== EXIT_CONN_STATE_CONNECTING
;
3095 return conn
->state
== DIR_CONN_STATE_CONNECTING
;
3101 /** Allocates a base64'ed authenticator for use in http or https
3102 * auth, based on the input string <b>authenticator</b>. Returns it
3103 * if success, else returns NULL. */
3105 alloc_http_authenticator(const char *authenticator
)
3107 /* an authenticator in Basic authentication
3108 * is just the string "username:password" */
3109 const size_t authenticator_length
= strlen(authenticator
);
3110 /* The base64_encode function needs a minimum buffer length
3112 const size_t base64_authenticator_length
= (authenticator_length
/48+1)*66;
3113 char *base64_authenticator
= tor_malloc(base64_authenticator_length
);
3114 if (base64_encode(base64_authenticator
, base64_authenticator_length
,
3115 authenticator
, authenticator_length
) < 0) {
3116 tor_free(base64_authenticator
); /* free and set to null */
3118 /* remove extra \n at end of encoding */
3119 base64_authenticator
[strlen(base64_authenticator
) - 1] = 0;
3121 return base64_authenticator
;
3124 /** Given a socket handle, check whether the local address (sockname) of the
3125 * socket is one that we've connected from before. If so, double-check
3126 * whether our address has changed and we need to generate keys. If we do,
3130 client_check_address_changed(int sock
)
3132 uint32_t iface_ip
, ip_out
; /* host order */
3133 struct sockaddr_in out_addr
;
3134 socklen_t out_addr_len
= (socklen_t
) sizeof(out_addr
);
3135 uint32_t *ip
; /* host order */
3137 if (!last_interface_ip
)
3138 get_interface_address(LOG_INFO
, &last_interface_ip
);
3139 if (!outgoing_addrs
)
3140 outgoing_addrs
= smartlist_create();
3142 if (getsockname(sock
, (struct sockaddr
*)&out_addr
, &out_addr_len
)<0) {
3143 int e
= tor_socket_errno(sock
);
3144 log_warn(LD_NET
, "getsockname() to check for address change failed: %s",
3145 tor_socket_strerror(e
));
3149 /* If we've used this address previously, we're okay. */
3150 ip_out
= ntohl(out_addr
.sin_addr
.s_addr
);
3151 SMARTLIST_FOREACH(outgoing_addrs
, uint32_t*, ip_ptr
,
3152 if (*ip_ptr
== ip_out
) return;
3155 /* Uh-oh. We haven't connected from this address before. Has the interface
3156 * address changed? */
3157 if (get_interface_address(LOG_INFO
, &iface_ip
)<0)
3159 ip
= tor_malloc(sizeof(uint32_t));
3162 if (iface_ip
== last_interface_ip
) {
3163 /* Nope, it hasn't changed. Add this address to the list. */
3164 smartlist_add(outgoing_addrs
, ip
);
3166 /* The interface changed. We're a client, so we need to regenerate our
3167 * keys. First, reset the state. */
3168 log(LOG_NOTICE
, LD_NET
, "Our IP address has changed. Rotating keys...");
3169 last_interface_ip
= iface_ip
;
3170 SMARTLIST_FOREACH(outgoing_addrs
, void*, ip_ptr
, tor_free(ip_ptr
));
3171 smartlist_clear(outgoing_addrs
);
3172 smartlist_add(outgoing_addrs
, ip
);
3173 /* Okay, now change our keys. */
3174 ip_address_changed(1);
3178 /** Some systems have limited system buffers for recv and xmit on
3179 * sockets allocated in a virtual server or similar environment. For a Tor
3180 * server this can produce the "Error creating network socket: No buffer
3181 * space available" error once all available TCP buffer space is consumed.
3182 * This method will attempt to constrain the buffers allocated for the socket
3183 * to the desired size to stay below system TCP buffer limits.
3186 set_constrained_socket_buffers(int sock
, int size
)
3188 void *sz
= (void*)&size
;
3189 socklen_t sz_sz
= (socklen_t
) sizeof(size
);
3190 if (setsockopt(sock
, SOL_SOCKET
, SO_SNDBUF
, sz
, sz_sz
) < 0) {
3191 int e
= tor_socket_errno(sock
);
3192 log_warn(LD_NET
, "setsockopt() to constrain send "
3193 "buffer to %d bytes failed: %s", size
, tor_socket_strerror(e
));
3195 if (setsockopt(sock
, SOL_SOCKET
, SO_RCVBUF
, sz
, sz_sz
) < 0) {
3196 int e
= tor_socket_errno(sock
);
3197 log_warn(LD_NET
, "setsockopt() to constrain recv "
3198 "buffer to %d bytes failed: %s", size
, tor_socket_strerror(e
));
3202 /** Process new bytes that have arrived on conn-\>inbuf.
3204 * This function just passes conn to the connection-specific
3205 * connection_*_process_inbuf() function. It also passes in
3206 * package_partial if wanted.
3209 connection_process_inbuf(connection_t
*conn
, int package_partial
)
3213 switch (conn
->type
) {
3215 return connection_or_process_inbuf(TO_OR_CONN(conn
));
3216 case CONN_TYPE_EXIT
:
3218 return connection_edge_process_inbuf(TO_EDGE_CONN(conn
),
3221 return connection_dir_process_inbuf(TO_DIR_CONN(conn
));
3222 case CONN_TYPE_CPUWORKER
:
3223 return connection_cpu_process_inbuf(conn
);
3224 case CONN_TYPE_CONTROL
:
3225 return connection_control_process_inbuf(TO_CONTROL_CONN(conn
));
3227 log_err(LD_BUG
,"got unexpected conn type %d.", conn
->type
);
3228 tor_fragile_assert();
3233 /** Called whenever we've written data on a connection. */
3235 connection_flushed_some(connection_t
*conn
)
3238 tor_assert(!conn
->in_flushed_some
);
3239 conn
->in_flushed_some
= 1;
3240 if (conn
->type
== CONN_TYPE_DIR
&&
3241 conn
->state
== DIR_CONN_STATE_SERVER_WRITING
) {
3242 r
= connection_dirserv_flushed_some(TO_DIR_CONN(conn
));
3243 } else if (conn
->type
== CONN_TYPE_OR
) {
3244 r
= connection_or_flushed_some(TO_OR_CONN(conn
));
3246 conn
->in_flushed_some
= 0;
3250 /** We just finished flushing bytes from conn-\>outbuf, and there
3251 * are no more bytes remaining.
3253 * This function just passes conn to the connection-specific
3254 * connection_*_finished_flushing() function.
3257 connection_finished_flushing(connection_t
*conn
)
3261 /* If the connection is closed, don't try to do anything more here. */
3262 if (CONN_IS_CLOSED(conn
))
3265 // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
3267 switch (conn
->type
) {
3269 return connection_or_finished_flushing(TO_OR_CONN(conn
));
3271 case CONN_TYPE_EXIT
:
3272 return connection_edge_finished_flushing(TO_EDGE_CONN(conn
));
3274 return connection_dir_finished_flushing(TO_DIR_CONN(conn
));
3275 case CONN_TYPE_CPUWORKER
:
3276 return connection_cpu_finished_flushing(conn
);
3277 case CONN_TYPE_CONTROL
:
3278 return connection_control_finished_flushing(TO_CONTROL_CONN(conn
));
3280 log_err(LD_BUG
,"got unexpected conn type %d.", conn
->type
);
3281 tor_fragile_assert();
3286 /** Called when our attempt to connect() to another server has just
3289 * This function just passes conn to the connection-specific
3290 * connection_*_finished_connecting() function.
3293 connection_finished_connecting(connection_t
*conn
)
3299 return connection_or_finished_connecting(TO_OR_CONN(conn
));
3300 case CONN_TYPE_EXIT
:
3301 return connection_edge_finished_connecting(TO_EDGE_CONN(conn
));
3303 return connection_dir_finished_connecting(TO_DIR_CONN(conn
));
3305 log_err(LD_BUG
,"got unexpected conn type %d.", conn
->type
);
3306 tor_fragile_assert();
3311 /** Callback: invoked when a connection reaches an EOF event. */
3313 connection_reached_eof(connection_t
*conn
)
3315 switch (conn
->type
) {
3317 return connection_or_reached_eof(TO_OR_CONN(conn
));
3319 case CONN_TYPE_EXIT
:
3320 return connection_edge_reached_eof(TO_EDGE_CONN(conn
));
3322 return connection_dir_reached_eof(TO_DIR_CONN(conn
));
3323 case CONN_TYPE_CPUWORKER
:
3324 return connection_cpu_reached_eof(conn
);
3325 case CONN_TYPE_CONTROL
:
3326 return connection_control_reached_eof(TO_CONTROL_CONN(conn
));
3328 log_err(LD_BUG
,"got unexpected conn type %d.", conn
->type
);
3329 tor_fragile_assert();
3334 /** Log how many bytes are used by buffers of different kinds and sizes. */
3336 connection_dump_buffer_mem_stats(int severity
)
3338 uint64_t used_by_type
[_CONN_TYPE_MAX
+1];
3339 uint64_t alloc_by_type
[_CONN_TYPE_MAX
+1];
3340 int n_conns_by_type
[_CONN_TYPE_MAX
+1];
3341 uint64_t total_alloc
= 0;
3342 uint64_t total_used
= 0;
3344 smartlist_t
*conns
= get_connection_array();
3346 memset(used_by_type
, 0, sizeof(used_by_type
));
3347 memset(alloc_by_type
, 0, sizeof(alloc_by_type
));
3348 memset(n_conns_by_type
, 0, sizeof(n_conns_by_type
));
3350 SMARTLIST_FOREACH(conns
, connection_t
*, c
,
3353 ++n_conns_by_type
[tp
];
3355 used_by_type
[tp
] += buf_datalen(c
->inbuf
);
3356 alloc_by_type
[tp
] += buf_allocation(c
->inbuf
);
3359 used_by_type
[tp
] += buf_datalen(c
->outbuf
);
3360 alloc_by_type
[tp
] += buf_allocation(c
->outbuf
);
3363 for (i
=0; i
<= _CONN_TYPE_MAX
; ++i
) {
3364 total_used
+= used_by_type
[i
];
3365 total_alloc
+= alloc_by_type
[i
];
3368 log(severity
, LD_GENERAL
,
3369 "In buffers for %d connections: "U64_FORMAT
" used/"U64_FORMAT
" allocated",
3370 smartlist_len(conns
),
3371 U64_PRINTF_ARG(total_used
), U64_PRINTF_ARG(total_alloc
));
3372 for (i
=_CONN_TYPE_MIN
; i
<= _CONN_TYPE_MAX
; ++i
) {
3373 if (!n_conns_by_type
[i
])
3375 log(severity
, LD_GENERAL
,
3376 " For %d %s connections: "U64_FORMAT
" used/"U64_FORMAT
" allocated",
3377 n_conns_by_type
[i
], conn_type_to_string(i
),
3378 U64_PRINTF_ARG(used_by_type
[i
]), U64_PRINTF_ARG(alloc_by_type
[i
]));
3382 /** Verify that connection <b>conn</b> has all of its invariants
3383 * correct. Trigger an assert if anything is invalid.
3386 assert_connection_ok(connection_t
*conn
, time_t now
)
3388 (void) now
; /* XXXX unused. */
3390 tor_assert(conn
->type
>= _CONN_TYPE_MIN
);
3391 tor_assert(conn
->type
<= _CONN_TYPE_MAX
);
3392 switch (conn
->type
) {
3394 tor_assert(conn
->magic
== OR_CONNECTION_MAGIC
);
3397 case CONN_TYPE_EXIT
:
3398 tor_assert(conn
->magic
== EDGE_CONNECTION_MAGIC
);
3401 tor_assert(conn
->magic
== DIR_CONNECTION_MAGIC
);
3403 case CONN_TYPE_CONTROL
:
3404 tor_assert(conn
->magic
== CONTROL_CONNECTION_MAGIC
);
3407 tor_assert(conn
->magic
== BASE_CONNECTION_MAGIC
);
3411 if (conn
->linked_conn
) {
3412 tor_assert(conn
->linked_conn
->linked_conn
== conn
);
3413 tor_assert(conn
->linked
);
3416 tor_assert(conn
->s
< 0);
3418 if (conn
->outbuf_flushlen
> 0) {
3419 tor_assert(connection_is_writing(conn
) || conn
->write_blocked_on_bw
||
3420 (CONN_IS_EDGE(conn
) && TO_EDGE_CONN(conn
)->edge_blocked_on_circ
));
3423 if (conn
->hold_open_until_flushed
)
3424 tor_assert(conn
->marked_for_close
);
3426 /* XXXX check: read_blocked_on_bw, write_blocked_on_bw, s, conn_array_index,
3427 * marked_for_close. */
3430 if (!connection_is_listener(conn
)) {
3431 assert_buf_ok(conn
->inbuf
);
3432 assert_buf_ok(conn
->outbuf
);
3435 if (conn
->type
== CONN_TYPE_OR
) {
3436 or_connection_t
*or_conn
= TO_OR_CONN(conn
);
3437 if (conn
->state
== OR_CONN_STATE_OPEN
) {
3438 /* tor_assert(conn->bandwidth > 0); */
3439 /* the above isn't necessarily true: if we just did a TLS
3440 * handshake but we didn't recognize the other peer, or it
3441 * gave a bad cert/etc, then we won't have assigned bandwidth,
3442 * yet it will be open. -RD
3444 // tor_assert(conn->read_bucket >= 0);
3446 // tor_assert(conn->addr && conn->port);
3447 tor_assert(conn
->address
);
3448 if (conn
->state
> OR_CONN_STATE_PROXY_HANDSHAKING
)
3449 tor_assert(or_conn
->tls
);
3452 if (CONN_IS_EDGE(conn
)) {
3453 edge_connection_t
*edge_conn
= TO_EDGE_CONN(conn
);
3454 if (edge_conn
->chosen_exit_optional
|| edge_conn
->chosen_exit_retries
) {
3455 tor_assert(conn
->type
== CONN_TYPE_AP
);
3456 tor_assert(edge_conn
->chosen_exit_name
);
3459 /* XXX unchecked: package window, deliver window. */
3460 if (conn
->type
== CONN_TYPE_AP
) {
3462 tor_assert(edge_conn
->socks_request
);
3463 if (conn
->state
== AP_CONN_STATE_OPEN
) {
3464 tor_assert(edge_conn
->socks_request
->has_finished
);
3465 if (!conn
->marked_for_close
) {
3466 tor_assert(edge_conn
->cpath_layer
);
3467 assert_cpath_layer_ok(edge_conn
->cpath_layer
);
3471 if (conn
->type
== CONN_TYPE_EXIT
) {
3472 tor_assert(conn
->purpose
== EXIT_PURPOSE_CONNECT
||
3473 conn
->purpose
== EXIT_PURPOSE_RESOLVE
);
3475 } else if (conn
->type
== CONN_TYPE_DIR
) {
3477 /* Purpose is only used for dir and exit types currently */
3478 tor_assert(!conn
->purpose
);
3483 case CONN_TYPE_OR_LISTENER
:
3484 case CONN_TYPE_AP_LISTENER
:
3485 case CONN_TYPE_AP_TRANS_LISTENER
:
3486 case CONN_TYPE_AP_NATD_LISTENER
:
3487 case CONN_TYPE_DIR_LISTENER
:
3488 case CONN_TYPE_CONTROL_LISTENER
:
3489 case CONN_TYPE_AP_DNS_LISTENER
:
3490 tor_assert(conn
->state
== LISTENER_STATE_READY
);
3493 tor_assert(conn
->state
>= _OR_CONN_STATE_MIN
);
3494 tor_assert(conn
->state
<= _OR_CONN_STATE_MAX
);
3495 tor_assert(TO_OR_CONN(conn
)->n_circuits
>= 0);
3497 case CONN_TYPE_EXIT
:
3498 tor_assert(conn
->state
>= _EXIT_CONN_STATE_MIN
);
3499 tor_assert(conn
->state
<= _EXIT_CONN_STATE_MAX
);
3500 tor_assert(conn
->purpose
>= _EXIT_PURPOSE_MIN
);
3501 tor_assert(conn
->purpose
<= _EXIT_PURPOSE_MAX
);
3504 tor_assert(conn
->state
>= _AP_CONN_STATE_MIN
);
3505 tor_assert(conn
->state
<= _AP_CONN_STATE_MAX
);
3506 tor_assert(TO_EDGE_CONN(conn
)->socks_request
);
3509 tor_assert(conn
->state
>= _DIR_CONN_STATE_MIN
);
3510 tor_assert(conn
->state
<= _DIR_CONN_STATE_MAX
);
3511 tor_assert(conn
->purpose
>= _DIR_PURPOSE_MIN
);
3512 tor_assert(conn
->purpose
<= _DIR_PURPOSE_MAX
);
3514 case CONN_TYPE_CPUWORKER
:
3515 tor_assert(conn
->state
>= _CPUWORKER_STATE_MIN
);
3516 tor_assert(conn
->state
<= _CPUWORKER_STATE_MAX
);
3518 case CONN_TYPE_CONTROL
:
3519 tor_assert(conn
->state
>= _CONTROL_CONN_STATE_MIN
);
3520 tor_assert(conn
->state
<= _CONTROL_CONN_STATE_MAX
);