Stop saying !is_internal_IP() when we really meant
[tor.git] / src / or / connection.c
blob188bfc75ee8c08cdf34d625d9250105153363b11
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, 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 dest 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 safe circuit";
107 case AP_CONN_STATE_CONNECT_WAIT: return "waiting for connect";
108 case AP_CONN_STATE_RESOLVE_WAIT: return "waiting for resolve";
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 break;
430 case CONN_TYPE_OR:
431 or_conn = TO_OR_CONN(conn);
432 /* Remember why we're closing this connection. */
433 if (conn->state != OR_CONN_STATE_OPEN) {
434 if (connection_or_nonopen_was_started_here(or_conn)) {
435 rep_hist_note_connect_failed(or_conn->identity_digest, now);
436 entry_guard_register_connect_status(or_conn->identity_digest,0,now);
437 router_set_status(or_conn->identity_digest, 0);
438 control_event_or_conn_status(or_conn, OR_CONN_EVENT_FAILED,
439 control_tls_error_to_reason(or_conn->tls_error));
441 /* Inform any pending (not attached) circs that they should
442 * give up. */
443 circuit_n_conn_done(TO_OR_CONN(conn), 0);
444 } else if (conn->hold_open_until_flushed) {
445 /* We only set hold_open_until_flushed when we're intentionally
446 * closing a connection. */
447 rep_hist_note_disconnect(or_conn->identity_digest, now);
448 control_event_or_conn_status(or_conn, OR_CONN_EVENT_CLOSED,
449 control_tls_error_to_reason(or_conn->tls_error));
450 } else if (or_conn->identity_digest) {
451 rep_hist_note_connection_died(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));
455 /* Now close all the attached circuits on it. */
456 circuit_unlink_all_from_or_conn(TO_OR_CONN(conn),
457 END_CIRC_REASON_OR_CONN_CLOSED);
458 break;
459 case CONN_TYPE_AP:
460 edge_conn = TO_EDGE_CONN(conn);
461 if (edge_conn->socks_request->has_finished == 0) {
462 /* since conn gets removed right after this function finishes,
463 * there's no point trying to send back a reply at this point. */
464 log_warn(LD_BUG,"Bug: Closing stream (marked at %s:%d) without sending"
465 " back a socks reply.",
466 conn->marked_for_close_file, conn->marked_for_close);
468 if (!edge_conn->end_reason) {
469 // XXXX012 Disable this before 0.1.2.x-final ships.
470 log_warn(LD_BUG,"Bug: Closing stream (marked at %s:%d) without having"
471 " set end_reason. Please tell Nick.",
472 conn->marked_for_close_file, conn->marked_for_close);
474 control_event_stream_status(edge_conn, STREAM_EVENT_CLOSED,
475 edge_conn->end_reason);
476 circ = circuit_get_by_edge_conn(edge_conn);
477 if (circ)
478 circuit_detach_stream(circ, edge_conn);
479 break;
480 case CONN_TYPE_EXIT:
481 edge_conn = TO_EDGE_CONN(conn);
482 circ = circuit_get_by_edge_conn(edge_conn);
483 if (circ)
484 circuit_detach_stream(circ, edge_conn);
485 if (conn->state == EXIT_CONN_STATE_RESOLVING) {
486 connection_dns_remove(edge_conn);
488 break;
489 case CONN_TYPE_DNSWORKER:
490 if (conn->state == DNSWORKER_STATE_BUSY) {
491 dns_cancel_pending_resolve(conn->address);
493 break;
497 /** Close the underlying socket for <b>conn</b>, so we don't try to
498 * flush it. Must be used in conjunction with (right before)
499 * connection_mark_for_close().
501 void
502 connection_close_immediate(connection_t *conn)
504 assert_connection_ok(conn,0);
505 if (conn->s < 0) {
506 log_err(LD_BUG,"Bug: Attempt to close already-closed connection.");
507 tor_fragile_assert();
508 return;
510 if (conn->outbuf_flushlen) {
511 log_info(LD_NET,"fd %d, type %s, state %s, %d bytes on outbuf.",
512 conn->s, conn_type_to_string(conn->type),
513 conn_state_to_string(conn->type, conn->state),
514 (int)conn->outbuf_flushlen);
517 connection_unregister(conn);
519 tor_close_socket(conn->s);
520 conn->s = -1;
521 if (!connection_is_listener(conn)) {
522 buf_clear(conn->outbuf);
523 conn->outbuf_flushlen = 0;
527 /** Mark <b>conn</b> to be closed next time we loop through
528 * conn_close_if_marked() in main.c. */
529 void
530 _connection_mark_for_close(connection_t *conn, int line, const char *file)
532 assert_connection_ok(conn,0);
533 tor_assert(line);
534 tor_assert(file);
536 if (conn->marked_for_close) {
537 log(LOG_WARN,LD_BUG,"Duplicate call to connection_mark_for_close at %s:%d"
538 " (first at %s:%d)", file, line, conn->marked_for_close_file,
539 conn->marked_for_close);
540 tor_fragile_assert();
541 return;
544 conn->marked_for_close = line;
545 conn->marked_for_close_file = file;
546 add_connection_to_closeable_list(conn);
548 /* in case we're going to be held-open-til-flushed, reset
549 * the number of seconds since last successful write, so
550 * we get our whole 15 seconds */
551 conn->timestamp_lastwritten = time(NULL);
554 /** Find each connection that has hold_open_until_flushed set to
555 * 1 but hasn't written in the past 15 seconds, and set
556 * hold_open_until_flushed to 0. This means it will get cleaned
557 * up in the next loop through close_if_marked() in main.c.
559 void
560 connection_expire_held_open(void)
562 connection_t **carray, *conn;
563 int n, i;
564 time_t now;
566 now = time(NULL);
568 get_connection_array(&carray, &n);
569 for (i = 0; i < n; ++i) {
570 conn = carray[i];
571 /* If we've been holding the connection open, but we haven't written
572 * for 15 seconds...
574 if (conn->hold_open_until_flushed) {
575 tor_assert(conn->marked_for_close);
576 if (now - conn->timestamp_lastwritten >= 15) {
577 int severity;
578 if (conn->type == CONN_TYPE_EXIT ||
579 (conn->type == CONN_TYPE_DIR &&
580 conn->purpose == DIR_PURPOSE_SERVER))
581 severity = LOG_INFO;
582 else
583 severity = LOG_NOTICE;
584 log_fn(severity, LD_NET,
585 "Giving up on marked_for_close conn that's been flushing "
586 "for 15s (fd %d, type %s, state %s).",
587 conn->s, conn_type_to_string(conn->type),
588 conn_state_to_string(conn->type, conn->state));
589 conn->hold_open_until_flushed = 0;
595 /** Bind a new non-blocking socket listening to
596 * <b>listenaddress</b>:<b>listenport</b>, and add this new connection
597 * (of type <b>type</b>) to the connection array.
599 * If <b>listenaddress</b> includes a port, we bind on that port;
600 * otherwise, we use listenport.
602 static connection_t *
603 connection_create_listener(const char *listenaddress, uint16_t listenport,
604 int type)
606 struct sockaddr_in listenaddr; /* where to bind */
607 char *address = NULL;
608 connection_t *conn;
609 uint16_t usePort;
610 uint32_t addr;
611 int s; /* the socket we're going to make */
612 #ifndef MS_WINDOWS
613 int one=1;
614 #endif
616 memset(&listenaddr,0,sizeof(struct sockaddr_in));
617 if (parse_addr_port(LOG_WARN, listenaddress, &address, &addr, &usePort)<0) {
618 log_warn(LD_CONFIG,
619 "Error parsing/resolving ListenAddress %s", listenaddress);
620 return NULL;
623 if (usePort==0)
624 usePort = listenport;
625 listenaddr.sin_addr.s_addr = htonl(addr);
626 listenaddr.sin_family = AF_INET;
627 listenaddr.sin_port = htons((uint16_t) usePort);
629 log_notice(LD_NET, "Opening %s on %s:%d",
630 conn_type_to_string(type), address, usePort);
632 s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
633 if (s < 0) {
634 log_warn(LD_NET,"Socket creation failed.");
635 goto err;
638 #ifndef MS_WINDOWS
639 /* REUSEADDR on normal places means you can rebind to the port
640 * right after somebody else has let it go. But REUSEADDR on win32
641 * means you can bind to the port _even when somebody else
642 * already has it bound_. So, don't do that on Win32. */
643 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*) &one, sizeof(one));
644 #endif
646 if (bind(s,(struct sockaddr *)&listenaddr,sizeof(listenaddr)) < 0) {
647 const char *helpfulhint = "";
648 int e = tor_socket_errno(s);
649 if (ERRNO_IS_EADDRINUSE(e))
650 helpfulhint = ". Is Tor already running?";
651 log_warn(LD_NET, "Could not bind to %s:%u: %s%s", address, usePort,
652 tor_socket_strerror(e), helpfulhint);
653 tor_close_socket(s);
654 goto err;
657 if (listen(s,SOMAXCONN) < 0) {
658 log_warn(LD_NET, "Could not listen on %s:%u: %s", address, usePort,
659 tor_socket_strerror(tor_socket_errno(s)));
660 tor_close_socket(s);
661 goto err;
664 set_socket_nonblocking(s);
666 conn = connection_new(type);
667 conn->s = s;
668 conn->address = address;
669 address = NULL;
670 conn->port = usePort;
672 if (connection_add(conn) < 0) { /* no space, forget it */
673 log_warn(LD_NET,"connection_add for listener failed. Giving up.");
674 connection_free(conn);
675 goto err;
678 log_debug(LD_NET,"%s listening on port %u.",
679 conn_type_to_string(type), usePort);
681 conn->state = LISTENER_STATE_READY;
682 connection_start_reading(conn);
684 return conn;
686 err:
687 tor_free(address);
688 return NULL;
691 /** Do basic sanity checking on a newly received socket. Return 0
692 * if it looks ok, else return -1. */
693 static int
694 check_sockaddr_in(struct sockaddr *sa, int len, int level)
696 int ok = 1;
697 struct sockaddr_in *sin=(struct sockaddr_in*)sa;
699 if (len != sizeof(struct sockaddr_in)) {
700 log_fn(level, LD_NET, "Length of address not as expected: %d vs %d",
701 len,(int)sizeof(struct sockaddr_in));
702 ok = 0;
704 if (sa->sa_family != AF_INET) {
705 log_fn(level, LD_NET, "Family of address not as expected: %d vs %d",
706 sa->sa_family, AF_INET);
707 ok = 0;
709 if (sin->sin_addr.s_addr == 0 || sin->sin_port == 0) {
710 log_fn(level, LD_NET,
711 "Address for new connection has address/port equal to zero.");
712 ok = 0;
714 return ok ? 0 : -1;
717 /** The listener connection <b>conn</b> told poll() it wanted to read.
718 * Call accept() on conn-\>s, and add the new connection if necessary.
720 static int
721 connection_handle_listener_read(connection_t *conn, int new_type)
723 int news; /* the new socket */
724 connection_t *newconn;
725 /* information about the remote peer when connecting to other routers */
726 struct sockaddr_in remote;
727 char addrbuf[256];
728 /* length of the remote address. Must be whatever accept() needs. */
729 socklen_t remotelen = 256;
730 char tmpbuf[INET_NTOA_BUF_LEN];
731 tor_assert((size_t)remotelen >= sizeof(struct sockaddr_in));
732 memset(addrbuf, 0, sizeof(addrbuf));
734 news = accept(conn->s,(struct sockaddr *)&addrbuf,&remotelen);
735 if (news < 0) { /* accept() error */
736 int e = tor_socket_errno(conn->s);
737 if (ERRNO_IS_ACCEPT_EAGAIN(e)) {
738 return 0; /* he hung up before we could accept(). that's fine. */
739 } else if (ERRNO_IS_ACCEPT_RESOURCE_LIMIT(e)) {
740 log_notice(LD_NET,"accept failed: %s. Dropping incoming connection.",
741 tor_socket_strerror(e));
742 return 0;
744 /* else there was a real error. */
745 log_warn(LD_NET,"accept() failed: %s. Closing listener.",
746 tor_socket_strerror(e));
747 connection_mark_for_close(conn);
748 return -1;
750 log_debug(LD_NET,
751 "Connection accepted on socket %d (child of fd %d).",
752 news,conn->s);
754 set_socket_nonblocking(news);
756 if (check_sockaddr_in((struct sockaddr*)addrbuf, remotelen, LOG_INFO)<0) {
757 log_info(LD_NET,
758 "accept() returned a strange address; trying getsockname().");
759 remotelen=256;
760 memset(addrbuf, 0, sizeof(addrbuf));
761 if (getsockname(news, (struct sockaddr*)addrbuf, &remotelen)<0) {
762 int e = tor_socket_errno(news);
763 log_warn(LD_NET, "getsockname() for new connection failed: %s",
764 tor_socket_strerror(e));
765 } else {
766 if (check_sockaddr_in((struct sockaddr*)addrbuf, remotelen,
767 LOG_WARN) < 0) {
768 log_warn(LD_NET,"Something's wrong with this conn. Closing it.");
769 tor_close_socket(news);
770 return 0;
774 memcpy(&remote, addrbuf, sizeof(struct sockaddr_in));
776 /* process entrance policies here, before we even create the connection */
777 if (new_type == CONN_TYPE_AP) {
778 /* check sockspolicy to see if we should accept it */
779 if (socks_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
780 tor_inet_ntoa(&remote.sin_addr, tmpbuf, sizeof(tmpbuf));
781 log_notice(LD_APP,"Denying socks connection from untrusted address %s.",
782 tmpbuf);
783 tor_close_socket(news);
784 return 0;
787 if (new_type == CONN_TYPE_DIR) {
788 /* check dirpolicy to see if we should accept it */
789 if (dir_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
790 tor_inet_ntoa(&remote.sin_addr, tmpbuf, sizeof(tmpbuf));
791 log_notice(LD_DIRSERV,"Denying dir connection from address %s.",
792 tmpbuf);
793 tor_close_socket(news);
794 return 0;
798 newconn = connection_new(new_type);
799 newconn->s = news;
801 /* remember the remote address */
802 newconn->addr = ntohl(remote.sin_addr.s_addr);
803 newconn->port = ntohs(remote.sin_port);
804 newconn->address = tor_dup_addr(newconn->addr);
806 if (connection_add(newconn) < 0) { /* no space, forget it */
807 connection_free(newconn);
808 return 0; /* no need to tear down the parent */
811 if (connection_init_accepted_conn(newconn, conn->type) < 0) {
812 connection_mark_for_close(newconn);
813 return 0;
815 return 0;
818 /** Initialize states for newly accepted connection <b>conn</b>.
819 * If conn is an OR, start the tls handshake.
820 * If conn is a transparent AP, get its original destination
821 * and place it in circuit_wait.
823 static int
824 connection_init_accepted_conn(connection_t *conn, uint8_t listener_type)
826 connection_start_reading(conn);
828 switch (conn->type) {
829 case CONN_TYPE_OR:
830 control_event_or_conn_status(TO_OR_CONN(conn), OR_CONN_EVENT_NEW, 0);
831 return connection_tls_start_handshake(TO_OR_CONN(conn), 1);
832 case CONN_TYPE_AP:
833 switch (listener_type) {
834 case CONN_TYPE_AP_LISTENER:
835 conn->state = AP_CONN_STATE_SOCKS_WAIT;
836 break;
837 case CONN_TYPE_AP_TRANS_LISTENER:
838 conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
839 return connection_ap_process_transparent(TO_EDGE_CONN(conn));
840 case CONN_TYPE_AP_NATD_LISTENER:
841 conn->state = AP_CONN_STATE_NATD_WAIT;
842 break;
844 break;
845 case CONN_TYPE_DIR:
846 conn->purpose = DIR_PURPOSE_SERVER;
847 conn->state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
848 break;
849 case CONN_TYPE_CONTROL:
850 conn->state = CONTROL_CONN_STATE_NEEDAUTH_V0;
851 break;
853 return 0;
856 /** Take conn, make a nonblocking socket; try to connect to
857 * addr:port (they arrive in *host order*). If fail, return -1. Else
858 * assign s to conn-\>s: if connected return 1, if EAGAIN return 0.
860 * address is used to make the logs useful.
862 * On success, add conn to the list of polled connections.
865 connection_connect(connection_t *conn, char *address,
866 uint32_t addr, uint16_t port)
868 int s, inprogress = 0;
869 struct sockaddr_in dest_addr;
870 or_options_t *options = get_options();
872 s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
873 if (s < 0) {
874 log_warn(LD_NET,"Error creating network socket: %s",
875 tor_socket_strerror(tor_socket_errno(-1)));
876 return -1;
879 if (options->OutboundBindAddress) {
880 struct sockaddr_in ext_addr;
882 memset(&ext_addr, 0, sizeof(ext_addr));
883 ext_addr.sin_family = AF_INET;
884 ext_addr.sin_port = 0;
885 if (!tor_inet_aton(options->OutboundBindAddress, &ext_addr.sin_addr)) {
886 log_warn(LD_CONFIG,"Outbound bind address '%s' didn't parse. Ignoring.",
887 options->OutboundBindAddress);
888 } else {
889 if (bind(s, (struct sockaddr*)&ext_addr, sizeof(ext_addr)) < 0) {
890 log_warn(LD_NET,"Error binding network socket: %s",
891 tor_socket_strerror(tor_socket_errno(s)));
892 tor_close_socket(s);
893 return -1;
898 set_socket_nonblocking(s);
900 memset(&dest_addr,0,sizeof(dest_addr));
901 dest_addr.sin_family = AF_INET;
902 dest_addr.sin_port = htons(port);
903 dest_addr.sin_addr.s_addr = htonl(addr);
905 log_debug(LD_NET,"Connecting to %s:%u.",escaped_safe_str(address),port);
907 if (connect(s,(struct sockaddr *)&dest_addr,sizeof(dest_addr)) < 0) {
908 int e = tor_socket_errno(s);
909 if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
910 /* yuck. kill it. */
911 log_info(LD_NET,
912 "connect() to %s:%u failed: %s",escaped_safe_str(address),
913 port, tor_socket_strerror(e));
914 tor_close_socket(s);
915 return -1;
916 } else {
917 inprogress = 1;
921 if (!server_mode(options))
922 client_check_address_changed(s);
924 /* it succeeded. we're connected. */
925 log_fn(inprogress?LOG_DEBUG:LOG_INFO, LD_NET,
926 "Connection to %s:%u %s (sock %d).",escaped_safe_str(address),
927 port, inprogress?"in progress":"established", s);
928 conn->s = s;
929 if (connection_add(conn) < 0) /* no space, forget it */
930 return -1;
931 return inprogress ? 0 : 1;
935 * Launch any configured listener connections of type <b>type</b>. (A
936 * listener is configured if <b>port_option</b> is non-zero. If any
937 * ListenAddress configuration options are given in <b>cfg</b>, create a
938 * connection binding to each one. Otherwise, create a single
939 * connection binding to the address <b>default_addr</b>.)
941 * If <b>force</b> is true, close and re-open all listener connections.
942 * Otherwise, only relaunch the listeners of this type if the number of
943 * existing connections is not as configured (e.g., because one died),
944 * or if the existing connections do not match those configured.
946 * Add all old conns that should be closed to <b>replaced_conns</b>.
947 * Add all new connections to <b>new_conns</b>.
949 static int
950 retry_listeners(int type, config_line_t *cfg,
951 int port_option, const char *default_addr, int force,
952 smartlist_t *replaced_conns,
953 smartlist_t *new_conns,
954 int never_open_conns)
956 smartlist_t *launch = smartlist_create();
957 int free_launch_elts = 1;
958 config_line_t *c;
959 int n_conn, i;
960 connection_t *conn;
961 connection_t **carray;
962 config_line_t *line;
964 if (cfg && port_option) {
965 for (c = cfg; c; c = c->next) {
966 smartlist_add(launch, c);
968 free_launch_elts = 0;
969 } else if (port_option) {
970 line = tor_malloc_zero(sizeof(config_line_t));
971 line->key = tor_strdup("");
972 line->value = tor_strdup(default_addr);
973 smartlist_add(launch, line);
977 SMARTLIST_FOREACH(launch, config_line_t *, l,
978 log_fn(LOG_NOTICE, "#%s#%s", l->key, l->value));
981 get_connection_array(&carray,&n_conn);
982 for (i=0; i < n_conn; ++i) {
983 conn = carray[i];
984 if (conn->type != type || conn->marked_for_close)
985 continue;
986 if (force) {
987 /* It's a listener, and we're relaunching all listeners of this
988 * type. Close this one. */
989 log_notice(LD_NET, "Force-closing listener %s on %s:%d",
990 conn_type_to_string(type), conn->address, conn->port);
991 connection_close_immediate(conn);
992 connection_mark_for_close(conn);
993 continue;
995 /* Okay, so this is a listener. Is it configured? */
996 line = NULL;
997 SMARTLIST_FOREACH(launch, config_line_t *, wanted,
999 char *address=NULL;
1000 uint16_t port;
1001 if (!parse_addr_port(LOG_WARN, wanted->value, &address, NULL, &port)) {
1002 int addr_matches = !strcasecmp(address, conn->address);
1003 tor_free(address);
1004 if (! port)
1005 port = port_option;
1006 if (port == conn->port && addr_matches) {
1007 line = wanted;
1008 break;
1012 if (! line) {
1013 /* This one isn't configured. Close it. */
1014 log_notice(LD_NET, "Closing no-longer-configured %s on %s:%d",
1015 conn_type_to_string(type), conn->address, conn->port);
1016 if (replaced_conns) {
1017 smartlist_add(replaced_conns, conn);
1018 } else {
1019 connection_close_immediate(conn);
1020 connection_mark_for_close(conn);
1022 } else {
1023 /* It's configured; we don't need to launch it. */
1024 // log_debug(LD_NET, "Already have %s on %s:%d",
1025 // conn_type_to_string(type), conn->address, conn->port);
1026 smartlist_remove(launch, line);
1027 if (free_launch_elts)
1028 config_free_lines(line);
1032 /* Now open all the listeners that are configured but not opened. */
1033 i = 0;
1034 if (!never_open_conns) {
1035 SMARTLIST_FOREACH(launch, config_line_t *, cfg,
1037 conn = connection_create_listener(cfg->value, (uint16_t) port_option,
1038 type);
1039 if (!conn) {
1040 i = -1;
1041 } else {
1042 if (new_conns)
1043 smartlist_add(new_conns, conn);
1048 if (free_launch_elts) {
1049 SMARTLIST_FOREACH(launch, config_line_t *, cfg,
1050 config_free_lines(cfg));
1052 smartlist_free(launch);
1054 return i;
1057 /** (Re)launch listeners for each port you should have open. If
1058 * <b>force</b> is true, close and relaunch all listeners. If <b>force</b>
1059 * is false, then only relaunch listeners when we have the wrong number of
1060 * connections for a given type.
1062 * Add all old conns that should be closed to <b>replaced_conns</b>.
1063 * Add all new connections to <b>new_conns</b>.
1066 retry_all_listeners(int force, smartlist_t *replaced_conns,
1067 smartlist_t *new_conns)
1069 or_options_t *options = get_options();
1071 if (retry_listeners(CONN_TYPE_OR_LISTENER, options->ORListenAddress,
1072 options->ORPort, "0.0.0.0", force,
1073 replaced_conns, new_conns, options->ClientOnly)<0)
1074 return -1;
1075 if (retry_listeners(CONN_TYPE_DIR_LISTENER, options->DirListenAddress,
1076 options->DirPort, "0.0.0.0", force,
1077 replaced_conns, new_conns, 0)<0)
1078 return -1;
1079 if (retry_listeners(CONN_TYPE_AP_LISTENER, options->SocksListenAddress,
1080 options->SocksPort, "127.0.0.1", force,
1081 replaced_conns, new_conns, 0)<0)
1082 return -1;
1083 if (retry_listeners(CONN_TYPE_AP_TRANS_LISTENER, options->TransListenAddress,
1084 options->TransPort, "127.0.0.1", force,
1085 replaced_conns, new_conns, 0)<0)
1086 return -1;
1087 if (retry_listeners(CONN_TYPE_AP_NATD_LISTENER, options->NatdListenAddress,
1088 options->NatdPort, "127.0.0.1", force,
1089 replaced_conns, new_conns, 0)<0)
1090 return -1;
1091 if (retry_listeners(CONN_TYPE_CONTROL_LISTENER,
1092 options->ControlListenAddress,
1093 options->ControlPort, "127.0.0.1", force,
1094 replaced_conns, new_conns, 0)<0)
1095 return -1;
1097 return 0;
1100 /** Return 1 if we should apply rate limiting to <b>conn</b>,
1101 * and 0 otherwise. Right now this just checks if it's an internal
1102 * IP address. */
1103 static int
1104 connection_is_rate_limited(connection_t *conn)
1106 return !is_internal_IP(conn->addr, 0);
1109 extern int global_read_bucket, global_write_bucket;
1111 /** Did our global write bucket run dry last second? If so, we are
1112 * likely to run dry again this second, so be stingy with the tokens
1113 * we just put in. */
1114 static int global_write_bucket_empty_last_second = 0;
1116 /** Helper function to decide how many bytes out of <b>global_bucket</b>
1117 * we're willing to use for this transaction. <b>base</b> is the size
1118 * of a cell on the network; <b>priority</b> says whether we should
1119 * write many of them or just a few; and <b>conn_bucket</b> (if
1120 * non-negative) provides an upper limit for our answer. */
1121 static int
1122 connection_bucket_round_robin(int base, int priority,
1123 int global_bucket, int conn_bucket)
1125 int at_most;
1126 int num_bytes_high = (priority ? 32 : 16) * base;
1127 int num_bytes_low = (priority ? 4 : 2) * base;
1129 /* Do a rudimentary round-robin so one circuit can't hog a connection.
1130 * Pick at most 32 cells, at least 4 cells if possible, and if we're in
1131 * the middle pick 1/8 of the available bandwidth. */
1132 at_most = global_bucket / 8;
1133 at_most -= (at_most % base); /* round down */
1134 if (at_most > num_bytes_high) /* 16 KB, or 8 KB for low-priority */
1135 at_most = num_bytes_high;
1136 else if (at_most < num_bytes_low) /* 2 KB, or 1 KB for low-priority */
1137 at_most = num_bytes_low;
1139 if (at_most > global_bucket)
1140 at_most = global_bucket;
1142 if (conn_bucket >= 0 && at_most > conn_bucket)
1143 at_most = conn_bucket;
1145 if (at_most < 0)
1146 return 0;
1147 return at_most;
1150 /** How many bytes at most can we read onto this connection? */
1151 static int
1152 connection_bucket_read_limit(connection_t *conn)
1154 int base = connection_speaks_cells(conn) ?
1155 CELL_NETWORK_SIZE : RELAY_PAYLOAD_SIZE;
1156 int priority = conn->type != CONN_TYPE_DIR;
1157 int conn_bucket = -1;
1158 if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
1159 or_connection_t *or_conn = TO_OR_CONN(conn);
1160 conn_bucket = or_conn->read_bucket;
1162 if (!connection_is_rate_limited(conn)) {
1163 /* be willing to read on local conns even if our buckets are empty */
1164 return conn_bucket>=0 ? conn_bucket : 1<<14;
1166 return connection_bucket_round_robin(base, priority,
1167 global_read_bucket, conn_bucket);
1170 /** How many bytes at most can we write onto this connection? */
1172 connection_bucket_write_limit(connection_t *conn)
1174 int base = connection_speaks_cells(conn) ?
1175 CELL_NETWORK_SIZE : RELAY_PAYLOAD_SIZE;
1176 int priority = conn->type != CONN_TYPE_DIR;
1178 if (!connection_is_rate_limited(conn)) {
1179 /* be willing to write to local conns even if our buckets are empty */
1180 return conn->outbuf_flushlen;
1182 return connection_bucket_round_robin(base, priority, global_write_bucket,
1183 conn->outbuf_flushlen);
1186 /** Return 1 if the global write bucket is low enough that we shouldn't
1187 * send <b>attempt</b> bytes of low-priority directory stuff out to
1188 * <b>conn</b>. Else return 0.
1190 * Priority is 1 for v1 requests (directories and running-routers),
1191 * and 2 for v2 requests (statuses and descriptors). But see FFFF in
1192 * directory_handle_command_get() for why we don't use priority 2 yet.
1194 * There are a lot of parameters we could use here:
1195 * - global_write_bucket. Low is bad.
1196 * - bandwidthrate. Low is bad.
1197 * - bandwidthburst. Not a big factor?
1198 * - attempt. High is bad.
1199 * - total bytes queued on outbufs. High is bad. But I'm wary of
1200 * using this, since a few slow-flushing queues will pump up the
1201 * number without meaning what we meant to mean. What we really
1202 * mean is "total directory bytes added to outbufs recently", but
1203 * that's harder to quantify and harder to keep track of.
1206 global_write_bucket_low(connection_t *conn, size_t attempt, int priority)
1208 if (authdir_mode(get_options()) && priority>1)
1209 return 0; /* there's always room to answer v2 if we're an auth dir */
1211 if (!connection_is_rate_limited(conn))
1212 return 0; /* local conns don't get limited */
1214 if (global_write_bucket < (int)attempt)
1215 return 1; /* not enough space no matter the priority */
1217 if (global_write_bucket_empty_last_second)
1218 return 1; /* we're already hitting our limits, no more please */
1220 if (priority == 1) { /* old-style v1 query */
1221 /* Could we handle *two* of these requests within the next two seconds? */
1222 int64_t can_write = (int64_t)global_write_bucket
1223 + 2*get_options()->BandwidthRate;
1224 if (can_write < 2*(int64_t)attempt)
1225 return 1;
1226 } else { /* v2 query */
1227 /* no further constraints yet */
1229 return 0;
1232 /** We just read num_read onto conn. Decrement buckets appropriately. */
1233 static void
1234 connection_read_bucket_decrement(connection_t *conn, int num_read)
1236 global_read_bucket -= num_read;
1237 if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
1238 TO_OR_CONN(conn)->read_bucket -= num_read;
1242 /** If we have exhausted our global buckets, or the buckets for conn,
1243 * stop reading. */
1244 static void
1245 connection_consider_empty_read_buckets(connection_t *conn)
1247 if (global_read_bucket <= 0) {
1248 LOG_FN_CONN(conn, (LOG_DEBUG,LD_NET,
1249 "global read bucket exhausted. Pausing."));
1250 conn->wants_to_read = 1;
1251 connection_stop_reading(conn);
1252 return;
1254 if (connection_speaks_cells(conn) &&
1255 conn->state == OR_CONN_STATE_OPEN &&
1256 TO_OR_CONN(conn)->read_bucket <= 0) {
1257 LOG_FN_CONN(conn,
1258 (LOG_DEBUG,LD_NET,"read bucket exhausted. Pausing."));
1259 conn->wants_to_read = 1;
1260 connection_stop_reading(conn);
1264 /** If we have exhausted our global buckets, or the buckets for conn,
1265 * stop writing. */
1266 static void
1267 connection_consider_empty_write_buckets(connection_t *conn)
1269 if (global_write_bucket <= 0) {
1270 LOG_FN_CONN(conn, (LOG_DEBUG,LD_NET,
1271 "global write bucket exhausted. Pausing."));
1272 conn->wants_to_write = 1;
1273 connection_stop_writing(conn);
1274 return;
1276 #if 0
1277 if (connection_speaks_cells(conn) &&
1278 conn->state == OR_CONN_STATE_OPEN &&
1279 TO_OR_CONN(conn)->write_bucket <= 0) {
1280 LOG_FN_CONN(conn,
1281 (LOG_DEBUG,LD_NET,"write bucket exhausted. Pausing."));
1282 conn->wants_to_write = 1;
1283 connection_stop_writing(conn);
1285 #endif
1288 /** Initialize the global read bucket to options->BandwidthBurst. */
1289 void
1290 connection_bucket_init(void)
1292 or_options_t *options = get_options();
1293 /* start it at max traffic */
1294 global_read_bucket = (int)options->BandwidthBurst;
1295 global_write_bucket = (int)options->BandwidthBurst;
1298 /** A second has rolled over; increment buckets appropriately. */
1299 void
1300 connection_bucket_refill(int seconds_elapsed)
1302 int i, n;
1303 connection_t *conn;
1304 connection_t **carray;
1305 or_options_t *options = get_options();
1307 tor_assert(seconds_elapsed >= 0);
1309 /* refill the global buckets */
1310 if (global_read_bucket < (int)options->BandwidthBurst) {
1311 global_read_bucket += (int)options->BandwidthRate*seconds_elapsed;
1312 if (global_read_bucket > (int)options->BandwidthBurst)
1313 global_read_bucket = (int)options->BandwidthBurst;
1314 log(LOG_DEBUG, LD_NET,"global_read_bucket now %d.", global_read_bucket);
1316 if (global_write_bucket < (int)options->BandwidthBurst) {
1317 global_write_bucket_empty_last_second = global_write_bucket == 0;
1318 global_write_bucket += (int)options->BandwidthRate*seconds_elapsed;
1319 if (global_write_bucket > (int)options->BandwidthBurst)
1320 global_write_bucket = (int)options->BandwidthBurst;
1321 log(LOG_DEBUG, LD_NET,"global_write_bucket now %d.", global_write_bucket);
1324 /* refill the per-connection buckets */
1325 get_connection_array(&carray,&n);
1326 for (i=0;i<n;i++) {
1327 conn = carray[i];
1329 if (connection_speaks_cells(conn)) {
1330 or_connection_t *or_conn = TO_OR_CONN(conn);
1331 if (connection_read_bucket_should_increase(or_conn)) {
1332 or_conn->read_bucket += or_conn->bandwidthrate*seconds_elapsed;
1333 if (or_conn->read_bucket > or_conn->bandwidthburst)
1334 or_conn->read_bucket = or_conn->bandwidthburst;
1335 //log_fn(LOG_DEBUG,"Receiver bucket %d now %d.", i,
1336 // conn->read_bucket);
1340 if (conn->wants_to_read == 1 /* it's marked to turn reading back on now */
1341 && global_read_bucket > 0 /* and we're allowed to read */
1342 && (!connection_speaks_cells(conn) ||
1343 conn->state != OR_CONN_STATE_OPEN ||
1344 TO_OR_CONN(conn)->read_bucket > 0)) {
1345 /* and either a non-cell conn or a cell conn with non-empty bucket */
1346 LOG_FN_CONN(conn, (LOG_DEBUG,LD_NET,
1347 "waking up conn (fd %d) for read",conn->s));
1348 conn->wants_to_read = 0;
1349 connection_start_reading(conn);
1351 if (conn->wants_to_write == 1 &&
1352 global_write_bucket > 0) { /* and we're allowed to write */
1353 LOG_FN_CONN(conn, (LOG_DEBUG,LD_NET,
1354 "waking up conn (fd %d) for write",conn->s));
1355 conn->wants_to_write = 0;
1356 connection_start_writing(conn);
1361 /** Is the receiver bucket for connection <b>conn</b> low enough that we
1362 * should add another pile of tokens to it?
1364 static int
1365 connection_read_bucket_should_increase(or_connection_t *conn)
1367 tor_assert(conn);
1369 if (conn->_base.state != OR_CONN_STATE_OPEN)
1370 return 0; /* only open connections play the rate limiting game */
1371 if (conn->read_bucket >= conn->bandwidthburst)
1372 return 0;
1374 return 1;
1377 /** Read bytes from conn-\>s and process them.
1379 * This function gets called from conn_read() in main.c, either
1380 * when poll() has declared that conn wants to read, or (for OR conns)
1381 * when there are pending TLS bytes.
1383 * It calls connection_read_to_buf() to bring in any new bytes,
1384 * and then calls connection_process_inbuf() to process them.
1386 * Mark the connection and return -1 if you want to close it, else
1387 * return 0.
1390 connection_handle_read(connection_t *conn)
1392 int max_to_read=-1, try_to_read;
1394 if (conn->marked_for_close)
1395 return 0; /* do nothing */
1397 conn->timestamp_lastread = time(NULL);
1399 switch (conn->type) {
1400 case CONN_TYPE_OR_LISTENER:
1401 return connection_handle_listener_read(conn, CONN_TYPE_OR);
1402 case CONN_TYPE_AP_LISTENER:
1403 case CONN_TYPE_AP_TRANS_LISTENER:
1404 case CONN_TYPE_AP_NATD_LISTENER:
1405 return connection_handle_listener_read(conn, CONN_TYPE_AP);
1406 case CONN_TYPE_DIR_LISTENER:
1407 return connection_handle_listener_read(conn, CONN_TYPE_DIR);
1408 case CONN_TYPE_CONTROL_LISTENER:
1409 return connection_handle_listener_read(conn, CONN_TYPE_CONTROL);
1412 loop_again:
1413 try_to_read = max_to_read;
1414 tor_assert(!conn->marked_for_close);
1415 if (connection_read_to_buf(conn, &max_to_read) < 0) {
1416 /* There's a read error; kill the connection.*/
1417 connection_close_immediate(conn); /* Don't flush; connection is dead. */
1418 if (CONN_IS_EDGE(conn)) {
1419 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
1420 connection_edge_end_errno(edge_conn, edge_conn->cpath_layer);
1421 if (edge_conn->socks_request) /* broken, don't send a socks reply back */
1422 edge_conn->socks_request->has_finished = 1;
1424 connection_mark_for_close(conn);
1425 return -1;
1427 if (CONN_IS_EDGE(conn) && try_to_read != max_to_read) {
1428 /* instruct it not to try to package partial cells. */
1429 if (connection_process_inbuf(conn, 0) < 0) {
1430 return -1;
1432 if (!conn->marked_for_close &&
1433 connection_is_reading(conn) &&
1434 !conn->inbuf_reached_eof &&
1435 max_to_read > 0)
1436 goto loop_again; /* try reading again, in case more is here now */
1438 /* one last try, packaging partial cells and all. */
1439 if (!conn->marked_for_close &&
1440 connection_process_inbuf(conn, 1) < 0) {
1441 return -1;
1443 if (!conn->marked_for_close &&
1444 conn->inbuf_reached_eof &&
1445 connection_reached_eof(conn) < 0) {
1446 return -1;
1448 return 0;
1451 /** Pull in new bytes from conn-\>s onto conn-\>inbuf, either
1452 * directly or via TLS. Reduce the token buckets by the number of
1453 * bytes read.
1455 * If *max_to_read is -1, then decide it ourselves, else go with the
1456 * value passed to us. When returning, if it's changed, subtract the
1457 * number of bytes we read from *max_to_read.
1459 * Return -1 if we want to break conn, else return 0.
1461 static int
1462 connection_read_to_buf(connection_t *conn, int *max_to_read)
1464 int result, at_most = *max_to_read;
1465 size_t bytes_in_buf, more_to_read;
1466 size_t n_read = 0, n_written = 0;
1468 if (at_most == -1) { /* we need to initialize it */
1469 /* how many bytes are we allowed to read? */
1470 at_most = connection_bucket_read_limit(conn);
1473 bytes_in_buf = buf_capacity(conn->inbuf) - buf_datalen(conn->inbuf);
1474 again:
1475 if ((size_t)at_most > bytes_in_buf && bytes_in_buf >= 1024) {
1476 more_to_read = at_most - bytes_in_buf;
1477 at_most = bytes_in_buf;
1478 } else {
1479 more_to_read = 0;
1482 if (connection_speaks_cells(conn) &&
1483 conn->state > OR_CONN_STATE_PROXY_READING) {
1484 int pending;
1485 or_connection_t *or_conn = TO_OR_CONN(conn);
1486 if (conn->state == OR_CONN_STATE_HANDSHAKING) {
1487 /* continue handshaking even if global token bucket is empty */
1488 return connection_tls_continue_handshake(or_conn);
1491 log_debug(LD_NET,
1492 "%d: starting, inbuf_datalen %d (%d pending in tls object)."
1493 " at_most %d.",
1494 conn->s,(int)buf_datalen(conn->inbuf),
1495 tor_tls_get_pending_bytes(or_conn->tls), at_most);
1497 /* else open, or closing */
1498 result = read_to_buf_tls(or_conn->tls, at_most, conn->inbuf);
1499 if (TOR_TLS_IS_ERROR(result) || result == TOR_TLS_CLOSE)
1500 or_conn->tls_error = result;
1501 else
1502 or_conn->tls_error = 0;
1504 switch (result) {
1505 case TOR_TLS_CLOSE:
1506 log_info(LD_NET,"TLS connection closed on read. Closing. "
1507 "(Nickname %s, address %s",
1508 or_conn->nickname ? or_conn->nickname : "not set",
1509 conn->address);
1510 return result;
1511 CASE_TOR_TLS_ERROR_ANY:
1512 log_info(LD_NET,"tls error. breaking (nickname %s, address %s).",
1513 or_conn->nickname ? or_conn->nickname : "not set",
1514 conn->address);
1515 return result;
1516 case TOR_TLS_WANTWRITE:
1517 connection_start_writing(conn);
1518 return 0;
1519 case TOR_TLS_WANTREAD: /* we're already reading */
1520 case TOR_TLS_DONE: /* no data read, so nothing to process */
1521 result = 0;
1522 break; /* so we call bucket_decrement below */
1523 default:
1524 break;
1526 pending = tor_tls_get_pending_bytes(or_conn->tls);
1527 if (pending) {
1528 /* If we have any pending bytes, we read them now. This *can*
1529 * take us over our read allotment, but really we shouldn't be
1530 * believing that SSL bytes are the same as TCP bytes anyway. */
1531 int r2 = read_to_buf_tls(or_conn->tls, pending, conn->inbuf);
1532 if (r2<0) {
1533 log_warn(LD_BUG, "Bug: apparently, reading pending bytes can fail.");
1534 return -1;
1535 } else {
1536 result += r2;
1540 tor_tls_get_n_raw_bytes(or_conn->tls, &n_read, &n_written);
1541 log_debug(LD_GENERAL, "After TLS read of %d: %ld read, %ld written",
1542 result, (long)n_read, (long)n_written);
1543 } else {
1544 int reached_eof = 0;
1545 CONN_LOG_PROTECT(conn,
1546 result = read_to_buf(conn->s, at_most, conn->inbuf, &reached_eof));
1547 if (reached_eof)
1548 conn->inbuf_reached_eof = 1;
1550 // log_fn(LOG_DEBUG,"read_to_buf returned %d.",read_result);
1552 if (result < 0)
1553 return -1;
1554 n_read = (size_t) result;
1557 if (n_read > 0) { /* change *max_to_read */
1558 *max_to_read = at_most - n_read;
1561 if (connection_is_rate_limited(conn)) {
1562 /* For non-local IPs, remember if we flushed any bytes over the wire. */
1563 time_t now = time(NULL);
1564 if (n_read > 0) {
1565 rep_hist_note_bytes_read(n_read, now);
1566 connection_read_bucket_decrement(conn, n_read);
1568 if (n_written > 0) {
1569 rep_hist_note_bytes_written(n_written, now);
1570 global_write_bucket -= n_written;
1574 if (more_to_read && result == at_most) {
1575 bytes_in_buf = buf_capacity(conn->inbuf) - buf_datalen(conn->inbuf);
1576 tor_assert(bytes_in_buf < 1024);
1577 at_most = more_to_read;
1578 goto again;
1581 /* Call even if result is 0, since the global read bucket may
1582 * have reached 0 on a different conn, and this guy needs to
1583 * know to stop reading. */
1584 connection_consider_empty_read_buckets(conn);
1585 if (n_written > 0 && connection_is_writing(conn))
1586 connection_consider_empty_write_buckets(conn);
1588 return 0;
1591 /** A pass-through to fetch_from_buf. */
1593 connection_fetch_from_buf(char *string, size_t len, connection_t *conn)
1595 return fetch_from_buf(string, len, conn->inbuf);
1598 /** Return conn-\>outbuf_flushlen: how many bytes conn wants to flush
1599 * from its outbuf. */
1601 connection_wants_to_flush(connection_t *conn)
1603 return conn->outbuf_flushlen;
1606 /** Are there too many bytes on edge connection <b>conn</b>'s outbuf to
1607 * send back a relay-level sendme yet? Return 1 if so, 0 if not. Used by
1608 * connection_edge_consider_sending_sendme().
1611 connection_outbuf_too_full(connection_t *conn)
1613 return (conn->outbuf_flushlen > 10*CELL_PAYLOAD_SIZE);
1616 /** Try to flush more bytes onto conn-\>s.
1618 * This function gets called either from conn_write() in main.c
1619 * when poll() has declared that conn wants to write, or below
1620 * from connection_write_to_buf() when an entire TLS record is ready.
1622 * Update conn-\>timestamp_lastwritten to now, and call flush_buf
1623 * or flush_buf_tls appropriately. If it succeeds and there are no more
1624 * more bytes on conn->outbuf, then call connection_finished_flushing
1625 * on it too.
1627 * If <b>force</b>, then write as many bytes as possible, ignoring bandwidth
1628 * limits. (Used for flushing messages to controller connections on fatal
1629 * errors.)
1631 * Mark the connection and return -1 if you want to close it, else
1632 * return 0.
1635 connection_handle_write(connection_t *conn, int force)
1637 int e;
1638 socklen_t len=sizeof(e);
1639 int result;
1640 int max_to_write;
1641 time_t now = time(NULL);
1642 size_t n_read = 0, n_written = 0;
1644 tor_assert(!connection_is_listener(conn));
1646 if (conn->marked_for_close || conn->s < 0)
1647 return 0; /* do nothing */
1649 conn->timestamp_lastwritten = now;
1651 /* Sometimes, "writable" means "connected". */
1652 if (connection_state_is_connecting(conn)) {
1653 if (getsockopt(conn->s, SOL_SOCKET, SO_ERROR, (void*)&e, &len) < 0) {
1654 log_warn(LD_BUG,
1655 "getsockopt() syscall failed?! Please report to tor-ops.");
1656 if (CONN_IS_EDGE(conn))
1657 connection_edge_end_errno(TO_EDGE_CONN(conn),
1658 TO_EDGE_CONN(conn)->cpath_layer);
1659 connection_mark_for_close(conn);
1660 return -1;
1662 if (e) {
1663 /* some sort of error, but maybe just inprogress still */
1664 if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
1665 log_info(LD_NET,"in-progress connect failed. Removing.");
1666 if (CONN_IS_EDGE(conn))
1667 connection_edge_end_errno(TO_EDGE_CONN(conn),
1668 TO_EDGE_CONN(conn)->cpath_layer);
1670 connection_close_immediate(conn);
1671 connection_mark_for_close(conn);
1672 /* it's safe to pass OPs to router_set_status(), since it just
1673 * ignores unrecognized routers
1675 if (conn->type == CONN_TYPE_OR && !get_options()->HttpsProxy)
1676 router_set_status(TO_OR_CONN(conn)->identity_digest, 0);
1677 return -1;
1678 } else {
1679 return 0; /* no change, see if next time is better */
1682 /* The connection is successful. */
1683 if (connection_finished_connecting(conn)<0)
1684 return -1;
1687 max_to_write = force ? (int)conn->outbuf_flushlen
1688 : connection_bucket_write_limit(conn);
1690 if (connection_speaks_cells(conn) &&
1691 conn->state > OR_CONN_STATE_PROXY_READING) {
1692 or_connection_t *or_conn = TO_OR_CONN(conn);
1693 if (conn->state == OR_CONN_STATE_HANDSHAKING) {
1694 connection_stop_writing(conn);
1695 if (connection_tls_continue_handshake(or_conn) < 0) {
1696 /* Don't flush; connection is dead. */
1697 connection_close_immediate(conn);
1698 connection_mark_for_close(conn);
1699 return -1;
1701 return 0;
1704 /* else open, or closing */
1705 result = flush_buf_tls(or_conn->tls, conn->outbuf,
1706 max_to_write, &conn->outbuf_flushlen);
1707 switch (result) {
1708 CASE_TOR_TLS_ERROR_ANY:
1709 case TOR_TLS_CLOSE:
1710 log_info(LD_NET,result!=TOR_TLS_CLOSE?
1711 "tls error. breaking.":"TLS connection closed on flush");
1712 /* Don't flush; connection is dead. */
1713 connection_close_immediate(conn);
1714 connection_mark_for_close(conn);
1715 return -1;
1716 case TOR_TLS_WANTWRITE:
1717 log_debug(LD_NET,"wanted write.");
1718 /* we're already writing */
1719 return 0;
1720 case TOR_TLS_WANTREAD:
1721 /* Make sure to avoid a loop if the receive buckets are empty. */
1722 log_debug(LD_NET,"wanted read.");
1723 if (!connection_is_reading(conn)) {
1724 connection_stop_writing(conn);
1725 conn->wants_to_write = 1;
1726 /* we'll start reading again when the next second arrives,
1727 * and then also start writing again.
1730 /* else no problem, we're already reading */
1731 return 0;
1732 /* case TOR_TLS_DONE:
1733 * for TOR_TLS_DONE, fall through to check if the flushlen
1734 * is empty, so we can stop writing.
1738 tor_tls_get_n_raw_bytes(or_conn->tls, &n_read, &n_written);
1739 log_debug(LD_GENERAL, "After TLS write of %d: %ld read, %ld written",
1740 result, (long)n_read, (long)n_written);
1741 } else {
1742 CONN_LOG_PROTECT(conn,
1743 result = flush_buf(conn->s, conn->outbuf,
1744 max_to_write, &conn->outbuf_flushlen));
1745 if (result < 0) {
1746 if (CONN_IS_EDGE(conn))
1747 connection_edge_end_errno(TO_EDGE_CONN(conn),
1748 TO_EDGE_CONN(conn)->cpath_layer);
1750 connection_close_immediate(conn); /* Don't flush; connection is dead. */
1751 connection_mark_for_close(conn);
1752 return -1;
1754 n_written = (size_t) result;
1757 if (connection_is_rate_limited(conn)) {
1758 /* For non-local IPs, remember if we flushed any bytes over the wire. */
1759 time_t now = time(NULL);
1760 if (n_written > 0) {
1761 rep_hist_note_bytes_written(n_written, now);
1762 global_write_bucket -= n_written;
1764 if (n_read > 0) {
1765 rep_hist_note_bytes_read(n_read, now);
1766 connection_read_bucket_decrement(conn, n_read);
1770 if (result > 0) {
1771 /* If we wrote any bytes from our buffer, then call the appropriate
1772 * functions. */
1773 if (connection_flushed_some(conn) < 0)
1774 connection_mark_for_close(conn);
1777 if (!connection_wants_to_flush(conn)) { /* it's done flushing */
1778 if (connection_finished_flushing(conn) < 0) {
1779 /* already marked */
1780 return -1;
1782 return 0;
1785 /* Call even if result is 0, since the global write bucket may
1786 * have reached 0 on a different conn, and this guy needs to
1787 * know to stop writing. */
1788 connection_consider_empty_write_buckets(conn);
1789 if (n_read > 0 && connection_is_reading(conn))
1790 connection_consider_empty_read_buckets(conn);
1792 return 0;
1795 /** Openssl TLS record size is 16383; this is close. The goal here is to
1796 * push data out as soon as we know there's enough for a TLS record, so
1797 * during periods of high load we won't read entire megabytes from
1798 * input before pushing any data out. It also has the feature of not
1799 * growing huge outbufs unless something is slow. */
1800 #define MIN_TLS_FLUSHLEN 15872
1802 /** Append <b>len</b> bytes of <b>string</b> onto <b>conn</b>'s
1803 * outbuf, and ask it to start writing.
1805 * If <b>zlib</b> is nonzero, this is a directory connection that should get
1806 * its contents compressed or decompressed as they're written. If zlib is
1807 * negative, this is the last data to be compressed, and the connection's zlib
1808 * state should be flushed.
1810 * If it's an OR conn and an entire TLS record is ready, then try to
1811 * flush the record now. Similarly, if it's a local control connection
1812 * and a 64k chunk is ready, try to flush it all, so we don't end up with
1813 * many megabytes of controller info queued at once.
1815 void
1816 _connection_write_to_buf_impl(const char *string, size_t len,
1817 connection_t *conn, int zlib)
1819 int r;
1820 size_t old_datalen;
1821 if (!len)
1822 return;
1823 /* if it's marked for close, only allow write if we mean to flush it */
1824 if (conn->marked_for_close && !conn->hold_open_until_flushed)
1825 return;
1827 old_datalen = buf_datalen(conn->outbuf);
1828 if (zlib) {
1829 dir_connection_t *dir_conn = TO_DIR_CONN(conn);
1830 int done = zlib < 0;
1831 CONN_LOG_PROTECT(conn, r = write_to_buf_zlib(conn->outbuf,
1832 dir_conn->zlib_state,
1833 string, len, done));
1834 } else {
1835 CONN_LOG_PROTECT(conn, r = write_to_buf(string, len, conn->outbuf));
1837 if (r < 0) {
1838 if (CONN_IS_EDGE(conn)) {
1839 /* if it failed, it means we have our package/delivery windows set
1840 wrong compared to our max outbuf size. close the whole circuit. */
1841 log_warn(LD_NET,
1842 "write_to_buf failed. Closing circuit (fd %d).", conn->s);
1843 circuit_mark_for_close(circuit_get_by_edge_conn(TO_EDGE_CONN(conn)),
1844 END_CIRC_REASON_INTERNAL);
1845 } else {
1846 log_warn(LD_NET,
1847 "write_to_buf failed. Closing connection (fd %d).", conn->s);
1848 connection_mark_for_close(conn);
1850 return;
1853 connection_start_writing(conn);
1854 if (zlib) {
1855 conn->outbuf_flushlen += buf_datalen(conn->outbuf) - old_datalen;
1856 } else {
1857 int extra = 0;
1858 conn->outbuf_flushlen += len;
1860 if (conn->type == CONN_TYPE_OR &&
1861 conn->outbuf_flushlen-len < MIN_TLS_FLUSHLEN &&
1862 conn->outbuf_flushlen >= MIN_TLS_FLUSHLEN) {
1863 extra = conn->outbuf_flushlen - MIN_TLS_FLUSHLEN;
1864 conn->outbuf_flushlen = MIN_TLS_FLUSHLEN;
1865 } else if (conn->type == CONN_TYPE_CONTROL &&
1866 !connection_is_rate_limited(conn) &&
1867 conn->outbuf_flushlen-len < 1<<16 &&
1868 conn->outbuf_flushlen >= 1<<16) {
1869 /* just try to flush all of it */
1870 } else
1871 return; /* no need to try flushing */
1873 if (connection_handle_write(conn, 0) < 0) {
1874 if (!conn->marked_for_close) {
1875 /* this connection is broken. remove it. */
1876 log_warn(LD_BUG, "Bug: unhandled error on write for "
1877 "conn (type %d, fd %d); removing",
1878 conn->type, conn->s);
1879 tor_fragile_assert();
1880 /* do a close-immediate here, so we don't try to flush */
1881 connection_close_immediate(conn);
1883 return;
1885 if (extra) {
1886 conn->outbuf_flushlen += extra;
1887 connection_start_writing(conn);
1892 /** Return the conn to addr/port that has the most recent
1893 * timestamp_created, or NULL if no such conn exists. */
1894 or_connection_t *
1895 connection_or_exact_get_by_addr_port(uint32_t addr, uint16_t port)
1897 int i, n;
1898 connection_t *conn;
1899 or_connection_t *best=NULL;
1900 connection_t **carray;
1902 get_connection_array(&carray,&n);
1903 for (i=0;i<n;i++) {
1904 conn = carray[i];
1905 if (conn->type == CONN_TYPE_OR &&
1906 conn->addr == addr &&
1907 conn->port == port &&
1908 !conn->marked_for_close &&
1909 (!best || best->_base.timestamp_created < conn->timestamp_created))
1910 best = TO_OR_CONN(conn);
1912 return best;
1915 /** Return a connection with given type, address, port, and purpose;
1916 * or NULL if no such connection exists. */
1917 connection_t *
1918 connection_get_by_type_addr_port_purpose(int type,
1919 uint32_t addr, uint16_t port,
1920 int purpose)
1922 int i, n;
1923 connection_t *conn;
1924 connection_t **carray;
1926 get_connection_array(&carray,&n);
1927 for (i=0;i<n;i++) {
1928 conn = carray[i];
1929 if (conn->type == type &&
1930 conn->addr == addr &&
1931 conn->port == port &&
1932 conn->purpose == purpose &&
1933 !conn->marked_for_close)
1934 return conn;
1936 return NULL;
1939 /** Return the stream with id <b>id</b> if it is not already marked for
1940 * close.
1942 edge_connection_t *
1943 connection_get_by_global_id(uint32_t id)
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_IS_EDGE(conn) && TO_EDGE_CONN(conn)->global_identifier == id) {
1953 if (!conn->marked_for_close)
1954 return TO_EDGE_CONN(conn);
1955 else
1956 return NULL;
1959 return NULL;
1962 /** Return a connection of type <b>type</b> that is not marked for close.
1964 connection_t *
1965 connection_get_by_type(int type)
1967 int i, n;
1968 connection_t *conn;
1969 connection_t **carray;
1971 get_connection_array(&carray,&n);
1972 for (i=0;i<n;i++) {
1973 conn = carray[i];
1974 if (conn->type == type && !conn->marked_for_close)
1975 return conn;
1977 return NULL;
1980 /** Return a connection of type <b>type</b> that is in state <b>state</b>,
1981 * and that is not marked for close.
1983 connection_t *
1984 connection_get_by_type_state(int type, int state)
1986 int i, n;
1987 connection_t *conn;
1988 connection_t **carray;
1990 get_connection_array(&carray,&n);
1991 for (i=0;i<n;i++) {
1992 conn = carray[i];
1993 if (conn->type == type && conn->state == state && !conn->marked_for_close)
1994 return conn;
1996 return NULL;
1999 /** Return the connection of type <b>type</b> that is in state
2000 * <b>state</b>, that was written to least recently, and that is not
2001 * marked for close.
2003 connection_t *
2004 connection_get_by_type_state_lastwritten(int type, int state)
2006 int i, n;
2007 connection_t *conn, *best=NULL;
2008 connection_t **carray;
2010 get_connection_array(&carray,&n);
2011 for (i=0;i<n;i++) {
2012 conn = carray[i];
2013 if (conn->type == type && conn->state == state && !conn->marked_for_close)
2014 if (!best || conn->timestamp_lastwritten < best->timestamp_lastwritten)
2015 best = conn;
2017 return best;
2020 /** Return a connection of type <b>type</b> that has rendquery equal
2021 * to <b>rendquery</b>, and that is not marked for close. If state
2022 * is non-zero, conn must be of that state too.
2024 connection_t *
2025 connection_get_by_type_state_rendquery(int type, int state,
2026 const char *rendquery)
2028 int i, n;
2029 connection_t *conn;
2030 connection_t **carray;
2032 tor_assert(type == CONN_TYPE_DIR ||
2033 type == CONN_TYPE_AP || type == CONN_TYPE_EXIT);
2035 get_connection_array(&carray,&n);
2036 for (i=0;i<n;i++) {
2037 conn = carray[i];
2038 if (conn->type == type &&
2039 !conn->marked_for_close &&
2040 (!state || state == conn->state)) {
2041 if (type == CONN_TYPE_DIR &&
2042 rend_cmp_service_ids(rendquery, TO_DIR_CONN(conn)->rend_query))
2043 return conn;
2044 else if (CONN_IS_EDGE(conn) &&
2045 rend_cmp_service_ids(rendquery, TO_EDGE_CONN(conn)->rend_query))
2046 return conn;
2049 return NULL;
2052 /** Return an open, non-marked connection of a given type and purpose, or NULL
2053 * if no such connection exists. */
2054 connection_t *
2055 connection_get_by_type_purpose(int type, int purpose)
2057 int i, n;
2058 connection_t *conn;
2059 connection_t **carray;
2061 get_connection_array(&carray,&n);
2062 for (i=0;i<n;i++) {
2063 conn = carray[i];
2064 if (conn->type == type &&
2065 !conn->marked_for_close &&
2066 (purpose == conn->purpose))
2067 return conn;
2069 return NULL;
2072 /** Return 1 if <b>conn</b> is a listener conn, else return 0. */
2074 connection_is_listener(connection_t *conn)
2076 if (conn->type == CONN_TYPE_OR_LISTENER ||
2077 conn->type == CONN_TYPE_AP_LISTENER ||
2078 conn->type == CONN_TYPE_AP_TRANS_LISTENER ||
2079 conn->type == CONN_TYPE_AP_NATD_LISTENER ||
2080 conn->type == CONN_TYPE_DIR_LISTENER ||
2081 conn->type == CONN_TYPE_CONTROL_LISTENER)
2082 return 1;
2083 return 0;
2086 /** Return 1 if <b>conn</b> is in state "open" and is not marked
2087 * for close, else return 0.
2090 connection_state_is_open(connection_t *conn)
2092 tor_assert(conn);
2094 if (conn->marked_for_close)
2095 return 0;
2097 if ((conn->type == CONN_TYPE_OR && conn->state == OR_CONN_STATE_OPEN) ||
2098 (conn->type == CONN_TYPE_AP && conn->state == AP_CONN_STATE_OPEN) ||
2099 (conn->type == CONN_TYPE_EXIT && conn->state == EXIT_CONN_STATE_OPEN) ||
2100 (conn->type == CONN_TYPE_CONTROL &&
2101 (conn->state == CONTROL_CONN_STATE_OPEN_V0 ||
2102 conn->state == CONTROL_CONN_STATE_OPEN_V1)))
2103 return 1;
2105 return 0;
2108 /** Return 1 if conn is in 'connecting' state, else return 0. */
2110 connection_state_is_connecting(connection_t *conn)
2112 tor_assert(conn);
2114 if (conn->marked_for_close)
2115 return 0;
2116 switch (conn->type)
2118 case CONN_TYPE_OR:
2119 return conn->state == OR_CONN_STATE_CONNECTING;
2120 case CONN_TYPE_EXIT:
2121 return conn->state == EXIT_CONN_STATE_CONNECTING;
2122 case CONN_TYPE_DIR:
2123 return conn->state == DIR_CONN_STATE_CONNECTING;
2126 return 0;
2129 /** Allocates a base64'ed authenticator for use in http or https
2130 * auth, based on the input string <b>authenticator</b>. Returns it
2131 * if success, else returns NULL. */
2132 char *
2133 alloc_http_authenticator(const char *authenticator)
2135 /* an authenticator in Basic authentication
2136 * is just the string "username:password" */
2137 const int authenticator_length = strlen(authenticator);
2138 /* The base64_encode function needs a minimum buffer length
2139 * of 66 bytes. */
2140 const int base64_authenticator_length = (authenticator_length/48+1)*66;
2141 char *base64_authenticator = tor_malloc(base64_authenticator_length);
2142 if (base64_encode(base64_authenticator, base64_authenticator_length,
2143 authenticator, authenticator_length) < 0) {
2144 tor_free(base64_authenticator); /* free and set to null */
2145 } else {
2146 /* remove extra \n at end of encoding */
2147 base64_authenticator[strlen(base64_authenticator) - 1] = 0;
2149 return base64_authenticator;
2152 /** Given a socket handle, check whether the local address (sockname) of the
2153 * socket is one that we've connected from before. If so, double-check
2154 * whether our address has changed and we need to generate keys. If we do,
2155 * call init_keys().
2157 static void
2158 client_check_address_changed(int sock)
2160 uint32_t iface_ip, ip_out;
2161 struct sockaddr_in out_addr;
2162 socklen_t out_addr_len = sizeof(out_addr);
2163 uint32_t *ip;
2165 if (!last_interface_ip)
2166 get_interface_address(LOG_INFO, &last_interface_ip);
2167 if (!outgoing_addrs)
2168 outgoing_addrs = smartlist_create();
2170 if (getsockname(sock, (struct sockaddr*)&out_addr, &out_addr_len)<0) {
2171 int e = tor_socket_errno(sock);
2172 log_warn(LD_NET, "getsockname() to check for address change failed: %s",
2173 tor_socket_strerror(e));
2174 return;
2177 /* Okay. If we've used this address previously, we're okay. */
2178 ip_out = ntohl(out_addr.sin_addr.s_addr);
2179 SMARTLIST_FOREACH(outgoing_addrs, uint32_t*, ip,
2180 if (*ip == ip_out) return;
2183 /* Uh-oh. We haven't connected from this address before. Has the interface
2184 * address changed? */
2185 if (get_interface_address(LOG_INFO, &iface_ip)<0)
2186 return;
2187 ip = tor_malloc(sizeof(uint32_t));
2188 *ip = ip_out;
2190 if (iface_ip == last_interface_ip) {
2191 /* Nope, it hasn't changed. Add this address to the list. */
2192 smartlist_add(outgoing_addrs, ip);
2193 } else {
2194 /* The interface changed. We're a client, so we need to regenerate our
2195 * keys. First, reset the state. */
2196 log(LOG_NOTICE, LD_NET, "Our IP has changed. Rotating keys...");
2197 last_interface_ip = iface_ip;
2198 SMARTLIST_FOREACH(outgoing_addrs, void*, ip, tor_free(ip));
2199 smartlist_clear(outgoing_addrs);
2200 smartlist_add(outgoing_addrs, ip);
2201 /* Okay, now change our keys. */
2202 ip_address_changed(1);
2206 /** Process new bytes that have arrived on conn-\>inbuf.
2208 * This function just passes conn to the connection-specific
2209 * connection_*_process_inbuf() function. It also passes in
2210 * package_partial if wanted.
2212 static int
2213 connection_process_inbuf(connection_t *conn, int package_partial)
2215 tor_assert(conn);
2217 switch (conn->type) {
2218 case CONN_TYPE_OR:
2219 return connection_or_process_inbuf(TO_OR_CONN(conn));
2220 case CONN_TYPE_EXIT:
2221 case CONN_TYPE_AP:
2222 return connection_edge_process_inbuf(TO_EDGE_CONN(conn),
2223 package_partial);
2224 case CONN_TYPE_DIR:
2225 return connection_dir_process_inbuf(TO_DIR_CONN(conn));
2226 case CONN_TYPE_DNSWORKER:
2227 return connection_dns_process_inbuf(conn);
2228 case CONN_TYPE_CPUWORKER:
2229 return connection_cpu_process_inbuf(conn);
2230 case CONN_TYPE_CONTROL:
2231 return connection_control_process_inbuf(TO_CONTROL_CONN(conn));
2232 default:
2233 log_err(LD_BUG,"Bug: got unexpected conn type %d.", conn->type);
2234 tor_fragile_assert();
2235 return -1;
2239 /** Called whenever we've written data on a connection. */
2240 static int
2241 connection_flushed_some(connection_t *conn)
2243 if (conn->type == CONN_TYPE_DIR &&
2244 conn->state == DIR_CONN_STATE_SERVER_WRITING)
2245 return connection_dirserv_flushed_some(TO_DIR_CONN(conn));
2246 else
2247 return 0;
2250 /** We just finished flushing bytes from conn-\>outbuf, and there
2251 * are no more bytes remaining.
2253 * This function just passes conn to the connection-specific
2254 * connection_*_finished_flushing() function.
2256 static int
2257 connection_finished_flushing(connection_t *conn)
2259 tor_assert(conn);
2261 // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
2263 switch (conn->type) {
2264 case CONN_TYPE_OR:
2265 return connection_or_finished_flushing(TO_OR_CONN(conn));
2266 case CONN_TYPE_AP:
2267 case CONN_TYPE_EXIT:
2268 return connection_edge_finished_flushing(TO_EDGE_CONN(conn));
2269 case CONN_TYPE_DIR:
2270 return connection_dir_finished_flushing(TO_DIR_CONN(conn));
2271 case CONN_TYPE_DNSWORKER:
2272 return connection_dns_finished_flushing(conn);
2273 case CONN_TYPE_CPUWORKER:
2274 return connection_cpu_finished_flushing(conn);
2275 case CONN_TYPE_CONTROL:
2276 return connection_control_finished_flushing(TO_CONTROL_CONN(conn));
2277 default:
2278 log_err(LD_BUG,"Bug: got unexpected conn type %d.", conn->type);
2279 tor_fragile_assert();
2280 return -1;
2284 /** Called when our attempt to connect() to another server has just
2285 * succeeded.
2287 * This function just passes conn to the connection-specific
2288 * connection_*_finished_connecting() function.
2290 static int
2291 connection_finished_connecting(connection_t *conn)
2293 tor_assert(conn);
2294 switch (conn->type)
2296 case CONN_TYPE_OR:
2297 return connection_or_finished_connecting(TO_OR_CONN(conn));
2298 case CONN_TYPE_EXIT:
2299 return connection_edge_finished_connecting(TO_EDGE_CONN(conn));
2300 case CONN_TYPE_DIR:
2301 return connection_dir_finished_connecting(TO_DIR_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 /** Callback: invoked when a connection reaches an EOF event. */
2310 static int
2311 connection_reached_eof(connection_t *conn)
2313 switch (conn->type) {
2314 case CONN_TYPE_OR:
2315 return connection_or_reached_eof(TO_OR_CONN(conn));
2316 case CONN_TYPE_AP:
2317 case CONN_TYPE_EXIT:
2318 return connection_edge_reached_eof(TO_EDGE_CONN(conn));
2319 case CONN_TYPE_DIR:
2320 return connection_dir_reached_eof(TO_DIR_CONN(conn));
2321 case CONN_TYPE_DNSWORKER:
2322 return connection_dns_reached_eof(conn);
2323 case CONN_TYPE_CPUWORKER:
2324 return connection_cpu_reached_eof(conn);
2325 case CONN_TYPE_CONTROL:
2326 return connection_control_reached_eof(TO_CONTROL_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 /** Verify that connection <b>conn</b> has all of its invariants
2335 * correct. Trigger an assert if anything is invalid.
2337 void
2338 assert_connection_ok(connection_t *conn, time_t now)
2340 (void) now; /* XXXX unused. */
2341 tor_assert(conn);
2342 tor_assert(conn->type >= _CONN_TYPE_MIN);
2343 tor_assert(conn->type <= _CONN_TYPE_MAX);
2344 switch (conn->type) {
2345 case CONN_TYPE_OR:
2346 tor_assert(conn->magic == OR_CONNECTION_MAGIC);
2347 break;
2348 case CONN_TYPE_AP:
2349 case CONN_TYPE_EXIT:
2350 tor_assert(conn->magic == EDGE_CONNECTION_MAGIC);
2351 break;
2352 case CONN_TYPE_DIR:
2353 tor_assert(conn->magic == DIR_CONNECTION_MAGIC);
2354 break;
2355 case CONN_TYPE_CONTROL:
2356 tor_assert(conn->magic == CONTROL_CONNECTION_MAGIC);
2357 break;
2358 default:
2359 tor_assert(conn->magic == BASE_CONNECTION_MAGIC);
2360 break;
2363 if (conn->outbuf_flushlen > 0) {
2364 tor_assert(connection_is_writing(conn) || conn->wants_to_write);
2367 if (conn->hold_open_until_flushed)
2368 tor_assert(conn->marked_for_close);
2370 /* XXXX012 check: wants_to_read, wants_to_write, s, conn_array_index,
2371 * marked_for_close. */
2373 /* buffers */
2374 if (!connection_is_listener(conn)) {
2375 assert_buf_ok(conn->inbuf);
2376 assert_buf_ok(conn->outbuf);
2379 /* XXXX012 Fix this; no longer so.*/
2380 #if 0
2381 if (conn->type != CONN_TYPE_OR && conn->type != CONN_TYPE_DIR)
2382 tor_assert(!conn->pkey);
2383 /* pkey is set if we're a dir client, or if we're an OR in state OPEN
2384 * connected to another OR.
2386 #endif
2388 if (conn->chosen_exit_optional) {
2389 tor_assert(conn->type == CONN_TYPE_AP);
2390 tor_assert((TO_EDGE_CONN(conn))->chosen_exit_name);
2393 if (conn->type == CONN_TYPE_OR) {
2394 or_connection_t *or_conn = TO_OR_CONN(conn);
2395 if (conn->state == OR_CONN_STATE_OPEN) {
2396 /* tor_assert(conn->bandwidth > 0); */
2397 /* the above isn't necessarily true: if we just did a TLS
2398 * handshake but we didn't recognize the other peer, or it
2399 * gave a bad cert/etc, then we won't have assigned bandwidth,
2400 * yet it will be open. -RD
2402 // tor_assert(conn->read_bucket >= 0);
2404 // tor_assert(conn->addr && conn->port);
2405 tor_assert(conn->address);
2406 if (conn->state > OR_CONN_STATE_PROXY_READING)
2407 tor_assert(or_conn->tls);
2410 if (CONN_IS_EDGE(conn)) {
2411 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
2412 /* XXX unchecked: package window, deliver window. */
2413 if (conn->type == CONN_TYPE_AP) {
2415 tor_assert(edge_conn->socks_request);
2416 if (conn->state == AP_CONN_STATE_OPEN) {
2417 tor_assert(edge_conn->socks_request->has_finished);
2418 if (!conn->marked_for_close) {
2419 tor_assert(edge_conn->cpath_layer);
2420 assert_cpath_layer_ok(edge_conn->cpath_layer);
2424 if (conn->type == CONN_TYPE_EXIT) {
2425 tor_assert(conn->purpose == EXIT_PURPOSE_CONNECT ||
2426 conn->purpose == EXIT_PURPOSE_RESOLVE);
2428 } else if (conn->type != CONN_TYPE_DIR) {
2429 /* Purpose is only used for dir and exit types currently */
2430 tor_assert(!conn->purpose);
2433 switch (conn->type)
2435 case CONN_TYPE_OR_LISTENER:
2436 case CONN_TYPE_AP_LISTENER:
2437 case CONN_TYPE_AP_TRANS_LISTENER:
2438 case CONN_TYPE_AP_NATD_LISTENER:
2439 case CONN_TYPE_DIR_LISTENER:
2440 case CONN_TYPE_CONTROL_LISTENER:
2441 tor_assert(conn->state == LISTENER_STATE_READY);
2442 break;
2443 case CONN_TYPE_OR:
2444 tor_assert(conn->state >= _OR_CONN_STATE_MIN);
2445 tor_assert(conn->state <= _OR_CONN_STATE_MAX);
2446 tor_assert(TO_OR_CONN(conn)->n_circuits >= 0);
2447 break;
2448 case CONN_TYPE_EXIT:
2449 tor_assert(conn->state >= _EXIT_CONN_STATE_MIN);
2450 tor_assert(conn->state <= _EXIT_CONN_STATE_MAX);
2451 tor_assert(conn->purpose >= _EXIT_PURPOSE_MIN);
2452 tor_assert(conn->purpose <= _EXIT_PURPOSE_MAX);
2453 break;
2454 case CONN_TYPE_AP:
2455 tor_assert(conn->state >= _AP_CONN_STATE_MIN);
2456 tor_assert(conn->state <= _AP_CONN_STATE_MAX);
2457 tor_assert(TO_EDGE_CONN(conn)->socks_request);
2458 break;
2459 case CONN_TYPE_DIR:
2460 tor_assert(conn->state >= _DIR_CONN_STATE_MIN);
2461 tor_assert(conn->state <= _DIR_CONN_STATE_MAX);
2462 tor_assert(conn->purpose >= _DIR_PURPOSE_MIN);
2463 tor_assert(conn->purpose <= _DIR_PURPOSE_MAX);
2464 break;
2465 case CONN_TYPE_DNSWORKER:
2466 tor_assert(conn->state >= _DNSWORKER_STATE_MIN);
2467 tor_assert(conn->state <= _DNSWORKER_STATE_MAX);
2468 break;
2469 case CONN_TYPE_CPUWORKER:
2470 tor_assert(conn->state >= _CPUWORKER_STATE_MIN);
2471 tor_assert(conn->state <= _CPUWORKER_STATE_MAX);
2472 break;
2473 case CONN_TYPE_CONTROL:
2474 tor_assert(conn->state >= _CONTROL_CONN_STATE_MIN);
2475 tor_assert(conn->state <= _CONTROL_CONN_STATE_MAX);
2476 break;
2477 default:
2478 tor_assert(0);