Fix an assert error introduced in 0.1.2.5-alpha: if a single TLS
[tor.git] / src / or / connection.c
blobe4a03ac61ba77e906bb6becf4d96370a3faf938e
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);
440 /* Inform any pending (not attached) circs that they should
441 * give up. */
442 circuit_n_conn_done(TO_OR_CONN(conn), 0);
443 } else if (conn->hold_open_until_flushed) {
444 /* We only set hold_open_until_flushed when we're intentionally
445 * closing a connection. */
446 rep_hist_note_disconnect(or_conn->identity_digest, now);
447 control_event_or_conn_status(or_conn, OR_CONN_EVENT_CLOSED);
448 } else if (or_conn->identity_digest) {
449 rep_hist_note_connection_died(or_conn->identity_digest, now);
450 control_event_or_conn_status(or_conn, OR_CONN_EVENT_CLOSED);
452 /* Now close all the attached circuits on it. */
453 circuit_unlink_all_from_or_conn(TO_OR_CONN(conn),
454 END_CIRC_REASON_OR_CONN_CLOSED);
455 break;
456 case CONN_TYPE_AP:
457 edge_conn = TO_EDGE_CONN(conn);
458 if (edge_conn->socks_request->has_finished == 0) {
459 /* since conn gets removed right after this function finishes,
460 * there's no point trying to send back a reply at this point. */
461 log_warn(LD_BUG,"Bug: Closing stream (marked at %s:%d) without sending"
462 " back a socks reply.",
463 conn->marked_for_close_file, conn->marked_for_close);
465 if (!edge_conn->end_reason) {
466 // XXXX012 Disable this before 0.1.2.x-final ships.
467 log_warn(LD_BUG,"Bug: Closing stream (marked at %s:%d) without having"
468 " set end_reason. Please tell Nick.",
469 conn->marked_for_close_file, conn->marked_for_close);
471 control_event_stream_status(edge_conn, STREAM_EVENT_CLOSED,
472 edge_conn->end_reason);
473 circ = circuit_get_by_edge_conn(edge_conn);
474 if (circ)
475 circuit_detach_stream(circ, edge_conn);
476 break;
477 case CONN_TYPE_EXIT:
478 edge_conn = TO_EDGE_CONN(conn);
479 circ = circuit_get_by_edge_conn(edge_conn);
480 if (circ)
481 circuit_detach_stream(circ, edge_conn);
482 if (conn->state == EXIT_CONN_STATE_RESOLVING) {
483 connection_dns_remove(edge_conn);
485 break;
486 case CONN_TYPE_DNSWORKER:
487 if (conn->state == DNSWORKER_STATE_BUSY) {
488 dns_cancel_pending_resolve(conn->address);
490 break;
494 /** Close the underlying socket for <b>conn</b>, so we don't try to
495 * flush it. Must be used in conjunction with (right before)
496 * connection_mark_for_close().
498 void
499 connection_close_immediate(connection_t *conn)
501 assert_connection_ok(conn,0);
502 if (conn->s < 0) {
503 log_err(LD_BUG,"Bug: Attempt to close already-closed connection.");
504 tor_fragile_assert();
505 return;
507 if (conn->outbuf_flushlen) {
508 log_info(LD_NET,"fd %d, type %s, state %s, %d bytes on outbuf.",
509 conn->s, conn_type_to_string(conn->type),
510 conn_state_to_string(conn->type, conn->state),
511 (int)conn->outbuf_flushlen);
514 connection_unregister(conn);
516 tor_close_socket(conn->s);
517 conn->s = -1;
518 if (!connection_is_listener(conn)) {
519 buf_clear(conn->outbuf);
520 conn->outbuf_flushlen = 0;
524 /** Mark <b>conn</b> to be closed next time we loop through
525 * conn_close_if_marked() in main.c. */
526 void
527 _connection_mark_for_close(connection_t *conn, int line, const char *file)
529 assert_connection_ok(conn,0);
530 tor_assert(line);
531 tor_assert(file);
533 if (conn->marked_for_close) {
534 log(LOG_WARN,LD_BUG,"Duplicate call to connection_mark_for_close at %s:%d"
535 " (first at %s:%d)", file, line, conn->marked_for_close_file,
536 conn->marked_for_close);
537 tor_fragile_assert();
538 return;
541 conn->marked_for_close = line;
542 conn->marked_for_close_file = file;
543 add_connection_to_closeable_list(conn);
545 /* in case we're going to be held-open-til-flushed, reset
546 * the number of seconds since last successful write, so
547 * we get our whole 15 seconds */
548 conn->timestamp_lastwritten = time(NULL);
551 /** Find each connection that has hold_open_until_flushed set to
552 * 1 but hasn't written in the past 15 seconds, and set
553 * hold_open_until_flushed to 0. This means it will get cleaned
554 * up in the next loop through close_if_marked() in main.c.
556 void
557 connection_expire_held_open(void)
559 connection_t **carray, *conn;
560 int n, i;
561 time_t now;
563 now = time(NULL);
565 get_connection_array(&carray, &n);
566 for (i = 0; i < n; ++i) {
567 conn = carray[i];
568 /* If we've been holding the connection open, but we haven't written
569 * for 15 seconds...
571 if (conn->hold_open_until_flushed) {
572 tor_assert(conn->marked_for_close);
573 if (now - conn->timestamp_lastwritten >= 15) {
574 int severity;
575 if (conn->type == CONN_TYPE_EXIT ||
576 (conn->type == CONN_TYPE_DIR &&
577 conn->purpose == DIR_PURPOSE_SERVER))
578 severity = LOG_INFO;
579 else
580 severity = LOG_NOTICE;
581 log_fn(severity, LD_NET,
582 "Giving up on marked_for_close conn that's been flushing "
583 "for 15s (fd %d, type %s, state %s).",
584 conn->s, conn_type_to_string(conn->type),
585 conn_state_to_string(conn->type, conn->state));
586 conn->hold_open_until_flushed = 0;
592 /** Bind a new non-blocking socket listening to
593 * <b>listenaddress</b>:<b>listenport</b>, and add this new connection
594 * (of type <b>type</b>) to the connection array.
596 * If <b>listenaddress</b> includes a port, we bind on that port;
597 * otherwise, we use listenport.
599 static connection_t *
600 connection_create_listener(const char *listenaddress, uint16_t listenport,
601 int type)
603 struct sockaddr_in listenaddr; /* where to bind */
604 char *address = NULL;
605 connection_t *conn;
606 uint16_t usePort;
607 uint32_t addr;
608 int s; /* the socket we're going to make */
609 #ifndef MS_WINDOWS
610 int one=1;
611 #endif
613 memset(&listenaddr,0,sizeof(struct sockaddr_in));
614 if (parse_addr_port(LOG_WARN, listenaddress, &address, &addr, &usePort)<0) {
615 log_warn(LD_CONFIG,
616 "Error parsing/resolving ListenAddress %s", listenaddress);
617 return NULL;
620 if (usePort==0)
621 usePort = listenport;
622 listenaddr.sin_addr.s_addr = htonl(addr);
623 listenaddr.sin_family = AF_INET;
624 listenaddr.sin_port = htons((uint16_t) usePort);
626 log_notice(LD_NET, "Opening %s on %s:%d",
627 conn_type_to_string(type), address, usePort);
629 s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
630 if (s < 0) {
631 log_warn(LD_NET,"Socket creation failed.");
632 goto err;
635 #ifndef MS_WINDOWS
636 /* REUSEADDR on normal places means you can rebind to the port
637 * right after somebody else has let it go. But REUSEADDR on win32
638 * means you can bind to the port _even when somebody else
639 * already has it bound_. So, don't do that on Win32. */
640 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*) &one, sizeof(one));
641 #endif
643 if (bind(s,(struct sockaddr *)&listenaddr,sizeof(listenaddr)) < 0) {
644 const char *helpfulhint = "";
645 int e = tor_socket_errno(s);
646 if (ERRNO_IS_EADDRINUSE(e))
647 helpfulhint = ". Is Tor already running?";
648 log_warn(LD_NET, "Could not bind to %s:%u: %s%s", address, usePort,
649 tor_socket_strerror(e), helpfulhint);
650 tor_close_socket(s);
651 goto err;
654 if (listen(s,SOMAXCONN) < 0) {
655 log_warn(LD_NET, "Could not listen on %s:%u: %s", address, usePort,
656 tor_socket_strerror(tor_socket_errno(s)));
657 tor_close_socket(s);
658 goto err;
661 set_socket_nonblocking(s);
663 conn = connection_new(type);
664 conn->s = s;
665 conn->address = address;
666 address = NULL;
667 conn->port = usePort;
669 if (connection_add(conn) < 0) { /* no space, forget it */
670 log_warn(LD_NET,"connection_add for listener failed. Giving up.");
671 connection_free(conn);
672 goto err;
675 log_debug(LD_NET,"%s listening on port %u.",
676 conn_type_to_string(type), usePort);
678 conn->state = LISTENER_STATE_READY;
679 connection_start_reading(conn);
681 return conn;
683 err:
684 tor_free(address);
685 return NULL;
688 /** Do basic sanity checking on a newly received socket. Return 0
689 * if it looks ok, else return -1. */
690 static int
691 check_sockaddr_in(struct sockaddr *sa, int len, int level)
693 int ok = 1;
694 struct sockaddr_in *sin=(struct sockaddr_in*)sa;
696 if (len != sizeof(struct sockaddr_in)) {
697 log_fn(level, LD_NET, "Length of address not as expected: %d vs %d",
698 len,(int)sizeof(struct sockaddr_in));
699 ok = 0;
701 if (sa->sa_family != AF_INET) {
702 log_fn(level, LD_NET, "Family of address not as expected: %d vs %d",
703 sa->sa_family, AF_INET);
704 ok = 0;
706 if (sin->sin_addr.s_addr == 0 || sin->sin_port == 0) {
707 log_fn(level, LD_NET,
708 "Address for new connection has address/port equal to zero.");
709 ok = 0;
711 return ok ? 0 : -1;
714 /** The listener connection <b>conn</b> told poll() it wanted to read.
715 * Call accept() on conn-\>s, and add the new connection if necessary.
717 static int
718 connection_handle_listener_read(connection_t *conn, int new_type)
720 int news; /* the new socket */
721 connection_t *newconn;
722 /* information about the remote peer when connecting to other routers */
723 struct sockaddr_in remote;
724 char addrbuf[256];
725 /* length of the remote address. Must be whatever accept() needs. */
726 socklen_t remotelen = 256;
727 char tmpbuf[INET_NTOA_BUF_LEN];
728 tor_assert((size_t)remotelen >= sizeof(struct sockaddr_in));
729 memset(addrbuf, 0, sizeof(addrbuf));
731 news = accept(conn->s,(struct sockaddr *)&addrbuf,&remotelen);
732 if (news < 0) { /* accept() error */
733 int e = tor_socket_errno(conn->s);
734 if (ERRNO_IS_ACCEPT_EAGAIN(e)) {
735 return 0; /* he hung up before we could accept(). that's fine. */
736 } else if (ERRNO_IS_ACCEPT_RESOURCE_LIMIT(e)) {
737 log_notice(LD_NET,"accept failed: %s. Dropping incoming connection.",
738 tor_socket_strerror(e));
739 return 0;
741 /* else there was a real error. */
742 log_warn(LD_NET,"accept() failed: %s. Closing listener.",
743 tor_socket_strerror(e));
744 connection_mark_for_close(conn);
745 return -1;
747 log_debug(LD_NET,
748 "Connection accepted on socket %d (child of fd %d).",
749 news,conn->s);
751 set_socket_nonblocking(news);
753 if (check_sockaddr_in((struct sockaddr*)addrbuf, remotelen, LOG_INFO)<0) {
754 log_info(LD_NET,
755 "accept() returned a strange address; trying getsockname().");
756 remotelen=256;
757 memset(addrbuf, 0, sizeof(addrbuf));
758 if (getsockname(news, (struct sockaddr*)addrbuf, &remotelen)<0) {
759 int e = tor_socket_errno(news);
760 log_warn(LD_NET, "getsockname() for new connection failed: %s",
761 tor_socket_strerror(e));
762 } else {
763 if (check_sockaddr_in((struct sockaddr*)addrbuf, remotelen,
764 LOG_WARN) < 0) {
765 log_warn(LD_NET,"Something's wrong with this conn. Closing it.");
766 tor_close_socket(news);
767 return 0;
771 memcpy(&remote, addrbuf, sizeof(struct sockaddr_in));
773 /* process entrance policies here, before we even create the connection */
774 if (new_type == CONN_TYPE_AP) {
775 /* check sockspolicy to see if we should accept it */
776 if (socks_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
777 tor_inet_ntoa(&remote.sin_addr, tmpbuf, sizeof(tmpbuf));
778 log_notice(LD_APP,"Denying socks connection from untrusted address %s.",
779 tmpbuf);
780 tor_close_socket(news);
781 return 0;
784 if (new_type == CONN_TYPE_DIR) {
785 /* check dirpolicy to see if we should accept it */
786 if (dir_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
787 tor_inet_ntoa(&remote.sin_addr, tmpbuf, sizeof(tmpbuf));
788 log_notice(LD_DIRSERV,"Denying dir connection from address %s.",
789 tmpbuf);
790 tor_close_socket(news);
791 return 0;
795 newconn = connection_new(new_type);
796 newconn->s = news;
798 /* remember the remote address */
799 newconn->addr = ntohl(remote.sin_addr.s_addr);
800 newconn->port = ntohs(remote.sin_port);
801 newconn->address = tor_dup_addr(newconn->addr);
803 if (connection_add(newconn) < 0) { /* no space, forget it */
804 connection_free(newconn);
805 return 0; /* no need to tear down the parent */
808 if (connection_init_accepted_conn(newconn, conn->type) < 0) {
809 connection_mark_for_close(newconn);
810 return 0;
812 return 0;
815 /** Initialize states for newly accepted connection <b>conn</b>.
816 * If conn is an OR, start the tls handshake.
817 * If conn is a transparent AP, get its original destination
818 * and place it in circuit_wait.
820 static int
821 connection_init_accepted_conn(connection_t *conn, uint8_t listener_type)
823 connection_start_reading(conn);
825 switch (conn->type) {
826 case CONN_TYPE_OR:
827 control_event_or_conn_status(TO_OR_CONN(conn), OR_CONN_EVENT_NEW);
828 return connection_tls_start_handshake(TO_OR_CONN(conn), 1);
829 case CONN_TYPE_AP:
830 switch (listener_type) {
831 case CONN_TYPE_AP_LISTENER:
832 conn->state = AP_CONN_STATE_SOCKS_WAIT;
833 break;
834 case CONN_TYPE_AP_TRANS_LISTENER:
835 conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
836 return connection_ap_process_transparent(TO_EDGE_CONN(conn));
837 case CONN_TYPE_AP_NATD_LISTENER:
838 conn->state = AP_CONN_STATE_NATD_WAIT;
839 break;
841 break;
842 case CONN_TYPE_DIR:
843 conn->purpose = DIR_PURPOSE_SERVER;
844 conn->state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
845 break;
846 case CONN_TYPE_CONTROL:
847 conn->state = CONTROL_CONN_STATE_NEEDAUTH_V0;
848 break;
850 return 0;
853 /** Take conn, make a nonblocking socket; try to connect to
854 * addr:port (they arrive in *host order*). If fail, return -1. Else
855 * assign s to conn-\>s: if connected return 1, if EAGAIN return 0.
857 * address is used to make the logs useful.
859 * On success, add conn to the list of polled connections.
862 connection_connect(connection_t *conn, char *address,
863 uint32_t addr, uint16_t port)
865 int s, inprogress = 0;
866 struct sockaddr_in dest_addr;
867 or_options_t *options = get_options();
869 s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
870 if (s < 0) {
871 log_warn(LD_NET,"Error creating network socket: %s",
872 tor_socket_strerror(tor_socket_errno(-1)));
873 return -1;
876 if (options->OutboundBindAddress) {
877 struct sockaddr_in ext_addr;
879 memset(&ext_addr, 0, sizeof(ext_addr));
880 ext_addr.sin_family = AF_INET;
881 ext_addr.sin_port = 0;
882 if (!tor_inet_aton(options->OutboundBindAddress, &ext_addr.sin_addr)) {
883 log_warn(LD_CONFIG,"Outbound bind address '%s' didn't parse. Ignoring.",
884 options->OutboundBindAddress);
885 } else {
886 if (bind(s, (struct sockaddr*)&ext_addr, sizeof(ext_addr)) < 0) {
887 log_warn(LD_NET,"Error binding network socket: %s",
888 tor_socket_strerror(tor_socket_errno(s)));
889 tor_close_socket(s);
890 return -1;
895 set_socket_nonblocking(s);
897 memset(&dest_addr,0,sizeof(dest_addr));
898 dest_addr.sin_family = AF_INET;
899 dest_addr.sin_port = htons(port);
900 dest_addr.sin_addr.s_addr = htonl(addr);
902 log_debug(LD_NET,"Connecting to %s:%u.",escaped_safe_str(address),port);
904 if (connect(s,(struct sockaddr *)&dest_addr,sizeof(dest_addr)) < 0) {
905 int e = tor_socket_errno(s);
906 if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
907 /* yuck. kill it. */
908 log_info(LD_NET,
909 "connect() to %s:%u failed: %s",escaped_safe_str(address),
910 port, tor_socket_strerror(e));
911 tor_close_socket(s);
912 return -1;
913 } else {
914 inprogress = 1;
918 if (!server_mode(options))
919 client_check_address_changed(s);
921 /* it succeeded. we're connected. */
922 log_fn(inprogress?LOG_DEBUG:LOG_INFO, LD_NET,
923 "Connection to %s:%u %s (sock %d).",escaped_safe_str(address),
924 port, inprogress?"in progress":"established", s);
925 conn->s = s;
926 if (connection_add(conn) < 0) /* no space, forget it */
927 return -1;
928 return inprogress ? 0 : 1;
932 * Launch any configured listener connections of type <b>type</b>. (A
933 * listener is configured if <b>port_option</b> is non-zero. If any
934 * ListenAddress configuration options are given in <b>cfg</b>, create a
935 * connection binding to each one. Otherwise, create a single
936 * connection binding to the address <b>default_addr</b>.)
938 * If <b>force</b> is true, close and re-open all listener connections.
939 * Otherwise, only relaunch the listeners of this type if the number of
940 * existing connections is not as configured (e.g., because one died),
941 * or if the existing connections do not match those configured.
943 * Add all old conns that should be closed to <b>replaced_conns</b>.
944 * Add all new connections to <b>new_conns</b>.
946 static int
947 retry_listeners(int type, config_line_t *cfg,
948 int port_option, const char *default_addr, int force,
949 smartlist_t *replaced_conns,
950 smartlist_t *new_conns,
951 int never_open_conns)
953 smartlist_t *launch = smartlist_create();
954 int free_launch_elts = 1;
955 config_line_t *c;
956 int n_conn, i;
957 connection_t *conn;
958 connection_t **carray;
959 config_line_t *line;
961 if (cfg && port_option) {
962 for (c = cfg; c; c = c->next) {
963 smartlist_add(launch, c);
965 free_launch_elts = 0;
966 } else if (port_option) {
967 line = tor_malloc_zero(sizeof(config_line_t));
968 line->key = tor_strdup("");
969 line->value = tor_strdup(default_addr);
970 smartlist_add(launch, line);
974 SMARTLIST_FOREACH(launch, config_line_t *, l,
975 log_fn(LOG_NOTICE, "#%s#%s", l->key, l->value));
978 get_connection_array(&carray,&n_conn);
979 for (i=0; i < n_conn; ++i) {
980 conn = carray[i];
981 if (conn->type != type || conn->marked_for_close)
982 continue;
983 if (force) {
984 /* It's a listener, and we're relaunching all listeners of this
985 * type. Close this one. */
986 log_notice(LD_NET, "Force-closing listener %s on %s:%d",
987 conn_type_to_string(type), conn->address, conn->port);
988 connection_close_immediate(conn);
989 connection_mark_for_close(conn);
990 continue;
992 /* Okay, so this is a listener. Is it configured? */
993 line = NULL;
994 SMARTLIST_FOREACH(launch, config_line_t *, wanted,
996 char *address=NULL;
997 uint16_t port;
998 if (!parse_addr_port(LOG_WARN, wanted->value, &address, NULL, &port)) {
999 int addr_matches = !strcasecmp(address, conn->address);
1000 tor_free(address);
1001 if (! port)
1002 port = port_option;
1003 if (port == conn->port && addr_matches) {
1004 line = wanted;
1005 break;
1009 if (! line) {
1010 /* This one isn't configured. Close it. */
1011 log_notice(LD_NET, "Closing no-longer-configured %s on %s:%d",
1012 conn_type_to_string(type), conn->address, conn->port);
1013 if (replaced_conns) {
1014 smartlist_add(replaced_conns, conn);
1015 } else {
1016 connection_close_immediate(conn);
1017 connection_mark_for_close(conn);
1019 } else {
1020 /* It's configured; we don't need to launch it. */
1021 // log_debug(LD_NET, "Already have %s on %s:%d",
1022 // conn_type_to_string(type), conn->address, conn->port);
1023 smartlist_remove(launch, line);
1024 if (free_launch_elts)
1025 config_free_lines(line);
1029 /* Now open all the listeners that are configured but not opened. */
1030 i = 0;
1031 if (!never_open_conns) {
1032 SMARTLIST_FOREACH(launch, config_line_t *, cfg,
1034 conn = connection_create_listener(cfg->value, (uint16_t) port_option,
1035 type);
1036 if (!conn) {
1037 i = -1;
1038 } else {
1039 if (new_conns)
1040 smartlist_add(new_conns, conn);
1045 if (free_launch_elts) {
1046 SMARTLIST_FOREACH(launch, config_line_t *, cfg,
1047 config_free_lines(cfg));
1049 smartlist_free(launch);
1051 return i;
1054 /** (Re)launch listeners for each port you should have open. If
1055 * <b>force</b> is true, close and relaunch all listeners. If <b>force</b>
1056 * is false, then only relaunch listeners when we have the wrong number of
1057 * connections for a given type.
1059 * Add all old conns that should be closed to <b>replaced_conns</b>.
1060 * Add all new connections to <b>new_conns</b>.
1063 retry_all_listeners(int force, smartlist_t *replaced_conns,
1064 smartlist_t *new_conns)
1066 or_options_t *options = get_options();
1068 if (retry_listeners(CONN_TYPE_OR_LISTENER, options->ORListenAddress,
1069 options->ORPort, "0.0.0.0", force,
1070 replaced_conns, new_conns, options->ClientOnly)<0)
1071 return -1;
1072 if (retry_listeners(CONN_TYPE_DIR_LISTENER, options->DirListenAddress,
1073 options->DirPort, "0.0.0.0", force,
1074 replaced_conns, new_conns, 0)<0)
1075 return -1;
1076 if (retry_listeners(CONN_TYPE_AP_LISTENER, options->SocksListenAddress,
1077 options->SocksPort, "127.0.0.1", force,
1078 replaced_conns, new_conns, 0)<0)
1079 return -1;
1080 if (retry_listeners(CONN_TYPE_AP_TRANS_LISTENER, options->TransListenAddress,
1081 options->TransPort, "127.0.0.1", force,
1082 replaced_conns, new_conns, 0)<0)
1083 return -1;
1084 if (retry_listeners(CONN_TYPE_AP_NATD_LISTENER, options->NatdListenAddress,
1085 options->NatdPort, "127.0.0.1", force,
1086 replaced_conns, new_conns, 0)<0)
1087 return -1;
1088 if (retry_listeners(CONN_TYPE_CONTROL_LISTENER,
1089 options->ControlListenAddress,
1090 options->ControlPort, "127.0.0.1", force,
1091 replaced_conns, new_conns, 0)<0)
1092 return -1;
1094 return 0;
1097 extern int global_read_bucket, global_write_bucket;
1099 static int
1100 connection_bucket_round_robin(int base, int priority,
1101 int global_bucket, int conn_bucket)
1103 int at_most;
1104 int num_bytes_high = (priority ? 32 : 16) * base;
1105 int num_bytes_low = (priority ? 4 : 2) * base;
1107 /* Do a rudimentary round-robin so one circuit can't hog a connection.
1108 * Pick at most 32 cells, at least 4 cells if possible, and if we're in
1109 * the middle pick 1/8 of the available bandwidth. */
1110 at_most = global_bucket / 8;
1111 at_most -= (at_most % base); /* round down */
1112 if (at_most > num_bytes_high) /* 16 KB, or 8 KB for low-priority */
1113 at_most = num_bytes_high;
1114 else if (at_most < num_bytes_low) /* 2 KB, or 1 KB for low-priority */
1115 at_most = num_bytes_low;
1117 if (at_most > global_bucket)
1118 at_most = global_bucket;
1120 if (conn_bucket >= 0 && at_most > conn_bucket)
1121 at_most = conn_bucket;
1123 if (at_most < 0)
1124 return 0;
1125 return at_most;
1128 /** How many bytes at most can we read onto this connection? */
1129 static int
1130 connection_bucket_read_limit(connection_t *conn)
1132 int base = connection_speaks_cells(conn) ?
1133 CELL_NETWORK_SIZE : RELAY_PAYLOAD_SIZE;
1134 int priority = conn->type != CONN_TYPE_DIR;
1135 int conn_bucket = -1;
1136 if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
1137 or_connection_t *or_conn = TO_OR_CONN(conn);
1138 conn_bucket = or_conn->read_bucket;
1140 return connection_bucket_round_robin(base, priority,
1141 global_read_bucket, conn_bucket);
1144 /** How many bytes at most can we write onto this connection? */
1146 connection_bucket_write_limit(connection_t *conn)
1148 int base = connection_speaks_cells(conn) ?
1149 CELL_NETWORK_SIZE : RELAY_PAYLOAD_SIZE;
1150 int priority = conn->type != CONN_TYPE_DIR;
1152 return connection_bucket_round_robin(base, priority, global_write_bucket,
1153 conn->outbuf_flushlen);
1156 /** Return 1 if the global write bucket is low enough that we shouldn't
1157 * send <b>attempt</b> bytes of low-priority directory stuff out.
1158 * Else return 0.
1160 * Priority is 1 for v1 requests (directories and running-routers),
1161 * and 2 for v2 requests (statuses and descriptors). But see FFFF in
1162 * directory_handle_command_get() for why we don't use priority 2 yet.
1164 * There are a lot of parameters we could use here:
1165 * - global_write_bucket. Low is bad.
1166 * - bandwidthrate. Low is bad.
1167 * - bandwidthburst. Not a big factor?
1168 * - attempt. High is bad.
1169 * - total bytes queued on outbufs. High is bad. But I'm wary of
1170 * using this, since a few slow-flushing queues will pump up the
1171 * number without meaning what we meant to mean. What we really
1172 * mean is "total directory bytes added to outbufs recently", but
1173 * that's harder to quantify and harder to keep track of.
1176 global_write_bucket_low(size_t attempt, int priority)
1178 if (authdir_mode(get_options()) && priority>1)
1179 return 0; /* there's always room to answer v2 if we're an auth dir */
1181 if (global_write_bucket < (int)attempt)
1182 return 1; /* not enough space no matter the priority */
1184 if (priority == 1) { /* old-style v1 query */
1185 /* Could we handle *two* of these requests within the next two seconds? */
1186 int64_t can_write = (int64_t)global_write_bucket
1187 + 2*get_options()->BandwidthRate;
1188 if (can_write < 2*(int64_t)attempt)
1189 return 1;
1190 } else { /* v2 query */
1191 /* no further constraints yet */
1193 return 0;
1196 /** We just read num_read onto conn. Decrement buckets appropriately. */
1197 static void
1198 connection_read_bucket_decrement(connection_t *conn, int num_read)
1200 global_read_bucket -= num_read;
1201 if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
1202 TO_OR_CONN(conn)->read_bucket -= num_read;
1206 /** If we have exhausted our global buckets, or the buckets for conn,
1207 * stop reading. */
1208 static void
1209 connection_consider_empty_read_buckets(connection_t *conn)
1211 if (global_read_bucket <= 0) {
1212 LOG_FN_CONN(conn, (LOG_DEBUG,LD_NET,
1213 "global read bucket exhausted. Pausing."));
1214 conn->wants_to_read = 1;
1215 connection_stop_reading(conn);
1216 return;
1218 if (connection_speaks_cells(conn) &&
1219 conn->state == OR_CONN_STATE_OPEN &&
1220 TO_OR_CONN(conn)->read_bucket <= 0) {
1221 LOG_FN_CONN(conn,
1222 (LOG_DEBUG,LD_NET,"read bucket exhausted. Pausing."));
1223 conn->wants_to_read = 1;
1224 connection_stop_reading(conn);
1228 /** If we have exhausted our global buckets, or the buckets for conn,
1229 * stop writing. */
1230 static void
1231 connection_consider_empty_write_buckets(connection_t *conn)
1233 if (global_write_bucket <= 0) {
1234 LOG_FN_CONN(conn, (LOG_DEBUG,LD_NET,
1235 "global write bucket exhausted. Pausing."));
1236 conn->wants_to_write = 1;
1237 connection_stop_writing(conn);
1238 return;
1240 #if 0
1241 if (connection_speaks_cells(conn) &&
1242 conn->state == OR_CONN_STATE_OPEN &&
1243 TO_OR_CONN(conn)->write_bucket <= 0) {
1244 LOG_FN_CONN(conn,
1245 (LOG_DEBUG,LD_NET,"write bucket exhausted. Pausing."));
1246 conn->wants_to_write = 1;
1247 connection_stop_writing(conn);
1249 #endif
1252 /** Initialize the global read bucket to options->BandwidthBurst. */
1253 void
1254 connection_bucket_init(void)
1256 or_options_t *options = get_options();
1257 /* start it at max traffic */
1258 global_read_bucket = (int)options->BandwidthBurst;
1259 global_write_bucket = (int)options->BandwidthBurst;
1262 /** A second has rolled over; increment buckets appropriately. */
1263 void
1264 connection_bucket_refill(int seconds_elapsed)
1266 int i, n;
1267 connection_t *conn;
1268 connection_t **carray;
1269 or_options_t *options = get_options();
1271 /* refill the global buckets */
1272 if (global_read_bucket < (int)options->BandwidthBurst) {
1273 global_read_bucket += (int)options->BandwidthRate*seconds_elapsed;
1274 if (global_read_bucket > (int)options->BandwidthBurst)
1275 global_read_bucket = (int)options->BandwidthBurst;
1276 log(LOG_DEBUG, LD_NET,"global_read_bucket now %d.", global_read_bucket);
1278 if (global_write_bucket < (int)options->BandwidthBurst) {
1279 global_write_bucket += (int)options->BandwidthRate*seconds_elapsed;
1280 if (global_write_bucket > (int)options->BandwidthBurst)
1281 global_write_bucket = (int)options->BandwidthBurst;
1282 log(LOG_DEBUG, LD_NET,"global_write_bucket now %d.", global_write_bucket);
1285 /* refill the per-connection buckets */
1286 get_connection_array(&carray,&n);
1287 for (i=0;i<n;i++) {
1288 conn = carray[i];
1290 if (connection_speaks_cells(conn)) {
1291 or_connection_t *or_conn = TO_OR_CONN(conn);
1292 if (connection_read_bucket_should_increase(or_conn)) {
1293 or_conn->read_bucket += or_conn->bandwidthrate*seconds_elapsed;
1294 if (or_conn->read_bucket > or_conn->bandwidthburst)
1295 or_conn->read_bucket = or_conn->bandwidthburst;
1296 //log_fn(LOG_DEBUG,"Receiver bucket %d now %d.", i,
1297 // conn->read_bucket);
1301 if (conn->wants_to_read == 1 /* it's marked to turn reading back on now */
1302 && global_read_bucket > 0 /* and we're allowed to read */
1303 && (!connection_speaks_cells(conn) ||
1304 conn->state != OR_CONN_STATE_OPEN ||
1305 TO_OR_CONN(conn)->read_bucket > 0)) {
1306 /* and either a non-cell conn or a cell conn with non-empty bucket */
1307 LOG_FN_CONN(conn, (LOG_DEBUG,LD_NET,
1308 "waking up conn (fd %d) for read",conn->s));
1309 conn->wants_to_read = 0;
1310 connection_start_reading(conn);
1312 if (conn->wants_to_write == 1 &&
1313 global_write_bucket > 0) { /* and we're allowed to write */
1314 LOG_FN_CONN(conn, (LOG_DEBUG,LD_NET,
1315 "waking up conn (fd %d) for write",conn->s));
1316 conn->wants_to_write = 0;
1317 connection_start_writing(conn);
1322 /** Is the receiver bucket for connection <b>conn</b> low enough that we
1323 * should add another pile of tokens to it?
1325 static int
1326 connection_read_bucket_should_increase(or_connection_t *conn)
1328 tor_assert(conn);
1330 if (conn->_base.state != OR_CONN_STATE_OPEN)
1331 return 0; /* only open connections play the rate limiting game */
1332 if (conn->read_bucket >= conn->bandwidthburst)
1333 return 0;
1335 return 1;
1338 /** Read bytes from conn-\>s and process them.
1340 * This function gets called from conn_read() in main.c, either
1341 * when poll() has declared that conn wants to read, or (for OR conns)
1342 * when there are pending TLS bytes.
1344 * It calls connection_read_to_buf() to bring in any new bytes,
1345 * and then calls connection_process_inbuf() to process them.
1347 * Mark the connection and return -1 if you want to close it, else
1348 * return 0.
1351 connection_handle_read(connection_t *conn)
1353 int max_to_read=-1, try_to_read;
1355 if (conn->marked_for_close)
1356 return 0; /* do nothing */
1358 conn->timestamp_lastread = time(NULL);
1360 switch (conn->type) {
1361 case CONN_TYPE_OR_LISTENER:
1362 return connection_handle_listener_read(conn, CONN_TYPE_OR);
1363 case CONN_TYPE_AP_LISTENER:
1364 case CONN_TYPE_AP_TRANS_LISTENER:
1365 case CONN_TYPE_AP_NATD_LISTENER:
1366 return connection_handle_listener_read(conn, CONN_TYPE_AP);
1367 case CONN_TYPE_DIR_LISTENER:
1368 return connection_handle_listener_read(conn, CONN_TYPE_DIR);
1369 case CONN_TYPE_CONTROL_LISTENER:
1370 return connection_handle_listener_read(conn, CONN_TYPE_CONTROL);
1373 loop_again:
1374 try_to_read = max_to_read;
1375 tor_assert(!conn->marked_for_close);
1376 if (connection_read_to_buf(conn, &max_to_read) < 0) {
1377 /* There's a read error; kill the connection.*/
1378 connection_close_immediate(conn); /* Don't flush; connection is dead. */
1379 if (CONN_IS_EDGE(conn)) {
1380 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
1381 connection_edge_end_errno(edge_conn, edge_conn->cpath_layer);
1382 if (edge_conn->socks_request) /* broken, don't send a socks reply back */
1383 edge_conn->socks_request->has_finished = 1;
1385 connection_mark_for_close(conn);
1386 return -1;
1388 if (CONN_IS_EDGE(conn) && try_to_read != max_to_read) {
1389 /* instruct it not to try to package partial cells. */
1390 if (connection_process_inbuf(conn, 0) < 0) {
1391 return -1;
1393 if (!conn->marked_for_close &&
1394 connection_is_reading(conn) &&
1395 !conn->inbuf_reached_eof &&
1396 max_to_read > 0)
1397 goto loop_again; /* try reading again, in case more is here now */
1399 /* one last try, packaging partial cells and all. */
1400 if (!conn->marked_for_close &&
1401 connection_process_inbuf(conn, 1) < 0) {
1402 return -1;
1404 if (!conn->marked_for_close &&
1405 conn->inbuf_reached_eof &&
1406 connection_reached_eof(conn) < 0) {
1407 return -1;
1409 return 0;
1412 /** Pull in new bytes from conn-\>s onto conn-\>inbuf, either
1413 * directly or via TLS. Reduce the token buckets by the number of
1414 * bytes read.
1416 * If *max_to_read is -1, then decide it ourselves, else go with the
1417 * value passed to us. When returning, if it's changed, subtract the
1418 * number of bytes we read from *max_to_read.
1420 * Return -1 if we want to break conn, else return 0.
1422 static int
1423 connection_read_to_buf(connection_t *conn, int *max_to_read)
1425 int result, at_most = *max_to_read;
1426 size_t bytes_in_buf, more_to_read;
1427 size_t n_read = 0, n_written = 0;
1429 if (at_most == -1) { /* we need to initialize it */
1430 /* how many bytes are we allowed to read? */
1431 at_most = connection_bucket_read_limit(conn);
1434 bytes_in_buf = buf_capacity(conn->inbuf) - buf_datalen(conn->inbuf);
1435 again:
1436 if ((size_t)at_most > bytes_in_buf && bytes_in_buf >= 1024) {
1437 more_to_read = at_most - bytes_in_buf;
1438 at_most = bytes_in_buf;
1439 } else {
1440 more_to_read = 0;
1443 if (connection_speaks_cells(conn) &&
1444 conn->state > OR_CONN_STATE_PROXY_READING) {
1445 int pending;
1446 or_connection_t *or_conn = TO_OR_CONN(conn);
1447 if (conn->state == OR_CONN_STATE_HANDSHAKING) {
1448 /* continue handshaking even if global token bucket is empty */
1449 return connection_tls_continue_handshake(or_conn);
1452 log_debug(LD_NET,
1453 "%d: starting, inbuf_datalen %d (%d pending in tls object)."
1454 " at_most %d.",
1455 conn->s,(int)buf_datalen(conn->inbuf),
1456 tor_tls_get_pending_bytes(or_conn->tls), at_most);
1458 /* else open, or closing */
1459 result = read_to_buf_tls(or_conn->tls, at_most, conn->inbuf);
1461 switch (result) {
1462 case TOR_TLS_CLOSE:
1463 log_info(LD_NET,"TLS connection closed on read. Closing. "
1464 "(Nickname %s, address %s",
1465 or_conn->nickname ? or_conn->nickname : "not set",
1466 conn->address);
1467 return -1;
1468 case TOR_TLS_ERROR:
1469 log_info(LD_NET,"tls error. breaking (nickname %s, address %s).",
1470 or_conn->nickname ? or_conn->nickname : "not set",
1471 conn->address);
1472 return -1;
1473 case TOR_TLS_WANTWRITE:
1474 connection_start_writing(conn);
1475 return 0;
1476 case TOR_TLS_WANTREAD: /* we're already reading */
1477 case TOR_TLS_DONE: /* no data read, so nothing to process */
1478 result = 0;
1479 break; /* so we call bucket_decrement below */
1480 default:
1481 break;
1483 pending = tor_tls_get_pending_bytes(or_conn->tls);
1484 if (pending) {
1485 /* If we have any pending bytes, we read them now. This *can*
1486 * take us over our read allotment, but really we shouldn't be
1487 * believing that SSL bytes are the same as TCP bytes anyway. */
1488 int r2 = read_to_buf_tls(or_conn->tls, pending, conn->inbuf);
1489 if (r2<0) {
1490 log_warn(LD_BUG, "Bug: apparently, reading pending bytes can fail.");
1491 return -1;
1492 } else {
1493 result += r2;
1497 tor_tls_get_n_raw_bytes(or_conn->tls, &n_read, &n_written);
1498 log_debug(LD_GENERAL, "After TLS read of %d: %ld read, %ld written",
1499 result, (long)n_read, (long)n_written);
1500 } else {
1501 int reached_eof = 0;
1502 CONN_LOG_PROTECT(conn,
1503 result = read_to_buf(conn->s, at_most, conn->inbuf, &reached_eof));
1504 if (reached_eof)
1505 conn->inbuf_reached_eof = 1;
1507 // log_fn(LOG_DEBUG,"read_to_buf returned %d.",read_result);
1509 if (result < 0)
1510 return -1;
1511 n_read = (size_t) result;
1514 if (n_read > 0) { /* change *max_to_read */
1515 *max_to_read = at_most - n_read;
1518 if (!is_internal_IP(conn->addr, 0)) {
1519 /* For non-local IPs, remember if we flushed any bytes over the wire. */
1520 time_t now = time(NULL);
1521 if (n_read > 0) {
1522 rep_hist_note_bytes_read(n_read, now);
1523 connection_read_bucket_decrement(conn, n_read);
1525 if (n_written > 0) {
1526 rep_hist_note_bytes_written(n_written, now);
1527 global_write_bucket -= n_written;
1531 if (more_to_read && result == at_most) {
1532 bytes_in_buf = buf_capacity(conn->inbuf) - buf_datalen(conn->inbuf);
1533 tor_assert(bytes_in_buf < 1024);
1534 at_most = more_to_read;
1535 goto again;
1538 /* Call even if result is 0, since the global read bucket may
1539 * have reached 0 on a different conn, and this guy needs to
1540 * know to stop reading. */
1541 connection_consider_empty_read_buckets(conn);
1542 if (n_written > 0 && connection_is_writing(conn))
1543 connection_consider_empty_write_buckets(conn);
1545 return 0;
1548 /** A pass-through to fetch_from_buf. */
1550 connection_fetch_from_buf(char *string, size_t len, connection_t *conn)
1552 return fetch_from_buf(string, len, conn->inbuf);
1555 /** Return conn-\>outbuf_flushlen: how many bytes conn wants to flush
1556 * from its outbuf. */
1558 connection_wants_to_flush(connection_t *conn)
1560 return conn->outbuf_flushlen;
1563 /** Are there too many bytes on edge connection <b>conn</b>'s outbuf to
1564 * send back a relay-level sendme yet? Return 1 if so, 0 if not. Used by
1565 * connection_edge_consider_sending_sendme().
1568 connection_outbuf_too_full(connection_t *conn)
1570 return (conn->outbuf_flushlen > 10*CELL_PAYLOAD_SIZE);
1573 /** Try to flush more bytes onto conn-\>s.
1575 * This function gets called either from conn_write() in main.c
1576 * when poll() has declared that conn wants to write, or below
1577 * from connection_write_to_buf() when an entire TLS record is ready.
1579 * Update conn-\>timestamp_lastwritten to now, and call flush_buf
1580 * or flush_buf_tls appropriately. If it succeeds and there no more
1581 * more bytes on conn->outbuf, then call connection_finished_flushing
1582 * on it too.
1584 * If <b>force</b>, then write as many bytes as possible, ignoring bandwidth
1585 * limits. (Used for flushing messages to controller connections on fatal
1586 * errors.)
1588 * Mark the connection and return -1 if you want to close it, else
1589 * return 0.
1592 connection_handle_write(connection_t *conn, int force)
1594 int e;
1595 socklen_t len=sizeof(e);
1596 int result;
1597 int max_to_write;
1598 time_t now = time(NULL);
1599 size_t n_read = 0, n_written = 0;
1601 tor_assert(!connection_is_listener(conn));
1603 if (conn->marked_for_close || conn->s < 0)
1604 return 0; /* do nothing */
1606 conn->timestamp_lastwritten = now;
1608 /* Sometimes, "writable" means "connected". */
1609 if (connection_state_is_connecting(conn)) {
1610 if (getsockopt(conn->s, SOL_SOCKET, SO_ERROR, (void*)&e, &len) < 0) {
1611 log_warn(LD_BUG,
1612 "getsockopt() syscall failed?! Please report to tor-ops.");
1613 if (CONN_IS_EDGE(conn))
1614 connection_edge_end_errno(TO_EDGE_CONN(conn),
1615 TO_EDGE_CONN(conn)->cpath_layer);
1616 connection_mark_for_close(conn);
1617 return -1;
1619 if (e) {
1620 /* some sort of error, but maybe just inprogress still */
1621 if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
1622 log_info(LD_NET,"in-progress connect failed. Removing.");
1623 if (CONN_IS_EDGE(conn))
1624 connection_edge_end_errno(TO_EDGE_CONN(conn),
1625 TO_EDGE_CONN(conn)->cpath_layer);
1627 connection_close_immediate(conn);
1628 connection_mark_for_close(conn);
1629 /* it's safe to pass OPs to router_set_status(), since it just
1630 * ignores unrecognized routers
1632 if (conn->type == CONN_TYPE_OR && !get_options()->HttpsProxy)
1633 router_set_status(TO_OR_CONN(conn)->identity_digest, 0);
1634 return -1;
1635 } else {
1636 return 0; /* no change, see if next time is better */
1639 /* The connection is successful. */
1640 if (connection_finished_connecting(conn)<0)
1641 return -1;
1644 max_to_write = force ? (int)conn->outbuf_flushlen
1645 : connection_bucket_write_limit(conn);
1647 if (connection_speaks_cells(conn) &&
1648 conn->state > OR_CONN_STATE_PROXY_READING) {
1649 or_connection_t *or_conn = TO_OR_CONN(conn);
1650 if (conn->state == OR_CONN_STATE_HANDSHAKING) {
1651 connection_stop_writing(conn);
1652 if (connection_tls_continue_handshake(or_conn) < 0) {
1653 /* Don't flush; connection is dead. */
1654 connection_close_immediate(conn);
1655 connection_mark_for_close(conn);
1656 return -1;
1658 return 0;
1661 /* else open, or closing */
1662 result = flush_buf_tls(or_conn->tls, conn->outbuf,
1663 max_to_write, &conn->outbuf_flushlen);
1664 switch (result) {
1665 case TOR_TLS_ERROR:
1666 case TOR_TLS_CLOSE:
1667 log_info(LD_NET,result==TOR_TLS_ERROR?
1668 "tls error. breaking.":"TLS connection closed on flush");
1669 /* Don't flush; connection is dead. */
1670 connection_close_immediate(conn);
1671 connection_mark_for_close(conn);
1672 return -1;
1673 case TOR_TLS_WANTWRITE:
1674 log_debug(LD_NET,"wanted write.");
1675 /* we're already writing */
1676 return 0;
1677 case TOR_TLS_WANTREAD:
1678 /* Make sure to avoid a loop if the receive buckets are empty. */
1679 log_debug(LD_NET,"wanted read.");
1680 if (!connection_is_reading(conn)) {
1681 connection_stop_writing(conn);
1682 conn->wants_to_write = 1;
1683 /* we'll start reading again when the next second arrives,
1684 * and then also start writing again.
1687 /* else no problem, we're already reading */
1688 return 0;
1689 /* case TOR_TLS_DONE:
1690 * for TOR_TLS_DONE, fall through to check if the flushlen
1691 * is empty, so we can stop writing.
1695 tor_tls_get_n_raw_bytes(or_conn->tls, &n_read, &n_written);
1696 log_debug(LD_GENERAL, "After TLS write of %d: %ld read, %ld written",
1697 result, (long)n_read, (long)n_written);
1698 } else {
1699 CONN_LOG_PROTECT(conn,
1700 result = flush_buf(conn->s, conn->outbuf,
1701 max_to_write, &conn->outbuf_flushlen));
1702 if (result < 0) {
1703 if (CONN_IS_EDGE(conn))
1704 connection_edge_end_errno(TO_EDGE_CONN(conn),
1705 TO_EDGE_CONN(conn)->cpath_layer);
1707 connection_close_immediate(conn); /* Don't flush; connection is dead. */
1708 connection_mark_for_close(conn);
1709 return -1;
1711 n_written = (size_t) result;
1714 if (!is_internal_IP(conn->addr, 0)) {
1715 /* For non-local IPs, remember if we flushed any bytes over the wire. */
1716 time_t now = time(NULL);
1717 if (n_written > 0) {
1718 rep_hist_note_bytes_written(n_written, now);
1719 global_write_bucket -= n_written;
1721 if (n_read > 0) {
1722 rep_hist_note_bytes_read(n_read, now);
1723 connection_read_bucket_decrement(conn, n_read);
1727 if (result > 0) {
1728 /* If we wrote any bytes from our buffer, then call the appropriate
1729 * functions. */
1730 if (connection_flushed_some(conn) < 0)
1731 connection_mark_for_close(conn);
1734 if (!connection_wants_to_flush(conn)) { /* it's done flushing */
1735 if (connection_finished_flushing(conn) < 0) {
1736 /* already marked */
1737 return -1;
1739 return 0;
1742 /* Call even if result is 0, since the global write bucket may
1743 * have reached 0 on a different conn, and this guy needs to
1744 * know to stop writing. */
1745 connection_consider_empty_write_buckets(conn);
1746 if (n_read > 0 && connection_is_reading(conn))
1747 connection_consider_empty_read_buckets(conn);
1749 return 0;
1752 /** Append <b>len</b> bytes of <b>string</b> onto <b>conn</b>'s
1753 * outbuf, and ask it to start writing.
1755 * If <b>zlib</b> is nonzero, this is a directory connection that should get
1756 * its contents compressed or decompressed as they're written. If zlib is
1757 * negative, this is the last data to be compressed, and the connection's zlib
1758 * state should be flushed.
1760 void
1761 _connection_write_to_buf_impl(const char *string, size_t len,
1762 connection_t *conn, int zlib)
1764 int r;
1765 size_t old_datalen;
1766 if (!len)
1767 return;
1768 /* if it's marked for close, only allow write if we mean to flush it */
1769 if (conn->marked_for_close && !conn->hold_open_until_flushed)
1770 return;
1772 old_datalen = buf_datalen(conn->outbuf);
1773 if (zlib) {
1774 dir_connection_t *dir_conn = TO_DIR_CONN(conn);
1775 int done = zlib < 0;
1776 if (!dir_conn) return;
1777 CONN_LOG_PROTECT(conn, r = write_to_buf_zlib(conn->outbuf,
1778 dir_conn->zlib_state,
1779 string, len, done));
1780 } else {
1781 CONN_LOG_PROTECT(conn, r = write_to_buf(string, len, conn->outbuf));
1783 if (r < 0) {
1784 if (CONN_IS_EDGE(conn)) {
1785 /* if it failed, it means we have our package/delivery windows set
1786 wrong compared to our max outbuf size. close the whole circuit. */
1787 log_warn(LD_NET,
1788 "write_to_buf failed. Closing circuit (fd %d).", conn->s);
1789 circuit_mark_for_close(circuit_get_by_edge_conn(TO_EDGE_CONN(conn)),
1790 END_CIRC_REASON_INTERNAL);
1791 } else {
1792 log_warn(LD_NET,
1793 "write_to_buf failed. Closing connection (fd %d).", conn->s);
1794 connection_mark_for_close(conn);
1796 return;
1799 connection_start_writing(conn);
1800 if (zlib)
1801 conn->outbuf_flushlen += buf_datalen(conn->outbuf) - old_datalen;
1802 else
1803 conn->outbuf_flushlen += len;
1806 /** Return the conn to addr/port that has the most recent
1807 * timestamp_created, or NULL if no such conn exists. */
1808 or_connection_t *
1809 connection_or_exact_get_by_addr_port(uint32_t addr, uint16_t port)
1811 int i, n;
1812 connection_t *conn;
1813 or_connection_t *best=NULL;
1814 connection_t **carray;
1816 get_connection_array(&carray,&n);
1817 for (i=0;i<n;i++) {
1818 conn = carray[i];
1819 if (conn->type == CONN_TYPE_OR &&
1820 conn->addr == addr &&
1821 conn->port == port &&
1822 !conn->marked_for_close &&
1823 (!best || best->_base.timestamp_created < conn->timestamp_created))
1824 best = TO_OR_CONN(conn);
1826 return best;
1829 /** Return a connection with given type, address, port, and purpose;
1830 * or NULL if no such connection exists. */
1831 connection_t *
1832 connection_get_by_type_addr_port_purpose(int type,
1833 uint32_t addr, uint16_t port,
1834 int purpose)
1836 int i, n;
1837 connection_t *conn;
1838 connection_t **carray;
1840 get_connection_array(&carray,&n);
1841 for (i=0;i<n;i++) {
1842 conn = carray[i];
1843 if (conn->type == type &&
1844 conn->addr == addr &&
1845 conn->port == port &&
1846 conn->purpose == purpose &&
1847 !conn->marked_for_close)
1848 return conn;
1850 return NULL;
1853 /** Return the connection with id <b>id</b> if it is not already marked for
1854 * close.
1856 edge_connection_t *
1857 connection_get_by_global_id(uint32_t id)
1859 int i, n;
1860 connection_t *conn;
1861 connection_t **carray;
1863 get_connection_array(&carray,&n);
1864 for (i=0;i<n;i++) {
1865 conn = carray[i];
1866 if (CONN_IS_EDGE(conn) && TO_EDGE_CONN(conn)->global_identifier == id) {
1867 if (!conn->marked_for_close)
1868 return TO_EDGE_CONN(conn);
1869 else
1870 return NULL;
1873 return NULL;
1876 /** Return a connection of type <b>type</b> that is not marked for close.
1878 connection_t *
1879 connection_get_by_type(int type)
1881 int i, n;
1882 connection_t *conn;
1883 connection_t **carray;
1885 get_connection_array(&carray,&n);
1886 for (i=0;i<n;i++) {
1887 conn = carray[i];
1888 if (conn->type == type && !conn->marked_for_close)
1889 return conn;
1891 return NULL;
1894 /** Return a connection of type <b>type</b> that is in state <b>state</b>,
1895 * and that is not marked for close.
1897 connection_t *
1898 connection_get_by_type_state(int type, int state)
1900 int i, n;
1901 connection_t *conn;
1902 connection_t **carray;
1904 get_connection_array(&carray,&n);
1905 for (i=0;i<n;i++) {
1906 conn = carray[i];
1907 if (conn->type == type && conn->state == state && !conn->marked_for_close)
1908 return conn;
1910 return NULL;
1913 /** Return the connection of type <b>type</b> that is in state
1914 * <b>state</b>, that was written to least recently, and that is not
1915 * marked for close.
1917 connection_t *
1918 connection_get_by_type_state_lastwritten(int type, int state)
1920 int i, n;
1921 connection_t *conn, *best=NULL;
1922 connection_t **carray;
1924 get_connection_array(&carray,&n);
1925 for (i=0;i<n;i++) {
1926 conn = carray[i];
1927 if (conn->type == type && conn->state == state && !conn->marked_for_close)
1928 if (!best || conn->timestamp_lastwritten < best->timestamp_lastwritten)
1929 best = conn;
1931 return best;
1934 /** Return a connection of type <b>type</b> that has rendquery equal
1935 * to <b>rendquery</b>, and that is not marked for close. If state
1936 * is non-zero, conn must be of that state too.
1938 connection_t *
1939 connection_get_by_type_state_rendquery(int type, int state,
1940 const char *rendquery)
1942 int i, n;
1943 connection_t *conn;
1944 connection_t **carray;
1946 tor_assert(type == CONN_TYPE_DIR ||
1947 type == CONN_TYPE_AP || type == CONN_TYPE_EXIT);
1949 get_connection_array(&carray,&n);
1950 for (i=0;i<n;i++) {
1951 conn = carray[i];
1952 if (conn->type == type &&
1953 !conn->marked_for_close &&
1954 (!state || state == conn->state)) {
1955 if (type == CONN_TYPE_DIR &&
1956 rend_cmp_service_ids(rendquery, TO_DIR_CONN(conn)->rend_query))
1957 return conn;
1958 else if (CONN_IS_EDGE(conn) &&
1959 rend_cmp_service_ids(rendquery, TO_EDGE_CONN(conn)->rend_query))
1960 return conn;
1963 return NULL;
1966 /** Return an open, non-marked connection of a given type and purpose, or NULL
1967 * if no such connection exists. */
1968 connection_t *
1969 connection_get_by_type_purpose(int type, int purpose)
1971 int i, n;
1972 connection_t *conn;
1973 connection_t **carray;
1975 get_connection_array(&carray,&n);
1976 for (i=0;i<n;i++) {
1977 conn = carray[i];
1978 if (conn->type == type &&
1979 !conn->marked_for_close &&
1980 (purpose == conn->purpose))
1981 return conn;
1983 return NULL;
1986 /** Return 1 if <b>conn</b> is a listener conn, else return 0. */
1988 connection_is_listener(connection_t *conn)
1990 if (conn->type == CONN_TYPE_OR_LISTENER ||
1991 conn->type == CONN_TYPE_AP_LISTENER ||
1992 conn->type == CONN_TYPE_AP_TRANS_LISTENER ||
1993 conn->type == CONN_TYPE_AP_NATD_LISTENER ||
1994 conn->type == CONN_TYPE_DIR_LISTENER ||
1995 conn->type == CONN_TYPE_CONTROL_LISTENER)
1996 return 1;
1997 return 0;
2000 /** Return 1 if <b>conn</b> is in state "open" and is not marked
2001 * for close, else return 0.
2004 connection_state_is_open(connection_t *conn)
2006 tor_assert(conn);
2008 if (conn->marked_for_close)
2009 return 0;
2011 if ((conn->type == CONN_TYPE_OR && conn->state == OR_CONN_STATE_OPEN) ||
2012 (conn->type == CONN_TYPE_AP && conn->state == AP_CONN_STATE_OPEN) ||
2013 (conn->type == CONN_TYPE_EXIT && conn->state == EXIT_CONN_STATE_OPEN) ||
2014 (conn->type == CONN_TYPE_CONTROL &&
2015 (conn->state == CONTROL_CONN_STATE_OPEN_V0 ||
2016 conn->state == CONTROL_CONN_STATE_OPEN_V1)))
2017 return 1;
2019 return 0;
2022 /** Return 1 if conn is in 'connecting' state, else return 0. */
2024 connection_state_is_connecting(connection_t *conn)
2026 tor_assert(conn);
2028 if (conn->marked_for_close)
2029 return 0;
2030 switch (conn->type)
2032 case CONN_TYPE_OR:
2033 return conn->state == OR_CONN_STATE_CONNECTING;
2034 case CONN_TYPE_EXIT:
2035 return conn->state == EXIT_CONN_STATE_CONNECTING;
2036 case CONN_TYPE_DIR:
2037 return conn->state == DIR_CONN_STATE_CONNECTING;
2040 return 0;
2043 /** Allocates a base64'ed authenticator for use in http or https
2044 * auth, based on the input string <b>authenticator</b>. Returns it
2045 * if success, else returns NULL. */
2046 char *
2047 alloc_http_authenticator(const char *authenticator)
2049 /* an authenticator in Basic authentication
2050 * is just the string "username:password" */
2051 const int authenticator_length = strlen(authenticator);
2052 /* The base64_encode function needs a minimum buffer length
2053 * of 66 bytes. */
2054 const int base64_authenticator_length = (authenticator_length/48+1)*66;
2055 char *base64_authenticator = tor_malloc(base64_authenticator_length);
2056 if (base64_encode(base64_authenticator, base64_authenticator_length,
2057 authenticator, authenticator_length) < 0) {
2058 tor_free(base64_authenticator); /* free and set to null */
2059 } else {
2060 /* remove extra \n at end of encoding */
2061 base64_authenticator[strlen(base64_authenticator) - 1] = 0;
2063 return base64_authenticator;
2066 /** Given a socket handle, check whether the local address (sockname) of the
2067 * socket is one that we've connected from before. If so, double-check
2068 * whether our address has changed and we need to generate keys. If we do,
2069 * call init_keys().
2071 static void
2072 client_check_address_changed(int sock)
2074 uint32_t iface_ip, ip_out;
2075 struct sockaddr_in out_addr;
2076 socklen_t out_addr_len = sizeof(out_addr);
2077 uint32_t *ip;
2079 if (!last_interface_ip)
2080 get_interface_address(LOG_INFO, &last_interface_ip);
2081 if (!outgoing_addrs)
2082 outgoing_addrs = smartlist_create();
2084 if (getsockname(sock, (struct sockaddr*)&out_addr, &out_addr_len)<0) {
2085 int e = tor_socket_errno(sock);
2086 log_warn(LD_NET, "getsockname() to check for address change failed: %s",
2087 tor_socket_strerror(e));
2088 return;
2091 /* Okay. If we've used this address previously, we're okay. */
2092 ip_out = ntohl(out_addr.sin_addr.s_addr);
2093 SMARTLIST_FOREACH(outgoing_addrs, uint32_t*, ip,
2094 if (*ip == ip_out) return;
2097 /* Uh-oh. We haven't connected from this address before. Has the interface
2098 * address changed? */
2099 if (get_interface_address(LOG_INFO, &iface_ip)<0)
2100 return;
2101 ip = tor_malloc(sizeof(uint32_t));
2102 *ip = ip_out;
2104 if (iface_ip == last_interface_ip) {
2105 /* Nope, it hasn't changed. Add this address to the list. */
2106 smartlist_add(outgoing_addrs, ip);
2107 } else {
2108 /* The interface changed. We're a client, so we need to regenerate our
2109 * keys. First, reset the state. */
2110 log(LOG_NOTICE, LD_NET, "Our IP has changed. Rotating keys...");
2111 last_interface_ip = iface_ip;
2112 SMARTLIST_FOREACH(outgoing_addrs, void*, ip, tor_free(ip));
2113 smartlist_clear(outgoing_addrs);
2114 smartlist_add(outgoing_addrs, ip);
2115 /* Okay, now change our keys. */
2116 ip_address_changed(1);
2120 /** Process new bytes that have arrived on conn-\>inbuf.
2122 * This function just passes conn to the connection-specific
2123 * connection_*_process_inbuf() function. It also passes in
2124 * package_partial if wanted.
2126 static int
2127 connection_process_inbuf(connection_t *conn, int package_partial)
2129 tor_assert(conn);
2131 switch (conn->type) {
2132 case CONN_TYPE_OR:
2133 return connection_or_process_inbuf(TO_OR_CONN(conn));
2134 case CONN_TYPE_EXIT:
2135 case CONN_TYPE_AP:
2136 return connection_edge_process_inbuf(TO_EDGE_CONN(conn),
2137 package_partial);
2138 case CONN_TYPE_DIR:
2139 return connection_dir_process_inbuf(TO_DIR_CONN(conn));
2140 case CONN_TYPE_DNSWORKER:
2141 return connection_dns_process_inbuf(conn);
2142 case CONN_TYPE_CPUWORKER:
2143 return connection_cpu_process_inbuf(conn);
2144 case CONN_TYPE_CONTROL:
2145 return connection_control_process_inbuf(TO_CONTROL_CONN(conn));
2146 default:
2147 log_err(LD_BUG,"Bug: got unexpected conn type %d.", conn->type);
2148 tor_fragile_assert();
2149 return -1;
2153 /** Called whenever we've written data on a connection. */
2154 static int
2155 connection_flushed_some(connection_t *conn)
2157 if (conn->type == CONN_TYPE_DIR &&
2158 conn->state == DIR_CONN_STATE_SERVER_WRITING)
2159 return connection_dirserv_flushed_some(TO_DIR_CONN(conn));
2160 else
2161 return 0;
2164 /** We just finished flushing bytes from conn-\>outbuf, and there
2165 * are no more bytes remaining.
2167 * This function just passes conn to the connection-specific
2168 * connection_*_finished_flushing() function.
2170 static int
2171 connection_finished_flushing(connection_t *conn)
2173 tor_assert(conn);
2175 // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
2177 switch (conn->type) {
2178 case CONN_TYPE_OR:
2179 return connection_or_finished_flushing(TO_OR_CONN(conn));
2180 case CONN_TYPE_AP:
2181 case CONN_TYPE_EXIT:
2182 return connection_edge_finished_flushing(TO_EDGE_CONN(conn));
2183 case CONN_TYPE_DIR:
2184 return connection_dir_finished_flushing(TO_DIR_CONN(conn));
2185 case CONN_TYPE_DNSWORKER:
2186 return connection_dns_finished_flushing(conn);
2187 case CONN_TYPE_CPUWORKER:
2188 return connection_cpu_finished_flushing(conn);
2189 case CONN_TYPE_CONTROL:
2190 return connection_control_finished_flushing(TO_CONTROL_CONN(conn));
2191 default:
2192 log_err(LD_BUG,"Bug: got unexpected conn type %d.", conn->type);
2193 tor_fragile_assert();
2194 return -1;
2198 /** Called when our attempt to connect() to another server has just
2199 * succeeded.
2201 * This function just passes conn to the connection-specific
2202 * connection_*_finished_connecting() function.
2204 static int
2205 connection_finished_connecting(connection_t *conn)
2207 tor_assert(conn);
2208 switch (conn->type)
2210 case CONN_TYPE_OR:
2211 return connection_or_finished_connecting(TO_OR_CONN(conn));
2212 case CONN_TYPE_EXIT:
2213 return connection_edge_finished_connecting(TO_EDGE_CONN(conn));
2214 case CONN_TYPE_DIR:
2215 return connection_dir_finished_connecting(TO_DIR_CONN(conn));
2216 default:
2217 log_err(LD_BUG,"Bug: got unexpected conn type %d.", conn->type);
2218 tor_fragile_assert();
2219 return -1;
2223 /** Callback: invoked when a connection reaches an EOF event. */
2224 static int
2225 connection_reached_eof(connection_t *conn)
2227 switch (conn->type) {
2228 case CONN_TYPE_OR:
2229 return connection_or_reached_eof(TO_OR_CONN(conn));
2230 case CONN_TYPE_AP:
2231 case CONN_TYPE_EXIT:
2232 return connection_edge_reached_eof(TO_EDGE_CONN(conn));
2233 case CONN_TYPE_DIR:
2234 return connection_dir_reached_eof(TO_DIR_CONN(conn));
2235 case CONN_TYPE_DNSWORKER:
2236 return connection_dns_reached_eof(conn);
2237 case CONN_TYPE_CPUWORKER:
2238 return connection_cpu_reached_eof(conn);
2239 case CONN_TYPE_CONTROL:
2240 return connection_control_reached_eof(TO_CONTROL_CONN(conn));
2241 default:
2242 log_err(LD_BUG,"Bug: got unexpected conn type %d.", conn->type);
2243 tor_fragile_assert();
2244 return -1;
2248 /** Verify that connection <b>conn</b> has all of its invariants
2249 * correct. Trigger an assert if anything is invalid.
2251 void
2252 assert_connection_ok(connection_t *conn, time_t now)
2254 (void) now; /* XXXX unused. */
2255 tor_assert(conn);
2256 tor_assert(conn->type >= _CONN_TYPE_MIN);
2257 tor_assert(conn->type <= _CONN_TYPE_MAX);
2258 switch (conn->type) {
2259 case CONN_TYPE_OR:
2260 tor_assert(conn->magic == OR_CONNECTION_MAGIC);
2261 break;
2262 case CONN_TYPE_AP:
2263 case CONN_TYPE_EXIT:
2264 tor_assert(conn->magic == EDGE_CONNECTION_MAGIC);
2265 break;
2266 case CONN_TYPE_DIR:
2267 tor_assert(conn->magic == DIR_CONNECTION_MAGIC);
2268 break;
2269 case CONN_TYPE_CONTROL:
2270 tor_assert(conn->magic == CONTROL_CONNECTION_MAGIC);
2271 break;
2272 default:
2273 tor_assert(conn->magic == BASE_CONNECTION_MAGIC);
2274 break;
2277 if (conn->outbuf_flushlen > 0) {
2278 tor_assert(connection_is_writing(conn) || conn->wants_to_write);
2281 if (conn->hold_open_until_flushed)
2282 tor_assert(conn->marked_for_close);
2284 /* XXXX012 check: wants_to_read, wants_to_write, s, conn_array_index,
2285 * marked_for_close. */
2287 /* buffers */
2288 if (!connection_is_listener(conn)) {
2289 assert_buf_ok(conn->inbuf);
2290 assert_buf_ok(conn->outbuf);
2293 /* XXXX012 Fix this; no longer so.*/
2294 #if 0
2295 if (conn->type != CONN_TYPE_OR && conn->type != CONN_TYPE_DIR)
2296 tor_assert(!conn->pkey);
2297 /* pkey is set if we're a dir client, or if we're an OR in state OPEN
2298 * connected to another OR.
2300 #endif
2302 if (conn->chosen_exit_optional) {
2303 tor_assert(conn->type == CONN_TYPE_AP);
2304 tor_assert((TO_EDGE_CONN(conn))->chosen_exit_name);
2307 if (conn->type == CONN_TYPE_OR) {
2308 or_connection_t *or_conn = TO_OR_CONN(conn);
2309 if (conn->state == OR_CONN_STATE_OPEN) {
2310 /* tor_assert(conn->bandwidth > 0); */
2311 /* the above isn't necessarily true: if we just did a TLS
2312 * handshake but we didn't recognize the other peer, or it
2313 * gave a bad cert/etc, then we won't have assigned bandwidth,
2314 * yet it will be open. -RD
2316 // tor_assert(conn->read_bucket >= 0);
2318 // tor_assert(conn->addr && conn->port);
2319 tor_assert(conn->address);
2320 if (conn->state > OR_CONN_STATE_PROXY_READING)
2321 tor_assert(or_conn->tls);
2324 if (CONN_IS_EDGE(conn)) {
2325 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
2326 /* XXX unchecked: package window, deliver window. */
2327 if (conn->type == CONN_TYPE_AP) {
2329 tor_assert(edge_conn->socks_request);
2330 if (conn->state == AP_CONN_STATE_OPEN) {
2331 tor_assert(edge_conn->socks_request->has_finished);
2332 if (!conn->marked_for_close) {
2333 tor_assert(edge_conn->cpath_layer);
2334 assert_cpath_layer_ok(edge_conn->cpath_layer);
2338 if (conn->type == CONN_TYPE_EXIT) {
2339 tor_assert(conn->purpose == EXIT_PURPOSE_CONNECT ||
2340 conn->purpose == EXIT_PURPOSE_RESOLVE);
2342 } else if (conn->type != CONN_TYPE_DIR) {
2343 /* Purpose is only used for dir and exit types currently */
2344 tor_assert(!conn->purpose);
2347 switch (conn->type)
2349 case CONN_TYPE_OR_LISTENER:
2350 case CONN_TYPE_AP_LISTENER:
2351 case CONN_TYPE_AP_TRANS_LISTENER:
2352 case CONN_TYPE_AP_NATD_LISTENER:
2353 case CONN_TYPE_DIR_LISTENER:
2354 case CONN_TYPE_CONTROL_LISTENER:
2355 tor_assert(conn->state == LISTENER_STATE_READY);
2356 break;
2357 case CONN_TYPE_OR:
2358 tor_assert(conn->state >= _OR_CONN_STATE_MIN);
2359 tor_assert(conn->state <= _OR_CONN_STATE_MAX);
2360 tor_assert(TO_OR_CONN(conn)->n_circuits >= 0);
2361 break;
2362 case CONN_TYPE_EXIT:
2363 tor_assert(conn->state >= _EXIT_CONN_STATE_MIN);
2364 tor_assert(conn->state <= _EXIT_CONN_STATE_MAX);
2365 tor_assert(conn->purpose >= _EXIT_PURPOSE_MIN);
2366 tor_assert(conn->purpose <= _EXIT_PURPOSE_MAX);
2367 break;
2368 case CONN_TYPE_AP:
2369 tor_assert(conn->state >= _AP_CONN_STATE_MIN);
2370 tor_assert(conn->state <= _AP_CONN_STATE_MAX);
2371 tor_assert(TO_EDGE_CONN(conn)->socks_request);
2372 break;
2373 case CONN_TYPE_DIR:
2374 tor_assert(conn->state >= _DIR_CONN_STATE_MIN);
2375 tor_assert(conn->state <= _DIR_CONN_STATE_MAX);
2376 tor_assert(conn->purpose >= _DIR_PURPOSE_MIN);
2377 tor_assert(conn->purpose <= _DIR_PURPOSE_MAX);
2378 break;
2379 case CONN_TYPE_DNSWORKER:
2380 tor_assert(conn->state >= _DNSWORKER_STATE_MIN);
2381 tor_assert(conn->state <= _DNSWORKER_STATE_MAX);
2382 break;
2383 case CONN_TYPE_CPUWORKER:
2384 tor_assert(conn->state >= _CPUWORKER_STATE_MIN);
2385 tor_assert(conn->state <= _CPUWORKER_STATE_MAX);
2386 break;
2387 case CONN_TYPE_CONTROL:
2388 tor_assert(conn->state >= _CONTROL_CONN_STATE_MIN);
2389 tor_assert(conn->state <= _CONTROL_CONN_STATE_MAX);
2390 break;
2391 default:
2392 tor_assert(0);