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 */
6 const char connection_c_id
[] =
11 * \brief General high-level functions to handle reading and writing
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 /**************************************************************/
37 * Return the human-readable name for the connection type <b>type</b>
40 conn_type_to_string(int 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";
59 log_warn(LD_BUG
, "Bug: unknown connection type %d", type
);
60 tor_snprintf(buf
, sizeof(buf
), "unknown [%d]", type
);
66 * Return the human-readable name for the connection state <b>state</b>
67 * for the connection type <b>type</b>
70 conn_state_to_string(int type
, int state
)
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
)
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";
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";
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";
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";
121 case CONN_TYPE_DNSWORKER
:
123 case DNSWORKER_STATE_IDLE
: return "idle";
124 case DNSWORKER_STATE_BUSY
: return "busy";
127 case CONN_TYPE_CPUWORKER
:
129 case CPUWORKER_STATE_IDLE
: return "idle";
130 case CPUWORKER_STATE_BUSY_ONION
: return "busy with onion";
133 case CONN_TYPE_CONTROL
:
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)";
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
));
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.
166 connection_new(int type
)
168 static uint32_t n_connections_allocated
= 1;
170 time_t now
= time(NULL
);
176 length
= sizeof(or_connection_t
);
177 magic
= OR_CONNECTION_MAGIC
;
181 length
= sizeof(edge_connection_t
);
182 magic
= EDGE_CONNECTION_MAGIC
;
185 length
= sizeof(dir_connection_t
);
186 magic
= DIR_CONNECTION_MAGIC
;
188 case CONN_TYPE_CONTROL
:
189 length
= sizeof(control_connection_t
);
190 magic
= CONTROL_CONNECTION_MAGIC
;
193 length
= sizeof(connection_t
);
194 magic
= BASE_CONNECTION_MAGIC
;
198 conn
= tor_malloc_zero(length
);
200 conn
->s
= -1; /* give it a default of 'not used' */
201 conn
->conn_array_index
= -1; /* also default to 'not used' */
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
;
225 /** Tell libevent that we don't care about <b>conn</b> any more. */
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.
246 _connection_free(connection_t
*conn
)
249 switch (conn
->type
) {
251 tor_assert(conn
->magic
== OR_CONNECTION_MAGIC
);
252 mem
= TO_OR_CONN(conn
);
256 tor_assert(conn
->magic
== EDGE_CONNECTION_MAGIC
);
257 mem
= TO_EDGE_CONN(conn
);
260 tor_assert(conn
->magic
== DIR_CONNECTION_MAGIC
);
261 mem
= TO_DIR_CONN(conn
);
263 case CONN_TYPE_CONTROL
:
264 tor_assert(conn
->magic
== CONTROL_CONNECTION_MAGIC
);
265 mem
= TO_CONTROL_CONN(conn
);
268 tor_assert(conn
->magic
== BASE_CONNECTION_MAGIC
);
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
);
283 tor_tls_free(or_conn
->tls
);
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
);
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 */
330 /** Make sure <b>conn</b> isn't in any of the global conn lists; then free it.
333 connection_free(connection_t
*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
358 * Don't do the checks in connection_free(), because they will
362 connection_free_all(void)
365 connection_t
**carray
;
367 get_connection_array(&carray
,&n
);
369 /* We don't want to log any messages to controllers. */
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();
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.
399 connection_about_to_close_connection(connection_t
*conn
)
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
) {
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 */
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
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
);
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
);
475 circuit_detach_stream(circ
, edge_conn
);
478 edge_conn
= TO_EDGE_CONN(conn
);
479 circ
= circuit_get_by_edge_conn(edge_conn
);
481 circuit_detach_stream(circ
, edge_conn
);
482 if (conn
->state
== EXIT_CONN_STATE_RESOLVING
) {
483 connection_dns_remove(edge_conn
);
486 case CONN_TYPE_DNSWORKER
:
487 if (conn
->state
== DNSWORKER_STATE_BUSY
) {
488 dns_cancel_pending_resolve(conn
->address
);
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().
499 connection_close_immediate(connection_t
*conn
)
501 assert_connection_ok(conn
,0);
503 log_err(LD_BUG
,"Bug: Attempt to close already-closed connection.");
504 tor_fragile_assert();
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
);
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. */
527 _connection_mark_for_close(connection_t
*conn
, int line
, const char *file
)
529 assert_connection_ok(conn
,0);
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();
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.
557 connection_expire_held_open(void)
559 connection_t
**carray
, *conn
;
565 get_connection_array(&carray
, &n
);
566 for (i
= 0; i
< n
; ++i
) {
568 /* If we've been holding the connection open, but we haven't written
571 if (conn
->hold_open_until_flushed
) {
572 tor_assert(conn
->marked_for_close
);
573 if (now
- conn
->timestamp_lastwritten
>= 15) {
575 if (conn
->type
== CONN_TYPE_EXIT
||
576 (conn
->type
== CONN_TYPE_DIR
&&
577 conn
->purpose
== DIR_PURPOSE_SERVER
))
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
,
603 struct sockaddr_in listenaddr
; /* where to bind */
604 char *address
= NULL
;
608 int s
; /* the socket we're going to make */
613 memset(&listenaddr
,0,sizeof(struct sockaddr_in
));
614 if (parse_addr_port(LOG_WARN
, listenaddress
, &address
, &addr
, &usePort
)<0) {
616 "Error parsing/resolving ListenAddress %s", listenaddress
);
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
);
631 log_warn(LD_NET
,"Socket creation failed.");
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
));
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
);
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
)));
661 set_socket_nonblocking(s
);
663 conn
= connection_new(type
);
665 conn
->address
= address
;
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
);
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
);
688 /** Do basic sanity checking on a newly received socket. Return 0
689 * if it looks ok, else return -1. */
691 check_sockaddr_in(struct sockaddr
*sa
, int len
, int level
)
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
));
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
);
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.");
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.
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
;
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
));
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
);
748 "Connection accepted on socket %d (child of fd %d).",
751 set_socket_nonblocking(news
);
753 if (check_sockaddr_in((struct sockaddr
*)addrbuf
, remotelen
, LOG_INFO
)<0) {
755 "accept() returned a strange address; trying getsockname().");
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
));
763 if (check_sockaddr_in((struct sockaddr
*)addrbuf
, remotelen
,
765 log_warn(LD_NET
,"Something's wrong with this conn. Closing it.");
766 tor_close_socket(news
);
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.",
780 tor_close_socket(news
);
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.",
790 tor_close_socket(news
);
795 newconn
= connection_new(new_type
);
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
);
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.
821 connection_init_accepted_conn(connection_t
*conn
, uint8_t listener_type
)
823 connection_start_reading(conn
);
825 switch (conn
->type
) {
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);
830 switch (listener_type
) {
831 case CONN_TYPE_AP_LISTENER
:
832 conn
->state
= AP_CONN_STATE_SOCKS_WAIT
;
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
;
843 conn
->purpose
= DIR_PURPOSE_SERVER
;
844 conn
->state
= DIR_CONN_STATE_SERVER_COMMAND_WAIT
;
846 case CONN_TYPE_CONTROL
:
847 conn
->state
= CONTROL_CONN_STATE_NEEDAUTH_V0
;
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
);
871 log_warn(LD_NET
,"Error creating network socket: %s",
872 tor_socket_strerror(tor_socket_errno(-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
);
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
)));
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
)) {
909 "connect() to %s:%u failed: %s",escaped_safe_str(address
),
910 port
, tor_socket_strerror(e
));
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
);
926 if (connection_add(conn
) < 0) /* no space, forget it */
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>.
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;
958 connection_t
**carray
;
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
) {
981 if (conn
->type
!= type
|| conn
->marked_for_close
)
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
);
992 /* Okay, so this is a listener. Is it configured? */
994 SMARTLIST_FOREACH(launch
, config_line_t
*, wanted
,
998 if (!parse_addr_port(LOG_WARN
, wanted
->value
, &address
, NULL
, &port
)) {
999 int addr_matches
= !strcasecmp(address
, conn
->address
);
1003 if (port
== conn
->port
&& addr_matches
) {
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
);
1016 connection_close_immediate(conn
);
1017 connection_mark_for_close(conn
);
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. */
1031 if (!never_open_conns
) {
1032 SMARTLIST_FOREACH(launch
, config_line_t
*, cfg
,
1034 conn
= connection_create_listener(cfg
->value
, (uint16_t) port_option
,
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
);
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)
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)
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)
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)
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)
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)
1097 extern int global_read_bucket
, global_write_bucket
;
1100 connection_bucket_round_robin(int base
, int priority
,
1101 int global_bucket
, int conn_bucket
)
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
;
1128 /** How many bytes at most can we read onto this connection? */
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.
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
)
1190 } else { /* v2 query */
1191 /* no further constraints yet */
1196 /** We just read num_read onto conn. Decrement buckets appropriately. */
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,
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
);
1218 if (connection_speaks_cells(conn
) &&
1219 conn
->state
== OR_CONN_STATE_OPEN
&&
1220 TO_OR_CONN(conn
)->read_bucket
<= 0) {
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,
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
);
1241 if (connection_speaks_cells(conn
) &&
1242 conn
->state
== OR_CONN_STATE_OPEN
&&
1243 TO_OR_CONN(conn
)->write_bucket
<= 0) {
1245 (LOG_DEBUG
,LD_NET
,"write bucket exhausted. Pausing."));
1246 conn
->wants_to_write
= 1;
1247 connection_stop_writing(conn
);
1252 /** Initialize the global read bucket to options->BandwidthBurst. */
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. */
1264 connection_bucket_refill(int seconds_elapsed
)
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
);
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?
1326 connection_read_bucket_should_increase(or_connection_t
*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
)
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
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
);
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
);
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) {
1393 if (!conn
->marked_for_close
&&
1394 connection_is_reading(conn
) &&
1395 !conn
->inbuf_reached_eof
&&
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) {
1404 if (!conn
->marked_for_close
&&
1405 conn
->inbuf_reached_eof
&&
1406 connection_reached_eof(conn
) < 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
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.
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
);
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
;
1443 if (connection_speaks_cells(conn
) &&
1444 conn
->state
> OR_CONN_STATE_PROXY_READING
) {
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
);
1453 "%d: starting, inbuf_datalen %d (%d pending in tls object)."
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
);
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",
1469 log_info(LD_NET
,"tls error. breaking (nickname %s, address %s).",
1470 or_conn
->nickname
? or_conn
->nickname
: "not set",
1473 case TOR_TLS_WANTWRITE
:
1474 connection_start_writing(conn
);
1476 case TOR_TLS_WANTREAD
: /* we're already reading */
1477 case TOR_TLS_DONE
: /* no data read, so nothing to process */
1479 break; /* so we call bucket_decrement below */
1483 pending
= tor_tls_get_pending_bytes(or_conn
->tls
);
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
);
1490 log_warn(LD_BUG
, "Bug: apparently, reading pending bytes can fail.");
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
);
1501 int reached_eof
= 0;
1502 CONN_LOG_PROTECT(conn
,
1503 result
= read_to_buf(conn
->s
, at_most
, conn
->inbuf
, &reached_eof
));
1505 conn
->inbuf_reached_eof
= 1;
1507 // log_fn(LOG_DEBUG,"read_to_buf returned %d.",read_result);
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
);
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
;
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
);
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
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
1588 * Mark the connection and return -1 if you want to close it, else
1592 connection_handle_write(connection_t
*conn
, int force
)
1595 socklen_t len
=sizeof(e
);
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) {
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
);
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);
1636 return 0; /* no change, see if next time is better */
1639 /* The connection is successful. */
1640 if (connection_finished_connecting(conn
)<0)
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
);
1661 /* else open, or closing */
1662 result
= flush_buf_tls(or_conn
->tls
, conn
->outbuf
,
1663 max_to_write
, &conn
->outbuf_flushlen
);
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
);
1673 case TOR_TLS_WANTWRITE
:
1674 log_debug(LD_NET
,"wanted write.");
1675 /* we're already writing */
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 */
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
);
1699 CONN_LOG_PROTECT(conn
,
1700 result
= flush_buf(conn
->s
, conn
->outbuf
,
1701 max_to_write
, &conn
->outbuf_flushlen
));
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
);
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
;
1722 rep_hist_note_bytes_read(n_read
, now
);
1723 connection_read_bucket_decrement(conn
, n_read
);
1728 /* If we wrote any bytes from our buffer, then call the appropriate
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 */
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
);
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.
1761 _connection_write_to_buf_impl(const char *string
, size_t len
,
1762 connection_t
*conn
, int zlib
)
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
)
1772 old_datalen
= buf_datalen(conn
->outbuf
);
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
));
1781 CONN_LOG_PROTECT(conn
, r
= write_to_buf(string
, len
, conn
->outbuf
));
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. */
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
);
1793 "write_to_buf failed. Closing connection (fd %d).", conn
->s
);
1794 connection_mark_for_close(conn
);
1799 connection_start_writing(conn
);
1801 conn
->outbuf_flushlen
+= buf_datalen(conn
->outbuf
) - old_datalen
;
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. */
1809 connection_or_exact_get_by_addr_port(uint32_t addr
, uint16_t port
)
1813 or_connection_t
*best
=NULL
;
1814 connection_t
**carray
;
1816 get_connection_array(&carray
,&n
);
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
);
1829 /** Return a connection with given type, address, port, and purpose;
1830 * or NULL if no such connection exists. */
1832 connection_get_by_type_addr_port_purpose(int type
,
1833 uint32_t addr
, uint16_t port
,
1838 connection_t
**carray
;
1840 get_connection_array(&carray
,&n
);
1843 if (conn
->type
== type
&&
1844 conn
->addr
== addr
&&
1845 conn
->port
== port
&&
1846 conn
->purpose
== purpose
&&
1847 !conn
->marked_for_close
)
1853 /** Return the connection with id <b>id</b> if it is not already marked for
1857 connection_get_by_global_id(uint32_t id
)
1861 connection_t
**carray
;
1863 get_connection_array(&carray
,&n
);
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
);
1876 /** Return a connection of type <b>type</b> that is not marked for close.
1879 connection_get_by_type(int type
)
1883 connection_t
**carray
;
1885 get_connection_array(&carray
,&n
);
1888 if (conn
->type
== type
&& !conn
->marked_for_close
)
1894 /** Return a connection of type <b>type</b> that is in state <b>state</b>,
1895 * and that is not marked for close.
1898 connection_get_by_type_state(int type
, int state
)
1902 connection_t
**carray
;
1904 get_connection_array(&carray
,&n
);
1907 if (conn
->type
== type
&& conn
->state
== state
&& !conn
->marked_for_close
)
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
1918 connection_get_by_type_state_lastwritten(int type
, int state
)
1921 connection_t
*conn
, *best
=NULL
;
1922 connection_t
**carray
;
1924 get_connection_array(&carray
,&n
);
1927 if (conn
->type
== type
&& conn
->state
== state
&& !conn
->marked_for_close
)
1928 if (!best
|| conn
->timestamp_lastwritten
< best
->timestamp_lastwritten
)
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.
1939 connection_get_by_type_state_rendquery(int type
, int state
,
1940 const char *rendquery
)
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
);
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
))
1958 else if (CONN_IS_EDGE(conn
) &&
1959 rend_cmp_service_ids(rendquery
, TO_EDGE_CONN(conn
)->rend_query
))
1966 /** Return an open, non-marked connection of a given type and purpose, or NULL
1967 * if no such connection exists. */
1969 connection_get_by_type_purpose(int type
, int purpose
)
1973 connection_t
**carray
;
1975 get_connection_array(&carray
,&n
);
1978 if (conn
->type
== type
&&
1979 !conn
->marked_for_close
&&
1980 (purpose
== conn
->purpose
))
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
)
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
)
2008 if (conn
->marked_for_close
)
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
)))
2022 /** Return 1 if conn is in 'connecting' state, else return 0. */
2024 connection_state_is_connecting(connection_t
*conn
)
2028 if (conn
->marked_for_close
)
2033 return conn
->state
== OR_CONN_STATE_CONNECTING
;
2034 case CONN_TYPE_EXIT
:
2035 return conn
->state
== EXIT_CONN_STATE_CONNECTING
;
2037 return conn
->state
== DIR_CONN_STATE_CONNECTING
;
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. */
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
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 */
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,
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
);
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
));
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)
2101 ip
= tor_malloc(sizeof(uint32_t));
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
);
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.
2127 connection_process_inbuf(connection_t
*conn
, int package_partial
)
2131 switch (conn
->type
) {
2133 return connection_or_process_inbuf(TO_OR_CONN(conn
));
2134 case CONN_TYPE_EXIT
:
2136 return connection_edge_process_inbuf(TO_EDGE_CONN(conn
),
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
));
2147 log_err(LD_BUG
,"Bug: got unexpected conn type %d.", conn
->type
);
2148 tor_fragile_assert();
2153 /** Called whenever we've written data on a connection. */
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
));
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.
2171 connection_finished_flushing(connection_t
*conn
)
2175 // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
2177 switch (conn
->type
) {
2179 return connection_or_finished_flushing(TO_OR_CONN(conn
));
2181 case CONN_TYPE_EXIT
:
2182 return connection_edge_finished_flushing(TO_EDGE_CONN(conn
));
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
));
2192 log_err(LD_BUG
,"Bug: got unexpected conn type %d.", conn
->type
);
2193 tor_fragile_assert();
2198 /** Called when our attempt to connect() to another server has just
2201 * This function just passes conn to the connection-specific
2202 * connection_*_finished_connecting() function.
2205 connection_finished_connecting(connection_t
*conn
)
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
));
2215 return connection_dir_finished_connecting(TO_DIR_CONN(conn
));
2217 log_err(LD_BUG
,"Bug: got unexpected conn type %d.", conn
->type
);
2218 tor_fragile_assert();
2223 /** Callback: invoked when a connection reaches an EOF event. */
2225 connection_reached_eof(connection_t
*conn
)
2227 switch (conn
->type
) {
2229 return connection_or_reached_eof(TO_OR_CONN(conn
));
2231 case CONN_TYPE_EXIT
:
2232 return connection_edge_reached_eof(TO_EDGE_CONN(conn
));
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
));
2242 log_err(LD_BUG
,"Bug: got unexpected conn type %d.", conn
->type
);
2243 tor_fragile_assert();
2248 /** Verify that connection <b>conn</b> has all of its invariants
2249 * correct. Trigger an assert if anything is invalid.
2252 assert_connection_ok(connection_t
*conn
, time_t now
)
2254 (void) now
; /* XXXX unused. */
2256 tor_assert(conn
->type
>= _CONN_TYPE_MIN
);
2257 tor_assert(conn
->type
<= _CONN_TYPE_MAX
);
2258 switch (conn
->type
) {
2260 tor_assert(conn
->magic
== OR_CONNECTION_MAGIC
);
2263 case CONN_TYPE_EXIT
:
2264 tor_assert(conn
->magic
== EDGE_CONNECTION_MAGIC
);
2267 tor_assert(conn
->magic
== DIR_CONNECTION_MAGIC
);
2269 case CONN_TYPE_CONTROL
:
2270 tor_assert(conn
->magic
== CONTROL_CONNECTION_MAGIC
);
2273 tor_assert(conn
->magic
== BASE_CONNECTION_MAGIC
);
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. */
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.*/
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.
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
);
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
);
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);
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
);
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
);
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
);
2379 case CONN_TYPE_DNSWORKER
:
2380 tor_assert(conn
->state
>= _DNSWORKER_STATE_MIN
);
2381 tor_assert(conn
->state
<= _DNSWORKER_STATE_MAX
);
2383 case CONN_TYPE_CPUWORKER
:
2384 tor_assert(conn
->state
>= _CPUWORKER_STATE_MIN
);
2385 tor_assert(conn
->state
<= _CPUWORKER_STATE_MAX
);
2387 case CONN_TYPE_CONTROL
:
2388 tor_assert(conn
->state
>= _CONTROL_CONN_STATE_MIN
);
2389 tor_assert(conn
->state
<= _CONTROL_CONN_STATE_MAX
);