Maintain separate server and client identity keys when appropriate.
[tor.git] / src / or / connection.c
blob2897fe10a12db2d0f05995f22fecaba0a0628b22
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-2011, 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 /** The last IPv4 address that our network interface seemed to have been
36 * binding to, in host order. We use this to detect when our IP changes. */
37 static uint32_t last_interface_ip = 0;
38 /** A list of uint32_ts for addresses we've used in outgoing connections.
39 * Used to detect IP address changes. */
40 static smartlist_t *outgoing_addrs = NULL;
42 /**************************************************************/
44 /**
45 * Return the human-readable name for the connection type <b>type</b>
47 const char *
48 conn_type_to_string(int type)
50 static char buf[64];
51 switch (type) {
52 case CONN_TYPE_OR_LISTENER: return "OR listener";
53 case CONN_TYPE_OR: return "OR";
54 case CONN_TYPE_EXIT: return "Exit";
55 case CONN_TYPE_AP_LISTENER: return "Socks listener";
56 case CONN_TYPE_AP_TRANS_LISTENER:
57 return "Transparent pf/netfilter listener";
58 case CONN_TYPE_AP_NATD_LISTENER: return "Transparent natd listener";
59 case CONN_TYPE_AP_DNS_LISTENER: return "DNS listener";
60 case CONN_TYPE_AP: return "Socks";
61 case CONN_TYPE_DIR_LISTENER: return "Directory listener";
62 case CONN_TYPE_DIR: return "Directory";
63 case CONN_TYPE_CPUWORKER: return "CPU worker";
64 case CONN_TYPE_CONTROL_LISTENER: return "Control listener";
65 case CONN_TYPE_CONTROL: return "Control";
66 default:
67 log_warn(LD_BUG, "unknown connection type %d", type);
68 tor_snprintf(buf, sizeof(buf), "unknown [%d]", type);
69 return buf;
73 /**
74 * Return the human-readable name for the connection state <b>state</b>
75 * for the connection type <b>type</b>
77 const char *
78 conn_state_to_string(int type, int state)
80 static char buf[96];
81 switch (type) {
82 case CONN_TYPE_OR_LISTENER:
83 case CONN_TYPE_AP_LISTENER:
84 case CONN_TYPE_AP_TRANS_LISTENER:
85 case CONN_TYPE_AP_NATD_LISTENER:
86 case CONN_TYPE_AP_DNS_LISTENER:
87 case CONN_TYPE_DIR_LISTENER:
88 case CONN_TYPE_CONTROL_LISTENER:
89 if (state == LISTENER_STATE_READY)
90 return "ready";
91 break;
92 case CONN_TYPE_OR:
93 switch (state) {
94 case OR_CONN_STATE_CONNECTING: return "connect()ing";
95 case OR_CONN_STATE_PROXY_FLUSHING: return "proxy flushing";
96 case OR_CONN_STATE_PROXY_READING: return "proxy reading";
97 case OR_CONN_STATE_TLS_HANDSHAKING: return "handshaking (TLS)";
98 case OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING:
99 return "renegotiating (TLS)";
100 case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING:
101 return "waiting for renegotiation (TLS)";
102 case OR_CONN_STATE_OR_HANDSHAKING: return "handshaking (Tor)";
103 case OR_CONN_STATE_OPEN: return "open";
105 break;
106 case CONN_TYPE_EXIT:
107 switch (state) {
108 case EXIT_CONN_STATE_RESOLVING: return "waiting for dest info";
109 case EXIT_CONN_STATE_CONNECTING: return "connecting";
110 case EXIT_CONN_STATE_OPEN: return "open";
111 case EXIT_CONN_STATE_RESOLVEFAILED: return "resolve failed";
113 break;
114 case CONN_TYPE_AP:
115 switch (state) {
116 case AP_CONN_STATE_SOCKS_WAIT: return "waiting for socks info";
117 case AP_CONN_STATE_NATD_WAIT: return "waiting for natd dest info";
118 case AP_CONN_STATE_RENDDESC_WAIT: return "waiting for rendezvous desc";
119 case AP_CONN_STATE_CONTROLLER_WAIT: return "waiting for controller";
120 case AP_CONN_STATE_CIRCUIT_WAIT: return "waiting for circuit";
121 case AP_CONN_STATE_CONNECT_WAIT: return "waiting for connect response";
122 case AP_CONN_STATE_RESOLVE_WAIT: return "waiting for resolve response";
123 case AP_CONN_STATE_OPEN: return "open";
125 break;
126 case CONN_TYPE_DIR:
127 switch (state) {
128 case DIR_CONN_STATE_CONNECTING: return "connecting";
129 case DIR_CONN_STATE_CLIENT_SENDING: return "client sending";
130 case DIR_CONN_STATE_CLIENT_READING: return "client reading";
131 case DIR_CONN_STATE_CLIENT_FINISHED: return "client finished";
132 case DIR_CONN_STATE_SERVER_COMMAND_WAIT: return "waiting for command";
133 case DIR_CONN_STATE_SERVER_WRITING: return "writing";
135 break;
136 case CONN_TYPE_CPUWORKER:
137 switch (state) {
138 case CPUWORKER_STATE_IDLE: return "idle";
139 case CPUWORKER_STATE_BUSY_ONION: return "busy with onion";
141 break;
142 case CONN_TYPE_CONTROL:
143 switch (state) {
144 case CONTROL_CONN_STATE_OPEN: return "open (protocol v1)";
145 case CONTROL_CONN_STATE_NEEDAUTH:
146 return "waiting for authentication (protocol v1)";
148 break;
151 log_warn(LD_BUG, "unknown connection state %d (type %d)", state, type);
152 tor_snprintf(buf, sizeof(buf),
153 "unknown state [%d] on unknown [%s] connection",
154 state, conn_type_to_string(type));
155 return buf;
158 /** Allocate and return a new dir_connection_t, initialized as by
159 * connection_init(). */
160 dir_connection_t *
161 dir_connection_new(int socket_family)
163 dir_connection_t *dir_conn = tor_malloc_zero(sizeof(dir_connection_t));
164 connection_init(time(NULL), TO_CONN(dir_conn), CONN_TYPE_DIR, socket_family);
165 return dir_conn;
168 /** Allocate and return a new or_connection_t, initialized as by
169 * connection_init(). */
170 or_connection_t *
171 or_connection_new(int socket_family)
173 or_connection_t *or_conn = tor_malloc_zero(sizeof(or_connection_t));
174 time_t now = time(NULL);
175 connection_init(now, TO_CONN(or_conn), CONN_TYPE_OR, socket_family);
177 or_conn->timestamp_last_added_nonpadding = time(NULL);
178 or_conn->next_circ_id = crypto_rand_int(1<<15);
180 return or_conn;
183 /** Allocate and return a new edge_connection_t, initialized as by
184 * connection_init(). */
185 edge_connection_t *
186 edge_connection_new(int type, int socket_family)
188 edge_connection_t *edge_conn = tor_malloc_zero(sizeof(edge_connection_t));
189 tor_assert(type == CONN_TYPE_EXIT || type == CONN_TYPE_AP);
190 connection_init(time(NULL), TO_CONN(edge_conn), type, socket_family);
191 if (type == CONN_TYPE_AP)
192 edge_conn->socks_request = tor_malloc_zero(sizeof(socks_request_t));
193 return edge_conn;
196 /** Allocate and return a new control_connection_t, initialized as by
197 * connection_init(). */
198 control_connection_t *
199 control_connection_new(int socket_family)
201 control_connection_t *control_conn =
202 tor_malloc_zero(sizeof(control_connection_t));
203 connection_init(time(NULL),
204 TO_CONN(control_conn), CONN_TYPE_CONTROL, socket_family);
205 return control_conn;
208 /** Allocate, initialize, and return a new connection_t subtype of <b>type</b>
209 * to make or receive connections of address family <b>socket_family</b>. The
210 * type should be one of the CONN_TYPE_* constants. */
211 connection_t *
212 connection_new(int type, int socket_family)
214 switch (type) {
215 case CONN_TYPE_OR:
216 return TO_CONN(or_connection_new(socket_family));
218 case CONN_TYPE_EXIT:
219 case CONN_TYPE_AP:
220 return TO_CONN(edge_connection_new(type, socket_family));
222 case CONN_TYPE_DIR:
223 return TO_CONN(dir_connection_new(socket_family));
225 case CONN_TYPE_CONTROL:
226 return TO_CONN(control_connection_new(socket_family));
228 default: {
229 connection_t *conn = tor_malloc_zero(sizeof(connection_t));
230 connection_init(time(NULL), conn, type, socket_family);
231 return conn;
236 /** Initializes conn. (you must call connection_add() to link it into the main
237 * array).
239 * Set conn-\>type to <b>type</b>. Set conn-\>s and conn-\>conn_array_index to
240 * -1 to signify they are not yet assigned.
242 * If conn is not a listener type, allocate buffers for it. If it's
243 * an AP type, allocate space to store the socks_request.
245 * Assign a pseudorandom next_circ_id between 0 and 2**15.
247 * Initialize conn's timestamps to now.
249 static void
250 connection_init(time_t now, connection_t *conn, int type, int socket_family)
252 static uint64_t n_connections_allocated = 1;
254 switch (type) {
255 case CONN_TYPE_OR:
256 conn->magic = OR_CONNECTION_MAGIC;
257 break;
258 case CONN_TYPE_EXIT:
259 case CONN_TYPE_AP:
260 conn->magic = EDGE_CONNECTION_MAGIC;
261 break;
262 case CONN_TYPE_DIR:
263 conn->magic = DIR_CONNECTION_MAGIC;
264 break;
265 case CONN_TYPE_CONTROL:
266 conn->magic = CONTROL_CONNECTION_MAGIC;
267 break;
268 default:
269 conn->magic = BASE_CONNECTION_MAGIC;
270 break;
273 conn->s = -1; /* give it a default of 'not used' */
274 conn->conn_array_index = -1; /* also default to 'not used' */
275 conn->global_identifier = n_connections_allocated++;
277 conn->type = type;
278 conn->socket_family = socket_family;
279 if (!connection_is_listener(conn)) { /* listeners never use their buf */
280 conn->inbuf = buf_new();
281 conn->outbuf = buf_new();
284 conn->timestamp_created = now;
285 conn->timestamp_lastread = now;
286 conn->timestamp_lastwritten = now;
289 /** Create a link between <b>conn_a</b> and <b>conn_b</b>. */
290 void
291 connection_link_connections(connection_t *conn_a, connection_t *conn_b)
293 tor_assert(conn_a->s < 0);
294 tor_assert(conn_b->s < 0);
296 conn_a->linked = 1;
297 conn_b->linked = 1;
298 conn_a->linked_conn = conn_b;
299 conn_b->linked_conn = conn_a;
302 /** Tell libevent that we don't care about <b>conn</b> any more. */
303 void
304 connection_unregister_events(connection_t *conn)
306 if (conn->read_event) {
307 if (event_del(conn->read_event))
308 log_warn(LD_BUG, "Error removing read event for %d", conn->s);
309 tor_free(conn->read_event);
311 if (conn->write_event) {
312 if (event_del(conn->write_event))
313 log_warn(LD_BUG, "Error removing write event for %d", conn->s);
314 tor_free(conn->write_event);
316 if (conn->dns_server_port) {
317 dnsserv_close_listener(conn);
321 /** Deallocate memory used by <b>conn</b>. Deallocate its buffers if
322 * necessary, close its socket if necessary, and mark the directory as dirty
323 * if <b>conn</b> is an OR or OP connection.
325 static void
326 _connection_free(connection_t *conn)
328 void *mem;
329 size_t memlen;
330 switch (conn->type) {
331 case CONN_TYPE_OR:
332 tor_assert(conn->magic == OR_CONNECTION_MAGIC);
333 mem = TO_OR_CONN(conn);
334 memlen = sizeof(or_connection_t);
335 break;
336 case CONN_TYPE_AP:
337 case CONN_TYPE_EXIT:
338 tor_assert(conn->magic == EDGE_CONNECTION_MAGIC);
339 mem = TO_EDGE_CONN(conn);
340 memlen = sizeof(edge_connection_t);
341 break;
342 case CONN_TYPE_DIR:
343 tor_assert(conn->magic == DIR_CONNECTION_MAGIC);
344 mem = TO_DIR_CONN(conn);
345 memlen = sizeof(dir_connection_t);
346 break;
347 case CONN_TYPE_CONTROL:
348 tor_assert(conn->magic == CONTROL_CONNECTION_MAGIC);
349 mem = TO_CONTROL_CONN(conn);
350 memlen = sizeof(control_connection_t);
351 break;
352 default:
353 tor_assert(conn->magic == BASE_CONNECTION_MAGIC);
354 mem = conn;
355 memlen = sizeof(connection_t);
356 break;
359 if (conn->linked) {
360 log_info(LD_GENERAL, "Freeing linked %s connection [%s] with %d "
361 "bytes on inbuf, %d on outbuf.",
362 conn_type_to_string(conn->type),
363 conn_state_to_string(conn->type, conn->state),
364 (int)buf_datalen(conn->inbuf), (int)buf_datalen(conn->outbuf));
367 if (!connection_is_listener(conn)) {
368 buf_free(conn->inbuf);
369 buf_free(conn->outbuf);
370 } else {
371 if (conn->socket_family == AF_UNIX) {
372 /* For now only control ports can be Unix domain sockets
373 * and listeners at the same time */
374 tor_assert(conn->type == CONN_TYPE_CONTROL_LISTENER);
376 if (unlink(conn->address) < 0 && errno != ENOENT) {
377 log_warn(LD_NET, "Could not unlink %s: %s", conn->address,
378 strerror(errno));
383 tor_free(conn->address);
385 if (connection_speaks_cells(conn)) {
386 or_connection_t *or_conn = TO_OR_CONN(conn);
387 if (or_conn->tls) {
388 tor_tls_free(or_conn->tls);
389 or_conn->tls = NULL;
391 if (or_conn->handshake_state) {
392 or_handshake_state_free(or_conn->handshake_state);
393 or_conn->handshake_state = NULL;
395 tor_free(or_conn->nickname);
397 if (CONN_IS_EDGE(conn)) {
398 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
399 tor_free(edge_conn->chosen_exit_name);
400 if (edge_conn->socks_request) {
401 memset(edge_conn->socks_request, 0xcc, sizeof(socks_request_t));
402 tor_free(edge_conn->socks_request);
404 if (edge_conn->rend_data)
405 rend_data_free(edge_conn->rend_data);
407 if (conn->type == CONN_TYPE_CONTROL) {
408 control_connection_t *control_conn = TO_CONTROL_CONN(conn);
409 tor_free(control_conn->incoming_cmd);
412 tor_free(conn->read_event); /* Probably already freed by connection_free. */
413 tor_free(conn->write_event); /* Probably already freed by connection_free. */
415 if (conn->type == CONN_TYPE_DIR) {
416 dir_connection_t *dir_conn = TO_DIR_CONN(conn);
417 tor_free(dir_conn->requested_resource);
418 if (dir_conn->zlib_state)
419 tor_zlib_free(dir_conn->zlib_state);
420 if (dir_conn->fingerprint_stack) {
421 SMARTLIST_FOREACH(dir_conn->fingerprint_stack, char *, cp, tor_free(cp));
422 smartlist_free(dir_conn->fingerprint_stack);
424 if (dir_conn->cached_dir)
425 cached_dir_decref(dir_conn->cached_dir);
426 if (dir_conn->rend_data)
427 rend_data_free(dir_conn->rend_data);
430 if (conn->s >= 0) {
431 log_debug(LD_NET,"closing fd %d.",conn->s);
432 tor_close_socket(conn->s);
433 conn->s = -1;
436 if (conn->type == CONN_TYPE_OR &&
437 !tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest)) {
438 log_warn(LD_BUG, "called on OR conn with non-zeroed identity_digest");
439 connection_or_remove_from_identity_map(TO_OR_CONN(conn));
442 memset(conn, 0xAA, memlen); /* poison memory */
443 tor_free(mem);
446 /** Make sure <b>conn</b> isn't in any of the global conn lists; then free it.
448 void
449 connection_free(connection_t *conn)
451 tor_assert(conn);
452 tor_assert(!connection_is_on_closeable_list(conn));
453 tor_assert(!connection_in_array(conn));
454 if (conn->linked_conn) {
455 log_err(LD_BUG, "Called with conn->linked_conn still set.");
456 tor_fragile_assert();
457 conn->linked_conn->linked_conn = NULL;
458 if (! conn->linked_conn->marked_for_close &&
459 conn->linked_conn->reading_from_linked_conn)
460 connection_start_reading(conn->linked_conn);
461 conn->linked_conn = NULL;
463 if (connection_speaks_cells(conn)) {
464 if (!tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest)) {
465 connection_or_remove_from_identity_map(TO_OR_CONN(conn));
468 if (conn->type == CONN_TYPE_CONTROL) {
469 TO_CONTROL_CONN(conn)->event_mask = 0;
470 control_update_global_event_mask();
472 connection_unregister_events(conn);
473 _connection_free(conn);
476 /** Call _connection_free() on every connection in our array, and release all
477 * storage held by connection.c. This is used by cpuworkers and dnsworkers
478 * when they fork, so they don't keep resources held open (especially
479 * sockets).
481 * Don't do the checks in connection_free(), because they will
482 * fail.
484 void
485 connection_free_all(void)
487 smartlist_t *conns = get_connection_array();
489 /* We don't want to log any messages to controllers. */
490 SMARTLIST_FOREACH(conns, connection_t *, conn,
491 if (conn->type == CONN_TYPE_CONTROL)
492 TO_CONTROL_CONN(conn)->event_mask = 0);
494 control_update_global_event_mask();
496 /* Unlink everything from the identity map. */
497 connection_or_clear_identity_map();
499 SMARTLIST_FOREACH(conns, connection_t *, conn, _connection_free(conn));
501 if (outgoing_addrs) {
502 SMARTLIST_FOREACH(outgoing_addrs, void*, addr, tor_free(addr));
503 smartlist_free(outgoing_addrs);
504 outgoing_addrs = NULL;
508 /** Do any cleanup needed:
509 * - Directory conns that failed to fetch a rendezvous descriptor
510 * need to inform pending rendezvous streams.
511 * - OR conns need to call rep_hist_note_*() to record status.
512 * - AP conns need to send a socks reject if necessary.
513 * - Exit conns need to call connection_dns_remove() if necessary.
514 * - AP and Exit conns need to send an end cell if they can.
515 * - DNS conns need to fail any resolves that are pending on them.
516 * - OR and edge connections need to be unlinked from circuits.
518 void
519 connection_about_to_close_connection(connection_t *conn)
521 circuit_t *circ;
522 dir_connection_t *dir_conn;
523 or_connection_t *or_conn;
524 edge_connection_t *edge_conn;
525 time_t now = time(NULL);
527 tor_assert(conn->marked_for_close);
529 if (CONN_IS_EDGE(conn)) {
530 edge_conn = TO_EDGE_CONN(conn);
531 if (!edge_conn->edge_has_sent_end) {
532 log_warn(LD_BUG, "(Harmless.) Edge connection (marked at %s:%d) "
533 "hasn't sent end yet?",
534 conn->marked_for_close_file, conn->marked_for_close);
535 tor_fragile_assert();
539 switch (conn->type) {
540 case CONN_TYPE_DIR:
541 dir_conn = TO_DIR_CONN(conn);
542 if (conn->state < DIR_CONN_STATE_CLIENT_FINISHED) {
543 /* It's a directory connection and connecting or fetching
544 * failed: forget about this router, and maybe try again. */
545 connection_dir_request_failed(dir_conn);
547 if (conn->purpose == DIR_PURPOSE_FETCH_RENDDESC && dir_conn->rend_data) {
548 /* Give it a try. However, there is no re-fetching for v0 rend
549 * descriptors; if the response is empty or the descriptor is
550 * unusable, close pending connections (unless a v2 request is
551 * still in progress). */
552 rend_client_desc_trynow(dir_conn->rend_data->onion_address, 0);
554 /* If we were trying to fetch a v2 rend desc and did not succeed,
555 * retry as needed. (If a fetch is successful, the connection state
556 * is changed to DIR_PURPOSE_HAS_FETCHED_RENDDESC to mark that
557 * refetching is unnecessary.) */
558 if (conn->purpose == DIR_PURPOSE_FETCH_RENDDESC_V2 &&
559 dir_conn->rend_data &&
560 strlen(dir_conn->rend_data->onion_address) ==
561 REND_SERVICE_ID_LEN_BASE32)
562 rend_client_refetch_v2_renddesc(dir_conn->rend_data);
563 break;
564 case CONN_TYPE_OR:
565 or_conn = TO_OR_CONN(conn);
566 /* Remember why we're closing this connection. */
567 if (conn->state != OR_CONN_STATE_OPEN) {
568 /* Inform any pending (not attached) circs that they should
569 * give up. */
570 circuit_n_conn_done(TO_OR_CONN(conn), 0);
571 /* now mark things down as needed */
572 if (connection_or_nonopen_was_started_here(or_conn)) {
573 or_options_t *options = get_options();
574 rep_hist_note_connect_failed(or_conn->identity_digest, now);
575 entry_guard_register_connect_status(or_conn->identity_digest,0,
576 !options->HttpsProxy, now);
577 if (conn->state >= OR_CONN_STATE_TLS_HANDSHAKING) {
578 int reason = tls_error_to_orconn_end_reason(or_conn->tls_error);
579 control_event_or_conn_status(or_conn, OR_CONN_EVENT_FAILED,
580 reason);
581 if (!authdir_mode_tests_reachability(options))
582 control_event_bootstrap_problem(
583 orconn_end_reason_to_control_string(reason), reason);
586 } else if (conn->hold_open_until_flushed) {
587 /* We only set hold_open_until_flushed when we're intentionally
588 * closing a connection. */
589 rep_hist_note_disconnect(or_conn->identity_digest, now);
590 control_event_or_conn_status(or_conn, OR_CONN_EVENT_CLOSED,
591 tls_error_to_orconn_end_reason(or_conn->tls_error));
592 } else if (or_conn->identity_digest) {
593 rep_hist_note_connection_died(or_conn->identity_digest, now);
594 control_event_or_conn_status(or_conn, OR_CONN_EVENT_CLOSED,
595 tls_error_to_orconn_end_reason(or_conn->tls_error));
597 /* Now close all the attached circuits on it. */
598 circuit_unlink_all_from_or_conn(TO_OR_CONN(conn),
599 END_CIRC_REASON_OR_CONN_CLOSED);
600 break;
601 case CONN_TYPE_AP:
602 edge_conn = TO_EDGE_CONN(conn);
603 if (edge_conn->socks_request->has_finished == 0) {
604 /* since conn gets removed right after this function finishes,
605 * there's no point trying to send back a reply at this point. */
606 log_warn(LD_BUG,"Closing stream (marked at %s:%d) without sending"
607 " back a socks reply.",
608 conn->marked_for_close_file, conn->marked_for_close);
610 if (!edge_conn->end_reason) {
611 log_warn(LD_BUG,"Closing stream (marked at %s:%d) without having"
612 " set end_reason.",
613 conn->marked_for_close_file, conn->marked_for_close);
615 if (edge_conn->dns_server_request) {
616 log_warn(LD_BUG,"Closing stream (marked at %s:%d) without having"
617 " replied to DNS request.",
618 conn->marked_for_close_file, conn->marked_for_close);
619 dnsserv_reject_request(edge_conn);
621 control_event_stream_bandwidth(edge_conn);
622 control_event_stream_status(edge_conn, STREAM_EVENT_CLOSED,
623 edge_conn->end_reason);
624 circ = circuit_get_by_edge_conn(edge_conn);
625 if (circ)
626 circuit_detach_stream(circ, edge_conn);
627 break;
628 case CONN_TYPE_EXIT:
629 edge_conn = TO_EDGE_CONN(conn);
630 circ = circuit_get_by_edge_conn(edge_conn);
631 if (circ)
632 circuit_detach_stream(circ, edge_conn);
633 if (conn->state == EXIT_CONN_STATE_RESOLVING) {
634 connection_dns_remove(edge_conn);
636 break;
640 /** Return true iff connection_close_immediate() has been called on this
641 * connection. */
642 #define CONN_IS_CLOSED(c) \
643 ((c)->linked ? ((c)->linked_conn_is_closed) : ((c)->s < 0))
645 /** Close the underlying socket for <b>conn</b>, so we don't try to
646 * flush it. Must be used in conjunction with (right before)
647 * connection_mark_for_close().
649 void
650 connection_close_immediate(connection_t *conn)
652 assert_connection_ok(conn,0);
653 if (CONN_IS_CLOSED(conn)) {
654 log_err(LD_BUG,"Attempt to close already-closed connection.");
655 tor_fragile_assert();
656 return;
658 if (conn->outbuf_flushlen) {
659 log_info(LD_NET,"fd %d, type %s, state %s, %d bytes on outbuf.",
660 conn->s, conn_type_to_string(conn->type),
661 conn_state_to_string(conn->type, conn->state),
662 (int)conn->outbuf_flushlen);
665 connection_unregister_events(conn);
667 if (conn->s >= 0)
668 tor_close_socket(conn->s);
669 conn->s = -1;
670 if (conn->linked)
671 conn->linked_conn_is_closed = 1;
672 if (!connection_is_listener(conn)) {
673 buf_clear(conn->outbuf);
674 conn->outbuf_flushlen = 0;
678 /** Mark <b>conn</b> to be closed next time we loop through
679 * conn_close_if_marked() in main.c. */
680 void
681 _connection_mark_for_close(connection_t *conn, int line, const char *file)
683 assert_connection_ok(conn,0);
684 tor_assert(line);
685 tor_assert(line < 1<<16); /* marked_for_close can only fit a uint16_t. */
686 tor_assert(file);
688 if (conn->marked_for_close) {
689 log(LOG_WARN,LD_BUG,"Duplicate call to connection_mark_for_close at %s:%d"
690 " (first at %s:%d)", file, line, conn->marked_for_close_file,
691 conn->marked_for_close);
692 tor_fragile_assert();
693 return;
696 conn->marked_for_close = line;
697 conn->marked_for_close_file = file;
698 add_connection_to_closeable_list(conn);
700 /* in case we're going to be held-open-til-flushed, reset
701 * the number of seconds since last successful write, so
702 * we get our whole 15 seconds */
703 conn->timestamp_lastwritten = time(NULL);
706 /** Find each connection that has hold_open_until_flushed set to
707 * 1 but hasn't written in the past 15 seconds, and set
708 * hold_open_until_flushed to 0. This means it will get cleaned
709 * up in the next loop through close_if_marked() in main.c.
711 void
712 connection_expire_held_open(void)
714 time_t now;
715 smartlist_t *conns = get_connection_array();
717 now = time(NULL);
719 SMARTLIST_FOREACH(conns, connection_t *, conn,
721 /* If we've been holding the connection open, but we haven't written
722 * for 15 seconds...
724 if (conn->hold_open_until_flushed) {
725 tor_assert(conn->marked_for_close);
726 if (now - conn->timestamp_lastwritten >= 15) {
727 int severity;
728 if (conn->type == CONN_TYPE_EXIT ||
729 (conn->type == CONN_TYPE_DIR &&
730 conn->purpose == DIR_PURPOSE_SERVER))
731 severity = LOG_INFO;
732 else
733 severity = LOG_NOTICE;
734 log_fn(severity, LD_NET,
735 "Giving up on marked_for_close conn that's been flushing "
736 "for 15s (fd %d, type %s, state %s).",
737 conn->s, conn_type_to_string(conn->type),
738 conn_state_to_string(conn->type, conn->state));
739 conn->hold_open_until_flushed = 0;
745 /** Create an AF_INET listenaddr struct.
746 * <b>listenaddress</b> provides the host and optionally the port information
747 * for the new structure. If no port is provided in <b>listenaddress</b> then
748 * <b>listenport</b> is used.
750 * If not NULL <b>readable_address</b> will contain a copy of the host part of
751 * <b>listenaddress</b>.
753 * The listenaddr struct has to be freed by the caller.
755 static struct sockaddr_in *
756 create_inet_sockaddr(const char *listenaddress, uint16_t listenport,
757 char **readable_address, socklen_t *socklen_out) {
758 struct sockaddr_in *listenaddr = NULL;
759 uint32_t addr;
760 uint16_t usePort = 0;
762 if (parse_addr_port(LOG_WARN,
763 listenaddress, readable_address, &addr, &usePort)<0) {
764 log_warn(LD_CONFIG,
765 "Error parsing/resolving ListenAddress %s", listenaddress);
766 goto err;
768 if (usePort==0)
769 usePort = listenport;
771 listenaddr = tor_malloc_zero(sizeof(struct sockaddr_in));
772 listenaddr->sin_addr.s_addr = htonl(addr);
773 listenaddr->sin_family = AF_INET;
774 listenaddr->sin_port = htons((uint16_t) usePort);
776 *socklen_out = sizeof(struct sockaddr_in);
778 return listenaddr;
780 err:
781 tor_free(listenaddr);
782 return NULL;
785 #ifdef HAVE_SYS_UN_H
786 /** Create an AF_UNIX listenaddr struct.
787 * <b>listenaddress</b> provides the path to the Unix socket.
789 * Eventually <b>listenaddress</b> will also optionally contain user, group,
790 * and file permissions for the new socket. But not yet. XXX
791 * Also, since we do not create the socket here the information doesn't help
792 * here.
794 * If not NULL <b>readable_address</b> will contain a copy of the path part of
795 * <b>listenaddress</b>.
797 * The listenaddr struct has to be freed by the caller.
799 static struct sockaddr_un *
800 create_unix_sockaddr(const char *listenaddress, char **readable_address,
801 socklen_t *len_out)
803 struct sockaddr_un *sockaddr = NULL;
805 sockaddr = tor_malloc_zero(sizeof(struct sockaddr_un));
806 sockaddr->sun_family = AF_UNIX;
807 if (strlcpy(sockaddr->sun_path, listenaddress, sizeof(sockaddr->sun_path))
808 >= sizeof(sockaddr->sun_path)) {
809 log_warn(LD_CONFIG, "Unix socket path '%s' is too long to fit.",
810 escaped(listenaddress));
811 tor_free(sockaddr);
812 return NULL;
815 if (readable_address)
816 *readable_address = tor_strdup(listenaddress);
818 *len_out = sizeof(struct sockaddr_un);
819 return sockaddr;
821 #else
822 static struct sockaddr *
823 create_unix_sockaddr(const char *listenaddress, char **readable_address,
824 socklen_t *len_out)
826 (void)listenaddress;
827 (void)readable_address;
828 log_fn(LOG_ERR, LD_BUG,
829 "Unix domain sockets not supported, yet we tried to create one.");
830 *len_out = 0;
831 tor_assert(0);
833 #endif /* HAVE_SYS_UN_H */
835 /** Warn that an accept or a connect has failed because we're running up
836 * against our ulimit. Rate-limit these warnings so that we don't spam
837 * the log. */
838 static void
839 warn_too_many_conns(void)
841 #define WARN_TOO_MANY_CONNS_INTERVAL (6*60*60)
842 static time_t last_warned = 0;
843 time_t now = time(NULL);
844 int n_conns = get_n_open_sockets();
845 if (last_warned + WARN_TOO_MANY_CONNS_INTERVAL < now) {
846 log_warn(LD_NET,"Failing because we have %d connections already. Please "
847 "raise your ulimit -n.", n_conns);
848 last_warned = now;
850 control_event_general_status(LOG_WARN, "TOO_MANY_CONNECTIONS CURRENT=%d",
851 n_conns);
854 /** Bind a new non-blocking socket listening to the socket described
855 * by <b>listensockaddr</b>.
857 * <b>address</b> is only used for logging purposes and to add the information
858 * to the conn.
860 static connection_t *
861 connection_create_listener(struct sockaddr *listensockaddr, socklen_t socklen,
862 int type, char* address)
864 connection_t *conn;
865 int s; /* the socket we're going to make */
866 uint16_t usePort = 0;
867 int start_reading = 0;
869 if (get_n_open_sockets() >= get_options()->_ConnLimit-1) {
870 warn_too_many_conns();
871 return NULL;
874 if (listensockaddr->sa_family == AF_INET) {
875 int is_tcp = (type != CONN_TYPE_AP_DNS_LISTENER);
876 #ifndef MS_WINDOWS
877 int one=1;
878 #endif
879 if (is_tcp)
880 start_reading = 1;
882 usePort = ntohs( (uint16_t)
883 ((struct sockaddr_in *)listensockaddr)->sin_port);
885 log_notice(LD_NET, "Opening %s on %s:%d",
886 conn_type_to_string(type), address, usePort);
888 s = tor_open_socket(PF_INET,
889 is_tcp ? SOCK_STREAM : SOCK_DGRAM,
890 is_tcp ? IPPROTO_TCP: IPPROTO_UDP);
891 if (s < 0) {
892 log_warn(LD_NET,"Socket creation failed.");
893 goto err;
896 #ifndef MS_WINDOWS
897 /* REUSEADDR on normal places means you can rebind to the port
898 * right after somebody else has let it go. But REUSEADDR on win32
899 * means you can bind to the port _even when somebody else
900 * already has it bound_. So, don't do that on Win32. */
901 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*) &one,
902 (socklen_t)sizeof(one));
903 #endif
905 if (bind(s,listensockaddr,socklen) < 0) {
906 const char *helpfulhint = "";
907 int e = tor_socket_errno(s);
908 if (ERRNO_IS_EADDRINUSE(e))
909 helpfulhint = ". Is Tor already running?";
910 log_warn(LD_NET, "Could not bind to %s:%u: %s%s", address, usePort,
911 tor_socket_strerror(e), helpfulhint);
912 tor_close_socket(s);
913 goto err;
916 if (is_tcp) {
917 if (listen(s,SOMAXCONN) < 0) {
918 log_warn(LD_NET, "Could not listen on %s:%u: %s", address, usePort,
919 tor_socket_strerror(tor_socket_errno(s)));
920 tor_close_socket(s);
921 goto err;
924 #ifdef HAVE_SYS_UN_H
925 } else if (listensockaddr->sa_family == AF_UNIX) {
926 start_reading = 1;
928 /* For now only control ports can be Unix domain sockets
929 * and listeners at the same time */
930 tor_assert(type == CONN_TYPE_CONTROL_LISTENER);
932 log_notice(LD_NET, "Opening %s on %s",
933 conn_type_to_string(type), address);
935 if (unlink(address) < 0 && errno != ENOENT) {
936 log_warn(LD_NET, "Could not unlink %s: %s", address,
937 strerror(errno));
938 goto err;
940 s = tor_open_socket(AF_UNIX, SOCK_STREAM, 0);
941 if (s < 0) {
942 log_warn(LD_NET,"Socket creation failed: %s.", strerror(errno));
943 goto err;
946 if (bind(s, listensockaddr, (socklen_t)sizeof(struct sockaddr_un)) == -1) {
947 log_warn(LD_NET,"Bind to %s failed: %s.", address,
948 tor_socket_strerror(tor_socket_errno(s)));
949 goto err;
952 if (listen(s,SOMAXCONN) < 0) {
953 log_warn(LD_NET, "Could not listen on %s: %s", address,
954 tor_socket_strerror(tor_socket_errno(s)));
955 tor_close_socket(s);
956 goto err;
958 #endif /* HAVE_SYS_UN_H */
959 } else {
960 log_err(LD_BUG,"Got unexpected address family %d.",
961 listensockaddr->sa_family);
962 tor_assert(0);
965 set_socket_nonblocking(s);
967 conn = connection_new(type, listensockaddr->sa_family);
968 conn->socket_family = listensockaddr->sa_family;
969 conn->s = s;
970 conn->address = tor_strdup(address);
971 conn->port = usePort;
973 if (connection_add(conn) < 0) { /* no space, forget it */
974 log_warn(LD_NET,"connection_add for listener failed. Giving up.");
975 connection_free(conn);
976 goto err;
979 log_debug(LD_NET,"%s listening on port %u.",
980 conn_type_to_string(type), usePort);
982 conn->state = LISTENER_STATE_READY;
983 if (start_reading) {
984 connection_start_reading(conn);
985 } else {
986 tor_assert(type == CONN_TYPE_AP_DNS_LISTENER);
987 dnsserv_configure_listener(conn);
990 return conn;
992 err:
993 return NULL;
996 /** Do basic sanity checking on a newly received socket. Return 0
997 * if it looks ok, else return -1. */
998 static int
999 check_sockaddr(struct sockaddr *sa, int len, int level)
1001 int ok = 1;
1003 if (sa->sa_family == AF_INET) {
1004 struct sockaddr_in *sin=(struct sockaddr_in*)sa;
1005 if (len != sizeof(struct sockaddr_in)) {
1006 log_fn(level, LD_NET, "Length of address not as expected: %d vs %d",
1007 len,(int)sizeof(struct sockaddr_in));
1008 ok = 0;
1010 if (sin->sin_addr.s_addr == 0 || sin->sin_port == 0) {
1011 log_fn(level, LD_NET,
1012 "Address for new connection has address/port equal to zero.");
1013 ok = 0;
1015 } else if (sa->sa_family == AF_INET6) {
1016 struct sockaddr_in6 *sin6=(struct sockaddr_in6*)sa;
1017 if (len != sizeof(struct sockaddr_in6)) {
1018 log_fn(level, LD_NET, "Length of address not as expected: %d vs %d",
1019 len,(int)sizeof(struct sockaddr_in6));
1020 ok = 0;
1022 if (tor_mem_is_zero((void*)sin6->sin6_addr.s6_addr, 16) ||
1023 sin6->sin6_port == 0) {
1024 log_fn(level, LD_NET,
1025 "Address for new connection has address/port equal to zero.");
1026 ok = 0;
1028 } else {
1029 ok = 0;
1031 return ok ? 0 : -1;
1034 /** Check whether the socket family from an accepted socket <b>got</b> is the
1035 * same as the one that <b>listener</b> is waiting for. If it isn't, log
1036 * a useful message and return -1. Else return 0.
1038 * This is annoying, but can apparently happen on some Darwins. */
1039 static int
1040 check_sockaddr_family_match(sa_family_t got, connection_t *listener)
1042 if (got != listener->socket_family) {
1043 log_info(LD_BUG, "A listener connection returned a socket with a "
1044 "mismatched family. %s for addr_family %d gave us a socket "
1045 "with address family %d. Dropping.",
1046 conn_type_to_string(listener->type),
1047 (int)listener->socket_family,
1048 (int)got);
1049 return -1;
1051 return 0;
1054 /** The listener connection <b>conn</b> told poll() it wanted to read.
1055 * Call accept() on conn-\>s, and add the new connection if necessary.
1057 static int
1058 connection_handle_listener_read(connection_t *conn, int new_type)
1060 int news; /* the new socket */
1061 connection_t *newconn;
1062 /* information about the remote peer when connecting to other routers */
1063 char addrbuf[256];
1064 struct sockaddr *remote = (struct sockaddr*)addrbuf;
1065 /* length of the remote address. Must be whatever accept() needs. */
1066 socklen_t remotelen = (socklen_t)sizeof(addrbuf);
1067 or_options_t *options = get_options();
1069 tor_assert((size_t)remotelen >= sizeof(struct sockaddr_in));
1070 memset(addrbuf, 0, sizeof(addrbuf));
1072 news = tor_accept_socket(conn->s,remote,&remotelen);
1073 if (news < 0) { /* accept() error */
1074 int e = tor_socket_errno(conn->s);
1075 if (ERRNO_IS_ACCEPT_EAGAIN(e)) {
1076 return 0; /* he hung up before we could accept(). that's fine. */
1077 } else if (ERRNO_IS_ACCEPT_RESOURCE_LIMIT(e)) {
1078 warn_too_many_conns();
1079 return 0;
1081 /* else there was a real error. */
1082 log_warn(LD_NET,"accept() failed: %s. Closing listener.",
1083 tor_socket_strerror(e));
1084 connection_mark_for_close(conn);
1085 return -1;
1087 log_debug(LD_NET,
1088 "Connection accepted on socket %d (child of fd %d).",
1089 news,conn->s);
1091 set_socket_nonblocking(news);
1093 if (options->ConstrainedSockets)
1094 set_constrained_socket_buffers(news, (int)options->ConstrainedSockSize);
1096 if (check_sockaddr_family_match(remote->sa_family, conn) < 0) {
1097 tor_close_socket(news);
1098 return 0;
1101 if (conn->socket_family == AF_INET || conn->socket_family == AF_INET6) {
1102 tor_addr_t addr;
1103 uint16_t port;
1104 if (check_sockaddr(remote, remotelen, LOG_INFO)<0) {
1105 log_info(LD_NET,
1106 "accept() returned a strange address; trying getsockname().");
1107 remotelen=sizeof(addrbuf);
1108 memset(addrbuf, 0, sizeof(addrbuf));
1109 if (getsockname(news, remote, &remotelen)<0) {
1110 int e = tor_socket_errno(news);
1111 log_warn(LD_NET, "getsockname() for new connection failed: %s",
1112 tor_socket_strerror(e));
1113 } else {
1114 if (check_sockaddr((struct sockaddr*)addrbuf, remotelen,
1115 LOG_WARN) < 0) {
1116 log_warn(LD_NET,"Something's wrong with this conn. Closing it.");
1117 tor_close_socket(news);
1118 return 0;
1123 if (check_sockaddr_family_match(remote->sa_family, conn) < 0) {
1124 tor_close_socket(news);
1125 return 0;
1128 tor_addr_from_sockaddr(&addr, remote, &port);
1130 /* process entrance policies here, before we even create the connection */
1131 if (new_type == CONN_TYPE_AP) {
1132 /* check sockspolicy to see if we should accept it */
1133 if (socks_policy_permits_address(&addr) == 0) {
1134 log_notice(LD_APP,
1135 "Denying socks connection from untrusted address %s.",
1136 fmt_addr(&addr));
1137 tor_close_socket(news);
1138 return 0;
1141 if (new_type == CONN_TYPE_DIR) {
1142 /* check dirpolicy to see if we should accept it */
1143 if (dir_policy_permits_address(&addr) == 0) {
1144 log_notice(LD_DIRSERV,"Denying dir connection from address %s.",
1145 fmt_addr(&addr));
1146 tor_close_socket(news);
1147 return 0;
1151 newconn = connection_new(new_type, conn->socket_family);
1152 newconn->s = news;
1154 /* remember the remote address */
1155 tor_addr_copy(&newconn->addr, &addr);
1156 newconn->port = port;
1157 newconn->address = tor_dup_addr(&addr);
1159 } else if (conn->socket_family == AF_UNIX) {
1160 /* For now only control ports can be Unix domain sockets
1161 * and listeners at the same time */
1162 tor_assert(conn->type == CONN_TYPE_CONTROL_LISTENER);
1164 newconn = connection_new(new_type, conn->socket_family);
1165 newconn->s = news;
1167 /* remember the remote address -- do we have anything sane to put here? */
1168 tor_addr_make_unspec(&newconn->addr);
1169 newconn->port = 1;
1170 newconn->address = tor_strdup(conn->address);
1171 } else {
1172 tor_assert(0);
1175 if (connection_add(newconn) < 0) { /* no space, forget it */
1176 connection_free(newconn);
1177 return 0; /* no need to tear down the parent */
1180 if (connection_init_accepted_conn(newconn, conn->type) < 0) {
1181 connection_mark_for_close(newconn);
1182 return 0;
1184 return 0;
1187 /** Initialize states for newly accepted connection <b>conn</b>.
1188 * If conn is an OR, start the TLS handshake.
1189 * If conn is a transparent AP, get its original destination
1190 * and place it in circuit_wait.
1192 static int
1193 connection_init_accepted_conn(connection_t *conn, uint8_t listener_type)
1195 connection_start_reading(conn);
1197 switch (conn->type) {
1198 case CONN_TYPE_OR:
1199 control_event_or_conn_status(TO_OR_CONN(conn), OR_CONN_EVENT_NEW, 0);
1200 return connection_tls_start_handshake(TO_OR_CONN(conn), 1);
1201 case CONN_TYPE_AP:
1202 switch (listener_type) {
1203 case CONN_TYPE_AP_LISTENER:
1204 conn->state = AP_CONN_STATE_SOCKS_WAIT;
1205 break;
1206 case CONN_TYPE_AP_TRANS_LISTENER:
1207 conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
1208 return connection_ap_process_transparent(TO_EDGE_CONN(conn));
1209 case CONN_TYPE_AP_NATD_LISTENER:
1210 conn->state = AP_CONN_STATE_NATD_WAIT;
1211 break;
1213 break;
1214 case CONN_TYPE_DIR:
1215 conn->purpose = DIR_PURPOSE_SERVER;
1216 conn->state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
1217 break;
1218 case CONN_TYPE_CONTROL:
1219 conn->state = CONTROL_CONN_STATE_NEEDAUTH;
1220 break;
1222 return 0;
1225 /** Take conn, make a nonblocking socket; try to connect to
1226 * addr:port (they arrive in *host order*). If fail, return -1 and if
1227 * applicable put your best guess about errno into *<b>socket_error</b>.
1228 * Else assign s to conn-\>s: if connected return 1, if EAGAIN return 0.
1230 * address is used to make the logs useful.
1232 * On success, add conn to the list of polled connections.
1235 connection_connect(connection_t *conn, const char *address,
1236 const tor_addr_t *addr, uint16_t port, int *socket_error)
1238 int s, inprogress = 0;
1239 char addrbuf[256];
1240 struct sockaddr *dest_addr = (struct sockaddr*) addrbuf;
1241 socklen_t dest_addr_len;
1242 or_options_t *options = get_options();
1243 int protocol_family;
1245 if (get_n_open_sockets() >= get_options()->_ConnLimit-1) {
1246 warn_too_many_conns();
1247 return -1;
1250 if (tor_addr_family(addr) == AF_INET6)
1251 protocol_family = PF_INET6;
1252 else
1253 protocol_family = PF_INET;
1255 s = tor_open_socket(protocol_family,SOCK_STREAM,IPPROTO_TCP);
1256 if (s < 0) {
1257 *socket_error = tor_socket_errno(-1);
1258 log_warn(LD_NET,"Error creating network socket: %s",
1259 tor_socket_strerror(*socket_error));
1260 return -1;
1263 if (options->OutboundBindAddress) {
1264 struct sockaddr_in ext_addr;
1266 memset(&ext_addr, 0, sizeof(ext_addr));
1267 ext_addr.sin_family = AF_INET;
1268 ext_addr.sin_port = 0;
1269 if (!tor_inet_aton(options->OutboundBindAddress, &ext_addr.sin_addr)) {
1270 log_warn(LD_CONFIG,"Outbound bind address '%s' didn't parse. Ignoring.",
1271 options->OutboundBindAddress);
1272 } else {
1273 if (bind(s, (struct sockaddr*)&ext_addr,
1274 (socklen_t)sizeof(ext_addr)) < 0) {
1275 *socket_error = tor_socket_errno(s);
1276 log_warn(LD_NET,"Error binding network socket: %s",
1277 tor_socket_strerror(*socket_error));
1278 tor_close_socket(s);
1279 return -1;
1284 set_socket_nonblocking(s);
1286 if (options->ConstrainedSockets)
1287 set_constrained_socket_buffers(s, (int)options->ConstrainedSockSize);
1289 memset(addrbuf,0,sizeof(addrbuf));
1290 dest_addr = (struct sockaddr*) addrbuf;
1291 dest_addr_len = tor_addr_to_sockaddr(addr, port, dest_addr, sizeof(addrbuf));
1292 tor_assert(dest_addr_len > 0);
1294 log_debug(LD_NET,"Connecting to %s:%u.",escaped_safe_str(address),port);
1296 if (connect(s, dest_addr, dest_addr_len) < 0) {
1297 int e = tor_socket_errno(s);
1298 if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
1299 /* yuck. kill it. */
1300 *socket_error = e;
1301 log_info(LD_NET,
1302 "connect() to %s:%u failed: %s",escaped_safe_str(address),
1303 port, tor_socket_strerror(e));
1304 tor_close_socket(s);
1305 return -1;
1306 } else {
1307 inprogress = 1;
1311 if (!server_mode(options))
1312 client_check_address_changed(s);
1314 /* it succeeded. we're connected. */
1315 log_fn(inprogress?LOG_DEBUG:LOG_INFO, LD_NET,
1316 "Connection to %s:%u %s (sock %d).",escaped_safe_str(address),
1317 port, inprogress?"in progress":"established", s);
1318 conn->s = s;
1319 if (connection_add(conn) < 0) /* no space, forget it */
1320 return -1;
1321 return inprogress ? 0 : 1;
1325 * Launch any configured listener connections of type <b>type</b>. (A
1326 * listener is configured if <b>port_option</b> is non-zero. If any
1327 * ListenAddress configuration options are given in <b>cfg</b>, create a
1328 * connection binding to each one. Otherwise, create a single
1329 * connection binding to the address <b>default_addr</b>.)
1331 * Only launch the listeners of this type that are not already open, and
1332 * only close listeners that are no longer wanted. Existing listeners
1333 * that are still configured are not touched.
1335 * If <b>disable_all_conns</b> is set, then never open new conns, and
1336 * close the existing ones.
1338 * Add all old conns that should be closed to <b>replaced_conns</b>.
1339 * Add all new connections to <b>new_conns</b>.
1341 static int
1342 retry_listeners(int type, config_line_t *cfg,
1343 int port_option, const char *default_addr,
1344 smartlist_t *replaced_conns,
1345 smartlist_t *new_conns,
1346 int disable_all_conns,
1347 int socket_family)
1349 smartlist_t *launch = smartlist_create(), *conns;
1350 int free_launch_elts = 1;
1351 int r;
1352 config_line_t *c;
1353 connection_t *conn;
1354 config_line_t *line;
1356 tor_assert(socket_family == AF_INET || socket_family == AF_UNIX);
1358 if (cfg && port_option) {
1359 for (c = cfg; c; c = c->next) {
1360 smartlist_add(launch, c);
1362 free_launch_elts = 0;
1363 } else if (port_option) {
1364 line = tor_malloc_zero(sizeof(config_line_t));
1365 line->key = tor_strdup("");
1366 line->value = tor_strdup(default_addr);
1367 smartlist_add(launch, line);
1371 SMARTLIST_FOREACH(launch, config_line_t *, l,
1372 log_fn(LOG_NOTICE, "#%s#%s", l->key, l->value));
1375 conns = get_connection_array();
1376 SMARTLIST_FOREACH(conns, connection_t *, conn,
1378 if (conn->type != type ||
1379 conn->socket_family != socket_family ||
1380 conn->marked_for_close)
1381 continue;
1382 /* Okay, so this is a listener. Is it configured? */
1383 line = NULL;
1384 SMARTLIST_FOREACH(launch, config_line_t *, wanted,
1386 char *address=NULL;
1387 uint16_t port;
1388 switch (socket_family) {
1389 case AF_INET:
1390 if (!parse_addr_port(LOG_WARN,
1391 wanted->value, &address, NULL, &port)) {
1392 int addr_matches = !strcasecmp(address, conn->address);
1393 tor_free(address);
1394 if (! port)
1395 port = port_option;
1396 if (port == conn->port && addr_matches) {
1397 line = wanted;
1398 break;
1401 break;
1402 case AF_UNIX:
1403 if (!strcasecmp(wanted->value, conn->address)) {
1404 line = wanted;
1405 break;
1407 break;
1408 default:
1409 tor_assert(0);
1412 if (!line || disable_all_conns) {
1413 /* This one isn't configured. Close it. */
1414 log_notice(LD_NET, "Closing no-longer-configured %s on %s:%d",
1415 conn_type_to_string(type), conn->address, conn->port);
1416 if (replaced_conns) {
1417 smartlist_add(replaced_conns, conn);
1418 } else {
1419 connection_close_immediate(conn);
1420 connection_mark_for_close(conn);
1422 } else {
1423 /* It's configured; we don't need to launch it. */
1424 // log_debug(LD_NET, "Already have %s on %s:%d",
1425 // conn_type_to_string(type), conn->address, conn->port);
1426 smartlist_remove(launch, line);
1427 if (free_launch_elts)
1428 config_free_lines(line);
1432 /* Now open all the listeners that are configured but not opened. */
1433 r = 0;
1434 if (!disable_all_conns) {
1435 SMARTLIST_FOREACH_BEGIN(launch, config_line_t *, cfg_line) {
1436 char *address = NULL;
1437 struct sockaddr *listensockaddr;
1438 socklen_t listensocklen = 0;
1440 switch (socket_family) {
1441 case AF_INET:
1442 listensockaddr = (struct sockaddr *)
1443 create_inet_sockaddr(cfg_line->value,
1444 (uint16_t) port_option,
1445 &address, &listensocklen);
1446 break;
1447 case AF_UNIX:
1448 listensockaddr = (struct sockaddr *)
1449 create_unix_sockaddr(cfg_line->value,
1450 &address, &listensocklen);
1451 break;
1452 default:
1453 tor_assert(0);
1456 if (listensockaddr) {
1457 conn = connection_create_listener(listensockaddr, listensocklen,
1458 type, address);
1459 tor_free(listensockaddr);
1460 tor_free(address);
1461 } else
1462 conn = NULL;
1464 if (!conn) {
1465 r = -1;
1466 } else {
1467 if (new_conns)
1468 smartlist_add(new_conns, conn);
1470 } SMARTLIST_FOREACH_END(cfg_line);
1473 if (free_launch_elts) {
1474 SMARTLIST_FOREACH(launch, config_line_t *, cfg_line,
1475 config_free_lines(cfg_line));
1477 smartlist_free(launch);
1479 return r;
1482 /** Launch listeners for each port you should have open. Only launch
1483 * listeners who are not already open, and only close listeners we no longer
1484 * want.
1486 * Add all old conns that should be closed to <b>replaced_conns</b>.
1487 * Add all new connections to <b>new_conns</b>.
1490 retry_all_listeners(smartlist_t *replaced_conns,
1491 smartlist_t *new_conns)
1493 or_options_t *options = get_options();
1495 if (retry_listeners(CONN_TYPE_OR_LISTENER, options->ORListenAddress,
1496 options->ORPort, "0.0.0.0",
1497 replaced_conns, new_conns, options->ClientOnly,
1498 AF_INET)<0)
1499 return -1;
1500 if (retry_listeners(CONN_TYPE_DIR_LISTENER, options->DirListenAddress,
1501 options->DirPort, "0.0.0.0",
1502 replaced_conns, new_conns, options->ClientOnly,
1503 AF_INET)<0)
1504 return -1;
1505 if (retry_listeners(CONN_TYPE_AP_LISTENER, options->SocksListenAddress,
1506 options->SocksPort, "127.0.0.1",
1507 replaced_conns, new_conns, 0,
1508 AF_INET)<0)
1509 return -1;
1510 if (retry_listeners(CONN_TYPE_AP_TRANS_LISTENER, options->TransListenAddress,
1511 options->TransPort, "127.0.0.1",
1512 replaced_conns, new_conns, 0,
1513 AF_INET)<0)
1514 return -1;
1515 if (retry_listeners(CONN_TYPE_AP_NATD_LISTENER, options->NatdListenAddress,
1516 options->NatdPort, "127.0.0.1",
1517 replaced_conns, new_conns, 0,
1518 AF_INET)<0)
1519 return -1;
1520 if (retry_listeners(CONN_TYPE_AP_DNS_LISTENER, options->DNSListenAddress,
1521 options->DNSPort, "127.0.0.1",
1522 replaced_conns, new_conns, 0,
1523 AF_INET)<0)
1524 return -1;
1525 if (retry_listeners(CONN_TYPE_CONTROL_LISTENER,
1526 options->ControlListenAddress,
1527 options->ControlPort, "127.0.0.1",
1528 replaced_conns, new_conns, 0,
1529 AF_INET)<0)
1530 return -1;
1531 if (retry_listeners(CONN_TYPE_CONTROL_LISTENER,
1532 options->ControlSocket,
1533 options->ControlSocket ? 1 : 0, NULL,
1534 replaced_conns, new_conns, 0,
1535 AF_UNIX)<0)
1536 return -1;
1538 return 0;
1541 /** Return 1 if we should apply rate limiting to <b>conn</b>,
1542 * and 0 otherwise. Right now this just checks if it's an internal
1543 * IP address or an internal connection. */
1544 static int
1545 connection_is_rate_limited(connection_t *conn)
1547 if (conn->linked || /* internal connection */
1548 tor_addr_family(&conn->addr) == AF_UNSPEC || /* no address */
1549 tor_addr_is_internal(&conn->addr, 0)) /* internal address */
1550 return 0;
1551 else
1552 return 1;
1555 extern int global_read_bucket, global_write_bucket;
1556 extern int global_relayed_read_bucket, global_relayed_write_bucket;
1558 /** Did either global write bucket run dry last second? If so,
1559 * we are likely to run dry again this second, so be stingy with the
1560 * tokens we just put in. */
1561 static int write_buckets_empty_last_second = 0;
1563 /** How many seconds of no active local circuits will make the
1564 * connection revert to the "relayed" bandwidth class? */
1565 #define CLIENT_IDLE_TIME_FOR_PRIORITY 30
1567 /** Return 1 if <b>conn</b> should use tokens from the "relayed"
1568 * bandwidth rates, else 0. Currently, only OR conns with bandwidth
1569 * class 1, and directory conns that are serving data out, count.
1571 static int
1572 connection_counts_as_relayed_traffic(connection_t *conn, time_t now)
1574 if (conn->type == CONN_TYPE_OR &&
1575 TO_OR_CONN(conn)->client_used + CLIENT_IDLE_TIME_FOR_PRIORITY < now)
1576 return 1;
1577 if (conn->type == CONN_TYPE_DIR && DIR_CONN_IS_SERVER(conn))
1578 return 1;
1579 return 0;
1582 /** Helper function to decide how many bytes out of <b>global_bucket</b>
1583 * we're willing to use for this transaction. <b>base</b> is the size
1584 * of a cell on the network; <b>priority</b> says whether we should
1585 * write many of them or just a few; and <b>conn_bucket</b> (if
1586 * non-negative) provides an upper limit for our answer. */
1587 static ssize_t
1588 connection_bucket_round_robin(int base, int priority,
1589 ssize_t global_bucket, ssize_t conn_bucket)
1591 ssize_t at_most;
1592 ssize_t num_bytes_high = (priority ? 32 : 16) * base;
1593 ssize_t num_bytes_low = (priority ? 4 : 2) * base;
1595 /* Do a rudimentary round-robin so one circuit can't hog a connection.
1596 * Pick at most 32 cells, at least 4 cells if possible, and if we're in
1597 * the middle pick 1/8 of the available bandwidth. */
1598 at_most = global_bucket / 8;
1599 at_most -= (at_most % base); /* round down */
1600 if (at_most > num_bytes_high) /* 16 KB, or 8 KB for low-priority */
1601 at_most = num_bytes_high;
1602 else if (at_most < num_bytes_low) /* 2 KB, or 1 KB for low-priority */
1603 at_most = num_bytes_low;
1605 if (at_most > global_bucket)
1606 at_most = global_bucket;
1608 if (conn_bucket >= 0 && at_most > conn_bucket)
1609 at_most = conn_bucket;
1611 if (at_most < 0)
1612 return 0;
1613 return at_most;
1616 /** How many bytes at most can we read onto this connection? */
1617 static ssize_t
1618 connection_bucket_read_limit(connection_t *conn, time_t now)
1620 int base = connection_speaks_cells(conn) ?
1621 CELL_NETWORK_SIZE : RELAY_PAYLOAD_SIZE;
1622 int priority = conn->type != CONN_TYPE_DIR;
1623 int conn_bucket = -1;
1624 int global_bucket = global_read_bucket;
1626 if (connection_speaks_cells(conn)) {
1627 or_connection_t *or_conn = TO_OR_CONN(conn);
1628 if (conn->state == OR_CONN_STATE_OPEN)
1629 conn_bucket = or_conn->read_bucket;
1632 if (!connection_is_rate_limited(conn)) {
1633 /* be willing to read on local conns even if our buckets are empty */
1634 return conn_bucket>=0 ? conn_bucket : 1<<14;
1637 if (connection_counts_as_relayed_traffic(conn, now) &&
1638 global_relayed_read_bucket <= global_read_bucket)
1639 global_bucket = global_relayed_read_bucket;
1641 return connection_bucket_round_robin(base, priority,
1642 global_bucket, conn_bucket);
1645 /** How many bytes at most can we write onto this connection? */
1646 ssize_t
1647 connection_bucket_write_limit(connection_t *conn, time_t now)
1649 int base = connection_speaks_cells(conn) ?
1650 CELL_NETWORK_SIZE : RELAY_PAYLOAD_SIZE;
1651 int priority = conn->type != CONN_TYPE_DIR;
1652 int global_bucket = global_write_bucket;
1654 if (!connection_is_rate_limited(conn)) {
1655 /* be willing to write to local conns even if our buckets are empty */
1656 return conn->outbuf_flushlen;
1659 if (connection_counts_as_relayed_traffic(conn, now) &&
1660 global_relayed_write_bucket <= global_write_bucket)
1661 global_bucket = global_relayed_write_bucket;
1663 return connection_bucket_round_robin(base, priority, global_bucket,
1664 conn->outbuf_flushlen);
1667 /** Return 1 if the global write buckets are low enough that we
1668 * shouldn't send <b>attempt</b> bytes of low-priority directory stuff
1669 * out to <b>conn</b>. Else return 0.
1671 * Priority is 1 for v1 requests (directories and running-routers),
1672 * and 2 for v2 requests (statuses and descriptors). But see FFFF in
1673 * directory_handle_command_get() for why we don't use priority 2 yet.
1675 * There are a lot of parameters we could use here:
1676 * - global_relayed_write_bucket. Low is bad.
1677 * - global_write_bucket. Low is bad.
1678 * - bandwidthrate. Low is bad.
1679 * - bandwidthburst. Not a big factor?
1680 * - attempt. High is bad.
1681 * - total bytes queued on outbufs. High is bad. But I'm wary of
1682 * using this, since a few slow-flushing queues will pump up the
1683 * number without meaning what we meant to mean. What we really
1684 * mean is "total directory bytes added to outbufs recently", but
1685 * that's harder to quantify and harder to keep track of.
1688 global_write_bucket_low(connection_t *conn, size_t attempt, int priority)
1690 int smaller_bucket = global_write_bucket < global_relayed_write_bucket ?
1691 global_write_bucket : global_relayed_write_bucket;
1692 if (authdir_mode(get_options()) && priority>1)
1693 return 0; /* there's always room to answer v2 if we're an auth dir */
1695 if (!connection_is_rate_limited(conn))
1696 return 0; /* local conns don't get limited */
1698 if (smaller_bucket < (int)attempt)
1699 return 1; /* not enough space no matter the priority */
1701 if (write_buckets_empty_last_second)
1702 return 1; /* we're already hitting our limits, no more please */
1704 if (priority == 1) { /* old-style v1 query */
1705 /* Could we handle *two* of these requests within the next two seconds? */
1706 or_options_t *options = get_options();
1707 int64_t can_write = (int64_t)smaller_bucket
1708 + 2*(options->RelayBandwidthRate ? options->RelayBandwidthRate :
1709 options->BandwidthRate);
1710 if (can_write < 2*(int64_t)attempt)
1711 return 1;
1712 } else { /* v2 query */
1713 /* no further constraints yet */
1715 return 0;
1718 /** We just read num_read and wrote num_written onto conn.
1719 * Decrement buckets appropriately. */
1720 static void
1721 connection_buckets_decrement(connection_t *conn, time_t now,
1722 size_t num_read, size_t num_written)
1724 if (!connection_is_rate_limited(conn))
1725 return; /* local IPs are free */
1726 if (num_written >= INT_MAX || num_read >= INT_MAX) {
1727 log_err(LD_BUG, "Value out of range. num_read=%lu, num_written=%lu, "
1728 "connection type=%s, state=%s",
1729 (unsigned long)num_read, (unsigned long)num_written,
1730 conn_type_to_string(conn->type),
1731 conn_state_to_string(conn->type, conn->state));
1732 if (num_written >= INT_MAX) num_written = 1;
1733 if (num_read >= INT_MAX) num_read = 1;
1734 tor_fragile_assert();
1737 if (num_read > 0)
1738 rep_hist_note_bytes_read(num_read, now);
1739 if (num_written > 0)
1740 rep_hist_note_bytes_written(num_written, now);
1742 if (connection_counts_as_relayed_traffic(conn, now)) {
1743 global_relayed_read_bucket -= (int)num_read;
1744 global_relayed_write_bucket -= (int)num_written;
1746 global_read_bucket -= (int)num_read;
1747 global_write_bucket -= (int)num_written;
1748 if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN)
1749 TO_OR_CONN(conn)->read_bucket -= (int)num_read;
1752 /** If we have exhausted our global buckets, or the buckets for conn,
1753 * stop reading. */
1754 static void
1755 connection_consider_empty_read_buckets(connection_t *conn)
1757 const char *reason;
1759 if (global_read_bucket <= 0) {
1760 reason = "global read bucket exhausted. Pausing.";
1761 } else if (connection_counts_as_relayed_traffic(conn, approx_time()) &&
1762 global_relayed_read_bucket <= 0) {
1763 reason = "global relayed read bucket exhausted. Pausing.";
1764 } else if (connection_speaks_cells(conn) &&
1765 conn->state == OR_CONN_STATE_OPEN &&
1766 TO_OR_CONN(conn)->read_bucket <= 0) {
1767 reason = "connection read bucket exhausted. Pausing.";
1768 } else
1769 return; /* all good, no need to stop it */
1771 LOG_FN_CONN(conn, (LOG_DEBUG, LD_NET, "%s", reason));
1772 conn->read_blocked_on_bw = 1;
1773 connection_stop_reading(conn);
1776 /** If we have exhausted our global buckets, or the buckets for conn,
1777 * stop writing. */
1778 static void
1779 connection_consider_empty_write_buckets(connection_t *conn)
1781 const char *reason;
1783 if (global_write_bucket <= 0) {
1784 reason = "global write bucket exhausted. Pausing.";
1785 } else if (connection_counts_as_relayed_traffic(conn, approx_time()) &&
1786 global_relayed_write_bucket <= 0) {
1787 reason = "global relayed write bucket exhausted. Pausing.";
1788 #if 0
1789 } else if (connection_speaks_cells(conn) &&
1790 conn->state == OR_CONN_STATE_OPEN &&
1791 TO_OR_CONN(conn)->write_bucket <= 0) {
1792 reason = "connection write bucket exhausted. Pausing.";
1793 #endif
1794 } else
1795 return; /* all good, no need to stop it */
1797 LOG_FN_CONN(conn, (LOG_DEBUG, LD_NET, "%s", reason));
1798 conn->write_blocked_on_bw = 1;
1799 connection_stop_writing(conn);
1802 /** Initialize the global read bucket to options-\>BandwidthBurst. */
1803 void
1804 connection_bucket_init(void)
1806 or_options_t *options = get_options();
1807 /* start it at max traffic */
1808 global_read_bucket = (int)options->BandwidthBurst;
1809 global_write_bucket = (int)options->BandwidthBurst;
1810 if (options->RelayBandwidthRate) {
1811 global_relayed_read_bucket = (int)options->RelayBandwidthBurst;
1812 global_relayed_write_bucket = (int)options->RelayBandwidthBurst;
1813 } else {
1814 global_relayed_read_bucket = (int)options->BandwidthBurst;
1815 global_relayed_write_bucket = (int)options->BandwidthBurst;
1819 /** Refill a single <b>bucket</b> called <b>name</b> with bandwidth rate
1820 * <b>rate</b> and bandwidth burst <b>burst</b>, assuming that
1821 * <b>seconds_elapsed</b> seconds have passed since the last call.
1823 static void
1824 connection_bucket_refill_helper(int *bucket, int rate, int burst,
1825 int seconds_elapsed, const char *name)
1827 int starting_bucket = *bucket;
1828 if (starting_bucket < burst && seconds_elapsed) {
1829 if (((burst - starting_bucket)/seconds_elapsed) < rate) {
1830 *bucket = burst; /* We would overflow the bucket; just set it to
1831 * the maximum. */
1832 } else {
1833 int incr = rate*seconds_elapsed;
1834 *bucket += incr;
1835 if (*bucket > burst || *bucket < starting_bucket) {
1836 /* If we overflow the burst, or underflow our starting bucket,
1837 * cap the bucket value to burst. */
1838 /* XXXX this might be redundant now, but it doesn't show up
1839 * in profiles. Remove it after analysis. */
1840 *bucket = burst;
1843 log(LOG_DEBUG, LD_NET,"%s now %d.", name, *bucket);
1847 /** A second has rolled over; increment buckets appropriately. */
1848 void
1849 connection_bucket_refill(int seconds_elapsed, time_t now)
1851 or_options_t *options = get_options();
1852 smartlist_t *conns = get_connection_array();
1853 int relayrate, relayburst;
1855 if (options->RelayBandwidthRate) {
1856 relayrate = (int)options->RelayBandwidthRate;
1857 relayburst = (int)options->RelayBandwidthBurst;
1858 } else {
1859 relayrate = (int)options->BandwidthRate;
1860 relayburst = (int)options->BandwidthBurst;
1863 tor_assert(seconds_elapsed >= 0);
1865 write_buckets_empty_last_second =
1866 global_relayed_write_bucket <= 0 || global_write_bucket <= 0;
1868 /* refill the global buckets */
1869 connection_bucket_refill_helper(&global_read_bucket,
1870 (int)options->BandwidthRate,
1871 (int)options->BandwidthBurst,
1872 seconds_elapsed, "global_read_bucket");
1873 connection_bucket_refill_helper(&global_write_bucket,
1874 (int)options->BandwidthRate,
1875 (int)options->BandwidthBurst,
1876 seconds_elapsed, "global_write_bucket");
1877 connection_bucket_refill_helper(&global_relayed_read_bucket,
1878 relayrate, relayburst, seconds_elapsed,
1879 "global_relayed_read_bucket");
1880 connection_bucket_refill_helper(&global_relayed_write_bucket,
1881 relayrate, relayburst, seconds_elapsed,
1882 "global_relayed_write_bucket");
1884 /* refill the per-connection buckets */
1885 SMARTLIST_FOREACH(conns, connection_t *, conn,
1887 if (connection_speaks_cells(conn)) {
1888 or_connection_t *or_conn = TO_OR_CONN(conn);
1889 if (connection_read_bucket_should_increase(or_conn)) {
1890 connection_bucket_refill_helper(&or_conn->read_bucket,
1891 or_conn->bandwidthrate,
1892 or_conn->bandwidthburst,
1893 seconds_elapsed,
1894 "or_conn->read_bucket");
1895 //log_fn(LOG_DEBUG,"Receiver bucket %d now %d.", i,
1896 // conn->read_bucket);
1900 if (conn->read_blocked_on_bw == 1 /* marked to turn reading back on now */
1901 && global_read_bucket > 0 /* and we're allowed to read */
1902 && (!connection_counts_as_relayed_traffic(conn, now) ||
1903 global_relayed_read_bucket > 0) /* even if we're relayed traffic */
1904 && (!connection_speaks_cells(conn) ||
1905 conn->state != OR_CONN_STATE_OPEN ||
1906 TO_OR_CONN(conn)->read_bucket > 0)) {
1907 /* and either a non-cell conn or a cell conn with non-empty bucket */
1908 LOG_FN_CONN(conn, (LOG_DEBUG,LD_NET,
1909 "waking up conn (fd %d) for read", conn->s));
1910 conn->read_blocked_on_bw = 0;
1911 connection_start_reading(conn);
1914 if (conn->write_blocked_on_bw == 1
1915 && global_write_bucket > 0 /* and we're allowed to write */
1916 && (!connection_counts_as_relayed_traffic(conn, now) ||
1917 global_relayed_write_bucket > 0)) {
1918 /* even if we're relayed traffic */
1919 LOG_FN_CONN(conn, (LOG_DEBUG,LD_NET,
1920 "waking up conn (fd %d) for write", conn->s));
1921 conn->write_blocked_on_bw = 0;
1922 connection_start_writing(conn);
1927 /** Is the receiver bucket for connection <b>conn</b> low enough that we
1928 * should add another pile of tokens to it?
1930 static int
1931 connection_read_bucket_should_increase(or_connection_t *conn)
1933 tor_assert(conn);
1935 if (conn->_base.state != OR_CONN_STATE_OPEN)
1936 return 0; /* only open connections play the rate limiting game */
1937 if (conn->read_bucket >= conn->bandwidthburst)
1938 return 0;
1940 return 1;
1943 /** Read bytes from conn-\>s and process them.
1945 * This function gets called from conn_read() in main.c, either
1946 * when poll() has declared that conn wants to read, or (for OR conns)
1947 * when there are pending TLS bytes.
1949 * It calls connection_read_to_buf() to bring in any new bytes,
1950 * and then calls connection_process_inbuf() to process them.
1952 * Mark the connection and return -1 if you want to close it, else
1953 * return 0.
1956 connection_handle_read(connection_t *conn)
1958 int max_to_read=-1, try_to_read;
1959 size_t before, n_read = 0;
1960 int socket_error = 0;
1962 if (conn->marked_for_close)
1963 return 0; /* do nothing */
1965 conn->timestamp_lastread = approx_time();
1967 switch (conn->type) {
1968 case CONN_TYPE_OR_LISTENER:
1969 return connection_handle_listener_read(conn, CONN_TYPE_OR);
1970 case CONN_TYPE_AP_LISTENER:
1971 case CONN_TYPE_AP_TRANS_LISTENER:
1972 case CONN_TYPE_AP_NATD_LISTENER:
1973 return connection_handle_listener_read(conn, CONN_TYPE_AP);
1974 case CONN_TYPE_DIR_LISTENER:
1975 return connection_handle_listener_read(conn, CONN_TYPE_DIR);
1976 case CONN_TYPE_CONTROL_LISTENER:
1977 return connection_handle_listener_read(conn, CONN_TYPE_CONTROL);
1978 case CONN_TYPE_AP_DNS_LISTENER:
1979 /* This should never happen; eventdns.c handles the reads here. */
1980 tor_fragile_assert();
1981 return 0;
1984 loop_again:
1985 try_to_read = max_to_read;
1986 tor_assert(!conn->marked_for_close);
1988 before = buf_datalen(conn->inbuf);
1989 if (connection_read_to_buf(conn, &max_to_read, &socket_error) < 0) {
1990 /* There's a read error; kill the connection.*/
1991 if (conn->type == CONN_TYPE_OR &&
1992 conn->state == OR_CONN_STATE_CONNECTING) {
1993 connection_or_connect_failed(TO_OR_CONN(conn),
1994 errno_to_orconn_end_reason(socket_error),
1995 tor_socket_strerror(socket_error));
1997 if (CONN_IS_EDGE(conn)) {
1998 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
1999 connection_edge_end_errno(edge_conn);
2000 if (edge_conn->socks_request) /* broken, don't send a socks reply back */
2001 edge_conn->socks_request->has_finished = 1;
2003 connection_close_immediate(conn); /* Don't flush; connection is dead. */
2004 connection_mark_for_close(conn);
2005 return -1;
2007 n_read += buf_datalen(conn->inbuf) - before;
2008 if (CONN_IS_EDGE(conn) && try_to_read != max_to_read) {
2009 /* instruct it not to try to package partial cells. */
2010 if (connection_process_inbuf(conn, 0) < 0) {
2011 return -1;
2013 if (!conn->marked_for_close &&
2014 connection_is_reading(conn) &&
2015 !conn->inbuf_reached_eof &&
2016 max_to_read > 0)
2017 goto loop_again; /* try reading again, in case more is here now */
2019 /* one last try, packaging partial cells and all. */
2020 if (!conn->marked_for_close &&
2021 connection_process_inbuf(conn, 1) < 0) {
2022 return -1;
2024 if (conn->linked_conn) {
2025 /* The other side's handle_write will never actually get called, so
2026 * we need to invoke the appropriate callbacks ourself. */
2027 connection_t *linked = conn->linked_conn;
2029 if (n_read) {
2030 /* Probably a no-op, but hey. */
2031 connection_buckets_decrement(linked, approx_time(), 0, n_read);
2033 if (connection_flushed_some(linked) < 0)
2034 connection_mark_for_close(linked);
2035 if (!connection_wants_to_flush(linked))
2036 connection_finished_flushing(linked);
2039 if (!buf_datalen(linked->outbuf) && conn->active_on_link)
2040 connection_stop_reading_from_linked_conn(conn);
2042 /* If we hit the EOF, call connection_reached_eof. */
2043 if (!conn->marked_for_close &&
2044 conn->inbuf_reached_eof &&
2045 connection_reached_eof(conn) < 0) {
2046 return -1;
2048 return 0;
2051 /** Pull in new bytes from conn-\>s or conn-\>linked_conn onto conn-\>inbuf,
2052 * either directly or via TLS. Reduce the token buckets by the number of bytes
2053 * read.
2055 * If *max_to_read is -1, then decide it ourselves, else go with the
2056 * value passed to us. When returning, if it's changed, subtract the
2057 * number of bytes we read from *max_to_read.
2059 * Return -1 if we want to break conn, else return 0.
2061 static int
2062 connection_read_to_buf(connection_t *conn, int *max_to_read, int *socket_error)
2064 int result;
2065 ssize_t at_most = *max_to_read;
2066 size_t slack_in_buf, more_to_read;
2067 size_t n_read = 0, n_written = 0;
2069 if (at_most == -1) { /* we need to initialize it */
2070 /* how many bytes are we allowed to read? */
2071 at_most = connection_bucket_read_limit(conn, approx_time());
2074 slack_in_buf = buf_slack(conn->inbuf);
2075 again:
2076 if ((size_t)at_most > slack_in_buf && slack_in_buf >= 1024) {
2077 more_to_read = at_most - slack_in_buf;
2078 at_most = slack_in_buf;
2079 } else {
2080 more_to_read = 0;
2083 if (connection_speaks_cells(conn) &&
2084 conn->state > OR_CONN_STATE_PROXY_READING) {
2085 int pending;
2086 or_connection_t *or_conn = TO_OR_CONN(conn);
2087 size_t initial_size;
2088 if (conn->state == OR_CONN_STATE_TLS_HANDSHAKING ||
2089 conn->state == OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING) {
2090 /* continue handshaking even if global token bucket is empty */
2091 return connection_tls_continue_handshake(or_conn);
2094 log_debug(LD_NET,
2095 "%d: starting, inbuf_datalen %ld (%d pending in tls object)."
2096 " at_most %ld.",
2097 conn->s,(long)buf_datalen(conn->inbuf),
2098 tor_tls_get_pending_bytes(or_conn->tls), (long)at_most);
2100 initial_size = buf_datalen(conn->inbuf);
2101 /* else open, or closing */
2102 result = read_to_buf_tls(or_conn->tls, at_most, conn->inbuf);
2103 if (TOR_TLS_IS_ERROR(result) || result == TOR_TLS_CLOSE)
2104 or_conn->tls_error = result;
2105 else
2106 or_conn->tls_error = 0;
2108 switch (result) {
2109 case TOR_TLS_CLOSE:
2110 case TOR_TLS_ERROR_IO:
2111 log_debug(LD_NET,"TLS connection closed %son read. Closing. "
2112 "(Nickname %s, address %s)",
2113 result == TOR_TLS_CLOSE ? "cleanly " : "",
2114 or_conn->nickname ? or_conn->nickname : "not set",
2115 conn->address);
2116 return result;
2117 CASE_TOR_TLS_ERROR_ANY_NONIO:
2118 log_debug(LD_NET,"tls error [%s]. breaking (nickname %s, address %s).",
2119 tor_tls_err_to_string(result),
2120 or_conn->nickname ? or_conn->nickname : "not set",
2121 conn->address);
2122 return result;
2123 case TOR_TLS_WANTWRITE:
2124 connection_start_writing(conn);
2125 return 0;
2126 case TOR_TLS_WANTREAD: /* we're already reading */
2127 case TOR_TLS_DONE: /* no data read, so nothing to process */
2128 result = 0;
2129 break; /* so we call bucket_decrement below */
2130 default:
2131 break;
2133 pending = tor_tls_get_pending_bytes(or_conn->tls);
2134 if (pending) {
2135 /* If we have any pending bytes, we read them now. This *can*
2136 * take us over our read allotment, but really we shouldn't be
2137 * believing that SSL bytes are the same as TCP bytes anyway. */
2138 int r2 = read_to_buf_tls(or_conn->tls, pending, conn->inbuf);
2139 if (r2<0) {
2140 log_warn(LD_BUG, "apparently, reading pending bytes can fail.");
2141 return -1;
2144 result = (int)(buf_datalen(conn->inbuf)-initial_size);
2145 tor_tls_get_n_raw_bytes(or_conn->tls, &n_read, &n_written);
2146 log_debug(LD_GENERAL, "After TLS read of %d: %ld read, %ld written",
2147 result, (long)n_read, (long)n_written);
2148 } else if (conn->linked) {
2149 if (conn->linked_conn) {
2150 result = move_buf_to_buf(conn->inbuf, conn->linked_conn->outbuf,
2151 &conn->linked_conn->outbuf_flushlen);
2152 } else {
2153 result = 0;
2155 //log_notice(LD_GENERAL, "Moved %d bytes on an internal link!", result);
2156 /* If the other side has disappeared, or if it's been marked for close and
2157 * we flushed its outbuf, then we should set our inbuf_reached_eof. */
2158 if (!conn->linked_conn ||
2159 (conn->linked_conn->marked_for_close &&
2160 buf_datalen(conn->linked_conn->outbuf) == 0))
2161 conn->inbuf_reached_eof = 1;
2163 n_read = (size_t) result;
2164 } else {
2165 /* !connection_speaks_cells, !conn->linked_conn. */
2166 int reached_eof = 0;
2167 CONN_LOG_PROTECT(conn,
2168 result = read_to_buf(conn->s, at_most, conn->inbuf, &reached_eof,
2169 socket_error));
2170 if (reached_eof)
2171 conn->inbuf_reached_eof = 1;
2173 // log_fn(LOG_DEBUG,"read_to_buf returned %d.",read_result);
2175 if (result < 0)
2176 return -1;
2177 n_read = (size_t) result;
2180 if (n_read > 0) { /* change *max_to_read */
2181 /*XXXX021 check for overflow*/
2182 *max_to_read = (int)(at_most - n_read);
2185 if (conn->type == CONN_TYPE_AP) {
2186 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
2187 /*XXXX021 check for overflow*/
2188 edge_conn->n_read += (int)n_read;
2191 connection_buckets_decrement(conn, approx_time(), n_read, n_written);
2193 if (more_to_read && result == at_most) {
2194 slack_in_buf = buf_slack(conn->inbuf);
2195 at_most = more_to_read;
2196 goto again;
2199 /* Call even if result is 0, since the global read bucket may
2200 * have reached 0 on a different conn, and this guy needs to
2201 * know to stop reading. */
2202 connection_consider_empty_read_buckets(conn);
2203 if (n_written > 0 && connection_is_writing(conn))
2204 connection_consider_empty_write_buckets(conn);
2206 return 0;
2209 /** A pass-through to fetch_from_buf. */
2211 connection_fetch_from_buf(char *string, size_t len, connection_t *conn)
2213 return fetch_from_buf(string, len, conn->inbuf);
2216 /** Return conn-\>outbuf_flushlen: how many bytes conn wants to flush
2217 * from its outbuf. */
2219 connection_wants_to_flush(connection_t *conn)
2221 return conn->outbuf_flushlen > 0;
2224 /** Are there too many bytes on edge connection <b>conn</b>'s outbuf to
2225 * send back a relay-level sendme yet? Return 1 if so, 0 if not. Used by
2226 * connection_edge_consider_sending_sendme().
2229 connection_outbuf_too_full(connection_t *conn)
2231 return (conn->outbuf_flushlen > 10*CELL_PAYLOAD_SIZE);
2234 /** Try to flush more bytes onto conn-\>s.
2236 * This function gets called either from conn_write() in main.c
2237 * when poll() has declared that conn wants to write, or below
2238 * from connection_write_to_buf() when an entire TLS record is ready.
2240 * Update conn-\>timestamp_lastwritten to now, and call flush_buf
2241 * or flush_buf_tls appropriately. If it succeeds and there are no more
2242 * more bytes on conn->outbuf, then call connection_finished_flushing
2243 * on it too.
2245 * If <b>force</b>, then write as many bytes as possible, ignoring bandwidth
2246 * limits. (Used for flushing messages to controller connections on fatal
2247 * errors.)
2249 * Mark the connection and return -1 if you want to close it, else
2250 * return 0.
2253 connection_handle_write(connection_t *conn, int force)
2255 int e;
2256 socklen_t len=(socklen_t)sizeof(e);
2257 int result;
2258 ssize_t max_to_write;
2259 time_t now = approx_time();
2260 size_t n_read = 0, n_written = 0;
2262 tor_assert(!connection_is_listener(conn));
2264 if (conn->marked_for_close || conn->s < 0)
2265 return 0; /* do nothing */
2267 if (conn->in_flushed_some) {
2268 log_warn(LD_BUG, "called recursively from inside conn->in_flushed_some()");
2269 return 0;
2272 conn->timestamp_lastwritten = now;
2274 /* Sometimes, "writable" means "connected". */
2275 if (connection_state_is_connecting(conn)) {
2276 if (getsockopt(conn->s, SOL_SOCKET, SO_ERROR, (void*)&e, &len) < 0) {
2277 log_warn(LD_BUG,
2278 "getsockopt() syscall failed?! Please report to tor-ops.");
2279 if (CONN_IS_EDGE(conn))
2280 connection_edge_end_errno(TO_EDGE_CONN(conn));
2281 connection_mark_for_close(conn);
2282 return -1;
2284 if (e) {
2285 /* some sort of error, but maybe just inprogress still */
2286 if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
2287 log_info(LD_NET,"in-progress connect failed. Removing. (%s)",
2288 tor_socket_strerror(e));
2289 if (CONN_IS_EDGE(conn))
2290 connection_edge_end_errno(TO_EDGE_CONN(conn));
2291 if (conn->type == CONN_TYPE_OR)
2292 connection_or_connect_failed(TO_OR_CONN(conn),
2293 errno_to_orconn_end_reason(e),
2294 tor_socket_strerror(e));
2296 connection_close_immediate(conn);
2297 connection_mark_for_close(conn);
2298 return -1;
2299 } else {
2300 return 0; /* no change, see if next time is better */
2303 /* The connection is successful. */
2304 if (connection_finished_connecting(conn)<0)
2305 return -1;
2308 max_to_write = force ? (ssize_t)conn->outbuf_flushlen
2309 : connection_bucket_write_limit(conn, now);
2311 if (connection_speaks_cells(conn) &&
2312 conn->state > OR_CONN_STATE_PROXY_READING) {
2313 or_connection_t *or_conn = TO_OR_CONN(conn);
2314 if (conn->state == OR_CONN_STATE_TLS_HANDSHAKING ||
2315 conn->state == OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING) {
2316 connection_stop_writing(conn);
2317 if (connection_tls_continue_handshake(or_conn) < 0) {
2318 /* Don't flush; connection is dead. */
2319 connection_close_immediate(conn);
2320 connection_mark_for_close(conn);
2321 return -1;
2323 return 0;
2324 } else if (conn->state == OR_CONN_STATE_TLS_SERVER_RENEGOTIATING) {
2325 return connection_handle_read(conn);
2328 /* else open, or closing */
2329 result = flush_buf_tls(or_conn->tls, conn->outbuf,
2330 max_to_write, &conn->outbuf_flushlen);
2331 switch (result) {
2332 CASE_TOR_TLS_ERROR_ANY:
2333 case TOR_TLS_CLOSE:
2334 log_info(LD_NET,result!=TOR_TLS_CLOSE?
2335 "tls error. breaking.":"TLS connection closed on flush");
2336 /* Don't flush; connection is dead. */
2337 connection_close_immediate(conn);
2338 connection_mark_for_close(conn);
2339 return -1;
2340 case TOR_TLS_WANTWRITE:
2341 log_debug(LD_NET,"wanted write.");
2342 /* we're already writing */
2343 return 0;
2344 case TOR_TLS_WANTREAD:
2345 /* Make sure to avoid a loop if the receive buckets are empty. */
2346 log_debug(LD_NET,"wanted read.");
2347 if (!connection_is_reading(conn)) {
2348 connection_stop_writing(conn);
2349 conn->write_blocked_on_bw = 1;
2350 /* we'll start reading again when the next second arrives,
2351 * and then also start writing again.
2354 /* else no problem, we're already reading */
2355 return 0;
2356 /* case TOR_TLS_DONE:
2357 * for TOR_TLS_DONE, fall through to check if the flushlen
2358 * is empty, so we can stop writing.
2362 tor_tls_get_n_raw_bytes(or_conn->tls, &n_read, &n_written);
2363 log_debug(LD_GENERAL, "After TLS write of %d: %ld read, %ld written",
2364 result, (long)n_read, (long)n_written);
2365 } else {
2366 CONN_LOG_PROTECT(conn,
2367 result = flush_buf(conn->s, conn->outbuf,
2368 max_to_write, &conn->outbuf_flushlen));
2369 if (result < 0) {
2370 if (CONN_IS_EDGE(conn))
2371 connection_edge_end_errno(TO_EDGE_CONN(conn));
2373 connection_close_immediate(conn); /* Don't flush; connection is dead. */
2374 connection_mark_for_close(conn);
2375 return -1;
2377 n_written = (size_t) result;
2380 if (conn->type == CONN_TYPE_AP) {
2381 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
2382 /*XXXX021 check for overflow.*/
2383 edge_conn->n_written += (int)n_written;
2386 connection_buckets_decrement(conn, approx_time(), n_read, n_written);
2388 if (result > 0) {
2389 /* If we wrote any bytes from our buffer, then call the appropriate
2390 * functions. */
2391 if (connection_flushed_some(conn) < 0)
2392 connection_mark_for_close(conn);
2395 if (!connection_wants_to_flush(conn)) { /* it's done flushing */
2396 if (connection_finished_flushing(conn) < 0) {
2397 /* already marked */
2398 return -1;
2400 return 0;
2403 /* Call even if result is 0, since the global write bucket may
2404 * have reached 0 on a different conn, and this guy needs to
2405 * know to stop writing. */
2406 connection_consider_empty_write_buckets(conn);
2407 if (n_read > 0 && connection_is_reading(conn))
2408 connection_consider_empty_read_buckets(conn);
2410 return 0;
2413 /** OpenSSL TLS record size is 16383; this is close. The goal here is to
2414 * push data out as soon as we know there's enough for a TLS record, so
2415 * during periods of high load we won't read entire megabytes from
2416 * input before pushing any data out. It also has the feature of not
2417 * growing huge outbufs unless something is slow. */
2418 #define MIN_TLS_FLUSHLEN 15872
2420 /** Append <b>len</b> bytes of <b>string</b> onto <b>conn</b>'s
2421 * outbuf, and ask it to start writing.
2423 * If <b>zlib</b> is nonzero, this is a directory connection that should get
2424 * its contents compressed or decompressed as they're written. If zlib is
2425 * negative, this is the last data to be compressed, and the connection's zlib
2426 * state should be flushed.
2428 * If it's an OR conn and an entire TLS record is ready, then try to
2429 * flush the record now. Similarly, if it's a local control connection
2430 * and a 64k chunk is ready, try to flush it all, so we don't end up with
2431 * many megabytes of controller info queued at once.
2433 void
2434 _connection_write_to_buf_impl(const char *string, size_t len,
2435 connection_t *conn, int zlib)
2437 /* XXXX This function really needs to return -1 on failure. */
2438 int r;
2439 size_t old_datalen;
2440 if (!len && !(zlib<0))
2441 return;
2442 /* if it's marked for close, only allow write if we mean to flush it */
2443 if (conn->marked_for_close && !conn->hold_open_until_flushed)
2444 return;
2446 old_datalen = buf_datalen(conn->outbuf);
2447 if (zlib) {
2448 dir_connection_t *dir_conn = TO_DIR_CONN(conn);
2449 int done = zlib < 0;
2450 CONN_LOG_PROTECT(conn, r = write_to_buf_zlib(conn->outbuf,
2451 dir_conn->zlib_state,
2452 string, len, done));
2453 } else {
2454 CONN_LOG_PROTECT(conn, r = write_to_buf(string, len, conn->outbuf));
2456 if (r < 0) {
2457 if (CONN_IS_EDGE(conn)) {
2458 /* if it failed, it means we have our package/delivery windows set
2459 wrong compared to our max outbuf size. close the whole circuit. */
2460 log_warn(LD_NET,
2461 "write_to_buf failed. Closing circuit (fd %d).", conn->s);
2462 circuit_mark_for_close(circuit_get_by_edge_conn(TO_EDGE_CONN(conn)),
2463 END_CIRC_REASON_INTERNAL);
2464 } else {
2465 log_warn(LD_NET,
2466 "write_to_buf failed. Closing connection (fd %d).", conn->s);
2467 connection_mark_for_close(conn);
2469 return;
2472 connection_start_writing(conn);
2473 if (zlib) {
2474 conn->outbuf_flushlen += buf_datalen(conn->outbuf) - old_datalen;
2475 } else {
2476 ssize_t extra = 0;
2477 conn->outbuf_flushlen += len;
2479 /* Should we try flushing the outbuf now? */
2480 if (conn->in_flushed_some) {
2481 /* Don't flush the outbuf when the reason we're writing more stuff is
2482 * _because_ we flushed the outbuf. That's unfair. */
2483 return;
2486 if (conn->type == CONN_TYPE_OR &&
2487 conn->outbuf_flushlen-len < MIN_TLS_FLUSHLEN &&
2488 conn->outbuf_flushlen >= MIN_TLS_FLUSHLEN) {
2489 /* We just pushed outbuf_flushlen to MIN_TLS_FLUSHLEN or above;
2490 * we can send out a full TLS frame now if we like. */
2491 extra = conn->outbuf_flushlen - MIN_TLS_FLUSHLEN;
2492 conn->outbuf_flushlen = MIN_TLS_FLUSHLEN;
2493 } else if (conn->type == CONN_TYPE_CONTROL &&
2494 !connection_is_rate_limited(conn) &&
2495 conn->outbuf_flushlen-len < 1<<16 &&
2496 conn->outbuf_flushlen >= 1<<16) {
2497 /* just try to flush all of it */
2498 } else
2499 return; /* no need to try flushing */
2501 if (connection_handle_write(conn, 0) < 0) {
2502 if (!conn->marked_for_close) {
2503 /* this connection is broken. remove it. */
2504 log_warn(LD_BUG, "unhandled error on write for "
2505 "conn (type %d, fd %d); removing",
2506 conn->type, conn->s);
2507 tor_fragile_assert();
2508 /* do a close-immediate here, so we don't try to flush */
2509 connection_close_immediate(conn);
2511 return;
2513 if (extra) {
2514 conn->outbuf_flushlen += extra;
2515 connection_start_writing(conn);
2520 /** Return a connection with given type, address, port, and purpose;
2521 * or NULL if no such connection exists. */
2522 connection_t *
2523 connection_get_by_type_addr_port_purpose(int type,
2524 const tor_addr_t *addr, uint16_t port,
2525 int purpose)
2527 smartlist_t *conns = get_connection_array();
2528 SMARTLIST_FOREACH(conns, connection_t *, conn,
2530 if (conn->type == type &&
2531 tor_addr_eq(&conn->addr, addr) &&
2532 conn->port == port &&
2533 conn->purpose == purpose &&
2534 !conn->marked_for_close)
2535 return conn;
2537 return NULL;
2540 /** Return the stream with id <b>id</b> if it is not already marked for
2541 * close.
2543 connection_t *
2544 connection_get_by_global_id(uint64_t id)
2546 smartlist_t *conns = get_connection_array();
2547 SMARTLIST_FOREACH(conns, connection_t *, conn,
2549 if (conn->global_identifier == id)
2550 return conn;
2552 return NULL;
2555 /** Return a connection of type <b>type</b> that is not marked for close.
2557 connection_t *
2558 connection_get_by_type(int type)
2560 smartlist_t *conns = get_connection_array();
2561 SMARTLIST_FOREACH(conns, connection_t *, conn,
2563 if (conn->type == type && !conn->marked_for_close)
2564 return conn;
2566 return NULL;
2569 /** Return a connection of type <b>type</b> that is in state <b>state</b>,
2570 * and that is not marked for close.
2572 connection_t *
2573 connection_get_by_type_state(int type, int state)
2575 smartlist_t *conns = get_connection_array();
2576 SMARTLIST_FOREACH(conns, connection_t *, conn,
2578 if (conn->type == type && conn->state == state && !conn->marked_for_close)
2579 return conn;
2581 return NULL;
2584 /** Return a connection of type <b>type</b> that has rendquery equal
2585 * to <b>rendquery</b>, and that is not marked for close. If state
2586 * is non-zero, conn must be of that state too. If rendversion is
2587 * nonnegative, conn must be fetching that rendversion, too.
2589 connection_t *
2590 connection_get_by_type_state_rendquery(int type, int state,
2591 const char *rendquery,
2592 int rendversion)
2594 smartlist_t *conns = get_connection_array();
2596 tor_assert(type == CONN_TYPE_DIR ||
2597 type == CONN_TYPE_AP || type == CONN_TYPE_EXIT);
2598 tor_assert(rendquery);
2600 SMARTLIST_FOREACH(conns, connection_t *, conn,
2602 if (conn->type == type &&
2603 !conn->marked_for_close &&
2604 (!state || state == conn->state)) {
2605 if (type == CONN_TYPE_DIR &&
2606 TO_DIR_CONN(conn)->rend_data &&
2607 (rendversion < 0 ||
2608 rendversion == TO_DIR_CONN(conn)->rend_data->rend_desc_version) &&
2609 !rend_cmp_service_ids(rendquery,
2610 TO_DIR_CONN(conn)->rend_data->onion_address))
2611 return conn;
2612 else if (CONN_IS_EDGE(conn) &&
2613 TO_EDGE_CONN(conn)->rend_data &&
2614 !rend_cmp_service_ids(rendquery,
2615 TO_EDGE_CONN(conn)->rend_data->onion_address))
2616 return conn;
2619 return NULL;
2622 /** Return an open, non-marked connection of a given type and purpose, or NULL
2623 * if no such connection exists. */
2624 connection_t *
2625 connection_get_by_type_purpose(int type, int purpose)
2627 smartlist_t *conns = get_connection_array();
2628 SMARTLIST_FOREACH(conns, connection_t *, conn,
2630 if (conn->type == type &&
2631 !conn->marked_for_close &&
2632 (purpose == conn->purpose))
2633 return conn;
2635 return NULL;
2638 /** Return 1 if <b>conn</b> is a listener conn, else return 0. */
2640 connection_is_listener(connection_t *conn)
2642 if (conn->type == CONN_TYPE_OR_LISTENER ||
2643 conn->type == CONN_TYPE_AP_LISTENER ||
2644 conn->type == CONN_TYPE_AP_TRANS_LISTENER ||
2645 conn->type == CONN_TYPE_AP_DNS_LISTENER ||
2646 conn->type == CONN_TYPE_AP_NATD_LISTENER ||
2647 conn->type == CONN_TYPE_DIR_LISTENER ||
2648 conn->type == CONN_TYPE_CONTROL_LISTENER)
2649 return 1;
2650 return 0;
2653 /** Return 1 if <b>conn</b> is in state "open" and is not marked
2654 * for close, else return 0.
2657 connection_state_is_open(connection_t *conn)
2659 tor_assert(conn);
2661 if (conn->marked_for_close)
2662 return 0;
2664 if ((conn->type == CONN_TYPE_OR && conn->state == OR_CONN_STATE_OPEN) ||
2665 (conn->type == CONN_TYPE_AP && conn->state == AP_CONN_STATE_OPEN) ||
2666 (conn->type == CONN_TYPE_EXIT && conn->state == EXIT_CONN_STATE_OPEN) ||
2667 (conn->type == CONN_TYPE_CONTROL &&
2668 conn->state == CONTROL_CONN_STATE_OPEN))
2669 return 1;
2671 return 0;
2674 /** Return 1 if conn is in 'connecting' state, else return 0. */
2676 connection_state_is_connecting(connection_t *conn)
2678 tor_assert(conn);
2680 if (conn->marked_for_close)
2681 return 0;
2682 switch (conn->type)
2684 case CONN_TYPE_OR:
2685 return conn->state == OR_CONN_STATE_CONNECTING;
2686 case CONN_TYPE_EXIT:
2687 return conn->state == EXIT_CONN_STATE_CONNECTING;
2688 case CONN_TYPE_DIR:
2689 return conn->state == DIR_CONN_STATE_CONNECTING;
2692 return 0;
2695 /** Allocates a base64'ed authenticator for use in http or https
2696 * auth, based on the input string <b>authenticator</b>. Returns it
2697 * if success, else returns NULL. */
2698 char *
2699 alloc_http_authenticator(const char *authenticator)
2701 /* an authenticator in Basic authentication
2702 * is just the string "username:password" */
2703 const size_t authenticator_length = strlen(authenticator);
2704 /* The base64_encode function needs a minimum buffer length
2705 * of 66 bytes. */
2706 const size_t base64_authenticator_length = (authenticator_length/48+1)*66;
2707 char *base64_authenticator = tor_malloc(base64_authenticator_length);
2708 if (base64_encode(base64_authenticator, base64_authenticator_length,
2709 authenticator, authenticator_length) < 0) {
2710 tor_free(base64_authenticator); /* free and set to null */
2711 } else {
2712 /* remove extra \n at end of encoding */
2713 base64_authenticator[strlen(base64_authenticator) - 1] = 0;
2715 return base64_authenticator;
2718 /** Given a socket handle, check whether the local address (sockname) of the
2719 * socket is one that we've connected from before. If so, double-check
2720 * whether our address has changed and we need to generate keys. If we do,
2721 * call init_keys().
2723 static void
2724 client_check_address_changed(int sock)
2726 uint32_t iface_ip, ip_out;
2727 struct sockaddr_in out_addr;
2728 socklen_t out_addr_len = (socklen_t) sizeof(out_addr);
2729 uint32_t *ip;
2731 if (!last_interface_ip)
2732 get_interface_address(LOG_INFO, &last_interface_ip);
2733 if (!outgoing_addrs)
2734 outgoing_addrs = smartlist_create();
2736 if (getsockname(sock, (struct sockaddr*)&out_addr, &out_addr_len)<0) {
2737 int e = tor_socket_errno(sock);
2738 log_warn(LD_NET, "getsockname() to check for address change failed: %s",
2739 tor_socket_strerror(e));
2740 return;
2743 /* Okay. If we've used this address previously, we're okay. */
2744 ip_out = ntohl(out_addr.sin_addr.s_addr);
2745 SMARTLIST_FOREACH(outgoing_addrs, uint32_t*, ip_ptr,
2746 if (*ip_ptr == ip_out) return;
2749 /* Uh-oh. We haven't connected from this address before. Has the interface
2750 * address changed? */
2751 if (get_interface_address(LOG_INFO, &iface_ip)<0)
2752 return;
2753 ip = tor_malloc(sizeof(uint32_t));
2754 *ip = ip_out;
2756 if (iface_ip == last_interface_ip) {
2757 /* Nope, it hasn't changed. Add this address to the list. */
2758 smartlist_add(outgoing_addrs, ip);
2759 } else {
2760 /* The interface changed. We're a client, so we need to regenerate our
2761 * keys. First, reset the state. */
2762 log(LOG_NOTICE, LD_NET, "Our IP address has changed. Rotating keys...");
2763 last_interface_ip = iface_ip;
2764 SMARTLIST_FOREACH(outgoing_addrs, void*, ip_ptr, tor_free(ip_ptr));
2765 smartlist_clear(outgoing_addrs);
2766 smartlist_add(outgoing_addrs, ip);
2767 /* Okay, now change our keys. */
2768 ip_address_changed(1);
2772 /** Some systems have limited system buffers for recv and xmit on
2773 * sockets allocated in a virtual server or similar environment. For a Tor
2774 * server this can produce the "Error creating network socket: No buffer
2775 * space available" error once all available TCP buffer space is consumed.
2776 * This method will attempt to constrain the buffers allocated for the socket
2777 * to the desired size to stay below system TCP buffer limits.
2779 static void
2780 set_constrained_socket_buffers(int sock, int size)
2782 void *sz = (void*)&size;
2783 socklen_t sz_sz = (socklen_t) sizeof(size);
2784 if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, sz, sz_sz) < 0) {
2785 int e = tor_socket_errno(sock);
2786 log_warn(LD_NET, "setsockopt() to constrain send "
2787 "buffer to %d bytes failed: %s", size, tor_socket_strerror(e));
2789 if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, sz, sz_sz) < 0) {
2790 int e = tor_socket_errno(sock);
2791 log_warn(LD_NET, "setsockopt() to constrain recv "
2792 "buffer to %d bytes failed: %s", size, tor_socket_strerror(e));
2796 /** Process new bytes that have arrived on conn-\>inbuf.
2798 * This function just passes conn to the connection-specific
2799 * connection_*_process_inbuf() function. It also passes in
2800 * package_partial if wanted.
2802 static int
2803 connection_process_inbuf(connection_t *conn, int package_partial)
2805 tor_assert(conn);
2807 switch (conn->type) {
2808 case CONN_TYPE_OR:
2809 return connection_or_process_inbuf(TO_OR_CONN(conn));
2810 case CONN_TYPE_EXIT:
2811 case CONN_TYPE_AP:
2812 return connection_edge_process_inbuf(TO_EDGE_CONN(conn),
2813 package_partial);
2814 case CONN_TYPE_DIR:
2815 return connection_dir_process_inbuf(TO_DIR_CONN(conn));
2816 case CONN_TYPE_CPUWORKER:
2817 return connection_cpu_process_inbuf(conn);
2818 case CONN_TYPE_CONTROL:
2819 return connection_control_process_inbuf(TO_CONTROL_CONN(conn));
2820 default:
2821 log_err(LD_BUG,"got unexpected conn type %d.", conn->type);
2822 tor_fragile_assert();
2823 return -1;
2827 /** Called whenever we've written data on a connection. */
2828 static int
2829 connection_flushed_some(connection_t *conn)
2831 int r = 0;
2832 tor_assert(!conn->in_flushed_some);
2833 conn->in_flushed_some = 1;
2834 if (conn->type == CONN_TYPE_DIR &&
2835 conn->state == DIR_CONN_STATE_SERVER_WRITING) {
2836 r = connection_dirserv_flushed_some(TO_DIR_CONN(conn));
2837 } else if (conn->type == CONN_TYPE_OR) {
2838 r = connection_or_flushed_some(TO_OR_CONN(conn));
2840 conn->in_flushed_some = 0;
2841 return r;
2844 /** We just finished flushing bytes from conn-\>outbuf, and there
2845 * are no more bytes remaining.
2847 * This function just passes conn to the connection-specific
2848 * connection_*_finished_flushing() function.
2850 static int
2851 connection_finished_flushing(connection_t *conn)
2853 tor_assert(conn);
2855 /* If the connection is closed, don't try to do anything more here. */
2856 if (CONN_IS_CLOSED(conn))
2857 return 0;
2859 // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
2861 switch (conn->type) {
2862 case CONN_TYPE_OR:
2863 return connection_or_finished_flushing(TO_OR_CONN(conn));
2864 case CONN_TYPE_AP:
2865 case CONN_TYPE_EXIT:
2866 return connection_edge_finished_flushing(TO_EDGE_CONN(conn));
2867 case CONN_TYPE_DIR:
2868 return connection_dir_finished_flushing(TO_DIR_CONN(conn));
2869 case CONN_TYPE_CPUWORKER:
2870 return connection_cpu_finished_flushing(conn);
2871 case CONN_TYPE_CONTROL:
2872 return connection_control_finished_flushing(TO_CONTROL_CONN(conn));
2873 default:
2874 log_err(LD_BUG,"got unexpected conn type %d.", conn->type);
2875 tor_fragile_assert();
2876 return -1;
2880 /** Called when our attempt to connect() to another server has just
2881 * succeeded.
2883 * This function just passes conn to the connection-specific
2884 * connection_*_finished_connecting() function.
2886 static int
2887 connection_finished_connecting(connection_t *conn)
2889 tor_assert(conn);
2890 switch (conn->type)
2892 case CONN_TYPE_OR:
2893 return connection_or_finished_connecting(TO_OR_CONN(conn));
2894 case CONN_TYPE_EXIT:
2895 return connection_edge_finished_connecting(TO_EDGE_CONN(conn));
2896 case CONN_TYPE_DIR:
2897 return connection_dir_finished_connecting(TO_DIR_CONN(conn));
2898 default:
2899 log_err(LD_BUG,"got unexpected conn type %d.", conn->type);
2900 tor_fragile_assert();
2901 return -1;
2905 /** Callback: invoked when a connection reaches an EOF event. */
2906 static int
2907 connection_reached_eof(connection_t *conn)
2909 switch (conn->type) {
2910 case CONN_TYPE_OR:
2911 return connection_or_reached_eof(TO_OR_CONN(conn));
2912 case CONN_TYPE_AP:
2913 case CONN_TYPE_EXIT:
2914 return connection_edge_reached_eof(TO_EDGE_CONN(conn));
2915 case CONN_TYPE_DIR:
2916 return connection_dir_reached_eof(TO_DIR_CONN(conn));
2917 case CONN_TYPE_CPUWORKER:
2918 return connection_cpu_reached_eof(conn);
2919 case CONN_TYPE_CONTROL:
2920 return connection_control_reached_eof(TO_CONTROL_CONN(conn));
2921 default:
2922 log_err(LD_BUG,"got unexpected conn type %d.", conn->type);
2923 tor_fragile_assert();
2924 return -1;
2928 /** Log how many bytes are used by buffers of different kinds and sizes. */
2929 void
2930 connection_dump_buffer_mem_stats(int severity)
2932 uint64_t used_by_type[_CONN_TYPE_MAX+1];
2933 uint64_t alloc_by_type[_CONN_TYPE_MAX+1];
2934 int n_conns_by_type[_CONN_TYPE_MAX+1];
2935 uint64_t total_alloc = 0;
2936 uint64_t total_used = 0;
2937 int i;
2938 smartlist_t *conns = get_connection_array();
2940 memset(used_by_type, 0, sizeof(used_by_type));
2941 memset(alloc_by_type, 0, sizeof(alloc_by_type));
2942 memset(n_conns_by_type, 0, sizeof(n_conns_by_type));
2944 SMARTLIST_FOREACH(conns, connection_t *, c,
2946 int tp = c->type;
2947 ++n_conns_by_type[tp];
2948 if (c->inbuf) {
2949 used_by_type[tp] += buf_datalen(c->inbuf);
2950 alloc_by_type[tp] += buf_allocation(c->inbuf);
2952 if (c->outbuf) {
2953 used_by_type[tp] += buf_datalen(c->outbuf);
2954 alloc_by_type[tp] += buf_allocation(c->outbuf);
2957 for (i=0; i <= _CONN_TYPE_MAX; ++i) {
2958 total_used += used_by_type[i];
2959 total_alloc += alloc_by_type[i];
2962 log(severity, LD_GENERAL,
2963 "In buffers for %d connections: "U64_FORMAT" used/"U64_FORMAT" allocated",
2964 smartlist_len(conns),
2965 U64_PRINTF_ARG(total_used), U64_PRINTF_ARG(total_alloc));
2966 for (i=_CONN_TYPE_MIN; i <= _CONN_TYPE_MAX; ++i) {
2967 if (!n_conns_by_type[i])
2968 continue;
2969 log(severity, LD_GENERAL,
2970 " For %d %s connections: "U64_FORMAT" used/"U64_FORMAT" allocated",
2971 n_conns_by_type[i], conn_type_to_string(i),
2972 U64_PRINTF_ARG(used_by_type[i]), U64_PRINTF_ARG(alloc_by_type[i]));
2976 /** Verify that connection <b>conn</b> has all of its invariants
2977 * correct. Trigger an assert if anything is invalid.
2979 void
2980 assert_connection_ok(connection_t *conn, time_t now)
2982 (void) now; /* XXXX unused. */
2983 tor_assert(conn);
2984 tor_assert(conn->type >= _CONN_TYPE_MIN);
2985 tor_assert(conn->type <= _CONN_TYPE_MAX);
2986 switch (conn->type) {
2987 case CONN_TYPE_OR:
2988 tor_assert(conn->magic == OR_CONNECTION_MAGIC);
2989 break;
2990 case CONN_TYPE_AP:
2991 case CONN_TYPE_EXIT:
2992 tor_assert(conn->magic == EDGE_CONNECTION_MAGIC);
2993 break;
2994 case CONN_TYPE_DIR:
2995 tor_assert(conn->magic == DIR_CONNECTION_MAGIC);
2996 break;
2997 case CONN_TYPE_CONTROL:
2998 tor_assert(conn->magic == CONTROL_CONNECTION_MAGIC);
2999 break;
3000 default:
3001 tor_assert(conn->magic == BASE_CONNECTION_MAGIC);
3002 break;
3005 if (conn->linked_conn) {
3006 tor_assert(conn->linked_conn->linked_conn == conn);
3007 tor_assert(conn->linked);
3009 if (conn->linked)
3010 tor_assert(conn->s < 0);
3012 if (conn->outbuf_flushlen > 0) {
3013 tor_assert(connection_is_writing(conn) || conn->write_blocked_on_bw ||
3014 (CONN_IS_EDGE(conn) && TO_EDGE_CONN(conn)->edge_blocked_on_circ));
3017 if (conn->hold_open_until_flushed)
3018 tor_assert(conn->marked_for_close);
3020 /* XXXX check: read_blocked_on_bw, write_blocked_on_bw, s, conn_array_index,
3021 * marked_for_close. */
3023 /* buffers */
3024 if (!connection_is_listener(conn)) {
3025 assert_buf_ok(conn->inbuf);
3026 assert_buf_ok(conn->outbuf);
3029 if (conn->type == CONN_TYPE_OR) {
3030 or_connection_t *or_conn = TO_OR_CONN(conn);
3031 if (conn->state == OR_CONN_STATE_OPEN) {
3032 /* tor_assert(conn->bandwidth > 0); */
3033 /* the above isn't necessarily true: if we just did a TLS
3034 * handshake but we didn't recognize the other peer, or it
3035 * gave a bad cert/etc, then we won't have assigned bandwidth,
3036 * yet it will be open. -RD
3038 // tor_assert(conn->read_bucket >= 0);
3040 // tor_assert(conn->addr && conn->port);
3041 tor_assert(conn->address);
3042 if (conn->state > OR_CONN_STATE_PROXY_READING)
3043 tor_assert(or_conn->tls);
3046 if (CONN_IS_EDGE(conn)) {
3047 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
3048 if (edge_conn->chosen_exit_optional || edge_conn->chosen_exit_retries) {
3049 tor_assert(conn->type == CONN_TYPE_AP);
3050 tor_assert(edge_conn->chosen_exit_name);
3053 /* XXX unchecked: package window, deliver window. */
3054 if (conn->type == CONN_TYPE_AP) {
3056 tor_assert(edge_conn->socks_request);
3057 if (conn->state == AP_CONN_STATE_OPEN) {
3058 tor_assert(edge_conn->socks_request->has_finished);
3059 if (!conn->marked_for_close) {
3060 tor_assert(edge_conn->cpath_layer);
3061 assert_cpath_layer_ok(edge_conn->cpath_layer);
3065 if (conn->type == CONN_TYPE_EXIT) {
3066 tor_assert(conn->purpose == EXIT_PURPOSE_CONNECT ||
3067 conn->purpose == EXIT_PURPOSE_RESOLVE);
3069 } else if (conn->type == CONN_TYPE_DIR) {
3070 } else {
3071 /* Purpose is only used for dir and exit types currently */
3072 tor_assert(!conn->purpose);
3075 switch (conn->type)
3077 case CONN_TYPE_OR_LISTENER:
3078 case CONN_TYPE_AP_LISTENER:
3079 case CONN_TYPE_AP_TRANS_LISTENER:
3080 case CONN_TYPE_AP_NATD_LISTENER:
3081 case CONN_TYPE_DIR_LISTENER:
3082 case CONN_TYPE_CONTROL_LISTENER:
3083 case CONN_TYPE_AP_DNS_LISTENER:
3084 tor_assert(conn->state == LISTENER_STATE_READY);
3085 break;
3086 case CONN_TYPE_OR:
3087 tor_assert(conn->state >= _OR_CONN_STATE_MIN);
3088 tor_assert(conn->state <= _OR_CONN_STATE_MAX);
3089 tor_assert(TO_OR_CONN(conn)->n_circuits >= 0);
3090 break;
3091 case CONN_TYPE_EXIT:
3092 tor_assert(conn->state >= _EXIT_CONN_STATE_MIN);
3093 tor_assert(conn->state <= _EXIT_CONN_STATE_MAX);
3094 tor_assert(conn->purpose >= _EXIT_PURPOSE_MIN);
3095 tor_assert(conn->purpose <= _EXIT_PURPOSE_MAX);
3096 break;
3097 case CONN_TYPE_AP:
3098 tor_assert(conn->state >= _AP_CONN_STATE_MIN);
3099 tor_assert(conn->state <= _AP_CONN_STATE_MAX);
3100 tor_assert(TO_EDGE_CONN(conn)->socks_request);
3101 break;
3102 case CONN_TYPE_DIR:
3103 tor_assert(conn->state >= _DIR_CONN_STATE_MIN);
3104 tor_assert(conn->state <= _DIR_CONN_STATE_MAX);
3105 tor_assert(conn->purpose >= _DIR_PURPOSE_MIN);
3106 tor_assert(conn->purpose <= _DIR_PURPOSE_MAX);
3107 break;
3108 case CONN_TYPE_CPUWORKER:
3109 tor_assert(conn->state >= _CPUWORKER_STATE_MIN);
3110 tor_assert(conn->state <= _CPUWORKER_STATE_MAX);
3111 break;
3112 case CONN_TYPE_CONTROL:
3113 tor_assert(conn->state >= _CONTROL_CONN_STATE_MIN);
3114 tor_assert(conn->state <= _CONTROL_CONN_STATE_MAX);
3115 break;
3116 default:
3117 tor_assert(0);