r11813@catbus: nickm | 2007-02-14 11:42:58 -0500
[tor.git] / src / or / connection.c
blob29d27c04373a0c23d929079c12c7396b3b23f7b2
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2007, Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
5 /* $Id$ */
6 const char connection_c_id[] =
7 "$Id$";
9 /**
10 * \file connection.c
11 * \brief General high-level functions to handle reading and writing
12 * on connections.
13 **/
15 #include "or.h"
17 static connection_t *connection_create_listener(const char *listenaddress,
18 uint16_t listenport, int type);
19 static int connection_init_accepted_conn(connection_t *conn,
20 uint8_t listener_type);
21 static int connection_handle_listener_read(connection_t *conn, int new_type);
22 static int connection_read_bucket_should_increase(or_connection_t *conn);
23 static int connection_finished_flushing(connection_t *conn);
24 static int connection_flushed_some(connection_t *conn);
25 static int connection_finished_connecting(connection_t *conn);
26 static int connection_reached_eof(connection_t *conn);
27 static int connection_read_to_buf(connection_t *conn, int *max_to_read);
28 static int connection_process_inbuf(connection_t *conn, int package_partial);
29 static void client_check_address_changed(int sock);
31 static uint32_t last_interface_ip = 0;
32 static smartlist_t *outgoing_addrs = NULL;
34 /**************************************************************/
36 /**
37 * Return the human-readable name for the connection type <b>type</b>
39 const char *
40 conn_type_to_string(int type)
42 static char buf[64];
43 switch (type) {
44 case CONN_TYPE_OR_LISTENER: return "OR listener";
45 case CONN_TYPE_OR: return "OR";
46 case CONN_TYPE_EXIT: return "Exit";
47 case CONN_TYPE_AP_LISTENER: return "Socks listener";
48 case CONN_TYPE_AP_TRANS_LISTENER:
49 return "Transparent pf/netfilter listener";
50 case CONN_TYPE_AP_NATD_LISTENER: return "Transparent natd listener";
51 case CONN_TYPE_AP: return "Socks";
52 case CONN_TYPE_DIR_LISTENER: return "Directory listener";
53 case CONN_TYPE_DIR: return "Directory";
54 case CONN_TYPE_DNSWORKER: return "DNS worker";
55 case CONN_TYPE_CPUWORKER: return "CPU worker";
56 case CONN_TYPE_CONTROL_LISTENER: return "Control listener";
57 case CONN_TYPE_CONTROL: return "Control";
58 default:
59 log_warn(LD_BUG, "Bug: unknown connection type %d", type);
60 tor_snprintf(buf, sizeof(buf), "unknown [%d]", type);
61 return buf;
65 /**
66 * Return the human-readable name for the connection state <b>state</b>
67 * for the connection type <b>type</b>
69 const char *
70 conn_state_to_string(int type, int state)
72 static char buf[96];
73 switch (type) {
74 case CONN_TYPE_OR_LISTENER:
75 case CONN_TYPE_AP_LISTENER:
76 case CONN_TYPE_AP_TRANS_LISTENER:
77 case CONN_TYPE_AP_NATD_LISTENER:
78 case CONN_TYPE_DIR_LISTENER:
79 case CONN_TYPE_CONTROL_LISTENER:
80 if (state == LISTENER_STATE_READY)
81 return "ready";
82 break;
83 case CONN_TYPE_OR:
84 switch (state) {
85 case OR_CONN_STATE_CONNECTING: return "connect()ing";
86 case OR_CONN_STATE_PROXY_FLUSHING: return "proxy flushing";
87 case OR_CONN_STATE_PROXY_READING: return "proxy reading";
88 case OR_CONN_STATE_HANDSHAKING: return "handshaking";
89 case OR_CONN_STATE_OPEN: return "open";
91 break;
92 case CONN_TYPE_EXIT:
93 switch (state) {
94 case EXIT_CONN_STATE_RESOLVING: return "waiting for dest info";
95 case EXIT_CONN_STATE_CONNECTING: return "connecting";
96 case EXIT_CONN_STATE_OPEN: return "open";
97 case EXIT_CONN_STATE_RESOLVEFAILED: return "resolve failed";
99 break;
100 case CONN_TYPE_AP:
101 switch (state) {
102 case AP_CONN_STATE_SOCKS_WAIT: return "waiting for socks info";
103 case AP_CONN_STATE_NATD_WAIT: return "waiting for natd dest info";
104 case AP_CONN_STATE_RENDDESC_WAIT: return "waiting for rendezvous desc";
105 case AP_CONN_STATE_CONTROLLER_WAIT: return "waiting for controller";
106 case AP_CONN_STATE_CIRCUIT_WAIT: return "waiting for circuit";
107 case AP_CONN_STATE_CONNECT_WAIT: return "waiting for connect response";
108 case AP_CONN_STATE_RESOLVE_WAIT: return "waiting for resolve response";
109 case AP_CONN_STATE_OPEN: return "open";
111 break;
112 case CONN_TYPE_DIR:
113 switch (state) {
114 case DIR_CONN_STATE_CONNECTING: return "connecting";
115 case DIR_CONN_STATE_CLIENT_SENDING: return "client sending";
116 case DIR_CONN_STATE_CLIENT_READING: return "client reading";
117 case DIR_CONN_STATE_SERVER_COMMAND_WAIT: return "waiting for command";
118 case DIR_CONN_STATE_SERVER_WRITING: return "writing";
120 break;
121 case CONN_TYPE_DNSWORKER:
122 switch (state) {
123 case DNSWORKER_STATE_IDLE: return "idle";
124 case DNSWORKER_STATE_BUSY: return "busy";
126 break;
127 case CONN_TYPE_CPUWORKER:
128 switch (state) {
129 case CPUWORKER_STATE_IDLE: return "idle";
130 case CPUWORKER_STATE_BUSY_ONION: return "busy with onion";
132 break;
133 case CONN_TYPE_CONTROL:
134 switch (state) {
135 case CONTROL_CONN_STATE_OPEN_V0: return "open (protocol v0)";
136 case CONTROL_CONN_STATE_OPEN_V1: return "open (protocol v1)";
137 case CONTROL_CONN_STATE_NEEDAUTH_V0:
138 return "waiting for authentication (protocol unknown)";
139 case CONTROL_CONN_STATE_NEEDAUTH_V1:
140 return "waiting for authentication (protocol v1)";
142 break;
145 log_warn(LD_BUG, "Bug: unknown connection state %d (type %d)", state, type);
146 tor_snprintf(buf, sizeof(buf),
147 "unknown state [%d] on unknown [%s] connection",
148 state, conn_type_to_string(type));
149 return buf;
152 /** Allocate space for a new connection_t. This function just initializes
153 * conn; you must call connection_add() to link it into the main array.
155 * Set conn-\>type to <b>type</b>. Set conn-\>s and conn-\>conn_array_index to
156 * -1 to signify they are not yet assigned.
158 * If conn is not a listener type, allocate buffers for it. If it's
159 * an AP type, allocate space to store the socks_request.
161 * Assign a pseudorandom next_circ_id between 0 and 2**15.
163 * Initialize conn's timestamps to now.
165 connection_t *
166 connection_new(int type)
168 static uint32_t n_connections_allocated = 1;
169 connection_t *conn;
170 time_t now = time(NULL);
171 size_t length;
172 uint32_t magic;
174 switch (type) {
175 case CONN_TYPE_OR:
176 length = sizeof(or_connection_t);
177 magic = OR_CONNECTION_MAGIC;
178 break;
179 case CONN_TYPE_EXIT:
180 case CONN_TYPE_AP:
181 length = sizeof(edge_connection_t);
182 magic = EDGE_CONNECTION_MAGIC;
183 break;
184 case CONN_TYPE_DIR:
185 length = sizeof(dir_connection_t);
186 magic = DIR_CONNECTION_MAGIC;
187 break;
188 case CONN_TYPE_CONTROL:
189 length = sizeof(control_connection_t);
190 magic = CONTROL_CONNECTION_MAGIC;
191 break;
192 default:
193 length = sizeof(connection_t);
194 magic = BASE_CONNECTION_MAGIC;
195 break;
198 conn = tor_malloc_zero(length);
199 conn->magic = magic;
200 conn->s = -1; /* give it a default of 'not used' */
201 conn->conn_array_index = -1; /* also default to 'not used' */
203 conn->type = type;
204 if (!connection_is_listener(conn)) { /* listeners never use their buf */
205 conn->inbuf = buf_new();
206 conn->outbuf = buf_new();
208 if (type == CONN_TYPE_AP) {
209 TO_EDGE_CONN(conn)->socks_request =
210 tor_malloc_zero(sizeof(socks_request_t));
212 if (CONN_IS_EDGE(conn)) {
213 TO_EDGE_CONN(conn)->global_identifier = n_connections_allocated++;
215 if (type == CONN_TYPE_OR)
216 TO_OR_CONN(conn)->next_circ_id = crypto_rand_int(1<<15);
218 conn->timestamp_created = now;
219 conn->timestamp_lastread = now;
220 conn->timestamp_lastwritten = now;
222 return conn;
225 /** Tell libevent that we don't care about <b>conn</b> any more. */
226 void
227 connection_unregister(connection_t *conn)
229 if (conn->read_event) {
230 if (event_del(conn->read_event))
231 log_warn(LD_BUG, "Error removing read event for %d", conn->s);
232 tor_free(conn->read_event);
234 if (conn->write_event) {
235 if (event_del(conn->write_event))
236 log_warn(LD_BUG, "Error removing write event for %d", conn->s);
237 tor_free(conn->write_event);
241 /** Deallocate memory used by <b>conn</b>. Deallocate its buffers if
242 * necessary, close its socket if necessary, and mark the directory as dirty
243 * if <b>conn</b> is an OR or OP connection.
245 static void
246 _connection_free(connection_t *conn)
248 void *mem;
249 switch (conn->type) {
250 case CONN_TYPE_OR:
251 tor_assert(conn->magic == OR_CONNECTION_MAGIC);
252 mem = TO_OR_CONN(conn);
253 break;
254 case CONN_TYPE_AP:
255 case CONN_TYPE_EXIT:
256 tor_assert(conn->magic == EDGE_CONNECTION_MAGIC);
257 mem = TO_EDGE_CONN(conn);
258 break;
259 case CONN_TYPE_DIR:
260 tor_assert(conn->magic == DIR_CONNECTION_MAGIC);
261 mem = TO_DIR_CONN(conn);
262 break;
263 case CONN_TYPE_CONTROL:
264 tor_assert(conn->magic == CONTROL_CONNECTION_MAGIC);
265 mem = TO_CONTROL_CONN(conn);
266 break;
267 default:
268 tor_assert(conn->magic == BASE_CONNECTION_MAGIC);
269 mem = conn;
270 break;
273 if (!connection_is_listener(conn)) {
274 buf_free(conn->inbuf);
275 buf_free(conn->outbuf);
278 tor_free(conn->address);
280 if (connection_speaks_cells(conn)) {
281 or_connection_t *or_conn = TO_OR_CONN(conn);
282 if (or_conn->tls) {
283 tor_tls_free(or_conn->tls);
284 or_conn->tls = NULL;
287 tor_free(or_conn->nickname);
289 if (CONN_IS_EDGE(conn)) {
290 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
291 tor_free(edge_conn->chosen_exit_name);
292 tor_free(edge_conn->socks_request);
294 if (conn->type == CONN_TYPE_CONTROL) {
295 control_connection_t *control_conn = TO_CONTROL_CONN(conn);
296 tor_free(control_conn->incoming_cmd);
299 tor_free(conn->read_event); /* Probably already freed by connection_free. */
300 tor_free(conn->write_event); /* Probably already freed by connection_free. */
302 if (conn->type == CONN_TYPE_DIR) {
303 dir_connection_t *dir_conn = TO_DIR_CONN(conn);
304 tor_free(dir_conn->requested_resource);
305 if (dir_conn->zlib_state)
306 tor_zlib_free(dir_conn->zlib_state);
307 if (dir_conn->fingerprint_stack) {
308 SMARTLIST_FOREACH(dir_conn->fingerprint_stack, char *, cp, tor_free(cp));
309 smartlist_free(dir_conn->fingerprint_stack);
311 if (dir_conn->cached_dir)
312 cached_dir_decref(dir_conn->cached_dir);
315 if (conn->s >= 0) {
316 log_debug(LD_NET,"closing fd %d.",conn->s);
317 tor_close_socket(conn->s);
320 if (conn->type == CONN_TYPE_OR &&
321 !tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest)) {
322 log_warn(LD_BUG, "called on OR conn with non-zeroed identity_digest");
323 connection_or_remove_from_identity_map(TO_OR_CONN(conn));
326 memset(conn, 0xAA, sizeof(connection_t)); /* poison memory */
327 tor_free(mem);
330 /** Make sure <b>conn</b> isn't in any of the global conn lists; then free it.
332 void
333 connection_free(connection_t *conn)
335 tor_assert(conn);
336 tor_assert(!connection_is_on_closeable_list(conn));
337 tor_assert(!connection_in_array(conn));
338 if (connection_speaks_cells(conn)) {
339 if (conn->state == OR_CONN_STATE_OPEN)
340 directory_set_dirty();
341 if (!tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest)) {
342 connection_or_remove_from_identity_map(TO_OR_CONN(conn));
345 if (conn->type == CONN_TYPE_CONTROL) {
346 TO_CONTROL_CONN(conn)->event_mask = 0;
347 control_update_global_event_mask();
349 connection_unregister(conn);
350 _connection_free(conn);
353 /** Call _connection_free() on every connection in our array, and release all
354 * storage helpd by connection.c. This is used by cpuworkers and dnsworkers
355 * when they fork, so they don't keep resources held open (especially
356 * sockets).
358 * Don't do the checks in connection_free(), because they will
359 * fail.
361 void
362 connection_free_all(void)
364 int i, n;
365 connection_t **carray;
367 get_connection_array(&carray,&n);
369 /* We don't want to log any messages to controllers. */
370 for (i=0;i<n;i++)
371 if (carray[i]->type == CONN_TYPE_CONTROL)
372 TO_CONTROL_CONN(carray[i])->event_mask = 0;
373 control_update_global_event_mask();
375 /* Unlink everything from the identity map. */
376 connection_or_clear_identity_map();
378 for (i=0;i<n;i++)
379 _connection_free(carray[i]);
381 if (outgoing_addrs) {
382 SMARTLIST_FOREACH(outgoing_addrs, void*, addr, tor_free(addr));
383 smartlist_free(outgoing_addrs);
384 outgoing_addrs = NULL;
388 /** Do any cleanup needed:
389 * - Directory conns that failed to fetch a rendezvous descriptor
390 * need to inform pending rendezvous streams.
391 * - OR conns need to call rep_hist_note_*() to record status.
392 * - AP conns need to send a socks reject if necessary.
393 * - Exit conns need to call connection_dns_remove() if necessary.
394 * - AP and Exit conns need to send an end cell if they can.
395 * - DNS conns need to fail any resolves that are pending on them.
396 * - OR and edge connections need to be unlinked from circuits.
398 void
399 connection_about_to_close_connection(connection_t *conn)
401 circuit_t *circ;
402 dir_connection_t *dir_conn;
403 or_connection_t *or_conn;
404 edge_connection_t *edge_conn;
405 time_t now = time(NULL);
407 assert(conn->marked_for_close);
409 if (CONN_IS_EDGE(conn)) {
410 if (!conn->edge_has_sent_end) {
411 log_warn(LD_BUG, "Harmless bug: Edge connection (marked at %s:%d) "
412 "hasn't sent end yet?",
413 conn->marked_for_close_file, conn->marked_for_close);
414 tor_fragile_assert();
418 switch (conn->type) {
419 case CONN_TYPE_DIR:
420 dir_conn = TO_DIR_CONN(conn);
421 if (conn->state < DIR_CONN_STATE_CLIENT_FINISHED) {
422 /* It's a directory connection and connecting or fetching
423 * failed: forget about this router, and maybe try again. */
424 connection_dir_request_failed(dir_conn);
425 // XXX if it's rend desc we may want to retry -RD
427 if (conn->purpose == DIR_PURPOSE_FETCH_RENDDESC)
428 rend_client_desc_here(dir_conn->rend_query); /* give it a try */
429 /* If this is from BEGIN_DIR, unlink it from the edge_conn and
430 * the or_conn. */
431 if (dir_conn->bridge_conn)
432 connection_dirserv_unlink_from_bridge(dir_conn);
433 break;
434 case CONN_TYPE_OR:
435 or_conn = TO_OR_CONN(conn);
436 /* Remember why we're closing this connection. */
437 if (conn->state != OR_CONN_STATE_OPEN) {
438 if (connection_or_nonopen_was_started_here(or_conn)) {
439 rep_hist_note_connect_failed(or_conn->identity_digest, now);
440 entry_guard_register_connect_status(or_conn->identity_digest,0,now);
441 router_set_status(or_conn->identity_digest, 0);
442 control_event_or_conn_status(or_conn, OR_CONN_EVENT_FAILED,
443 control_tls_error_to_reason(or_conn->tls_error));
445 /* Inform any pending (not attached) circs that they should
446 * give up. */
447 circuit_n_conn_done(TO_OR_CONN(conn), 0);
448 } else if (conn->hold_open_until_flushed) {
449 /* We only set hold_open_until_flushed when we're intentionally
450 * closing a connection. */
451 rep_hist_note_disconnect(or_conn->identity_digest, now);
452 control_event_or_conn_status(or_conn, OR_CONN_EVENT_CLOSED,
453 control_tls_error_to_reason(or_conn->tls_error));
454 } else if (or_conn->identity_digest) {
455 rep_hist_note_connection_died(or_conn->identity_digest, now);
456 control_event_or_conn_status(or_conn, OR_CONN_EVENT_CLOSED,
457 control_tls_error_to_reason(or_conn->tls_error));
459 /* Remove any dir_conns that are blocked on this one. Non-blocked
460 * ones will die when the circuits do. */
461 while (or_conn->blocked_dir_connections) {
462 dir_connection_t *dir_conn = or_conn->blocked_dir_connections;
463 connection_dirserv_unlink_from_bridge(dir_conn);
464 tor_assert(or_conn->blocked_dir_connections != dir_conn);
466 /* Now close all the attached circuits on it. */
467 circuit_unlink_all_from_or_conn(TO_OR_CONN(conn),
468 END_CIRC_REASON_OR_CONN_CLOSED);
469 break;
470 case CONN_TYPE_AP:
471 edge_conn = TO_EDGE_CONN(conn);
472 if (edge_conn->socks_request->has_finished == 0) {
473 /* since conn gets removed right after this function finishes,
474 * there's no point trying to send back a reply at this point. */
475 log_warn(LD_BUG,"Bug: Closing stream (marked at %s:%d) without sending"
476 " back a socks reply.",
477 conn->marked_for_close_file, conn->marked_for_close);
479 if (!edge_conn->end_reason) {
480 log_warn(LD_BUG,"Bug: Closing stream (marked at %s:%d) without having"
481 " set end_reason.",
482 conn->marked_for_close_file, conn->marked_for_close);
484 control_event_stream_status(edge_conn, STREAM_EVENT_CLOSED,
485 edge_conn->end_reason);
486 circ = circuit_get_by_edge_conn(edge_conn);
487 if (circ)
488 circuit_detach_stream(circ, edge_conn);
489 break;
490 case CONN_TYPE_EXIT:
491 edge_conn = TO_EDGE_CONN(conn);
492 circ = circuit_get_by_edge_conn(edge_conn);
493 if (circ)
494 circuit_detach_stream(circ, edge_conn);
495 if (conn->state == EXIT_CONN_STATE_RESOLVING) {
496 connection_dns_remove(edge_conn);
498 /* If we're relaying a dirserv connection, clean up any pointers */
499 if (edge_conn->bridge_for_conn)
500 connection_dirserv_unlink_from_bridge(edge_conn->bridge_for_conn);
501 break;
502 case CONN_TYPE_DNSWORKER:
503 if (conn->state == DNSWORKER_STATE_BUSY) {
504 dns_cancel_pending_resolve(conn->address);
506 break;
510 /** Close the underlying socket for <b>conn</b>, so we don't try to
511 * flush it. Must be used in conjunction with (right before)
512 * connection_mark_for_close().
514 void
515 connection_close_immediate(connection_t *conn)
517 assert_connection_ok(conn,0);
518 if (conn->s < 0) {
519 log_err(LD_BUG,"Bug: Attempt to close already-closed connection.");
520 tor_fragile_assert();
521 return;
523 if (conn->outbuf_flushlen) {
524 log_info(LD_NET,"fd %d, type %s, state %s, %d bytes on outbuf.",
525 conn->s, conn_type_to_string(conn->type),
526 conn_state_to_string(conn->type, conn->state),
527 (int)conn->outbuf_flushlen);
530 connection_unregister(conn);
532 tor_close_socket(conn->s);
533 conn->s = -1;
534 if (!connection_is_listener(conn)) {
535 buf_clear(conn->outbuf);
536 conn->outbuf_flushlen = 0;
540 /** Mark <b>conn</b> to be closed next time we loop through
541 * conn_close_if_marked() in main.c. */
542 void
543 _connection_mark_for_close(connection_t *conn, int line, const char *file)
545 assert_connection_ok(conn,0);
546 tor_assert(line);
547 tor_assert(file);
549 if (conn->marked_for_close) {
550 log(LOG_WARN,LD_BUG,"Duplicate call to connection_mark_for_close at %s:%d"
551 " (first at %s:%d)", file, line, conn->marked_for_close_file,
552 conn->marked_for_close);
553 tor_fragile_assert();
554 return;
557 conn->marked_for_close = line;
558 conn->marked_for_close_file = file;
559 add_connection_to_closeable_list(conn);
561 /* in case we're going to be held-open-til-flushed, reset
562 * the number of seconds since last successful write, so
563 * we get our whole 15 seconds */
564 conn->timestamp_lastwritten = time(NULL);
567 /** Find each connection that has hold_open_until_flushed set to
568 * 1 but hasn't written in the past 15 seconds, and set
569 * hold_open_until_flushed to 0. This means it will get cleaned
570 * up in the next loop through close_if_marked() in main.c.
572 void
573 connection_expire_held_open(void)
575 connection_t **carray, *conn;
576 int n, i;
577 time_t now;
579 now = time(NULL);
581 get_connection_array(&carray, &n);
582 for (i = 0; i < n; ++i) {
583 conn = carray[i];
584 /* If we've been holding the connection open, but we haven't written
585 * for 15 seconds...
587 if (conn->hold_open_until_flushed) {
588 tor_assert(conn->marked_for_close);
589 if (now - conn->timestamp_lastwritten >= 15) {
590 int severity;
591 if (conn->type == CONN_TYPE_EXIT ||
592 (conn->type == CONN_TYPE_DIR &&
593 conn->purpose == DIR_PURPOSE_SERVER))
594 severity = LOG_INFO;
595 else
596 severity = LOG_NOTICE;
597 log_fn(severity, LD_NET,
598 "Giving up on marked_for_close conn that's been flushing "
599 "for 15s (fd %d, type %s, state %s).",
600 conn->s, conn_type_to_string(conn->type),
601 conn_state_to_string(conn->type, conn->state));
602 conn->hold_open_until_flushed = 0;
608 /** Bind a new non-blocking socket listening to
609 * <b>listenaddress</b>:<b>listenport</b>, and add this new connection
610 * (of type <b>type</b>) to the connection array.
612 * If <b>listenaddress</b> includes a port, we bind on that port;
613 * otherwise, we use listenport.
615 static connection_t *
616 connection_create_listener(const char *listenaddress, uint16_t listenport,
617 int type)
619 struct sockaddr_in listenaddr; /* where to bind */
620 char *address = NULL;
621 connection_t *conn;
622 uint16_t usePort;
623 uint32_t addr;
624 int s; /* the socket we're going to make */
625 #ifndef MS_WINDOWS
626 int one=1;
627 #endif
629 memset(&listenaddr,0,sizeof(struct sockaddr_in));
630 if (parse_addr_port(LOG_WARN, listenaddress, &address, &addr, &usePort)<0) {
631 log_warn(LD_CONFIG,
632 "Error parsing/resolving ListenAddress %s", listenaddress);
633 return NULL;
636 if (usePort==0)
637 usePort = listenport;
638 listenaddr.sin_addr.s_addr = htonl(addr);
639 listenaddr.sin_family = AF_INET;
640 listenaddr.sin_port = htons((uint16_t) usePort);
642 log_notice(LD_NET, "Opening %s on %s:%d",
643 conn_type_to_string(type), address, usePort);
645 s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
646 if (s < 0) {
647 log_warn(LD_NET,"Socket creation failed.");
648 goto err;
651 #ifndef MS_WINDOWS
652 /* REUSEADDR on normal places means you can rebind to the port
653 * right after somebody else has let it go. But REUSEADDR on win32
654 * means you can bind to the port _even when somebody else
655 * already has it bound_. So, don't do that on Win32. */
656 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*) &one, sizeof(one));
657 #endif
659 if (bind(s,(struct sockaddr *)&listenaddr,sizeof(listenaddr)) < 0) {
660 const char *helpfulhint = "";
661 int e = tor_socket_errno(s);
662 if (ERRNO_IS_EADDRINUSE(e))
663 helpfulhint = ". Is Tor already running?";
664 log_warn(LD_NET, "Could not bind to %s:%u: %s%s", address, usePort,
665 tor_socket_strerror(e), helpfulhint);
666 tor_close_socket(s);
667 goto err;
670 if (listen(s,SOMAXCONN) < 0) {
671 log_warn(LD_NET, "Could not listen on %s:%u: %s", address, usePort,
672 tor_socket_strerror(tor_socket_errno(s)));
673 tor_close_socket(s);
674 goto err;
677 set_socket_nonblocking(s);
679 conn = connection_new(type);
680 conn->s = s;
681 conn->address = address;
682 address = NULL;
683 conn->port = usePort;
685 if (connection_add(conn) < 0) { /* no space, forget it */
686 log_warn(LD_NET,"connection_add for listener failed. Giving up.");
687 connection_free(conn);
688 goto err;
691 log_debug(LD_NET,"%s listening on port %u.",
692 conn_type_to_string(type), usePort);
694 conn->state = LISTENER_STATE_READY;
695 connection_start_reading(conn);
697 return conn;
699 err:
700 tor_free(address);
701 return NULL;
704 /** Do basic sanity checking on a newly received socket. Return 0
705 * if it looks ok, else return -1. */
706 static int
707 check_sockaddr_in(struct sockaddr *sa, int len, int level)
709 int ok = 1;
710 struct sockaddr_in *sin=(struct sockaddr_in*)sa;
712 if (len != sizeof(struct sockaddr_in)) {
713 log_fn(level, LD_NET, "Length of address not as expected: %d vs %d",
714 len,(int)sizeof(struct sockaddr_in));
715 ok = 0;
717 if (sa->sa_family != AF_INET) {
718 log_fn(level, LD_NET, "Family of address not as expected: %d vs %d",
719 sa->sa_family, AF_INET);
720 ok = 0;
722 if (sin->sin_addr.s_addr == 0 || sin->sin_port == 0) {
723 log_fn(level, LD_NET,
724 "Address for new connection has address/port equal to zero.");
725 ok = 0;
727 return ok ? 0 : -1;
730 /** The listener connection <b>conn</b> told poll() it wanted to read.
731 * Call accept() on conn-\>s, and add the new connection if necessary.
733 static int
734 connection_handle_listener_read(connection_t *conn, int new_type)
736 int news; /* the new socket */
737 connection_t *newconn;
738 /* information about the remote peer when connecting to other routers */
739 struct sockaddr_in remote;
740 char addrbuf[256];
741 /* length of the remote address. Must be whatever accept() needs. */
742 socklen_t remotelen = 256;
743 char tmpbuf[INET_NTOA_BUF_LEN];
744 tor_assert((size_t)remotelen >= sizeof(struct sockaddr_in));
745 memset(addrbuf, 0, sizeof(addrbuf));
747 news = accept(conn->s,(struct sockaddr *)&addrbuf,&remotelen);
748 if (news < 0) { /* accept() error */
749 int e = tor_socket_errno(conn->s);
750 if (ERRNO_IS_ACCEPT_EAGAIN(e)) {
751 return 0; /* he hung up before we could accept(). that's fine. */
752 } else if (ERRNO_IS_ACCEPT_RESOURCE_LIMIT(e)) {
753 log_notice(LD_NET,"accept failed: %s. Dropping incoming connection.",
754 tor_socket_strerror(e));
755 return 0;
757 /* else there was a real error. */
758 log_warn(LD_NET,"accept() failed: %s. Closing listener.",
759 tor_socket_strerror(e));
760 connection_mark_for_close(conn);
761 return -1;
763 log_debug(LD_NET,
764 "Connection accepted on socket %d (child of fd %d).",
765 news,conn->s);
767 set_socket_nonblocking(news);
769 if (check_sockaddr_in((struct sockaddr*)addrbuf, remotelen, LOG_INFO)<0) {
770 log_info(LD_NET,
771 "accept() returned a strange address; trying getsockname().");
772 remotelen=256;
773 memset(addrbuf, 0, sizeof(addrbuf));
774 if (getsockname(news, (struct sockaddr*)addrbuf, &remotelen)<0) {
775 int e = tor_socket_errno(news);
776 log_warn(LD_NET, "getsockname() for new connection failed: %s",
777 tor_socket_strerror(e));
778 } else {
779 if (check_sockaddr_in((struct sockaddr*)addrbuf, remotelen,
780 LOG_WARN) < 0) {
781 log_warn(LD_NET,"Something's wrong with this conn. Closing it.");
782 tor_close_socket(news);
783 return 0;
787 memcpy(&remote, addrbuf, sizeof(struct sockaddr_in));
789 /* process entrance policies here, before we even create the connection */
790 if (new_type == CONN_TYPE_AP) {
791 /* check sockspolicy to see if we should accept it */
792 if (socks_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
793 tor_inet_ntoa(&remote.sin_addr, tmpbuf, sizeof(tmpbuf));
794 log_notice(LD_APP,"Denying socks connection from untrusted address %s.",
795 tmpbuf);
796 tor_close_socket(news);
797 return 0;
800 if (new_type == CONN_TYPE_DIR) {
801 /* check dirpolicy to see if we should accept it */
802 if (dir_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
803 tor_inet_ntoa(&remote.sin_addr, tmpbuf, sizeof(tmpbuf));
804 log_notice(LD_DIRSERV,"Denying dir connection from address %s.",
805 tmpbuf);
806 tor_close_socket(news);
807 return 0;
811 newconn = connection_new(new_type);
812 newconn->s = news;
814 /* remember the remote address */
815 newconn->addr = ntohl(remote.sin_addr.s_addr);
816 newconn->port = ntohs(remote.sin_port);
817 newconn->address = tor_dup_addr(newconn->addr);
819 if (connection_add(newconn) < 0) { /* no space, forget it */
820 connection_free(newconn);
821 return 0; /* no need to tear down the parent */
824 if (connection_init_accepted_conn(newconn, conn->type) < 0) {
825 connection_mark_for_close(newconn);
826 return 0;
828 return 0;
831 /** Initialize states for newly accepted connection <b>conn</b>.
832 * If conn is an OR, start the tls handshake.
833 * If conn is a transparent AP, get its original destination
834 * and place it in circuit_wait.
836 static int
837 connection_init_accepted_conn(connection_t *conn, uint8_t listener_type)
839 connection_start_reading(conn);
841 switch (conn->type) {
842 case CONN_TYPE_OR:
843 control_event_or_conn_status(TO_OR_CONN(conn), OR_CONN_EVENT_NEW, 0);
844 return connection_tls_start_handshake(TO_OR_CONN(conn), 1);
845 case CONN_TYPE_AP:
846 switch (listener_type) {
847 case CONN_TYPE_AP_LISTENER:
848 conn->state = AP_CONN_STATE_SOCKS_WAIT;
849 break;
850 case CONN_TYPE_AP_TRANS_LISTENER:
851 conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
852 return connection_ap_process_transparent(TO_EDGE_CONN(conn));
853 case CONN_TYPE_AP_NATD_LISTENER:
854 conn->state = AP_CONN_STATE_NATD_WAIT;
855 break;
857 break;
858 case CONN_TYPE_DIR:
859 conn->purpose = DIR_PURPOSE_SERVER;
860 conn->state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
861 break;
862 case CONN_TYPE_CONTROL:
863 conn->state = CONTROL_CONN_STATE_NEEDAUTH_V0;
864 break;
866 return 0;
869 /** Take conn, make a nonblocking socket; try to connect to
870 * addr:port (they arrive in *host order*). If fail, return -1. Else
871 * assign s to conn-\>s: if connected return 1, if EAGAIN return 0.
873 * address is used to make the logs useful.
875 * On success, add conn to the list of polled connections.
878 connection_connect(connection_t *conn, const char *address,
879 uint32_t addr, uint16_t port)
881 int s, inprogress = 0;
882 struct sockaddr_in dest_addr;
883 or_options_t *options = get_options();
885 s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
886 if (s < 0) {
887 log_warn(LD_NET,"Error creating network socket: %s",
888 tor_socket_strerror(tor_socket_errno(-1)));
889 return -1;
892 if (options->OutboundBindAddress) {
893 struct sockaddr_in ext_addr;
895 memset(&ext_addr, 0, sizeof(ext_addr));
896 ext_addr.sin_family = AF_INET;
897 ext_addr.sin_port = 0;
898 if (!tor_inet_aton(options->OutboundBindAddress, &ext_addr.sin_addr)) {
899 log_warn(LD_CONFIG,"Outbound bind address '%s' didn't parse. Ignoring.",
900 options->OutboundBindAddress);
901 } else {
902 if (bind(s, (struct sockaddr*)&ext_addr, sizeof(ext_addr)) < 0) {
903 log_warn(LD_NET,"Error binding network socket: %s",
904 tor_socket_strerror(tor_socket_errno(s)));
905 tor_close_socket(s);
906 return -1;
911 set_socket_nonblocking(s);
913 memset(&dest_addr,0,sizeof(dest_addr));
914 dest_addr.sin_family = AF_INET;
915 dest_addr.sin_port = htons(port);
916 dest_addr.sin_addr.s_addr = htonl(addr);
918 log_debug(LD_NET,"Connecting to %s:%u.",escaped_safe_str(address),port);
920 if (connect(s,(struct sockaddr *)&dest_addr,sizeof(dest_addr)) < 0) {
921 int e = tor_socket_errno(s);
922 if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
923 /* yuck. kill it. */
924 log_info(LD_NET,
925 "connect() to %s:%u failed: %s",escaped_safe_str(address),
926 port, tor_socket_strerror(e));
927 tor_close_socket(s);
928 return -1;
929 } else {
930 inprogress = 1;
934 if (!server_mode(options))
935 client_check_address_changed(s);
937 /* it succeeded. we're connected. */
938 log_fn(inprogress?LOG_DEBUG:LOG_INFO, LD_NET,
939 "Connection to %s:%u %s (sock %d).",escaped_safe_str(address),
940 port, inprogress?"in progress":"established", s);
941 conn->s = s;
942 if (connection_add(conn) < 0) /* no space, forget it */
943 return -1;
944 return inprogress ? 0 : 1;
948 * Launch any configured listener connections of type <b>type</b>. (A
949 * listener is configured if <b>port_option</b> is non-zero. If any
950 * ListenAddress configuration options are given in <b>cfg</b>, create a
951 * connection binding to each one. Otherwise, create a single
952 * connection binding to the address <b>default_addr</b>.)
954 * If <b>force</b> is true, close and re-open all listener connections.
955 * Otherwise, only relaunch the listeners of this type if the number of
956 * existing connections is not as configured (e.g., because one died),
957 * or if the existing connections do not match those configured.
959 * Add all old conns that should be closed to <b>replaced_conns</b>.
960 * Add all new connections to <b>new_conns</b>.
962 static int
963 retry_listeners(int type, config_line_t *cfg,
964 int port_option, const char *default_addr, int force,
965 smartlist_t *replaced_conns,
966 smartlist_t *new_conns,
967 int never_open_conns)
969 smartlist_t *launch = smartlist_create();
970 int free_launch_elts = 1;
971 config_line_t *c;
972 int n_conn, i;
973 connection_t *conn;
974 connection_t **carray;
975 config_line_t *line;
977 if (cfg && port_option) {
978 for (c = cfg; c; c = c->next) {
979 smartlist_add(launch, c);
981 free_launch_elts = 0;
982 } else if (port_option) {
983 line = tor_malloc_zero(sizeof(config_line_t));
984 line->key = tor_strdup("");
985 line->value = tor_strdup(default_addr);
986 smartlist_add(launch, line);
990 SMARTLIST_FOREACH(launch, config_line_t *, l,
991 log_fn(LOG_NOTICE, "#%s#%s", l->key, l->value));
994 get_connection_array(&carray,&n_conn);
995 for (i=0; i < n_conn; ++i) {
996 conn = carray[i];
997 if (conn->type != type || conn->marked_for_close)
998 continue;
999 if (force) {
1000 /* It's a listener, and we're relaunching all listeners of this
1001 * type. Close this one. */
1002 log_notice(LD_NET, "Force-closing listener %s on %s:%d",
1003 conn_type_to_string(type), conn->address, conn->port);
1004 connection_close_immediate(conn);
1005 connection_mark_for_close(conn);
1006 continue;
1008 /* Okay, so this is a listener. Is it configured? */
1009 line = NULL;
1010 SMARTLIST_FOREACH(launch, config_line_t *, wanted,
1012 char *address=NULL;
1013 uint16_t port;
1014 if (!parse_addr_port(LOG_WARN, wanted->value, &address, NULL, &port)) {
1015 int addr_matches = !strcasecmp(address, conn->address);
1016 tor_free(address);
1017 if (! port)
1018 port = port_option;
1019 if (port == conn->port && addr_matches) {
1020 line = wanted;
1021 break;
1025 if (! line) {
1026 /* This one isn't configured. Close it. */
1027 log_notice(LD_NET, "Closing no-longer-configured %s on %s:%d",
1028 conn_type_to_string(type), conn->address, conn->port);
1029 if (replaced_conns) {
1030 smartlist_add(replaced_conns, conn);
1031 } else {
1032 connection_close_immediate(conn);
1033 connection_mark_for_close(conn);
1035 } else {
1036 /* It's configured; we don't need to launch it. */
1037 // log_debug(LD_NET, "Already have %s on %s:%d",
1038 // conn_type_to_string(type), conn->address, conn->port);
1039 smartlist_remove(launch, line);
1040 if (free_launch_elts)
1041 config_free_lines(line);
1045 /* Now open all the listeners that are configured but not opened. */
1046 i = 0;
1047 if (!never_open_conns) {
1048 SMARTLIST_FOREACH(launch, config_line_t *, cfg,
1050 conn = connection_create_listener(cfg->value, (uint16_t) port_option,
1051 type);
1052 if (!conn) {
1053 i = -1;
1054 } else {
1055 if (new_conns)
1056 smartlist_add(new_conns, conn);
1061 if (free_launch_elts) {
1062 SMARTLIST_FOREACH(launch, config_line_t *, cfg,
1063 config_free_lines(cfg));
1065 smartlist_free(launch);
1067 return i;
1070 /** (Re)launch listeners for each port you should have open. If
1071 * <b>force</b> is true, close and relaunch all listeners. If <b>force</b>
1072 * is false, then only relaunch listeners when we have the wrong number of
1073 * connections for a given type.
1075 * Add all old conns that should be closed to <b>replaced_conns</b>.
1076 * Add all new connections to <b>new_conns</b>.
1079 retry_all_listeners(int force, smartlist_t *replaced_conns,
1080 smartlist_t *new_conns)
1082 or_options_t *options = get_options();
1084 if (retry_listeners(CONN_TYPE_OR_LISTENER, options->ORListenAddress,
1085 options->ORPort, "0.0.0.0", force,
1086 replaced_conns, new_conns, options->ClientOnly)<0)
1087 return -1;
1088 if (retry_listeners(CONN_TYPE_DIR_LISTENER, options->DirListenAddress,
1089 options->DirPort, "0.0.0.0", force,
1090 replaced_conns, new_conns, 0)<0)
1091 return -1;
1092 if (retry_listeners(CONN_TYPE_AP_LISTENER, options->SocksListenAddress,
1093 options->SocksPort, "127.0.0.1", force,
1094 replaced_conns, new_conns, 0)<0)
1095 return -1;
1096 if (retry_listeners(CONN_TYPE_AP_TRANS_LISTENER, options->TransListenAddress,
1097 options->TransPort, "127.0.0.1", force,
1098 replaced_conns, new_conns, 0)<0)
1099 return -1;
1100 if (retry_listeners(CONN_TYPE_AP_NATD_LISTENER, options->NatdListenAddress,
1101 options->NatdPort, "127.0.0.1", force,
1102 replaced_conns, new_conns, 0)<0)
1103 return -1;
1104 if (retry_listeners(CONN_TYPE_CONTROL_LISTENER,
1105 options->ControlListenAddress,
1106 options->ControlPort, "127.0.0.1", force,
1107 replaced_conns, new_conns, 0)<0)
1108 return -1;
1110 return 0;
1113 /** Return 1 if we should apply rate limiting to <b>conn</b>,
1114 * and 0 otherwise. Right now this just checks if it's an internal
1115 * IP address. */
1116 static int
1117 connection_is_rate_limited(connection_t *conn)
1119 return !is_internal_IP(conn->addr, 0);
1122 extern int global_read_bucket, global_write_bucket;
1124 /** Did our global write bucket run dry last second? If so, we are
1125 * likely to run dry again this second, so be stingy with the tokens
1126 * we just put in. */
1127 static int global_write_bucket_empty_last_second = 0;
1129 /** Helper function to decide how many bytes out of <b>global_bucket</b>
1130 * we're willing to use for this transaction. <b>base</b> is the size
1131 * of a cell on the network; <b>priority</b> says whether we should
1132 * write many of them or just a few; and <b>conn_bucket</b> (if
1133 * non-negative) provides an upper limit for our answer. */
1134 static int
1135 connection_bucket_round_robin(int base, int priority,
1136 int global_bucket, int conn_bucket)
1138 int at_most;
1139 int num_bytes_high = (priority ? 32 : 16) * base;
1140 int num_bytes_low = (priority ? 4 : 2) * base;
1142 /* Do a rudimentary round-robin so one circuit can't hog a connection.
1143 * Pick at most 32 cells, at least 4 cells if possible, and if we're in
1144 * the middle pick 1/8 of the available bandwidth. */
1145 at_most = global_bucket / 8;
1146 at_most -= (at_most % base); /* round down */
1147 if (at_most > num_bytes_high) /* 16 KB, or 8 KB for low-priority */
1148 at_most = num_bytes_high;
1149 else if (at_most < num_bytes_low) /* 2 KB, or 1 KB for low-priority */
1150 at_most = num_bytes_low;
1152 if (at_most > global_bucket)
1153 at_most = global_bucket;
1155 if (conn_bucket >= 0 && at_most > conn_bucket)
1156 at_most = conn_bucket;
1158 if (at_most < 0)
1159 return 0;
1160 return at_most;
1163 /** How many bytes at most can we read onto this connection? */
1164 static int
1165 connection_bucket_read_limit(connection_t *conn)
1167 int base = connection_speaks_cells(conn) ?
1168 CELL_NETWORK_SIZE : RELAY_PAYLOAD_SIZE;
1169 int priority = conn->type != CONN_TYPE_DIR;
1170 int conn_bucket = -1;
1171 if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
1172 or_connection_t *or_conn = TO_OR_CONN(conn);
1173 conn_bucket = or_conn->read_bucket;
1175 if (!connection_is_rate_limited(conn)) {
1176 /* be willing to read on local conns even if our buckets are empty */
1177 return conn_bucket>=0 ? conn_bucket : 1<<14;
1179 return connection_bucket_round_robin(base, priority,
1180 global_read_bucket, conn_bucket);
1183 /** How many bytes at most can we write onto this connection? */
1185 connection_bucket_write_limit(connection_t *conn)
1187 int base = connection_speaks_cells(conn) ?
1188 CELL_NETWORK_SIZE : RELAY_PAYLOAD_SIZE;
1189 int priority = conn->type != CONN_TYPE_DIR;
1191 if (!connection_is_rate_limited(conn)) {
1192 /* be willing to write to local conns even if our buckets are empty */
1193 return conn->outbuf_flushlen;
1195 return connection_bucket_round_robin(base, priority, global_write_bucket,
1196 conn->outbuf_flushlen);
1199 /** Return 1 if the global write bucket is low enough that we shouldn't
1200 * send <b>attempt</b> bytes of low-priority directory stuff out to
1201 * <b>conn</b>. Else return 0.
1203 * Priority is 1 for v1 requests (directories and running-routers),
1204 * and 2 for v2 requests (statuses and descriptors). But see FFFF in
1205 * directory_handle_command_get() for why we don't use priority 2 yet.
1207 * There are a lot of parameters we could use here:
1208 * - global_write_bucket. Low is bad.
1209 * - bandwidthrate. Low is bad.
1210 * - bandwidthburst. Not a big factor?
1211 * - attempt. High is bad.
1212 * - total bytes queued on outbufs. High is bad. But I'm wary of
1213 * using this, since a few slow-flushing queues will pump up the
1214 * number without meaning what we meant to mean. What we really
1215 * mean is "total directory bytes added to outbufs recently", but
1216 * that's harder to quantify and harder to keep track of.
1219 global_write_bucket_low(connection_t *conn, size_t attempt, int priority)
1221 if (authdir_mode(get_options()) && priority>1)
1222 return 0; /* there's always room to answer v2 if we're an auth dir */
1224 if (!connection_is_rate_limited(conn))
1225 return 0; /* local conns don't get limited */
1227 if (global_write_bucket < (int)attempt)
1228 return 1; /* not enough space no matter the priority */
1230 if (global_write_bucket_empty_last_second)
1231 return 1; /* we're already hitting our limits, no more please */
1233 if (priority == 1) { /* old-style v1 query */
1234 /* Could we handle *two* of these requests within the next two seconds? */
1235 int64_t can_write = (int64_t)global_write_bucket
1236 + 2*get_options()->BandwidthRate;
1237 if (can_write < 2*(int64_t)attempt)
1238 return 1;
1239 } else { /* v2 query */
1240 /* no further constraints yet */
1242 return 0;
1245 /** We just read num_read onto conn. Decrement buckets appropriately. */
1246 static void
1247 connection_read_bucket_decrement(connection_t *conn, int num_read)
1249 global_read_bucket -= num_read;
1250 if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
1251 TO_OR_CONN(conn)->read_bucket -= num_read;
1255 /** If we have exhausted our global buckets, or the buckets for conn,
1256 * stop reading. */
1257 static void
1258 connection_consider_empty_read_buckets(connection_t *conn)
1260 if (global_read_bucket <= 0) {
1261 LOG_FN_CONN(conn, (LOG_DEBUG,LD_NET,
1262 "global read bucket exhausted. Pausing."));
1263 conn->wants_to_read = 1;
1264 connection_stop_reading(conn);
1265 return;
1267 if (connection_speaks_cells(conn) &&
1268 conn->state == OR_CONN_STATE_OPEN &&
1269 TO_OR_CONN(conn)->read_bucket <= 0) {
1270 LOG_FN_CONN(conn,
1271 (LOG_DEBUG,LD_NET,"read bucket exhausted. Pausing."));
1272 conn->wants_to_read = 1;
1273 connection_stop_reading(conn);
1277 /** If we have exhausted our global buckets, or the buckets for conn,
1278 * stop writing. */
1279 static void
1280 connection_consider_empty_write_buckets(connection_t *conn)
1282 if (global_write_bucket <= 0) {
1283 LOG_FN_CONN(conn, (LOG_DEBUG,LD_NET,
1284 "global write bucket exhausted. Pausing."));
1285 conn->wants_to_write = 1;
1286 connection_stop_writing(conn);
1287 return;
1289 #if 0
1290 if (connection_speaks_cells(conn) &&
1291 conn->state == OR_CONN_STATE_OPEN &&
1292 TO_OR_CONN(conn)->write_bucket <= 0) {
1293 LOG_FN_CONN(conn,
1294 (LOG_DEBUG,LD_NET,"write bucket exhausted. Pausing."));
1295 conn->wants_to_write = 1;
1296 connection_stop_writing(conn);
1298 #endif
1301 /** Initialize the global read bucket to options->BandwidthBurst. */
1302 void
1303 connection_bucket_init(void)
1305 or_options_t *options = get_options();
1306 /* start it at max traffic */
1307 global_read_bucket = (int)options->BandwidthBurst;
1308 global_write_bucket = (int)options->BandwidthBurst;
1311 /** A second has rolled over; increment buckets appropriately. */
1312 void
1313 connection_bucket_refill(int seconds_elapsed)
1315 int i, n;
1316 connection_t *conn;
1317 connection_t **carray;
1318 or_options_t *options = get_options();
1320 tor_assert(seconds_elapsed >= 0);
1322 /* refill the global buckets */
1323 if (global_read_bucket < (int)options->BandwidthBurst) {
1324 global_read_bucket += (int)options->BandwidthRate*seconds_elapsed;
1325 if (global_read_bucket > (int)options->BandwidthBurst)
1326 global_read_bucket = (int)options->BandwidthBurst;
1327 log(LOG_DEBUG, LD_NET,"global_read_bucket now %d.", global_read_bucket);
1329 if (global_write_bucket < (int)options->BandwidthBurst) {
1330 global_write_bucket_empty_last_second = global_write_bucket == 0;
1331 global_write_bucket += (int)options->BandwidthRate*seconds_elapsed;
1332 if (global_write_bucket > (int)options->BandwidthBurst)
1333 global_write_bucket = (int)options->BandwidthBurst;
1334 log(LOG_DEBUG, LD_NET,"global_write_bucket now %d.", global_write_bucket);
1337 /* refill the per-connection buckets */
1338 get_connection_array(&carray,&n);
1339 for (i=0;i<n;i++) {
1340 conn = carray[i];
1342 if (connection_speaks_cells(conn)) {
1343 or_connection_t *or_conn = TO_OR_CONN(conn);
1344 if (connection_read_bucket_should_increase(or_conn)) {
1345 or_conn->read_bucket += or_conn->bandwidthrate*seconds_elapsed;
1346 if (or_conn->read_bucket > or_conn->bandwidthburst)
1347 or_conn->read_bucket = or_conn->bandwidthburst;
1348 //log_fn(LOG_DEBUG,"Receiver bucket %d now %d.", i,
1349 // conn->read_bucket);
1353 if (conn->wants_to_read == 1 /* it's marked to turn reading back on now */
1354 && global_read_bucket > 0 /* and we're allowed to read */
1355 && (!connection_speaks_cells(conn) ||
1356 conn->state != OR_CONN_STATE_OPEN ||
1357 TO_OR_CONN(conn)->read_bucket > 0)) {
1358 /* and either a non-cell conn or a cell conn with non-empty bucket */
1359 LOG_FN_CONN(conn, (LOG_DEBUG,LD_NET,
1360 "waking up conn (fd %d) for read",conn->s));
1361 conn->wants_to_read = 0;
1362 connection_start_reading(conn);
1364 if (conn->wants_to_write == 1 &&
1365 global_write_bucket > 0) { /* and we're allowed to write */
1366 LOG_FN_CONN(conn, (LOG_DEBUG,LD_NET,
1367 "waking up conn (fd %d) for write",conn->s));
1368 conn->wants_to_write = 0;
1369 connection_start_writing(conn);
1374 /** Is the receiver bucket for connection <b>conn</b> low enough that we
1375 * should add another pile of tokens to it?
1377 static int
1378 connection_read_bucket_should_increase(or_connection_t *conn)
1380 tor_assert(conn);
1382 if (conn->_base.state != OR_CONN_STATE_OPEN)
1383 return 0; /* only open connections play the rate limiting game */
1384 if (conn->read_bucket >= conn->bandwidthburst)
1385 return 0;
1387 return 1;
1390 /** Read bytes from conn-\>s and process them.
1392 * This function gets called from conn_read() in main.c, either
1393 * when poll() has declared that conn wants to read, or (for OR conns)
1394 * when there are pending TLS bytes.
1396 * It calls connection_read_to_buf() to bring in any new bytes,
1397 * and then calls connection_process_inbuf() to process them.
1399 * Mark the connection and return -1 if you want to close it, else
1400 * return 0.
1403 connection_handle_read(connection_t *conn)
1405 int max_to_read=-1, try_to_read;
1407 if (conn->marked_for_close)
1408 return 0; /* do nothing */
1410 conn->timestamp_lastread = time(NULL);
1412 switch (conn->type) {
1413 case CONN_TYPE_OR_LISTENER:
1414 return connection_handle_listener_read(conn, CONN_TYPE_OR);
1415 case CONN_TYPE_AP_LISTENER:
1416 case CONN_TYPE_AP_TRANS_LISTENER:
1417 case CONN_TYPE_AP_NATD_LISTENER:
1418 return connection_handle_listener_read(conn, CONN_TYPE_AP);
1419 case CONN_TYPE_DIR_LISTENER:
1420 return connection_handle_listener_read(conn, CONN_TYPE_DIR);
1421 case CONN_TYPE_CONTROL_LISTENER:
1422 return connection_handle_listener_read(conn, CONN_TYPE_CONTROL);
1425 loop_again:
1426 try_to_read = max_to_read;
1427 tor_assert(!conn->marked_for_close);
1428 if (connection_read_to_buf(conn, &max_to_read) < 0) {
1429 /* There's a read error; kill the connection.*/
1430 connection_close_immediate(conn); /* Don't flush; connection is dead. */
1431 if (CONN_IS_EDGE(conn)) {
1432 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
1433 connection_edge_end_errno(edge_conn, edge_conn->cpath_layer);
1434 if (edge_conn->socks_request) /* broken, don't send a socks reply back */
1435 edge_conn->socks_request->has_finished = 1;
1437 connection_mark_for_close(conn);
1438 return -1;
1440 if (CONN_IS_EDGE(conn) && try_to_read != max_to_read) {
1441 /* instruct it not to try to package partial cells. */
1442 if (connection_process_inbuf(conn, 0) < 0) {
1443 return -1;
1445 if (!conn->marked_for_close &&
1446 connection_is_reading(conn) &&
1447 !conn->inbuf_reached_eof &&
1448 max_to_read > 0)
1449 goto loop_again; /* try reading again, in case more is here now */
1451 /* one last try, packaging partial cells and all. */
1452 if (!conn->marked_for_close &&
1453 connection_process_inbuf(conn, 1) < 0) {
1454 return -1;
1456 if (!conn->marked_for_close &&
1457 conn->inbuf_reached_eof &&
1458 connection_reached_eof(conn) < 0) {
1459 return -1;
1461 return 0;
1464 /** Pull in new bytes from conn-\>s onto conn-\>inbuf, either
1465 * directly or via TLS. Reduce the token buckets by the number of
1466 * bytes read.
1468 * If *max_to_read is -1, then decide it ourselves, else go with the
1469 * value passed to us. When returning, if it's changed, subtract the
1470 * number of bytes we read from *max_to_read.
1472 * Return -1 if we want to break conn, else return 0.
1474 static int
1475 connection_read_to_buf(connection_t *conn, int *max_to_read)
1477 int result, at_most = *max_to_read;
1478 size_t bytes_in_buf, more_to_read;
1479 size_t n_read = 0, n_written = 0;
1481 if (at_most == -1) { /* we need to initialize it */
1482 /* how many bytes are we allowed to read? */
1483 at_most = connection_bucket_read_limit(conn);
1486 bytes_in_buf = buf_capacity(conn->inbuf) - buf_datalen(conn->inbuf);
1487 again:
1488 if ((size_t)at_most > bytes_in_buf && bytes_in_buf >= 1024) {
1489 more_to_read = at_most - bytes_in_buf;
1490 at_most = bytes_in_buf;
1491 } else {
1492 more_to_read = 0;
1495 if (connection_speaks_cells(conn) &&
1496 conn->state > OR_CONN_STATE_PROXY_READING) {
1497 int pending;
1498 or_connection_t *or_conn = TO_OR_CONN(conn);
1499 if (conn->state == OR_CONN_STATE_HANDSHAKING) {
1500 /* continue handshaking even if global token bucket is empty */
1501 return connection_tls_continue_handshake(or_conn);
1504 log_debug(LD_NET,
1505 "%d: starting, inbuf_datalen %d (%d pending in tls object)."
1506 " at_most %d.",
1507 conn->s,(int)buf_datalen(conn->inbuf),
1508 tor_tls_get_pending_bytes(or_conn->tls), at_most);
1510 /* else open, or closing */
1511 result = read_to_buf_tls(or_conn->tls, at_most, conn->inbuf);
1512 if (TOR_TLS_IS_ERROR(result) || result == TOR_TLS_CLOSE)
1513 or_conn->tls_error = result;
1514 else
1515 or_conn->tls_error = 0;
1517 switch (result) {
1518 case TOR_TLS_CLOSE:
1519 log_info(LD_NET,"TLS connection closed on read. Closing. "
1520 "(Nickname %s, address %s",
1521 or_conn->nickname ? or_conn->nickname : "not set",
1522 conn->address);
1523 return result;
1524 CASE_TOR_TLS_ERROR_ANY:
1525 log_info(LD_NET,"tls error. breaking (nickname %s, address %s).",
1526 or_conn->nickname ? or_conn->nickname : "not set",
1527 conn->address);
1528 return result;
1529 case TOR_TLS_WANTWRITE:
1530 connection_start_writing(conn);
1531 return 0;
1532 case TOR_TLS_WANTREAD: /* we're already reading */
1533 case TOR_TLS_DONE: /* no data read, so nothing to process */
1534 result = 0;
1535 break; /* so we call bucket_decrement below */
1536 default:
1537 break;
1539 pending = tor_tls_get_pending_bytes(or_conn->tls);
1540 if (pending) {
1541 /* If we have any pending bytes, we read them now. This *can*
1542 * take us over our read allotment, but really we shouldn't be
1543 * believing that SSL bytes are the same as TCP bytes anyway. */
1544 int r2 = read_to_buf_tls(or_conn->tls, pending, conn->inbuf);
1545 if (r2<0) {
1546 log_warn(LD_BUG, "Bug: apparently, reading pending bytes can fail.");
1547 return -1;
1548 } else {
1549 result += r2;
1553 tor_tls_get_n_raw_bytes(or_conn->tls, &n_read, &n_written);
1554 log_debug(LD_GENERAL, "After TLS read of %d: %ld read, %ld written",
1555 result, (long)n_read, (long)n_written);
1556 } else {
1557 int reached_eof = 0;
1558 CONN_LOG_PROTECT(conn,
1559 result = read_to_buf(conn->s, at_most, conn->inbuf, &reached_eof));
1560 if (reached_eof)
1561 conn->inbuf_reached_eof = 1;
1563 // log_fn(LOG_DEBUG,"read_to_buf returned %d.",read_result);
1565 if (result < 0)
1566 return -1;
1567 n_read = (size_t) result;
1570 if (n_read > 0) { /* change *max_to_read */
1571 *max_to_read = at_most - n_read;
1574 if (conn->type == CONN_TYPE_AP) {
1575 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
1576 edge_conn->n_read += n_read;
1579 if (connection_is_rate_limited(conn)) {
1580 /* For non-local IPs, remember if we flushed any bytes over the wire. */
1581 time_t now = time(NULL);
1582 if (n_read > 0) {
1583 rep_hist_note_bytes_read(n_read, now);
1584 connection_read_bucket_decrement(conn, n_read);
1586 if (n_written > 0) {
1587 rep_hist_note_bytes_written(n_written, now);
1588 global_write_bucket -= n_written;
1592 if (more_to_read && result == at_most) {
1593 bytes_in_buf = buf_capacity(conn->inbuf) - buf_datalen(conn->inbuf);
1594 tor_assert(bytes_in_buf < 1024);
1595 at_most = more_to_read;
1596 goto again;
1599 /* Call even if result is 0, since the global read bucket may
1600 * have reached 0 on a different conn, and this guy needs to
1601 * know to stop reading. */
1602 connection_consider_empty_read_buckets(conn);
1603 if (n_written > 0 && connection_is_writing(conn))
1604 connection_consider_empty_write_buckets(conn);
1606 return 0;
1609 /** A pass-through to fetch_from_buf. */
1611 connection_fetch_from_buf(char *string, size_t len, connection_t *conn)
1613 return fetch_from_buf(string, len, conn->inbuf);
1616 /** Return conn-\>outbuf_flushlen: how many bytes conn wants to flush
1617 * from its outbuf. */
1619 connection_wants_to_flush(connection_t *conn)
1621 return conn->outbuf_flushlen;
1624 /** Are there too many bytes on edge connection <b>conn</b>'s outbuf to
1625 * send back a relay-level sendme yet? Return 1 if so, 0 if not. Used by
1626 * connection_edge_consider_sending_sendme().
1629 connection_outbuf_too_full(connection_t *conn)
1631 return (conn->outbuf_flushlen > 10*CELL_PAYLOAD_SIZE);
1634 /** Try to flush more bytes onto conn-\>s.
1636 * This function gets called either from conn_write() in main.c
1637 * when poll() has declared that conn wants to write, or below
1638 * from connection_write_to_buf() when an entire TLS record is ready.
1640 * Update conn-\>timestamp_lastwritten to now, and call flush_buf
1641 * or flush_buf_tls appropriately. If it succeeds and there are no more
1642 * more bytes on conn->outbuf, then call connection_finished_flushing
1643 * on it too.
1645 * If <b>force</b>, then write as many bytes as possible, ignoring bandwidth
1646 * limits. (Used for flushing messages to controller connections on fatal
1647 * errors.)
1649 * Mark the connection and return -1 if you want to close it, else
1650 * return 0.
1653 connection_handle_write(connection_t *conn, int force)
1655 int e;
1656 socklen_t len=sizeof(e);
1657 int result;
1658 int max_to_write;
1659 time_t now = time(NULL);
1660 size_t n_read = 0, n_written = 0;
1662 tor_assert(!connection_is_listener(conn));
1664 if (conn->marked_for_close || conn->s < 0)
1665 return 0; /* do nothing */
1667 conn->timestamp_lastwritten = now;
1669 /* Sometimes, "writable" means "connected". */
1670 if (connection_state_is_connecting(conn)) {
1671 if (getsockopt(conn->s, SOL_SOCKET, SO_ERROR, (void*)&e, &len) < 0) {
1672 log_warn(LD_BUG,
1673 "getsockopt() syscall failed?! Please report to tor-ops.");
1674 if (CONN_IS_EDGE(conn))
1675 connection_edge_end_errno(TO_EDGE_CONN(conn),
1676 TO_EDGE_CONN(conn)->cpath_layer);
1677 connection_mark_for_close(conn);
1678 return -1;
1680 if (e) {
1681 /* some sort of error, but maybe just inprogress still */
1682 if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
1683 log_info(LD_NET,"in-progress connect failed. Removing.");
1684 if (CONN_IS_EDGE(conn))
1685 connection_edge_end_errno(TO_EDGE_CONN(conn),
1686 TO_EDGE_CONN(conn)->cpath_layer);
1688 connection_close_immediate(conn);
1689 connection_mark_for_close(conn);
1690 /* it's safe to pass OPs to router_set_status(), since it just
1691 * ignores unrecognized routers
1693 if (conn->type == CONN_TYPE_OR && !get_options()->HttpsProxy)
1694 router_set_status(TO_OR_CONN(conn)->identity_digest, 0);
1695 return -1;
1696 } else {
1697 return 0; /* no change, see if next time is better */
1700 /* The connection is successful. */
1701 if (connection_finished_connecting(conn)<0)
1702 return -1;
1705 max_to_write = force ? (int)conn->outbuf_flushlen
1706 : connection_bucket_write_limit(conn);
1708 if (connection_speaks_cells(conn) &&
1709 conn->state > OR_CONN_STATE_PROXY_READING) {
1710 or_connection_t *or_conn = TO_OR_CONN(conn);
1711 if (conn->state == OR_CONN_STATE_HANDSHAKING) {
1712 connection_stop_writing(conn);
1713 if (connection_tls_continue_handshake(or_conn) < 0) {
1714 /* Don't flush; connection is dead. */
1715 connection_close_immediate(conn);
1716 connection_mark_for_close(conn);
1717 return -1;
1719 return 0;
1722 /* else open, or closing */
1723 result = flush_buf_tls(or_conn->tls, conn->outbuf,
1724 max_to_write, &conn->outbuf_flushlen);
1725 switch (result) {
1726 CASE_TOR_TLS_ERROR_ANY:
1727 case TOR_TLS_CLOSE:
1728 log_info(LD_NET,result!=TOR_TLS_CLOSE?
1729 "tls error. breaking.":"TLS connection closed on flush");
1730 /* Don't flush; connection is dead. */
1731 connection_close_immediate(conn);
1732 connection_mark_for_close(conn);
1733 return -1;
1734 case TOR_TLS_WANTWRITE:
1735 log_debug(LD_NET,"wanted write.");
1736 /* we're already writing */
1737 return 0;
1738 case TOR_TLS_WANTREAD:
1739 /* Make sure to avoid a loop if the receive buckets are empty. */
1740 log_debug(LD_NET,"wanted read.");
1741 if (!connection_is_reading(conn)) {
1742 connection_stop_writing(conn);
1743 conn->wants_to_write = 1;
1744 /* we'll start reading again when the next second arrives,
1745 * and then also start writing again.
1748 /* else no problem, we're already reading */
1749 return 0;
1750 /* case TOR_TLS_DONE:
1751 * for TOR_TLS_DONE, fall through to check if the flushlen
1752 * is empty, so we can stop writing.
1756 tor_tls_get_n_raw_bytes(or_conn->tls, &n_read, &n_written);
1757 log_debug(LD_GENERAL, "After TLS write of %d: %ld read, %ld written",
1758 result, (long)n_read, (long)n_written);
1759 } else {
1760 CONN_LOG_PROTECT(conn,
1761 result = flush_buf(conn->s, conn->outbuf,
1762 max_to_write, &conn->outbuf_flushlen));
1763 if (result < 0) {
1764 if (CONN_IS_EDGE(conn))
1765 connection_edge_end_errno(TO_EDGE_CONN(conn),
1766 TO_EDGE_CONN(conn)->cpath_layer);
1768 connection_close_immediate(conn); /* Don't flush; connection is dead. */
1769 connection_mark_for_close(conn);
1770 return -1;
1772 n_written = (size_t) result;
1775 if (conn->type == CONN_TYPE_AP) {
1776 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
1777 edge_conn->n_written += n_written;
1780 if (connection_is_rate_limited(conn)) {
1781 /* For non-local IPs, remember if we flushed any bytes over the wire. */
1782 time_t now = time(NULL);
1783 if (n_written > 0) {
1784 rep_hist_note_bytes_written(n_written, now);
1785 global_write_bucket -= n_written;
1787 if (n_read > 0) {
1788 rep_hist_note_bytes_read(n_read, now);
1789 connection_read_bucket_decrement(conn, n_read);
1793 if (result > 0) {
1794 /* If we wrote any bytes from our buffer, then call the appropriate
1795 * functions. */
1796 if (connection_flushed_some(conn) < 0)
1797 connection_mark_for_close(conn);
1800 if (!connection_wants_to_flush(conn)) { /* it's done flushing */
1801 if (connection_finished_flushing(conn) < 0) {
1802 /* already marked */
1803 return -1;
1805 return 0;
1808 /* Call even if result is 0, since the global write bucket may
1809 * have reached 0 on a different conn, and this guy needs to
1810 * know to stop writing. */
1811 connection_consider_empty_write_buckets(conn);
1812 if (n_read > 0 && connection_is_reading(conn))
1813 connection_consider_empty_read_buckets(conn);
1815 return 0;
1818 /** Openssl TLS record size is 16383; this is close. The goal here is to
1819 * push data out as soon as we know there's enough for a TLS record, so
1820 * during periods of high load we won't read entire megabytes from
1821 * input before pushing any data out. It also has the feature of not
1822 * growing huge outbufs unless something is slow. */
1823 #define MIN_TLS_FLUSHLEN 15872
1825 /** Append <b>len</b> bytes of <b>string</b> onto <b>conn</b>'s
1826 * outbuf, and ask it to start writing.
1828 * If <b>zlib</b> is nonzero, this is a directory connection that should get
1829 * its contents compressed or decompressed as they're written. If zlib is
1830 * negative, this is the last data to be compressed, and the connection's zlib
1831 * state should be flushed.
1833 * If it's an OR conn and an entire TLS record is ready, then try to
1834 * flush the record now. Similarly, if it's a local control connection
1835 * and a 64k chunk is ready, try to flush it all, so we don't end up with
1836 * many megabytes of controller info queued at once.
1838 void
1839 _connection_write_to_buf_impl(const char *string, size_t len,
1840 connection_t *conn, int zlib)
1842 int r;
1843 size_t old_datalen;
1844 if (!len)
1845 return;
1846 /* if it's marked for close, only allow write if we mean to flush it */
1847 if (conn->marked_for_close && !conn->hold_open_until_flushed)
1848 return;
1850 old_datalen = buf_datalen(conn->outbuf);
1851 if (zlib) {
1852 dir_connection_t *dir_conn = TO_DIR_CONN(conn);
1853 int done = zlib < 0;
1854 CONN_LOG_PROTECT(conn, r = write_to_buf_zlib(conn->outbuf,
1855 dir_conn->zlib_state,
1856 string, len, done));
1857 } else {
1858 CONN_LOG_PROTECT(conn, r = write_to_buf(string, len, conn->outbuf));
1860 if (r < 0) {
1861 if (CONN_IS_EDGE(conn)) {
1862 /* if it failed, it means we have our package/delivery windows set
1863 wrong compared to our max outbuf size. close the whole circuit. */
1864 log_warn(LD_NET,
1865 "write_to_buf failed. Closing circuit (fd %d).", conn->s);
1866 circuit_mark_for_close(circuit_get_by_edge_conn(TO_EDGE_CONN(conn)),
1867 END_CIRC_REASON_INTERNAL);
1868 } else {
1869 log_warn(LD_NET,
1870 "write_to_buf failed. Closing connection (fd %d).", conn->s);
1871 connection_mark_for_close(conn);
1873 return;
1876 connection_start_writing(conn);
1877 if (zlib) {
1878 conn->outbuf_flushlen += buf_datalen(conn->outbuf) - old_datalen;
1879 } else {
1880 int extra = 0;
1881 conn->outbuf_flushlen += len;
1883 if (conn->type == CONN_TYPE_OR &&
1884 conn->outbuf_flushlen-len < MIN_TLS_FLUSHLEN &&
1885 conn->outbuf_flushlen >= MIN_TLS_FLUSHLEN) {
1886 extra = conn->outbuf_flushlen - MIN_TLS_FLUSHLEN;
1887 conn->outbuf_flushlen = MIN_TLS_FLUSHLEN;
1888 } else if (conn->type == CONN_TYPE_CONTROL &&
1889 !connection_is_rate_limited(conn) &&
1890 conn->outbuf_flushlen-len < 1<<16 &&
1891 conn->outbuf_flushlen >= 1<<16) {
1892 /* just try to flush all of it */
1893 } else
1894 return; /* no need to try flushing */
1896 if (connection_handle_write(conn, 0) < 0) {
1897 if (!conn->marked_for_close) {
1898 /* this connection is broken. remove it. */
1899 log_warn(LD_BUG, "Bug: unhandled error on write for "
1900 "conn (type %d, fd %d); removing",
1901 conn->type, conn->s);
1902 tor_fragile_assert();
1903 /* do a close-immediate here, so we don't try to flush */
1904 connection_close_immediate(conn);
1906 return;
1908 if (extra) {
1909 conn->outbuf_flushlen += extra;
1910 connection_start_writing(conn);
1915 /** Return the conn to addr/port that has the most recent
1916 * timestamp_created, or NULL if no such conn exists. */
1917 or_connection_t *
1918 connection_or_exact_get_by_addr_port(uint32_t addr, uint16_t port)
1920 int i, n;
1921 connection_t *conn;
1922 or_connection_t *best=NULL;
1923 connection_t **carray;
1925 get_connection_array(&carray,&n);
1926 for (i=0;i<n;i++) {
1927 conn = carray[i];
1928 if (conn->type == CONN_TYPE_OR &&
1929 conn->addr == addr &&
1930 conn->port == port &&
1931 !conn->marked_for_close &&
1932 (!best || best->_base.timestamp_created < conn->timestamp_created))
1933 best = TO_OR_CONN(conn);
1935 return best;
1938 /** Return a connection with given type, address, port, and purpose;
1939 * or NULL if no such connection exists. */
1940 connection_t *
1941 connection_get_by_type_addr_port_purpose(int type,
1942 uint32_t addr, uint16_t port,
1943 int purpose)
1945 int i, n;
1946 connection_t *conn;
1947 connection_t **carray;
1949 get_connection_array(&carray,&n);
1950 for (i=0;i<n;i++) {
1951 conn = carray[i];
1952 if (conn->type == type &&
1953 conn->addr == addr &&
1954 conn->port == port &&
1955 conn->purpose == purpose &&
1956 !conn->marked_for_close)
1957 return conn;
1959 return NULL;
1962 /** Return the stream with id <b>id</b> if it is not already marked for
1963 * close.
1965 edge_connection_t *
1966 connection_get_by_global_id(uint32_t id)
1968 int i, n;
1969 connection_t *conn;
1970 connection_t **carray;
1972 get_connection_array(&carray,&n);
1973 for (i=0;i<n;i++) {
1974 conn = carray[i];
1975 if (CONN_IS_EDGE(conn) && TO_EDGE_CONN(conn)->global_identifier == id) {
1976 if (!conn->marked_for_close)
1977 return TO_EDGE_CONN(conn);
1978 else
1979 return NULL;
1982 return NULL;
1985 /** Return a connection of type <b>type</b> that is not marked for close.
1987 connection_t *
1988 connection_get_by_type(int type)
1990 int i, n;
1991 connection_t *conn;
1992 connection_t **carray;
1994 get_connection_array(&carray,&n);
1995 for (i=0;i<n;i++) {
1996 conn = carray[i];
1997 if (conn->type == type && !conn->marked_for_close)
1998 return conn;
2000 return NULL;
2003 /** Return a connection of type <b>type</b> that is in state <b>state</b>,
2004 * and that is not marked for close.
2006 connection_t *
2007 connection_get_by_type_state(int type, int state)
2009 int i, n;
2010 connection_t *conn;
2011 connection_t **carray;
2013 get_connection_array(&carray,&n);
2014 for (i=0;i<n;i++) {
2015 conn = carray[i];
2016 if (conn->type == type && conn->state == state && !conn->marked_for_close)
2017 return conn;
2019 return NULL;
2022 /** Return the connection of type <b>type</b> that is in state
2023 * <b>state</b>, that was written to least recently, and that is not
2024 * marked for close.
2026 connection_t *
2027 connection_get_by_type_state_lastwritten(int type, int state)
2029 int i, n;
2030 connection_t *conn, *best=NULL;
2031 connection_t **carray;
2033 get_connection_array(&carray,&n);
2034 for (i=0;i<n;i++) {
2035 conn = carray[i];
2036 if (conn->type == type && conn->state == state && !conn->marked_for_close)
2037 if (!best || conn->timestamp_lastwritten < best->timestamp_lastwritten)
2038 best = conn;
2040 return best;
2043 /** Return a connection of type <b>type</b> that has rendquery equal
2044 * to <b>rendquery</b>, and that is not marked for close. If state
2045 * is non-zero, conn must be of that state too.
2047 connection_t *
2048 connection_get_by_type_state_rendquery(int type, int state,
2049 const char *rendquery)
2051 int i, n;
2052 connection_t *conn;
2053 connection_t **carray;
2055 tor_assert(type == CONN_TYPE_DIR ||
2056 type == CONN_TYPE_AP || type == CONN_TYPE_EXIT);
2058 get_connection_array(&carray,&n);
2059 for (i=0;i<n;i++) {
2060 conn = carray[i];
2061 if (conn->type == type &&
2062 !conn->marked_for_close &&
2063 (!state || state == conn->state)) {
2064 if (type == CONN_TYPE_DIR &&
2065 rend_cmp_service_ids(rendquery, TO_DIR_CONN(conn)->rend_query))
2066 return conn;
2067 else if (CONN_IS_EDGE(conn) &&
2068 rend_cmp_service_ids(rendquery, TO_EDGE_CONN(conn)->rend_query))
2069 return conn;
2072 return NULL;
2075 /** Return an open, non-marked connection of a given type and purpose, or NULL
2076 * if no such connection exists. */
2077 connection_t *
2078 connection_get_by_type_purpose(int type, int purpose)
2080 int i, n;
2081 connection_t *conn;
2082 connection_t **carray;
2084 get_connection_array(&carray,&n);
2085 for (i=0;i<n;i++) {
2086 conn = carray[i];
2087 if (conn->type == type &&
2088 !conn->marked_for_close &&
2089 (purpose == conn->purpose))
2090 return conn;
2092 return NULL;
2095 /** Return 1 if <b>conn</b> is a listener conn, else return 0. */
2097 connection_is_listener(connection_t *conn)
2099 if (conn->type == CONN_TYPE_OR_LISTENER ||
2100 conn->type == CONN_TYPE_AP_LISTENER ||
2101 conn->type == CONN_TYPE_AP_TRANS_LISTENER ||
2102 conn->type == CONN_TYPE_AP_NATD_LISTENER ||
2103 conn->type == CONN_TYPE_DIR_LISTENER ||
2104 conn->type == CONN_TYPE_CONTROL_LISTENER)
2105 return 1;
2106 return 0;
2109 /** Return 1 if <b>conn</b> is in state "open" and is not marked
2110 * for close, else return 0.
2113 connection_state_is_open(connection_t *conn)
2115 tor_assert(conn);
2117 if (conn->marked_for_close)
2118 return 0;
2120 if ((conn->type == CONN_TYPE_OR && conn->state == OR_CONN_STATE_OPEN) ||
2121 (conn->type == CONN_TYPE_AP && conn->state == AP_CONN_STATE_OPEN) ||
2122 (conn->type == CONN_TYPE_EXIT && conn->state == EXIT_CONN_STATE_OPEN) ||
2123 (conn->type == CONN_TYPE_CONTROL &&
2124 (conn->state == CONTROL_CONN_STATE_OPEN_V0 ||
2125 conn->state == CONTROL_CONN_STATE_OPEN_V1)))
2126 return 1;
2128 return 0;
2131 /** Return 1 if conn is in 'connecting' state, else return 0. */
2133 connection_state_is_connecting(connection_t *conn)
2135 tor_assert(conn);
2137 if (conn->marked_for_close)
2138 return 0;
2139 switch (conn->type)
2141 case CONN_TYPE_OR:
2142 return conn->state == OR_CONN_STATE_CONNECTING;
2143 case CONN_TYPE_EXIT:
2144 return conn->state == EXIT_CONN_STATE_CONNECTING;
2145 case CONN_TYPE_DIR:
2146 return conn->state == DIR_CONN_STATE_CONNECTING;
2149 return 0;
2152 /** Allocates a base64'ed authenticator for use in http or https
2153 * auth, based on the input string <b>authenticator</b>. Returns it
2154 * if success, else returns NULL. */
2155 char *
2156 alloc_http_authenticator(const char *authenticator)
2158 /* an authenticator in Basic authentication
2159 * is just the string "username:password" */
2160 const int authenticator_length = strlen(authenticator);
2161 /* The base64_encode function needs a minimum buffer length
2162 * of 66 bytes. */
2163 const int base64_authenticator_length = (authenticator_length/48+1)*66;
2164 char *base64_authenticator = tor_malloc(base64_authenticator_length);
2165 if (base64_encode(base64_authenticator, base64_authenticator_length,
2166 authenticator, authenticator_length) < 0) {
2167 tor_free(base64_authenticator); /* free and set to null */
2168 } else {
2169 /* remove extra \n at end of encoding */
2170 base64_authenticator[strlen(base64_authenticator) - 1] = 0;
2172 return base64_authenticator;
2175 /** Given a socket handle, check whether the local address (sockname) of the
2176 * socket is one that we've connected from before. If so, double-check
2177 * whether our address has changed and we need to generate keys. If we do,
2178 * call init_keys().
2180 static void
2181 client_check_address_changed(int sock)
2183 uint32_t iface_ip, ip_out;
2184 struct sockaddr_in out_addr;
2185 socklen_t out_addr_len = sizeof(out_addr);
2186 uint32_t *ip;
2188 if (!last_interface_ip)
2189 get_interface_address(LOG_INFO, &last_interface_ip);
2190 if (!outgoing_addrs)
2191 outgoing_addrs = smartlist_create();
2193 if (getsockname(sock, (struct sockaddr*)&out_addr, &out_addr_len)<0) {
2194 int e = tor_socket_errno(sock);
2195 log_warn(LD_NET, "getsockname() to check for address change failed: %s",
2196 tor_socket_strerror(e));
2197 return;
2200 /* Okay. If we've used this address previously, we're okay. */
2201 ip_out = ntohl(out_addr.sin_addr.s_addr);
2202 SMARTLIST_FOREACH(outgoing_addrs, uint32_t*, ip,
2203 if (*ip == ip_out) return;
2206 /* Uh-oh. We haven't connected from this address before. Has the interface
2207 * address changed? */
2208 if (get_interface_address(LOG_INFO, &iface_ip)<0)
2209 return;
2210 ip = tor_malloc(sizeof(uint32_t));
2211 *ip = ip_out;
2213 if (iface_ip == last_interface_ip) {
2214 /* Nope, it hasn't changed. Add this address to the list. */
2215 smartlist_add(outgoing_addrs, ip);
2216 } else {
2217 /* The interface changed. We're a client, so we need to regenerate our
2218 * keys. First, reset the state. */
2219 log(LOG_NOTICE, LD_NET, "Our IP has changed. Rotating keys...");
2220 last_interface_ip = iface_ip;
2221 SMARTLIST_FOREACH(outgoing_addrs, void*, ip, tor_free(ip));
2222 smartlist_clear(outgoing_addrs);
2223 smartlist_add(outgoing_addrs, ip);
2224 /* Okay, now change our keys. */
2225 ip_address_changed(1);
2229 /** Process new bytes that have arrived on conn-\>inbuf.
2231 * This function just passes conn to the connection-specific
2232 * connection_*_process_inbuf() function. It also passes in
2233 * package_partial if wanted.
2235 static int
2236 connection_process_inbuf(connection_t *conn, int package_partial)
2238 tor_assert(conn);
2240 switch (conn->type) {
2241 case CONN_TYPE_OR:
2242 return connection_or_process_inbuf(TO_OR_CONN(conn));
2243 case CONN_TYPE_EXIT:
2244 case CONN_TYPE_AP:
2245 return connection_edge_process_inbuf(TO_EDGE_CONN(conn),
2246 package_partial);
2247 case CONN_TYPE_DIR:
2248 return connection_dir_process_inbuf(TO_DIR_CONN(conn));
2249 case CONN_TYPE_DNSWORKER:
2250 return connection_dns_process_inbuf(conn);
2251 case CONN_TYPE_CPUWORKER:
2252 return connection_cpu_process_inbuf(conn);
2253 case CONN_TYPE_CONTROL:
2254 return connection_control_process_inbuf(TO_CONTROL_CONN(conn));
2255 default:
2256 log_err(LD_BUG,"Bug: got unexpected conn type %d.", conn->type);
2257 tor_fragile_assert();
2258 return -1;
2262 /** Called whenever we've written data on a connection. */
2263 static int
2264 connection_flushed_some(connection_t *conn)
2266 if (conn->type == CONN_TYPE_DIR &&
2267 conn->state == DIR_CONN_STATE_SERVER_WRITING)
2268 return connection_dirserv_flushed_some(TO_DIR_CONN(conn));
2269 else if (conn->type == CONN_TYPE_OR)
2270 return connection_or_flushed_some(TO_OR_CONN(conn));
2271 else
2272 return 0;
2275 /** We just finished flushing bytes from conn-\>outbuf, and there
2276 * are no more bytes remaining.
2278 * This function just passes conn to the connection-specific
2279 * connection_*_finished_flushing() function.
2281 static int
2282 connection_finished_flushing(connection_t *conn)
2284 tor_assert(conn);
2286 // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
2288 switch (conn->type) {
2289 case CONN_TYPE_OR:
2290 return connection_or_finished_flushing(TO_OR_CONN(conn));
2291 case CONN_TYPE_AP:
2292 case CONN_TYPE_EXIT:
2293 return connection_edge_finished_flushing(TO_EDGE_CONN(conn));
2294 case CONN_TYPE_DIR:
2295 return connection_dir_finished_flushing(TO_DIR_CONN(conn));
2296 case CONN_TYPE_DNSWORKER:
2297 return connection_dns_finished_flushing(conn);
2298 case CONN_TYPE_CPUWORKER:
2299 return connection_cpu_finished_flushing(conn);
2300 case CONN_TYPE_CONTROL:
2301 return connection_control_finished_flushing(TO_CONTROL_CONN(conn));
2302 default:
2303 log_err(LD_BUG,"Bug: got unexpected conn type %d.", conn->type);
2304 tor_fragile_assert();
2305 return -1;
2309 /** Called when our attempt to connect() to another server has just
2310 * succeeded.
2312 * This function just passes conn to the connection-specific
2313 * connection_*_finished_connecting() function.
2315 static int
2316 connection_finished_connecting(connection_t *conn)
2318 tor_assert(conn);
2319 switch (conn->type)
2321 case CONN_TYPE_OR:
2322 return connection_or_finished_connecting(TO_OR_CONN(conn));
2323 case CONN_TYPE_EXIT:
2324 return connection_edge_finished_connecting(TO_EDGE_CONN(conn));
2325 case CONN_TYPE_DIR:
2326 return connection_dir_finished_connecting(TO_DIR_CONN(conn));
2327 default:
2328 log_err(LD_BUG,"Bug: got unexpected conn type %d.", conn->type);
2329 tor_fragile_assert();
2330 return -1;
2334 /** Callback: invoked when a connection reaches an EOF event. */
2335 static int
2336 connection_reached_eof(connection_t *conn)
2338 switch (conn->type) {
2339 case CONN_TYPE_OR:
2340 return connection_or_reached_eof(TO_OR_CONN(conn));
2341 case CONN_TYPE_AP:
2342 case CONN_TYPE_EXIT:
2343 return connection_edge_reached_eof(TO_EDGE_CONN(conn));
2344 case CONN_TYPE_DIR:
2345 return connection_dir_reached_eof(TO_DIR_CONN(conn));
2346 case CONN_TYPE_DNSWORKER:
2347 return connection_dns_reached_eof(conn);
2348 case CONN_TYPE_CPUWORKER:
2349 return connection_cpu_reached_eof(conn);
2350 case CONN_TYPE_CONTROL:
2351 return connection_control_reached_eof(TO_CONTROL_CONN(conn));
2352 default:
2353 log_err(LD_BUG,"Bug: got unexpected conn type %d.", conn->type);
2354 tor_fragile_assert();
2355 return -1;
2359 /** Verify that connection <b>conn</b> has all of its invariants
2360 * correct. Trigger an assert if anything is invalid.
2362 void
2363 assert_connection_ok(connection_t *conn, time_t now)
2365 (void) now; /* XXXX unused. */
2366 tor_assert(conn);
2367 tor_assert(conn->type >= _CONN_TYPE_MIN);
2368 tor_assert(conn->type <= _CONN_TYPE_MAX);
2369 switch (conn->type) {
2370 case CONN_TYPE_OR:
2371 tor_assert(conn->magic == OR_CONNECTION_MAGIC);
2372 break;
2373 case CONN_TYPE_AP:
2374 case CONN_TYPE_EXIT:
2375 tor_assert(conn->magic == EDGE_CONNECTION_MAGIC);
2376 break;
2377 case CONN_TYPE_DIR:
2378 tor_assert(conn->magic == DIR_CONNECTION_MAGIC);
2379 break;
2380 case CONN_TYPE_CONTROL:
2381 tor_assert(conn->magic == CONTROL_CONNECTION_MAGIC);
2382 break;
2383 default:
2384 tor_assert(conn->magic == BASE_CONNECTION_MAGIC);
2385 break;
2388 if (conn->outbuf_flushlen > 0) {
2389 tor_assert(connection_is_writing(conn) || conn->wants_to_write ||
2390 (conn->type == CONN_TYPE_DIR &&
2391 TO_DIR_CONN(conn)->is_blocked_on_or_conn));
2394 if (conn->hold_open_until_flushed)
2395 tor_assert(conn->marked_for_close);
2397 /* XXXX check: wants_to_read, wants_to_write, s, conn_array_index,
2398 * marked_for_close. */
2400 /* buffers */
2401 if (!connection_is_listener(conn)) {
2402 assert_buf_ok(conn->inbuf);
2403 assert_buf_ok(conn->outbuf);
2406 /* XXXX Fix this; no longer so.*/
2407 #if 0
2408 if (conn->type != CONN_TYPE_OR && conn->type != CONN_TYPE_DIR)
2409 tor_assert(!conn->pkey);
2410 /* pkey is set if we're a dir client, or if we're an OR in state OPEN
2411 * connected to another OR.
2413 #endif
2415 if (conn->chosen_exit_optional) {
2416 tor_assert(conn->type == CONN_TYPE_AP);
2417 tor_assert((TO_EDGE_CONN(conn))->chosen_exit_name);
2420 if (conn->type == CONN_TYPE_OR) {
2421 or_connection_t *or_conn = TO_OR_CONN(conn);
2422 if (conn->state == OR_CONN_STATE_OPEN) {
2423 /* tor_assert(conn->bandwidth > 0); */
2424 /* the above isn't necessarily true: if we just did a TLS
2425 * handshake but we didn't recognize the other peer, or it
2426 * gave a bad cert/etc, then we won't have assigned bandwidth,
2427 * yet it will be open. -RD
2429 // tor_assert(conn->read_bucket >= 0);
2431 // tor_assert(conn->addr && conn->port);
2432 tor_assert(conn->address);
2433 if (conn->state > OR_CONN_STATE_PROXY_READING)
2434 tor_assert(or_conn->tls);
2437 if (CONN_IS_EDGE(conn)) {
2438 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
2439 /* XXX unchecked: package window, deliver window. */
2440 if (conn->type == CONN_TYPE_AP) {
2442 tor_assert(edge_conn->socks_request);
2443 if (conn->state == AP_CONN_STATE_OPEN) {
2444 tor_assert(edge_conn->socks_request->has_finished);
2445 if (!conn->marked_for_close) {
2446 tor_assert(edge_conn->cpath_layer);
2447 assert_cpath_layer_ok(edge_conn->cpath_layer);
2451 if (conn->type == CONN_TYPE_EXIT) {
2452 tor_assert(conn->purpose == EXIT_PURPOSE_CONNECT ||
2453 conn->purpose == EXIT_PURPOSE_RESOLVE);
2455 if (edge_conn->bridge_for_conn) {
2456 tor_assert(conn->type == CONN_TYPE_EXIT);
2457 tor_assert(edge_conn->bridge_for_conn->bridge_conn == edge_conn);
2459 } else if (conn->type == CONN_TYPE_DIR) {
2460 dir_connection_t *dir_conn = TO_DIR_CONN(conn);
2462 if (dir_conn->bridge_conn) {
2463 tor_assert(DIR_CONN_IS_SERVER(conn));
2464 tor_assert(dir_conn->bridge_conn->bridge_for_conn == dir_conn);
2465 if (dir_conn->bridge_conn->on_circuit) {
2466 dir_connection_t *d;
2467 or_connection_t *or_conn;
2468 tor_assert(!CIRCUIT_IS_ORIGIN(dir_conn->bridge_conn->on_circuit));
2469 or_conn = TO_OR_CIRCUIT(dir_conn->bridge_conn->on_circuit)->p_conn;
2470 if (dir_conn->is_blocked_on_or_conn)
2471 tor_assert(or_conn);
2472 for (d = or_conn->blocked_dir_connections; d;
2473 d = d->next_blocked_on_same_or_conn) {
2474 if (d == dir_conn) {
2475 tor_assert(dir_conn->is_blocked_on_or_conn == 1);
2476 break;
2479 if (!d)
2480 tor_assert(!dir_conn->is_blocked_on_or_conn);
2483 } else {
2484 /* Purpose is only used for dir and exit types currently */
2485 tor_assert(!conn->purpose);
2488 switch (conn->type)
2490 case CONN_TYPE_OR_LISTENER:
2491 case CONN_TYPE_AP_LISTENER:
2492 case CONN_TYPE_AP_TRANS_LISTENER:
2493 case CONN_TYPE_AP_NATD_LISTENER:
2494 case CONN_TYPE_DIR_LISTENER:
2495 case CONN_TYPE_CONTROL_LISTENER:
2496 tor_assert(conn->state == LISTENER_STATE_READY);
2497 break;
2498 case CONN_TYPE_OR:
2499 tor_assert(conn->state >= _OR_CONN_STATE_MIN);
2500 tor_assert(conn->state <= _OR_CONN_STATE_MAX);
2501 tor_assert(TO_OR_CONN(conn)->n_circuits >= 0);
2502 break;
2503 case CONN_TYPE_EXIT:
2504 tor_assert(conn->state >= _EXIT_CONN_STATE_MIN);
2505 tor_assert(conn->state <= _EXIT_CONN_STATE_MAX);
2506 tor_assert(conn->purpose >= _EXIT_PURPOSE_MIN);
2507 tor_assert(conn->purpose <= _EXIT_PURPOSE_MAX);
2508 break;
2509 case CONN_TYPE_AP:
2510 tor_assert(conn->state >= _AP_CONN_STATE_MIN);
2511 tor_assert(conn->state <= _AP_CONN_STATE_MAX);
2512 tor_assert(TO_EDGE_CONN(conn)->socks_request);
2513 break;
2514 case CONN_TYPE_DIR:
2515 tor_assert(conn->state >= _DIR_CONN_STATE_MIN);
2516 tor_assert(conn->state <= _DIR_CONN_STATE_MAX);
2517 tor_assert(conn->purpose >= _DIR_PURPOSE_MIN);
2518 tor_assert(conn->purpose <= _DIR_PURPOSE_MAX);
2519 break;
2520 case CONN_TYPE_DNSWORKER:
2521 tor_assert(conn->state >= _DNSWORKER_STATE_MIN);
2522 tor_assert(conn->state <= _DNSWORKER_STATE_MAX);
2523 break;
2524 case CONN_TYPE_CPUWORKER:
2525 tor_assert(conn->state >= _CPUWORKER_STATE_MIN);
2526 tor_assert(conn->state <= _CPUWORKER_STATE_MAX);
2527 break;
2528 case CONN_TYPE_CONTROL:
2529 tor_assert(conn->state >= _CONTROL_CONN_STATE_MIN);
2530 tor_assert(conn->state <= _CONTROL_CONN_STATE_MAX);
2531 break;
2532 default:
2533 tor_assert(0);