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"
31 #include "rendclient.h"
32 #include "rendcommon.h"
35 static connection_t
*connection_create_listener(
36 struct sockaddr
*listensockaddr
,
37 socklen_t listensocklen
, int type
,
39 static void connection_init(time_t now
, connection_t
*conn
, int type
,
41 static int connection_init_accepted_conn(connection_t
*conn
,
42 uint8_t listener_type
);
43 static int connection_handle_listener_read(connection_t
*conn
, int new_type
);
44 static int connection_bucket_should_increase(int bucket
,
45 or_connection_t
*conn
);
46 static int connection_finished_flushing(connection_t
*conn
);
47 static int connection_flushed_some(connection_t
*conn
);
48 static int connection_finished_connecting(connection_t
*conn
);
49 static int connection_reached_eof(connection_t
*conn
);
50 static int connection_read_to_buf(connection_t
*conn
, int *max_to_read
,
52 static int connection_process_inbuf(connection_t
*conn
, int package_partial
);
53 static void client_check_address_changed(int sock
);
54 static void set_constrained_socket_buffers(int sock
, int size
);
56 static const char *connection_proxy_state_to_string(int state
);
57 static int connection_read_https_proxy_response(connection_t
*conn
);
58 static void connection_send_socks5_connect(connection_t
*conn
);
60 /** The last IPv4 address that our network interface seemed to have been
61 * binding to, in host order. We use this to detect when our IP changes. */
62 static uint32_t last_interface_ip
= 0;
63 /** A list of uint32_ts for addresses we've used in outgoing connections.
64 * Used to detect IP address changes. */
65 static smartlist_t
*outgoing_addrs
= NULL
;
67 /**************************************************************/
70 * Return the human-readable name for the connection type <b>type</b>
73 conn_type_to_string(int type
)
77 case CONN_TYPE_OR_LISTENER
: return "OR listener";
78 case CONN_TYPE_OR
: return "OR";
79 case CONN_TYPE_EXIT
: return "Exit";
80 case CONN_TYPE_AP_LISTENER
: return "Socks listener";
81 case CONN_TYPE_AP_TRANS_LISTENER
:
82 return "Transparent pf/netfilter listener";
83 case CONN_TYPE_AP_NATD_LISTENER
: return "Transparent natd listener";
84 case CONN_TYPE_AP_DNS_LISTENER
: return "DNS listener";
85 case CONN_TYPE_AP
: return "Socks";
86 case CONN_TYPE_DIR_LISTENER
: return "Directory listener";
87 case CONN_TYPE_DIR
: return "Directory";
88 case CONN_TYPE_CPUWORKER
: return "CPU worker";
89 case CONN_TYPE_CONTROL_LISTENER
: return "Control listener";
90 case CONN_TYPE_CONTROL
: return "Control";
92 log_warn(LD_BUG
, "unknown connection type %d", type
);
93 tor_snprintf(buf
, sizeof(buf
), "unknown [%d]", type
);
99 * Return the human-readable name for the connection state <b>state</b>
100 * for the connection type <b>type</b>
103 conn_state_to_string(int type
, int state
)
107 case CONN_TYPE_OR_LISTENER
:
108 case CONN_TYPE_AP_LISTENER
:
109 case CONN_TYPE_AP_TRANS_LISTENER
:
110 case CONN_TYPE_AP_NATD_LISTENER
:
111 case CONN_TYPE_AP_DNS_LISTENER
:
112 case CONN_TYPE_DIR_LISTENER
:
113 case CONN_TYPE_CONTROL_LISTENER
:
114 if (state
== LISTENER_STATE_READY
)
119 case OR_CONN_STATE_CONNECTING
: return "connect()ing";
120 case OR_CONN_STATE_PROXY_HANDSHAKING
: return "handshaking (proxy)";
121 case OR_CONN_STATE_TLS_HANDSHAKING
: return "handshaking (TLS)";
122 case OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING
:
123 return "renegotiating (TLS)";
124 case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING
:
125 return "waiting for renegotiation (TLS)";
126 case OR_CONN_STATE_OR_HANDSHAKING
: return "handshaking (Tor)";
127 case OR_CONN_STATE_OPEN
: return "open";
132 case EXIT_CONN_STATE_RESOLVING
: return "waiting for dest info";
133 case EXIT_CONN_STATE_CONNECTING
: return "connecting";
134 case EXIT_CONN_STATE_OPEN
: return "open";
135 case EXIT_CONN_STATE_RESOLVEFAILED
: return "resolve failed";
140 case AP_CONN_STATE_SOCKS_WAIT
: return "waiting for socks info";
141 case AP_CONN_STATE_NATD_WAIT
: return "waiting for natd dest info";
142 case AP_CONN_STATE_RENDDESC_WAIT
: return "waiting for rendezvous desc";
143 case AP_CONN_STATE_CONTROLLER_WAIT
: return "waiting for controller";
144 case AP_CONN_STATE_CIRCUIT_WAIT
: return "waiting for circuit";
145 case AP_CONN_STATE_CONNECT_WAIT
: return "waiting for connect response";
146 case AP_CONN_STATE_RESOLVE_WAIT
: return "waiting for resolve response";
147 case AP_CONN_STATE_OPEN
: return "open";
152 case DIR_CONN_STATE_CONNECTING
: return "connecting";
153 case DIR_CONN_STATE_CLIENT_SENDING
: return "client sending";
154 case DIR_CONN_STATE_CLIENT_READING
: return "client reading";
155 case DIR_CONN_STATE_CLIENT_FINISHED
: return "client finished";
156 case DIR_CONN_STATE_SERVER_COMMAND_WAIT
: return "waiting for command";
157 case DIR_CONN_STATE_SERVER_WRITING
: return "writing";
160 case CONN_TYPE_CPUWORKER
:
162 case CPUWORKER_STATE_IDLE
: return "idle";
163 case CPUWORKER_STATE_BUSY_ONION
: return "busy with onion";
166 case CONN_TYPE_CONTROL
:
168 case CONTROL_CONN_STATE_OPEN
: return "open (protocol v1)";
169 case CONTROL_CONN_STATE_NEEDAUTH
:
170 return "waiting for authentication (protocol v1)";
175 log_warn(LD_BUG
, "unknown connection state %d (type %d)", state
, type
);
176 tor_snprintf(buf
, sizeof(buf
),
177 "unknown state [%d] on unknown [%s] connection",
178 state
, conn_type_to_string(type
));
182 /** Allocate and return a new dir_connection_t, initialized as by
183 * connection_init(). */
185 dir_connection_new(int socket_family
)
187 dir_connection_t
*dir_conn
= tor_malloc_zero(sizeof(dir_connection_t
));
188 connection_init(time(NULL
), TO_CONN(dir_conn
), CONN_TYPE_DIR
, socket_family
);
192 /** Allocate and return a new or_connection_t, initialized as by
193 * connection_init(). */
195 or_connection_new(int socket_family
)
197 or_connection_t
*or_conn
= tor_malloc_zero(sizeof(or_connection_t
));
198 time_t now
= time(NULL
);
199 connection_init(now
, TO_CONN(or_conn
), CONN_TYPE_OR
, socket_family
);
201 or_conn
->timestamp_last_added_nonpadding
= time(NULL
);
202 or_conn
->next_circ_id
= crypto_rand_int(1<<15);
204 or_conn
->active_circuit_pqueue
= smartlist_create();
205 or_conn
->active_circuit_pqueue_last_recalibrated
= cell_ewma_get_tick();
210 /** Allocate and return a new edge_connection_t, initialized as by
211 * connection_init(). */
213 edge_connection_new(int type
, int socket_family
)
215 edge_connection_t
*edge_conn
= tor_malloc_zero(sizeof(edge_connection_t
));
216 tor_assert(type
== CONN_TYPE_EXIT
|| type
== CONN_TYPE_AP
);
217 connection_init(time(NULL
), TO_CONN(edge_conn
), type
, socket_family
);
218 if (type
== CONN_TYPE_AP
)
219 edge_conn
->socks_request
= tor_malloc_zero(sizeof(socks_request_t
));
223 /** Allocate and return a new control_connection_t, initialized as by
224 * connection_init(). */
225 control_connection_t
*
226 control_connection_new(int socket_family
)
228 control_connection_t
*control_conn
=
229 tor_malloc_zero(sizeof(control_connection_t
));
230 connection_init(time(NULL
),
231 TO_CONN(control_conn
), CONN_TYPE_CONTROL
, socket_family
);
232 log_notice(LD_CONTROL
, "New control connection opened.");
236 /** Allocate, initialize, and return a new connection_t subtype of <b>type</b>
237 * to make or receive connections of address family <b>socket_family</b>. The
238 * type should be one of the CONN_TYPE_* constants. */
240 connection_new(int type
, int socket_family
)
244 return TO_CONN(or_connection_new(socket_family
));
248 return TO_CONN(edge_connection_new(type
, socket_family
));
251 return TO_CONN(dir_connection_new(socket_family
));
253 case CONN_TYPE_CONTROL
:
254 return TO_CONN(control_connection_new(socket_family
));
257 connection_t
*conn
= tor_malloc_zero(sizeof(connection_t
));
258 connection_init(time(NULL
), conn
, type
, socket_family
);
264 /** Initializes conn. (you must call connection_add() to link it into the main
267 * Set conn-\>type to <b>type</b>. Set conn-\>s and conn-\>conn_array_index to
268 * -1 to signify they are not yet assigned.
270 * If conn is not a listener type, allocate buffers for it. If it's
271 * an AP type, allocate space to store the socks_request.
273 * Assign a pseudorandom next_circ_id between 0 and 2**15.
275 * Initialize conn's timestamps to now.
278 connection_init(time_t now
, connection_t
*conn
, int type
, int socket_family
)
280 static uint64_t n_connections_allocated
= 1;
284 conn
->magic
= OR_CONNECTION_MAGIC
;
288 conn
->magic
= EDGE_CONNECTION_MAGIC
;
291 conn
->magic
= DIR_CONNECTION_MAGIC
;
293 case CONN_TYPE_CONTROL
:
294 conn
->magic
= CONTROL_CONNECTION_MAGIC
;
297 conn
->magic
= BASE_CONNECTION_MAGIC
;
301 conn
->s
= -1; /* give it a default of 'not used' */
302 conn
->conn_array_index
= -1; /* also default to 'not used' */
303 conn
->global_identifier
= n_connections_allocated
++;
306 conn
->socket_family
= socket_family
;
307 if (!connection_is_listener(conn
)) { /* listeners never use their buf */
308 conn
->inbuf
= buf_new();
309 conn
->outbuf
= buf_new();
312 conn
->timestamp_created
= now
;
313 conn
->timestamp_lastread
= now
;
314 conn
->timestamp_lastwritten
= now
;
317 /** Create a link between <b>conn_a</b> and <b>conn_b</b>. */
319 connection_link_connections(connection_t
*conn_a
, connection_t
*conn_b
)
321 tor_assert(conn_a
->s
< 0);
322 tor_assert(conn_b
->s
< 0);
326 conn_a
->linked_conn
= conn_b
;
327 conn_b
->linked_conn
= conn_a
;
330 /** Deallocate memory used by <b>conn</b>. Deallocate its buffers if
331 * necessary, close its socket if necessary, and mark the directory as dirty
332 * if <b>conn</b> is an OR or OP connection.
335 _connection_free(connection_t
*conn
)
342 switch (conn
->type
) {
344 tor_assert(conn
->magic
== OR_CONNECTION_MAGIC
);
345 mem
= TO_OR_CONN(conn
);
346 memlen
= sizeof(or_connection_t
);
350 tor_assert(conn
->magic
== EDGE_CONNECTION_MAGIC
);
351 mem
= TO_EDGE_CONN(conn
);
352 memlen
= sizeof(edge_connection_t
);
355 tor_assert(conn
->magic
== DIR_CONNECTION_MAGIC
);
356 mem
= TO_DIR_CONN(conn
);
357 memlen
= sizeof(dir_connection_t
);
359 case CONN_TYPE_CONTROL
:
360 tor_assert(conn
->magic
== CONTROL_CONNECTION_MAGIC
);
361 mem
= TO_CONTROL_CONN(conn
);
362 memlen
= sizeof(control_connection_t
);
365 tor_assert(conn
->magic
== BASE_CONNECTION_MAGIC
);
367 memlen
= sizeof(connection_t
);
372 log_info(LD_GENERAL
, "Freeing linked %s connection [%s] with %d "
373 "bytes on inbuf, %d on outbuf.",
374 conn_type_to_string(conn
->type
),
375 conn_state_to_string(conn
->type
, conn
->state
),
376 (int)buf_datalen(conn
->inbuf
), (int)buf_datalen(conn
->outbuf
));
379 if (!connection_is_listener(conn
)) {
380 buf_free(conn
->inbuf
);
381 buf_free(conn
->outbuf
);
383 if (conn
->socket_family
== AF_UNIX
) {
384 /* For now only control ports can be Unix domain sockets
385 * and listeners at the same time */
386 tor_assert(conn
->type
== CONN_TYPE_CONTROL_LISTENER
);
388 if (unlink(conn
->address
) < 0 && errno
!= ENOENT
) {
389 log_warn(LD_NET
, "Could not unlink %s: %s", conn
->address
,
395 tor_free(conn
->address
);
397 if (connection_speaks_cells(conn
)) {
398 or_connection_t
*or_conn
= TO_OR_CONN(conn
);
399 tor_tls_free(or_conn
->tls
);
401 or_handshake_state_free(or_conn
->handshake_state
);
402 or_conn
->handshake_state
= NULL
;
403 smartlist_free(or_conn
->active_circuit_pqueue
);
404 tor_free(or_conn
->nickname
);
406 if (CONN_IS_EDGE(conn
)) {
407 edge_connection_t
*edge_conn
= TO_EDGE_CONN(conn
);
408 tor_free(edge_conn
->chosen_exit_name
);
409 if (edge_conn
->socks_request
) {
410 memset(edge_conn
->socks_request
, 0xcc, sizeof(socks_request_t
));
411 tor_free(edge_conn
->socks_request
);
414 rend_data_free(edge_conn
->rend_data
);
416 if (conn
->type
== CONN_TYPE_CONTROL
) {
417 control_connection_t
*control_conn
= TO_CONTROL_CONN(conn
);
418 tor_free(control_conn
->incoming_cmd
);
421 tor_free(conn
->read_event
); /* Probably already freed by connection_free. */
422 tor_free(conn
->write_event
); /* Probably already freed by connection_free. */
424 if (conn
->type
== CONN_TYPE_DIR
) {
425 dir_connection_t
*dir_conn
= TO_DIR_CONN(conn
);
426 tor_free(dir_conn
->requested_resource
);
428 tor_zlib_free(dir_conn
->zlib_state
);
429 if (dir_conn
->fingerprint_stack
) {
430 SMARTLIST_FOREACH(dir_conn
->fingerprint_stack
, char *, cp
, tor_free(cp
));
431 smartlist_free(dir_conn
->fingerprint_stack
);
434 cached_dir_decref(dir_conn
->cached_dir
);
435 rend_data_free(dir_conn
->rend_data
);
439 log_debug(LD_NET
,"closing fd %d.",conn
->s
);
440 tor_close_socket(conn
->s
);
444 if (conn
->type
== CONN_TYPE_OR
&&
445 !tor_digest_is_zero(TO_OR_CONN(conn
)->identity_digest
)) {
446 log_warn(LD_BUG
, "called on OR conn with non-zeroed identity_digest");
447 connection_or_remove_from_identity_map(TO_OR_CONN(conn
));
450 memset(mem
, 0xCC, memlen
); /* poison memory */
454 /** Make sure <b>conn</b> isn't in any of the global conn lists; then free it.
457 connection_free(connection_t
*conn
)
461 tor_assert(!connection_is_on_closeable_list(conn
));
462 tor_assert(!connection_in_array(conn
));
463 if (conn
->linked_conn
) {
464 log_err(LD_BUG
, "Called with conn->linked_conn still set.");
465 tor_fragile_assert();
466 conn
->linked_conn
->linked_conn
= NULL
;
467 if (! conn
->linked_conn
->marked_for_close
&&
468 conn
->linked_conn
->reading_from_linked_conn
)
469 connection_start_reading(conn
->linked_conn
);
470 conn
->linked_conn
= NULL
;
472 if (connection_speaks_cells(conn
)) {
473 if (!tor_digest_is_zero(TO_OR_CONN(conn
)->identity_digest
)) {
474 connection_or_remove_from_identity_map(TO_OR_CONN(conn
));
477 if (conn
->type
== CONN_TYPE_CONTROL
) {
478 TO_CONTROL_CONN(conn
)->event_mask
= 0;
479 control_update_global_event_mask();
481 connection_unregister_events(conn
);
482 _connection_free(conn
);
485 /** Call _connection_free() on every connection in our array, and release all
486 * storage held by connection.c. This is used by cpuworkers and dnsworkers
487 * when they fork, so they don't keep resources held open (especially
490 * Don't do the checks in connection_free(), because they will
494 connection_free_all(void)
496 smartlist_t
*conns
= get_connection_array();
498 /* We don't want to log any messages to controllers. */
499 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
500 if (conn
->type
== CONN_TYPE_CONTROL
)
501 TO_CONTROL_CONN(conn
)->event_mask
= 0);
503 control_update_global_event_mask();
505 /* Unlink everything from the identity map. */
506 connection_or_clear_identity_map();
508 SMARTLIST_FOREACH(conns
, connection_t
*, conn
, _connection_free(conn
));
510 if (outgoing_addrs
) {
511 SMARTLIST_FOREACH(outgoing_addrs
, void*, addr
, tor_free(addr
));
512 smartlist_free(outgoing_addrs
);
513 outgoing_addrs
= NULL
;
517 /** Do any cleanup needed:
518 * - Directory conns that failed to fetch a rendezvous descriptor
519 * need to inform pending rendezvous streams.
520 * - OR conns need to call rep_hist_note_*() to record status.
521 * - AP conns need to send a socks reject if necessary.
522 * - Exit conns need to call connection_dns_remove() if necessary.
523 * - AP and Exit conns need to send an end cell if they can.
524 * - DNS conns need to fail any resolves that are pending on them.
525 * - OR and edge connections need to be unlinked from circuits.
528 connection_about_to_close_connection(connection_t
*conn
)
531 dir_connection_t
*dir_conn
;
532 or_connection_t
*or_conn
;
533 edge_connection_t
*edge_conn
;
534 time_t now
= time(NULL
);
536 tor_assert(conn
->marked_for_close
);
538 if (CONN_IS_EDGE(conn
)) {
539 edge_conn
= TO_EDGE_CONN(conn
);
540 if (!edge_conn
->edge_has_sent_end
) {
541 log_warn(LD_BUG
, "(Harmless.) Edge connection (marked at %s:%d) "
542 "hasn't sent end yet?",
543 conn
->marked_for_close_file
, conn
->marked_for_close
);
544 tor_fragile_assert();
548 switch (conn
->type
) {
550 dir_conn
= TO_DIR_CONN(conn
);
551 if (conn
->state
< DIR_CONN_STATE_CLIENT_FINISHED
) {
552 /* It's a directory connection and connecting or fetching
553 * failed: forget about this router, and maybe try again. */
554 connection_dir_request_failed(dir_conn
);
556 /* If we were trying to fetch a v2 rend desc and did not succeed,
557 * retry as needed. (If a fetch is successful, the connection state
558 * is changed to DIR_PURPOSE_HAS_FETCHED_RENDDESC to mark that
559 * refetching is unnecessary.) */
560 if (conn
->purpose
== DIR_PURPOSE_FETCH_RENDDESC_V2
&&
561 dir_conn
->rend_data
&&
562 strlen(dir_conn
->rend_data
->onion_address
) ==
563 REND_SERVICE_ID_LEN_BASE32
)
564 rend_client_refetch_v2_renddesc(dir_conn
->rend_data
);
567 or_conn
= TO_OR_CONN(conn
);
568 /* Remember why we're closing this connection. */
569 if (conn
->state
!= OR_CONN_STATE_OPEN
) {
570 /* Inform any pending (not attached) circs that they should
572 circuit_n_conn_done(TO_OR_CONN(conn
), 0);
573 /* now mark things down as needed */
574 if (connection_or_nonopen_was_started_here(or_conn
)) {
575 or_options_t
*options
= get_options();
576 rep_hist_note_connect_failed(or_conn
->identity_digest
, now
);
577 entry_guard_register_connect_status(or_conn
->identity_digest
,0,
578 !options
->HttpsProxy
, now
);
579 if (conn
->state
>= OR_CONN_STATE_TLS_HANDSHAKING
) {
580 int reason
= tls_error_to_orconn_end_reason(or_conn
->tls_error
);
581 control_event_or_conn_status(or_conn
, OR_CONN_EVENT_FAILED
,
583 if (!authdir_mode_tests_reachability(options
))
584 control_event_bootstrap_problem(
585 orconn_end_reason_to_control_string(reason
), reason
);
588 } else if (conn
->hold_open_until_flushed
) {
589 /* We only set hold_open_until_flushed when we're intentionally
590 * closing a connection. */
591 rep_hist_note_disconnect(or_conn
->identity_digest
, now
);
592 control_event_or_conn_status(or_conn
, OR_CONN_EVENT_CLOSED
,
593 tls_error_to_orconn_end_reason(or_conn
->tls_error
));
594 } else if (!tor_digest_is_zero(or_conn
->identity_digest
)) {
595 rep_hist_note_connection_died(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
));
599 /* Now close all the attached circuits on it. */
600 circuit_unlink_all_from_or_conn(TO_OR_CONN(conn
),
601 END_CIRC_REASON_OR_CONN_CLOSED
);
604 edge_conn
= TO_EDGE_CONN(conn
);
605 if (edge_conn
->socks_request
->has_finished
== 0) {
606 /* since conn gets removed right after this function finishes,
607 * there's no point trying to send back a reply at this point. */
608 log_warn(LD_BUG
,"Closing stream (marked at %s:%d) without sending"
609 " back a socks reply.",
610 conn
->marked_for_close_file
, conn
->marked_for_close
);
612 if (!edge_conn
->end_reason
) {
613 log_warn(LD_BUG
,"Closing stream (marked at %s:%d) without having"
615 conn
->marked_for_close_file
, conn
->marked_for_close
);
617 if (edge_conn
->dns_server_request
) {
618 log_warn(LD_BUG
,"Closing stream (marked at %s:%d) without having"
619 " replied to DNS request.",
620 conn
->marked_for_close_file
, conn
->marked_for_close
);
621 dnsserv_reject_request(edge_conn
);
623 control_event_stream_bandwidth(edge_conn
);
624 control_event_stream_status(edge_conn
, STREAM_EVENT_CLOSED
,
625 edge_conn
->end_reason
);
626 circ
= circuit_get_by_edge_conn(edge_conn
);
628 circuit_detach_stream(circ
, edge_conn
);
631 edge_conn
= TO_EDGE_CONN(conn
);
632 circ
= circuit_get_by_edge_conn(edge_conn
);
634 circuit_detach_stream(circ
, edge_conn
);
635 if (conn
->state
== EXIT_CONN_STATE_RESOLVING
) {
636 connection_dns_remove(edge_conn
);
642 /** Return true iff connection_close_immediate() has been called on this
644 #define CONN_IS_CLOSED(c) \
645 ((c)->linked ? ((c)->linked_conn_is_closed) : ((c)->s < 0))
647 /** Close the underlying socket for <b>conn</b>, so we don't try to
648 * flush it. Must be used in conjunction with (right before)
649 * connection_mark_for_close().
652 connection_close_immediate(connection_t
*conn
)
654 assert_connection_ok(conn
,0);
655 if (CONN_IS_CLOSED(conn
)) {
656 log_err(LD_BUG
,"Attempt to close already-closed connection.");
657 tor_fragile_assert();
660 if (conn
->outbuf_flushlen
) {
661 log_info(LD_NET
,"fd %d, type %s, state %s, %d bytes on outbuf.",
662 conn
->s
, conn_type_to_string(conn
->type
),
663 conn_state_to_string(conn
->type
, conn
->state
),
664 (int)conn
->outbuf_flushlen
);
667 connection_unregister_events(conn
);
670 tor_close_socket(conn
->s
);
673 conn
->linked_conn_is_closed
= 1;
674 if (!connection_is_listener(conn
)) {
675 buf_clear(conn
->outbuf
);
676 conn
->outbuf_flushlen
= 0;
680 /** Mark <b>conn</b> to be closed next time we loop through
681 * conn_close_if_marked() in main.c. */
683 _connection_mark_for_close(connection_t
*conn
, int line
, const char *file
)
685 assert_connection_ok(conn
,0);
687 tor_assert(line
< 1<<16); /* marked_for_close can only fit a uint16_t. */
690 if (conn
->marked_for_close
) {
691 log(LOG_WARN
,LD_BUG
,"Duplicate call to connection_mark_for_close at %s:%d"
692 " (first at %s:%d)", file
, line
, conn
->marked_for_close_file
,
693 conn
->marked_for_close
);
694 tor_fragile_assert();
698 conn
->marked_for_close
= line
;
699 conn
->marked_for_close_file
= file
;
700 add_connection_to_closeable_list(conn
);
702 /* in case we're going to be held-open-til-flushed, reset
703 * the number of seconds since last successful write, so
704 * we get our whole 15 seconds */
705 conn
->timestamp_lastwritten
= time(NULL
);
708 /** Find each connection that has hold_open_until_flushed set to
709 * 1 but hasn't written in the past 15 seconds, and set
710 * hold_open_until_flushed to 0. This means it will get cleaned
711 * up in the next loop through close_if_marked() in main.c.
714 connection_expire_held_open(void)
717 smartlist_t
*conns
= get_connection_array();
721 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
723 /* If we've been holding the connection open, but we haven't written
726 if (conn
->hold_open_until_flushed
) {
727 tor_assert(conn
->marked_for_close
);
728 if (now
- conn
->timestamp_lastwritten
>= 15) {
730 if (conn
->type
== CONN_TYPE_EXIT
||
731 (conn
->type
== CONN_TYPE_DIR
&&
732 conn
->purpose
== DIR_PURPOSE_SERVER
))
735 severity
= LOG_NOTICE
;
736 log_fn(severity
, LD_NET
,
737 "Giving up on marked_for_close conn that's been flushing "
738 "for 15s (fd %d, type %s, state %s).",
739 conn
->s
, conn_type_to_string(conn
->type
),
740 conn_state_to_string(conn
->type
, conn
->state
));
741 conn
->hold_open_until_flushed
= 0;
747 /** Create an AF_INET listenaddr struct.
748 * <b>listenaddress</b> provides the host and optionally the port information
749 * for the new structure. If no port is provided in <b>listenaddress</b> then
750 * <b>listenport</b> is used.
752 * If not NULL <b>readable_address</b> will contain a copy of the host part of
753 * <b>listenaddress</b>.
755 * The listenaddr struct has to be freed by the caller.
757 static struct sockaddr_in
*
758 create_inet_sockaddr(const char *listenaddress
, uint16_t listenport
,
759 char **readable_address
, socklen_t
*socklen_out
) {
760 struct sockaddr_in
*listenaddr
= NULL
;
762 uint16_t usePort
= 0;
764 if (parse_addr_port(LOG_WARN
,
765 listenaddress
, readable_address
, &addr
, &usePort
)<0) {
767 "Error parsing/resolving ListenAddress %s", listenaddress
);
771 usePort
= listenport
;
773 listenaddr
= tor_malloc_zero(sizeof(struct sockaddr_in
));
774 listenaddr
->sin_addr
.s_addr
= htonl(addr
);
775 listenaddr
->sin_family
= AF_INET
;
776 listenaddr
->sin_port
= htons((uint16_t) usePort
);
778 *socklen_out
= sizeof(struct sockaddr_in
);
783 tor_free(listenaddr
);
788 /** Create an AF_UNIX listenaddr struct.
789 * <b>listenaddress</b> provides the path to the Unix socket.
791 * Eventually <b>listenaddress</b> will also optionally contain user, group,
792 * and file permissions for the new socket. But not yet. XXX
793 * Also, since we do not create the socket here the information doesn't help
796 * If not NULL <b>readable_address</b> will contain a copy of the path part of
797 * <b>listenaddress</b>.
799 * The listenaddr struct has to be freed by the caller.
801 static struct sockaddr_un
*
802 create_unix_sockaddr(const char *listenaddress
, char **readable_address
,
805 struct sockaddr_un
*sockaddr
= NULL
;
807 sockaddr
= tor_malloc_zero(sizeof(struct sockaddr_un
));
808 sockaddr
->sun_family
= AF_UNIX
;
809 strncpy(sockaddr
->sun_path
, listenaddress
, sizeof(sockaddr
->sun_path
));
811 if (readable_address
)
812 *readable_address
= tor_strdup(listenaddress
);
814 *len_out
= sizeof(struct sockaddr_un
);
818 static struct sockaddr
*
819 create_unix_sockaddr(const char *listenaddress
, char **readable_address
,
823 (void)readable_address
;
824 log_fn(LOG_ERR
, LD_BUG
,
825 "Unix domain sockets not supported, yet we tried to create one.");
829 #endif /* HAVE_SYS_UN_H */
831 /** Warn that an accept or a connect has failed because we're running up
832 * against our ulimit. Rate-limit these warnings so that we don't spam
835 warn_too_many_conns(void)
837 #define WARN_TOO_MANY_CONNS_INTERVAL (6*60*60)
838 static time_t last_warned
= 0;
839 time_t now
= time(NULL
);
840 int n_conns
= get_n_open_sockets();
841 if (last_warned
+ WARN_TOO_MANY_CONNS_INTERVAL
< now
) {
842 log_warn(LD_NET
,"Failing because we have %d connections already. Please "
843 "raise your ulimit -n.", n_conns
);
845 control_event_general_status(LOG_WARN
, "TOO_MANY_CONNECTIONS CURRENT=%d",
850 /** Bind a new non-blocking socket listening to the socket described
851 * by <b>listensockaddr</b>.
853 * <b>address</b> is only used for logging purposes and to add the information
856 static connection_t
*
857 connection_create_listener(struct sockaddr
*listensockaddr
, socklen_t socklen
,
858 int type
, char* address
)
861 int s
; /* the socket we're going to make */
862 uint16_t usePort
= 0;
863 int start_reading
= 0;
865 if (get_n_open_sockets() >= get_options()->_ConnLimit
-1) {
866 warn_too_many_conns();
870 if (listensockaddr
->sa_family
== AF_INET
) {
871 int is_tcp
= (type
!= CONN_TYPE_AP_DNS_LISTENER
);
878 usePort
= ntohs( (uint16_t)
879 ((struct sockaddr_in
*)listensockaddr
)->sin_port
);
881 log_notice(LD_NET
, "Opening %s on %s:%d",
882 conn_type_to_string(type
), address
, usePort
);
884 s
= tor_open_socket(PF_INET
,
885 is_tcp
? SOCK_STREAM
: SOCK_DGRAM
,
886 is_tcp
? IPPROTO_TCP
: IPPROTO_UDP
);
888 log_warn(LD_NET
,"Socket creation failed.");
893 /* REUSEADDR on normal places means you can rebind to the port
894 * right after somebody else has let it go. But REUSEADDR on win32
895 * means you can bind to the port _even when somebody else
896 * already has it bound_. So, don't do that on Win32. */
897 setsockopt(s
, SOL_SOCKET
, SO_REUSEADDR
, (void*) &one
,
898 (socklen_t
)sizeof(one
));
901 if (bind(s
,listensockaddr
,socklen
) < 0) {
902 const char *helpfulhint
= "";
903 int e
= tor_socket_errno(s
);
904 if (ERRNO_IS_EADDRINUSE(e
))
905 helpfulhint
= ". Is Tor already running?";
906 log_warn(LD_NET
, "Could not bind to %s:%u: %s%s", address
, usePort
,
907 tor_socket_strerror(e
), helpfulhint
);
913 if (listen(s
,SOMAXCONN
) < 0) {
914 log_warn(LD_NET
, "Could not listen on %s:%u: %s", address
, usePort
,
915 tor_socket_strerror(tor_socket_errno(s
)));
921 } else if (listensockaddr
->sa_family
== AF_UNIX
) {
924 /* For now only control ports can be Unix domain sockets
925 * and listeners at the same time */
926 tor_assert(type
== CONN_TYPE_CONTROL_LISTENER
);
928 log_notice(LD_NET
, "Opening %s on %s",
929 conn_type_to_string(type
), address
);
931 if (unlink(address
) < 0 && errno
!= ENOENT
) {
932 log_warn(LD_NET
, "Could not unlink %s: %s", address
,
936 s
= tor_open_socket(AF_UNIX
, SOCK_STREAM
, 0);
938 log_warn(LD_NET
,"Socket creation failed: %s.", strerror(errno
));
942 if (bind(s
, listensockaddr
, (socklen_t
)sizeof(struct sockaddr_un
)) == -1) {
943 log_warn(LD_NET
,"Bind to %s failed: %s.", address
,
944 tor_socket_strerror(tor_socket_errno(s
)));
948 if (listen(s
,SOMAXCONN
) < 0) {
949 log_warn(LD_NET
, "Could not listen on %s: %s", address
,
950 tor_socket_strerror(tor_socket_errno(s
)));
954 #endif /* HAVE_SYS_UN_H */
956 log_err(LD_BUG
,"Got unexpected address family %d.",
957 listensockaddr
->sa_family
);
961 set_socket_nonblocking(s
);
963 conn
= connection_new(type
, listensockaddr
->sa_family
);
964 conn
->socket_family
= listensockaddr
->sa_family
;
966 conn
->address
= tor_strdup(address
);
967 conn
->port
= usePort
;
969 if (connection_add(conn
) < 0) { /* no space, forget it */
970 log_warn(LD_NET
,"connection_add for listener failed. Giving up.");
971 connection_free(conn
);
975 log_debug(LD_NET
,"%s listening on port %u.",
976 conn_type_to_string(type
), usePort
);
978 conn
->state
= LISTENER_STATE_READY
;
980 connection_start_reading(conn
);
982 tor_assert(type
== CONN_TYPE_AP_DNS_LISTENER
);
983 dnsserv_configure_listener(conn
);
992 /** Do basic sanity checking on a newly received socket. Return 0
993 * if it looks ok, else return -1. */
995 check_sockaddr(struct sockaddr
*sa
, int len
, int level
)
999 if (sa
->sa_family
== AF_INET
) {
1000 struct sockaddr_in
*sin
=(struct sockaddr_in
*)sa
;
1001 if (len
!= sizeof(struct sockaddr_in
)) {
1002 log_fn(level
, LD_NET
, "Length of address not as expected: %d vs %d",
1003 len
,(int)sizeof(struct sockaddr_in
));
1006 if (sin
->sin_addr
.s_addr
== 0 || sin
->sin_port
== 0) {
1007 log_fn(level
, LD_NET
,
1008 "Address for new connection has address/port equal to zero.");
1011 } else if (sa
->sa_family
== AF_INET6
) {
1012 struct sockaddr_in6
*sin6
=(struct sockaddr_in6
*)sa
;
1013 if (len
!= sizeof(struct sockaddr_in6
)) {
1014 log_fn(level
, LD_NET
, "Length of address not as expected: %d vs %d",
1015 len
,(int)sizeof(struct sockaddr_in6
));
1018 if (tor_mem_is_zero((void*)sin6
->sin6_addr
.s6_addr
, 16) ||
1019 sin6
->sin6_port
== 0) {
1020 log_fn(level
, LD_NET
,
1021 "Address for new connection has address/port equal to zero.");
1030 /** Check whether the socket family from an accepted socket <b>got</b> is the
1031 * same as the one that <b>listener</b> is waiting for. If it isn't, log
1032 * a useful message and return -1. Else return 0.
1034 * This is annoying, but can apparently happen on some Darwins. */
1036 check_sockaddr_family_match(sa_family_t got
, connection_t
*listener
)
1038 if (got
!= listener
->socket_family
) {
1039 log_info(LD_BUG
, "A listener connection returned a socket with a "
1040 "mismatched family. %s for addr_family %d gave us a socket "
1041 "with address family %d. Dropping.",
1042 conn_type_to_string(listener
->type
),
1043 (int)listener
->socket_family
,
1050 /** The listener connection <b>conn</b> told poll() it wanted to read.
1051 * Call accept() on conn-\>s, and add the new connection if necessary.
1054 connection_handle_listener_read(connection_t
*conn
, int new_type
)
1056 int news
; /* the new socket */
1057 connection_t
*newconn
;
1058 /* information about the remote peer when connecting to other routers */
1060 struct sockaddr
*remote
= (struct sockaddr
*)addrbuf
;
1061 /* length of the remote address. Must be whatever accept() needs. */
1062 socklen_t remotelen
= (socklen_t
)sizeof(addrbuf
);
1063 or_options_t
*options
= get_options();
1065 tor_assert((size_t)remotelen
>= sizeof(struct sockaddr_in
));
1066 memset(addrbuf
, 0, sizeof(addrbuf
));
1068 news
= tor_accept_socket(conn
->s
,remote
,&remotelen
);
1069 if (news
< 0) { /* accept() error */
1070 int e
= tor_socket_errno(conn
->s
);
1071 if (ERRNO_IS_ACCEPT_EAGAIN(e
)) {
1072 return 0; /* he hung up before we could accept(). that's fine. */
1073 } else if (ERRNO_IS_ACCEPT_RESOURCE_LIMIT(e
)) {
1074 warn_too_many_conns();
1077 /* else there was a real error. */
1078 log_warn(LD_NET
,"accept() failed: %s. Closing listener.",
1079 tor_socket_strerror(e
));
1080 connection_mark_for_close(conn
);
1084 "Connection accepted on socket %d (child of fd %d).",
1087 set_socket_nonblocking(news
);
1089 if (options
->ConstrainedSockets
)
1090 set_constrained_socket_buffers(news
, (int)options
->ConstrainedSockSize
);
1092 if (check_sockaddr_family_match(remote
->sa_family
, conn
) < 0) {
1093 tor_close_socket(news
);
1097 if (conn
->socket_family
== AF_INET
|| conn
->socket_family
== AF_INET6
) {
1100 if (check_sockaddr(remote
, remotelen
, LOG_INFO
)<0) {
1102 "accept() returned a strange address; trying getsockname().");
1103 remotelen
=sizeof(addrbuf
);
1104 memset(addrbuf
, 0, sizeof(addrbuf
));
1105 if (getsockname(news
, remote
, &remotelen
)<0) {
1106 int e
= tor_socket_errno(news
);
1107 log_warn(LD_NET
, "getsockname() for new connection failed: %s",
1108 tor_socket_strerror(e
));
1110 if (check_sockaddr((struct sockaddr
*)addrbuf
, remotelen
,
1112 log_warn(LD_NET
,"Something's wrong with this conn. Closing it.");
1113 tor_close_socket(news
);
1119 if (check_sockaddr_family_match(remote
->sa_family
, conn
) < 0) {
1120 tor_close_socket(news
);
1124 tor_addr_from_sockaddr(&addr
, remote
, &port
);
1126 /* process entrance policies here, before we even create the connection */
1127 if (new_type
== CONN_TYPE_AP
) {
1128 /* check sockspolicy to see if we should accept it */
1129 if (socks_policy_permits_address(&addr
) == 0) {
1131 "Denying socks connection from untrusted address %s.",
1133 tor_close_socket(news
);
1137 if (new_type
== CONN_TYPE_DIR
) {
1138 /* check dirpolicy to see if we should accept it */
1139 if (dir_policy_permits_address(&addr
) == 0) {
1140 log_notice(LD_DIRSERV
,"Denying dir connection from address %s.",
1142 tor_close_socket(news
);
1147 newconn
= connection_new(new_type
, conn
->socket_family
);
1150 /* remember the remote address */
1151 tor_addr_copy(&newconn
->addr
, &addr
);
1152 newconn
->port
= port
;
1153 newconn
->address
= tor_dup_addr(&addr
);
1155 } else if (conn
->socket_family
== AF_UNIX
) {
1156 /* For now only control ports can be Unix domain sockets
1157 * and listeners at the same time */
1158 tor_assert(conn
->type
== CONN_TYPE_CONTROL_LISTENER
);
1160 newconn
= connection_new(new_type
, conn
->socket_family
);
1163 /* remember the remote address -- do we have anything sane to put here? */
1164 tor_addr_make_unspec(&newconn
->addr
);
1166 newconn
->address
= tor_strdup(conn
->address
);
1171 if (connection_add(newconn
) < 0) { /* no space, forget it */
1172 connection_free(newconn
);
1173 return 0; /* no need to tear down the parent */
1176 if (connection_init_accepted_conn(newconn
, conn
->type
) < 0) {
1177 connection_mark_for_close(newconn
);
1183 /** Initialize states for newly accepted connection <b>conn</b>.
1184 * If conn is an OR, start the TLS handshake.
1185 * If conn is a transparent AP, get its original destination
1186 * and place it in circuit_wait.
1189 connection_init_accepted_conn(connection_t
*conn
, uint8_t listener_type
)
1191 connection_start_reading(conn
);
1193 switch (conn
->type
) {
1195 control_event_or_conn_status(TO_OR_CONN(conn
), OR_CONN_EVENT_NEW
, 0);
1196 return connection_tls_start_handshake(TO_OR_CONN(conn
), 1);
1198 switch (listener_type
) {
1199 case CONN_TYPE_AP_LISTENER
:
1200 conn
->state
= AP_CONN_STATE_SOCKS_WAIT
;
1202 case CONN_TYPE_AP_TRANS_LISTENER
:
1203 conn
->state
= AP_CONN_STATE_CIRCUIT_WAIT
;
1204 return connection_ap_process_transparent(TO_EDGE_CONN(conn
));
1205 case CONN_TYPE_AP_NATD_LISTENER
:
1206 conn
->state
= AP_CONN_STATE_NATD_WAIT
;
1211 conn
->purpose
= DIR_PURPOSE_SERVER
;
1212 conn
->state
= DIR_CONN_STATE_SERVER_COMMAND_WAIT
;
1214 case CONN_TYPE_CONTROL
:
1215 conn
->state
= CONTROL_CONN_STATE_NEEDAUTH
;
1221 /** Take conn, make a nonblocking socket; try to connect to
1222 * addr:port (they arrive in *host order*). If fail, return -1 and if
1223 * applicable put your best guess about errno into *<b>socket_error</b>.
1224 * Else assign s to conn-\>s: if connected return 1, if EAGAIN return 0.
1226 * address is used to make the logs useful.
1228 * On success, add conn to the list of polled connections.
1231 connection_connect(connection_t
*conn
, const char *address
,
1232 const tor_addr_t
*addr
, uint16_t port
, int *socket_error
)
1234 int s
, inprogress
= 0;
1236 struct sockaddr
*dest_addr
= (struct sockaddr
*) addrbuf
;
1237 socklen_t dest_addr_len
;
1238 or_options_t
*options
= get_options();
1239 int protocol_family
;
1241 if (get_n_open_sockets() >= get_options()->_ConnLimit
-1) {
1242 warn_too_many_conns();
1246 if (tor_addr_family(addr
) == AF_INET6
)
1247 protocol_family
= PF_INET6
;
1249 protocol_family
= PF_INET
;
1251 s
= tor_open_socket(protocol_family
,SOCK_STREAM
,IPPROTO_TCP
);
1253 *socket_error
= tor_socket_errno(-1);
1254 log_warn(LD_NET
,"Error creating network socket: %s",
1255 tor_socket_strerror(*socket_error
));
1259 if (options
->OutboundBindAddress
&& !tor_addr_is_loopback(addr
)) {
1260 struct sockaddr_in ext_addr
;
1262 memset(&ext_addr
, 0, sizeof(ext_addr
));
1263 ext_addr
.sin_family
= AF_INET
;
1264 ext_addr
.sin_port
= 0;
1265 if (!tor_inet_aton(options
->OutboundBindAddress
, &ext_addr
.sin_addr
)) {
1266 log_warn(LD_CONFIG
,"Outbound bind address '%s' didn't parse. Ignoring.",
1267 options
->OutboundBindAddress
);
1269 if (bind(s
, (struct sockaddr
*)&ext_addr
,
1270 (socklen_t
)sizeof(ext_addr
)) < 0) {
1271 *socket_error
= tor_socket_errno(s
);
1272 log_warn(LD_NET
,"Error binding network socket: %s",
1273 tor_socket_strerror(*socket_error
));
1274 tor_close_socket(s
);
1280 set_socket_nonblocking(s
);
1282 if (options
->ConstrainedSockets
)
1283 set_constrained_socket_buffers(s
, (int)options
->ConstrainedSockSize
);
1285 memset(addrbuf
,0,sizeof(addrbuf
));
1286 dest_addr
= (struct sockaddr
*) addrbuf
;
1287 dest_addr_len
= tor_addr_to_sockaddr(addr
, port
, dest_addr
, sizeof(addrbuf
));
1288 tor_assert(dest_addr_len
> 0);
1290 log_debug(LD_NET
, "Connecting to %s:%u.",
1291 escaped_safe_str_client(address
), port
);
1293 if (connect(s
, dest_addr
, dest_addr_len
) < 0) {
1294 int e
= tor_socket_errno(s
);
1295 if (!ERRNO_IS_CONN_EINPROGRESS(e
)) {
1296 /* yuck. kill it. */
1299 "connect() to %s:%u failed: %s",
1300 escaped_safe_str_client(address
),
1301 port
, tor_socket_strerror(e
));
1302 tor_close_socket(s
);
1309 if (!server_mode(options
))
1310 client_check_address_changed(s
);
1312 /* it succeeded. we're connected. */
1313 log_fn(inprogress
?LOG_DEBUG
:LOG_INFO
, LD_NET
,
1314 "Connection to %s:%u %s (sock %d).",
1315 escaped_safe_str_client(address
),
1316 port
, inprogress
?"in progress":"established", s
);
1318 if (connection_add(conn
) < 0) /* no space, forget it */
1320 return inprogress
? 0 : 1;
1323 /** Convert state number to string representation for logging purposes.
1326 connection_proxy_state_to_string(int state
)
1328 static const char *unknown
= "???";
1329 static const char *states
[] = {
1331 "PROXY_HTTPS_WANT_CONNECT_OK",
1332 "PROXY_SOCKS4_WANT_CONNECT_OK",
1333 "PROXY_SOCKS5_WANT_AUTH_METHOD_NONE",
1334 "PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929",
1335 "PROXY_SOCKS5_WANT_AUTH_RFC1929_OK",
1336 "PROXY_SOCKS5_WANT_CONNECT_OK",
1340 if (state
< PROXY_NONE
|| state
> PROXY_CONNECTED
)
1343 return states
[state
];
1346 /** Write a proxy request of <b>type</b> (socks4, socks5, https) to conn
1347 * for conn->addr:conn->port, authenticating with the auth details given
1348 * in the configuration (if available). SOCKS 5 and HTTP CONNECT proxies
1349 * support authentication.
1351 * Returns -1 if conn->addr is incompatible with the proxy protocol, and
1354 * Use connection_read_proxy_handshake() to complete the handshake.
1357 connection_proxy_connect(connection_t
*conn
, int type
)
1359 or_options_t
*options
;
1363 options
= get_options();
1366 case PROXY_CONNECT
: {
1368 char *base64_authenticator
=NULL
;
1369 const char *authenticator
= options
->HttpsProxyAuthenticator
;
1371 /* Send HTTP CONNECT and authentication (if available) in
1374 if (authenticator
) {
1375 base64_authenticator
= alloc_http_authenticator(authenticator
);
1376 if (!base64_authenticator
)
1377 log_warn(LD_OR
, "Encoding https authenticator failed");
1380 if (base64_authenticator
) {
1381 tor_snprintf(buf
, sizeof(buf
), "CONNECT %s:%d HTTP/1.1\r\n"
1382 "Proxy-Authorization: Basic %s\r\n\r\n",
1383 fmt_addr(&conn
->addr
),
1384 conn
->port
, base64_authenticator
);
1385 tor_free(base64_authenticator
);
1387 tor_snprintf(buf
, sizeof(buf
), "CONNECT %s:%d HTTP/1.0\r\n\r\n",
1388 fmt_addr(&conn
->addr
), conn
->port
);
1391 connection_write_to_buf(buf
, strlen(buf
), conn
);
1392 conn
->proxy_state
= PROXY_HTTPS_WANT_CONNECT_OK
;
1396 case PROXY_SOCKS4
: {
1397 unsigned char buf
[9];
1401 /* Send a SOCKS4 connect request with empty user id */
1403 if (tor_addr_family(&conn
->addr
) != AF_INET
) {
1404 log_warn(LD_NET
, "SOCKS4 client is incompatible with IPv6");
1408 ip4addr
= tor_addr_to_ipv4n(&conn
->addr
);
1409 portn
= htons(conn
->port
);
1411 buf
[0] = 4; /* version */
1412 buf
[1] = SOCKS_COMMAND_CONNECT
; /* command */
1413 memcpy(buf
+ 2, &portn
, 2); /* port */
1414 memcpy(buf
+ 4, &ip4addr
, 4); /* addr */
1415 buf
[8] = 0; /* userid (empty) */
1417 connection_write_to_buf((char *)buf
, sizeof(buf
), conn
);
1418 conn
->proxy_state
= PROXY_SOCKS4_WANT_CONNECT_OK
;
1422 case PROXY_SOCKS5
: {
1423 unsigned char buf
[4]; /* fields: vers, num methods, method list */
1425 /* Send a SOCKS5 greeting (connect request must wait) */
1427 buf
[0] = 5; /* version */
1429 /* number of auth methods */
1430 if (options
->Socks5ProxyUsername
) {
1432 buf
[2] = 0x00; /* no authentication */
1433 buf
[3] = 0x02; /* rfc1929 Username/Passwd auth */
1434 conn
->proxy_state
= PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929
;
1437 buf
[2] = 0x00; /* no authentication */
1438 conn
->proxy_state
= PROXY_SOCKS5_WANT_AUTH_METHOD_NONE
;
1441 connection_write_to_buf((char *)buf
, 2 + buf
[1], conn
);
1446 log_err(LD_BUG
, "Invalid proxy protocol, %d", type
);
1447 tor_fragile_assert();
1451 log_debug(LD_NET
, "set state %s",
1452 connection_proxy_state_to_string(conn
->proxy_state
));
1457 /** Read conn's inbuf. If the http response from the proxy is all
1458 * here, make sure it's good news, then return 1. If it's bad news,
1459 * return -1. Else return 0 and hope for better luck next time.
1462 connection_read_https_proxy_response(connection_t
*conn
)
1469 switch (fetch_from_buf_http(conn
->inbuf
,
1470 &headers
, MAX_HEADERS_SIZE
,
1471 NULL
, NULL
, 10000, 0)) {
1472 case -1: /* overflow */
1473 log_warn(LD_PROTOCOL
,
1474 "Your https proxy sent back an oversized response. Closing.");
1477 log_info(LD_NET
,"https proxy response not all here yet. Waiting.");
1479 /* case 1, fall through */
1482 if (parse_http_response(headers
, &status_code
, &date_header
,
1483 NULL
, &reason
) < 0) {
1485 "Unparseable headers from proxy (connecting to '%s'). Closing.",
1490 if (!reason
) reason
= tor_strdup("[no reason given]");
1492 if (status_code
== 200) {
1494 "HTTPS connect to '%s' successful! (200 %s) Starting TLS.",
1495 conn
->address
, escaped(reason
));
1499 /* else, bad news on the status code */
1501 "The https proxy sent back an unexpected status code %d (%s). "
1503 status_code
, escaped(reason
));
1508 /** Send SOCKS5 CONNECT command to <b>conn</b>, copying <b>conn->addr</b>
1509 * and <b>conn->port</b> into the request.
1512 connection_send_socks5_connect(connection_t
*conn
)
1514 unsigned char buf
[1024];
1516 uint16_t port
= htons(conn
->port
);
1518 buf
[0] = 5; /* version */
1519 buf
[1] = SOCKS_COMMAND_CONNECT
; /* command */
1520 buf
[2] = 0; /* reserved */
1522 if (tor_addr_family(&conn
->addr
) == AF_INET
) {
1523 uint32_t addr
= tor_addr_to_ipv4n(&conn
->addr
);
1527 memcpy(buf
+ 4, &addr
, 4);
1528 memcpy(buf
+ 8, &port
, 2);
1529 } else { /* AF_INET6 */
1532 memcpy(buf
+ 4, tor_addr_to_in6(&conn
->addr
), 16);
1533 memcpy(buf
+ 20, &port
, 2);
1536 connection_write_to_buf((char *)buf
, reqsize
, conn
);
1538 conn
->proxy_state
= PROXY_SOCKS5_WANT_CONNECT_OK
;
1541 /** Call this from connection_*_process_inbuf() to advance the proxy
1544 * No matter what proxy protocol is used, if this function returns 1, the
1545 * handshake is complete, and the data remaining on inbuf may contain the
1546 * start of the communication with the requested server.
1548 * Returns 0 if the current buffer contains an incomplete response, and -1
1552 connection_read_proxy_handshake(connection_t
*conn
)
1555 char *reason
= NULL
;
1557 log_debug(LD_NET
, "enter state %s",
1558 connection_proxy_state_to_string(conn
->proxy_state
));
1560 switch (conn
->proxy_state
) {
1561 case PROXY_HTTPS_WANT_CONNECT_OK
:
1562 ret
= connection_read_https_proxy_response(conn
);
1564 conn
->proxy_state
= PROXY_CONNECTED
;
1567 case PROXY_SOCKS4_WANT_CONNECT_OK
:
1568 ret
= fetch_from_buf_socks_client(conn
->inbuf
,
1572 conn
->proxy_state
= PROXY_CONNECTED
;
1575 case PROXY_SOCKS5_WANT_AUTH_METHOD_NONE
:
1576 ret
= fetch_from_buf_socks_client(conn
->inbuf
,
1579 /* no auth needed, do connect */
1581 connection_send_socks5_connect(conn
);
1586 case PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929
:
1587 ret
= fetch_from_buf_socks_client(conn
->inbuf
,
1591 /* send auth if needed, otherwise do connect */
1593 connection_send_socks5_connect(conn
);
1595 } else if (ret
== 2) {
1596 unsigned char buf
[1024];
1597 size_t reqsize
, usize
, psize
;
1598 const char *user
, *pass
;
1600 user
= get_options()->Socks5ProxyUsername
;
1601 pass
= get_options()->Socks5ProxyPassword
;
1602 tor_assert(user
&& pass
);
1604 /* XXX len of user and pass must be <= 255 !!! */
1605 usize
= strlen(user
);
1606 psize
= strlen(pass
);
1607 tor_assert(usize
<= 255 && psize
<= 255);
1608 reqsize
= 3 + usize
+ psize
;
1610 buf
[0] = 1; /* negotiation version */
1612 memcpy(buf
+ 2, user
, usize
);
1613 buf
[2 + usize
] = psize
;
1614 memcpy(buf
+ 3 + usize
, pass
, psize
);
1616 connection_write_to_buf((char *)buf
, reqsize
, conn
);
1618 conn
->proxy_state
= PROXY_SOCKS5_WANT_AUTH_RFC1929_OK
;
1623 case PROXY_SOCKS5_WANT_AUTH_RFC1929_OK
:
1624 ret
= fetch_from_buf_socks_client(conn
->inbuf
,
1627 /* send the connect request */
1629 connection_send_socks5_connect(conn
);
1634 case PROXY_SOCKS5_WANT_CONNECT_OK
:
1635 ret
= fetch_from_buf_socks_client(conn
->inbuf
,
1639 conn
->proxy_state
= PROXY_CONNECTED
;
1643 log_err(LD_BUG
, "Invalid proxy_state for reading, %d",
1645 tor_fragile_assert();
1650 log_debug(LD_NET
, "leaving state %s",
1651 connection_proxy_state_to_string(conn
->proxy_state
));
1655 log_warn(LD_NET
, "Proxy Client: unable to connect to %s:%d (%s)",
1656 conn
->address
, conn
->port
, escaped(reason
));
1659 log_warn(LD_NET
, "Proxy Client: unable to connect to %s:%d",
1660 conn
->address
, conn
->port
);
1662 } else if (ret
== 1) {
1663 log_info(LD_NET
, "Proxy Client: connection to %s:%d successful",
1664 conn
->address
, conn
->port
);
1671 * Launch any configured listener connections of type <b>type</b>. (A
1672 * listener is configured if <b>port_option</b> is non-zero. If any
1673 * ListenAddress configuration options are given in <b>cfg</b>, create a
1674 * connection binding to each one. Otherwise, create a single
1675 * connection binding to the address <b>default_addr</b>.)
1677 * Only launch the listeners of this type that are not already open, and
1678 * only close listeners that are no longer wanted. Existing listeners
1679 * that are still configured are not touched.
1681 * If <b>disable_all_conns</b> is set, then never open new conns, and
1682 * close the existing ones.
1684 * Add all old conns that should be closed to <b>replaced_conns</b>.
1685 * Add all new connections to <b>new_conns</b>.
1688 retry_listeners(int type
, config_line_t
*cfg
,
1689 int port_option
, const char *default_addr
,
1690 smartlist_t
*replaced_conns
,
1691 smartlist_t
*new_conns
,
1692 int disable_all_conns
,
1695 smartlist_t
*launch
= smartlist_create(), *conns
;
1696 int free_launch_elts
= 1;
1700 config_line_t
*line
;
1702 tor_assert(socket_family
== AF_INET
|| socket_family
== AF_UNIX
);
1704 if (cfg
&& port_option
) {
1705 for (c
= cfg
; c
; c
= c
->next
) {
1706 smartlist_add(launch
, c
);
1708 free_launch_elts
= 0;
1709 } else if (port_option
) {
1710 line
= tor_malloc_zero(sizeof(config_line_t
));
1711 line
->key
= tor_strdup("");
1712 line
->value
= tor_strdup(default_addr
);
1713 smartlist_add(launch
, line
);
1717 SMARTLIST_FOREACH(launch, config_line_t *, l,
1718 log_fn(LOG_NOTICE, "#%s#%s", l->key, l->value));
1721 conns
= get_connection_array();
1722 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
1724 if (conn
->type
!= type
||
1725 conn
->socket_family
!= socket_family
||
1726 conn
->marked_for_close
)
1728 /* Okay, so this is a listener. Is it configured? */
1730 SMARTLIST_FOREACH(launch
, config_line_t
*, wanted
,
1734 switch (socket_family
) {
1736 if (!parse_addr_port(LOG_WARN
,
1737 wanted
->value
, &address
, NULL
, &port
)) {
1738 int addr_matches
= !strcasecmp(address
, conn
->address
);
1742 if (port
== conn
->port
&& addr_matches
) {
1749 if (!strcasecmp(wanted
->value
, conn
->address
)) {
1758 if (!line
|| disable_all_conns
) {
1759 /* This one isn't configured. Close it. */
1760 log_notice(LD_NET
, "Closing no-longer-configured %s on %s:%d",
1761 conn_type_to_string(type
), conn
->address
, conn
->port
);
1762 if (replaced_conns
) {
1763 smartlist_add(replaced_conns
, conn
);
1765 connection_close_immediate(conn
);
1766 connection_mark_for_close(conn
);
1769 /* It's configured; we don't need to launch it. */
1770 // log_debug(LD_NET, "Already have %s on %s:%d",
1771 // conn_type_to_string(type), conn->address, conn->port);
1772 smartlist_remove(launch
, line
);
1773 if (free_launch_elts
)
1774 config_free_lines(line
);
1778 /* Now open all the listeners that are configured but not opened. */
1780 if (!disable_all_conns
) {
1781 SMARTLIST_FOREACH_BEGIN(launch
, config_line_t
*, cfg_line
) {
1782 char *address
= NULL
;
1783 struct sockaddr
*listensockaddr
;
1784 socklen_t listensocklen
= 0;
1786 switch (socket_family
) {
1788 listensockaddr
= (struct sockaddr
*)
1789 create_inet_sockaddr(cfg_line
->value
,
1790 (uint16_t) port_option
,
1791 &address
, &listensocklen
);
1794 listensockaddr
= (struct sockaddr
*)
1795 create_unix_sockaddr(cfg_line
->value
,
1796 &address
, &listensocklen
);
1802 if (listensockaddr
) {
1803 conn
= connection_create_listener(listensockaddr
, listensocklen
,
1805 tor_free(listensockaddr
);
1814 smartlist_add(new_conns
, conn
);
1816 } SMARTLIST_FOREACH_END(cfg_line
);
1819 if (free_launch_elts
) {
1820 SMARTLIST_FOREACH(launch
, config_line_t
*, cfg_line
,
1821 config_free_lines(cfg_line
));
1823 smartlist_free(launch
);
1828 /** Launch listeners for each port you should have open. Only launch
1829 * listeners who are not already open, and only close listeners we no longer
1832 * Add all old conns that should be closed to <b>replaced_conns</b>.
1833 * Add all new connections to <b>new_conns</b>.
1836 retry_all_listeners(smartlist_t
*replaced_conns
,
1837 smartlist_t
*new_conns
)
1839 or_options_t
*options
= get_options();
1841 if (retry_listeners(CONN_TYPE_OR_LISTENER
, options
->ORListenAddress
,
1842 options
->ORPort
, "0.0.0.0",
1843 replaced_conns
, new_conns
, options
->ClientOnly
,
1846 if (retry_listeners(CONN_TYPE_DIR_LISTENER
, options
->DirListenAddress
,
1847 options
->DirPort
, "0.0.0.0",
1848 replaced_conns
, new_conns
, options
->ClientOnly
,
1851 if (retry_listeners(CONN_TYPE_AP_LISTENER
, options
->SocksListenAddress
,
1852 options
->SocksPort
, "127.0.0.1",
1853 replaced_conns
, new_conns
, 0,
1856 if (retry_listeners(CONN_TYPE_AP_TRANS_LISTENER
, options
->TransListenAddress
,
1857 options
->TransPort
, "127.0.0.1",
1858 replaced_conns
, new_conns
, 0,
1861 if (retry_listeners(CONN_TYPE_AP_NATD_LISTENER
, options
->NatdListenAddress
,
1862 options
->NatdPort
, "127.0.0.1",
1863 replaced_conns
, new_conns
, 0,
1866 if (retry_listeners(CONN_TYPE_AP_DNS_LISTENER
, options
->DNSListenAddress
,
1867 options
->DNSPort
, "127.0.0.1",
1868 replaced_conns
, new_conns
, 0,
1871 if (retry_listeners(CONN_TYPE_CONTROL_LISTENER
,
1872 options
->ControlListenAddress
,
1873 options
->ControlPort
, "127.0.0.1",
1874 replaced_conns
, new_conns
, 0,
1877 if (retry_listeners(CONN_TYPE_CONTROL_LISTENER
,
1878 options
->ControlSocket
,
1879 options
->ControlSocket
? 1 : 0, NULL
,
1880 replaced_conns
, new_conns
, 0,
1887 /** Return 1 if we should apply rate limiting to <b>conn</b>,
1888 * and 0 otherwise. Right now this just checks if it's an internal
1889 * IP address or an internal connection. */
1891 connection_is_rate_limited(connection_t
*conn
)
1893 if (conn
->linked
|| /* internal connection */
1894 tor_addr_family(&conn
->addr
) == AF_UNSPEC
|| /* no address */
1895 tor_addr_is_internal(&conn
->addr
, 0)) /* internal address */
1901 extern int global_read_bucket
, global_write_bucket
;
1902 extern int global_relayed_read_bucket
, global_relayed_write_bucket
;
1904 /** Did either global write bucket run dry last second? If so,
1905 * we are likely to run dry again this second, so be stingy with the
1906 * tokens we just put in. */
1907 static int write_buckets_empty_last_second
= 0;
1909 /** How many seconds of no active local circuits will make the
1910 * connection revert to the "relayed" bandwidth class? */
1911 #define CLIENT_IDLE_TIME_FOR_PRIORITY 30
1913 /** Return 1 if <b>conn</b> should use tokens from the "relayed"
1914 * bandwidth rates, else 0. Currently, only OR conns with bandwidth
1915 * class 1, and directory conns that are serving data out, count.
1918 connection_counts_as_relayed_traffic(connection_t
*conn
, time_t now
)
1920 if (conn
->type
== CONN_TYPE_OR
&&
1921 TO_OR_CONN(conn
)->client_used
+ CLIENT_IDLE_TIME_FOR_PRIORITY
< now
)
1923 if (conn
->type
== CONN_TYPE_DIR
&& DIR_CONN_IS_SERVER(conn
))
1928 /** Helper function to decide how many bytes out of <b>global_bucket</b>
1929 * we're willing to use for this transaction. <b>base</b> is the size
1930 * of a cell on the network; <b>priority</b> says whether we should
1931 * write many of them or just a few; and <b>conn_bucket</b> (if
1932 * non-negative) provides an upper limit for our answer. */
1934 connection_bucket_round_robin(int base
, int priority
,
1935 ssize_t global_bucket
, ssize_t conn_bucket
)
1938 ssize_t num_bytes_high
= (priority
? 32 : 16) * base
;
1939 ssize_t num_bytes_low
= (priority
? 4 : 2) * base
;
1941 /* Do a rudimentary round-robin so one circuit can't hog a connection.
1942 * Pick at most 32 cells, at least 4 cells if possible, and if we're in
1943 * the middle pick 1/8 of the available bandwidth. */
1944 at_most
= global_bucket
/ 8;
1945 at_most
-= (at_most
% base
); /* round down */
1946 if (at_most
> num_bytes_high
) /* 16 KB, or 8 KB for low-priority */
1947 at_most
= num_bytes_high
;
1948 else if (at_most
< num_bytes_low
) /* 2 KB, or 1 KB for low-priority */
1949 at_most
= num_bytes_low
;
1951 if (at_most
> global_bucket
)
1952 at_most
= global_bucket
;
1954 if (conn_bucket
>= 0 && at_most
> conn_bucket
)
1955 at_most
= conn_bucket
;
1962 /** How many bytes at most can we read onto this connection? */
1964 connection_bucket_read_limit(connection_t
*conn
, time_t now
)
1966 int base
= connection_speaks_cells(conn
) ?
1967 CELL_NETWORK_SIZE
: RELAY_PAYLOAD_SIZE
;
1968 int priority
= conn
->type
!= CONN_TYPE_DIR
;
1969 int conn_bucket
= -1;
1970 int global_bucket
= global_read_bucket
;
1972 if (connection_speaks_cells(conn
)) {
1973 or_connection_t
*or_conn
= TO_OR_CONN(conn
);
1974 if (conn
->state
== OR_CONN_STATE_OPEN
)
1975 conn_bucket
= or_conn
->read_bucket
;
1978 if (!connection_is_rate_limited(conn
)) {
1979 /* be willing to read on local conns even if our buckets are empty */
1980 return conn_bucket
>=0 ? conn_bucket
: 1<<14;
1983 if (connection_counts_as_relayed_traffic(conn
, now
) &&
1984 global_relayed_read_bucket
<= global_read_bucket
)
1985 global_bucket
= global_relayed_read_bucket
;
1987 return connection_bucket_round_robin(base
, priority
,
1988 global_bucket
, conn_bucket
);
1991 /** How many bytes at most can we write onto this connection? */
1993 connection_bucket_write_limit(connection_t
*conn
, time_t now
)
1995 int base
= connection_speaks_cells(conn
) ?
1996 CELL_NETWORK_SIZE
: RELAY_PAYLOAD_SIZE
;
1997 int priority
= conn
->type
!= CONN_TYPE_DIR
;
1998 int conn_bucket
= (int)conn
->outbuf_flushlen
;
1999 int global_bucket
= global_write_bucket
;
2001 if (!connection_is_rate_limited(conn
)) {
2002 /* be willing to write to local conns even if our buckets are empty */
2003 return conn
->outbuf_flushlen
;
2006 if (connection_speaks_cells(conn
)) {
2007 /* use the per-conn write limit if it's lower, but if it's less
2008 * than zero just use zero */
2009 or_connection_t
*or_conn
= TO_OR_CONN(conn
);
2010 if (conn
->state
== OR_CONN_STATE_OPEN
)
2011 if (or_conn
->write_bucket
< conn_bucket
)
2012 conn_bucket
= or_conn
->write_bucket
>= 0 ?
2013 or_conn
->write_bucket
: 0;
2016 if (connection_counts_as_relayed_traffic(conn
, now
) &&
2017 global_relayed_write_bucket
<= global_write_bucket
)
2018 global_bucket
= global_relayed_write_bucket
;
2020 return connection_bucket_round_robin(base
, priority
,
2021 global_bucket
, conn_bucket
);
2024 /** Return 1 if the global write buckets are low enough that we
2025 * shouldn't send <b>attempt</b> bytes of low-priority directory stuff
2026 * out to <b>conn</b>. Else return 0.
2028 * Priority is 1 for v1 requests (directories and running-routers),
2029 * and 2 for v2 requests (statuses and descriptors). But see FFFF in
2030 * directory_handle_command_get() for why we don't use priority 2 yet.
2032 * There are a lot of parameters we could use here:
2033 * - global_relayed_write_bucket. Low is bad.
2034 * - global_write_bucket. Low is bad.
2035 * - bandwidthrate. Low is bad.
2036 * - bandwidthburst. Not a big factor?
2037 * - attempt. High is bad.
2038 * - total bytes queued on outbufs. High is bad. But I'm wary of
2039 * using this, since a few slow-flushing queues will pump up the
2040 * number without meaning what we meant to mean. What we really
2041 * mean is "total directory bytes added to outbufs recently", but
2042 * that's harder to quantify and harder to keep track of.
2045 global_write_bucket_low(connection_t
*conn
, size_t attempt
, int priority
)
2047 int smaller_bucket
= global_write_bucket
< global_relayed_write_bucket
?
2048 global_write_bucket
: global_relayed_write_bucket
;
2049 if (authdir_mode(get_options()) && priority
>1)
2050 return 0; /* there's always room to answer v2 if we're an auth dir */
2052 if (!connection_is_rate_limited(conn
))
2053 return 0; /* local conns don't get limited */
2055 if (smaller_bucket
< (int)attempt
)
2056 return 1; /* not enough space no matter the priority */
2058 if (write_buckets_empty_last_second
)
2059 return 1; /* we're already hitting our limits, no more please */
2061 if (priority
== 1) { /* old-style v1 query */
2062 /* Could we handle *two* of these requests within the next two seconds? */
2063 or_options_t
*options
= get_options();
2064 int64_t can_write
= (int64_t)smaller_bucket
2065 + 2*(options
->RelayBandwidthRate
? options
->RelayBandwidthRate
:
2066 options
->BandwidthRate
);
2067 if (can_write
< 2*(int64_t)attempt
)
2069 } else { /* v2 query */
2070 /* no further constraints yet */
2075 /** We just read <b>num_read</b> and wrote <b>num_written</b> bytes
2076 * onto <b>conn</b>. Decrement buckets appropriately. */
2078 connection_buckets_decrement(connection_t
*conn
, time_t now
,
2079 size_t num_read
, size_t num_written
)
2081 if (!connection_is_rate_limited(conn
))
2082 return; /* local IPs are free */
2083 if (num_written
>= INT_MAX
|| num_read
>= INT_MAX
) {
2084 log_err(LD_BUG
, "Value out of range. num_read=%lu, num_written=%lu, "
2085 "connection type=%s, state=%s",
2086 (unsigned long)num_read
, (unsigned long)num_written
,
2087 conn_type_to_string(conn
->type
),
2088 conn_state_to_string(conn
->type
, conn
->state
));
2089 if (num_written
>= INT_MAX
) num_written
= 1;
2090 if (num_read
>= INT_MAX
) num_read
= 1;
2091 tor_fragile_assert();
2095 if (conn
->type
== CONN_TYPE_EXIT
)
2096 rep_hist_note_exit_bytes_read(conn
->port
, num_read
);
2097 rep_hist_note_bytes_read(num_read
, now
);
2099 if (num_written
> 0) {
2100 if (conn
->type
== CONN_TYPE_EXIT
)
2101 rep_hist_note_exit_bytes_written(conn
->port
, num_written
);
2102 rep_hist_note_bytes_written(num_written
, now
);
2105 if (connection_counts_as_relayed_traffic(conn
, now
)) {
2106 global_relayed_read_bucket
-= (int)num_read
;
2107 global_relayed_write_bucket
-= (int)num_written
;
2109 global_read_bucket
-= (int)num_read
;
2110 global_write_bucket
-= (int)num_written
;
2111 if (connection_speaks_cells(conn
) && conn
->state
== OR_CONN_STATE_OPEN
) {
2112 TO_OR_CONN(conn
)->read_bucket
-= (int)num_read
;
2113 TO_OR_CONN(conn
)->write_bucket
-= (int)num_written
;
2117 /** If we have exhausted our global buckets, or the buckets for conn,
2120 connection_consider_empty_read_buckets(connection_t
*conn
)
2124 if (global_read_bucket
<= 0) {
2125 reason
= "global read bucket exhausted. Pausing.";
2126 } else if (connection_counts_as_relayed_traffic(conn
, approx_time()) &&
2127 global_relayed_read_bucket
<= 0) {
2128 reason
= "global relayed read bucket exhausted. Pausing.";
2129 } else if (connection_speaks_cells(conn
) &&
2130 conn
->state
== OR_CONN_STATE_OPEN
&&
2131 TO_OR_CONN(conn
)->read_bucket
<= 0) {
2132 reason
= "connection read bucket exhausted. Pausing.";
2134 return; /* all good, no need to stop it */
2136 LOG_FN_CONN(conn
, (LOG_DEBUG
, LD_NET
, "%s", reason
));
2137 conn
->read_blocked_on_bw
= 1;
2138 connection_stop_reading(conn
);
2141 /** If we have exhausted our global buckets, or the buckets for conn,
2144 connection_consider_empty_write_buckets(connection_t
*conn
)
2148 if (global_write_bucket
<= 0) {
2149 reason
= "global write bucket exhausted. Pausing.";
2150 } else if (connection_counts_as_relayed_traffic(conn
, approx_time()) &&
2151 global_relayed_write_bucket
<= 0) {
2152 reason
= "global relayed write bucket exhausted. Pausing.";
2153 } else if (connection_speaks_cells(conn
) &&
2154 conn
->state
== OR_CONN_STATE_OPEN
&&
2155 TO_OR_CONN(conn
)->write_bucket
<= 0) {
2156 reason
= "connection write bucket exhausted. Pausing.";
2158 return; /* all good, no need to stop it */
2160 LOG_FN_CONN(conn
, (LOG_DEBUG
, LD_NET
, "%s", reason
));
2161 conn
->write_blocked_on_bw
= 1;
2162 connection_stop_writing(conn
);
2165 /** Initialize the global read bucket to options-\>BandwidthBurst. */
2167 connection_bucket_init(void)
2169 or_options_t
*options
= get_options();
2170 /* start it at max traffic */
2171 global_read_bucket
= (int)options
->BandwidthBurst
;
2172 global_write_bucket
= (int)options
->BandwidthBurst
;
2173 if (options
->RelayBandwidthRate
) {
2174 global_relayed_read_bucket
= (int)options
->RelayBandwidthBurst
;
2175 global_relayed_write_bucket
= (int)options
->RelayBandwidthBurst
;
2177 global_relayed_read_bucket
= (int)options
->BandwidthBurst
;
2178 global_relayed_write_bucket
= (int)options
->BandwidthBurst
;
2182 /** Refill a single <b>bucket</b> called <b>name</b> with bandwidth rate
2183 * <b>rate</b> and bandwidth burst <b>burst</b>, assuming that
2184 * <b>seconds_elapsed</b> seconds have passed since the last call.
2187 connection_bucket_refill_helper(int *bucket
, int rate
, int burst
,
2188 int seconds_elapsed
, const char *name
)
2190 int starting_bucket
= *bucket
;
2191 if (starting_bucket
< burst
&& seconds_elapsed
) {
2192 if (((burst
- starting_bucket
)/seconds_elapsed
) < rate
) {
2193 *bucket
= burst
; /* We would overflow the bucket; just set it to
2196 int incr
= rate
*seconds_elapsed
;
2198 if (*bucket
> burst
|| *bucket
< starting_bucket
) {
2199 /* If we overflow the burst, or underflow our starting bucket,
2200 * cap the bucket value to burst. */
2201 /* XXXX this might be redundant now, but it doesn't show up
2202 * in profiles. Remove it after analysis. */
2206 log(LOG_DEBUG
, LD_NET
,"%s now %d.", name
, *bucket
);
2210 /** A second has rolled over; increment buckets appropriately. */
2212 connection_bucket_refill(int seconds_elapsed
, time_t now
)
2214 or_options_t
*options
= get_options();
2215 smartlist_t
*conns
= get_connection_array();
2216 int relayrate
, relayburst
;
2218 if (options
->RelayBandwidthRate
) {
2219 relayrate
= (int)options
->RelayBandwidthRate
;
2220 relayburst
= (int)options
->RelayBandwidthBurst
;
2222 relayrate
= (int)options
->BandwidthRate
;
2223 relayburst
= (int)options
->BandwidthBurst
;
2226 tor_assert(seconds_elapsed
>= 0);
2228 write_buckets_empty_last_second
=
2229 global_relayed_write_bucket
<= 0 || global_write_bucket
<= 0;
2231 /* refill the global buckets */
2232 connection_bucket_refill_helper(&global_read_bucket
,
2233 (int)options
->BandwidthRate
,
2234 (int)options
->BandwidthBurst
,
2235 seconds_elapsed
, "global_read_bucket");
2236 connection_bucket_refill_helper(&global_write_bucket
,
2237 (int)options
->BandwidthRate
,
2238 (int)options
->BandwidthBurst
,
2239 seconds_elapsed
, "global_write_bucket");
2240 connection_bucket_refill_helper(&global_relayed_read_bucket
,
2241 relayrate
, relayburst
, seconds_elapsed
,
2242 "global_relayed_read_bucket");
2243 connection_bucket_refill_helper(&global_relayed_write_bucket
,
2244 relayrate
, relayburst
, seconds_elapsed
,
2245 "global_relayed_write_bucket");
2247 /* refill the per-connection buckets */
2248 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
2250 if (connection_speaks_cells(conn
)) {
2251 or_connection_t
*or_conn
= TO_OR_CONN(conn
);
2252 if (connection_bucket_should_increase(or_conn
->read_bucket
, or_conn
)) {
2253 connection_bucket_refill_helper(&or_conn
->read_bucket
,
2254 or_conn
->bandwidthrate
,
2255 or_conn
->bandwidthburst
,
2257 "or_conn->read_bucket");
2259 if (connection_bucket_should_increase(or_conn
->write_bucket
, or_conn
)) {
2260 connection_bucket_refill_helper(&or_conn
->write_bucket
,
2261 or_conn
->bandwidthrate
,
2262 or_conn
->bandwidthburst
,
2264 "or_conn->write_bucket");
2268 if (conn
->read_blocked_on_bw
== 1 /* marked to turn reading back on now */
2269 && global_read_bucket
> 0 /* and we're allowed to read */
2270 && (!connection_counts_as_relayed_traffic(conn
, now
) ||
2271 global_relayed_read_bucket
> 0) /* even if we're relayed traffic */
2272 && (!connection_speaks_cells(conn
) ||
2273 conn
->state
!= OR_CONN_STATE_OPEN
||
2274 TO_OR_CONN(conn
)->read_bucket
> 0)) {
2275 /* and either a non-cell conn or a cell conn with non-empty bucket */
2276 LOG_FN_CONN(conn
, (LOG_DEBUG
,LD_NET
,
2277 "waking up conn (fd %d) for read", conn
->s
));
2278 conn
->read_blocked_on_bw
= 0;
2279 connection_start_reading(conn
);
2282 if (conn
->write_blocked_on_bw
== 1
2283 && global_write_bucket
> 0 /* and we're allowed to write */
2284 && (!connection_counts_as_relayed_traffic(conn
, now
) ||
2285 global_relayed_write_bucket
> 0) /* even if it's relayed traffic */
2286 && (!connection_speaks_cells(conn
) ||
2287 conn
->state
!= OR_CONN_STATE_OPEN
||
2288 TO_OR_CONN(conn
)->write_bucket
> 0)) {
2289 LOG_FN_CONN(conn
, (LOG_DEBUG
,LD_NET
,
2290 "waking up conn (fd %d) for write", conn
->s
));
2291 conn
->write_blocked_on_bw
= 0;
2292 connection_start_writing(conn
);
2297 /** Is the <b>bucket</b> for connection <b>conn</b> low enough that we
2298 * should add another pile of tokens to it?
2301 connection_bucket_should_increase(int bucket
, or_connection_t
*conn
)
2305 if (conn
->_base
.state
!= OR_CONN_STATE_OPEN
)
2306 return 0; /* only open connections play the rate limiting game */
2307 if (bucket
>= conn
->bandwidthburst
)
2313 /** Read bytes from conn-\>s and process them.
2315 * This function gets called from conn_read() in main.c, either
2316 * when poll() has declared that conn wants to read, or (for OR conns)
2317 * when there are pending TLS bytes.
2319 * It calls connection_read_to_buf() to bring in any new bytes,
2320 * and then calls connection_process_inbuf() to process them.
2322 * Mark the connection and return -1 if you want to close it, else
2326 connection_handle_read_impl(connection_t
*conn
)
2328 int max_to_read
=-1, try_to_read
;
2329 size_t before
, n_read
= 0;
2330 int socket_error
= 0;
2332 if (conn
->marked_for_close
)
2333 return 0; /* do nothing */
2335 conn
->timestamp_lastread
= approx_time();
2337 switch (conn
->type
) {
2338 case CONN_TYPE_OR_LISTENER
:
2339 return connection_handle_listener_read(conn
, CONN_TYPE_OR
);
2340 case CONN_TYPE_AP_LISTENER
:
2341 case CONN_TYPE_AP_TRANS_LISTENER
:
2342 case CONN_TYPE_AP_NATD_LISTENER
:
2343 return connection_handle_listener_read(conn
, CONN_TYPE_AP
);
2344 case CONN_TYPE_DIR_LISTENER
:
2345 return connection_handle_listener_read(conn
, CONN_TYPE_DIR
);
2346 case CONN_TYPE_CONTROL_LISTENER
:
2347 return connection_handle_listener_read(conn
, CONN_TYPE_CONTROL
);
2348 case CONN_TYPE_AP_DNS_LISTENER
:
2349 /* This should never happen; eventdns.c handles the reads here. */
2350 tor_fragile_assert();
2355 try_to_read
= max_to_read
;
2356 tor_assert(!conn
->marked_for_close
);
2358 before
= buf_datalen(conn
->inbuf
);
2359 if (connection_read_to_buf(conn
, &max_to_read
, &socket_error
) < 0) {
2360 /* There's a read error; kill the connection.*/
2361 if (conn
->type
== CONN_TYPE_OR
&&
2362 conn
->state
== OR_CONN_STATE_CONNECTING
) {
2363 connection_or_connect_failed(TO_OR_CONN(conn
),
2364 errno_to_orconn_end_reason(socket_error
),
2365 tor_socket_strerror(socket_error
));
2367 if (CONN_IS_EDGE(conn
)) {
2368 edge_connection_t
*edge_conn
= TO_EDGE_CONN(conn
);
2369 connection_edge_end_errno(edge_conn
);
2370 if (edge_conn
->socks_request
) /* broken, don't send a socks reply back */
2371 edge_conn
->socks_request
->has_finished
= 1;
2373 connection_close_immediate(conn
); /* Don't flush; connection is dead. */
2374 connection_mark_for_close(conn
);
2377 n_read
+= buf_datalen(conn
->inbuf
) - before
;
2378 if (CONN_IS_EDGE(conn
) && try_to_read
!= max_to_read
) {
2379 /* instruct it not to try to package partial cells. */
2380 if (connection_process_inbuf(conn
, 0) < 0) {
2383 if (!conn
->marked_for_close
&&
2384 connection_is_reading(conn
) &&
2385 !conn
->inbuf_reached_eof
&&
2387 goto loop_again
; /* try reading again, in case more is here now */
2389 /* one last try, packaging partial cells and all. */
2390 if (!conn
->marked_for_close
&&
2391 connection_process_inbuf(conn
, 1) < 0) {
2394 if (conn
->linked_conn
) {
2395 /* The other side's handle_write() will never actually get called, so
2396 * we need to invoke the appropriate callbacks ourself. */
2397 connection_t
*linked
= conn
->linked_conn
;
2400 /* Probably a no-op, but hey. */
2401 connection_buckets_decrement(linked
, approx_time(), n_read
, 0);
2403 if (connection_flushed_some(linked
) < 0)
2404 connection_mark_for_close(linked
);
2405 if (!connection_wants_to_flush(linked
))
2406 connection_finished_flushing(linked
);
2409 if (!buf_datalen(linked
->outbuf
) && conn
->active_on_link
)
2410 connection_stop_reading_from_linked_conn(conn
);
2412 /* If we hit the EOF, call connection_reached_eof(). */
2413 if (!conn
->marked_for_close
&&
2414 conn
->inbuf_reached_eof
&&
2415 connection_reached_eof(conn
) < 0) {
2422 connection_handle_read(connection_t
*conn
)
2426 tor_gettimeofday_cache_clear();
2427 res
= connection_handle_read_impl(conn
);
2431 /** Pull in new bytes from conn-\>s or conn-\>linked_conn onto conn-\>inbuf,
2432 * either directly or via TLS. Reduce the token buckets by the number of bytes
2435 * If *max_to_read is -1, then decide it ourselves, else go with the
2436 * value passed to us. When returning, if it's changed, subtract the
2437 * number of bytes we read from *max_to_read.
2439 * Return -1 if we want to break conn, else return 0.
2442 connection_read_to_buf(connection_t
*conn
, int *max_to_read
, int *socket_error
)
2445 ssize_t at_most
= *max_to_read
;
2446 size_t slack_in_buf
, more_to_read
;
2447 size_t n_read
= 0, n_written
= 0;
2449 if (at_most
== -1) { /* we need to initialize it */
2450 /* how many bytes are we allowed to read? */
2451 at_most
= connection_bucket_read_limit(conn
, approx_time());
2454 slack_in_buf
= buf_slack(conn
->inbuf
);
2456 if ((size_t)at_most
> slack_in_buf
&& slack_in_buf
>= 1024) {
2457 more_to_read
= at_most
- slack_in_buf
;
2458 at_most
= slack_in_buf
;
2463 if (connection_speaks_cells(conn
) &&
2464 conn
->state
> OR_CONN_STATE_PROXY_HANDSHAKING
) {
2466 or_connection_t
*or_conn
= TO_OR_CONN(conn
);
2467 size_t initial_size
;
2468 if (conn
->state
== OR_CONN_STATE_TLS_HANDSHAKING
||
2469 conn
->state
== OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING
) {
2470 /* continue handshaking even if global token bucket is empty */
2471 return connection_tls_continue_handshake(or_conn
);
2475 "%d: starting, inbuf_datalen %ld (%d pending in tls object)."
2477 conn
->s
,(long)buf_datalen(conn
->inbuf
),
2478 tor_tls_get_pending_bytes(or_conn
->tls
), (long)at_most
);
2480 initial_size
= buf_datalen(conn
->inbuf
);
2481 /* else open, or closing */
2482 result
= read_to_buf_tls(or_conn
->tls
, at_most
, conn
->inbuf
);
2483 if (TOR_TLS_IS_ERROR(result
) || result
== TOR_TLS_CLOSE
)
2484 or_conn
->tls_error
= result
;
2486 or_conn
->tls_error
= 0;
2490 case TOR_TLS_ERROR_IO
:
2491 log_debug(LD_NET
,"TLS connection closed %son read. Closing. "
2492 "(Nickname %s, address %s)",
2493 result
== TOR_TLS_CLOSE
? "cleanly " : "",
2494 or_conn
->nickname
? or_conn
->nickname
: "not set",
2497 CASE_TOR_TLS_ERROR_ANY_NONIO
:
2498 log_debug(LD_NET
,"tls error [%s]. breaking (nickname %s, address %s).",
2499 tor_tls_err_to_string(result
),
2500 or_conn
->nickname
? or_conn
->nickname
: "not set",
2503 case TOR_TLS_WANTWRITE
:
2504 connection_start_writing(conn
);
2506 case TOR_TLS_WANTREAD
: /* we're already reading */
2507 case TOR_TLS_DONE
: /* no data read, so nothing to process */
2509 break; /* so we call bucket_decrement below */
2513 pending
= tor_tls_get_pending_bytes(or_conn
->tls
);
2515 /* If we have any pending bytes, we read them now. This *can*
2516 * take us over our read allotment, but really we shouldn't be
2517 * believing that SSL bytes are the same as TCP bytes anyway. */
2518 int r2
= read_to_buf_tls(or_conn
->tls
, pending
, conn
->inbuf
);
2520 log_warn(LD_BUG
, "apparently, reading pending bytes can fail.");
2524 result
= (int)(buf_datalen(conn
->inbuf
)-initial_size
);
2525 tor_tls_get_n_raw_bytes(or_conn
->tls
, &n_read
, &n_written
);
2526 log_debug(LD_GENERAL
, "After TLS read of %d: %ld read, %ld written",
2527 result
, (long)n_read
, (long)n_written
);
2528 } else if (conn
->linked
) {
2529 if (conn
->linked_conn
) {
2530 result
= move_buf_to_buf(conn
->inbuf
, conn
->linked_conn
->outbuf
,
2531 &conn
->linked_conn
->outbuf_flushlen
);
2535 //log_notice(LD_GENERAL, "Moved %d bytes on an internal link!", result);
2536 /* If the other side has disappeared, or if it's been marked for close and
2537 * we flushed its outbuf, then we should set our inbuf_reached_eof. */
2538 if (!conn
->linked_conn
||
2539 (conn
->linked_conn
->marked_for_close
&&
2540 buf_datalen(conn
->linked_conn
->outbuf
) == 0))
2541 conn
->inbuf_reached_eof
= 1;
2543 n_read
= (size_t) result
;
2545 /* !connection_speaks_cells, !conn->linked_conn. */
2546 int reached_eof
= 0;
2547 CONN_LOG_PROTECT(conn
,
2548 result
= read_to_buf(conn
->s
, at_most
, conn
->inbuf
, &reached_eof
,
2551 conn
->inbuf_reached_eof
= 1;
2553 // log_fn(LOG_DEBUG,"read_to_buf returned %d.",read_result);
2557 n_read
= (size_t) result
;
2560 if (n_read
> 0) { /* change *max_to_read */
2561 /*XXXX021 check for overflow*/
2562 *max_to_read
= (int)(at_most
- n_read
);
2565 if (conn
->type
== CONN_TYPE_AP
) {
2566 edge_connection_t
*edge_conn
= TO_EDGE_CONN(conn
);
2567 /*XXXX021 check for overflow*/
2568 edge_conn
->n_read
+= (int)n_read
;
2571 connection_buckets_decrement(conn
, approx_time(), n_read
, n_written
);
2573 if (more_to_read
&& result
== at_most
) {
2574 slack_in_buf
= buf_slack(conn
->inbuf
);
2575 at_most
= more_to_read
;
2579 /* Call even if result is 0, since the global read bucket may
2580 * have reached 0 on a different conn, and this guy needs to
2581 * know to stop reading. */
2582 connection_consider_empty_read_buckets(conn
);
2583 if (n_written
> 0 && connection_is_writing(conn
))
2584 connection_consider_empty_write_buckets(conn
);
2589 /** A pass-through to fetch_from_buf. */
2591 connection_fetch_from_buf(char *string
, size_t len
, connection_t
*conn
)
2593 return fetch_from_buf(string
, len
, conn
->inbuf
);
2596 /** Return conn-\>outbuf_flushlen: how many bytes conn wants to flush
2597 * from its outbuf. */
2599 connection_wants_to_flush(connection_t
*conn
)
2601 return conn
->outbuf_flushlen
> 0;
2604 /** Are there too many bytes on edge connection <b>conn</b>'s outbuf to
2605 * send back a relay-level sendme yet? Return 1 if so, 0 if not. Used by
2606 * connection_edge_consider_sending_sendme().
2609 connection_outbuf_too_full(connection_t
*conn
)
2611 return (conn
->outbuf_flushlen
> 10*CELL_PAYLOAD_SIZE
);
2614 /** Try to flush more bytes onto conn-\>s.
2616 * This function gets called either from conn_write() in main.c
2617 * when poll() has declared that conn wants to write, or below
2618 * from connection_write_to_buf() when an entire TLS record is ready.
2620 * Update conn-\>timestamp_lastwritten to now, and call flush_buf
2621 * or flush_buf_tls appropriately. If it succeeds and there are no more
2622 * more bytes on conn->outbuf, then call connection_finished_flushing
2625 * If <b>force</b>, then write as many bytes as possible, ignoring bandwidth
2626 * limits. (Used for flushing messages to controller connections on fatal
2629 * Mark the connection and return -1 if you want to close it, else
2633 connection_handle_write_impl(connection_t
*conn
, int force
)
2636 socklen_t len
=(socklen_t
)sizeof(e
);
2638 ssize_t max_to_write
;
2639 time_t now
= approx_time();
2640 size_t n_read
= 0, n_written
= 0;
2642 tor_assert(!connection_is_listener(conn
));
2644 if (conn
->marked_for_close
|| conn
->s
< 0)
2645 return 0; /* do nothing */
2647 if (conn
->in_flushed_some
) {
2648 log_warn(LD_BUG
, "called recursively from inside conn->in_flushed_some");
2652 conn
->timestamp_lastwritten
= now
;
2654 /* Sometimes, "writable" means "connected". */
2655 if (connection_state_is_connecting(conn
)) {
2656 if (getsockopt(conn
->s
, SOL_SOCKET
, SO_ERROR
, (void*)&e
, &len
) < 0) {
2658 "getsockopt() syscall failed?! Please report to tor-ops.");
2659 if (CONN_IS_EDGE(conn
))
2660 connection_edge_end_errno(TO_EDGE_CONN(conn
));
2661 connection_mark_for_close(conn
);
2665 /* some sort of error, but maybe just inprogress still */
2666 if (!ERRNO_IS_CONN_EINPROGRESS(e
)) {
2667 log_info(LD_NET
,"in-progress connect failed. Removing. (%s)",
2668 tor_socket_strerror(e
));
2669 if (CONN_IS_EDGE(conn
))
2670 connection_edge_end_errno(TO_EDGE_CONN(conn
));
2671 if (conn
->type
== CONN_TYPE_OR
)
2672 connection_or_connect_failed(TO_OR_CONN(conn
),
2673 errno_to_orconn_end_reason(e
),
2674 tor_socket_strerror(e
));
2676 connection_close_immediate(conn
);
2677 connection_mark_for_close(conn
);
2680 return 0; /* no change, see if next time is better */
2683 /* The connection is successful. */
2684 if (connection_finished_connecting(conn
)<0)
2688 max_to_write
= force
? (ssize_t
)conn
->outbuf_flushlen
2689 : connection_bucket_write_limit(conn
, now
);
2691 if (connection_speaks_cells(conn
) &&
2692 conn
->state
> OR_CONN_STATE_PROXY_HANDSHAKING
) {
2693 or_connection_t
*or_conn
= TO_OR_CONN(conn
);
2694 if (conn
->state
== OR_CONN_STATE_TLS_HANDSHAKING
||
2695 conn
->state
== OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING
) {
2696 connection_stop_writing(conn
);
2697 if (connection_tls_continue_handshake(or_conn
) < 0) {
2698 /* Don't flush; connection is dead. */
2699 connection_close_immediate(conn
);
2700 connection_mark_for_close(conn
);
2704 } else if (conn
->state
== OR_CONN_STATE_TLS_SERVER_RENEGOTIATING
) {
2705 return connection_handle_read(conn
);
2708 /* else open, or closing */
2709 result
= flush_buf_tls(or_conn
->tls
, conn
->outbuf
,
2710 max_to_write
, &conn
->outbuf_flushlen
);
2712 /* If we just flushed the last bytes, check if this tunneled dir
2713 * request is done. */
2714 if (buf_datalen(conn
->outbuf
) == 0 && conn
->dirreq_id
)
2715 geoip_change_dirreq_state(conn
->dirreq_id
, DIRREQ_TUNNELED
,
2716 DIRREQ_OR_CONN_BUFFER_FLUSHED
);
2719 CASE_TOR_TLS_ERROR_ANY
:
2721 log_info(LD_NET
,result
!=TOR_TLS_CLOSE
?
2722 "tls error. breaking.":"TLS connection closed on flush");
2723 /* Don't flush; connection is dead. */
2724 connection_close_immediate(conn
);
2725 connection_mark_for_close(conn
);
2727 case TOR_TLS_WANTWRITE
:
2728 log_debug(LD_NET
,"wanted write.");
2729 /* we're already writing */
2731 case TOR_TLS_WANTREAD
:
2732 /* Make sure to avoid a loop if the receive buckets are empty. */
2733 log_debug(LD_NET
,"wanted read.");
2734 if (!connection_is_reading(conn
)) {
2735 connection_stop_writing(conn
);
2736 conn
->write_blocked_on_bw
= 1;
2737 /* we'll start reading again when we get more tokens in our
2738 * read bucket; then we'll start writing again too.
2741 /* else no problem, we're already reading */
2743 /* case TOR_TLS_DONE:
2744 * for TOR_TLS_DONE, fall through to check if the flushlen
2745 * is empty, so we can stop writing.
2749 tor_tls_get_n_raw_bytes(or_conn
->tls
, &n_read
, &n_written
);
2750 log_debug(LD_GENERAL
, "After TLS write of %d: %ld read, %ld written",
2751 result
, (long)n_read
, (long)n_written
);
2753 CONN_LOG_PROTECT(conn
,
2754 result
= flush_buf(conn
->s
, conn
->outbuf
,
2755 max_to_write
, &conn
->outbuf_flushlen
));
2757 if (CONN_IS_EDGE(conn
))
2758 connection_edge_end_errno(TO_EDGE_CONN(conn
));
2760 connection_close_immediate(conn
); /* Don't flush; connection is dead. */
2761 connection_mark_for_close(conn
);
2764 n_written
= (size_t) result
;
2767 if (conn
->type
== CONN_TYPE_AP
) {
2768 edge_connection_t
*edge_conn
= TO_EDGE_CONN(conn
);
2769 /*XXXX021 check for overflow.*/
2770 edge_conn
->n_written
+= (int)n_written
;
2773 connection_buckets_decrement(conn
, approx_time(), n_read
, n_written
);
2776 /* If we wrote any bytes from our buffer, then call the appropriate
2778 if (connection_flushed_some(conn
) < 0)
2779 connection_mark_for_close(conn
);
2782 if (!connection_wants_to_flush(conn
)) { /* it's done flushing */
2783 if (connection_finished_flushing(conn
) < 0) {
2784 /* already marked */
2790 /* Call even if result is 0, since the global write bucket may
2791 * have reached 0 on a different conn, and this guy needs to
2792 * know to stop writing. */
2793 connection_consider_empty_write_buckets(conn
);
2794 if (n_read
> 0 && connection_is_reading(conn
))
2795 connection_consider_empty_read_buckets(conn
);
2801 connection_handle_write(connection_t
*conn
, int force
)
2804 tor_gettimeofday_cache_clear();
2805 res
= connection_handle_write_impl(conn
, force
);
2809 /** OpenSSL TLS record size is 16383; this is close. The goal here is to
2810 * push data out as soon as we know there's enough for a TLS record, so
2811 * during periods of high load we won't read entire megabytes from
2812 * input before pushing any data out. It also has the feature of not
2813 * growing huge outbufs unless something is slow. */
2814 #define MIN_TLS_FLUSHLEN 15872
2816 /** Append <b>len</b> bytes of <b>string</b> onto <b>conn</b>'s
2817 * outbuf, and ask it to start writing.
2819 * If <b>zlib</b> is nonzero, this is a directory connection that should get
2820 * its contents compressed or decompressed as they're written. If zlib is
2821 * negative, this is the last data to be compressed, and the connection's zlib
2822 * state should be flushed.
2824 * If it's an OR conn and an entire TLS record is ready, then try to
2825 * flush the record now. Similarly, if it's a local control connection
2826 * and a 64k chunk is ready, try to flush it all, so we don't end up with
2827 * many megabytes of controller info queued at once.
2830 _connection_write_to_buf_impl(const char *string
, size_t len
,
2831 connection_t
*conn
, int zlib
)
2833 /* XXXX This function really needs to return -1 on failure. */
2836 if (!len
&& !(zlib
<0))
2838 /* if it's marked for close, only allow write if we mean to flush it */
2839 if (conn
->marked_for_close
&& !conn
->hold_open_until_flushed
)
2842 old_datalen
= buf_datalen(conn
->outbuf
);
2844 dir_connection_t
*dir_conn
= TO_DIR_CONN(conn
);
2845 int done
= zlib
< 0;
2846 CONN_LOG_PROTECT(conn
, r
= write_to_buf_zlib(conn
->outbuf
,
2847 dir_conn
->zlib_state
,
2848 string
, len
, done
));
2850 CONN_LOG_PROTECT(conn
, r
= write_to_buf(string
, len
, conn
->outbuf
));
2853 if (CONN_IS_EDGE(conn
)) {
2854 /* if it failed, it means we have our package/delivery windows set
2855 wrong compared to our max outbuf size. close the whole circuit. */
2857 "write_to_buf failed. Closing circuit (fd %d).", conn
->s
);
2858 circuit_mark_for_close(circuit_get_by_edge_conn(TO_EDGE_CONN(conn
)),
2859 END_CIRC_REASON_INTERNAL
);
2862 "write_to_buf failed. Closing connection (fd %d).", conn
->s
);
2863 connection_mark_for_close(conn
);
2868 connection_start_writing(conn
);
2870 conn
->outbuf_flushlen
+= buf_datalen(conn
->outbuf
) - old_datalen
;
2873 conn
->outbuf_flushlen
+= len
;
2875 /* Should we try flushing the outbuf now? */
2876 if (conn
->in_flushed_some
) {
2877 /* Don't flush the outbuf when the reason we're writing more stuff is
2878 * _because_ we flushed the outbuf. That's unfair. */
2882 if (conn
->type
== CONN_TYPE_OR
&&
2883 conn
->outbuf_flushlen
-len
< MIN_TLS_FLUSHLEN
&&
2884 conn
->outbuf_flushlen
>= MIN_TLS_FLUSHLEN
) {
2885 /* We just pushed outbuf_flushlen to MIN_TLS_FLUSHLEN or above;
2886 * we can send out a full TLS frame now if we like. */
2887 extra
= conn
->outbuf_flushlen
- MIN_TLS_FLUSHLEN
;
2888 conn
->outbuf_flushlen
= MIN_TLS_FLUSHLEN
;
2889 } else if (conn
->type
== CONN_TYPE_CONTROL
&&
2890 !connection_is_rate_limited(conn
) &&
2891 conn
->outbuf_flushlen
-len
< 1<<16 &&
2892 conn
->outbuf_flushlen
>= 1<<16) {
2893 /* just try to flush all of it */
2895 return; /* no need to try flushing */
2897 if (connection_handle_write(conn
, 0) < 0) {
2898 if (!conn
->marked_for_close
) {
2899 /* this connection is broken. remove it. */
2900 log_warn(LD_BUG
, "unhandled error on write for "
2901 "conn (type %d, fd %d); removing",
2902 conn
->type
, conn
->s
);
2903 tor_fragile_assert();
2904 /* do a close-immediate here, so we don't try to flush */
2905 connection_close_immediate(conn
);
2910 conn
->outbuf_flushlen
+= extra
;
2911 connection_start_writing(conn
);
2916 /** Return a connection with given type, address, port, and purpose;
2917 * or NULL if no such connection exists. */
2919 connection_get_by_type_addr_port_purpose(int type
,
2920 const tor_addr_t
*addr
, uint16_t port
,
2923 smartlist_t
*conns
= get_connection_array();
2924 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
2926 if (conn
->type
== type
&&
2927 tor_addr_eq(&conn
->addr
, addr
) &&
2928 conn
->port
== port
&&
2929 conn
->purpose
== purpose
&&
2930 !conn
->marked_for_close
)
2936 /** Return the stream with id <b>id</b> if it is not already marked for
2940 connection_get_by_global_id(uint64_t id
)
2942 smartlist_t
*conns
= get_connection_array();
2943 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
2945 if (conn
->global_identifier
== id
)
2951 /** Return a connection of type <b>type</b> that is not marked for close.
2954 connection_get_by_type(int type
)
2956 smartlist_t
*conns
= get_connection_array();
2957 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
2959 if (conn
->type
== type
&& !conn
->marked_for_close
)
2965 /** Return a connection of type <b>type</b> that is in state <b>state</b>,
2966 * and that is not marked for close.
2969 connection_get_by_type_state(int type
, int state
)
2971 smartlist_t
*conns
= get_connection_array();
2972 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
2974 if (conn
->type
== type
&& conn
->state
== state
&& !conn
->marked_for_close
)
2980 /** Return a connection of type <b>type</b> that has rendquery equal
2981 * to <b>rendquery</b>, and that is not marked for close. If state
2982 * is non-zero, conn must be of that state too.
2985 connection_get_by_type_state_rendquery(int type
, int state
,
2986 const char *rendquery
)
2988 smartlist_t
*conns
= get_connection_array();
2990 tor_assert(type
== CONN_TYPE_DIR
||
2991 type
== CONN_TYPE_AP
|| type
== CONN_TYPE_EXIT
);
2992 tor_assert(rendquery
);
2994 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
2996 if (conn
->type
== type
&&
2997 !conn
->marked_for_close
&&
2998 (!state
|| state
== conn
->state
)) {
2999 if (type
== CONN_TYPE_DIR
&&
3000 TO_DIR_CONN(conn
)->rend_data
&&
3001 !rend_cmp_service_ids(rendquery
,
3002 TO_DIR_CONN(conn
)->rend_data
->onion_address
))
3004 else if (CONN_IS_EDGE(conn
) &&
3005 TO_EDGE_CONN(conn
)->rend_data
&&
3006 !rend_cmp_service_ids(rendquery
,
3007 TO_EDGE_CONN(conn
)->rend_data
->onion_address
))
3014 /** Return an open, non-marked connection of a given type and purpose, or NULL
3015 * if no such connection exists. */
3017 connection_get_by_type_purpose(int type
, int purpose
)
3019 smartlist_t
*conns
= get_connection_array();
3020 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
3022 if (conn
->type
== type
&&
3023 !conn
->marked_for_close
&&
3024 (purpose
== conn
->purpose
))
3030 /** Return 1 if <b>conn</b> is a listener conn, else return 0. */
3032 connection_is_listener(connection_t
*conn
)
3034 if (conn
->type
== CONN_TYPE_OR_LISTENER
||
3035 conn
->type
== CONN_TYPE_AP_LISTENER
||
3036 conn
->type
== CONN_TYPE_AP_TRANS_LISTENER
||
3037 conn
->type
== CONN_TYPE_AP_DNS_LISTENER
||
3038 conn
->type
== CONN_TYPE_AP_NATD_LISTENER
||
3039 conn
->type
== CONN_TYPE_DIR_LISTENER
||
3040 conn
->type
== CONN_TYPE_CONTROL_LISTENER
)
3045 /** Return 1 if <b>conn</b> is in state "open" and is not marked
3046 * for close, else return 0.
3049 connection_state_is_open(connection_t
*conn
)
3053 if (conn
->marked_for_close
)
3056 if ((conn
->type
== CONN_TYPE_OR
&& conn
->state
== OR_CONN_STATE_OPEN
) ||
3057 (conn
->type
== CONN_TYPE_AP
&& conn
->state
== AP_CONN_STATE_OPEN
) ||
3058 (conn
->type
== CONN_TYPE_EXIT
&& conn
->state
== EXIT_CONN_STATE_OPEN
) ||
3059 (conn
->type
== CONN_TYPE_CONTROL
&&
3060 conn
->state
== CONTROL_CONN_STATE_OPEN
))
3066 /** Return 1 if conn is in 'connecting' state, else return 0. */
3068 connection_state_is_connecting(connection_t
*conn
)
3072 if (conn
->marked_for_close
)
3077 return conn
->state
== OR_CONN_STATE_CONNECTING
;
3078 case CONN_TYPE_EXIT
:
3079 return conn
->state
== EXIT_CONN_STATE_CONNECTING
;
3081 return conn
->state
== DIR_CONN_STATE_CONNECTING
;
3087 /** Allocates a base64'ed authenticator for use in http or https
3088 * auth, based on the input string <b>authenticator</b>. Returns it
3089 * if success, else returns NULL. */
3091 alloc_http_authenticator(const char *authenticator
)
3093 /* an authenticator in Basic authentication
3094 * is just the string "username:password" */
3095 const size_t authenticator_length
= strlen(authenticator
);
3096 /* The base64_encode function needs a minimum buffer length
3098 const size_t base64_authenticator_length
= (authenticator_length
/48+1)*66;
3099 char *base64_authenticator
= tor_malloc(base64_authenticator_length
);
3100 if (base64_encode(base64_authenticator
, base64_authenticator_length
,
3101 authenticator
, authenticator_length
) < 0) {
3102 tor_free(base64_authenticator
); /* free and set to null */
3104 /* remove extra \n at end of encoding */
3105 base64_authenticator
[strlen(base64_authenticator
) - 1] = 0;
3107 return base64_authenticator
;
3110 /** Given a socket handle, check whether the local address (sockname) of the
3111 * socket is one that we've connected from before. If so, double-check
3112 * whether our address has changed and we need to generate keys. If we do,
3116 client_check_address_changed(int sock
)
3118 uint32_t iface_ip
, ip_out
; /* host order */
3119 struct sockaddr_in out_addr
;
3120 socklen_t out_addr_len
= (socklen_t
) sizeof(out_addr
);
3121 uint32_t *ip
; /* host order */
3123 if (!last_interface_ip
)
3124 get_interface_address(LOG_INFO
, &last_interface_ip
);
3125 if (!outgoing_addrs
)
3126 outgoing_addrs
= smartlist_create();
3128 if (getsockname(sock
, (struct sockaddr
*)&out_addr
, &out_addr_len
)<0) {
3129 int e
= tor_socket_errno(sock
);
3130 log_warn(LD_NET
, "getsockname() to check for address change failed: %s",
3131 tor_socket_strerror(e
));
3135 /* If we've used this address previously, we're okay. */
3136 ip_out
= ntohl(out_addr
.sin_addr
.s_addr
);
3137 SMARTLIST_FOREACH(outgoing_addrs
, uint32_t*, ip_ptr
,
3138 if (*ip_ptr
== ip_out
) return;
3141 /* Uh-oh. We haven't connected from this address before. Has the interface
3142 * address changed? */
3143 if (get_interface_address(LOG_INFO
, &iface_ip
)<0)
3145 ip
= tor_malloc(sizeof(uint32_t));
3148 if (iface_ip
== last_interface_ip
) {
3149 /* Nope, it hasn't changed. Add this address to the list. */
3150 smartlist_add(outgoing_addrs
, ip
);
3152 /* The interface changed. We're a client, so we need to regenerate our
3153 * keys. First, reset the state. */
3154 log(LOG_NOTICE
, LD_NET
, "Our IP address has changed. Rotating keys...");
3155 last_interface_ip
= iface_ip
;
3156 SMARTLIST_FOREACH(outgoing_addrs
, void*, ip_ptr
, tor_free(ip_ptr
));
3157 smartlist_clear(outgoing_addrs
);
3158 smartlist_add(outgoing_addrs
, ip
);
3159 /* Okay, now change our keys. */
3160 ip_address_changed(1);
3164 /** Some systems have limited system buffers for recv and xmit on
3165 * sockets allocated in a virtual server or similar environment. For a Tor
3166 * server this can produce the "Error creating network socket: No buffer
3167 * space available" error once all available TCP buffer space is consumed.
3168 * This method will attempt to constrain the buffers allocated for the socket
3169 * to the desired size to stay below system TCP buffer limits.
3172 set_constrained_socket_buffers(int sock
, int size
)
3174 void *sz
= (void*)&size
;
3175 socklen_t sz_sz
= (socklen_t
) sizeof(size
);
3176 if (setsockopt(sock
, SOL_SOCKET
, SO_SNDBUF
, sz
, sz_sz
) < 0) {
3177 int e
= tor_socket_errno(sock
);
3178 log_warn(LD_NET
, "setsockopt() to constrain send "
3179 "buffer to %d bytes failed: %s", size
, tor_socket_strerror(e
));
3181 if (setsockopt(sock
, SOL_SOCKET
, SO_RCVBUF
, sz
, sz_sz
) < 0) {
3182 int e
= tor_socket_errno(sock
);
3183 log_warn(LD_NET
, "setsockopt() to constrain recv "
3184 "buffer to %d bytes failed: %s", size
, tor_socket_strerror(e
));
3188 /** Process new bytes that have arrived on conn-\>inbuf.
3190 * This function just passes conn to the connection-specific
3191 * connection_*_process_inbuf() function. It also passes in
3192 * package_partial if wanted.
3195 connection_process_inbuf(connection_t
*conn
, int package_partial
)
3199 switch (conn
->type
) {
3201 return connection_or_process_inbuf(TO_OR_CONN(conn
));
3202 case CONN_TYPE_EXIT
:
3204 return connection_edge_process_inbuf(TO_EDGE_CONN(conn
),
3207 return connection_dir_process_inbuf(TO_DIR_CONN(conn
));
3208 case CONN_TYPE_CPUWORKER
:
3209 return connection_cpu_process_inbuf(conn
);
3210 case CONN_TYPE_CONTROL
:
3211 return connection_control_process_inbuf(TO_CONTROL_CONN(conn
));
3213 log_err(LD_BUG
,"got unexpected conn type %d.", conn
->type
);
3214 tor_fragile_assert();
3219 /** Called whenever we've written data on a connection. */
3221 connection_flushed_some(connection_t
*conn
)
3224 tor_assert(!conn
->in_flushed_some
);
3225 conn
->in_flushed_some
= 1;
3226 if (conn
->type
== CONN_TYPE_DIR
&&
3227 conn
->state
== DIR_CONN_STATE_SERVER_WRITING
) {
3228 r
= connection_dirserv_flushed_some(TO_DIR_CONN(conn
));
3229 } else if (conn
->type
== CONN_TYPE_OR
) {
3230 r
= connection_or_flushed_some(TO_OR_CONN(conn
));
3232 conn
->in_flushed_some
= 0;
3236 /** We just finished flushing bytes from conn-\>outbuf, and there
3237 * are no more bytes remaining.
3239 * This function just passes conn to the connection-specific
3240 * connection_*_finished_flushing() function.
3243 connection_finished_flushing(connection_t
*conn
)
3247 /* If the connection is closed, don't try to do anything more here. */
3248 if (CONN_IS_CLOSED(conn
))
3251 // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
3253 switch (conn
->type
) {
3255 return connection_or_finished_flushing(TO_OR_CONN(conn
));
3257 case CONN_TYPE_EXIT
:
3258 return connection_edge_finished_flushing(TO_EDGE_CONN(conn
));
3260 return connection_dir_finished_flushing(TO_DIR_CONN(conn
));
3261 case CONN_TYPE_CPUWORKER
:
3262 return connection_cpu_finished_flushing(conn
);
3263 case CONN_TYPE_CONTROL
:
3264 return connection_control_finished_flushing(TO_CONTROL_CONN(conn
));
3266 log_err(LD_BUG
,"got unexpected conn type %d.", conn
->type
);
3267 tor_fragile_assert();
3272 /** Called when our attempt to connect() to another server has just
3275 * This function just passes conn to the connection-specific
3276 * connection_*_finished_connecting() function.
3279 connection_finished_connecting(connection_t
*conn
)
3285 return connection_or_finished_connecting(TO_OR_CONN(conn
));
3286 case CONN_TYPE_EXIT
:
3287 return connection_edge_finished_connecting(TO_EDGE_CONN(conn
));
3289 return connection_dir_finished_connecting(TO_DIR_CONN(conn
));
3291 log_err(LD_BUG
,"got unexpected conn type %d.", conn
->type
);
3292 tor_fragile_assert();
3297 /** Callback: invoked when a connection reaches an EOF event. */
3299 connection_reached_eof(connection_t
*conn
)
3301 switch (conn
->type
) {
3303 return connection_or_reached_eof(TO_OR_CONN(conn
));
3305 case CONN_TYPE_EXIT
:
3306 return connection_edge_reached_eof(TO_EDGE_CONN(conn
));
3308 return connection_dir_reached_eof(TO_DIR_CONN(conn
));
3309 case CONN_TYPE_CPUWORKER
:
3310 return connection_cpu_reached_eof(conn
);
3311 case CONN_TYPE_CONTROL
:
3312 return connection_control_reached_eof(TO_CONTROL_CONN(conn
));
3314 log_err(LD_BUG
,"got unexpected conn type %d.", conn
->type
);
3315 tor_fragile_assert();
3320 /** Log how many bytes are used by buffers of different kinds and sizes. */
3322 connection_dump_buffer_mem_stats(int severity
)
3324 uint64_t used_by_type
[_CONN_TYPE_MAX
+1];
3325 uint64_t alloc_by_type
[_CONN_TYPE_MAX
+1];
3326 int n_conns_by_type
[_CONN_TYPE_MAX
+1];
3327 uint64_t total_alloc
= 0;
3328 uint64_t total_used
= 0;
3330 smartlist_t
*conns
= get_connection_array();
3332 memset(used_by_type
, 0, sizeof(used_by_type
));
3333 memset(alloc_by_type
, 0, sizeof(alloc_by_type
));
3334 memset(n_conns_by_type
, 0, sizeof(n_conns_by_type
));
3336 SMARTLIST_FOREACH(conns
, connection_t
*, c
,
3339 ++n_conns_by_type
[tp
];
3341 used_by_type
[tp
] += buf_datalen(c
->inbuf
);
3342 alloc_by_type
[tp
] += buf_allocation(c
->inbuf
);
3345 used_by_type
[tp
] += buf_datalen(c
->outbuf
);
3346 alloc_by_type
[tp
] += buf_allocation(c
->outbuf
);
3349 for (i
=0; i
<= _CONN_TYPE_MAX
; ++i
) {
3350 total_used
+= used_by_type
[i
];
3351 total_alloc
+= alloc_by_type
[i
];
3354 log(severity
, LD_GENERAL
,
3355 "In buffers for %d connections: "U64_FORMAT
" used/"U64_FORMAT
" allocated",
3356 smartlist_len(conns
),
3357 U64_PRINTF_ARG(total_used
), U64_PRINTF_ARG(total_alloc
));
3358 for (i
=_CONN_TYPE_MIN
; i
<= _CONN_TYPE_MAX
; ++i
) {
3359 if (!n_conns_by_type
[i
])
3361 log(severity
, LD_GENERAL
,
3362 " For %d %s connections: "U64_FORMAT
" used/"U64_FORMAT
" allocated",
3363 n_conns_by_type
[i
], conn_type_to_string(i
),
3364 U64_PRINTF_ARG(used_by_type
[i
]), U64_PRINTF_ARG(alloc_by_type
[i
]));
3368 /** Verify that connection <b>conn</b> has all of its invariants
3369 * correct. Trigger an assert if anything is invalid.
3372 assert_connection_ok(connection_t
*conn
, time_t now
)
3374 (void) now
; /* XXXX unused. */
3376 tor_assert(conn
->type
>= _CONN_TYPE_MIN
);
3377 tor_assert(conn
->type
<= _CONN_TYPE_MAX
);
3378 switch (conn
->type
) {
3380 tor_assert(conn
->magic
== OR_CONNECTION_MAGIC
);
3383 case CONN_TYPE_EXIT
:
3384 tor_assert(conn
->magic
== EDGE_CONNECTION_MAGIC
);
3387 tor_assert(conn
->magic
== DIR_CONNECTION_MAGIC
);
3389 case CONN_TYPE_CONTROL
:
3390 tor_assert(conn
->magic
== CONTROL_CONNECTION_MAGIC
);
3393 tor_assert(conn
->magic
== BASE_CONNECTION_MAGIC
);
3397 if (conn
->linked_conn
) {
3398 tor_assert(conn
->linked_conn
->linked_conn
== conn
);
3399 tor_assert(conn
->linked
);
3402 tor_assert(conn
->s
< 0);
3404 if (conn
->outbuf_flushlen
> 0) {
3405 tor_assert(connection_is_writing(conn
) || conn
->write_blocked_on_bw
||
3406 (CONN_IS_EDGE(conn
) && TO_EDGE_CONN(conn
)->edge_blocked_on_circ
));
3409 if (conn
->hold_open_until_flushed
)
3410 tor_assert(conn
->marked_for_close
);
3412 /* XXXX check: read_blocked_on_bw, write_blocked_on_bw, s, conn_array_index,
3413 * marked_for_close. */
3416 if (!connection_is_listener(conn
)) {
3417 assert_buf_ok(conn
->inbuf
);
3418 assert_buf_ok(conn
->outbuf
);
3421 if (conn
->type
== CONN_TYPE_OR
) {
3422 or_connection_t
*or_conn
= TO_OR_CONN(conn
);
3423 if (conn
->state
== OR_CONN_STATE_OPEN
) {
3424 /* tor_assert(conn->bandwidth > 0); */
3425 /* the above isn't necessarily true: if we just did a TLS
3426 * handshake but we didn't recognize the other peer, or it
3427 * gave a bad cert/etc, then we won't have assigned bandwidth,
3428 * yet it will be open. -RD
3430 // tor_assert(conn->read_bucket >= 0);
3432 // tor_assert(conn->addr && conn->port);
3433 tor_assert(conn
->address
);
3434 if (conn
->state
> OR_CONN_STATE_PROXY_HANDSHAKING
)
3435 tor_assert(or_conn
->tls
);
3438 if (CONN_IS_EDGE(conn
)) {
3439 edge_connection_t
*edge_conn
= TO_EDGE_CONN(conn
);
3440 if (edge_conn
->chosen_exit_optional
|| edge_conn
->chosen_exit_retries
) {
3441 tor_assert(conn
->type
== CONN_TYPE_AP
);
3442 tor_assert(edge_conn
->chosen_exit_name
);
3445 /* XXX unchecked: package window, deliver window. */
3446 if (conn
->type
== CONN_TYPE_AP
) {
3448 tor_assert(edge_conn
->socks_request
);
3449 if (conn
->state
== AP_CONN_STATE_OPEN
) {
3450 tor_assert(edge_conn
->socks_request
->has_finished
);
3451 if (!conn
->marked_for_close
) {
3452 tor_assert(edge_conn
->cpath_layer
);
3453 assert_cpath_layer_ok(edge_conn
->cpath_layer
);
3457 if (conn
->type
== CONN_TYPE_EXIT
) {
3458 tor_assert(conn
->purpose
== EXIT_PURPOSE_CONNECT
||
3459 conn
->purpose
== EXIT_PURPOSE_RESOLVE
);
3461 } else if (conn
->type
== CONN_TYPE_DIR
) {
3463 /* Purpose is only used for dir and exit types currently */
3464 tor_assert(!conn
->purpose
);
3469 case CONN_TYPE_OR_LISTENER
:
3470 case CONN_TYPE_AP_LISTENER
:
3471 case CONN_TYPE_AP_TRANS_LISTENER
:
3472 case CONN_TYPE_AP_NATD_LISTENER
:
3473 case CONN_TYPE_DIR_LISTENER
:
3474 case CONN_TYPE_CONTROL_LISTENER
:
3475 case CONN_TYPE_AP_DNS_LISTENER
:
3476 tor_assert(conn
->state
== LISTENER_STATE_READY
);
3479 tor_assert(conn
->state
>= _OR_CONN_STATE_MIN
);
3480 tor_assert(conn
->state
<= _OR_CONN_STATE_MAX
);
3481 tor_assert(TO_OR_CONN(conn
)->n_circuits
>= 0);
3483 case CONN_TYPE_EXIT
:
3484 tor_assert(conn
->state
>= _EXIT_CONN_STATE_MIN
);
3485 tor_assert(conn
->state
<= _EXIT_CONN_STATE_MAX
);
3486 tor_assert(conn
->purpose
>= _EXIT_PURPOSE_MIN
);
3487 tor_assert(conn
->purpose
<= _EXIT_PURPOSE_MAX
);
3490 tor_assert(conn
->state
>= _AP_CONN_STATE_MIN
);
3491 tor_assert(conn
->state
<= _AP_CONN_STATE_MAX
);
3492 tor_assert(TO_EDGE_CONN(conn
)->socks_request
);
3495 tor_assert(conn
->state
>= _DIR_CONN_STATE_MIN
);
3496 tor_assert(conn
->state
<= _DIR_CONN_STATE_MAX
);
3497 tor_assert(conn
->purpose
>= _DIR_PURPOSE_MIN
);
3498 tor_assert(conn
->purpose
<= _DIR_PURPOSE_MAX
);
3500 case CONN_TYPE_CPUWORKER
:
3501 tor_assert(conn
->state
>= _CPUWORKER_STATE_MIN
);
3502 tor_assert(conn
->state
<= _CPUWORKER_STATE_MAX
);
3504 case CONN_TYPE_CONTROL
:
3505 tor_assert(conn
->state
>= _CONTROL_CONN_STATE_MIN
);
3506 tor_assert(conn
->state
<= _CONTROL_CONN_STATE_MAX
);