stop assuming that our downcasts have a struct offset of 0
[tor.git] / src / or / connection.c
blob48740412c4a1437851d169cfc0f6e092a8090928
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-2009, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file connection.c
9 * \brief General high-level functions to handle reading and writing
10 * on connections.
11 **/
13 #include "or.h"
15 static connection_t *connection_create_listener(
16 struct sockaddr *listensockaddr,
17 socklen_t listensocklen, int type,
18 char* address);
19 static void connection_init(time_t now, connection_t *conn, int type,
20 int socket_family);
21 static int connection_init_accepted_conn(connection_t *conn,
22 uint8_t listener_type);
23 static int connection_handle_listener_read(connection_t *conn, int new_type);
24 static int connection_read_bucket_should_increase(or_connection_t *conn);
25 static int connection_finished_flushing(connection_t *conn);
26 static int connection_flushed_some(connection_t *conn);
27 static int connection_finished_connecting(connection_t *conn);
28 static int connection_reached_eof(connection_t *conn);
29 static int connection_read_to_buf(connection_t *conn, int *max_to_read,
30 int *socket_error);
31 static int connection_process_inbuf(connection_t *conn, int package_partial);
32 static void client_check_address_changed(int sock);
33 static void set_constrained_socket_buffers(int sock, int size);
35 static const char *connection_proxy_state_to_string(int state);
36 static int connection_read_https_proxy_response(connection_t *conn);
37 static void connection_send_socks5_connect(connection_t *conn);
39 /** The last IPv4 address that our network interface seemed to have been
40 * binding to, in host order. We use this to detect when our IP changes. */
41 static uint32_t last_interface_ip = 0;
42 /** A list of uint32_ts for addresses we've used in outgoing connections.
43 * Used to detect IP address changes. */
44 static smartlist_t *outgoing_addrs = NULL;
46 /**************************************************************/
48 /**
49 * Return the human-readable name for the connection type <b>type</b>
51 const char *
52 conn_type_to_string(int type)
54 static char buf[64];
55 switch (type) {
56 case CONN_TYPE_OR_LISTENER: return "OR listener";
57 case CONN_TYPE_OR: return "OR";
58 case CONN_TYPE_EXIT: return "Exit";
59 case CONN_TYPE_AP_LISTENER: return "Socks listener";
60 case CONN_TYPE_AP_TRANS_LISTENER:
61 return "Transparent pf/netfilter listener";
62 case CONN_TYPE_AP_NATD_LISTENER: return "Transparent natd listener";
63 case CONN_TYPE_AP_DNS_LISTENER: return "DNS listener";
64 case CONN_TYPE_AP: return "Socks";
65 case CONN_TYPE_DIR_LISTENER: return "Directory listener";
66 case CONN_TYPE_DIR: return "Directory";
67 case CONN_TYPE_CPUWORKER: return "CPU worker";
68 case CONN_TYPE_CONTROL_LISTENER: return "Control listener";
69 case CONN_TYPE_CONTROL: return "Control";
70 default:
71 log_warn(LD_BUG, "unknown connection type %d", type);
72 tor_snprintf(buf, sizeof(buf), "unknown [%d]", type);
73 return buf;
77 /**
78 * Return the human-readable name for the connection state <b>state</b>
79 * for the connection type <b>type</b>
81 const char *
82 conn_state_to_string(int type, int state)
84 static char buf[96];
85 switch (type) {
86 case CONN_TYPE_OR_LISTENER:
87 case CONN_TYPE_AP_LISTENER:
88 case CONN_TYPE_AP_TRANS_LISTENER:
89 case CONN_TYPE_AP_NATD_LISTENER:
90 case CONN_TYPE_AP_DNS_LISTENER:
91 case CONN_TYPE_DIR_LISTENER:
92 case CONN_TYPE_CONTROL_LISTENER:
93 if (state == LISTENER_STATE_READY)
94 return "ready";
95 break;
96 case CONN_TYPE_OR:
97 switch (state) {
98 case OR_CONN_STATE_CONNECTING: return "connect()ing";
99 case OR_CONN_STATE_PROXY_HANDSHAKING: return "handshaking (proxy)";
100 case OR_CONN_STATE_TLS_HANDSHAKING: return "handshaking (TLS)";
101 case OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING:
102 return "renegotiating (TLS)";
103 case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING:
104 return "waiting for renegotiation (TLS)";
105 case OR_CONN_STATE_OR_HANDSHAKING: return "handshaking (Tor)";
106 case OR_CONN_STATE_OPEN: return "open";
108 break;
109 case CONN_TYPE_EXIT:
110 switch (state) {
111 case EXIT_CONN_STATE_RESOLVING: return "waiting for dest info";
112 case EXIT_CONN_STATE_CONNECTING: return "connecting";
113 case EXIT_CONN_STATE_OPEN: return "open";
114 case EXIT_CONN_STATE_RESOLVEFAILED: return "resolve failed";
116 break;
117 case CONN_TYPE_AP:
118 switch (state) {
119 case AP_CONN_STATE_SOCKS_WAIT: return "waiting for socks info";
120 case AP_CONN_STATE_NATD_WAIT: return "waiting for natd dest info";
121 case AP_CONN_STATE_RENDDESC_WAIT: return "waiting for rendezvous desc";
122 case AP_CONN_STATE_CONTROLLER_WAIT: return "waiting for controller";
123 case AP_CONN_STATE_CIRCUIT_WAIT: return "waiting for circuit";
124 case AP_CONN_STATE_CONNECT_WAIT: return "waiting for connect response";
125 case AP_CONN_STATE_RESOLVE_WAIT: return "waiting for resolve response";
126 case AP_CONN_STATE_OPEN: return "open";
128 break;
129 case CONN_TYPE_DIR:
130 switch (state) {
131 case DIR_CONN_STATE_CONNECTING: return "connecting";
132 case DIR_CONN_STATE_CLIENT_SENDING: return "client sending";
133 case DIR_CONN_STATE_CLIENT_READING: return "client reading";
134 case DIR_CONN_STATE_CLIENT_FINISHED: return "client finished";
135 case DIR_CONN_STATE_SERVER_COMMAND_WAIT: return "waiting for command";
136 case DIR_CONN_STATE_SERVER_WRITING: return "writing";
138 break;
139 case CONN_TYPE_CPUWORKER:
140 switch (state) {
141 case CPUWORKER_STATE_IDLE: return "idle";
142 case CPUWORKER_STATE_BUSY_ONION: return "busy with onion";
144 break;
145 case CONN_TYPE_CONTROL:
146 switch (state) {
147 case CONTROL_CONN_STATE_OPEN: return "open (protocol v1)";
148 case CONTROL_CONN_STATE_NEEDAUTH:
149 return "waiting for authentication (protocol v1)";
151 break;
154 log_warn(LD_BUG, "unknown connection state %d (type %d)", state, type);
155 tor_snprintf(buf, sizeof(buf),
156 "unknown state [%d] on unknown [%s] connection",
157 state, conn_type_to_string(type));
158 return buf;
161 /** Allocate and return a new dir_connection_t, initialized as by
162 * connection_init(). */
163 dir_connection_t *
164 dir_connection_new(int socket_family)
166 dir_connection_t *dir_conn = tor_malloc_zero(sizeof(dir_connection_t));
167 connection_init(time(NULL), TO_CONN(dir_conn), CONN_TYPE_DIR, socket_family);
168 return dir_conn;
171 /** Allocate and return a new or_connection_t, initialized as by
172 * connection_init(). */
173 or_connection_t *
174 or_connection_new(int socket_family)
176 or_connection_t *or_conn = tor_malloc_zero(sizeof(or_connection_t));
177 time_t now = time(NULL);
178 connection_init(now, TO_CONN(or_conn), CONN_TYPE_OR, socket_family);
180 or_conn->timestamp_last_added_nonpadding = time(NULL);
181 or_conn->next_circ_id = crypto_rand_int(1<<15);
183 return or_conn;
186 /** Allocate and return a new edge_connection_t, initialized as by
187 * connection_init(). */
188 edge_connection_t *
189 edge_connection_new(int type, int socket_family)
191 edge_connection_t *edge_conn = tor_malloc_zero(sizeof(edge_connection_t));
192 tor_assert(type == CONN_TYPE_EXIT || type == CONN_TYPE_AP);
193 connection_init(time(NULL), TO_CONN(edge_conn), type, socket_family);
194 if (type == CONN_TYPE_AP)
195 edge_conn->socks_request = tor_malloc_zero(sizeof(socks_request_t));
196 return edge_conn;
199 /** Allocate and return a new control_connection_t, initialized as by
200 * connection_init(). */
201 control_connection_t *
202 control_connection_new(int socket_family)
204 control_connection_t *control_conn =
205 tor_malloc_zero(sizeof(control_connection_t));
206 connection_init(time(NULL),
207 TO_CONN(control_conn), CONN_TYPE_CONTROL, socket_family);
208 return control_conn;
211 /** Allocate, initialize, and return a new connection_t subtype of <b>type</b>
212 * to make or receive connections of address family <b>socket_family</b>. The
213 * type should be one of the CONN_TYPE_* constants. */
214 connection_t *
215 connection_new(int type, int socket_family)
217 switch (type) {
218 case CONN_TYPE_OR:
219 return TO_CONN(or_connection_new(socket_family));
221 case CONN_TYPE_EXIT:
222 case CONN_TYPE_AP:
223 return TO_CONN(edge_connection_new(type, socket_family));
225 case CONN_TYPE_DIR:
226 return TO_CONN(dir_connection_new(socket_family));
228 case CONN_TYPE_CONTROL:
229 return TO_CONN(control_connection_new(socket_family));
231 default: {
232 connection_t *conn = tor_malloc_zero(sizeof(connection_t));
233 connection_init(time(NULL), conn, type, socket_family);
234 return conn;
239 /** Initializes conn. (you must call connection_add() to link it into the main
240 * array).
242 * Set conn-\>type to <b>type</b>. Set conn-\>s and conn-\>conn_array_index to
243 * -1 to signify they are not yet assigned.
245 * If conn is not a listener type, allocate buffers for it. If it's
246 * an AP type, allocate space to store the socks_request.
248 * Assign a pseudorandom next_circ_id between 0 and 2**15.
250 * Initialize conn's timestamps to now.
252 static void
253 connection_init(time_t now, connection_t *conn, int type, int socket_family)
255 static uint64_t n_connections_allocated = 1;
257 switch (type) {
258 case CONN_TYPE_OR:
259 conn->magic = OR_CONNECTION_MAGIC;
260 break;
261 case CONN_TYPE_EXIT:
262 case CONN_TYPE_AP:
263 conn->magic = EDGE_CONNECTION_MAGIC;
264 break;
265 case CONN_TYPE_DIR:
266 conn->magic = DIR_CONNECTION_MAGIC;
267 break;
268 case CONN_TYPE_CONTROL:
269 conn->magic = CONTROL_CONNECTION_MAGIC;
270 break;
271 default:
272 conn->magic = BASE_CONNECTION_MAGIC;
273 break;
276 conn->s = -1; /* give it a default of 'not used' */
277 conn->conn_array_index = -1; /* also default to 'not used' */
278 conn->global_identifier = n_connections_allocated++;
280 conn->type = type;
281 conn->socket_family = socket_family;
282 if (!connection_is_listener(conn)) { /* listeners never use their buf */
283 conn->inbuf = buf_new();
284 conn->outbuf = buf_new();
287 conn->timestamp_created = now;
288 conn->timestamp_lastread = now;
289 conn->timestamp_lastwritten = now;
292 /** Create a link between <b>conn_a</b> and <b>conn_b</b>. */
293 void
294 connection_link_connections(connection_t *conn_a, connection_t *conn_b)
296 tor_assert(conn_a->s < 0);
297 tor_assert(conn_b->s < 0);
299 conn_a->linked = 1;
300 conn_b->linked = 1;
301 conn_a->linked_conn = conn_b;
302 conn_b->linked_conn = conn_a;
305 /** Deallocate memory used by <b>conn</b>. Deallocate its buffers if
306 * necessary, close its socket if necessary, and mark the directory as dirty
307 * if <b>conn</b> is an OR or OP connection.
309 static void
310 _connection_free(connection_t *conn)
312 void *mem;
313 size_t memlen;
314 switch (conn->type) {
315 case CONN_TYPE_OR:
316 tor_assert(conn->magic == OR_CONNECTION_MAGIC);
317 mem = TO_OR_CONN(conn);
318 memlen = sizeof(or_connection_t);
319 break;
320 case CONN_TYPE_AP:
321 case CONN_TYPE_EXIT:
322 tor_assert(conn->magic == EDGE_CONNECTION_MAGIC);
323 mem = TO_EDGE_CONN(conn);
324 memlen = sizeof(edge_connection_t);
325 break;
326 case CONN_TYPE_DIR:
327 tor_assert(conn->magic == DIR_CONNECTION_MAGIC);
328 mem = TO_DIR_CONN(conn);
329 memlen = sizeof(dir_connection_t);
330 break;
331 case CONN_TYPE_CONTROL:
332 tor_assert(conn->magic == CONTROL_CONNECTION_MAGIC);
333 mem = TO_CONTROL_CONN(conn);
334 memlen = sizeof(control_connection_t);
335 break;
336 default:
337 tor_assert(conn->magic == BASE_CONNECTION_MAGIC);
338 mem = conn;
339 memlen = sizeof(connection_t);
340 break;
343 if (conn->linked) {
344 log_info(LD_GENERAL, "Freeing linked %s connection [%s] with %d "
345 "bytes on inbuf, %d on outbuf.",
346 conn_type_to_string(conn->type),
347 conn_state_to_string(conn->type, conn->state),
348 (int)buf_datalen(conn->inbuf), (int)buf_datalen(conn->outbuf));
351 if (!connection_is_listener(conn)) {
352 buf_free(conn->inbuf);
353 buf_free(conn->outbuf);
354 } else {
355 if (conn->socket_family == AF_UNIX) {
356 /* For now only control ports can be Unix domain sockets
357 * and listeners at the same time */
358 tor_assert(conn->type == CONN_TYPE_CONTROL_LISTENER);
360 if (unlink(conn->address) < 0 && errno != ENOENT) {
361 log_warn(LD_NET, "Could not unlink %s: %s", conn->address,
362 strerror(errno));
367 tor_free(conn->address);
369 if (connection_speaks_cells(conn)) {
370 or_connection_t *or_conn = TO_OR_CONN(conn);
371 if (or_conn->tls) {
372 tor_tls_free(or_conn->tls);
373 or_conn->tls = NULL;
375 if (or_conn->handshake_state) {
376 or_handshake_state_free(or_conn->handshake_state);
377 or_conn->handshake_state = NULL;
379 tor_free(or_conn->nickname);
381 if (CONN_IS_EDGE(conn)) {
382 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
383 tor_free(edge_conn->chosen_exit_name);
384 if (edge_conn->socks_request) {
385 memset(edge_conn->socks_request, 0xcc, sizeof(socks_request_t));
386 tor_free(edge_conn->socks_request);
388 if (edge_conn->rend_data)
389 rend_data_free(edge_conn->rend_data);
391 if (conn->type == CONN_TYPE_CONTROL) {
392 control_connection_t *control_conn = TO_CONTROL_CONN(conn);
393 tor_free(control_conn->incoming_cmd);
396 tor_free(conn->read_event); /* Probably already freed by connection_free. */
397 tor_free(conn->write_event); /* Probably already freed by connection_free. */
399 if (conn->type == CONN_TYPE_DIR) {
400 dir_connection_t *dir_conn = TO_DIR_CONN(conn);
401 tor_free(dir_conn->requested_resource);
402 if (dir_conn->zlib_state)
403 tor_zlib_free(dir_conn->zlib_state);
404 if (dir_conn->fingerprint_stack) {
405 SMARTLIST_FOREACH(dir_conn->fingerprint_stack, char *, cp, tor_free(cp));
406 smartlist_free(dir_conn->fingerprint_stack);
408 if (dir_conn->cached_dir)
409 cached_dir_decref(dir_conn->cached_dir);
410 if (dir_conn->rend_data)
411 rend_data_free(dir_conn->rend_data);
414 if (conn->s >= 0) {
415 log_debug(LD_NET,"closing fd %d.",conn->s);
416 tor_close_socket(conn->s);
417 conn->s = -1;
420 if (conn->type == CONN_TYPE_OR &&
421 !tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest)) {
422 log_warn(LD_BUG, "called on OR conn with non-zeroed identity_digest");
423 connection_or_remove_from_identity_map(TO_OR_CONN(conn));
426 memset(mem, 0xAA, memlen); /* poison memory */
427 tor_free(mem);
430 /** Make sure <b>conn</b> isn't in any of the global conn lists; then free it.
432 void
433 connection_free(connection_t *conn)
435 tor_assert(conn);
436 tor_assert(!connection_is_on_closeable_list(conn));
437 tor_assert(!connection_in_array(conn));
438 if (conn->linked_conn) {
439 log_err(LD_BUG, "Called with conn->linked_conn still set.");
440 tor_fragile_assert();
441 conn->linked_conn->linked_conn = NULL;
442 if (! conn->linked_conn->marked_for_close &&
443 conn->linked_conn->reading_from_linked_conn)
444 connection_start_reading(conn->linked_conn);
445 conn->linked_conn = NULL;
447 if (connection_speaks_cells(conn)) {
448 if (!tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest)) {
449 connection_or_remove_from_identity_map(TO_OR_CONN(conn));
452 if (conn->type == CONN_TYPE_CONTROL) {
453 TO_CONTROL_CONN(conn)->event_mask = 0;
454 control_update_global_event_mask();
456 connection_unregister_events(conn);
457 _connection_free(conn);
460 /** Call _connection_free() on every connection in our array, and release all
461 * storage held by connection.c. This is used by cpuworkers and dnsworkers
462 * when they fork, so they don't keep resources held open (especially
463 * sockets).
465 * Don't do the checks in connection_free(), because they will
466 * fail.
468 void
469 connection_free_all(void)
471 smartlist_t *conns = get_connection_array();
473 /* We don't want to log any messages to controllers. */
474 SMARTLIST_FOREACH(conns, connection_t *, conn,
475 if (conn->type == CONN_TYPE_CONTROL)
476 TO_CONTROL_CONN(conn)->event_mask = 0);
478 control_update_global_event_mask();
480 /* Unlink everything from the identity map. */
481 connection_or_clear_identity_map();
483 SMARTLIST_FOREACH(conns, connection_t *, conn, _connection_free(conn));
485 if (outgoing_addrs) {
486 SMARTLIST_FOREACH(outgoing_addrs, void*, addr, tor_free(addr));
487 smartlist_free(outgoing_addrs);
488 outgoing_addrs = NULL;
492 /** Do any cleanup needed:
493 * - Directory conns that failed to fetch a rendezvous descriptor
494 * need to inform pending rendezvous streams.
495 * - OR conns need to call rep_hist_note_*() to record status.
496 * - AP conns need to send a socks reject if necessary.
497 * - Exit conns need to call connection_dns_remove() if necessary.
498 * - AP and Exit conns need to send an end cell if they can.
499 * - DNS conns need to fail any resolves that are pending on them.
500 * - OR and edge connections need to be unlinked from circuits.
502 void
503 connection_about_to_close_connection(connection_t *conn)
505 circuit_t *circ;
506 dir_connection_t *dir_conn;
507 or_connection_t *or_conn;
508 edge_connection_t *edge_conn;
509 time_t now = time(NULL);
511 tor_assert(conn->marked_for_close);
513 if (CONN_IS_EDGE(conn)) {
514 edge_conn = TO_EDGE_CONN(conn);
515 if (!edge_conn->edge_has_sent_end) {
516 log_warn(LD_BUG, "(Harmless.) Edge connection (marked at %s:%d) "
517 "hasn't sent end yet?",
518 conn->marked_for_close_file, conn->marked_for_close);
519 tor_fragile_assert();
523 switch (conn->type) {
524 case CONN_TYPE_DIR:
525 dir_conn = TO_DIR_CONN(conn);
526 if (conn->state < DIR_CONN_STATE_CLIENT_FINISHED) {
527 /* It's a directory connection and connecting or fetching
528 * failed: forget about this router, and maybe try again. */
529 connection_dir_request_failed(dir_conn);
531 /* If we were trying to fetch a v2 rend desc and did not succeed,
532 * retry as needed. (If a fetch is successful, the connection state
533 * is changed to DIR_PURPOSE_HAS_FETCHED_RENDDESC to mark that
534 * refetching is unnecessary.) */
535 if (conn->purpose == DIR_PURPOSE_FETCH_RENDDESC_V2 &&
536 dir_conn->rend_data &&
537 strlen(dir_conn->rend_data->onion_address) ==
538 REND_SERVICE_ID_LEN_BASE32)
539 rend_client_refetch_v2_renddesc(dir_conn->rend_data);
540 break;
541 case CONN_TYPE_OR:
542 or_conn = TO_OR_CONN(conn);
543 /* Remember why we're closing this connection. */
544 if (conn->state != OR_CONN_STATE_OPEN) {
545 /* Inform any pending (not attached) circs that they should
546 * give up. */
547 circuit_n_conn_done(TO_OR_CONN(conn), 0);
548 /* now mark things down as needed */
549 if (connection_or_nonopen_was_started_here(or_conn)) {
550 or_options_t *options = get_options();
551 rep_hist_note_connect_failed(or_conn->identity_digest, now);
552 entry_guard_register_connect_status(or_conn->identity_digest,0,
553 !options->HttpsProxy, now);
554 if (conn->state >= OR_CONN_STATE_TLS_HANDSHAKING) {
555 int reason = tls_error_to_orconn_end_reason(or_conn->tls_error);
556 control_event_or_conn_status(or_conn, OR_CONN_EVENT_FAILED,
557 reason);
558 if (!authdir_mode_tests_reachability(options))
559 control_event_bootstrap_problem(
560 orconn_end_reason_to_control_string(reason), reason);
563 } else if (conn->hold_open_until_flushed) {
564 /* We only set hold_open_until_flushed when we're intentionally
565 * closing a connection. */
566 rep_hist_note_disconnect(or_conn->identity_digest, now);
567 control_event_or_conn_status(or_conn, OR_CONN_EVENT_CLOSED,
568 tls_error_to_orconn_end_reason(or_conn->tls_error));
569 } else if (!tor_digest_is_zero(or_conn->identity_digest)) {
570 rep_hist_note_connection_died(or_conn->identity_digest, now);
571 control_event_or_conn_status(or_conn, OR_CONN_EVENT_CLOSED,
572 tls_error_to_orconn_end_reason(or_conn->tls_error));
574 /* Now close all the attached circuits on it. */
575 circuit_unlink_all_from_or_conn(TO_OR_CONN(conn),
576 END_CIRC_REASON_OR_CONN_CLOSED);
577 break;
578 case CONN_TYPE_AP:
579 edge_conn = TO_EDGE_CONN(conn);
580 if (edge_conn->socks_request->has_finished == 0) {
581 /* since conn gets removed right after this function finishes,
582 * there's no point trying to send back a reply at this point. */
583 log_warn(LD_BUG,"Closing stream (marked at %s:%d) without sending"
584 " back a socks reply.",
585 conn->marked_for_close_file, conn->marked_for_close);
587 if (!edge_conn->end_reason) {
588 log_warn(LD_BUG,"Closing stream (marked at %s:%d) without having"
589 " set end_reason.",
590 conn->marked_for_close_file, conn->marked_for_close);
592 if (edge_conn->dns_server_request) {
593 log_warn(LD_BUG,"Closing stream (marked at %s:%d) without having"
594 " replied to DNS request.",
595 conn->marked_for_close_file, conn->marked_for_close);
596 dnsserv_reject_request(edge_conn);
598 control_event_stream_bandwidth(edge_conn);
599 control_event_stream_status(edge_conn, STREAM_EVENT_CLOSED,
600 edge_conn->end_reason);
601 circ = circuit_get_by_edge_conn(edge_conn);
602 if (circ)
603 circuit_detach_stream(circ, edge_conn);
604 break;
605 case CONN_TYPE_EXIT:
606 edge_conn = TO_EDGE_CONN(conn);
607 circ = circuit_get_by_edge_conn(edge_conn);
608 if (circ)
609 circuit_detach_stream(circ, edge_conn);
610 if (conn->state == EXIT_CONN_STATE_RESOLVING) {
611 connection_dns_remove(edge_conn);
613 break;
617 /** Return true iff connection_close_immediate() has been called on this
618 * connection. */
619 #define CONN_IS_CLOSED(c) \
620 ((c)->linked ? ((c)->linked_conn_is_closed) : ((c)->s < 0))
622 /** Close the underlying socket for <b>conn</b>, so we don't try to
623 * flush it. Must be used in conjunction with (right before)
624 * connection_mark_for_close().
626 void
627 connection_close_immediate(connection_t *conn)
629 assert_connection_ok(conn,0);
630 if (CONN_IS_CLOSED(conn)) {
631 log_err(LD_BUG,"Attempt to close already-closed connection.");
632 tor_fragile_assert();
633 return;
635 if (conn->outbuf_flushlen) {
636 log_info(LD_NET,"fd %d, type %s, state %s, %d bytes on outbuf.",
637 conn->s, conn_type_to_string(conn->type),
638 conn_state_to_string(conn->type, conn->state),
639 (int)conn->outbuf_flushlen);
642 connection_unregister_events(conn);
644 if (conn->s >= 0)
645 tor_close_socket(conn->s);
646 conn->s = -1;
647 if (conn->linked)
648 conn->linked_conn_is_closed = 1;
649 if (!connection_is_listener(conn)) {
650 buf_clear(conn->outbuf);
651 conn->outbuf_flushlen = 0;
655 /** Mark <b>conn</b> to be closed next time we loop through
656 * conn_close_if_marked() in main.c. */
657 void
658 _connection_mark_for_close(connection_t *conn, int line, const char *file)
660 assert_connection_ok(conn,0);
661 tor_assert(line);
662 tor_assert(line < 1<<16); /* marked_for_close can only fit a uint16_t. */
663 tor_assert(file);
665 if (conn->marked_for_close) {
666 log(LOG_WARN,LD_BUG,"Duplicate call to connection_mark_for_close at %s:%d"
667 " (first at %s:%d)", file, line, conn->marked_for_close_file,
668 conn->marked_for_close);
669 tor_fragile_assert();
670 return;
673 conn->marked_for_close = line;
674 conn->marked_for_close_file = file;
675 add_connection_to_closeable_list(conn);
677 /* in case we're going to be held-open-til-flushed, reset
678 * the number of seconds since last successful write, so
679 * we get our whole 15 seconds */
680 conn->timestamp_lastwritten = time(NULL);
683 /** Find each connection that has hold_open_until_flushed set to
684 * 1 but hasn't written in the past 15 seconds, and set
685 * hold_open_until_flushed to 0. This means it will get cleaned
686 * up in the next loop through close_if_marked() in main.c.
688 void
689 connection_expire_held_open(void)
691 time_t now;
692 smartlist_t *conns = get_connection_array();
694 now = time(NULL);
696 SMARTLIST_FOREACH(conns, connection_t *, conn,
698 /* If we've been holding the connection open, but we haven't written
699 * for 15 seconds...
701 if (conn->hold_open_until_flushed) {
702 tor_assert(conn->marked_for_close);
703 if (now - conn->timestamp_lastwritten >= 15) {
704 int severity;
705 if (conn->type == CONN_TYPE_EXIT ||
706 (conn->type == CONN_TYPE_DIR &&
707 conn->purpose == DIR_PURPOSE_SERVER))
708 severity = LOG_INFO;
709 else
710 severity = LOG_NOTICE;
711 log_fn(severity, LD_NET,
712 "Giving up on marked_for_close conn that's been flushing "
713 "for 15s (fd %d, type %s, state %s).",
714 conn->s, conn_type_to_string(conn->type),
715 conn_state_to_string(conn->type, conn->state));
716 conn->hold_open_until_flushed = 0;
722 /** Create an AF_INET listenaddr struct.
723 * <b>listenaddress</b> provides the host and optionally the port information
724 * for the new structure. If no port is provided in <b>listenaddress</b> then
725 * <b>listenport</b> is used.
727 * If not NULL <b>readable_address</b> will contain a copy of the host part of
728 * <b>listenaddress</b>.
730 * The listenaddr struct has to be freed by the caller.
732 static struct sockaddr_in *
733 create_inet_sockaddr(const char *listenaddress, uint16_t listenport,
734 char **readable_address, socklen_t *socklen_out) {
735 struct sockaddr_in *listenaddr = NULL;
736 uint32_t addr;
737 uint16_t usePort = 0;
739 if (parse_addr_port(LOG_WARN,
740 listenaddress, readable_address, &addr, &usePort)<0) {
741 log_warn(LD_CONFIG,
742 "Error parsing/resolving ListenAddress %s", listenaddress);
743 goto err;
745 if (usePort==0)
746 usePort = listenport;
748 listenaddr = tor_malloc_zero(sizeof(struct sockaddr_in));
749 listenaddr->sin_addr.s_addr = htonl(addr);
750 listenaddr->sin_family = AF_INET;
751 listenaddr->sin_port = htons((uint16_t) usePort);
753 *socklen_out = sizeof(struct sockaddr_in);
755 return listenaddr;
757 err:
758 tor_free(listenaddr);
759 return NULL;
762 #ifdef HAVE_SYS_UN_H
763 /** Create an AF_UNIX listenaddr struct.
764 * <b>listenaddress</b> provides the path to the Unix socket.
766 * Eventually <b>listenaddress</b> will also optionally contain user, group,
767 * and file permissions for the new socket. But not yet. XXX
768 * Also, since we do not create the socket here the information doesn't help
769 * here.
771 * If not NULL <b>readable_address</b> will contain a copy of the path part of
772 * <b>listenaddress</b>.
774 * The listenaddr struct has to be freed by the caller.
776 static struct sockaddr_un *
777 create_unix_sockaddr(const char *listenaddress, char **readable_address,
778 socklen_t *len_out)
780 struct sockaddr_un *sockaddr = NULL;
782 sockaddr = tor_malloc_zero(sizeof(struct sockaddr_un));
783 sockaddr->sun_family = AF_UNIX;
784 strncpy(sockaddr->sun_path, listenaddress, sizeof(sockaddr->sun_path));
786 if (readable_address)
787 *readable_address = tor_strdup(listenaddress);
789 *len_out = sizeof(struct sockaddr_un);
790 return sockaddr;
792 #else
793 static struct sockaddr *
794 create_unix_sockaddr(const char *listenaddress, char **readable_address,
795 socklen_t *len_out)
797 (void)listenaddress;
798 (void)readable_address;
799 log_fn(LOG_ERR, LD_BUG,
800 "Unix domain sockets not supported, yet we tried to create one.");
801 *len_out = 0;
802 tor_assert(0);
804 #endif /* HAVE_SYS_UN_H */
806 /** Warn that an accept or a connect has failed because we're running up
807 * against our ulimit. Rate-limit these warnings so that we don't spam
808 * the log. */
809 static void
810 warn_too_many_conns(void)
812 #define WARN_TOO_MANY_CONNS_INTERVAL (6*60*60)
813 static time_t last_warned = 0;
814 time_t now = time(NULL);
815 int n_conns = get_n_open_sockets();
816 if (last_warned + WARN_TOO_MANY_CONNS_INTERVAL < now) {
817 log_warn(LD_NET,"Failing because we have %d connections already. Please "
818 "raise your ulimit -n.", n_conns);
819 last_warned = now;
821 control_event_general_status(LOG_WARN, "TOO_MANY_CONNECTIONS CURRENT=%d",
822 n_conns);
825 /** Bind a new non-blocking socket listening to the socket described
826 * by <b>listensockaddr</b>.
828 * <b>address</b> is only used for logging purposes and to add the information
829 * to the conn.
831 static connection_t *
832 connection_create_listener(struct sockaddr *listensockaddr, socklen_t socklen,
833 int type, char* address)
835 connection_t *conn;
836 int s; /* the socket we're going to make */
837 uint16_t usePort = 0;
838 int start_reading = 0;
840 if (get_n_open_sockets() >= get_options()->_ConnLimit-1) {
841 warn_too_many_conns();
842 return NULL;
845 if (listensockaddr->sa_family == AF_INET) {
846 int is_tcp = (type != CONN_TYPE_AP_DNS_LISTENER);
847 #ifndef MS_WINDOWS
848 int one=1;
849 #endif
850 if (is_tcp)
851 start_reading = 1;
853 usePort = ntohs( (uint16_t)
854 ((struct sockaddr_in *)listensockaddr)->sin_port);
856 log_notice(LD_NET, "Opening %s on %s:%d",
857 conn_type_to_string(type), address, usePort);
859 s = tor_open_socket(PF_INET,
860 is_tcp ? SOCK_STREAM : SOCK_DGRAM,
861 is_tcp ? IPPROTO_TCP: IPPROTO_UDP);
862 if (s < 0) {
863 log_warn(LD_NET,"Socket creation failed.");
864 goto err;
867 #ifndef MS_WINDOWS
868 /* REUSEADDR on normal places means you can rebind to the port
869 * right after somebody else has let it go. But REUSEADDR on win32
870 * means you can bind to the port _even when somebody else
871 * already has it bound_. So, don't do that on Win32. */
872 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*) &one,
873 (socklen_t)sizeof(one));
874 #endif
876 if (bind(s,listensockaddr,socklen) < 0) {
877 const char *helpfulhint = "";
878 int e = tor_socket_errno(s);
879 if (ERRNO_IS_EADDRINUSE(e))
880 helpfulhint = ". Is Tor already running?";
881 log_warn(LD_NET, "Could not bind to %s:%u: %s%s", address, usePort,
882 tor_socket_strerror(e), helpfulhint);
883 tor_close_socket(s);
884 goto err;
887 if (is_tcp) {
888 if (listen(s,SOMAXCONN) < 0) {
889 log_warn(LD_NET, "Could not listen on %s:%u: %s", address, usePort,
890 tor_socket_strerror(tor_socket_errno(s)));
891 tor_close_socket(s);
892 goto err;
895 #ifdef HAVE_SYS_UN_H
896 } else if (listensockaddr->sa_family == AF_UNIX) {
897 start_reading = 1;
899 /* For now only control ports can be Unix domain sockets
900 * and listeners at the same time */
901 tor_assert(type == CONN_TYPE_CONTROL_LISTENER);
903 log_notice(LD_NET, "Opening %s on %s",
904 conn_type_to_string(type), address);
906 if (unlink(address) < 0 && errno != ENOENT) {
907 log_warn(LD_NET, "Could not unlink %s: %s", address,
908 strerror(errno));
909 goto err;
911 s = tor_open_socket(AF_UNIX, SOCK_STREAM, 0);
912 if (s < 0) {
913 log_warn(LD_NET,"Socket creation failed: %s.", strerror(errno));
914 goto err;
917 if (bind(s, listensockaddr, (socklen_t)sizeof(struct sockaddr_un)) == -1) {
918 log_warn(LD_NET,"Bind to %s failed: %s.", address,
919 tor_socket_strerror(tor_socket_errno(s)));
920 goto err;
923 if (listen(s,SOMAXCONN) < 0) {
924 log_warn(LD_NET, "Could not listen on %s: %s", address,
925 tor_socket_strerror(tor_socket_errno(s)));
926 tor_close_socket(s);
927 goto err;
929 #endif /* HAVE_SYS_UN_H */
930 } else {
931 log_err(LD_BUG,"Got unexpected address family %d.",
932 listensockaddr->sa_family);
933 tor_assert(0);
936 set_socket_nonblocking(s);
938 conn = connection_new(type, listensockaddr->sa_family);
939 conn->socket_family = listensockaddr->sa_family;
940 conn->s = s;
941 conn->address = tor_strdup(address);
942 conn->port = usePort;
944 if (connection_add(conn) < 0) { /* no space, forget it */
945 log_warn(LD_NET,"connection_add for listener failed. Giving up.");
946 connection_free(conn);
947 goto err;
950 log_debug(LD_NET,"%s listening on port %u.",
951 conn_type_to_string(type), usePort);
953 conn->state = LISTENER_STATE_READY;
954 if (start_reading) {
955 connection_start_reading(conn);
956 } else {
957 tor_assert(type == CONN_TYPE_AP_DNS_LISTENER);
958 dnsserv_configure_listener(conn);
961 return conn;
963 err:
964 return NULL;
967 /** Do basic sanity checking on a newly received socket. Return 0
968 * if it looks ok, else return -1. */
969 static int
970 check_sockaddr(struct sockaddr *sa, int len, int level)
972 int ok = 1;
974 if (sa->sa_family == AF_INET) {
975 struct sockaddr_in *sin=(struct sockaddr_in*)sa;
976 if (len != sizeof(struct sockaddr_in)) {
977 log_fn(level, LD_NET, "Length of address not as expected: %d vs %d",
978 len,(int)sizeof(struct sockaddr_in));
979 ok = 0;
981 if (sin->sin_addr.s_addr == 0 || sin->sin_port == 0) {
982 log_fn(level, LD_NET,
983 "Address for new connection has address/port equal to zero.");
984 ok = 0;
986 } else if (sa->sa_family == AF_INET6) {
987 struct sockaddr_in6 *sin6=(struct sockaddr_in6*)sa;
988 if (len != sizeof(struct sockaddr_in6)) {
989 log_fn(level, LD_NET, "Length of address not as expected: %d vs %d",
990 len,(int)sizeof(struct sockaddr_in6));
991 ok = 0;
993 if (tor_mem_is_zero((void*)sin6->sin6_addr.s6_addr, 16) ||
994 sin6->sin6_port == 0) {
995 log_fn(level, LD_NET,
996 "Address for new connection has address/port equal to zero.");
997 ok = 0;
999 } else {
1000 ok = 0;
1002 return ok ? 0 : -1;
1005 /** Check whether the socket family from an accepted socket <b>got</b> is the
1006 * same as the one that <b>listener</b> is waiting for. If it isn't, log
1007 * a useful message and return -1. Else return 0.
1009 * This is annoying, but can apparently happen on some Darwins. */
1010 static int
1011 check_sockaddr_family_match(sa_family_t got, connection_t *listener)
1013 if (got != listener->socket_family) {
1014 log_info(LD_BUG, "A listener connection returned a socket with a "
1015 "mismatched family. %s for addr_family %d gave us a socket "
1016 "with address family %d. Dropping.",
1017 conn_type_to_string(listener->type),
1018 (int)listener->socket_family,
1019 (int)got);
1020 return -1;
1022 return 0;
1025 /** The listener connection <b>conn</b> told poll() it wanted to read.
1026 * Call accept() on conn-\>s, and add the new connection if necessary.
1028 static int
1029 connection_handle_listener_read(connection_t *conn, int new_type)
1031 int news; /* the new socket */
1032 connection_t *newconn;
1033 /* information about the remote peer when connecting to other routers */
1034 char addrbuf[256];
1035 struct sockaddr *remote = (struct sockaddr*)addrbuf;
1036 /* length of the remote address. Must be whatever accept() needs. */
1037 socklen_t remotelen = (socklen_t)sizeof(addrbuf);
1038 or_options_t *options = get_options();
1040 tor_assert((size_t)remotelen >= sizeof(struct sockaddr_in));
1041 memset(addrbuf, 0, sizeof(addrbuf));
1043 news = tor_accept_socket(conn->s,remote,&remotelen);
1044 if (news < 0) { /* accept() error */
1045 int e = tor_socket_errno(conn->s);
1046 if (ERRNO_IS_ACCEPT_EAGAIN(e)) {
1047 return 0; /* he hung up before we could accept(). that's fine. */
1048 } else if (ERRNO_IS_ACCEPT_RESOURCE_LIMIT(e)) {
1049 warn_too_many_conns();
1050 return 0;
1052 /* else there was a real error. */
1053 log_warn(LD_NET,"accept() failed: %s. Closing listener.",
1054 tor_socket_strerror(e));
1055 connection_mark_for_close(conn);
1056 return -1;
1058 log_debug(LD_NET,
1059 "Connection accepted on socket %d (child of fd %d).",
1060 news,conn->s);
1062 set_socket_nonblocking(news);
1064 if (options->ConstrainedSockets)
1065 set_constrained_socket_buffers(news, (int)options->ConstrainedSockSize);
1067 if (check_sockaddr_family_match(remote->sa_family, conn) < 0) {
1068 tor_close_socket(news);
1069 return 0;
1072 if (conn->socket_family == AF_INET || conn->socket_family == AF_INET6) {
1073 tor_addr_t addr;
1074 uint16_t port;
1075 if (check_sockaddr(remote, remotelen, LOG_INFO)<0) {
1076 log_info(LD_NET,
1077 "accept() returned a strange address; trying getsockname().");
1078 remotelen=sizeof(addrbuf);
1079 memset(addrbuf, 0, sizeof(addrbuf));
1080 if (getsockname(news, remote, &remotelen)<0) {
1081 int e = tor_socket_errno(news);
1082 log_warn(LD_NET, "getsockname() for new connection failed: %s",
1083 tor_socket_strerror(e));
1084 } else {
1085 if (check_sockaddr((struct sockaddr*)addrbuf, remotelen,
1086 LOG_WARN) < 0) {
1087 log_warn(LD_NET,"Something's wrong with this conn. Closing it.");
1088 tor_close_socket(news);
1089 return 0;
1094 if (check_sockaddr_family_match(remote->sa_family, conn) < 0) {
1095 tor_close_socket(news);
1096 return 0;
1099 tor_addr_from_sockaddr(&addr, remote, &port);
1101 /* process entrance policies here, before we even create the connection */
1102 if (new_type == CONN_TYPE_AP) {
1103 /* check sockspolicy to see if we should accept it */
1104 if (socks_policy_permits_address(&addr) == 0) {
1105 log_notice(LD_APP,
1106 "Denying socks connection from untrusted address %s.",
1107 fmt_addr(&addr));
1108 tor_close_socket(news);
1109 return 0;
1112 if (new_type == CONN_TYPE_DIR) {
1113 /* check dirpolicy to see if we should accept it */
1114 if (dir_policy_permits_address(&addr) == 0) {
1115 log_notice(LD_DIRSERV,"Denying dir connection from address %s.",
1116 fmt_addr(&addr));
1117 tor_close_socket(news);
1118 return 0;
1122 newconn = connection_new(new_type, conn->socket_family);
1123 newconn->s = news;
1125 /* remember the remote address */
1126 tor_addr_copy(&newconn->addr, &addr);
1127 newconn->port = port;
1128 newconn->address = tor_dup_addr(&addr);
1130 } else if (conn->socket_family == AF_UNIX) {
1131 /* For now only control ports can be Unix domain sockets
1132 * and listeners at the same time */
1133 tor_assert(conn->type == CONN_TYPE_CONTROL_LISTENER);
1135 newconn = connection_new(new_type, conn->socket_family);
1136 newconn->s = news;
1138 /* remember the remote address -- do we have anything sane to put here? */
1139 tor_addr_make_unspec(&newconn->addr);
1140 newconn->port = 1;
1141 newconn->address = tor_strdup(conn->address);
1142 } else {
1143 tor_assert(0);
1146 if (connection_add(newconn) < 0) { /* no space, forget it */
1147 connection_free(newconn);
1148 return 0; /* no need to tear down the parent */
1151 if (connection_init_accepted_conn(newconn, conn->type) < 0) {
1152 connection_mark_for_close(newconn);
1153 return 0;
1155 return 0;
1158 /** Initialize states for newly accepted connection <b>conn</b>.
1159 * If conn is an OR, start the TLS handshake.
1160 * If conn is a transparent AP, get its original destination
1161 * and place it in circuit_wait.
1163 static int
1164 connection_init_accepted_conn(connection_t *conn, uint8_t listener_type)
1166 connection_start_reading(conn);
1168 switch (conn->type) {
1169 case CONN_TYPE_OR:
1170 control_event_or_conn_status(TO_OR_CONN(conn), OR_CONN_EVENT_NEW, 0);
1171 return connection_tls_start_handshake(TO_OR_CONN(conn), 1);
1172 case CONN_TYPE_AP:
1173 switch (listener_type) {
1174 case CONN_TYPE_AP_LISTENER:
1175 conn->state = AP_CONN_STATE_SOCKS_WAIT;
1176 break;
1177 case CONN_TYPE_AP_TRANS_LISTENER:
1178 conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
1179 return connection_ap_process_transparent(TO_EDGE_CONN(conn));
1180 case CONN_TYPE_AP_NATD_LISTENER:
1181 conn->state = AP_CONN_STATE_NATD_WAIT;
1182 break;
1184 break;
1185 case CONN_TYPE_DIR:
1186 conn->purpose = DIR_PURPOSE_SERVER;
1187 conn->state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
1188 break;
1189 case CONN_TYPE_CONTROL:
1190 conn->state = CONTROL_CONN_STATE_NEEDAUTH;
1191 break;
1193 return 0;
1196 /** Take conn, make a nonblocking socket; try to connect to
1197 * addr:port (they arrive in *host order*). If fail, return -1 and if
1198 * applicable put your best guess about errno into *<b>socket_error</b>.
1199 * Else assign s to conn-\>s: if connected return 1, if EAGAIN return 0.
1201 * address is used to make the logs useful.
1203 * On success, add conn to the list of polled connections.
1206 connection_connect(connection_t *conn, const char *address,
1207 const tor_addr_t *addr, uint16_t port, int *socket_error)
1209 int s, inprogress = 0;
1210 char addrbuf[256];
1211 struct sockaddr *dest_addr = (struct sockaddr*) addrbuf;
1212 socklen_t dest_addr_len;
1213 or_options_t *options = get_options();
1214 int protocol_family;
1216 if (get_n_open_sockets() >= get_options()->_ConnLimit-1) {
1217 warn_too_many_conns();
1218 return -1;
1221 if (tor_addr_family(addr) == AF_INET6)
1222 protocol_family = PF_INET6;
1223 else
1224 protocol_family = PF_INET;
1226 s = tor_open_socket(protocol_family,SOCK_STREAM,IPPROTO_TCP);
1227 if (s < 0) {
1228 *socket_error = tor_socket_errno(-1);
1229 log_warn(LD_NET,"Error creating network socket: %s",
1230 tor_socket_strerror(*socket_error));
1231 return -1;
1234 if (options->OutboundBindAddress) {
1235 struct sockaddr_in ext_addr;
1237 memset(&ext_addr, 0, sizeof(ext_addr));
1238 ext_addr.sin_family = AF_INET;
1239 ext_addr.sin_port = 0;
1240 if (!tor_inet_aton(options->OutboundBindAddress, &ext_addr.sin_addr)) {
1241 log_warn(LD_CONFIG,"Outbound bind address '%s' didn't parse. Ignoring.",
1242 options->OutboundBindAddress);
1243 } else {
1244 if (bind(s, (struct sockaddr*)&ext_addr,
1245 (socklen_t)sizeof(ext_addr)) < 0) {
1246 *socket_error = tor_socket_errno(s);
1247 log_warn(LD_NET,"Error binding network socket: %s",
1248 tor_socket_strerror(*socket_error));
1249 tor_close_socket(s);
1250 return -1;
1255 set_socket_nonblocking(s);
1257 if (options->ConstrainedSockets)
1258 set_constrained_socket_buffers(s, (int)options->ConstrainedSockSize);
1260 memset(addrbuf,0,sizeof(addrbuf));
1261 dest_addr = (struct sockaddr*) addrbuf;
1262 dest_addr_len = tor_addr_to_sockaddr(addr, port, dest_addr, sizeof(addrbuf));
1263 tor_assert(dest_addr_len > 0);
1265 log_debug(LD_NET,"Connecting to %s:%u.",escaped_safe_str(address),port);
1267 if (connect(s, dest_addr, dest_addr_len) < 0) {
1268 int e = tor_socket_errno(s);
1269 if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
1270 /* yuck. kill it. */
1271 *socket_error = e;
1272 log_info(LD_NET,
1273 "connect() to %s:%u failed: %s",escaped_safe_str(address),
1274 port, tor_socket_strerror(e));
1275 tor_close_socket(s);
1276 return -1;
1277 } else {
1278 inprogress = 1;
1282 if (!server_mode(options))
1283 client_check_address_changed(s);
1285 /* it succeeded. we're connected. */
1286 log_fn(inprogress?LOG_DEBUG:LOG_INFO, LD_NET,
1287 "Connection to %s:%u %s (sock %d).",escaped_safe_str(address),
1288 port, inprogress?"in progress":"established", s);
1289 conn->s = s;
1290 if (connection_add(conn) < 0) /* no space, forget it */
1291 return -1;
1292 return inprogress ? 0 : 1;
1295 /** Convert state number to string representation for logging purposes.
1297 static const char *
1298 connection_proxy_state_to_string(int state)
1300 static const char *unknown = "???";
1301 static const char *states[] = {
1302 "PROXY_NONE",
1303 "PROXY_HTTPS_WANT_CONNECT_OK",
1304 "PROXY_SOCKS4_WANT_CONNECT_OK",
1305 "PROXY_SOCKS5_WANT_AUTH_METHOD_NONE",
1306 "PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929",
1307 "PROXY_SOCKS5_WANT_AUTH_RFC1929_OK",
1308 "PROXY_SOCKS5_WANT_CONNECT_OK",
1309 "PROXY_CONNECTED",
1312 if (state < PROXY_NONE || state > PROXY_CONNECTED)
1313 return unknown;
1315 return states[state];
1318 /** Write a proxy request of <b>type</b> (socks4, socks5, https) to conn
1319 * for conn->addr:conn->port, authenticating with the auth details given
1320 * in the configuration (if available). SOCKS 5 and HTTP CONNECT proxies
1321 * support authentication.
1323 * Returns -1 if conn->addr is incompatible with the proxy protocol, and
1324 * 0 otherwise.
1326 * Use connection_read_proxy_handshake() to complete the handshake.
1329 connection_proxy_connect(connection_t *conn, int type)
1331 or_options_t *options;
1333 tor_assert(conn);
1335 options = get_options();
1337 switch (type) {
1338 case PROXY_CONNECT: {
1339 char buf[1024];
1340 char *base64_authenticator=NULL;
1341 const char *authenticator = options->HttpsProxyAuthenticator;
1343 /* Send HTTP CONNECT and authentication (if available) in
1344 * one request */
1346 if (authenticator) {
1347 base64_authenticator = alloc_http_authenticator(authenticator);
1348 if (!base64_authenticator)
1349 log_warn(LD_OR, "Encoding https authenticator failed");
1352 if (base64_authenticator) {
1353 tor_snprintf(buf, sizeof(buf), "CONNECT %s:%d HTTP/1.1\r\n"
1354 "Proxy-Authorization: Basic %s\r\n\r\n",
1355 fmt_addr(&conn->addr),
1356 conn->port, base64_authenticator);
1357 tor_free(base64_authenticator);
1358 } else {
1359 tor_snprintf(buf, sizeof(buf), "CONNECT %s:%d HTTP/1.0\r\n\r\n",
1360 fmt_addr(&conn->addr), conn->port);
1363 connection_write_to_buf(buf, strlen(buf), conn);
1364 conn->proxy_state = PROXY_HTTPS_WANT_CONNECT_OK;
1365 break;
1368 case PROXY_SOCKS4: {
1369 unsigned char buf[9];
1370 uint16_t portn;
1371 uint32_t ip4addr;
1373 /* Send a SOCKS4 connect request with empty user id */
1375 if (tor_addr_family(&conn->addr) != AF_INET) {
1376 log_warn(LD_NET, "SOCKS4 client is incompatible with with IPv6");
1377 return -1;
1380 ip4addr = tor_addr_to_ipv4n(&conn->addr);
1381 portn = htons(conn->port);
1383 buf[0] = 4; /* version */
1384 buf[1] = SOCKS_COMMAND_CONNECT; /* command */
1385 memcpy(buf + 2, &portn, 2); /* port */
1386 memcpy(buf + 4, &ip4addr, 4); /* addr */
1387 buf[8] = 0; /* userid (empty) */
1389 connection_write_to_buf((char *)buf, sizeof(buf), conn);
1390 conn->proxy_state = PROXY_SOCKS4_WANT_CONNECT_OK;
1391 break;
1394 case PROXY_SOCKS5: {
1395 unsigned char buf[4]; /* fields: vers, num methods, method list */
1397 /* Send a SOCKS5 greeting (connect request must wait) */
1399 buf[0] = 5; /* version */
1401 /* number of auth methods */
1402 if (options->Socks5ProxyUsername) {
1403 buf[1] = 2;
1404 buf[2] = 0x00; /* no authentication */
1405 buf[3] = 0x02; /* rfc1929 Username/Passwd auth */
1406 conn->proxy_state = PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929;
1407 } else {
1408 buf[1] = 1;
1409 buf[2] = 0x00; /* no authentication */
1410 conn->proxy_state = PROXY_SOCKS5_WANT_AUTH_METHOD_NONE;
1413 connection_write_to_buf((char *)buf, 2 + buf[1], conn);
1414 break;
1417 default:
1418 log_err(LD_BUG, "Invalid proxy protocol, %d", type);
1419 tor_fragile_assert();
1420 return -1;
1423 log_debug(LD_NET, "set state %s",
1424 connection_proxy_state_to_string(conn->proxy_state));
1426 return 0;
1429 /** Read conn's inbuf. If the http response from the proxy is all
1430 * here, make sure it's good news, then return 1. If it's bad news,
1431 * return -1. Else return 0 and hope for better luck next time.
1433 static int
1434 connection_read_https_proxy_response(connection_t *conn)
1436 char *headers;
1437 char *reason=NULL;
1438 int status_code;
1439 time_t date_header;
1441 switch (fetch_from_buf_http(conn->inbuf,
1442 &headers, MAX_HEADERS_SIZE,
1443 NULL, NULL, 10000, 0)) {
1444 case -1: /* overflow */
1445 log_warn(LD_PROTOCOL,
1446 "Your https proxy sent back an oversized response. Closing.");
1447 return -1;
1448 case 0:
1449 log_info(LD_NET,"https proxy response not all here yet. Waiting.");
1450 return 0;
1451 /* case 1, fall through */
1454 if (parse_http_response(headers, &status_code, &date_header,
1455 NULL, &reason) < 0) {
1456 log_warn(LD_NET,
1457 "Unparseable headers from proxy (connecting to '%s'). Closing.",
1458 conn->address);
1459 tor_free(headers);
1460 return -1;
1462 if (!reason) reason = tor_strdup("[no reason given]");
1464 if (status_code == 200) {
1465 log_info(LD_NET,
1466 "HTTPS connect to '%s' successful! (200 %s) Starting TLS.",
1467 conn->address, escaped(reason));
1468 tor_free(reason);
1469 return 1;
1471 /* else, bad news on the status code */
1472 log_warn(LD_NET,
1473 "The https proxy sent back an unexpected status code %d (%s). "
1474 "Closing.",
1475 status_code, escaped(reason));
1476 tor_free(reason);
1477 return -1;
1480 /** Send SOCKS5 CONNECT command to <b>conn</b>, copying <b>conn->addr</b>
1481 * and <b>conn->port</b> into the request.
1483 static void
1484 connection_send_socks5_connect(connection_t *conn)
1486 unsigned char buf[1024];
1487 size_t reqsize = 6;
1488 uint16_t port = htons(conn->port);
1490 buf[0] = 5; /* version */
1491 buf[1] = SOCKS_COMMAND_CONNECT; /* command */
1492 buf[2] = 0; /* reserved */
1494 if (tor_addr_family(&conn->addr) == AF_INET) {
1495 uint32_t addr = tor_addr_to_ipv4n(&conn->addr);
1497 buf[3] = 1;
1498 reqsize += 4;
1499 memcpy(buf + 4, &addr, 4);
1500 memcpy(buf + 8, &port, 2);
1501 } else { /* AF_INET6 */
1502 buf[3] = 4;
1503 reqsize += 16;
1504 memcpy(buf + 4, tor_addr_to_in6(&conn->addr), 16);
1505 memcpy(buf + 20, &port, 2);
1508 connection_write_to_buf((char *)buf, reqsize, conn);
1510 conn->proxy_state = PROXY_SOCKS5_WANT_CONNECT_OK;
1513 /** Call this from connection_*_process_inbuf() to advance the proxy
1514 * handshake.
1516 * No matter what proxy protocol is used, if this function returns 1, the
1517 * handshake is complete, and the data remaining on inbuf may contain the
1518 * start of the communication with the requested server.
1520 * Returns 0 if the current buffer contains an incomplete response, and -1
1521 * on error.
1524 connection_read_proxy_handshake(connection_t *conn)
1526 int ret = 0;
1527 char *reason = NULL;
1529 log_debug(LD_NET, "enter state %s",
1530 connection_proxy_state_to_string(conn->proxy_state));
1532 switch (conn->proxy_state) {
1533 case PROXY_HTTPS_WANT_CONNECT_OK:
1534 ret = connection_read_https_proxy_response(conn);
1535 if (ret == 1)
1536 conn->proxy_state = PROXY_CONNECTED;
1537 break;
1539 case PROXY_SOCKS4_WANT_CONNECT_OK:
1540 ret = fetch_from_buf_socks_client(conn->inbuf,
1541 conn->proxy_state,
1542 &reason);
1543 if (ret == 1)
1544 conn->proxy_state = PROXY_CONNECTED;
1545 break;
1547 case PROXY_SOCKS5_WANT_AUTH_METHOD_NONE:
1548 ret = fetch_from_buf_socks_client(conn->inbuf,
1549 conn->proxy_state,
1550 &reason);
1551 /* no auth needed, do connect */
1552 if (ret == 1) {
1553 connection_send_socks5_connect(conn);
1554 ret = 0;
1556 break;
1558 case PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929:
1559 ret = fetch_from_buf_socks_client(conn->inbuf,
1560 conn->proxy_state,
1561 &reason);
1563 /* send auth if needed, otherwise do connect */
1564 if (ret == 1) {
1565 connection_send_socks5_connect(conn);
1566 ret = 0;
1567 } else if (ret == 2) {
1568 unsigned char buf[1024];
1569 size_t reqsize, usize, psize;
1570 const char *user, *pass;
1572 user = get_options()->Socks5ProxyUsername;
1573 pass = get_options()->Socks5ProxyPassword;
1574 tor_assert(user && pass);
1576 /* XXX len of user and pass must be <= 255 !!! */
1577 usize = strlen(user);
1578 psize = strlen(pass);
1579 tor_assert(usize <= 255 && psize <= 255);
1580 reqsize = 3 + usize + psize;
1582 buf[0] = 1; /* negotiation version */
1583 buf[1] = usize;
1584 memcpy(buf + 2, user, usize);
1585 buf[2 + usize] = psize;
1586 memcpy(buf + 3 + usize, pass, psize);
1588 connection_write_to_buf((char *)buf, reqsize, conn);
1590 conn->proxy_state = PROXY_SOCKS5_WANT_AUTH_RFC1929_OK;
1591 ret = 0;
1593 break;
1595 case PROXY_SOCKS5_WANT_AUTH_RFC1929_OK:
1596 ret = fetch_from_buf_socks_client(conn->inbuf,
1597 conn->proxy_state,
1598 &reason);
1599 /* send the connect request */
1600 if (ret == 1) {
1601 connection_send_socks5_connect(conn);
1602 ret = 0;
1604 break;
1606 case PROXY_SOCKS5_WANT_CONNECT_OK:
1607 ret = fetch_from_buf_socks_client(conn->inbuf,
1608 conn->proxy_state,
1609 &reason);
1610 if (ret == 1)
1611 conn->proxy_state = PROXY_CONNECTED;
1612 break;
1614 default:
1615 log_err(LD_BUG, "Invalid proxy_state for reading, %d",
1616 conn->proxy_state);
1617 tor_fragile_assert();
1618 ret = -1;
1619 break;
1622 log_debug(LD_NET, "leaving state %s",
1623 connection_proxy_state_to_string(conn->proxy_state));
1625 if (ret < 0) {
1626 if (reason) {
1627 log_warn(LD_NET, "Proxy Client: unable to connect to %s:%d (%s)",
1628 conn->address, conn->port, escaped(reason));
1629 tor_free(reason);
1630 } else {
1631 log_warn(LD_NET, "Proxy Client: unable to connect to %s:%d",
1632 conn->address, conn->port);
1634 } else if (ret == 1) {
1635 log_info(LD_NET, "Proxy Client: connection to %s:%d successful",
1636 conn->address, conn->port);
1639 return ret;
1643 * Launch any configured listener connections of type <b>type</b>. (A
1644 * listener is configured if <b>port_option</b> is non-zero. If any
1645 * ListenAddress configuration options are given in <b>cfg</b>, create a
1646 * connection binding to each one. Otherwise, create a single
1647 * connection binding to the address <b>default_addr</b>.)
1649 * Only launch the listeners of this type that are not already open, and
1650 * only close listeners that are no longer wanted. Existing listeners
1651 * that are still configured are not touched.
1653 * If <b>disable_all_conns</b> is set, then never open new conns, and
1654 * close the existing ones.
1656 * Add all old conns that should be closed to <b>replaced_conns</b>.
1657 * Add all new connections to <b>new_conns</b>.
1659 static int
1660 retry_listeners(int type, config_line_t *cfg,
1661 int port_option, const char *default_addr,
1662 smartlist_t *replaced_conns,
1663 smartlist_t *new_conns,
1664 int disable_all_conns,
1665 int socket_family)
1667 smartlist_t *launch = smartlist_create(), *conns;
1668 int free_launch_elts = 1;
1669 int r;
1670 config_line_t *c;
1671 connection_t *conn;
1672 config_line_t *line;
1674 tor_assert(socket_family == AF_INET || socket_family == AF_UNIX);
1676 if (cfg && port_option) {
1677 for (c = cfg; c; c = c->next) {
1678 smartlist_add(launch, c);
1680 free_launch_elts = 0;
1681 } else if (port_option) {
1682 line = tor_malloc_zero(sizeof(config_line_t));
1683 line->key = tor_strdup("");
1684 line->value = tor_strdup(default_addr);
1685 smartlist_add(launch, line);
1689 SMARTLIST_FOREACH(launch, config_line_t *, l,
1690 log_fn(LOG_NOTICE, "#%s#%s", l->key, l->value));
1693 conns = get_connection_array();
1694 SMARTLIST_FOREACH(conns, connection_t *, conn,
1696 if (conn->type != type ||
1697 conn->socket_family != socket_family ||
1698 conn->marked_for_close)
1699 continue;
1700 /* Okay, so this is a listener. Is it configured? */
1701 line = NULL;
1702 SMARTLIST_FOREACH(launch, config_line_t *, wanted,
1704 char *address=NULL;
1705 uint16_t port;
1706 switch (socket_family) {
1707 case AF_INET:
1708 if (!parse_addr_port(LOG_WARN,
1709 wanted->value, &address, NULL, &port)) {
1710 int addr_matches = !strcasecmp(address, conn->address);
1711 tor_free(address);
1712 if (! port)
1713 port = port_option;
1714 if (port == conn->port && addr_matches) {
1715 line = wanted;
1716 break;
1719 break;
1720 case AF_UNIX:
1721 if (!strcasecmp(wanted->value, conn->address)) {
1722 line = wanted;
1723 break;
1725 break;
1726 default:
1727 tor_assert(0);
1730 if (!line || disable_all_conns) {
1731 /* This one isn't configured. Close it. */
1732 log_notice(LD_NET, "Closing no-longer-configured %s on %s:%d",
1733 conn_type_to_string(type), conn->address, conn->port);
1734 if (replaced_conns) {
1735 smartlist_add(replaced_conns, conn);
1736 } else {
1737 connection_close_immediate(conn);
1738 connection_mark_for_close(conn);
1740 } else {
1741 /* It's configured; we don't need to launch it. */
1742 // log_debug(LD_NET, "Already have %s on %s:%d",
1743 // conn_type_to_string(type), conn->address, conn->port);
1744 smartlist_remove(launch, line);
1745 if (free_launch_elts)
1746 config_free_lines(line);
1750 /* Now open all the listeners that are configured but not opened. */
1751 r = 0;
1752 if (!disable_all_conns) {
1753 SMARTLIST_FOREACH_BEGIN(launch, config_line_t *, cfg_line) {
1754 char *address = NULL;
1755 struct sockaddr *listensockaddr;
1756 socklen_t listensocklen = 0;
1758 switch (socket_family) {
1759 case AF_INET:
1760 listensockaddr = (struct sockaddr *)
1761 create_inet_sockaddr(cfg_line->value,
1762 (uint16_t) port_option,
1763 &address, &listensocklen);
1764 break;
1765 case AF_UNIX:
1766 listensockaddr = (struct sockaddr *)
1767 create_unix_sockaddr(cfg_line->value,
1768 &address, &listensocklen);
1769 break;
1770 default:
1771 tor_assert(0);
1774 if (listensockaddr) {
1775 conn = connection_create_listener(listensockaddr, listensocklen,
1776 type, address);
1777 tor_free(listensockaddr);
1778 tor_free(address);
1779 } else
1780 conn = NULL;
1782 if (!conn) {
1783 r = -1;
1784 } else {
1785 if (new_conns)
1786 smartlist_add(new_conns, conn);
1788 } SMARTLIST_FOREACH_END(cfg_line);
1791 if (free_launch_elts) {
1792 SMARTLIST_FOREACH(launch, config_line_t *, cfg_line,
1793 config_free_lines(cfg_line));
1795 smartlist_free(launch);
1797 return r;
1800 /** Launch listeners for each port you should have open. Only launch
1801 * listeners who are not already open, and only close listeners we no longer
1802 * want.
1804 * Add all old conns that should be closed to <b>replaced_conns</b>.
1805 * Add all new connections to <b>new_conns</b>.
1808 retry_all_listeners(smartlist_t *replaced_conns,
1809 smartlist_t *new_conns)
1811 or_options_t *options = get_options();
1813 if (retry_listeners(CONN_TYPE_OR_LISTENER, options->ORListenAddress,
1814 options->ORPort, "0.0.0.0",
1815 replaced_conns, new_conns, options->ClientOnly,
1816 AF_INET)<0)
1817 return -1;
1818 if (retry_listeners(CONN_TYPE_DIR_LISTENER, options->DirListenAddress,
1819 options->DirPort, "0.0.0.0",
1820 replaced_conns, new_conns, options->ClientOnly,
1821 AF_INET)<0)
1822 return -1;
1823 if (retry_listeners(CONN_TYPE_AP_LISTENER, options->SocksListenAddress,
1824 options->SocksPort, "127.0.0.1",
1825 replaced_conns, new_conns, 0,
1826 AF_INET)<0)
1827 return -1;
1828 if (retry_listeners(CONN_TYPE_AP_TRANS_LISTENER, options->TransListenAddress,
1829 options->TransPort, "127.0.0.1",
1830 replaced_conns, new_conns, 0,
1831 AF_INET)<0)
1832 return -1;
1833 if (retry_listeners(CONN_TYPE_AP_NATD_LISTENER, options->NatdListenAddress,
1834 options->NatdPort, "127.0.0.1",
1835 replaced_conns, new_conns, 0,
1836 AF_INET)<0)
1837 return -1;
1838 if (retry_listeners(CONN_TYPE_AP_DNS_LISTENER, options->DNSListenAddress,
1839 options->DNSPort, "127.0.0.1",
1840 replaced_conns, new_conns, 0,
1841 AF_INET)<0)
1842 return -1;
1843 if (retry_listeners(CONN_TYPE_CONTROL_LISTENER,
1844 options->ControlListenAddress,
1845 options->ControlPort, "127.0.0.1",
1846 replaced_conns, new_conns, 0,
1847 AF_INET)<0)
1848 return -1;
1849 if (retry_listeners(CONN_TYPE_CONTROL_LISTENER,
1850 options->ControlSocket,
1851 options->ControlSocket ? 1 : 0, NULL,
1852 replaced_conns, new_conns, 0,
1853 AF_UNIX)<0)
1854 return -1;
1856 return 0;
1859 /** Return 1 if we should apply rate limiting to <b>conn</b>,
1860 * and 0 otherwise. Right now this just checks if it's an internal
1861 * IP address or an internal connection. */
1862 static int
1863 connection_is_rate_limited(connection_t *conn)
1865 if (conn->linked || /* internal connection */
1866 tor_addr_family(&conn->addr) == AF_UNSPEC || /* no address */
1867 tor_addr_is_internal(&conn->addr, 0)) /* internal address */
1868 return 0;
1869 else
1870 return 1;
1873 extern int global_read_bucket, global_write_bucket;
1874 extern int global_relayed_read_bucket, global_relayed_write_bucket;
1876 /** Did either global write bucket run dry last second? If so,
1877 * we are likely to run dry again this second, so be stingy with the
1878 * tokens we just put in. */
1879 static int write_buckets_empty_last_second = 0;
1881 /** How many seconds of no active local circuits will make the
1882 * connection revert to the "relayed" bandwidth class? */
1883 #define CLIENT_IDLE_TIME_FOR_PRIORITY 30
1885 /** Return 1 if <b>conn</b> should use tokens from the "relayed"
1886 * bandwidth rates, else 0. Currently, only OR conns with bandwidth
1887 * class 1, and directory conns that are serving data out, count.
1889 static int
1890 connection_counts_as_relayed_traffic(connection_t *conn, time_t now)
1892 if (conn->type == CONN_TYPE_OR &&
1893 TO_OR_CONN(conn)->client_used + CLIENT_IDLE_TIME_FOR_PRIORITY < now)
1894 return 1;
1895 if (conn->type == CONN_TYPE_DIR && DIR_CONN_IS_SERVER(conn))
1896 return 1;
1897 return 0;
1900 /** Helper function to decide how many bytes out of <b>global_bucket</b>
1901 * we're willing to use for this transaction. <b>base</b> is the size
1902 * of a cell on the network; <b>priority</b> says whether we should
1903 * write many of them or just a few; and <b>conn_bucket</b> (if
1904 * non-negative) provides an upper limit for our answer. */
1905 static ssize_t
1906 connection_bucket_round_robin(int base, int priority,
1907 ssize_t global_bucket, ssize_t conn_bucket)
1909 ssize_t at_most;
1910 ssize_t num_bytes_high = (priority ? 32 : 16) * base;
1911 ssize_t num_bytes_low = (priority ? 4 : 2) * base;
1913 /* Do a rudimentary round-robin so one circuit can't hog a connection.
1914 * Pick at most 32 cells, at least 4 cells if possible, and if we're in
1915 * the middle pick 1/8 of the available bandwidth. */
1916 at_most = global_bucket / 8;
1917 at_most -= (at_most % base); /* round down */
1918 if (at_most > num_bytes_high) /* 16 KB, or 8 KB for low-priority */
1919 at_most = num_bytes_high;
1920 else if (at_most < num_bytes_low) /* 2 KB, or 1 KB for low-priority */
1921 at_most = num_bytes_low;
1923 if (at_most > global_bucket)
1924 at_most = global_bucket;
1926 if (conn_bucket >= 0 && at_most > conn_bucket)
1927 at_most = conn_bucket;
1929 if (at_most < 0)
1930 return 0;
1931 return at_most;
1934 /** How many bytes at most can we read onto this connection? */
1935 static ssize_t
1936 connection_bucket_read_limit(connection_t *conn, time_t now)
1938 int base = connection_speaks_cells(conn) ?
1939 CELL_NETWORK_SIZE : RELAY_PAYLOAD_SIZE;
1940 int priority = conn->type != CONN_TYPE_DIR;
1941 int conn_bucket = -1;
1942 int global_bucket = global_read_bucket;
1944 if (connection_speaks_cells(conn)) {
1945 or_connection_t *or_conn = TO_OR_CONN(conn);
1946 if (conn->state == OR_CONN_STATE_OPEN)
1947 conn_bucket = or_conn->read_bucket;
1950 if (!connection_is_rate_limited(conn)) {
1951 /* be willing to read on local conns even if our buckets are empty */
1952 return conn_bucket>=0 ? conn_bucket : 1<<14;
1955 if (connection_counts_as_relayed_traffic(conn, now) &&
1956 global_relayed_read_bucket <= global_read_bucket)
1957 global_bucket = global_relayed_read_bucket;
1959 return connection_bucket_round_robin(base, priority,
1960 global_bucket, conn_bucket);
1963 /** How many bytes at most can we write onto this connection? */
1964 ssize_t
1965 connection_bucket_write_limit(connection_t *conn, time_t now)
1967 int base = connection_speaks_cells(conn) ?
1968 CELL_NETWORK_SIZE : RELAY_PAYLOAD_SIZE;
1969 int priority = conn->type != CONN_TYPE_DIR;
1970 int global_bucket = global_write_bucket;
1972 if (!connection_is_rate_limited(conn)) {
1973 /* be willing to write to local conns even if our buckets are empty */
1974 return conn->outbuf_flushlen;
1977 if (connection_counts_as_relayed_traffic(conn, now) &&
1978 global_relayed_write_bucket <= global_write_bucket)
1979 global_bucket = global_relayed_write_bucket;
1981 return connection_bucket_round_robin(base, priority, global_bucket,
1982 conn->outbuf_flushlen);
1985 /** Return 1 if the global write buckets are low enough that we
1986 * shouldn't send <b>attempt</b> bytes of low-priority directory stuff
1987 * out to <b>conn</b>. Else return 0.
1989 * Priority is 1 for v1 requests (directories and running-routers),
1990 * and 2 for v2 requests (statuses and descriptors). But see FFFF in
1991 * directory_handle_command_get() for why we don't use priority 2 yet.
1993 * There are a lot of parameters we could use here:
1994 * - global_relayed_write_bucket. Low is bad.
1995 * - global_write_bucket. Low is bad.
1996 * - bandwidthrate. Low is bad.
1997 * - bandwidthburst. Not a big factor?
1998 * - attempt. High is bad.
1999 * - total bytes queued on outbufs. High is bad. But I'm wary of
2000 * using this, since a few slow-flushing queues will pump up the
2001 * number without meaning what we meant to mean. What we really
2002 * mean is "total directory bytes added to outbufs recently", but
2003 * that's harder to quantify and harder to keep track of.
2006 global_write_bucket_low(connection_t *conn, size_t attempt, int priority)
2008 int smaller_bucket = global_write_bucket < global_relayed_write_bucket ?
2009 global_write_bucket : global_relayed_write_bucket;
2010 if (authdir_mode(get_options()) && priority>1)
2011 return 0; /* there's always room to answer v2 if we're an auth dir */
2013 if (!connection_is_rate_limited(conn))
2014 return 0; /* local conns don't get limited */
2016 if (smaller_bucket < (int)attempt)
2017 return 1; /* not enough space no matter the priority */
2019 if (write_buckets_empty_last_second)
2020 return 1; /* we're already hitting our limits, no more please */
2022 if (priority == 1) { /* old-style v1 query */
2023 /* Could we handle *two* of these requests within the next two seconds? */
2024 or_options_t *options = get_options();
2025 int64_t can_write = (int64_t)smaller_bucket
2026 + 2*(options->RelayBandwidthRate ? options->RelayBandwidthRate :
2027 options->BandwidthRate);
2028 if (can_write < 2*(int64_t)attempt)
2029 return 1;
2030 } else { /* v2 query */
2031 /* no further constraints yet */
2033 return 0;
2036 /** We just read num_read and wrote num_written onto conn.
2037 * Decrement buckets appropriately. */
2038 static void
2039 connection_buckets_decrement(connection_t *conn, time_t now,
2040 size_t num_read, size_t num_written)
2042 if (!connection_is_rate_limited(conn))
2043 return; /* local IPs are free */
2044 if (num_written >= INT_MAX || num_read >= INT_MAX) {
2045 log_err(LD_BUG, "Value out of range. num_read=%lu, num_written=%lu, "
2046 "connection type=%s, state=%s",
2047 (unsigned long)num_read, (unsigned long)num_written,
2048 conn_type_to_string(conn->type),
2049 conn_state_to_string(conn->type, conn->state));
2050 if (num_written >= INT_MAX) num_written = 1;
2051 if (num_read >= INT_MAX) num_read = 1;
2052 tor_fragile_assert();
2055 if (num_read > 0) {
2056 if (conn->type == CONN_TYPE_EXIT)
2057 rep_hist_note_exit_bytes_read(conn->port, num_read);
2058 rep_hist_note_bytes_read(num_read, now);
2060 if (num_written > 0) {
2061 if (conn->type == CONN_TYPE_EXIT)
2062 rep_hist_note_exit_bytes_written(conn->port, num_written);
2063 rep_hist_note_bytes_written(num_written, now);
2066 if (connection_counts_as_relayed_traffic(conn, now)) {
2067 global_relayed_read_bucket -= (int)num_read;
2068 global_relayed_write_bucket -= (int)num_written;
2070 global_read_bucket -= (int)num_read;
2071 global_write_bucket -= (int)num_written;
2072 if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN)
2073 TO_OR_CONN(conn)->read_bucket -= (int)num_read;
2076 /** If we have exhausted our global buckets, or the buckets for conn,
2077 * stop reading. */
2078 static void
2079 connection_consider_empty_read_buckets(connection_t *conn)
2081 const char *reason;
2083 if (global_read_bucket <= 0) {
2084 reason = "global read bucket exhausted. Pausing.";
2085 } else if (connection_counts_as_relayed_traffic(conn, approx_time()) &&
2086 global_relayed_read_bucket <= 0) {
2087 reason = "global relayed read bucket exhausted. Pausing.";
2088 } else if (connection_speaks_cells(conn) &&
2089 conn->state == OR_CONN_STATE_OPEN &&
2090 TO_OR_CONN(conn)->read_bucket <= 0) {
2091 reason = "connection read bucket exhausted. Pausing.";
2092 } else
2093 return; /* all good, no need to stop it */
2095 LOG_FN_CONN(conn, (LOG_DEBUG, LD_NET, "%s", reason));
2096 conn->read_blocked_on_bw = 1;
2097 connection_stop_reading(conn);
2100 /** If we have exhausted our global buckets, or the buckets for conn,
2101 * stop writing. */
2102 static void
2103 connection_consider_empty_write_buckets(connection_t *conn)
2105 const char *reason;
2107 if (global_write_bucket <= 0) {
2108 reason = "global write bucket exhausted. Pausing.";
2109 } else if (connection_counts_as_relayed_traffic(conn, approx_time()) &&
2110 global_relayed_write_bucket <= 0) {
2111 reason = "global relayed write bucket exhausted. Pausing.";
2112 #if 0
2113 } else if (connection_speaks_cells(conn) &&
2114 conn->state == OR_CONN_STATE_OPEN &&
2115 TO_OR_CONN(conn)->write_bucket <= 0) {
2116 reason = "connection write bucket exhausted. Pausing.";
2117 #endif
2118 } else
2119 return; /* all good, no need to stop it */
2121 LOG_FN_CONN(conn, (LOG_DEBUG, LD_NET, "%s", reason));
2122 conn->write_blocked_on_bw = 1;
2123 connection_stop_writing(conn);
2126 /** Initialize the global read bucket to options-\>BandwidthBurst. */
2127 void
2128 connection_bucket_init(void)
2130 or_options_t *options = get_options();
2131 /* start it at max traffic */
2132 global_read_bucket = (int)options->BandwidthBurst;
2133 global_write_bucket = (int)options->BandwidthBurst;
2134 if (options->RelayBandwidthRate) {
2135 global_relayed_read_bucket = (int)options->RelayBandwidthBurst;
2136 global_relayed_write_bucket = (int)options->RelayBandwidthBurst;
2137 } else {
2138 global_relayed_read_bucket = (int)options->BandwidthBurst;
2139 global_relayed_write_bucket = (int)options->BandwidthBurst;
2143 /** Refill a single <b>bucket</b> called <b>name</b> with bandwidth rate
2144 * <b>rate</b> and bandwidth burst <b>burst</b>, assuming that
2145 * <b>seconds_elapsed</b> seconds have passed since the last call.
2147 static void
2148 connection_bucket_refill_helper(int *bucket, int rate, int burst,
2149 int seconds_elapsed, const char *name)
2151 int starting_bucket = *bucket;
2152 if (starting_bucket < burst && seconds_elapsed) {
2153 if (((burst - starting_bucket)/seconds_elapsed) < rate) {
2154 *bucket = burst; /* We would overflow the bucket; just set it to
2155 * the maximum. */
2156 } else {
2157 int incr = rate*seconds_elapsed;
2158 *bucket += incr;
2159 if (*bucket > burst || *bucket < starting_bucket) {
2160 /* If we overflow the burst, or underflow our starting bucket,
2161 * cap the bucket value to burst. */
2162 /* XXXX this might be redundant now, but it doesn't show up
2163 * in profiles. Remove it after analysis. */
2164 *bucket = burst;
2167 log(LOG_DEBUG, LD_NET,"%s now %d.", name, *bucket);
2171 /** A second has rolled over; increment buckets appropriately. */
2172 void
2173 connection_bucket_refill(int seconds_elapsed, time_t now)
2175 or_options_t *options = get_options();
2176 smartlist_t *conns = get_connection_array();
2177 int relayrate, relayburst;
2179 if (options->RelayBandwidthRate) {
2180 relayrate = (int)options->RelayBandwidthRate;
2181 relayburst = (int)options->RelayBandwidthBurst;
2182 } else {
2183 relayrate = (int)options->BandwidthRate;
2184 relayburst = (int)options->BandwidthBurst;
2187 tor_assert(seconds_elapsed >= 0);
2189 write_buckets_empty_last_second =
2190 global_relayed_write_bucket <= 0 || global_write_bucket <= 0;
2192 /* refill the global buckets */
2193 connection_bucket_refill_helper(&global_read_bucket,
2194 (int)options->BandwidthRate,
2195 (int)options->BandwidthBurst,
2196 seconds_elapsed, "global_read_bucket");
2197 connection_bucket_refill_helper(&global_write_bucket,
2198 (int)options->BandwidthRate,
2199 (int)options->BandwidthBurst,
2200 seconds_elapsed, "global_write_bucket");
2201 connection_bucket_refill_helper(&global_relayed_read_bucket,
2202 relayrate, relayburst, seconds_elapsed,
2203 "global_relayed_read_bucket");
2204 connection_bucket_refill_helper(&global_relayed_write_bucket,
2205 relayrate, relayburst, seconds_elapsed,
2206 "global_relayed_write_bucket");
2208 /* refill the per-connection buckets */
2209 SMARTLIST_FOREACH(conns, connection_t *, conn,
2211 if (connection_speaks_cells(conn)) {
2212 or_connection_t *or_conn = TO_OR_CONN(conn);
2213 if (connection_read_bucket_should_increase(or_conn)) {
2214 connection_bucket_refill_helper(&or_conn->read_bucket,
2215 or_conn->bandwidthrate,
2216 or_conn->bandwidthburst,
2217 seconds_elapsed,
2218 "or_conn->read_bucket");
2219 //log_fn(LOG_DEBUG,"Receiver bucket %d now %d.", i,
2220 // conn->read_bucket);
2224 if (conn->read_blocked_on_bw == 1 /* marked to turn reading back on now */
2225 && global_read_bucket > 0 /* and we're allowed to read */
2226 && (!connection_counts_as_relayed_traffic(conn, now) ||
2227 global_relayed_read_bucket > 0) /* even if we're relayed traffic */
2228 && (!connection_speaks_cells(conn) ||
2229 conn->state != OR_CONN_STATE_OPEN ||
2230 TO_OR_CONN(conn)->read_bucket > 0)) {
2231 /* and either a non-cell conn or a cell conn with non-empty bucket */
2232 LOG_FN_CONN(conn, (LOG_DEBUG,LD_NET,
2233 "waking up conn (fd %d) for read", conn->s));
2234 conn->read_blocked_on_bw = 0;
2235 connection_start_reading(conn);
2238 if (conn->write_blocked_on_bw == 1
2239 && global_write_bucket > 0 /* and we're allowed to write */
2240 && (!connection_counts_as_relayed_traffic(conn, now) ||
2241 global_relayed_write_bucket > 0)) {
2242 /* even if we're relayed traffic */
2243 LOG_FN_CONN(conn, (LOG_DEBUG,LD_NET,
2244 "waking up conn (fd %d) for write", conn->s));
2245 conn->write_blocked_on_bw = 0;
2246 connection_start_writing(conn);
2251 /** Is the receiver bucket for connection <b>conn</b> low enough that we
2252 * should add another pile of tokens to it?
2254 static int
2255 connection_read_bucket_should_increase(or_connection_t *conn)
2257 tor_assert(conn);
2259 if (conn->_base.state != OR_CONN_STATE_OPEN)
2260 return 0; /* only open connections play the rate limiting game */
2261 if (conn->read_bucket >= conn->bandwidthburst)
2262 return 0;
2264 return 1;
2267 /** Read bytes from conn-\>s and process them.
2269 * This function gets called from conn_read() in main.c, either
2270 * when poll() has declared that conn wants to read, or (for OR conns)
2271 * when there are pending TLS bytes.
2273 * It calls connection_read_to_buf() to bring in any new bytes,
2274 * and then calls connection_process_inbuf() to process them.
2276 * Mark the connection and return -1 if you want to close it, else
2277 * return 0.
2280 connection_handle_read(connection_t *conn)
2282 int max_to_read=-1, try_to_read;
2283 size_t before, n_read = 0;
2284 int socket_error = 0;
2286 if (conn->marked_for_close)
2287 return 0; /* do nothing */
2289 conn->timestamp_lastread = approx_time();
2291 switch (conn->type) {
2292 case CONN_TYPE_OR_LISTENER:
2293 return connection_handle_listener_read(conn, CONN_TYPE_OR);
2294 case CONN_TYPE_AP_LISTENER:
2295 case CONN_TYPE_AP_TRANS_LISTENER:
2296 case CONN_TYPE_AP_NATD_LISTENER:
2297 return connection_handle_listener_read(conn, CONN_TYPE_AP);
2298 case CONN_TYPE_DIR_LISTENER:
2299 return connection_handle_listener_read(conn, CONN_TYPE_DIR);
2300 case CONN_TYPE_CONTROL_LISTENER:
2301 return connection_handle_listener_read(conn, CONN_TYPE_CONTROL);
2302 case CONN_TYPE_AP_DNS_LISTENER:
2303 /* This should never happen; eventdns.c handles the reads here. */
2304 tor_fragile_assert();
2305 return 0;
2308 loop_again:
2309 try_to_read = max_to_read;
2310 tor_assert(!conn->marked_for_close);
2312 before = buf_datalen(conn->inbuf);
2313 if (connection_read_to_buf(conn, &max_to_read, &socket_error) < 0) {
2314 /* There's a read error; kill the connection.*/
2315 if (conn->type == CONN_TYPE_OR &&
2316 conn->state == OR_CONN_STATE_CONNECTING) {
2317 connection_or_connect_failed(TO_OR_CONN(conn),
2318 errno_to_orconn_end_reason(socket_error),
2319 tor_socket_strerror(socket_error));
2321 if (CONN_IS_EDGE(conn)) {
2322 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
2323 connection_edge_end_errno(edge_conn);
2324 if (edge_conn->socks_request) /* broken, don't send a socks reply back */
2325 edge_conn->socks_request->has_finished = 1;
2327 connection_close_immediate(conn); /* Don't flush; connection is dead. */
2328 connection_mark_for_close(conn);
2329 return -1;
2331 n_read += buf_datalen(conn->inbuf) - before;
2332 if (CONN_IS_EDGE(conn) && try_to_read != max_to_read) {
2333 /* instruct it not to try to package partial cells. */
2334 if (connection_process_inbuf(conn, 0) < 0) {
2335 return -1;
2337 if (!conn->marked_for_close &&
2338 connection_is_reading(conn) &&
2339 !conn->inbuf_reached_eof &&
2340 max_to_read > 0)
2341 goto loop_again; /* try reading again, in case more is here now */
2343 /* one last try, packaging partial cells and all. */
2344 if (!conn->marked_for_close &&
2345 connection_process_inbuf(conn, 1) < 0) {
2346 return -1;
2348 if (conn->linked_conn) {
2349 /* The other side's handle_write() will never actually get called, so
2350 * we need to invoke the appropriate callbacks ourself. */
2351 connection_t *linked = conn->linked_conn;
2353 if (n_read) {
2354 /* Probably a no-op, but hey. */
2355 connection_buckets_decrement(linked, approx_time(), n_read, 0);
2357 if (connection_flushed_some(linked) < 0)
2358 connection_mark_for_close(linked);
2359 if (!connection_wants_to_flush(linked))
2360 connection_finished_flushing(linked);
2363 if (!buf_datalen(linked->outbuf) && conn->active_on_link)
2364 connection_stop_reading_from_linked_conn(conn);
2366 /* If we hit the EOF, call connection_reached_eof(). */
2367 if (!conn->marked_for_close &&
2368 conn->inbuf_reached_eof &&
2369 connection_reached_eof(conn) < 0) {
2370 return -1;
2372 return 0;
2375 /** Pull in new bytes from conn-\>s or conn-\>linked_conn onto conn-\>inbuf,
2376 * either directly or via TLS. Reduce the token buckets by the number of bytes
2377 * read.
2379 * If *max_to_read is -1, then decide it ourselves, else go with the
2380 * value passed to us. When returning, if it's changed, subtract the
2381 * number of bytes we read from *max_to_read.
2383 * Return -1 if we want to break conn, else return 0.
2385 static int
2386 connection_read_to_buf(connection_t *conn, int *max_to_read, int *socket_error)
2388 int result;
2389 ssize_t at_most = *max_to_read;
2390 size_t slack_in_buf, more_to_read;
2391 size_t n_read = 0, n_written = 0;
2393 if (at_most == -1) { /* we need to initialize it */
2394 /* how many bytes are we allowed to read? */
2395 at_most = connection_bucket_read_limit(conn, approx_time());
2398 slack_in_buf = buf_slack(conn->inbuf);
2399 again:
2400 if ((size_t)at_most > slack_in_buf && slack_in_buf >= 1024) {
2401 more_to_read = at_most - slack_in_buf;
2402 at_most = slack_in_buf;
2403 } else {
2404 more_to_read = 0;
2407 if (connection_speaks_cells(conn) &&
2408 conn->state > OR_CONN_STATE_PROXY_HANDSHAKING) {
2409 int pending;
2410 or_connection_t *or_conn = TO_OR_CONN(conn);
2411 size_t initial_size;
2412 if (conn->state == OR_CONN_STATE_TLS_HANDSHAKING ||
2413 conn->state == OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING) {
2414 /* continue handshaking even if global token bucket is empty */
2415 return connection_tls_continue_handshake(or_conn);
2418 log_debug(LD_NET,
2419 "%d: starting, inbuf_datalen %ld (%d pending in tls object)."
2420 " at_most %ld.",
2421 conn->s,(long)buf_datalen(conn->inbuf),
2422 tor_tls_get_pending_bytes(or_conn->tls), (long)at_most);
2424 initial_size = buf_datalen(conn->inbuf);
2425 /* else open, or closing */
2426 result = read_to_buf_tls(or_conn->tls, at_most, conn->inbuf);
2427 if (TOR_TLS_IS_ERROR(result) || result == TOR_TLS_CLOSE)
2428 or_conn->tls_error = result;
2429 else
2430 or_conn->tls_error = 0;
2432 switch (result) {
2433 case TOR_TLS_CLOSE:
2434 case TOR_TLS_ERROR_IO:
2435 log_debug(LD_NET,"TLS connection closed %son read. Closing. "
2436 "(Nickname %s, address %s)",
2437 result == TOR_TLS_CLOSE ? "cleanly " : "",
2438 or_conn->nickname ? or_conn->nickname : "not set",
2439 conn->address);
2440 return result;
2441 CASE_TOR_TLS_ERROR_ANY_NONIO:
2442 log_debug(LD_NET,"tls error [%s]. breaking (nickname %s, address %s).",
2443 tor_tls_err_to_string(result),
2444 or_conn->nickname ? or_conn->nickname : "not set",
2445 conn->address);
2446 return result;
2447 case TOR_TLS_WANTWRITE:
2448 connection_start_writing(conn);
2449 return 0;
2450 case TOR_TLS_WANTREAD: /* we're already reading */
2451 case TOR_TLS_DONE: /* no data read, so nothing to process */
2452 result = 0;
2453 break; /* so we call bucket_decrement below */
2454 default:
2455 break;
2457 pending = tor_tls_get_pending_bytes(or_conn->tls);
2458 if (pending) {
2459 /* If we have any pending bytes, we read them now. This *can*
2460 * take us over our read allotment, but really we shouldn't be
2461 * believing that SSL bytes are the same as TCP bytes anyway. */
2462 int r2 = read_to_buf_tls(or_conn->tls, pending, conn->inbuf);
2463 if (r2<0) {
2464 log_warn(LD_BUG, "apparently, reading pending bytes can fail.");
2465 return -1;
2468 result = (int)(buf_datalen(conn->inbuf)-initial_size);
2469 tor_tls_get_n_raw_bytes(or_conn->tls, &n_read, &n_written);
2470 log_debug(LD_GENERAL, "After TLS read of %d: %ld read, %ld written",
2471 result, (long)n_read, (long)n_written);
2472 } else if (conn->linked) {
2473 if (conn->linked_conn) {
2474 result = move_buf_to_buf(conn->inbuf, conn->linked_conn->outbuf,
2475 &conn->linked_conn->outbuf_flushlen);
2476 } else {
2477 result = 0;
2479 //log_notice(LD_GENERAL, "Moved %d bytes on an internal link!", result);
2480 /* If the other side has disappeared, or if it's been marked for close and
2481 * we flushed its outbuf, then we should set our inbuf_reached_eof. */
2482 if (!conn->linked_conn ||
2483 (conn->linked_conn->marked_for_close &&
2484 buf_datalen(conn->linked_conn->outbuf) == 0))
2485 conn->inbuf_reached_eof = 1;
2487 n_read = (size_t) result;
2488 } else {
2489 /* !connection_speaks_cells, !conn->linked_conn. */
2490 int reached_eof = 0;
2491 CONN_LOG_PROTECT(conn,
2492 result = read_to_buf(conn->s, at_most, conn->inbuf, &reached_eof,
2493 socket_error));
2494 if (reached_eof)
2495 conn->inbuf_reached_eof = 1;
2497 // log_fn(LOG_DEBUG,"read_to_buf returned %d.",read_result);
2499 if (result < 0)
2500 return -1;
2501 n_read = (size_t) result;
2504 if (n_read > 0) { /* change *max_to_read */
2505 /*XXXX021 check for overflow*/
2506 *max_to_read = (int)(at_most - n_read);
2509 if (conn->type == CONN_TYPE_AP) {
2510 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
2511 /*XXXX021 check for overflow*/
2512 edge_conn->n_read += (int)n_read;
2515 connection_buckets_decrement(conn, approx_time(), n_read, n_written);
2517 if (more_to_read && result == at_most) {
2518 slack_in_buf = buf_slack(conn->inbuf);
2519 at_most = more_to_read;
2520 goto again;
2523 /* Call even if result is 0, since the global read bucket may
2524 * have reached 0 on a different conn, and this guy needs to
2525 * know to stop reading. */
2526 connection_consider_empty_read_buckets(conn);
2527 if (n_written > 0 && connection_is_writing(conn))
2528 connection_consider_empty_write_buckets(conn);
2530 return 0;
2533 /** A pass-through to fetch_from_buf. */
2535 connection_fetch_from_buf(char *string, size_t len, connection_t *conn)
2537 return fetch_from_buf(string, len, conn->inbuf);
2540 /** Return conn-\>outbuf_flushlen: how many bytes conn wants to flush
2541 * from its outbuf. */
2543 connection_wants_to_flush(connection_t *conn)
2545 return conn->outbuf_flushlen > 0;
2548 /** Are there too many bytes on edge connection <b>conn</b>'s outbuf to
2549 * send back a relay-level sendme yet? Return 1 if so, 0 if not. Used by
2550 * connection_edge_consider_sending_sendme().
2553 connection_outbuf_too_full(connection_t *conn)
2555 return (conn->outbuf_flushlen > 10*CELL_PAYLOAD_SIZE);
2558 /** Try to flush more bytes onto conn-\>s.
2560 * This function gets called either from conn_write() in main.c
2561 * when poll() has declared that conn wants to write, or below
2562 * from connection_write_to_buf() when an entire TLS record is ready.
2564 * Update conn-\>timestamp_lastwritten to now, and call flush_buf
2565 * or flush_buf_tls appropriately. If it succeeds and there are no more
2566 * more bytes on conn->outbuf, then call connection_finished_flushing
2567 * on it too.
2569 * If <b>force</b>, then write as many bytes as possible, ignoring bandwidth
2570 * limits. (Used for flushing messages to controller connections on fatal
2571 * errors.)
2573 * Mark the connection and return -1 if you want to close it, else
2574 * return 0.
2577 connection_handle_write(connection_t *conn, int force)
2579 int e;
2580 socklen_t len=(socklen_t)sizeof(e);
2581 int result;
2582 ssize_t max_to_write;
2583 time_t now = approx_time();
2584 size_t n_read = 0, n_written = 0;
2586 tor_assert(!connection_is_listener(conn));
2588 if (conn->marked_for_close || conn->s < 0)
2589 return 0; /* do nothing */
2591 if (conn->in_flushed_some) {
2592 log_warn(LD_BUG, "called recursively from inside conn->in_flushed_some");
2593 return 0;
2596 conn->timestamp_lastwritten = now;
2598 /* Sometimes, "writable" means "connected". */
2599 if (connection_state_is_connecting(conn)) {
2600 if (getsockopt(conn->s, SOL_SOCKET, SO_ERROR, (void*)&e, &len) < 0) {
2601 log_warn(LD_BUG,
2602 "getsockopt() syscall failed?! Please report to tor-ops.");
2603 if (CONN_IS_EDGE(conn))
2604 connection_edge_end_errno(TO_EDGE_CONN(conn));
2605 connection_mark_for_close(conn);
2606 return -1;
2608 if (e) {
2609 /* some sort of error, but maybe just inprogress still */
2610 if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
2611 log_info(LD_NET,"in-progress connect failed. Removing. (%s)",
2612 tor_socket_strerror(e));
2613 if (CONN_IS_EDGE(conn))
2614 connection_edge_end_errno(TO_EDGE_CONN(conn));
2615 if (conn->type == CONN_TYPE_OR)
2616 connection_or_connect_failed(TO_OR_CONN(conn),
2617 errno_to_orconn_end_reason(e),
2618 tor_socket_strerror(e));
2620 connection_close_immediate(conn);
2621 connection_mark_for_close(conn);
2622 return -1;
2623 } else {
2624 return 0; /* no change, see if next time is better */
2627 /* The connection is successful. */
2628 if (connection_finished_connecting(conn)<0)
2629 return -1;
2632 max_to_write = force ? (ssize_t)conn->outbuf_flushlen
2633 : connection_bucket_write_limit(conn, now);
2635 if (connection_speaks_cells(conn) &&
2636 conn->state > OR_CONN_STATE_PROXY_HANDSHAKING) {
2637 or_connection_t *or_conn = TO_OR_CONN(conn);
2638 if (conn->state == OR_CONN_STATE_TLS_HANDSHAKING ||
2639 conn->state == OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING) {
2640 connection_stop_writing(conn);
2641 if (connection_tls_continue_handshake(or_conn) < 0) {
2642 /* Don't flush; connection is dead. */
2643 connection_close_immediate(conn);
2644 connection_mark_for_close(conn);
2645 return -1;
2647 return 0;
2648 } else if (conn->state == OR_CONN_STATE_TLS_SERVER_RENEGOTIATING) {
2649 return connection_handle_read(conn);
2652 /* else open, or closing */
2653 result = flush_buf_tls(or_conn->tls, conn->outbuf,
2654 max_to_write, &conn->outbuf_flushlen);
2656 /* If we just flushed the last bytes, check if this tunneled dir
2657 * request is done. */
2658 if (buf_datalen(conn->outbuf) == 0 && conn->dirreq_id)
2659 geoip_change_dirreq_state(conn->dirreq_id, DIRREQ_TUNNELED,
2660 DIRREQ_OR_CONN_BUFFER_FLUSHED);
2662 switch (result) {
2663 CASE_TOR_TLS_ERROR_ANY:
2664 case TOR_TLS_CLOSE:
2665 log_info(LD_NET,result!=TOR_TLS_CLOSE?
2666 "tls error. breaking.":"TLS connection closed on flush");
2667 /* Don't flush; connection is dead. */
2668 connection_close_immediate(conn);
2669 connection_mark_for_close(conn);
2670 return -1;
2671 case TOR_TLS_WANTWRITE:
2672 log_debug(LD_NET,"wanted write.");
2673 /* we're already writing */
2674 return 0;
2675 case TOR_TLS_WANTREAD:
2676 /* Make sure to avoid a loop if the receive buckets are empty. */
2677 log_debug(LD_NET,"wanted read.");
2678 if (!connection_is_reading(conn)) {
2679 connection_stop_writing(conn);
2680 conn->write_blocked_on_bw = 1;
2681 /* we'll start reading again when we get more tokens in our
2682 * read bucket; then we'll start writing again too.
2685 /* else no problem, we're already reading */
2686 return 0;
2687 /* case TOR_TLS_DONE:
2688 * for TOR_TLS_DONE, fall through to check if the flushlen
2689 * is empty, so we can stop writing.
2693 tor_tls_get_n_raw_bytes(or_conn->tls, &n_read, &n_written);
2694 log_debug(LD_GENERAL, "After TLS write of %d: %ld read, %ld written",
2695 result, (long)n_read, (long)n_written);
2696 } else {
2697 CONN_LOG_PROTECT(conn,
2698 result = flush_buf(conn->s, conn->outbuf,
2699 max_to_write, &conn->outbuf_flushlen));
2700 if (result < 0) {
2701 if (CONN_IS_EDGE(conn))
2702 connection_edge_end_errno(TO_EDGE_CONN(conn));
2704 connection_close_immediate(conn); /* Don't flush; connection is dead. */
2705 connection_mark_for_close(conn);
2706 return -1;
2708 n_written = (size_t) result;
2711 if (conn->type == CONN_TYPE_AP) {
2712 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
2713 /*XXXX021 check for overflow.*/
2714 edge_conn->n_written += (int)n_written;
2717 connection_buckets_decrement(conn, approx_time(), n_read, n_written);
2719 if (result > 0) {
2720 /* If we wrote any bytes from our buffer, then call the appropriate
2721 * functions. */
2722 if (connection_flushed_some(conn) < 0)
2723 connection_mark_for_close(conn);
2726 if (!connection_wants_to_flush(conn)) { /* it's done flushing */
2727 if (connection_finished_flushing(conn) < 0) {
2728 /* already marked */
2729 return -1;
2731 return 0;
2734 /* Call even if result is 0, since the global write bucket may
2735 * have reached 0 on a different conn, and this guy needs to
2736 * know to stop writing. */
2737 connection_consider_empty_write_buckets(conn);
2738 if (n_read > 0 && connection_is_reading(conn))
2739 connection_consider_empty_read_buckets(conn);
2741 return 0;
2744 /** OpenSSL TLS record size is 16383; this is close. The goal here is to
2745 * push data out as soon as we know there's enough for a TLS record, so
2746 * during periods of high load we won't read entire megabytes from
2747 * input before pushing any data out. It also has the feature of not
2748 * growing huge outbufs unless something is slow. */
2749 #define MIN_TLS_FLUSHLEN 15872
2751 /** Append <b>len</b> bytes of <b>string</b> onto <b>conn</b>'s
2752 * outbuf, and ask it to start writing.
2754 * If <b>zlib</b> is nonzero, this is a directory connection that should get
2755 * its contents compressed or decompressed as they're written. If zlib is
2756 * negative, this is the last data to be compressed, and the connection's zlib
2757 * state should be flushed.
2759 * If it's an OR conn and an entire TLS record is ready, then try to
2760 * flush the record now. Similarly, if it's a local control connection
2761 * and a 64k chunk is ready, try to flush it all, so we don't end up with
2762 * many megabytes of controller info queued at once.
2764 void
2765 _connection_write_to_buf_impl(const char *string, size_t len,
2766 connection_t *conn, int zlib)
2768 /* XXXX This function really needs to return -1 on failure. */
2769 int r;
2770 size_t old_datalen;
2771 if (!len && !(zlib<0))
2772 return;
2773 /* if it's marked for close, only allow write if we mean to flush it */
2774 if (conn->marked_for_close && !conn->hold_open_until_flushed)
2775 return;
2777 old_datalen = buf_datalen(conn->outbuf);
2778 if (zlib) {
2779 dir_connection_t *dir_conn = TO_DIR_CONN(conn);
2780 int done = zlib < 0;
2781 CONN_LOG_PROTECT(conn, r = write_to_buf_zlib(conn->outbuf,
2782 dir_conn->zlib_state,
2783 string, len, done));
2784 } else {
2785 CONN_LOG_PROTECT(conn, r = write_to_buf(string, len, conn->outbuf));
2787 if (r < 0) {
2788 if (CONN_IS_EDGE(conn)) {
2789 /* if it failed, it means we have our package/delivery windows set
2790 wrong compared to our max outbuf size. close the whole circuit. */
2791 log_warn(LD_NET,
2792 "write_to_buf failed. Closing circuit (fd %d).", conn->s);
2793 circuit_mark_for_close(circuit_get_by_edge_conn(TO_EDGE_CONN(conn)),
2794 END_CIRC_REASON_INTERNAL);
2795 } else {
2796 log_warn(LD_NET,
2797 "write_to_buf failed. Closing connection (fd %d).", conn->s);
2798 connection_mark_for_close(conn);
2800 return;
2803 connection_start_writing(conn);
2804 if (zlib) {
2805 conn->outbuf_flushlen += buf_datalen(conn->outbuf) - old_datalen;
2806 } else {
2807 ssize_t extra = 0;
2808 conn->outbuf_flushlen += len;
2810 /* Should we try flushing the outbuf now? */
2811 if (conn->in_flushed_some) {
2812 /* Don't flush the outbuf when the reason we're writing more stuff is
2813 * _because_ we flushed the outbuf. That's unfair. */
2814 return;
2817 if (conn->type == CONN_TYPE_OR &&
2818 conn->outbuf_flushlen-len < MIN_TLS_FLUSHLEN &&
2819 conn->outbuf_flushlen >= MIN_TLS_FLUSHLEN) {
2820 /* We just pushed outbuf_flushlen to MIN_TLS_FLUSHLEN or above;
2821 * we can send out a full TLS frame now if we like. */
2822 extra = conn->outbuf_flushlen - MIN_TLS_FLUSHLEN;
2823 conn->outbuf_flushlen = MIN_TLS_FLUSHLEN;
2824 } else if (conn->type == CONN_TYPE_CONTROL &&
2825 !connection_is_rate_limited(conn) &&
2826 conn->outbuf_flushlen-len < 1<<16 &&
2827 conn->outbuf_flushlen >= 1<<16) {
2828 /* just try to flush all of it */
2829 } else
2830 return; /* no need to try flushing */
2832 if (connection_handle_write(conn, 0) < 0) {
2833 if (!conn->marked_for_close) {
2834 /* this connection is broken. remove it. */
2835 log_warn(LD_BUG, "unhandled error on write for "
2836 "conn (type %d, fd %d); removing",
2837 conn->type, conn->s);
2838 tor_fragile_assert();
2839 /* do a close-immediate here, so we don't try to flush */
2840 connection_close_immediate(conn);
2842 return;
2844 if (extra) {
2845 conn->outbuf_flushlen += extra;
2846 connection_start_writing(conn);
2851 /** Return a connection with given type, address, port, and purpose;
2852 * or NULL if no such connection exists. */
2853 connection_t *
2854 connection_get_by_type_addr_port_purpose(int type,
2855 const tor_addr_t *addr, uint16_t port,
2856 int purpose)
2858 smartlist_t *conns = get_connection_array();
2859 SMARTLIST_FOREACH(conns, connection_t *, conn,
2861 if (conn->type == type &&
2862 tor_addr_eq(&conn->addr, addr) &&
2863 conn->port == port &&
2864 conn->purpose == purpose &&
2865 !conn->marked_for_close)
2866 return conn;
2868 return NULL;
2871 /** Return the stream with id <b>id</b> if it is not already marked for
2872 * close.
2874 connection_t *
2875 connection_get_by_global_id(uint64_t id)
2877 smartlist_t *conns = get_connection_array();
2878 SMARTLIST_FOREACH(conns, connection_t *, conn,
2880 if (conn->global_identifier == id)
2881 return conn;
2883 return NULL;
2886 /** Return a connection of type <b>type</b> that is not marked for close.
2888 connection_t *
2889 connection_get_by_type(int type)
2891 smartlist_t *conns = get_connection_array();
2892 SMARTLIST_FOREACH(conns, connection_t *, conn,
2894 if (conn->type == type && !conn->marked_for_close)
2895 return conn;
2897 return NULL;
2900 /** Return a connection of type <b>type</b> that is in state <b>state</b>,
2901 * and that is not marked for close.
2903 connection_t *
2904 connection_get_by_type_state(int type, int state)
2906 smartlist_t *conns = get_connection_array();
2907 SMARTLIST_FOREACH(conns, connection_t *, conn,
2909 if (conn->type == type && conn->state == state && !conn->marked_for_close)
2910 return conn;
2912 return NULL;
2915 /** Return a connection of type <b>type</b> that has rendquery equal
2916 * to <b>rendquery</b>, and that is not marked for close. If state
2917 * is non-zero, conn must be of that state too.
2919 connection_t *
2920 connection_get_by_type_state_rendquery(int type, int state,
2921 const char *rendquery)
2923 smartlist_t *conns = get_connection_array();
2925 tor_assert(type == CONN_TYPE_DIR ||
2926 type == CONN_TYPE_AP || type == CONN_TYPE_EXIT);
2927 tor_assert(rendquery);
2929 SMARTLIST_FOREACH(conns, connection_t *, conn,
2931 if (conn->type == type &&
2932 !conn->marked_for_close &&
2933 (!state || state == conn->state)) {
2934 if (type == CONN_TYPE_DIR &&
2935 TO_DIR_CONN(conn)->rend_data &&
2936 !rend_cmp_service_ids(rendquery,
2937 TO_DIR_CONN(conn)->rend_data->onion_address))
2938 return conn;
2939 else if (CONN_IS_EDGE(conn) &&
2940 TO_EDGE_CONN(conn)->rend_data &&
2941 !rend_cmp_service_ids(rendquery,
2942 TO_EDGE_CONN(conn)->rend_data->onion_address))
2943 return conn;
2946 return NULL;
2949 /** Return an open, non-marked connection of a given type and purpose, or NULL
2950 * if no such connection exists. */
2951 connection_t *
2952 connection_get_by_type_purpose(int type, int purpose)
2954 smartlist_t *conns = get_connection_array();
2955 SMARTLIST_FOREACH(conns, connection_t *, conn,
2957 if (conn->type == type &&
2958 !conn->marked_for_close &&
2959 (purpose == conn->purpose))
2960 return conn;
2962 return NULL;
2965 /** Return 1 if <b>conn</b> is a listener conn, else return 0. */
2967 connection_is_listener(connection_t *conn)
2969 if (conn->type == CONN_TYPE_OR_LISTENER ||
2970 conn->type == CONN_TYPE_AP_LISTENER ||
2971 conn->type == CONN_TYPE_AP_TRANS_LISTENER ||
2972 conn->type == CONN_TYPE_AP_DNS_LISTENER ||
2973 conn->type == CONN_TYPE_AP_NATD_LISTENER ||
2974 conn->type == CONN_TYPE_DIR_LISTENER ||
2975 conn->type == CONN_TYPE_CONTROL_LISTENER)
2976 return 1;
2977 return 0;
2980 /** Return 1 if <b>conn</b> is in state "open" and is not marked
2981 * for close, else return 0.
2984 connection_state_is_open(connection_t *conn)
2986 tor_assert(conn);
2988 if (conn->marked_for_close)
2989 return 0;
2991 if ((conn->type == CONN_TYPE_OR && conn->state == OR_CONN_STATE_OPEN) ||
2992 (conn->type == CONN_TYPE_AP && conn->state == AP_CONN_STATE_OPEN) ||
2993 (conn->type == CONN_TYPE_EXIT && conn->state == EXIT_CONN_STATE_OPEN) ||
2994 (conn->type == CONN_TYPE_CONTROL &&
2995 conn->state == CONTROL_CONN_STATE_OPEN))
2996 return 1;
2998 return 0;
3001 /** Return 1 if conn is in 'connecting' state, else return 0. */
3003 connection_state_is_connecting(connection_t *conn)
3005 tor_assert(conn);
3007 if (conn->marked_for_close)
3008 return 0;
3009 switch (conn->type)
3011 case CONN_TYPE_OR:
3012 return conn->state == OR_CONN_STATE_CONNECTING;
3013 case CONN_TYPE_EXIT:
3014 return conn->state == EXIT_CONN_STATE_CONNECTING;
3015 case CONN_TYPE_DIR:
3016 return conn->state == DIR_CONN_STATE_CONNECTING;
3019 return 0;
3022 /** Allocates a base64'ed authenticator for use in http or https
3023 * auth, based on the input string <b>authenticator</b>. Returns it
3024 * if success, else returns NULL. */
3025 char *
3026 alloc_http_authenticator(const char *authenticator)
3028 /* an authenticator in Basic authentication
3029 * is just the string "username:password" */
3030 const size_t authenticator_length = strlen(authenticator);
3031 /* The base64_encode function needs a minimum buffer length
3032 * of 66 bytes. */
3033 const size_t base64_authenticator_length = (authenticator_length/48+1)*66;
3034 char *base64_authenticator = tor_malloc(base64_authenticator_length);
3035 if (base64_encode(base64_authenticator, base64_authenticator_length,
3036 authenticator, authenticator_length) < 0) {
3037 tor_free(base64_authenticator); /* free and set to null */
3038 } else {
3039 /* remove extra \n at end of encoding */
3040 base64_authenticator[strlen(base64_authenticator) - 1] = 0;
3042 return base64_authenticator;
3045 /** Given a socket handle, check whether the local address (sockname) of the
3046 * socket is one that we've connected from before. If so, double-check
3047 * whether our address has changed and we need to generate keys. If we do,
3048 * call init_keys().
3050 static void
3051 client_check_address_changed(int sock)
3053 uint32_t iface_ip, ip_out;
3054 struct sockaddr_in out_addr;
3055 socklen_t out_addr_len = (socklen_t) sizeof(out_addr);
3056 uint32_t *ip;
3058 if (!last_interface_ip)
3059 get_interface_address(LOG_INFO, &last_interface_ip);
3060 if (!outgoing_addrs)
3061 outgoing_addrs = smartlist_create();
3063 if (getsockname(sock, (struct sockaddr*)&out_addr, &out_addr_len)<0) {
3064 int e = tor_socket_errno(sock);
3065 log_warn(LD_NET, "getsockname() to check for address change failed: %s",
3066 tor_socket_strerror(e));
3067 return;
3070 /* If we've used this address previously, we're okay. */
3071 ip_out = ntohl(out_addr.sin_addr.s_addr);
3072 SMARTLIST_FOREACH(outgoing_addrs, uint32_t*, ip_ptr,
3073 if (*ip_ptr == ip_out) return;
3076 /* Uh-oh. We haven't connected from this address before. Has the interface
3077 * address changed? */
3078 if (get_interface_address(LOG_INFO, &iface_ip)<0)
3079 return;
3080 ip = tor_malloc(sizeof(uint32_t));
3081 *ip = ip_out;
3083 if (iface_ip == last_interface_ip) {
3084 /* Nope, it hasn't changed. Add this address to the list. */
3085 smartlist_add(outgoing_addrs, ip);
3086 } else {
3087 /* The interface changed. We're a client, so we need to regenerate our
3088 * keys. First, reset the state. */
3089 log(LOG_NOTICE, LD_NET, "Our IP address has changed. Rotating keys...");
3090 last_interface_ip = iface_ip;
3091 SMARTLIST_FOREACH(outgoing_addrs, void*, ip_ptr, tor_free(ip_ptr));
3092 smartlist_clear(outgoing_addrs);
3093 smartlist_add(outgoing_addrs, ip);
3094 /* Okay, now change our keys. */
3095 ip_address_changed(1);
3099 /** Some systems have limited system buffers for recv and xmit on
3100 * sockets allocated in a virtual server or similar environment. For a Tor
3101 * server this can produce the "Error creating network socket: No buffer
3102 * space available" error once all available TCP buffer space is consumed.
3103 * This method will attempt to constrain the buffers allocated for the socket
3104 * to the desired size to stay below system TCP buffer limits.
3106 static void
3107 set_constrained_socket_buffers(int sock, int size)
3109 void *sz = (void*)&size;
3110 socklen_t sz_sz = (socklen_t) sizeof(size);
3111 if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, sz, sz_sz) < 0) {
3112 int e = tor_socket_errno(sock);
3113 log_warn(LD_NET, "setsockopt() to constrain send "
3114 "buffer to %d bytes failed: %s", size, tor_socket_strerror(e));
3116 if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, sz, sz_sz) < 0) {
3117 int e = tor_socket_errno(sock);
3118 log_warn(LD_NET, "setsockopt() to constrain recv "
3119 "buffer to %d bytes failed: %s", size, tor_socket_strerror(e));
3123 /** Process new bytes that have arrived on conn-\>inbuf.
3125 * This function just passes conn to the connection-specific
3126 * connection_*_process_inbuf() function. It also passes in
3127 * package_partial if wanted.
3129 static int
3130 connection_process_inbuf(connection_t *conn, int package_partial)
3132 tor_assert(conn);
3134 switch (conn->type) {
3135 case CONN_TYPE_OR:
3136 return connection_or_process_inbuf(TO_OR_CONN(conn));
3137 case CONN_TYPE_EXIT:
3138 case CONN_TYPE_AP:
3139 return connection_edge_process_inbuf(TO_EDGE_CONN(conn),
3140 package_partial);
3141 case CONN_TYPE_DIR:
3142 return connection_dir_process_inbuf(TO_DIR_CONN(conn));
3143 case CONN_TYPE_CPUWORKER:
3144 return connection_cpu_process_inbuf(conn);
3145 case CONN_TYPE_CONTROL:
3146 return connection_control_process_inbuf(TO_CONTROL_CONN(conn));
3147 default:
3148 log_err(LD_BUG,"got unexpected conn type %d.", conn->type);
3149 tor_fragile_assert();
3150 return -1;
3154 /** Called whenever we've written data on a connection. */
3155 static int
3156 connection_flushed_some(connection_t *conn)
3158 int r = 0;
3159 tor_assert(!conn->in_flushed_some);
3160 conn->in_flushed_some = 1;
3161 if (conn->type == CONN_TYPE_DIR &&
3162 conn->state == DIR_CONN_STATE_SERVER_WRITING) {
3163 r = connection_dirserv_flushed_some(TO_DIR_CONN(conn));
3164 } else if (conn->type == CONN_TYPE_OR) {
3165 r = connection_or_flushed_some(TO_OR_CONN(conn));
3167 conn->in_flushed_some = 0;
3168 return r;
3171 /** We just finished flushing bytes from conn-\>outbuf, and there
3172 * are no more bytes remaining.
3174 * This function just passes conn to the connection-specific
3175 * connection_*_finished_flushing() function.
3177 static int
3178 connection_finished_flushing(connection_t *conn)
3180 tor_assert(conn);
3182 /* If the connection is closed, don't try to do anything more here. */
3183 if (CONN_IS_CLOSED(conn))
3184 return 0;
3186 // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
3188 switch (conn->type) {
3189 case CONN_TYPE_OR:
3190 return connection_or_finished_flushing(TO_OR_CONN(conn));
3191 case CONN_TYPE_AP:
3192 case CONN_TYPE_EXIT:
3193 return connection_edge_finished_flushing(TO_EDGE_CONN(conn));
3194 case CONN_TYPE_DIR:
3195 return connection_dir_finished_flushing(TO_DIR_CONN(conn));
3196 case CONN_TYPE_CPUWORKER:
3197 return connection_cpu_finished_flushing(conn);
3198 case CONN_TYPE_CONTROL:
3199 return connection_control_finished_flushing(TO_CONTROL_CONN(conn));
3200 default:
3201 log_err(LD_BUG,"got unexpected conn type %d.", conn->type);
3202 tor_fragile_assert();
3203 return -1;
3207 /** Called when our attempt to connect() to another server has just
3208 * succeeded.
3210 * This function just passes conn to the connection-specific
3211 * connection_*_finished_connecting() function.
3213 static int
3214 connection_finished_connecting(connection_t *conn)
3216 tor_assert(conn);
3217 switch (conn->type)
3219 case CONN_TYPE_OR:
3220 return connection_or_finished_connecting(TO_OR_CONN(conn));
3221 case CONN_TYPE_EXIT:
3222 return connection_edge_finished_connecting(TO_EDGE_CONN(conn));
3223 case CONN_TYPE_DIR:
3224 return connection_dir_finished_connecting(TO_DIR_CONN(conn));
3225 default:
3226 log_err(LD_BUG,"got unexpected conn type %d.", conn->type);
3227 tor_fragile_assert();
3228 return -1;
3232 /** Callback: invoked when a connection reaches an EOF event. */
3233 static int
3234 connection_reached_eof(connection_t *conn)
3236 switch (conn->type) {
3237 case CONN_TYPE_OR:
3238 return connection_or_reached_eof(TO_OR_CONN(conn));
3239 case CONN_TYPE_AP:
3240 case CONN_TYPE_EXIT:
3241 return connection_edge_reached_eof(TO_EDGE_CONN(conn));
3242 case CONN_TYPE_DIR:
3243 return connection_dir_reached_eof(TO_DIR_CONN(conn));
3244 case CONN_TYPE_CPUWORKER:
3245 return connection_cpu_reached_eof(conn);
3246 case CONN_TYPE_CONTROL:
3247 return connection_control_reached_eof(TO_CONTROL_CONN(conn));
3248 default:
3249 log_err(LD_BUG,"got unexpected conn type %d.", conn->type);
3250 tor_fragile_assert();
3251 return -1;
3255 /** Log how many bytes are used by buffers of different kinds and sizes. */
3256 void
3257 connection_dump_buffer_mem_stats(int severity)
3259 uint64_t used_by_type[_CONN_TYPE_MAX+1];
3260 uint64_t alloc_by_type[_CONN_TYPE_MAX+1];
3261 int n_conns_by_type[_CONN_TYPE_MAX+1];
3262 uint64_t total_alloc = 0;
3263 uint64_t total_used = 0;
3264 int i;
3265 smartlist_t *conns = get_connection_array();
3267 memset(used_by_type, 0, sizeof(used_by_type));
3268 memset(alloc_by_type, 0, sizeof(alloc_by_type));
3269 memset(n_conns_by_type, 0, sizeof(n_conns_by_type));
3271 SMARTLIST_FOREACH(conns, connection_t *, c,
3273 int tp = c->type;
3274 ++n_conns_by_type[tp];
3275 if (c->inbuf) {
3276 used_by_type[tp] += buf_datalen(c->inbuf);
3277 alloc_by_type[tp] += buf_allocation(c->inbuf);
3279 if (c->outbuf) {
3280 used_by_type[tp] += buf_datalen(c->outbuf);
3281 alloc_by_type[tp] += buf_allocation(c->outbuf);
3284 for (i=0; i <= _CONN_TYPE_MAX; ++i) {
3285 total_used += used_by_type[i];
3286 total_alloc += alloc_by_type[i];
3289 log(severity, LD_GENERAL,
3290 "In buffers for %d connections: "U64_FORMAT" used/"U64_FORMAT" allocated",
3291 smartlist_len(conns),
3292 U64_PRINTF_ARG(total_used), U64_PRINTF_ARG(total_alloc));
3293 for (i=_CONN_TYPE_MIN; i <= _CONN_TYPE_MAX; ++i) {
3294 if (!n_conns_by_type[i])
3295 continue;
3296 log(severity, LD_GENERAL,
3297 " For %d %s connections: "U64_FORMAT" used/"U64_FORMAT" allocated",
3298 n_conns_by_type[i], conn_type_to_string(i),
3299 U64_PRINTF_ARG(used_by_type[i]), U64_PRINTF_ARG(alloc_by_type[i]));
3303 /** Verify that connection <b>conn</b> has all of its invariants
3304 * correct. Trigger an assert if anything is invalid.
3306 void
3307 assert_connection_ok(connection_t *conn, time_t now)
3309 (void) now; /* XXXX unused. */
3310 tor_assert(conn);
3311 tor_assert(conn->type >= _CONN_TYPE_MIN);
3312 tor_assert(conn->type <= _CONN_TYPE_MAX);
3313 switch (conn->type) {
3314 case CONN_TYPE_OR:
3315 tor_assert(conn->magic == OR_CONNECTION_MAGIC);
3316 break;
3317 case CONN_TYPE_AP:
3318 case CONN_TYPE_EXIT:
3319 tor_assert(conn->magic == EDGE_CONNECTION_MAGIC);
3320 break;
3321 case CONN_TYPE_DIR:
3322 tor_assert(conn->magic == DIR_CONNECTION_MAGIC);
3323 break;
3324 case CONN_TYPE_CONTROL:
3325 tor_assert(conn->magic == CONTROL_CONNECTION_MAGIC);
3326 break;
3327 default:
3328 tor_assert(conn->magic == BASE_CONNECTION_MAGIC);
3329 break;
3332 if (conn->linked_conn) {
3333 tor_assert(conn->linked_conn->linked_conn == conn);
3334 tor_assert(conn->linked);
3336 if (conn->linked)
3337 tor_assert(conn->s < 0);
3339 if (conn->outbuf_flushlen > 0) {
3340 tor_assert(connection_is_writing(conn) || conn->write_blocked_on_bw ||
3341 (CONN_IS_EDGE(conn) && TO_EDGE_CONN(conn)->edge_blocked_on_circ));
3344 if (conn->hold_open_until_flushed)
3345 tor_assert(conn->marked_for_close);
3347 /* XXXX check: read_blocked_on_bw, write_blocked_on_bw, s, conn_array_index,
3348 * marked_for_close. */
3350 /* buffers */
3351 if (!connection_is_listener(conn)) {
3352 assert_buf_ok(conn->inbuf);
3353 assert_buf_ok(conn->outbuf);
3356 if (conn->type == CONN_TYPE_OR) {
3357 or_connection_t *or_conn = TO_OR_CONN(conn);
3358 if (conn->state == OR_CONN_STATE_OPEN) {
3359 /* tor_assert(conn->bandwidth > 0); */
3360 /* the above isn't necessarily true: if we just did a TLS
3361 * handshake but we didn't recognize the other peer, or it
3362 * gave a bad cert/etc, then we won't have assigned bandwidth,
3363 * yet it will be open. -RD
3365 // tor_assert(conn->read_bucket >= 0);
3367 // tor_assert(conn->addr && conn->port);
3368 tor_assert(conn->address);
3369 if (conn->state > OR_CONN_STATE_PROXY_HANDSHAKING)
3370 tor_assert(or_conn->tls);
3373 if (CONN_IS_EDGE(conn)) {
3374 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
3375 if (edge_conn->chosen_exit_optional || edge_conn->chosen_exit_retries) {
3376 tor_assert(conn->type == CONN_TYPE_AP);
3377 tor_assert(edge_conn->chosen_exit_name);
3380 /* XXX unchecked: package window, deliver window. */
3381 if (conn->type == CONN_TYPE_AP) {
3383 tor_assert(edge_conn->socks_request);
3384 if (conn->state == AP_CONN_STATE_OPEN) {
3385 tor_assert(edge_conn->socks_request->has_finished);
3386 if (!conn->marked_for_close) {
3387 tor_assert(edge_conn->cpath_layer);
3388 assert_cpath_layer_ok(edge_conn->cpath_layer);
3392 if (conn->type == CONN_TYPE_EXIT) {
3393 tor_assert(conn->purpose == EXIT_PURPOSE_CONNECT ||
3394 conn->purpose == EXIT_PURPOSE_RESOLVE);
3396 } else if (conn->type == CONN_TYPE_DIR) {
3397 } else {
3398 /* Purpose is only used for dir and exit types currently */
3399 tor_assert(!conn->purpose);
3402 switch (conn->type)
3404 case CONN_TYPE_OR_LISTENER:
3405 case CONN_TYPE_AP_LISTENER:
3406 case CONN_TYPE_AP_TRANS_LISTENER:
3407 case CONN_TYPE_AP_NATD_LISTENER:
3408 case CONN_TYPE_DIR_LISTENER:
3409 case CONN_TYPE_CONTROL_LISTENER:
3410 case CONN_TYPE_AP_DNS_LISTENER:
3411 tor_assert(conn->state == LISTENER_STATE_READY);
3412 break;
3413 case CONN_TYPE_OR:
3414 tor_assert(conn->state >= _OR_CONN_STATE_MIN);
3415 tor_assert(conn->state <= _OR_CONN_STATE_MAX);
3416 tor_assert(TO_OR_CONN(conn)->n_circuits >= 0);
3417 break;
3418 case CONN_TYPE_EXIT:
3419 tor_assert(conn->state >= _EXIT_CONN_STATE_MIN);
3420 tor_assert(conn->state <= _EXIT_CONN_STATE_MAX);
3421 tor_assert(conn->purpose >= _EXIT_PURPOSE_MIN);
3422 tor_assert(conn->purpose <= _EXIT_PURPOSE_MAX);
3423 break;
3424 case CONN_TYPE_AP:
3425 tor_assert(conn->state >= _AP_CONN_STATE_MIN);
3426 tor_assert(conn->state <= _AP_CONN_STATE_MAX);
3427 tor_assert(TO_EDGE_CONN(conn)->socks_request);
3428 break;
3429 case CONN_TYPE_DIR:
3430 tor_assert(conn->state >= _DIR_CONN_STATE_MIN);
3431 tor_assert(conn->state <= _DIR_CONN_STATE_MAX);
3432 tor_assert(conn->purpose >= _DIR_PURPOSE_MIN);
3433 tor_assert(conn->purpose <= _DIR_PURPOSE_MAX);
3434 break;
3435 case CONN_TYPE_CPUWORKER:
3436 tor_assert(conn->state >= _CPUWORKER_STATE_MIN);
3437 tor_assert(conn->state <= _CPUWORKER_STATE_MAX);
3438 break;
3439 case CONN_TYPE_CONTROL:
3440 tor_assert(conn->state >= _CONTROL_CONN_STATE_MIN);
3441 tor_assert(conn->state <= _CONTROL_CONN_STATE_MAX);
3442 break;
3443 default:
3444 tor_assert(0);