1 /* Copyright 2001 Matej Pfajfar.
2 * Copyright 2001-2004 Roger Dingledine.
3 * Copyright 2004-2005 Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
6 const char connection_c_id
[] = "$Id$";
10 * \brief General high-level functions to handle reading and writing
16 /********* START VARIABLES **********/
18 /** Array of strings to make conn-\>type human-readable. */
19 const char *conn_type_to_string
[] = {
21 "OP listener", /* 1 */
23 "OR listener", /* 3 */
26 "App listener",/* 6 */
28 "Dir listener",/* 8 */
30 "DNS worker", /* 10 */
31 "CPU worker", /* 11 */
32 "Control listener", /* 12 */
36 /** Array of string arrays to make {conn-\>type,conn-\>state} human-readable. */
37 const char *conn_state_to_string
[][_CONN_TYPE_MAX
+1] = {
38 { NULL
}, /* no type associated with 0 */
39 { NULL
}, /* op listener, obsolete */
40 { NULL
}, /* op, obsolete */
41 { "ready" }, /* or listener, 0 */
43 "connect()ing", /* 1 */
44 "handshaking", /* 2 */
47 "waiting for dest info", /* 1 */
50 "resolve failed" }, /* 4 */
51 { "ready" }, /* app listener, 0 */
57 "awaiting dest info", /* app, 5 */
58 "waiting for rendezvous desc", /* 6 */
59 "waiting for controller", /* 7 */
60 "waiting for safe circuit", /* 8 */
61 "waiting for connected", /* 9 */
62 "waiting for resolve", /* 10 */
64 { "ready" }, /* dir listener, 0 */
67 "client sending", /* 2 */
68 "client reading", /* 3 */
69 "awaiting command", /* 4 */
71 { "", /* dns worker, 0 */
74 { "", /* cpu worker, 0 */
76 "busy with onion", /* 2 */
77 "busy with handshake" }, /* 3 */
78 { "ready" }, /* control listener, 0 */
79 { "", /* control, 0 */
81 "waiting for authentication", }, /* 2 */
84 /********* END VARIABLES ************/
86 static int connection_create_listener(const char *bindaddress
,
87 uint16_t bindport
, int type
);
88 static int connection_init_accepted_conn(connection_t
*conn
);
89 static int connection_handle_listener_read(connection_t
*conn
, int new_type
);
90 static int connection_receiver_bucket_should_increase(connection_t
*conn
);
91 static int connection_finished_flushing(connection_t
*conn
);
92 static int connection_finished_connecting(connection_t
*conn
);
93 static int connection_reached_eof(connection_t
*conn
);
94 static int connection_read_to_buf(connection_t
*conn
, int *max_to_read
);
95 static int connection_process_inbuf(connection_t
*conn
, int package_partial
);
96 static int connection_bucket_read_limit(connection_t
*conn
);
98 /**************************************************************/
100 /** Allocate space for a new connection_t. This function just initializes
101 * conn; you must call connection_add() to link it into the main array.
103 * Set conn-\>type to <b>type</b>. Set conn-\>s and conn-\>poll_index to
104 * -1 to signify they are not yet assigned.
106 * If conn is not a listener type, allocate buffers for it. If it's
107 * an AP type, allocate space to store the socks_request.
109 * Assign a pseudorandom next_circ_id between 0 and 2**15.
111 * Initialize conn's timestamps to now.
113 connection_t
*connection_new(int type
) {
114 static uint32_t n_connections_allocated
= 0;
116 time_t now
= time(NULL
);
118 conn
= tor_malloc_zero(sizeof(connection_t
));
119 conn
->magic
= CONNECTION_MAGIC
;
120 conn
->s
= -1; /* give it a default of 'not used' */
121 conn
->poll_index
= -1; /* also default to 'not used' */
122 conn
->global_identifier
= n_connections_allocated
++;
125 if (!connection_is_listener(conn
)) { /* listeners never use their buf */
126 conn
->inbuf
= buf_new();
127 conn
->outbuf
= buf_new();
129 if (type
== CONN_TYPE_AP
) {
130 conn
->socks_request
= tor_malloc_zero(sizeof(socks_request_t
));
133 conn
->next_circ_id
= crypto_pseudo_rand_int(1<<15);
135 conn
->timestamp_created
= now
;
136 conn
->timestamp_lastread
= now
;
137 conn
->timestamp_lastwritten
= now
;
142 /** Tell libevent that we don't care about <b>conn</b> any more. */
144 connection_unregister(connection_t
*conn
)
146 if (conn
->read_event
) {
147 if (event_del(conn
->read_event
))
148 log_fn(LOG_WARN
, "Error removing read event for %d", (int)conn
->s
);
149 tor_free(conn
->read_event
);
151 if (conn
->write_event
) {
152 if (event_del(conn
->write_event
))
153 log_fn(LOG_WARN
, "Error removing write event for %d", (int)conn
->s
);
154 tor_free(conn
->write_event
);
158 /** Deallocate memory used by <b>conn</b>. Deallocate its buffers if necessary,
159 * close its socket if necessary, and mark the directory as dirty if <b>conn</b>
160 * is an OR or OP connection.
163 _connection_free(connection_t
*conn
) {
164 tor_assert(conn
->magic
== CONNECTION_MAGIC
);
166 if (!connection_is_listener(conn
)) {
167 buf_free(conn
->inbuf
);
168 buf_free(conn
->outbuf
);
170 tor_free(conn
->address
);
171 tor_free(conn
->chosen_exit_name
);
173 if (connection_speaks_cells(conn
)) {
174 if (conn
->state
== OR_CONN_STATE_OPEN
)
175 directory_set_dirty();
177 tor_tls_free(conn
->tls
);
182 if (conn
->identity_pkey
)
183 crypto_free_pk_env(conn
->identity_pkey
);
184 tor_free(conn
->nickname
);
185 tor_free(conn
->socks_request
);
187 connection_unregister(conn
);
190 log_fn(LOG_INFO
,"closing fd %d.",conn
->s
);
191 tor_close_socket(conn
->s
);
194 memset(conn
, 0xAA, sizeof(connection_t
)); /* poison memory */
198 /** Make sure <b>conn</b> isn't in any of the global conn lists; then free it.
200 void connection_free(connection_t
*conn
) {
202 tor_assert(!connection_is_on_closeable_list(conn
));
203 tor_assert(!connection_in_array(conn
));
204 _connection_free(conn
);
207 /** Call _connection_free() on every connection in our array.
208 * This is used by cpuworkers and dnsworkers when they fork,
209 * so they don't keep resources held open (especially sockets).
211 * Don't do the checks in connection_free(), because they will
214 void connection_free_all(void) {
216 connection_t
**carray
;
218 get_connection_array(&carray
,&n
);
220 _connection_free(carray
[i
]);
223 /** Do any cleanup needed:
224 * - Directory conns that failed to fetch a rendezvous descriptor
225 * need to inform pending rendezvous streams.
226 * - OR conns need to call rep_hist_note_*() to record status.
227 * - AP conns need to send a socks reject if necessary.
228 * - Exit conns need to call connection_dns_remove() if necessary.
229 * - AP and Exit conns need to send an end cell if they can.
230 * - DNS conns need to fail any resolves that are pending on them.
232 void connection_about_to_close_connection(connection_t
*conn
)
236 assert(conn
->marked_for_close
);
238 if (CONN_IS_EDGE(conn
)) {
239 if (!conn
->has_sent_end
) {
240 log_fn(LOG_WARN
,"Harmless bug: Edge connection (marked at %s:%d) hasn't sent end yet?", conn
->marked_for_close_file
, conn
->marked_for_close
);
247 switch (conn
->type
) {
249 if (conn
->state
== DIR_CONN_STATE_CONNECTING
) {
250 /* it's a directory server and connecting failed: forget about
252 connection_dir_connect_failed(conn
);
254 if (conn
->purpose
== DIR_PURPOSE_FETCH_RENDDESC
)
255 rend_client_desc_here(conn
->rend_query
); /* give it a try */
258 /* Remember why we're closing this connection. */
259 if (conn
->state
!= OR_CONN_STATE_OPEN
) {
260 if (connection_or_nonopen_was_started_here(conn
)) {
261 rep_hist_note_connect_failed(conn
->identity_digest
, time(NULL
));
262 control_event_or_conn_status(conn
, OR_CONN_EVENT_FAILED
);
264 } else if (conn
->hold_open_until_flushed
) {
265 /* XXXX009 We used to have an arg that told us whether we closed the
266 * connection on purpose or not. Can we use hold_open_until_flushed
267 * instead? We only set it when we are intentionally closing a
270 * (Of course, now things we set to close which expire rather than
271 * flushing still get noted as dead, not disconnected. But this is an
274 rep_hist_note_disconnect(conn
->identity_digest
, time(NULL
));
275 control_event_or_conn_status(conn
, OR_CONN_EVENT_CLOSED
);
276 } else if (conn
->identity_digest
) {
277 rep_hist_note_connection_died(conn
->identity_digest
, time(NULL
));
278 control_event_or_conn_status(conn
, OR_CONN_EVENT_CLOSED
);
282 if (conn
->socks_request
->has_finished
== 0) {
283 /* since conn gets removed right after this function finishes,
284 * there's no point trying to send back a reply at this point. */
285 log_fn(LOG_WARN
,"Bug: Closing stream (marked at %s:%d) without sending back a socks reply.",
286 conn
->marked_for_close_file
, conn
->marked_for_close
);
288 control_event_stream_status(conn
, STREAM_EVENT_CLOSED
);
292 if (conn
->state
== EXIT_CONN_STATE_RESOLVING
) {
293 circ
= circuit_get_by_conn(conn
);
295 circuit_detach_stream(circ
, conn
);
296 connection_dns_remove(conn
);
299 case CONN_TYPE_DNSWORKER
:
300 if (conn
->state
== DNSWORKER_STATE_BUSY
) {
301 dns_cancel_pending_resolve(conn
->address
);
307 /** Close the underlying socket for <b>conn</b>, so we don't try to
308 * flush it. Must be used in conjunction with (right before)
309 * connection_mark_for_close().
311 void connection_close_immediate(connection_t
*conn
)
313 assert_connection_ok(conn
,0);
315 log_fn(LOG_WARN
,"Bug: Attempt to close already-closed connection.");
321 if (conn
->outbuf_flushlen
) {
322 log_fn(LOG_INFO
,"fd %d, type %s, state %d, %d bytes on outbuf.",
323 conn
->s
, CONN_TYPE_TO_STRING(conn
->type
),
324 conn
->state
, (int)conn
->outbuf_flushlen
);
327 connection_unregister(conn
);
329 tor_close_socket(conn
->s
);
331 if (!connection_is_listener(conn
)) {
332 buf_clear(conn
->outbuf
);
333 conn
->outbuf_flushlen
= 0;
337 /** Mark <b>conn</b> to be closed next time we loop through
338 * conn_close_if_marked() in main.c. */
340 _connection_mark_for_close(connection_t
*conn
, int line
, const char *file
)
342 assert_connection_ok(conn
,0);
346 if (conn
->marked_for_close
) {
347 log(LOG_WARN
, "Duplicate call to connection_mark_for_close at %s:%d"
348 " (first at %s:%d)", file
, line
, conn
->marked_for_close_file
,
349 conn
->marked_for_close
);
356 conn
->marked_for_close
= line
;
357 conn
->marked_for_close_file
= file
;
358 add_connection_to_closeable_list(conn
);
360 /* in case we're going to be held-open-til-flushed, reset
361 * the number of seconds since last successful write, so
362 * we get our whole 15 seconds */
363 conn
->timestamp_lastwritten
= time(NULL
);
366 /** Find each connection that has hold_open_until_flushed set to
367 * 1 but hasn't written in the past 15 seconds, and set
368 * hold_open_until_flushed to 0. This means it will get cleaned
369 * up in the next loop through close_if_marked() in main.c.
371 void connection_expire_held_open(void)
373 connection_t
**carray
, *conn
;
379 get_connection_array(&carray
, &n
);
380 for (i
= 0; i
< n
; ++i
) {
382 /* If we've been holding the connection open, but we haven't written
385 if (conn
->hold_open_until_flushed
) {
386 tor_assert(conn
->marked_for_close
);
387 if (now
- conn
->timestamp_lastwritten
>= 15) {
388 log_fn(LOG_NOTICE
,"Giving up on marked_for_close conn that's been flushing for 15s (fd %d, type %s, state %d).",
389 conn
->s
, CONN_TYPE_TO_STRING(conn
->type
), conn
->state
);
390 conn
->hold_open_until_flushed
= 0;
396 /** Bind a new non-blocking socket listening to
397 * <b>bindaddress</b>:<b>bindport</b>, and add this new connection
398 * (of type <b>type</b>) to the connection array.
400 * If <b>bindaddress</b> includes a port, we bind on that port; otherwise, we
403 static int connection_create_listener(const char *bindaddress
, uint16_t bindport
, int type
) {
404 struct sockaddr_in bindaddr
; /* where to bind */
408 int s
; /* the socket we're going to make */
413 memset(&bindaddr
,0,sizeof(struct sockaddr_in
));
414 if (parse_addr_port(bindaddress
, NULL
, &addr
, &usePort
)<0) {
415 log_fn(LOG_WARN
, "Error parsing/resolving BindAddress %s",bindaddress
);
421 bindaddr
.sin_addr
.s_addr
= htonl(addr
);
422 bindaddr
.sin_family
= AF_INET
;
423 bindaddr
.sin_port
= htons((uint16_t) usePort
);
425 s
= socket(PF_INET
,SOCK_STREAM
,IPPROTO_TCP
);
427 log_fn(LOG_WARN
,"Socket creation failed.");
429 } else if (!SOCKET_IS_POLLABLE(s
)) {
430 log_fn(LOG_WARN
,"Too many connections; can't create pollable listener.");
436 /* REUSEADDR on normal places means you can rebind to the port
437 * right after somebody else has let it go. But REUSEADDR on win32
438 * means to let you bind to the port _even when somebody else
439 * already has it bound_. So, don't do that on Win32. */
440 setsockopt(s
, SOL_SOCKET
, SO_REUSEADDR
, (void*) &one
, sizeof(one
));
443 if (bind(s
,(struct sockaddr
*)&bindaddr
,sizeof(bindaddr
)) < 0) {
444 log_fn(LOG_WARN
,"Could not bind to port %u: %s",usePort
,
445 tor_socket_strerror(tor_socket_errno(s
)));
449 if (listen(s
,SOMAXCONN
) < 0) {
450 log_fn(LOG_WARN
,"Could not listen on port %u: %s",usePort
,
451 tor_socket_strerror(tor_socket_errno(s
)));
455 set_socket_nonblocking(s
);
457 conn
= connection_new(type
);
460 if (connection_add(conn
) < 0) { /* no space, forget it */
461 log_fn(LOG_WARN
,"connection_add failed. Giving up.");
462 connection_free(conn
);
466 log_fn(LOG_DEBUG
,"%s listening on port %u.",conn_type_to_string
[type
], usePort
);
468 conn
->state
= LISTENER_STATE_READY
;
469 connection_start_reading(conn
);
474 /** The listener connection <b>conn</b> told poll() it wanted to read.
475 * Call accept() on conn-\>s, and add the new connection if necessary.
477 static int connection_handle_listener_read(connection_t
*conn
, int new_type
) {
478 int news
; /* the new socket */
479 connection_t
*newconn
;
480 /* information about the remote peer when connecting to other routers */
481 struct sockaddr_in remote
;
482 /* length of the remote address. Must be an int, since accept() needs that. */
483 int remotelen
= sizeof(struct sockaddr_in
);
484 char tmpbuf
[INET_NTOA_BUF_LEN
];
486 news
= accept(conn
->s
,(struct sockaddr
*)&remote
,&remotelen
);
487 if (!SOCKET_IS_POLLABLE(news
)) {
488 /* accept() error, or too many conns to poll */
491 /* Too many conns to poll. */
492 log_fn(LOG_WARN
,"Too many connections; couldn't accept connection.");
493 tor_close_socket(news
);
496 e
= tor_socket_errno(conn
->s
);
497 if (ERRNO_IS_ACCEPT_EAGAIN(e
)) {
498 return 0; /* he hung up before we could accept(). that's fine. */
499 } else if (ERRNO_IS_ACCEPT_RESOURCE_LIMIT(e
)) {
500 log_fn(LOG_NOTICE
,"accept failed: %s. Dropping incoming connection.",
501 tor_socket_strerror(e
));
504 /* else there was a real error. */
505 log_fn(LOG_WARN
,"accept() failed: %s. Closing listener.",
506 tor_socket_strerror(e
));
507 connection_mark_for_close(conn
);
510 log(LOG_INFO
,"Connection accepted on socket %d (child of fd %d).",news
, conn
->s
);
512 set_socket_nonblocking(news
);
514 /* process entrance policies here, before we even create the connection */
515 if (new_type
== CONN_TYPE_AP
) {
516 /* check sockspolicy to see if we should accept it */
517 if (socks_policy_permits_address(ntohl(remote
.sin_addr
.s_addr
)) == 0) {
518 tor_inet_ntoa(&remote
.sin_addr
, tmpbuf
, sizeof(tmpbuf
));
519 log_fn(LOG_NOTICE
,"Denying socks connection from untrusted address %s.",
521 tor_close_socket(news
);
525 if (new_type
== CONN_TYPE_DIR
) {
526 /* check dirpolicy to see if we should accept it */
527 if (dir_policy_permits_address(ntohl(remote
.sin_addr
.s_addr
)) == 0) {
528 tor_inet_ntoa(&remote
.sin_addr
, tmpbuf
, sizeof(tmpbuf
));
529 log_fn(LOG_NOTICE
,"Denying dir connection from address %s.",
531 tor_close_socket(news
);
536 newconn
= connection_new(new_type
);
539 /* remember the remote address */
540 newconn
->address
= tor_malloc(INET_NTOA_BUF_LEN
);
541 tor_inet_ntoa(&remote
.sin_addr
, newconn
->address
, INET_NTOA_BUF_LEN
);
543 newconn
->addr
= ntohl(remote
.sin_addr
.s_addr
);
544 newconn
->port
= ntohs(remote
.sin_port
);
546 if (connection_add(newconn
) < 0) { /* no space, forget it */
547 connection_free(newconn
);
548 return 0; /* no need to tear down the parent */
551 if (connection_init_accepted_conn(newconn
) < 0) {
552 connection_mark_for_close(newconn
);
558 /** Initialize states for newly accepted connection <b>conn</b>.
559 * If conn is an OR, start the tls handshake.
561 static int connection_init_accepted_conn(connection_t
*conn
) {
563 connection_start_reading(conn
);
565 switch (conn
->type
) {
567 return connection_tls_start_handshake(conn
, 1);
569 conn
->state
= AP_CONN_STATE_SOCKS_WAIT
;
572 conn
->purpose
= DIR_PURPOSE_SERVER
;
573 conn
->state
= DIR_CONN_STATE_SERVER_COMMAND_WAIT
;
575 case CONN_TYPE_CONTROL
:
576 conn
->state
= CONTROL_CONN_STATE_NEEDAUTH
;
582 /** Take conn, make a nonblocking socket; try to connect to
583 * addr:port (they arrive in *host order*). If fail, return -1. Else
584 * assign s to conn->\s: if connected return 1, if EAGAIN return 0.
586 * address is used to make the logs useful.
588 * On success, add conn to the list of polled connections.
590 int connection_connect(connection_t
*conn
, char *address
, uint32_t addr
, uint16_t port
) {
592 struct sockaddr_in dest_addr
;
593 or_options_t
*options
= get_options();
595 s
= socket(PF_INET
,SOCK_STREAM
,IPPROTO_TCP
);
597 log_fn(LOG_WARN
,"Error creating network socket: %s",
598 tor_socket_strerror(tor_socket_errno(-1)));
600 } else if (!SOCKET_IS_POLLABLE(s
)) {
602 "Too many connections; can't create pollable connection to %s", address
);
607 if (options
->OutboundBindAddress
) {
608 struct sockaddr_in ext_addr
;
610 memset(&ext_addr
, 0, sizeof(ext_addr
));
611 ext_addr
.sin_family
= AF_INET
;
612 ext_addr
.sin_port
= 0;
613 if (!tor_inet_aton(options
->OutboundBindAddress
, &ext_addr
.sin_addr
)) {
614 log_fn(LOG_WARN
,"Outbound bind address '%s' didn't parse. Ignoring.",
615 options
->OutboundBindAddress
);
617 if (bind(s
, (struct sockaddr
*)&ext_addr
, sizeof(ext_addr
)) < 0) {
618 log_fn(LOG_WARN
,"Error binding network socket: %s",
619 tor_socket_strerror(tor_socket_errno(s
)));
625 set_socket_nonblocking(s
);
627 memset(&dest_addr
,0,sizeof(dest_addr
));
628 dest_addr
.sin_family
= AF_INET
;
629 dest_addr
.sin_port
= htons(port
);
630 dest_addr
.sin_addr
.s_addr
= htonl(addr
);
632 log_fn(LOG_DEBUG
,"Connecting to %s:%u.",address
,port
);
634 if (connect(s
,(struct sockaddr
*)&dest_addr
,sizeof(dest_addr
)) < 0) {
635 int e
= tor_socket_errno(s
);
636 if (!ERRNO_IS_CONN_EINPROGRESS(e
)) {
638 log_fn(LOG_INFO
,"Connect() to %s:%u failed: %s",address
,port
,
639 tor_socket_strerror(e
));
643 /* it's in progress. set state appropriately and return. */
645 if (connection_add(conn
) < 0) /* no space, forget it */
647 log_fn(LOG_DEBUG
,"connect in progress, socket %d.",s
);
652 /* it succeeded. we're connected. */
653 log_fn(LOG_INFO
,"Connection to %s:%u established.",address
,port
);
655 if (connection_add(conn
) < 0) /* no space, forget it */
660 /** If there exist any listeners of type <b>type</b> in the connection
661 * array, mark them for close.
663 static void listener_close_if_present(int type
) {
665 connection_t
**carray
;
667 tor_assert(type
== CONN_TYPE_OR_LISTENER
||
668 type
== CONN_TYPE_AP_LISTENER
||
669 type
== CONN_TYPE_DIR_LISTENER
||
670 type
== CONN_TYPE_CONTROL_LISTENER
);
671 get_connection_array(&carray
,&n
);
674 if (conn
->type
== type
&& !conn
->marked_for_close
) {
675 connection_close_immediate(conn
);
676 connection_mark_for_close(conn
);
682 * Launch any configured listener connections of type <b>type</b>. (A
683 * listener is configured if <b>port_option</b> is non-zero. If any
684 * BindAddress configuration options are given in <b>cfg</b>, create a
685 * connection binding to each one. Otherwise, create a single
686 * connection binding to the address <b>default_addr</b>.)
688 * If <b>force</b> is true, close and re-open all listener connections.
689 * Otherwise, only relaunch the listeners of this type if the number of
690 * existing connections is not as configured (e.g., because one died).
692 static int retry_listeners(int type
, struct config_line_t
*cfg
,
693 int port_option
, const char *default_addr
,
697 int want
, have
, n_conn
, i
;
698 struct config_line_t
*c
;
700 connection_t
**carray
;
701 /* How many should there be? */
702 if (cfg
&& port_option
) {
704 for (c
= cfg
; c
; c
= c
->next
)
706 } else if (port_option
) {
712 /* How many are there actually? */
714 get_connection_array(&carray
,&n_conn
);
715 for (i
=0;i
<n_conn
;i
++) {
717 if (conn
->type
== type
&& !conn
->marked_for_close
)
721 /* If we have the right number of listeners, do nothing. */
725 /* Otherwise, warn the user and relaunch. */
726 log_fn(LOG_NOTICE
,"We have %d %s(s) open, but we want %d; relaunching.",
727 have
, conn_type_to_string
[type
], want
);
730 listener_close_if_present(type
);
733 if (connection_create_listener(default_addr
, (uint16_t) port_option
,
737 for ( ; cfg
; cfg
= cfg
->next
) {
738 if (connection_create_listener(cfg
->value
, (uint16_t) port_option
,
747 /** (Re)launch listeners for each port you should have open. If
748 * <b>force</b> is true, close and relaunch all listeners. If <b>force</b>
749 * is false, then only relaunch listeners when we have the wrong number of
750 * connections for a given type.
752 int retry_all_listeners(int force
) {
753 or_options_t
*options
= get_options();
755 if (retry_listeners(CONN_TYPE_OR_LISTENER
, options
->ORBindAddress
,
756 options
->ORPort
, "0.0.0.0", force
)<0)
758 if (retry_listeners(CONN_TYPE_DIR_LISTENER
, options
->DirBindAddress
,
759 options
->DirPort
, "0.0.0.0", force
)<0)
761 if (retry_listeners(CONN_TYPE_AP_LISTENER
, options
->SocksBindAddress
,
762 options
->SocksPort
, "127.0.0.1", force
)<0)
764 if (retry_listeners(CONN_TYPE_CONTROL_LISTENER
, NULL
,
765 options
->ControlPort
, "127.0.0.1", force
)<0)
771 extern int global_read_bucket
, global_write_bucket
;
773 /** How many bytes at most can we read onto this connection? */
774 static int connection_bucket_read_limit(connection_t
*conn
) {
777 /* do a rudimentary round-robin so one circuit can't hog a connection */
778 if (connection_speaks_cells(conn
)) {
779 at_most
= 32*(CELL_NETWORK_SIZE
);
781 at_most
= 32*(RELAY_PAYLOAD_SIZE
);
784 if (at_most
> global_read_bucket
)
785 at_most
= global_read_bucket
;
787 if (connection_speaks_cells(conn
) && conn
->state
== OR_CONN_STATE_OPEN
)
788 if (at_most
> conn
->receiver_bucket
)
789 at_most
= conn
->receiver_bucket
;
796 /** We just read num_read onto conn. Decrement buckets appropriately. */
797 static void connection_read_bucket_decrement(connection_t
*conn
, int num_read
) {
798 global_read_bucket
-= num_read
; //tor_assert(global_read_bucket >= 0);
799 if (connection_speaks_cells(conn
) && conn
->state
== OR_CONN_STATE_OPEN
) {
800 conn
->receiver_bucket
-= num_read
; //tor_assert(conn->receiver_bucket >= 0);
804 static void connection_consider_empty_buckets(connection_t
*conn
) {
805 if (global_read_bucket
<= 0) {
806 log_fn(LOG_DEBUG
,"global bucket exhausted. Pausing.");
807 conn
->wants_to_read
= 1;
808 connection_stop_reading(conn
);
811 if (connection_speaks_cells(conn
) &&
812 conn
->state
== OR_CONN_STATE_OPEN
&&
813 conn
->receiver_bucket
<= 0) {
814 log_fn(LOG_DEBUG
,"receiver bucket exhausted. Pausing.");
815 conn
->wants_to_read
= 1;
816 connection_stop_reading(conn
);
820 /** Initialize the global read bucket to options->BandwidthBurst,
821 * and current_time to the current time. */
822 void connection_bucket_init(void) {
823 or_options_t
*options
= get_options();
824 global_read_bucket
= (int)options
->BandwidthBurst
; /* start it at max traffic */
825 global_write_bucket
= (int)options
->BandwidthBurst
; /* start it at max traffic */
828 /** A second has rolled over; increment buckets appropriately. */
829 void connection_bucket_refill(struct timeval
*now
) {
832 connection_t
**carray
;
833 or_options_t
*options
= get_options();
835 /* refill the global buckets */
836 if (global_read_bucket
< (int)options
->BandwidthBurst
) {
837 global_read_bucket
+= (int)options
->BandwidthRate
;
838 log_fn(LOG_DEBUG
,"global_read_bucket now %d.", global_read_bucket
);
840 if (global_write_bucket
< (int)options
->BandwidthBurst
) {
841 global_write_bucket
+= (int)options
->BandwidthRate
;
842 log_fn(LOG_DEBUG
,"global_write_bucket now %d.", global_write_bucket
);
845 /* refill the per-connection buckets */
846 get_connection_array(&carray
,&n
);
850 if (connection_receiver_bucket_should_increase(conn
)) {
851 conn
->receiver_bucket
= conn
->bandwidth
;
852 //log_fn(LOG_DEBUG,"Receiver bucket %d now %d.", i, conn->receiver_bucket);
855 if (conn
->wants_to_read
== 1 /* it's marked to turn reading back on now */
856 && global_read_bucket
> 0 /* and we're allowed to read */
857 && global_write_bucket
> 0 /* and we're allowed to write (XXXX,
858 * not the best place to check this.) */
859 && (!connection_speaks_cells(conn
) ||
860 conn
->state
!= OR_CONN_STATE_OPEN
||
861 conn
->receiver_bucket
> 0)) {
862 /* and either a non-cell conn or a cell conn with non-empty bucket */
863 log_fn(LOG_DEBUG
,"waking up conn (fd %d)",conn
->s
);
864 conn
->wants_to_read
= 0;
865 connection_start_reading(conn
);
866 if (conn
->wants_to_write
== 1) {
867 conn
->wants_to_write
= 0;
868 connection_start_writing(conn
);
874 /** Is the receiver bucket for connection <b>conn</b> low enough that we
875 * should add another pile of tokens to it?
877 static int connection_receiver_bucket_should_increase(connection_t
*conn
) {
880 if (!connection_speaks_cells(conn
))
881 return 0; /* edge connections don't use receiver_buckets */
882 if (conn
->state
!= OR_CONN_STATE_OPEN
)
883 return 0; /* only open connections play the rate limiting game */
885 if (conn
->receiver_bucket
>= conn
->bandwidth
)
891 /** Read bytes from conn->\s and process them.
893 * This function gets called from conn_read() in main.c, either
894 * when poll() has declared that conn wants to read, or (for OR conns)
895 * when there are pending TLS bytes.
897 * It calls connection_read_to_buf() to bring in any new bytes,
898 * and then calls connection_process_inbuf() to process them.
900 * Mark the connection and return -1 if you want to close it, else
903 int connection_handle_read(connection_t
*conn
) {
904 int max_to_read
=-1, try_to_read
;
906 conn
->timestamp_lastread
= time(NULL
);
908 switch (conn
->type
) {
909 case CONN_TYPE_OR_LISTENER
:
910 return connection_handle_listener_read(conn
, CONN_TYPE_OR
);
911 case CONN_TYPE_AP_LISTENER
:
912 return connection_handle_listener_read(conn
, CONN_TYPE_AP
);
913 case CONN_TYPE_DIR_LISTENER
:
914 return connection_handle_listener_read(conn
, CONN_TYPE_DIR
);
915 case CONN_TYPE_CONTROL_LISTENER
:
916 return connection_handle_listener_read(conn
, CONN_TYPE_CONTROL
);
920 try_to_read
= max_to_read
;
921 tor_assert(!conn
->marked_for_close
);
922 if (connection_read_to_buf(conn
, &max_to_read
) < 0) {
923 /* There's a read error; kill the connection.*/
924 connection_close_immediate(conn
); /* Don't flush; connection is dead. */
925 if (CONN_IS_EDGE(conn
)) {
926 connection_edge_end_errno(conn
, conn
->cpath_layer
);
928 connection_mark_for_close(conn
);
931 if (CONN_IS_EDGE(conn
) &&
932 try_to_read
!= max_to_read
) {
933 /* instruct it not to try to package partial cells. */
934 if (connection_process_inbuf(conn
, 0) < 0) {
937 if (!conn
->marked_for_close
&&
938 connection_is_reading(conn
) &&
939 !conn
->inbuf_reached_eof
&&
941 goto loop_again
; /* try reading again, in case more is here now */
943 /* one last try, packaging partial cells and all. */
944 if (!conn
->marked_for_close
&&
945 connection_process_inbuf(conn
, 1) < 0) {
948 if (!conn
->marked_for_close
&&
949 conn
->inbuf_reached_eof
&&
950 connection_reached_eof(conn
) < 0) {
956 /** Pull in new bytes from conn-\>s onto conn-\>inbuf, either
957 * directly or via TLS. Reduce the token buckets by the number of
960 * If *max_to_read is -1, then decide it ourselves, else go with the
961 * value passed to us. When returning, if it's changed, subtract the
962 * number of bytes we read from *max_to_read.
964 * Return -1 if we want to break conn, else return 0.
966 static int connection_read_to_buf(connection_t
*conn
, int *max_to_read
) {
967 int result
, at_most
= *max_to_read
;
969 if (at_most
== -1) { /* we need to initialize it */
970 /* how many bytes are we allowed to read? */
971 at_most
= connection_bucket_read_limit(conn
);
974 if (connection_speaks_cells(conn
) && conn
->state
> OR_CONN_STATE_PROXY_READING
) {
976 if (conn
->state
== OR_CONN_STATE_HANDSHAKING
) {
977 /* continue handshaking even if global token bucket is empty */
978 return connection_tls_continue_handshake(conn
);
981 log_fn(LOG_DEBUG
,"%d: starting, inbuf_datalen %d (%d pending in tls object). at_most %d.",
982 conn
->s
,(int)buf_datalen(conn
->inbuf
),tor_tls_get_pending_bytes(conn
->tls
), at_most
);
984 /* else open, or closing */
985 result
= read_to_buf_tls(conn
->tls
, at_most
, conn
->inbuf
);
989 log_fn(LOG_INFO
,"TLS connection closed on read. Closing. (Nickname %s, address %s",
990 conn
->nickname
? conn
->nickname
: "not set", conn
->address
);
993 log_fn(LOG_INFO
,"tls error. breaking (nickname %s, address %s).",
994 conn
->nickname
? conn
->nickname
: "not set", conn
->address
);
996 case TOR_TLS_WANTWRITE
:
997 connection_start_writing(conn
);
999 case TOR_TLS_WANTREAD
: /* we're already reading */
1000 case TOR_TLS_DONE
: /* no data read, so nothing to process */
1002 break; /* so we call bucket_decrement below */
1006 pending
= tor_tls_get_pending_bytes(conn
->tls
);
1008 /* XXXX If we have any pending bytes, read them now. This *can*
1009 * take us over our read alotment, but really we shouldn't be
1010 * believing that SSL bytes are the same as TCP bytes anyway. */
1011 int r2
= read_to_buf_tls(conn
->tls
, pending
, conn
->inbuf
);
1013 log_fn(LOG_WARN
, "Bug: apparently, reading pending bytes can fail.");
1021 result
= read_to_buf(conn
->s
, at_most
, conn
->inbuf
,
1022 &conn
->inbuf_reached_eof
);
1024 // log_fn(LOG_DEBUG,"read_to_buf returned %d.",read_result);
1030 if (result
> 0) { /* change *max_to_read */
1031 *max_to_read
= at_most
- result
;
1034 if (result
> 0 && !is_local_IP(conn
->addr
)) { /* remember it */
1035 rep_hist_note_bytes_read(result
, time(NULL
));
1036 connection_read_bucket_decrement(conn
, result
);
1039 /* Call even if result is 0, since the global read bucket may
1040 * have reached 0 on a different conn, and this guy needs to
1041 * know to stop reading. */
1042 connection_consider_empty_buckets(conn
);
1047 /** A pass-through to fetch_from_buf. */
1048 int connection_fetch_from_buf(char *string
, size_t len
, connection_t
*conn
) {
1049 return fetch_from_buf(string
, len
, conn
->inbuf
);
1052 /** Return conn-\>outbuf_flushlen: how many bytes conn wants to flush
1053 * from its outbuf. */
1054 int connection_wants_to_flush(connection_t
*conn
) {
1055 return conn
->outbuf_flushlen
;
1058 /** Are there too many bytes on edge connection <b>conn</b>'s outbuf to
1059 * send back a relay-level sendme yet? Return 1 if so, 0 if not. Used by
1060 * connection_edge_consider_sending_sendme().
1062 int connection_outbuf_too_full(connection_t
*conn
) {
1063 return (conn
->outbuf_flushlen
> 10*CELL_PAYLOAD_SIZE
);
1066 /** Try to flush more bytes onto conn-\>s.
1068 * This function gets called either from conn_write() in main.c
1069 * when poll() has declared that conn wants to write, or below
1070 * from connection_write_to_buf() when an entire TLS record is ready.
1072 * Update conn-\>timestamp_lastwritten to now, and call flush_buf
1073 * or flush_buf_tls appropriately. If it succeeds and there no more
1074 * more bytes on conn->outbuf, then call connection_finished_flushing
1077 * Mark the connection and return -1 if you want to close it, else
1080 int connection_handle_write(connection_t
*conn
) {
1081 int e
, len
=sizeof(e
);
1083 time_t now
= time(NULL
);
1085 tor_assert(!connection_is_listener(conn
));
1087 conn
->timestamp_lastwritten
= now
;
1089 /* Sometimes, "writable" means "connected". */
1090 if (connection_state_is_connecting(conn
)) {
1091 if (getsockopt(conn
->s
, SOL_SOCKET
, SO_ERROR
, (void*)&e
, &len
) < 0) {
1092 log_fn(LOG_WARN
,"getsockopt() syscall failed?! Please report to tor-ops.");
1093 if (CONN_IS_EDGE(conn
))
1094 connection_edge_end_errno(conn
, conn
->cpath_layer
);
1095 connection_mark_for_close(conn
);
1099 /* some sort of error, but maybe just inprogress still */
1100 if (!ERRNO_IS_CONN_EINPROGRESS(e
)) {
1101 log_fn(LOG_INFO
,"in-progress connect failed. Removing.");
1102 if (CONN_IS_EDGE(conn
))
1103 connection_edge_end_errno(conn
, conn
->cpath_layer
);
1105 connection_close_immediate(conn
);
1106 connection_mark_for_close(conn
);
1107 /* it's safe to pass OPs to router_mark_as_down(), since it just
1108 * ignores unrecognized routers
1110 if (conn
->type
== CONN_TYPE_OR
&& !get_options()->HttpsProxy
)
1111 router_mark_as_down(conn
->identity_digest
);
1114 return 0; /* no change, see if next time is better */
1117 /* The connection is successful. */
1118 if (connection_finished_connecting(conn
)<0)
1122 if (connection_speaks_cells(conn
) && conn
->state
> OR_CONN_STATE_PROXY_READING
) {
1123 if (conn
->state
== OR_CONN_STATE_HANDSHAKING
) {
1124 connection_stop_writing(conn
);
1125 if (connection_tls_continue_handshake(conn
) < 0) {
1126 connection_close_immediate(conn
); /* Don't flush; connection is dead. */
1127 connection_mark_for_close(conn
);
1133 /* else open, or closing */
1134 result
= flush_buf_tls(conn
->tls
, conn
->outbuf
, &conn
->outbuf_flushlen
);
1138 log_fn(LOG_INFO
,result
==TOR_TLS_ERROR
?
1139 "tls error. breaking.":"TLS connection closed on flush");
1140 connection_close_immediate(conn
); /* Don't flush; connection is dead. */
1141 connection_mark_for_close(conn
);
1143 case TOR_TLS_WANTWRITE
:
1144 log_fn(LOG_DEBUG
,"wanted write.");
1145 /* we're already writing */
1147 case TOR_TLS_WANTREAD
:
1148 /* Make sure to avoid a loop if the receive buckets are empty. */
1149 log_fn(LOG_DEBUG
,"wanted read.");
1150 if (!connection_is_reading(conn
)) {
1151 connection_stop_writing(conn
);
1152 conn
->wants_to_write
= 1;
1153 /* we'll start reading again when the next second arrives,
1154 * and then also start writing again.
1157 /* else no problem, we're already reading */
1159 /* case TOR_TLS_DONE:
1160 * for TOR_TLS_DONE, fall through to check if the flushlen
1161 * is empty, so we can stop writing.
1165 result
= flush_buf(conn
->s
, conn
->outbuf
, &conn
->outbuf_flushlen
);
1167 if (CONN_IS_EDGE(conn
))
1168 connection_edge_end_errno(conn
, conn
->cpath_layer
);
1170 connection_close_immediate(conn
); /* Don't flush; connection is dead. */
1171 connection_mark_for_close(conn
);
1176 if (result
> 0 && !is_local_IP(conn
->addr
)) { /* remember it */
1177 rep_hist_note_bytes_written(result
, now
);
1178 global_write_bucket
-= result
;
1181 if (!connection_wants_to_flush(conn
)) { /* it's done flushing */
1182 if (connection_finished_flushing(conn
) < 0) {
1183 /* already marked */
1191 /** Append <b>len</b> bytes of <b>string</b> onto <b>conn</b>'s
1192 * outbuf, and ask it to start writing.
1194 void connection_write_to_buf(const char *string
, size_t len
, connection_t
*conn
) {
1198 /* if it's marked for close, only allow write if we mean to flush it */
1199 if (conn
->marked_for_close
&& !conn
->hold_open_until_flushed
)
1202 if (write_to_buf(string
, len
, conn
->outbuf
) < 0) {
1203 if (CONN_IS_EDGE(conn
)) {
1204 /* if it failed, it means we have our package/delivery windows set
1205 wrong compared to our max outbuf size. close the whole circuit. */
1206 log_fn(LOG_WARN
,"write_to_buf failed. Closing circuit (fd %d).", conn
->s
);
1207 circuit_mark_for_close(circuit_get_by_conn(conn
));
1209 log_fn(LOG_WARN
,"write_to_buf failed. Closing connection (fd %d).", conn
->s
);
1210 connection_mark_for_close(conn
);
1215 connection_start_writing(conn
);
1216 conn
->outbuf_flushlen
+= len
;
1219 /** Return the conn to addr/port that has the most recent
1220 * timestamp_created, or NULL if no such conn exists. */
1221 connection_t
*connection_exact_get_by_addr_port(uint32_t addr
, uint16_t port
) {
1223 connection_t
*conn
, *best
=NULL
;
1224 connection_t
**carray
;
1226 get_connection_array(&carray
,&n
);
1229 if (conn
->addr
== addr
&& conn
->port
== port
&& !conn
->marked_for_close
&&
1230 (!best
|| best
->timestamp_created
< conn
->timestamp_created
))
1236 connection_t
*connection_get_by_identity_digest(const char *digest
, int type
)
1239 connection_t
*conn
, *best
=NULL
;
1240 connection_t
**carray
;
1242 get_connection_array(&carray
,&n
);
1245 if (conn
->type
!= type
)
1247 if (!memcmp(conn
->identity_digest
, digest
, DIGEST_LEN
) &&
1248 !conn
->marked_for_close
&&
1249 (!best
|| best
->timestamp_created
< conn
->timestamp_created
))
1255 /** Return the connection with id <b>id</b> if it is not already
1259 connection_get_by_global_id(uint32_t id
) {
1262 connection_t
**carray
;
1264 get_connection_array(&carray
,&n
);
1267 if (conn
->global_identifier
== id
) {
1268 if (!conn
->marked_for_close
)
1277 /** Return a connection of type <b>type</b> that is not marked for
1280 connection_t
*connection_get_by_type(int type
) {
1283 connection_t
**carray
;
1285 get_connection_array(&carray
,&n
);
1288 if (conn
->type
== type
&& !conn
->marked_for_close
)
1294 /** Return a connection of type <b>type</b> that is in state <b>state</b>,
1295 * and that is not marked for close.
1297 connection_t
*connection_get_by_type_state(int type
, int state
) {
1300 connection_t
**carray
;
1302 get_connection_array(&carray
,&n
);
1305 if (conn
->type
== type
&& conn
->state
== state
&& !conn
->marked_for_close
)
1311 /** Return a connection of type <b>type</b> that has purpose <b>purpose</b>,
1312 * and that is not marked for close.
1314 connection_t
*connection_get_by_type_purpose(int type
, int purpose
) {
1317 connection_t
**carray
;
1319 get_connection_array(&carray
,&n
);
1322 if (conn
->type
== type
&& conn
->purpose
== purpose
&& !conn
->marked_for_close
)
1328 /** Return the connection of type <b>type</b> that is in state
1329 * <b>state</b>, that was written to least recently, and that is not
1332 connection_t
*connection_get_by_type_state_lastwritten(int type
, int state
) {
1334 connection_t
*conn
, *best
=NULL
;
1335 connection_t
**carray
;
1337 get_connection_array(&carray
,&n
);
1340 if (conn
->type
== type
&& conn
->state
== state
&& !conn
->marked_for_close
)
1341 if (!best
|| conn
->timestamp_lastwritten
< best
->timestamp_lastwritten
)
1347 /** Return a connection of type <b>type</b> that has rendquery equal
1348 * to <b>rendquery</b>, and that is not marked for close. If state
1349 * is non-zero, conn must be of that state too.
1352 connection_get_by_type_state_rendquery(int type
, int state
, const char *rendquery
) {
1355 connection_t
**carray
;
1357 get_connection_array(&carray
,&n
);
1360 if (conn
->type
== type
&&
1361 !conn
->marked_for_close
&&
1362 (!state
|| state
== conn
->state
) &&
1363 !rend_cmp_service_ids(rendquery
, conn
->rend_query
))
1369 /** Return 1 if <b>conn</b> is a listener conn, else return 0. */
1370 int connection_is_listener(connection_t
*conn
) {
1371 if (conn
->type
== CONN_TYPE_OR_LISTENER
||
1372 conn
->type
== CONN_TYPE_AP_LISTENER
||
1373 conn
->type
== CONN_TYPE_DIR_LISTENER
||
1374 conn
->type
== CONN_TYPE_CONTROL_LISTENER
)
1379 /** Return 1 if <b>conn</b> is in state "open" and is not marked
1380 * for close, else return 0.
1382 int connection_state_is_open(connection_t
*conn
) {
1385 if (conn
->marked_for_close
)
1388 if ((conn
->type
== CONN_TYPE_OR
&& conn
->state
== OR_CONN_STATE_OPEN
) ||
1389 (conn
->type
== CONN_TYPE_AP
&& conn
->state
== AP_CONN_STATE_OPEN
) ||
1390 (conn
->type
== CONN_TYPE_EXIT
&& conn
->state
== EXIT_CONN_STATE_OPEN
) ||
1391 (conn
->type
== CONN_TYPE_CONTROL
&& conn
->state
==CONTROL_CONN_STATE_OPEN
))
1397 /** Return 1 if conn is in 'connecting' state, else return 0. */
1398 int connection_state_is_connecting(connection_t
*conn
) {
1401 if (conn
->marked_for_close
)
1406 return conn
->state
== OR_CONN_STATE_CONNECTING
;
1407 case CONN_TYPE_EXIT
:
1408 return conn
->state
== EXIT_CONN_STATE_CONNECTING
;
1410 return conn
->state
== DIR_CONN_STATE_CONNECTING
;
1416 /** Write a destroy cell with circ ID <b>circ_id</b> onto OR connection
1421 int connection_send_destroy(uint16_t circ_id
, connection_t
*conn
) {
1425 tor_assert(connection_speaks_cells(conn
));
1427 memset(&cell
, 0, sizeof(cell_t
));
1428 cell
.circ_id
= circ_id
;
1429 cell
.command
= CELL_DESTROY
;
1430 log_fn(LOG_INFO
,"Sending destroy (circID %d).", circ_id
);
1431 connection_or_write_cell_to_buf(&cell
, conn
);
1435 /** Process new bytes that have arrived on conn-\>inbuf.
1437 * This function just passes conn to the connection-specific
1438 * connection_*_process_inbuf() function. It also passes in
1439 * package_partial if wanted.
1441 static int connection_process_inbuf(connection_t
*conn
, int package_partial
) {
1445 switch (conn
->type
) {
1447 return connection_or_process_inbuf(conn
);
1448 case CONN_TYPE_EXIT
:
1450 return connection_edge_process_inbuf(conn
, package_partial
);
1452 return connection_dir_process_inbuf(conn
);
1453 case CONN_TYPE_DNSWORKER
:
1454 return connection_dns_process_inbuf(conn
);
1455 case CONN_TYPE_CPUWORKER
:
1456 return connection_cpu_process_inbuf(conn
);
1457 case CONN_TYPE_CONTROL
:
1458 return connection_control_process_inbuf(conn
);
1460 log_fn(LOG_WARN
,"Bug: got unexpected conn type %d.", conn
->type
);
1468 /** We just finished flushing bytes from conn-\>outbuf, and there
1469 * are no more bytes remaining.
1471 * This function just passes conn to the connection-specific
1472 * connection_*_finished_flushing() function.
1474 static int connection_finished_flushing(connection_t
*conn
) {
1478 // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
1480 switch (conn
->type
) {
1482 return connection_or_finished_flushing(conn
);
1484 case CONN_TYPE_EXIT
:
1485 return connection_edge_finished_flushing(conn
);
1487 return connection_dir_finished_flushing(conn
);
1488 case CONN_TYPE_DNSWORKER
:
1489 return connection_dns_finished_flushing(conn
);
1490 case CONN_TYPE_CPUWORKER
:
1491 return connection_cpu_finished_flushing(conn
);
1492 case CONN_TYPE_CONTROL
:
1493 return connection_control_finished_flushing(conn
);
1495 log_fn(LOG_WARN
,"Bug: got unexpected conn type %d.", conn
->type
);
1503 /** Called when our attempt to connect() to another server has just
1506 * This function just passes conn to the connection-specific
1507 * connection_*_finished_connecting() function.
1509 static int connection_finished_connecting(connection_t
*conn
)
1515 return connection_or_finished_connecting(conn
);
1516 case CONN_TYPE_EXIT
:
1517 return connection_edge_finished_connecting(conn
);
1519 return connection_dir_finished_connecting(conn
);
1521 log_fn(LOG_WARN
,"Bug: got unexpected conn type %d.", conn
->type
);
1529 static int connection_reached_eof(connection_t
*conn
)
1531 switch (conn
->type
) {
1533 return connection_or_reached_eof(conn
);
1535 case CONN_TYPE_EXIT
:
1536 return connection_edge_reached_eof(conn
);
1538 return connection_dir_reached_eof(conn
);
1539 case CONN_TYPE_DNSWORKER
:
1540 return connection_dns_reached_eof(conn
);
1541 case CONN_TYPE_CPUWORKER
:
1542 return connection_cpu_reached_eof(conn
);
1543 case CONN_TYPE_CONTROL
:
1544 return connection_control_reached_eof(conn
);
1546 log_fn(LOG_WARN
,"Bug: got unexpected conn type %d.", conn
->type
);
1554 /** Verify that connection <b>conn</b> has all of its invariants
1555 * correct. Trigger an assert if anything is invalid.
1557 void assert_connection_ok(connection_t
*conn
, time_t now
)
1560 tor_assert(conn
->magic
== CONNECTION_MAGIC
);
1561 tor_assert(conn
->type
>= _CONN_TYPE_MIN
);
1562 tor_assert(conn
->type
<= _CONN_TYPE_MAX
);
1564 if (conn
->outbuf_flushlen
> 0) {
1565 tor_assert(connection_is_writing(conn
) || conn
->wants_to_write
);
1568 if (conn
->hold_open_until_flushed
)
1569 tor_assert(conn
->marked_for_close
);
1571 /* XXX check: wants_to_read, wants_to_write, s, poll_index,
1572 * marked_for_close. */
1575 if (!connection_is_listener(conn
)) {
1576 assert_buf_ok(conn
->inbuf
);
1577 assert_buf_ok(conn
->outbuf
);
1580 #if 0 /* computers often go back in time; no way to know */
1581 tor_assert(!now
|| conn
->timestamp_lastread
<= now
);
1582 tor_assert(!now
|| conn
->timestamp_lastwritten
<= now
);
1583 tor_assert(conn
->timestamp_created
<= conn
->timestamp_lastread
);
1584 tor_assert(conn
->timestamp_created
<= conn
->timestamp_lastwritten
);
1587 /* XXX Fix this; no longer so.*/
1589 if (conn
->type
!= CONN_TYPE_OR
&& conn
->type
!= CONN_TYPE_DIR
)
1590 tor_assert(!conn
->pkey
);
1591 /* pkey is set if we're a dir client, or if we're an OR in state OPEN
1592 * connected to another OR.
1596 if (conn
->type
!= CONN_TYPE_OR
) {
1597 tor_assert(!conn
->tls
);
1599 if (conn
->state
== OR_CONN_STATE_OPEN
) {
1600 /* tor_assert(conn->bandwidth > 0); */
1601 /* the above isn't necessarily true: if we just did a TLS
1602 * handshake but we didn't recognize the other peer, or it
1603 * gave a bad cert/etc, then we won't have assigned bandwidth,
1604 * yet it will be open. -RD
1606 // tor_assert(conn->receiver_bucket >= 0);
1608 // tor_assert(conn->addr && conn->port);
1609 tor_assert(conn
->address
);
1610 if (conn
->state
> OR_CONN_STATE_PROXY_READING
)
1611 tor_assert(conn
->tls
);
1614 if (! CONN_IS_EDGE(conn
)) {
1615 tor_assert(!conn
->stream_id
);
1616 tor_assert(!conn
->next_stream
);
1617 tor_assert(!conn
->cpath_layer
);
1618 tor_assert(!conn
->package_window
);
1619 tor_assert(!conn
->deliver_window
);
1620 tor_assert(!conn
->done_sending
);
1621 tor_assert(!conn
->done_receiving
);
1623 /* XXX unchecked: package window, deliver window. */
1625 if (conn
->type
== CONN_TYPE_AP
) {
1626 tor_assert(conn
->socks_request
);
1627 if (conn
->state
== AP_CONN_STATE_OPEN
) {
1628 tor_assert(conn
->socks_request
->has_finished
);
1629 if (!conn
->marked_for_close
) {
1630 tor_assert(conn
->cpath_layer
);
1631 assert_cpath_layer_ok(conn
->cpath_layer
);
1635 tor_assert(!conn
->socks_request
);
1637 if (conn
->type
== CONN_TYPE_EXIT
) {
1638 tor_assert(conn
->purpose
== EXIT_PURPOSE_CONNECT
||
1639 conn
->purpose
== EXIT_PURPOSE_RESOLVE
);
1640 } else if (conn
->type
!= CONN_TYPE_DIR
) {
1641 tor_assert(!conn
->purpose
); /* only used for dir types currently */
1646 case CONN_TYPE_OR_LISTENER
:
1647 case CONN_TYPE_AP_LISTENER
:
1648 case CONN_TYPE_DIR_LISTENER
:
1649 case CONN_TYPE_CONTROL_LISTENER
:
1650 tor_assert(conn
->state
== LISTENER_STATE_READY
);
1653 tor_assert(conn
->state
>= _OR_CONN_STATE_MIN
);
1654 tor_assert(conn
->state
<= _OR_CONN_STATE_MAX
);
1656 case CONN_TYPE_EXIT
:
1657 tor_assert(conn
->state
>= _EXIT_CONN_STATE_MIN
);
1658 tor_assert(conn
->state
<= _EXIT_CONN_STATE_MAX
);
1661 tor_assert(conn
->state
>= _AP_CONN_STATE_MIN
);
1662 tor_assert(conn
->state
<= _AP_CONN_STATE_MAX
);
1663 tor_assert(conn
->socks_request
);
1666 tor_assert(conn
->state
>= _DIR_CONN_STATE_MIN
);
1667 tor_assert(conn
->state
<= _DIR_CONN_STATE_MAX
);
1668 tor_assert(conn
->purpose
>= _DIR_PURPOSE_MIN
);
1669 tor_assert(conn
->purpose
<= _DIR_PURPOSE_MAX
);
1671 case CONN_TYPE_DNSWORKER
:
1672 tor_assert(conn
->state
== DNSWORKER_STATE_IDLE
||
1673 conn
->state
== DNSWORKER_STATE_BUSY
);
1675 case CONN_TYPE_CPUWORKER
:
1676 tor_assert(conn
->state
>= _CPUWORKER_STATE_MIN
);
1677 tor_assert(conn
->state
<= _CPUWORKER_STATE_MAX
);
1679 case CONN_TYPE_CONTROL
:
1680 tor_assert(conn
->state
>= _CONTROL_CONN_STATE_MIN
);
1681 tor_assert(conn
->state
<= _CONTROL_CONN_STATE_MAX
);