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 static int connection_handle_listener_read(connection_t
*conn
, int new_type
);
21 static int connection_receiver_bucket_should_increase(connection_t
*conn
);
22 static int connection_finished_flushing(connection_t
*conn
);
23 static int connection_finished_connecting(connection_t
*conn
);
24 static int connection_reached_eof(connection_t
*conn
);
25 static int connection_read_to_buf(connection_t
*conn
, int *max_to_read
);
26 static int connection_process_inbuf(connection_t
*conn
, int package_partial
);
27 static void client_check_address_changed(int sock
);
29 static uint32_t last_interface_ip
= 0;
30 static smartlist_t
*outgoing_addrs
= NULL
;
32 /**************************************************************/
35 * Return the human-readable name for the connection type <b>type</b>
38 conn_type_to_string(int type
)
42 case CONN_TYPE_OR_LISTENER
: return "OR listener";
43 case CONN_TYPE_OR
: return "OR";
44 case CONN_TYPE_EXIT
: return "Exit";
45 case CONN_TYPE_AP_LISTENER
: return "Socks listener";
46 case CONN_TYPE_AP
: return "Socks";
47 case CONN_TYPE_DIR_LISTENER
: return "Directory listener";
48 case CONN_TYPE_DIR
: return "Directory";
49 case CONN_TYPE_DNSWORKER
: return "DNS worker";
50 case CONN_TYPE_CPUWORKER
: return "CPU worker";
51 case CONN_TYPE_CONTROL_LISTENER
: return "Control listener";
52 case CONN_TYPE_CONTROL
: return "Control";
54 log_warn(LD_BUG
, "Bug: unknown connection type %d", type
);
55 tor_snprintf(buf
, sizeof(buf
), "unknown [%d]", type
);
61 * Return the human-readable name for the connection state <b>state</b>
62 * for the connection type <b>type</b>
65 conn_state_to_string(int type
, int state
)
69 case CONN_TYPE_OR_LISTENER
:
70 case CONN_TYPE_AP_LISTENER
:
71 case CONN_TYPE_DIR_LISTENER
:
72 case CONN_TYPE_CONTROL_LISTENER
:
73 if (state
== LISTENER_STATE_READY
)
78 case OR_CONN_STATE_CONNECTING
: return "connect()ing";
79 case OR_CONN_STATE_PROXY_FLUSHING
: return "proxy flushing";
80 case OR_CONN_STATE_PROXY_READING
: return "proxy reading";
81 case OR_CONN_STATE_HANDSHAKING
: return "handshaking";
82 case OR_CONN_STATE_OPEN
: return "open";
87 case EXIT_CONN_STATE_RESOLVING
: return "waiting for dest info";
88 case EXIT_CONN_STATE_CONNECTING
: return "connecting";
89 case EXIT_CONN_STATE_OPEN
: return "open";
90 case EXIT_CONN_STATE_RESOLVEFAILED
: return "resolve failed";
95 case AP_CONN_STATE_SOCKS_WAIT
: return "waiting for dest info";
96 case AP_CONN_STATE_RENDDESC_WAIT
: return "waiting for rendezvous desc";
97 case AP_CONN_STATE_CONTROLLER_WAIT
: return "waiting for controller";
98 case AP_CONN_STATE_CIRCUIT_WAIT
: return "waiting for safe circuit";
99 case AP_CONN_STATE_CONNECT_WAIT
: return "waiting for connect";
100 case AP_CONN_STATE_RESOLVE_WAIT
: return "waiting for resolve";
101 case AP_CONN_STATE_OPEN
: return "open";
106 case DIR_CONN_STATE_CONNECTING
: return "connecting";
107 case DIR_CONN_STATE_CLIENT_SENDING
: return "client sending";
108 case DIR_CONN_STATE_CLIENT_READING
: return "client reading";
109 case DIR_CONN_STATE_SERVER_COMMAND_WAIT
: return "waiting for command";
110 case DIR_CONN_STATE_SERVER_WRITING
: return "writing";
113 case CONN_TYPE_DNSWORKER
:
115 case DNSWORKER_STATE_IDLE
: return "idle";
116 case DNSWORKER_STATE_BUSY
: return "busy";
119 case CONN_TYPE_CPUWORKER
:
121 case CPUWORKER_STATE_IDLE
: return "idle";
122 case CPUWORKER_STATE_BUSY_ONION
: return "busy with onion";
125 case CONN_TYPE_CONTROL
:
127 case CONTROL_CONN_STATE_OPEN_V0
: return "open (protocol v0)";
128 case CONTROL_CONN_STATE_OPEN_V1
: return "open (protocol v1)";
129 case CONTROL_CONN_STATE_NEEDAUTH_V0
:
130 return "waiting for authentication (protocol unknown)";
131 case CONTROL_CONN_STATE_NEEDAUTH_V1
:
132 return "waiting for authentication (protocol v1)";
137 log_warn(LD_BUG
, "Bug: unknown connection state %d (type %d)", state
, type
);
138 tor_snprintf(buf
, sizeof(buf
),
139 "unknown state [%d] on unknown [%s] connection",
140 state
, conn_type_to_string(type
));
144 /** Allocate space for a new connection_t. This function just initializes
145 * conn; you must call connection_add() to link it into the main array.
147 * Set conn-\>type to <b>type</b>. Set conn-\>s and conn-\>poll_index to
148 * -1 to signify they are not yet assigned.
150 * If conn is not a listener type, allocate buffers for it. If it's
151 * an AP type, allocate space to store the socks_request.
153 * Assign a pseudorandom next_circ_id between 0 and 2**15.
155 * Initialize conn's timestamps to now.
158 connection_new(int type
)
160 static uint32_t n_connections_allocated
= 0;
162 time_t now
= time(NULL
);
164 conn
= tor_malloc_zero(sizeof(connection_t
));
165 conn
->magic
= CONNECTION_MAGIC
;
166 conn
->s
= -1; /* give it a default of 'not used' */
167 conn
->poll_index
= -1; /* also default to 'not used' */
168 conn
->global_identifier
= n_connections_allocated
++;
171 if (!connection_is_listener(conn
)) { /* listeners never use their buf */
172 conn
->inbuf
= buf_new();
173 conn
->outbuf
= buf_new();
175 if (type
== CONN_TYPE_AP
) {
176 conn
->socks_request
= tor_malloc_zero(sizeof(socks_request_t
));
179 conn
->next_circ_id
= crypto_rand_int(1<<15);
181 conn
->timestamp_created
= now
;
182 conn
->timestamp_lastread
= now
;
183 conn
->timestamp_lastwritten
= now
;
188 /** Tell libevent that we don't care about <b>conn</b> any more. */
190 connection_unregister(connection_t
*conn
)
192 if (conn
->read_event
) {
193 if (event_del(conn
->read_event
))
194 log_warn(LD_BUG
, "Error removing read event for %d", conn
->s
);
195 tor_free(conn
->read_event
);
197 if (conn
->write_event
) {
198 if (event_del(conn
->write_event
))
199 log_warn(LD_BUG
, "Error removing write event for %d", conn
->s
);
200 tor_free(conn
->write_event
);
204 /** Deallocate memory used by <b>conn</b>. Deallocate its buffers if
205 * necessary, close its socket if necessary, and mark the directory as dirty
206 * if <b>conn</b> is an OR or OP connection.
209 _connection_free(connection_t
*conn
)
211 tor_assert(conn
->magic
== CONNECTION_MAGIC
);
213 if (!connection_is_listener(conn
)) {
214 buf_free(conn
->inbuf
);
215 buf_free(conn
->outbuf
);
217 tor_free(conn
->address
);
218 tor_free(conn
->chosen_exit_name
);
220 if (connection_speaks_cells(conn
)) {
222 tor_tls_free(conn
->tls
);
227 if (conn
->identity_pkey
)
228 crypto_free_pk_env(conn
->identity_pkey
);
229 tor_free(conn
->nickname
);
230 tor_free(conn
->socks_request
);
231 tor_free(conn
->incoming_cmd
);
232 tor_free(conn
->read_event
); /* Probably already freed by connection_free. */
233 tor_free(conn
->write_event
); /* Probably already freed by connection_free. */
234 tor_free(conn
->requested_resource
);
237 log_debug(LD_NET
,"closing fd %d.",conn
->s
);
238 tor_close_socket(conn
->s
);
241 if (conn
->type
== CONN_TYPE_OR
&&
242 !tor_digest_is_zero(conn
->identity_digest
)) {
243 log_warn(LD_BUG
, "called on OR conn with non-zeroed identity_digest");
244 connection_or_remove_from_identity_map(conn
);
247 memset(conn
, 0xAA, sizeof(connection_t
)); /* poison memory */
251 /** Make sure <b>conn</b> isn't in any of the global conn lists; then free it.
254 connection_free(connection_t
*conn
)
257 tor_assert(!connection_is_on_closeable_list(conn
));
258 tor_assert(!connection_in_array(conn
));
259 if (connection_speaks_cells(conn
)) {
260 if (conn
->state
== OR_CONN_STATE_OPEN
)
261 directory_set_dirty();
262 if (!tor_digest_is_zero(conn
->identity_digest
)) {
263 connection_or_remove_from_identity_map(conn
);
266 if (conn
->type
== CONN_TYPE_CONTROL
) {
267 conn
->event_mask
= 0;
268 control_update_global_event_mask();
270 connection_unregister(conn
);
271 _connection_free(conn
);
274 /** Call _connection_free() on every connection in our array, and release all
275 * storage helpd by connection.c. This is used by cpuworkers and dnsworkers
276 * when they fork, so they don't keep resources held open (especially
279 * Don't do the checks in connection_free(), because they will
283 connection_free_all(void)
286 connection_t
**carray
;
288 get_connection_array(&carray
,&n
);
290 /* We don't want to log any messages to controllers. */
292 if (carray
[i
]->type
== CONN_TYPE_CONTROL
)
293 carray
[i
]->event_mask
= 0;
294 control_update_global_event_mask();
296 /* Unlink everything from the identity map. */
297 connection_or_clear_identity_map();
300 _connection_free(carray
[i
]);
302 if (outgoing_addrs
) {
303 SMARTLIST_FOREACH(outgoing_addrs
, void*, addr
, tor_free(addr
));
304 smartlist_free(outgoing_addrs
);
305 outgoing_addrs
= NULL
;
309 /** Do any cleanup needed:
310 * - Directory conns that failed to fetch a rendezvous descriptor
311 * need to inform pending rendezvous streams.
312 * - OR conns need to call rep_hist_note_*() to record status.
313 * - AP conns need to send a socks reject if necessary.
314 * - Exit conns need to call connection_dns_remove() if necessary.
315 * - AP and Exit conns need to send an end cell if they can.
316 * - DNS conns need to fail any resolves that are pending on them.
319 connection_about_to_close_connection(connection_t
*conn
)
323 assert(conn
->marked_for_close
);
325 if (CONN_IS_EDGE(conn
)) {
326 if (!conn
->has_sent_end
) {
327 log_warn(LD_BUG
, "Harmless bug: Edge connection (marked at %s:%d) "
328 "hasn't sent end yet?",
329 conn
->marked_for_close_file
, conn
->marked_for_close
);
330 tor_fragile_assert();
334 switch (conn
->type
) {
336 if (conn
->state
< DIR_CONN_STATE_CLIENT_FINISHED
) {
337 /* It's a directory connection and connecting or fetching
338 * failed: forget about this router, and maybe try again. */
339 connection_dir_request_failed(conn
);
340 // XXX if it's rend desc we may want to retry -RD
342 if (conn
->purpose
== DIR_PURPOSE_FETCH_RENDDESC
)
343 rend_client_desc_here(conn
->rend_query
); /* give it a try */
346 /* Remember why we're closing this connection. */
347 if (conn
->state
!= OR_CONN_STATE_OPEN
) {
348 if (connection_or_nonopen_was_started_here(conn
)) {
349 rep_hist_note_connect_failed(conn
->identity_digest
, time(NULL
));
350 entry_guard_set_status(conn
->identity_digest
, 0);
351 control_event_or_conn_status(conn
, OR_CONN_EVENT_FAILED
);
353 } else if (conn
->hold_open_until_flushed
) {
354 /* XXXX009 We used to have an arg that told us whether we closed the
355 * connection on purpose or not. Can we use hold_open_until_flushed
356 * instead? We only set it when we are intentionally closing a
359 * (Of course, now things we set to close which expire rather than
360 * flushing still get noted as dead, not disconnected. But this is an
363 rep_hist_note_disconnect(conn
->identity_digest
, time(NULL
));
364 control_event_or_conn_status(conn
, OR_CONN_EVENT_CLOSED
);
365 } else if (conn
->identity_digest
) {
366 rep_hist_note_connection_died(conn
->identity_digest
, time(NULL
));
367 control_event_or_conn_status(conn
, OR_CONN_EVENT_CLOSED
);
371 if (conn
->socks_request
->has_finished
== 0) {
372 /* since conn gets removed right after this function finishes,
373 * there's no point trying to send back a reply at this point. */
374 log_warn(LD_BUG
,"Bug: Closing stream (marked at %s:%d) without sending"
375 " back a socks reply.",
376 conn
->marked_for_close_file
, conn
->marked_for_close
);
378 control_event_stream_status(conn
, STREAM_EVENT_CLOSED
);
382 if (conn
->state
== EXIT_CONN_STATE_RESOLVING
) {
383 circ
= circuit_get_by_edge_conn(conn
);
385 circuit_detach_stream(circ
, conn
);
386 connection_dns_remove(conn
);
389 case CONN_TYPE_DNSWORKER
:
390 if (conn
->state
== DNSWORKER_STATE_BUSY
) {
391 dns_cancel_pending_resolve(conn
->address
);
397 /** Close the underlying socket for <b>conn</b>, so we don't try to
398 * flush it. Must be used in conjunction with (right before)
399 * connection_mark_for_close().
402 connection_close_immediate(connection_t
*conn
)
404 assert_connection_ok(conn
,0);
406 log_err(LD_BUG
,"Bug: Attempt to close already-closed connection.");
407 tor_fragile_assert();
410 if (conn
->outbuf_flushlen
) {
411 log_info(LD_NET
,"fd %d, type %s, state %s, %d bytes on outbuf.",
412 conn
->s
, conn_type_to_string(conn
->type
),
413 conn_state_to_string(conn
->type
, conn
->state
),
414 (int)conn
->outbuf_flushlen
);
417 connection_unregister(conn
);
419 tor_close_socket(conn
->s
);
421 if (!connection_is_listener(conn
)) {
422 buf_clear(conn
->outbuf
);
423 conn
->outbuf_flushlen
= 0;
427 /** Mark <b>conn</b> to be closed next time we loop through
428 * conn_close_if_marked() in main.c. */
430 _connection_mark_for_close(connection_t
*conn
, int line
, const char *file
)
432 assert_connection_ok(conn
,0);
436 if (conn
->marked_for_close
) {
437 log(LOG_WARN
,LD_BUG
,"Duplicate call to connection_mark_for_close at %s:%d"
438 " (first at %s:%d)", file
, line
, conn
->marked_for_close_file
,
439 conn
->marked_for_close
);
440 tor_fragile_assert();
444 conn
->marked_for_close
= line
;
445 conn
->marked_for_close_file
= file
;
446 add_connection_to_closeable_list(conn
);
448 /* in case we're going to be held-open-til-flushed, reset
449 * the number of seconds since last successful write, so
450 * we get our whole 15 seconds */
451 conn
->timestamp_lastwritten
= time(NULL
);
454 /** Find each connection that has hold_open_until_flushed set to
455 * 1 but hasn't written in the past 15 seconds, and set
456 * hold_open_until_flushed to 0. This means it will get cleaned
457 * up in the next loop through close_if_marked() in main.c.
460 connection_expire_held_open(void)
462 connection_t
**carray
, *conn
;
468 get_connection_array(&carray
, &n
);
469 for (i
= 0; i
< n
; ++i
) {
471 /* If we've been holding the connection open, but we haven't written
474 if (conn
->hold_open_until_flushed
) {
475 tor_assert(conn
->marked_for_close
);
476 if (now
- conn
->timestamp_lastwritten
>= 15) {
478 if (conn
->type
== CONN_TYPE_EXIT
||
479 (conn
->type
== CONN_TYPE_DIR
&&
480 conn
->purpose
== DIR_PURPOSE_SERVER
))
483 severity
= LOG_NOTICE
;
484 log_fn(severity
, LD_NET
,
485 "Giving up on marked_for_close conn that's been flushing "
486 "for 15s (fd %d, type %s, state %s).",
487 conn
->s
, conn_type_to_string(conn
->type
),
488 conn_state_to_string(conn
->type
, conn
->state
));
489 conn
->hold_open_until_flushed
= 0;
495 /** Bind a new non-blocking socket listening to
496 * <b>listenaddress</b>:<b>listenport</b>, and add this new connection
497 * (of type <b>type</b>) to the connection array.
499 * If <b>listenaddress</b> includes a port, we bind on that port;
500 * otherwise, we use listenport.
502 static connection_t
*
503 connection_create_listener(const char *listenaddress
, uint16_t listenport
,
506 struct sockaddr_in listenaddr
; /* where to bind */
507 char *address
= NULL
;
511 int s
; /* the socket we're going to make */
516 memset(&listenaddr
,0,sizeof(struct sockaddr_in
));
517 if (parse_addr_port(listenaddress
, &address
, &addr
, &usePort
)<0) {
519 "Error parsing/resolving ListenAddress %s", listenaddress
);
524 usePort
= listenport
;
525 listenaddr
.sin_addr
.s_addr
= htonl(addr
);
526 listenaddr
.sin_family
= AF_INET
;
527 listenaddr
.sin_port
= htons((uint16_t) usePort
);
529 log_notice(LD_NET
, "Opening %s on %s:%d",
530 conn_type_to_string(type
), address
, usePort
);
532 s
= socket(PF_INET
,SOCK_STREAM
,IPPROTO_TCP
);
534 log_warn(LD_NET
,"Socket creation failed.");
536 } else if (!SOCKET_IS_POLLABLE(s
)) {
537 log_warn(LD_NET
,"Too many connections; can't create pollable listener.");
543 /* REUSEADDR on normal places means you can rebind to the port
544 * right after somebody else has let it go. But REUSEADDR on win32
545 * means you can bind to the port _even when somebody else
546 * already has it bound_. So, don't do that on Win32. */
547 setsockopt(s
, SOL_SOCKET
, SO_REUSEADDR
, (void*) &one
, sizeof(one
));
550 if (bind(s
,(struct sockaddr
*)&listenaddr
,sizeof(listenaddr
)) < 0) {
551 const char *helpfulhint
= "";
552 int e
= tor_socket_errno(s
);
553 if (ERRNO_IS_EADDRINUSE(e
))
554 helpfulhint
= ". Is Tor already running?";
555 log_warn(LD_NET
, "Could not bind to %s:%u: %s%s", address
, usePort
,
556 tor_socket_strerror(e
), helpfulhint
);
560 if (listen(s
,SOMAXCONN
) < 0) {
561 log_warn(LD_NET
, "Could not listen on %s:%u: %s", address
, usePort
,
562 tor_socket_strerror(tor_socket_errno(s
)));
566 set_socket_nonblocking(s
);
568 conn
= connection_new(type
);
570 conn
->address
= address
;
572 conn
->port
= usePort
;
574 if (connection_add(conn
) < 0) { /* no space, forget it */
575 log_warn(LD_NET
,"connection_add failed. Giving up.");
576 connection_free(conn
);
580 log_debug(LD_NET
,"%s listening on port %u.",
581 conn_type_to_string(type
), usePort
);
583 conn
->state
= LISTENER_STATE_READY
;
584 connection_start_reading(conn
);
593 /** Do basic sanity checking on a newly received socket. Return 0
594 * if it looks ok, else return -1. */
596 check_sockaddr_in(struct sockaddr
*sa
, int len
, int level
)
599 struct sockaddr_in
*sin
=(struct sockaddr_in
*)sa
;
601 if (len
!= sizeof(struct sockaddr_in
)) {
602 log_fn(level
, LD_NET
, "Length of address not as expected: %d vs %d",
603 len
,(int)sizeof(struct sockaddr_in
));
606 if (sa
->sa_family
!= AF_INET
) {
607 log_fn(level
, LD_NET
, "Family of address not as expected: %d vs %d",
608 sa
->sa_family
, AF_INET
);
611 if (sin
->sin_addr
.s_addr
== 0 || sin
->sin_port
== 0) {
612 log_fn(level
, LD_NET
,
613 "Address for new connection has address/port equal to zero.");
619 /** The listener connection <b>conn</b> told poll() it wanted to read.
620 * Call accept() on conn-\>s, and add the new connection if necessary.
623 connection_handle_listener_read(connection_t
*conn
, int new_type
)
625 int news
; /* the new socket */
626 connection_t
*newconn
;
627 /* information about the remote peer when connecting to other routers */
628 struct sockaddr_in remote
;
630 /* length of the remote address. Must be whatever accept() needs. */
631 socklen_t remotelen
= 256;
632 char tmpbuf
[INET_NTOA_BUF_LEN
];
633 tor_assert((size_t)remotelen
>= sizeof(struct sockaddr_in
));
634 memset(addrbuf
, 0, sizeof(addrbuf
));
636 news
= accept(conn
->s
,(struct sockaddr
*)&addrbuf
,&remotelen
);
637 if (!SOCKET_IS_POLLABLE(news
)) {
638 /* accept() error, or too many conns to poll */
641 /* Too many conns to poll. */
642 log_warn(LD_NET
,"Too many connections; couldn't accept connection.");
643 tor_close_socket(news
);
646 e
= tor_socket_errno(conn
->s
);
647 if (ERRNO_IS_ACCEPT_EAGAIN(e
)) {
648 return 0; /* he hung up before we could accept(). that's fine. */
649 } else if (ERRNO_IS_ACCEPT_RESOURCE_LIMIT(e
)) {
650 log_notice(LD_NET
,"accept failed: %s. Dropping incoming connection.",
651 tor_socket_strerror(e
));
654 /* else there was a real error. */
655 log_warn(LD_NET
,"accept() failed: %s. Closing listener.",
656 tor_socket_strerror(e
));
657 connection_mark_for_close(conn
);
661 "Connection accepted on socket %d (child of fd %d).",
664 set_socket_nonblocking(news
);
666 if (check_sockaddr_in((struct sockaddr
*)addrbuf
, remotelen
, LOG_INFO
)<0) {
668 "accept() returned a strange address; trying getsockname().");
670 memset(addrbuf
, 0, sizeof(addrbuf
));
671 if (getsockname(news
, (struct sockaddr
*)addrbuf
, &remotelen
)<0) {
672 log_warn(LD_NET
, "getsockname() failed.");
674 if (check_sockaddr_in((struct sockaddr
*)addrbuf
, remotelen
,
676 log_warn(LD_NET
,"Something's wrong with this conn. Closing it.");
677 tor_close_socket(news
);
682 memcpy(&remote
, addrbuf
, sizeof(struct sockaddr_in
));
684 /* process entrance policies here, before we even create the connection */
685 if (new_type
== CONN_TYPE_AP
) {
686 /* check sockspolicy to see if we should accept it */
687 if (socks_policy_permits_address(ntohl(remote
.sin_addr
.s_addr
)) == 0) {
688 tor_inet_ntoa(&remote
.sin_addr
, tmpbuf
, sizeof(tmpbuf
));
689 log_notice(LD_APP
,"Denying socks connection from untrusted address %s.",
691 tor_close_socket(news
);
695 if (new_type
== CONN_TYPE_DIR
) {
696 /* check dirpolicy to see if we should accept it */
697 if (dir_policy_permits_address(ntohl(remote
.sin_addr
.s_addr
)) == 0) {
698 tor_inet_ntoa(&remote
.sin_addr
, tmpbuf
, sizeof(tmpbuf
));
699 log_notice(LD_DIRSERV
,"Denying dir connection from address %s.",
701 tor_close_socket(news
);
706 newconn
= connection_new(new_type
);
709 /* remember the remote address */
710 newconn
->addr
= ntohl(remote
.sin_addr
.s_addr
);
711 newconn
->port
= ntohs(remote
.sin_port
);
712 newconn
->address
= tor_dup_addr(newconn
->addr
);
714 if (connection_add(newconn
) < 0) { /* no space, forget it */
715 connection_free(newconn
);
716 return 0; /* no need to tear down the parent */
719 if (connection_init_accepted_conn(newconn
) < 0) {
720 connection_mark_for_close(newconn
);
726 /** Initialize states for newly accepted connection <b>conn</b>.
727 * If conn is an OR, start the tls handshake.
730 connection_init_accepted_conn(connection_t
*conn
)
732 connection_start_reading(conn
);
734 switch (conn
->type
) {
736 return connection_tls_start_handshake(conn
, 1);
738 conn
->state
= AP_CONN_STATE_SOCKS_WAIT
;
741 conn
->purpose
= DIR_PURPOSE_SERVER
;
742 conn
->state
= DIR_CONN_STATE_SERVER_COMMAND_WAIT
;
744 case CONN_TYPE_CONTROL
:
745 conn
->state
= CONTROL_CONN_STATE_NEEDAUTH_V0
;
751 /** Take conn, make a nonblocking socket; try to connect to
752 * addr:port (they arrive in *host order*). If fail, return -1. Else
753 * assign s to conn-\>s: if connected return 1, if EAGAIN return 0.
755 * address is used to make the logs useful.
757 * On success, add conn to the list of polled connections.
760 connection_connect(connection_t
*conn
, char *address
,
761 uint32_t addr
, uint16_t port
)
763 int s
, inprogress
= 0;
764 struct sockaddr_in dest_addr
;
765 or_options_t
*options
= get_options();
767 s
= socket(PF_INET
,SOCK_STREAM
,IPPROTO_TCP
);
769 log_warn(LD_NET
,"Error creating network socket: %s",
770 tor_socket_strerror(tor_socket_errno(-1)));
772 } else if (!SOCKET_IS_POLLABLE(s
)) {
774 "Too many connections; can't create pollable connection to %s",
780 if (options
->OutboundBindAddress
) {
781 struct sockaddr_in ext_addr
;
783 memset(&ext_addr
, 0, sizeof(ext_addr
));
784 ext_addr
.sin_family
= AF_INET
;
785 ext_addr
.sin_port
= 0;
786 if (!tor_inet_aton(options
->OutboundBindAddress
, &ext_addr
.sin_addr
)) {
787 log_warn(LD_CONFIG
,"Outbound bind address '%s' didn't parse. Ignoring.",
788 options
->OutboundBindAddress
);
790 if (bind(s
, (struct sockaddr
*)&ext_addr
, sizeof(ext_addr
)) < 0) {
791 log_warn(LD_NET
,"Error binding network socket: %s",
792 tor_socket_strerror(tor_socket_errno(s
)));
798 set_socket_nonblocking(s
);
800 memset(&dest_addr
,0,sizeof(dest_addr
));
801 dest_addr
.sin_family
= AF_INET
;
802 dest_addr
.sin_port
= htons(port
);
803 dest_addr
.sin_addr
.s_addr
= htonl(addr
);
805 log_debug(LD_NET
,"Connecting to %s:%u.",safe_str(address
),port
);
807 if (connect(s
,(struct sockaddr
*)&dest_addr
,sizeof(dest_addr
)) < 0) {
808 int e
= tor_socket_errno(s
);
809 if (!ERRNO_IS_CONN_EINPROGRESS(e
)) {
812 "connect() to %s:%u failed: %s",safe_str(address
),port
,
813 tor_socket_strerror(e
));
821 if (!server_mode(options
))
822 client_check_address_changed(s
);
824 /* it succeeded. we're connected. */
825 log_fn(inprogress
?LOG_DEBUG
:LOG_INFO
, LD_NET
,
826 "Connection to %s:%u %s (sock %d).",safe_str(address
),port
,
827 inprogress
?"in progress":"established",s
);
829 if (connection_add(conn
) < 0) /* no space, forget it */
831 return inprogress
? 0 : 1;
835 * Launch any configured listener connections of type <b>type</b>. (A
836 * listener is configured if <b>port_option</b> is non-zero. If any
837 * ListenAddress configuration options are given in <b>cfg</b>, create a
838 * connection binding to each one. Otherwise, create a single
839 * connection binding to the address <b>default_addr</b>.)
841 * If <b>force</b> is true, close and re-open all listener connections.
842 * Otherwise, only relaunch the listeners of this type if the number of
843 * existing connections is not as configured (e.g., because one died),
844 * or if the existing connections do not match those configured.
846 * Add all old conns that should be closed to <b>replaced_conns</b>.
847 * Add all new connections to <b>new_conns</b>.
850 retry_listeners(int type
, config_line_t
*cfg
,
851 int port_option
, const char *default_addr
, int force
,
852 smartlist_t
*replaced_conns
,
853 smartlist_t
*new_conns
)
855 smartlist_t
*launch
= smartlist_create();
856 int free_launch_elts
= 1;
860 connection_t
**carray
;
863 if (cfg
&& port_option
) {
864 for (c
= cfg
; c
; c
= c
->next
) {
865 smartlist_add(launch
, c
);
867 free_launch_elts
= 0;
868 } else if (port_option
) {
869 line
= tor_malloc_zero(sizeof(config_line_t
));
870 line
->key
= tor_strdup("");
871 line
->value
= tor_strdup(default_addr
);
872 smartlist_add(launch
, line
);
876 SMARTLIST_FOREACH(launch, config_line_t *, l,
877 log_fn(LOG_NOTICE, "#%s#%s", l->key, l->value));
880 get_connection_array(&carray
,&n_conn
);
881 for (i
=0; i
< n_conn
; ++i
) {
883 if (conn
->type
!= type
|| conn
->marked_for_close
)
886 /* It's a listener, and we're relaunching all listeners of this
887 * type. Close this one. */
888 log_fn(LOG_NOTICE
, LD_NET
, "Closing %s on %s:%d",
889 conn_type_to_string(type
), conn
->address
, conn
->port
);
890 connection_close_immediate(conn
);
891 connection_mark_for_close(conn
);
894 /* Okay, so this is a listener. Is it configured? */
896 SMARTLIST_FOREACH(launch
, config_line_t
*, wanted
,
900 if (! parse_addr_port(wanted
->value
, &address
, NULL
, &port
)) {
901 int addr_matches
= !strcasecmp(address
, conn
->address
);
905 if (port
== conn
->port
&& addr_matches
) {
912 /* This one isn't configured. Close it. */
913 log_notice(LD_NET
, "Closing %s on %s:%d",
914 conn_type_to_string(type
), conn
->address
, conn
->port
);
915 if (replaced_conns
) {
916 smartlist_add(replaced_conns
, conn
);
918 connection_close_immediate(conn
);
919 connection_mark_for_close(conn
);
922 /* It's configured; we don't need to launch it. */
923 // log_debug(LD_NET, "Already have %s on %s:%d",
924 // conn_type_to_string(type), conn->address, conn->port);
925 smartlist_remove(launch
, line
);
926 if (free_launch_elts
)
927 config_free_lines(line
);
931 /* Now open all the listeners that are configured but not opened. */
933 SMARTLIST_FOREACH(launch
, config_line_t
*, cfg
,
935 conn
= connection_create_listener(cfg
->value
, (uint16_t) port_option
,
941 smartlist_add(new_conns
, conn
);
945 if (free_launch_elts
) {
946 SMARTLIST_FOREACH(launch
, config_line_t
*, cfg
,
947 config_free_lines(cfg
));
949 smartlist_free(launch
);
954 /** (Re)launch listeners for each port you should have open. If
955 * <b>force</b> is true, close and relaunch all listeners. If <b>force</b>
956 * is false, then only relaunch listeners when we have the wrong number of
957 * connections for a given type.
959 * Add all old conns that should be closed to <b>replaced_conns</b>.
960 * Add all new connections to <b>new_conns</b>.
963 retry_all_listeners(int force
, smartlist_t
*replaced_conns
,
964 smartlist_t
*new_conns
)
966 or_options_t
*options
= get_options();
968 if (server_mode(options
) &&
969 retry_listeners(CONN_TYPE_OR_LISTENER
, options
->ORListenAddress
,
970 options
->ORPort
, "0.0.0.0", force
,
971 replaced_conns
, new_conns
)<0)
973 if (retry_listeners(CONN_TYPE_DIR_LISTENER
, options
->DirListenAddress
,
974 options
->DirPort
, "0.0.0.0", force
,
975 replaced_conns
, new_conns
)<0)
977 if (retry_listeners(CONN_TYPE_AP_LISTENER
, options
->SocksListenAddress
,
978 options
->SocksPort
, "127.0.0.1", force
,
979 replaced_conns
, new_conns
)<0)
981 if (retry_listeners(CONN_TYPE_CONTROL_LISTENER
,
982 options
->ControlListenAddress
,
983 options
->ControlPort
, "127.0.0.1", force
,
984 replaced_conns
, new_conns
)<0)
990 extern int global_read_bucket
, global_write_bucket
;
992 /** How many bytes at most can we read onto this connection? */
994 connection_bucket_read_limit(connection_t
*conn
)
997 int base
= connection_speaks_cells(conn
) ?
998 CELL_NETWORK_SIZE
: RELAY_PAYLOAD_SIZE
;
1000 /* Do a rudimentary round-robin so one circuit can't hog a connection.
1001 * Pick at most 32 cells, at least 4 cells if possible, and if we're in
1002 * the middle pick 1/8 of the available bandwidth. */
1003 at_most
= global_read_bucket
/ 8;
1004 at_most
-= (at_most
% base
); /* round down */
1005 if (at_most
> 32*base
) /* 16 KB */
1007 else if (at_most
< 4*base
) /* 2 KB */
1010 if (at_most
> global_read_bucket
)
1011 at_most
= global_read_bucket
;
1013 if (connection_speaks_cells(conn
) && conn
->state
== OR_CONN_STATE_OPEN
)
1014 if (at_most
> conn
->receiver_bucket
)
1015 at_most
= conn
->receiver_bucket
;
1022 /** How many bytes at most can we write onto this connection? */
1024 connection_bucket_write_limit(connection_t
*conn
)
1026 unsigned int at_most
;
1028 /* do a rudimentary round-robin so one circuit can't hog a connection */
1029 if (connection_speaks_cells(conn
)) {
1030 at_most
= 32*(CELL_NETWORK_SIZE
);
1032 at_most
= 32*(RELAY_PAYLOAD_SIZE
);
1035 if (at_most
> conn
->outbuf_flushlen
)
1036 at_most
= conn
->outbuf_flushlen
;
1038 #if 0 /* don't enable til we actually do write limiting */
1039 if (at_most
> global_write_bucket
)
1040 at_most
= global_write_bucket
;
1045 /** Return 1 if the global write bucket has no bytes in it,
1046 * or return 0 if it does. */
1048 global_write_bucket_empty(void)
1050 return global_write_bucket
<= 0;
1053 /** We just read num_read onto conn. Decrement buckets appropriately. */
1055 connection_read_bucket_decrement(connection_t
*conn
, int num_read
)
1057 global_read_bucket
-= num_read
;
1058 //tor_assert(global_read_bucket >= 0);
1059 if (connection_speaks_cells(conn
) && conn
->state
== OR_CONN_STATE_OPEN
) {
1060 conn
->receiver_bucket
-= num_read
;
1061 //tor_assert(conn->receiver_bucket >= 0);
1065 /** If we have exhaused our global read bucket, or the read bucket for conn,
1068 connection_consider_empty_buckets(connection_t
*conn
)
1070 if (global_read_bucket
<= 0) {
1071 LOG_FN_CONN(conn
, (LOG_DEBUG
,LD_NET
,"global bucket exhausted. Pausing."));
1072 conn
->wants_to_read
= 1;
1073 connection_stop_reading(conn
);
1076 if (connection_speaks_cells(conn
) &&
1077 conn
->state
== OR_CONN_STATE_OPEN
&&
1078 conn
->receiver_bucket
<= 0) {
1080 (LOG_DEBUG
,LD_NET
,"receiver bucket exhausted. Pausing."));
1081 conn
->wants_to_read
= 1;
1082 connection_stop_reading(conn
);
1086 /** Initialize the global read bucket to options->BandwidthBurst,
1087 * and current_time to the current time. */
1089 connection_bucket_init(void)
1091 or_options_t
*options
= get_options();
1092 /* start it at max traffic */
1093 global_read_bucket
= (int)options
->BandwidthBurst
;
1094 global_write_bucket
= (int)options
->BandwidthBurst
;
1097 /** A second has rolled over; increment buckets appropriately. */
1099 connection_bucket_refill(struct timeval
*now
)
1103 connection_t
**carray
;
1104 or_options_t
*options
= get_options();
1106 /* refill the global buckets */
1107 if (global_read_bucket
< (int)options
->BandwidthBurst
) {
1108 global_read_bucket
+= (int)options
->BandwidthRate
;
1109 log_debug(LD_NET
,"global_read_bucket now %d.", global_read_bucket
);
1111 if (global_write_bucket
< (int)options
->BandwidthBurst
) {
1112 global_write_bucket
+= (int)options
->BandwidthRate
;
1113 log_debug(LD_NET
,"global_write_bucket now %d.", global_write_bucket
);
1116 /* refill the per-connection buckets */
1117 get_connection_array(&carray
,&n
);
1121 if (connection_receiver_bucket_should_increase(conn
)) {
1122 conn
->receiver_bucket
= conn
->bandwidth
;
1123 //log_fn(LOG_DEBUG,"Receiver bucket %d now %d.", i,
1124 // conn->receiver_bucket);
1127 if (conn
->wants_to_read
== 1 /* it's marked to turn reading back on now */
1128 && global_read_bucket
> 0 /* and we're allowed to read */
1129 && global_write_bucket
> 0 /* and we're allowed to write (XXXX,
1130 * not the best place to check this.) */
1131 && (!connection_speaks_cells(conn
) ||
1132 conn
->state
!= OR_CONN_STATE_OPEN
||
1133 conn
->receiver_bucket
> 0)) {
1134 /* and either a non-cell conn or a cell conn with non-empty bucket */
1135 LOG_FN_CONN(conn
, (LOG_DEBUG
,LD_NET
,"waking up conn (fd %d)",conn
->s
));
1136 conn
->wants_to_read
= 0;
1137 connection_start_reading(conn
);
1138 if (conn
->wants_to_write
== 1) {
1139 conn
->wants_to_write
= 0;
1140 connection_start_writing(conn
);
1146 /** Is the receiver bucket for connection <b>conn</b> low enough that we
1147 * should add another pile of tokens to it?
1150 connection_receiver_bucket_should_increase(connection_t
*conn
)
1154 if (!connection_speaks_cells(conn
))
1155 return 0; /* edge connections don't use receiver_buckets */
1156 if (conn
->state
!= OR_CONN_STATE_OPEN
)
1157 return 0; /* only open connections play the rate limiting game */
1159 if (conn
->receiver_bucket
>= conn
->bandwidth
)
1165 /** Read bytes from conn-\>s and process them.
1167 * This function gets called from conn_read() in main.c, either
1168 * when poll() has declared that conn wants to read, or (for OR conns)
1169 * when there are pending TLS bytes.
1171 * It calls connection_read_to_buf() to bring in any new bytes,
1172 * and then calls connection_process_inbuf() to process them.
1174 * Mark the connection and return -1 if you want to close it, else
1178 connection_handle_read(connection_t
*conn
)
1180 int max_to_read
=-1, try_to_read
;
1182 if (conn
->marked_for_close
)
1183 return 0; /* do nothing */
1185 conn
->timestamp_lastread
= time(NULL
);
1187 switch (conn
->type
) {
1188 case CONN_TYPE_OR_LISTENER
:
1189 return connection_handle_listener_read(conn
, CONN_TYPE_OR
);
1190 case CONN_TYPE_AP_LISTENER
:
1191 return connection_handle_listener_read(conn
, CONN_TYPE_AP
);
1192 case CONN_TYPE_DIR_LISTENER
:
1193 return connection_handle_listener_read(conn
, CONN_TYPE_DIR
);
1194 case CONN_TYPE_CONTROL_LISTENER
:
1195 return connection_handle_listener_read(conn
, CONN_TYPE_CONTROL
);
1199 try_to_read
= max_to_read
;
1200 tor_assert(!conn
->marked_for_close
);
1201 if (connection_read_to_buf(conn
, &max_to_read
) < 0) {
1202 /* There's a read error; kill the connection.*/
1203 connection_close_immediate(conn
); /* Don't flush; connection is dead. */
1204 if (CONN_IS_EDGE(conn
)) {
1205 connection_edge_end_errno(conn
, conn
->cpath_layer
);
1206 if (conn
->socks_request
) /* broken, so don't send a socks reply back */
1207 conn
->socks_request
->has_finished
= 1;
1209 connection_mark_for_close(conn
);
1212 if (CONN_IS_EDGE(conn
) &&
1213 try_to_read
!= max_to_read
) {
1214 /* instruct it not to try to package partial cells. */
1215 if (connection_process_inbuf(conn
, 0) < 0) {
1218 if (!conn
->marked_for_close
&&
1219 connection_is_reading(conn
) &&
1220 !conn
->inbuf_reached_eof
&&
1222 goto loop_again
; /* try reading again, in case more is here now */
1224 /* one last try, packaging partial cells and all. */
1225 if (!conn
->marked_for_close
&&
1226 connection_process_inbuf(conn
, 1) < 0) {
1229 if (!conn
->marked_for_close
&&
1230 conn
->inbuf_reached_eof
&&
1231 connection_reached_eof(conn
) < 0) {
1237 /** Pull in new bytes from conn-\>s onto conn-\>inbuf, either
1238 * directly or via TLS. Reduce the token buckets by the number of
1241 * If *max_to_read is -1, then decide it ourselves, else go with the
1242 * value passed to us. When returning, if it's changed, subtract the
1243 * number of bytes we read from *max_to_read.
1245 * Return -1 if we want to break conn, else return 0.
1248 connection_read_to_buf(connection_t
*conn
, int *max_to_read
)
1250 int result
, at_most
= *max_to_read
;
1251 size_t bytes_in_buf
, more_to_read
;
1253 if (at_most
== -1) { /* we need to initialize it */
1254 /* how many bytes are we allowed to read? */
1255 at_most
= connection_bucket_read_limit(conn
);
1258 bytes_in_buf
= buf_capacity(conn
->inbuf
) - buf_datalen(conn
->inbuf
);
1260 if ((size_t)at_most
> bytes_in_buf
&& bytes_in_buf
>= 1024) {
1261 more_to_read
= at_most
- bytes_in_buf
;
1262 at_most
= bytes_in_buf
;
1267 if (connection_speaks_cells(conn
) &&
1268 conn
->state
> OR_CONN_STATE_PROXY_READING
) {
1270 if (conn
->state
== OR_CONN_STATE_HANDSHAKING
) {
1271 /* continue handshaking even if global token bucket is empty */
1272 return connection_tls_continue_handshake(conn
);
1276 "%d: starting, inbuf_datalen %d (%d pending in tls object)."
1278 conn
->s
,(int)buf_datalen(conn
->inbuf
),
1279 tor_tls_get_pending_bytes(conn
->tls
), at_most
);
1281 /* else open, or closing */
1282 result
= read_to_buf_tls(conn
->tls
, at_most
, conn
->inbuf
);
1286 log_info(LD_NET
,"TLS connection closed on read. Closing. "
1287 "(Nickname %s, address %s",
1288 conn
->nickname
? conn
->nickname
: "not set", conn
->address
);
1291 log_info(LD_NET
,"tls error. breaking (nickname %s, address %s).",
1292 conn
->nickname
? conn
->nickname
: "not set", conn
->address
);
1294 case TOR_TLS_WANTWRITE
:
1295 connection_start_writing(conn
);
1297 case TOR_TLS_WANTREAD
: /* we're already reading */
1298 case TOR_TLS_DONE
: /* no data read, so nothing to process */
1300 break; /* so we call bucket_decrement below */
1304 pending
= tor_tls_get_pending_bytes(conn
->tls
);
1306 /* XXXX If we have any pending bytes, read them now. This *can*
1307 * take us over our read allotment, but really we shouldn't be
1308 * believing that SSL bytes are the same as TCP bytes anyway. */
1309 int r2
= read_to_buf_tls(conn
->tls
, pending
, conn
->inbuf
);
1311 log_warn(LD_BUG
, "Bug: apparently, reading pending bytes can fail.");
1319 CONN_LOG_PROTECT(conn
,
1320 result
= read_to_buf(conn
->s
, at_most
, conn
->inbuf
,
1321 &conn
->inbuf_reached_eof
));
1323 // log_fn(LOG_DEBUG,"read_to_buf returned %d.",read_result);
1329 if (result
> 0) { /* change *max_to_read */
1330 *max_to_read
= at_most
- result
;
1333 if (result
> 0 && !is_local_IP(conn
->addr
)) { /* remember it */
1334 rep_hist_note_bytes_read(result
, time(NULL
));
1335 connection_read_bucket_decrement(conn
, result
);
1338 if (more_to_read
&& result
== at_most
) {
1339 bytes_in_buf
= buf_capacity(conn
->inbuf
) - buf_datalen(conn
->inbuf
);
1340 tor_assert(bytes_in_buf
< 1024);
1341 at_most
= more_to_read
;
1345 /* Call even if result is 0, since the global read bucket may
1346 * have reached 0 on a different conn, and this guy needs to
1347 * know to stop reading. */
1348 connection_consider_empty_buckets(conn
);
1353 /** A pass-through to fetch_from_buf. */
1355 connection_fetch_from_buf(char *string
, size_t len
, connection_t
*conn
)
1357 return fetch_from_buf(string
, len
, conn
->inbuf
);
1360 /** Return conn-\>outbuf_flushlen: how many bytes conn wants to flush
1361 * from its outbuf. */
1363 connection_wants_to_flush(connection_t
*conn
)
1365 return conn
->outbuf_flushlen
;
1368 /** Are there too many bytes on edge connection <b>conn</b>'s outbuf to
1369 * send back a relay-level sendme yet? Return 1 if so, 0 if not. Used by
1370 * connection_edge_consider_sending_sendme().
1373 connection_outbuf_too_full(connection_t
*conn
)
1375 return (conn
->outbuf_flushlen
> 10*CELL_PAYLOAD_SIZE
);
1378 /** Try to flush more bytes onto conn-\>s.
1380 * This function gets called either from conn_write() in main.c
1381 * when poll() has declared that conn wants to write, or below
1382 * from connection_write_to_buf() when an entire TLS record is ready.
1384 * Update conn-\>timestamp_lastwritten to now, and call flush_buf
1385 * or flush_buf_tls appropriately. If it succeeds and there no more
1386 * more bytes on conn->outbuf, then call connection_finished_flushing
1389 * Mark the connection and return -1 if you want to close it, else
1393 connection_handle_write(connection_t
*conn
)
1396 socklen_t len
=sizeof(e
);
1399 time_t now
= time(NULL
);
1401 tor_assert(!connection_is_listener(conn
));
1403 if (conn
->marked_for_close
)
1404 return 0; /* do nothing */
1406 conn
->timestamp_lastwritten
= now
;
1408 /* Sometimes, "writable" means "connected". */
1409 if (connection_state_is_connecting(conn
)) {
1410 if (getsockopt(conn
->s
, SOL_SOCKET
, SO_ERROR
, (void*)&e
, &len
) < 0) {
1412 "getsockopt() syscall failed?! Please report to tor-ops.");
1413 if (CONN_IS_EDGE(conn
))
1414 connection_edge_end_errno(conn
, conn
->cpath_layer
);
1415 connection_mark_for_close(conn
);
1419 /* some sort of error, but maybe just inprogress still */
1420 if (!ERRNO_IS_CONN_EINPROGRESS(e
)) {
1421 log_info(LD_NET
,"in-progress connect failed. Removing.");
1422 if (CONN_IS_EDGE(conn
))
1423 connection_edge_end_errno(conn
, conn
->cpath_layer
);
1425 connection_close_immediate(conn
);
1426 connection_mark_for_close(conn
);
1427 /* it's safe to pass OPs to router_mark_as_down(), since it just
1428 * ignores unrecognized routers
1430 if (conn
->type
== CONN_TYPE_OR
&& !get_options()->HttpsProxy
)
1431 router_mark_as_down(conn
->identity_digest
);
1434 return 0; /* no change, see if next time is better */
1437 /* The connection is successful. */
1438 if (connection_finished_connecting(conn
)<0)
1442 max_to_write
= connection_bucket_write_limit(conn
);
1444 if (connection_speaks_cells(conn
) &&
1445 conn
->state
> OR_CONN_STATE_PROXY_READING
) {
1446 if (conn
->state
== OR_CONN_STATE_HANDSHAKING
) {
1447 connection_stop_writing(conn
);
1448 if (connection_tls_continue_handshake(conn
) < 0) {
1449 /* Don't flush; connection is dead. */
1450 connection_close_immediate(conn
);
1451 connection_mark_for_close(conn
);
1457 /* else open, or closing */
1458 result
= flush_buf_tls(conn
->tls
, conn
->outbuf
,
1459 max_to_write
, &conn
->outbuf_flushlen
);
1463 log_info(LD_NET
,result
==TOR_TLS_ERROR
?
1464 "tls error. breaking.":"TLS connection closed on flush");
1465 /* Don't flush; connection is dead. */
1466 connection_close_immediate(conn
);
1467 connection_mark_for_close(conn
);
1469 case TOR_TLS_WANTWRITE
:
1470 log_debug(LD_NET
,"wanted write.");
1471 /* we're already writing */
1473 case TOR_TLS_WANTREAD
:
1474 /* Make sure to avoid a loop if the receive buckets are empty. */
1475 log_debug(LD_NET
,"wanted read.");
1476 if (!connection_is_reading(conn
)) {
1477 connection_stop_writing(conn
);
1478 conn
->wants_to_write
= 1;
1479 /* we'll start reading again when the next second arrives,
1480 * and then also start writing again.
1483 /* else no problem, we're already reading */
1485 /* case TOR_TLS_DONE:
1486 * for TOR_TLS_DONE, fall through to check if the flushlen
1487 * is empty, so we can stop writing.
1491 CONN_LOG_PROTECT(conn
,
1492 result
= flush_buf(conn
->s
, conn
->outbuf
,
1493 max_to_write
, &conn
->outbuf_flushlen
));
1495 if (CONN_IS_EDGE(conn
))
1496 connection_edge_end_errno(conn
, conn
->cpath_layer
);
1498 connection_close_immediate(conn
); /* Don't flush; connection is dead. */
1499 connection_mark_for_close(conn
);
1504 if (result
> 0 && !is_local_IP(conn
->addr
)) { /* remember it */
1505 rep_hist_note_bytes_written(result
, now
);
1506 global_write_bucket
-= result
;
1509 if (!connection_wants_to_flush(conn
)) { /* it's done flushing */
1510 if (connection_finished_flushing(conn
) < 0) {
1511 /* already marked */
1519 /* A controller event has just happened with such urgency that we
1520 * need to write it onto controller <b>conn</b> immediately. */
1522 _connection_controller_force_write(connection_t
*conn
)
1524 /* XXX This is hideous code duplication, but raising it seems a little
1525 * tricky for now. Think more about this one. We only call it for
1526 * EVENT_ERR_MSG, so messing with buckets a little isn't such a big problem.
1530 tor_assert(!conn
->tls
);
1531 tor_assert(conn
->type
== CONN_TYPE_CONTROL
);
1532 if (conn
->marked_for_close
|| conn
->s
< 0)
1535 CONN_LOG_PROTECT(conn
,
1536 result
= flush_buf(conn
->s
, conn
->outbuf
,
1537 conn
->outbuf_flushlen
, &conn
->outbuf_flushlen
));
1539 connection_close_immediate(conn
); /* Don't flush; connection is dead. */
1540 connection_mark_for_close(conn
);
1544 if (result
> 0 && !is_local_IP(conn
->addr
)) { /* remember it */
1545 rep_hist_note_bytes_written(result
, time(NULL
));
1546 global_write_bucket
-= result
;
1549 if (!connection_wants_to_flush(conn
)) { /* it's done flushing */
1550 if (connection_finished_flushing(conn
) < 0) {
1551 /* already marked */
1557 /** Append <b>len</b> bytes of <b>string</b> onto <b>conn</b>'s
1558 * outbuf, and ask it to start writing.
1561 connection_write_to_buf(const char *string
, size_t len
, connection_t
*conn
)
1566 /* if it's marked for close, only allow write if we mean to flush it */
1567 if (conn
->marked_for_close
&& !conn
->hold_open_until_flushed
)
1570 CONN_LOG_PROTECT(conn
, r
= write_to_buf(string
, len
, conn
->outbuf
));
1572 if (CONN_IS_EDGE(conn
)) {
1573 /* if it failed, it means we have our package/delivery windows set
1574 wrong compared to our max outbuf size. close the whole circuit. */
1576 "write_to_buf failed. Closing circuit (fd %d).", conn
->s
);
1577 circuit_mark_for_close(circuit_get_by_edge_conn(conn
),
1578 END_CIRC_REASON_INTERNAL
);
1581 "write_to_buf failed. Closing connection (fd %d).", conn
->s
);
1582 connection_mark_for_close(conn
);
1587 connection_start_writing(conn
);
1588 conn
->outbuf_flushlen
+= len
;
1591 /** Return the conn to addr/port that has the most recent
1592 * timestamp_created, or NULL if no such conn exists. */
1594 connection_or_exact_get_by_addr_port(uint32_t addr
, uint16_t port
)
1597 connection_t
*conn
, *best
=NULL
;
1598 connection_t
**carray
;
1600 get_connection_array(&carray
,&n
);
1603 if (conn
->type
== CONN_TYPE_OR
&&
1604 conn
->addr
== addr
&&
1605 conn
->port
== port
&&
1606 !conn
->marked_for_close
&&
1607 (!best
|| best
->timestamp_created
< conn
->timestamp_created
))
1613 /** Return a connection with given type, address, port, and purpose;
1614 * or NULL if no such connection exists. */
1616 connection_get_by_type_addr_port_purpose(int type
,
1617 uint32_t addr
, uint16_t port
,
1622 connection_t
**carray
;
1624 get_connection_array(&carray
,&n
);
1627 if (conn
->type
== type
&&
1628 conn
->addr
== addr
&&
1629 conn
->port
== port
&&
1630 conn
->purpose
== purpose
&&
1631 !conn
->marked_for_close
)
1637 /** Return the connection with id <b>id</b> if it is not already marked for
1641 connection_get_by_global_id(uint32_t id
)
1645 connection_t
**carray
;
1647 get_connection_array(&carray
,&n
);
1650 if (conn
->global_identifier
== id
) {
1651 if (!conn
->marked_for_close
)
1660 /** Return a connection of type <b>type</b> that is not marked for close.
1663 connection_get_by_type(int type
)
1667 connection_t
**carray
;
1669 get_connection_array(&carray
,&n
);
1672 if (conn
->type
== type
&& !conn
->marked_for_close
)
1678 /** Return a connection of type <b>type</b> that is in state <b>state</b>,
1679 * and that is not marked for close.
1682 connection_get_by_type_state(int type
, int state
)
1686 connection_t
**carray
;
1688 get_connection_array(&carray
,&n
);
1691 if (conn
->type
== type
&& conn
->state
== state
&& !conn
->marked_for_close
)
1697 /** Return the connection of type <b>type</b> that is in state
1698 * <b>state</b>, that was written to least recently, and that is not
1702 connection_get_by_type_state_lastwritten(int type
, int state
)
1705 connection_t
*conn
, *best
=NULL
;
1706 connection_t
**carray
;
1708 get_connection_array(&carray
,&n
);
1711 if (conn
->type
== type
&& conn
->state
== state
&& !conn
->marked_for_close
)
1712 if (!best
|| conn
->timestamp_lastwritten
< best
->timestamp_lastwritten
)
1718 /** Return a connection of type <b>type</b> that has rendquery equal
1719 * to <b>rendquery</b>, and that is not marked for close. If state
1720 * is non-zero, conn must be of that state too.
1723 connection_get_by_type_state_rendquery(int type
, int state
,
1724 const char *rendquery
)
1728 connection_t
**carray
;
1730 get_connection_array(&carray
,&n
);
1733 if (conn
->type
== type
&&
1734 !conn
->marked_for_close
&&
1735 (!state
|| state
== conn
->state
) &&
1736 !rend_cmp_service_ids(rendquery
, conn
->rend_query
))
1742 /** Return an open, non-marked connection of a given type and purpose, or NULL
1743 * if no such connection exists. */
1745 connection_get_by_type_purpose(int type
, int purpose
)
1749 connection_t
**carray
;
1751 get_connection_array(&carray
,&n
);
1754 if (conn
->type
== type
&&
1755 !conn
->marked_for_close
&&
1756 (purpose
== conn
->purpose
))
1762 /** Return 1 if <b>conn</b> is a listener conn, else return 0. */
1764 connection_is_listener(connection_t
*conn
)
1766 if (conn
->type
== CONN_TYPE_OR_LISTENER
||
1767 conn
->type
== CONN_TYPE_AP_LISTENER
||
1768 conn
->type
== CONN_TYPE_DIR_LISTENER
||
1769 conn
->type
== CONN_TYPE_CONTROL_LISTENER
)
1774 /** Return 1 if <b>conn</b> is in state "open" and is not marked
1775 * for close, else return 0.
1778 connection_state_is_open(connection_t
*conn
)
1782 if (conn
->marked_for_close
)
1785 if ((conn
->type
== CONN_TYPE_OR
&& conn
->state
== OR_CONN_STATE_OPEN
) ||
1786 (conn
->type
== CONN_TYPE_AP
&& conn
->state
== AP_CONN_STATE_OPEN
) ||
1787 (conn
->type
== CONN_TYPE_EXIT
&& conn
->state
== EXIT_CONN_STATE_OPEN
) ||
1788 (conn
->type
== CONN_TYPE_CONTROL
&&
1789 (conn
->state
== CONTROL_CONN_STATE_OPEN_V0
||
1790 conn
->state
== CONTROL_CONN_STATE_OPEN_V1
)))
1796 /** Return 1 if conn is in 'connecting' state, else return 0. */
1798 connection_state_is_connecting(connection_t
*conn
)
1802 if (conn
->marked_for_close
)
1807 return conn
->state
== OR_CONN_STATE_CONNECTING
;
1808 case CONN_TYPE_EXIT
:
1809 return conn
->state
== EXIT_CONN_STATE_CONNECTING
;
1811 return conn
->state
== DIR_CONN_STATE_CONNECTING
;
1817 /** Alloocates a base64'ed authenticator for use in http or https
1818 * auth, based on the input string <b>authenticator</b>. Returns it
1819 * if success, else returns NULL. */
1821 alloc_http_authenticator(const char *authenticator
)
1823 /* an authenticator in Basic authentication
1824 * is just the string "username:password" */
1825 const int authenticator_length
= strlen(authenticator
);
1826 /* The base64_encode function needs a minimum buffer length
1828 const int base64_authenticator_length
= (authenticator_length
/48+1)*66;
1829 char *base64_authenticator
= tor_malloc(base64_authenticator_length
);
1830 if (base64_encode(base64_authenticator
, base64_authenticator_length
,
1831 authenticator
, authenticator_length
) < 0) {
1832 tor_free(base64_authenticator
); /* free and set to null */
1834 /* remove extra \n at end of encoding */
1835 base64_authenticator
[strlen(base64_authenticator
) - 1] = 0;
1837 return base64_authenticator
;
1840 /** Given a socket handle, check whether the local address (sockname) of the
1841 * socket is one that we've connected from before. If so, double-check
1842 * whether our address has changed and we need to generate keys. If we do,
1845 /* XXXX Handle IPv6, eventually. */
1847 client_check_address_changed(int sock
)
1849 uint32_t iface_ip
, ip_out
;
1850 struct sockaddr_in out_addr
;
1851 socklen_t out_addr_len
= sizeof(out_addr
);
1854 if (!last_interface_ip
)
1855 get_interface_address(&last_interface_ip
);
1856 if (!outgoing_addrs
)
1857 outgoing_addrs
= smartlist_create();
1859 if (getsockname(sock
, (struct sockaddr
*)&out_addr
, &out_addr_len
)<0) {
1860 int e
= tor_socket_errno(sock
);
1861 log_warn(LD_NET
, "getsockname() failed: %s", tor_socket_strerror(e
));
1865 /* Okay. If we've used this address previously, we're okay. */
1866 ip_out
= ntohl(out_addr
.sin_addr
.s_addr
);
1867 SMARTLIST_FOREACH(outgoing_addrs
, uint32_t*, ip
,
1868 if (*ip
== ip_out
) return;
1871 /* Uh-oh. We haven't connected from this address before. Has the interface
1872 * address changed? */
1873 if (get_interface_address(&iface_ip
)<0)
1875 ip
= tor_malloc(sizeof(uint32_t));
1878 if (iface_ip
== last_interface_ip
) {
1879 /* Nope, it hasn't changed. Add this address to the list. */
1880 smartlist_add(outgoing_addrs
, ip
);
1882 /* The interface changed. We're a client, so we need to regenerate our
1883 * keys. First, reset the state. */
1884 log(LOG_NOTICE
, LD_NET
, "Our IP has changed. Rotating keys...");
1885 last_interface_ip
= iface_ip
;
1886 SMARTLIST_FOREACH(outgoing_addrs
, void*, ip
, tor_free(ip
));
1887 smartlist_clear(outgoing_addrs
);
1888 smartlist_add(outgoing_addrs
, ip
);
1889 /* Okay, now change our keys. */
1890 init_keys(); /* XXXX NM return value-- safe to ignore? */
1894 /** Process new bytes that have arrived on conn-\>inbuf.
1896 * This function just passes conn to the connection-specific
1897 * connection_*_process_inbuf() function. It also passes in
1898 * package_partial if wanted.
1901 connection_process_inbuf(connection_t
*conn
, int package_partial
)
1905 switch (conn
->type
) {
1907 return connection_or_process_inbuf(conn
);
1908 case CONN_TYPE_EXIT
:
1910 return connection_edge_process_inbuf(conn
, package_partial
);
1912 return connection_dir_process_inbuf(conn
);
1913 case CONN_TYPE_DNSWORKER
:
1914 return connection_dns_process_inbuf(conn
);
1915 case CONN_TYPE_CPUWORKER
:
1916 return connection_cpu_process_inbuf(conn
);
1917 case CONN_TYPE_CONTROL
:
1918 return connection_control_process_inbuf(conn
);
1920 log_err(LD_BUG
,"Bug: got unexpected conn type %d.", conn
->type
);
1921 tor_fragile_assert();
1926 /** We just finished flushing bytes from conn-\>outbuf, and there
1927 * are no more bytes remaining.
1929 * This function just passes conn to the connection-specific
1930 * connection_*_finished_flushing() function.
1933 connection_finished_flushing(connection_t
*conn
)
1937 // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
1939 switch (conn
->type
) {
1941 return connection_or_finished_flushing(conn
);
1943 case CONN_TYPE_EXIT
:
1944 return connection_edge_finished_flushing(conn
);
1946 return connection_dir_finished_flushing(conn
);
1947 case CONN_TYPE_DNSWORKER
:
1948 return connection_dns_finished_flushing(conn
);
1949 case CONN_TYPE_CPUWORKER
:
1950 return connection_cpu_finished_flushing(conn
);
1951 case CONN_TYPE_CONTROL
:
1952 return connection_control_finished_flushing(conn
);
1954 log_err(LD_BUG
,"Bug: got unexpected conn type %d.", conn
->type
);
1955 tor_fragile_assert();
1960 /** Called when our attempt to connect() to another server has just
1963 * This function just passes conn to the connection-specific
1964 * connection_*_finished_connecting() function.
1967 connection_finished_connecting(connection_t
*conn
)
1973 return connection_or_finished_connecting(conn
);
1974 case CONN_TYPE_EXIT
:
1975 return connection_edge_finished_connecting(conn
);
1977 return connection_dir_finished_connecting(conn
);
1979 log_err(LD_BUG
,"Bug: got unexpected conn type %d.", conn
->type
);
1980 tor_fragile_assert();
1985 /** Callback: invoked when a connection reaches an EOF event. */
1987 connection_reached_eof(connection_t
*conn
)
1989 switch (conn
->type
) {
1991 return connection_or_reached_eof(conn
);
1993 case CONN_TYPE_EXIT
:
1994 return connection_edge_reached_eof(conn
);
1996 return connection_dir_reached_eof(conn
);
1997 case CONN_TYPE_DNSWORKER
:
1998 return connection_dns_reached_eof(conn
);
1999 case CONN_TYPE_CPUWORKER
:
2000 return connection_cpu_reached_eof(conn
);
2001 case CONN_TYPE_CONTROL
:
2002 return connection_control_reached_eof(conn
);
2004 log_err(LD_BUG
,"Bug: got unexpected conn type %d.", conn
->type
);
2005 tor_fragile_assert();
2010 /** Verify that connection <b>conn</b> has all of its invariants
2011 * correct. Trigger an assert if anything is invalid.
2014 assert_connection_ok(connection_t
*conn
, time_t now
)
2017 tor_assert(conn
->magic
== CONNECTION_MAGIC
);
2018 tor_assert(conn
->type
>= _CONN_TYPE_MIN
);
2019 tor_assert(conn
->type
<= _CONN_TYPE_MAX
);
2021 if (conn
->outbuf_flushlen
> 0) {
2022 tor_assert(connection_is_writing(conn
) || conn
->wants_to_write
);
2025 if (conn
->hold_open_until_flushed
)
2026 tor_assert(conn
->marked_for_close
);
2028 /* XXX check: wants_to_read, wants_to_write, s, poll_index,
2029 * marked_for_close. */
2032 if (!connection_is_listener(conn
)) {
2033 assert_buf_ok(conn
->inbuf
);
2034 assert_buf_ok(conn
->outbuf
);
2037 /* XXX Fix this; no longer so.*/
2039 if (conn
->type
!= CONN_TYPE_OR
&& conn
->type
!= CONN_TYPE_DIR
)
2040 tor_assert(!conn
->pkey
);
2041 /* pkey is set if we're a dir client, or if we're an OR in state OPEN
2042 * connected to another OR.
2046 if (conn
->type
!= CONN_TYPE_OR
) {
2047 tor_assert(!conn
->tls
);
2049 if (conn
->state
== OR_CONN_STATE_OPEN
) {
2050 /* tor_assert(conn->bandwidth > 0); */
2051 /* the above isn't necessarily true: if we just did a TLS
2052 * handshake but we didn't recognize the other peer, or it
2053 * gave a bad cert/etc, then we won't have assigned bandwidth,
2054 * yet it will be open. -RD
2056 // tor_assert(conn->receiver_bucket >= 0);
2058 // tor_assert(conn->addr && conn->port);
2059 tor_assert(conn
->address
);
2060 if (conn
->state
> OR_CONN_STATE_PROXY_READING
)
2061 tor_assert(conn
->tls
);
2064 if (! CONN_IS_EDGE(conn
)) {
2065 tor_assert(!conn
->stream_id
);
2066 tor_assert(!conn
->next_stream
);
2067 tor_assert(!conn
->cpath_layer
);
2068 tor_assert(!conn
->package_window
);
2069 tor_assert(!conn
->deliver_window
);
2071 tor_assert(!conn
->done_sending
);
2072 tor_assert(!conn
->done_receiving
);
2075 /* XXX unchecked: package window, deliver window. */
2077 if (conn
->type
== CONN_TYPE_AP
) {
2078 tor_assert(conn
->socks_request
);
2079 if (conn
->state
== AP_CONN_STATE_OPEN
) {
2080 tor_assert(conn
->socks_request
->has_finished
);
2081 if (!conn
->marked_for_close
) {
2082 tor_assert(conn
->cpath_layer
);
2083 assert_cpath_layer_ok(conn
->cpath_layer
);
2087 tor_assert(!conn
->socks_request
);
2089 if (conn
->type
== CONN_TYPE_EXIT
) {
2090 tor_assert(conn
->purpose
== EXIT_PURPOSE_CONNECT
||
2091 conn
->purpose
== EXIT_PURPOSE_RESOLVE
);
2092 } else if (conn
->type
!= CONN_TYPE_DIR
) {
2093 tor_assert(!conn
->purpose
); /* only used for dir types currently */
2095 if (conn
->type
!= CONN_TYPE_DIR
) {
2096 tor_assert(!conn
->requested_resource
);
2101 case CONN_TYPE_OR_LISTENER
:
2102 case CONN_TYPE_AP_LISTENER
:
2103 case CONN_TYPE_DIR_LISTENER
:
2104 case CONN_TYPE_CONTROL_LISTENER
:
2105 tor_assert(conn
->state
== LISTENER_STATE_READY
);
2108 tor_assert(conn
->state
>= _OR_CONN_STATE_MIN
);
2109 tor_assert(conn
->state
<= _OR_CONN_STATE_MAX
);
2110 tor_assert(conn
->n_circuits
>= 0);
2112 case CONN_TYPE_EXIT
:
2113 tor_assert(conn
->state
>= _EXIT_CONN_STATE_MIN
);
2114 tor_assert(conn
->state
<= _EXIT_CONN_STATE_MAX
);
2117 tor_assert(conn
->state
>= _AP_CONN_STATE_MIN
);
2118 tor_assert(conn
->state
<= _AP_CONN_STATE_MAX
);
2119 tor_assert(conn
->socks_request
);
2122 tor_assert(conn
->state
>= _DIR_CONN_STATE_MIN
);
2123 tor_assert(conn
->state
<= _DIR_CONN_STATE_MAX
);
2124 tor_assert(conn
->purpose
>= _DIR_PURPOSE_MIN
);
2125 tor_assert(conn
->purpose
<= _DIR_PURPOSE_MAX
);
2127 case CONN_TYPE_DNSWORKER
:
2128 tor_assert(conn
->state
== DNSWORKER_STATE_IDLE
||
2129 conn
->state
== DNSWORKER_STATE_BUSY
);
2131 case CONN_TYPE_CPUWORKER
:
2132 tor_assert(conn
->state
>= _CPUWORKER_STATE_MIN
);
2133 tor_assert(conn
->state
<= _CPUWORKER_STATE_MAX
);
2135 case CONN_TYPE_CONTROL
:
2136 tor_assert(conn
->state
>= _CONTROL_CONN_STATE_MIN
);
2137 tor_assert(conn
->state
<= _CONTROL_CONN_STATE_MAX
);