Reformat inconsistent function declarations.
[tor.git] / src / or / connection.c
blob85449b43a401333af191a61f53249673b5d7eec3
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 */
5 /* $Id$ */
6 const char connection_c_id[] = "$Id$";
8 /**
9 * \file connection.c
10 * \brief General high-level functions to handle reading and writing
11 * on connections.
12 **/
14 #include "or.h"
16 static connection_t *connection_create_listener(const char *bindaddress,
17 uint16_t bindport, int type);
18 static int connection_init_accepted_conn(connection_t *conn);
19 static int connection_handle_listener_read(connection_t *conn, int new_type);
20 static int connection_receiver_bucket_should_increase(connection_t *conn);
21 static int connection_finished_flushing(connection_t *conn);
22 static int connection_finished_connecting(connection_t *conn);
23 static int connection_reached_eof(connection_t *conn);
24 static int connection_read_to_buf(connection_t *conn, int *max_to_read);
25 static int connection_process_inbuf(connection_t *conn, int package_partial);
26 static int connection_bucket_read_limit(connection_t *conn);
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 /**************************************************************/
34 /**
35 * Return the human-readable name for the connection type <b>type</b>
37 const char *
38 conn_type_to_string(int type)
40 static char buf[64];
41 switch (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";
53 default:
54 log_fn(LOG_WARN, "Bug: unknown connection type %d", type);
55 tor_snprintf(buf, sizeof(buf), "unknown [%d]", type);
56 return buf;
60 /**
61 * Return the human-readable name for the connection state <b>state</b>
62 * for the connection type <b>type</b>
64 const char *
65 conn_state_to_string(int type, int state)
67 static char buf[96];
68 switch (type) {
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)
74 return "ready";
75 break;
76 case CONN_TYPE_OR:
77 switch (state) {
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 "proxy reading";
82 case OR_CONN_STATE_OPEN: return "open";
84 break;
85 case CONN_TYPE_EXIT:
86 switch (state) {
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";
92 break;
93 case CONN_TYPE_AP:
94 switch (state) {
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";
103 break;
104 case CONN_TYPE_DIR:
105 switch (state) {
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 "cleint reading";
109 case DIR_CONN_STATE_SERVER_COMMAND_WAIT: return "waiting for command";
110 case DIR_CONN_STATE_SERVER_WRITING: return "writing";
112 break;
113 case CONN_TYPE_DNSWORKER:
114 switch (state) {
115 case DNSWORKER_STATE_IDLE: return "idle";
116 case DNSWORKER_STATE_BUSY: return "busy";
118 break;
119 case CONN_TYPE_CPUWORKER:
120 switch (state) {
121 case CPUWORKER_STATE_IDLE: return "idle";
122 case CPUWORKER_STATE_BUSY_ONION: return "busy with onion";
124 break;
125 case CONN_TYPE_CONTROL:
126 switch (state) {
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)";
134 break;
137 log_fn(LOG_WARN, "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));
141 return buf;
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.
157 connection_t *
158 connection_new(int type)
160 static uint32_t n_connections_allocated = 0;
161 connection_t *conn;
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++;
170 conn->type = type;
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_pseudo_rand_int(1<<15);
181 conn->timestamp_created = now;
182 conn->timestamp_lastread = now;
183 conn->timestamp_lastwritten = now;
185 return conn;
188 /** Tell libevent that we don't care about <b>conn</b> any more. */
189 void
190 connection_unregister(connection_t *conn)
192 if (conn->read_event) {
193 if (event_del(conn->read_event))
194 log_fn(LOG_WARN, "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_fn(LOG_WARN, "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 necessary,
205 * close its socket if necessary, and mark the directory as dirty if <b>conn</b>
206 * is an OR or OP connection.
208 static void
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)) {
221 if (conn->tls) {
222 tor_tls_free(conn->tls);
223 conn->tls = NULL;
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);
236 if (conn->s >= 0) {
237 log_fn(LOG_INFO,"closing fd %d.",conn->s);
238 tor_close_socket(conn->s);
241 memset(conn, 0xAA, sizeof(connection_t)); /* poison memory */
242 tor_free(conn);
245 /** Make sure <b>conn</b> isn't in any of the global conn lists; then free it.
247 void
248 connection_free(connection_t *conn)
250 tor_assert(conn);
251 tor_assert(!connection_is_on_closeable_list(conn));
252 tor_assert(!connection_in_array(conn));
253 if (connection_speaks_cells(conn)) {
254 if (conn->state == OR_CONN_STATE_OPEN)
255 directory_set_dirty();
257 if (conn->type == CONN_TYPE_CONTROL) {
258 conn->event_mask = 0;
259 control_update_global_event_mask();
261 connection_unregister(conn);
262 _connection_free(conn);
265 /** Call _connection_free() on every connection in our array, and release all
266 * storage helpd by connection.c. This is used by cpuworkers and dnsworkers
267 * when they fork, so they don't keep resources held open (especially
268 * sockets).
270 * Don't do the checks in connection_free(), because they will
271 * fail.
273 void
274 connection_free_all(void)
276 int i, n;
277 connection_t **carray;
279 get_connection_array(&carray,&n);
281 /* We don't want to log any messages to controllers. */
282 for (i=0;i<n;i++)
283 if (carray[i]->type == CONN_TYPE_CONTROL)
284 carray[i]->event_mask = 0;
285 control_update_global_event_mask();
287 for (i=0;i<n;i++)
288 _connection_free(carray[i]);
290 if (outgoing_addrs) {
291 SMARTLIST_FOREACH(outgoing_addrs, void*, addr, tor_free(addr));
292 smartlist_free(outgoing_addrs);
293 outgoing_addrs = NULL;
297 /** Do any cleanup needed:
298 * - Directory conns that failed to fetch a rendezvous descriptor
299 * need to inform pending rendezvous streams.
300 * - OR conns need to call rep_hist_note_*() to record status.
301 * - AP conns need to send a socks reject if necessary.
302 * - Exit conns need to call connection_dns_remove() if necessary.
303 * - AP and Exit conns need to send an end cell if they can.
304 * - DNS conns need to fail any resolves that are pending on them.
306 void
307 connection_about_to_close_connection(connection_t *conn)
309 circuit_t *circ;
311 assert(conn->marked_for_close);
313 if (CONN_IS_EDGE(conn)) {
314 if (!conn->has_sent_end) {
315 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);
316 tor_fragile_assert();
320 switch (conn->type) {
321 case CONN_TYPE_DIR:
322 if (conn->state < DIR_CONN_STATE_CLIENT_FINISHED) {
323 /* It's a directory connection and connecting or fetching
324 * failed: forget about this router, and maybe try again. */
325 connection_dir_request_failed(conn);
327 if (conn->purpose == DIR_PURPOSE_FETCH_RENDDESC)
328 rend_client_desc_here(conn->rend_query); /* give it a try */
329 break;
330 case CONN_TYPE_OR:
331 /* Remember why we're closing this connection. */
332 if (conn->state != OR_CONN_STATE_OPEN) {
333 if (connection_or_nonopen_was_started_here(conn)) {
334 rep_hist_note_connect_failed(conn->identity_digest, time(NULL));
335 helper_node_set_status(conn->identity_digest, 0);
336 control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED);
338 } else if (conn->hold_open_until_flushed) {
339 /* XXXX009 We used to have an arg that told us whether we closed the
340 * connection on purpose or not. Can we use hold_open_until_flushed
341 * instead? We only set it when we are intentionally closing a
342 * connection. -NM
344 * (Of course, now things we set to close which expire rather than
345 * flushing still get noted as dead, not disconnected. But this is an
346 * improvement. -NM
348 rep_hist_note_disconnect(conn->identity_digest, time(NULL));
349 control_event_or_conn_status(conn, OR_CONN_EVENT_CLOSED);
350 } else if (conn->identity_digest) {
351 rep_hist_note_connection_died(conn->identity_digest, time(NULL));
352 control_event_or_conn_status(conn, OR_CONN_EVENT_CLOSED);
354 break;
355 case CONN_TYPE_AP:
356 if (conn->socks_request->has_finished == 0) {
357 /* since conn gets removed right after this function finishes,
358 * there's no point trying to send back a reply at this point. */
359 log_fn(LOG_WARN,"Bug: Closing stream (marked at %s:%d) without sending back a socks reply.",
360 conn->marked_for_close_file, conn->marked_for_close);
361 } else {
362 control_event_stream_status(conn, STREAM_EVENT_CLOSED);
364 break;
365 case CONN_TYPE_EXIT:
366 if (conn->state == EXIT_CONN_STATE_RESOLVING) {
367 circ = circuit_get_by_edge_conn(conn);
368 if (circ)
369 circuit_detach_stream(circ, conn);
370 connection_dns_remove(conn);
372 break;
373 case CONN_TYPE_DNSWORKER:
374 if (conn->state == DNSWORKER_STATE_BUSY) {
375 dns_cancel_pending_resolve(conn->address);
377 break;
381 /** Close the underlying socket for <b>conn</b>, so we don't try to
382 * flush it. Must be used in conjunction with (right before)
383 * connection_mark_for_close().
385 void
386 connection_close_immediate(connection_t *conn)
388 assert_connection_ok(conn,0);
389 if (conn->s < 0) {
390 log_fn(LOG_WARN,"Bug: Attempt to close already-closed connection.");
391 tor_fragile_assert();
392 return;
394 if (conn->outbuf_flushlen) {
395 log_fn(LOG_INFO,"fd %d, type %s, state %s, %d bytes on outbuf.",
396 conn->s, conn_type_to_string(conn->type),
397 conn_state_to_string(conn->type, conn->state),
398 (int)conn->outbuf_flushlen);
401 connection_unregister(conn);
403 tor_close_socket(conn->s);
404 conn->s = -1;
405 if (!connection_is_listener(conn)) {
406 buf_clear(conn->outbuf);
407 conn->outbuf_flushlen = 0;
411 /** Mark <b>conn</b> to be closed next time we loop through
412 * conn_close_if_marked() in main.c. */
413 void
414 _connection_mark_for_close(connection_t *conn, int line, const char *file)
416 assert_connection_ok(conn,0);
417 tor_assert(line);
418 tor_assert(file);
420 if (conn->marked_for_close) {
421 log(LOG_WARN, "Duplicate call to connection_mark_for_close at %s:%d"
422 " (first at %s:%d)", file, line, conn->marked_for_close_file,
423 conn->marked_for_close);
424 tor_fragile_assert();
425 return;
428 conn->marked_for_close = line;
429 conn->marked_for_close_file = file;
430 add_connection_to_closeable_list(conn);
432 /* in case we're going to be held-open-til-flushed, reset
433 * the number of seconds since last successful write, so
434 * we get our whole 15 seconds */
435 conn->timestamp_lastwritten = time(NULL);
438 /** Find each connection that has hold_open_until_flushed set to
439 * 1 but hasn't written in the past 15 seconds, and set
440 * hold_open_until_flushed to 0. This means it will get cleaned
441 * up in the next loop through close_if_marked() in main.c.
443 void
444 connection_expire_held_open(void)
446 connection_t **carray, *conn;
447 int n, i;
448 time_t now;
450 now = time(NULL);
452 get_connection_array(&carray, &n);
453 for (i = 0; i < n; ++i) {
454 conn = carray[i];
455 /* If we've been holding the connection open, but we haven't written
456 * for 15 seconds...
458 if (conn->hold_open_until_flushed) {
459 tor_assert(conn->marked_for_close);
460 if (now - conn->timestamp_lastwritten >= 15) {
461 log_fn(LOG_NOTICE,"Giving up on marked_for_close conn that's been flushing for 15s (fd %d, type %s, state %s).",
462 conn->s, conn_type_to_string(conn->type),
463 conn_state_to_string(conn->type, conn->state));
464 conn->hold_open_until_flushed = 0;
470 /** Bind a new non-blocking socket listening to
471 * <b>bindaddress</b>:<b>bindport</b>, and add this new connection
472 * (of type <b>type</b>) to the connection array.
474 * If <b>bindaddress</b> includes a port, we bind on that port; otherwise, we
475 * use bindport.
477 static connection_t *
478 connection_create_listener(const char *bindaddress, uint16_t bindport,
479 int type)
481 struct sockaddr_in bindaddr; /* where to bind */
482 char *address = NULL;
483 connection_t *conn;
484 uint16_t usePort;
485 uint32_t addr;
486 int s; /* the socket we're going to make */
487 #ifndef MS_WINDOWS
488 int one=1;
489 #endif
491 memset(&bindaddr,0,sizeof(struct sockaddr_in));
492 if (parse_addr_port(bindaddress, &address, &addr, &usePort)<0) {
493 log_fn(LOG_WARN, "Error parsing/resolving BindAddress %s",bindaddress);
494 return NULL;
497 if (usePort==0)
498 usePort = bindport;
499 bindaddr.sin_addr.s_addr = htonl(addr);
500 bindaddr.sin_family = AF_INET;
501 bindaddr.sin_port = htons((uint16_t) usePort);
503 log_fn(LOG_NOTICE, "Opening %s on %s:%d",
504 conn_type_to_string(type), address, usePort);
506 s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
507 if (s < 0) {
508 log_fn(LOG_WARN,"Socket creation failed.");
509 goto err;
510 } else if (!SOCKET_IS_POLLABLE(s)) {
511 log_fn(LOG_WARN,"Too many connections; can't create pollable listener.");
512 tor_close_socket(s);
513 goto err;
516 #ifndef MS_WINDOWS
517 /* REUSEADDR on normal places means you can rebind to the port
518 * right after somebody else has let it go. But REUSEADDR on win32
519 * means you can bind to the port _even when somebody else
520 * already has it bound_. So, don't do that on Win32. */
521 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*) &one, sizeof(one));
522 #endif
524 if (bind(s,(struct sockaddr *)&bindaddr,sizeof(bindaddr)) < 0) {
525 log_fn(LOG_WARN, "Could not bind to port %u: %s", usePort,
526 tor_socket_strerror(tor_socket_errno(s)));
527 goto err;
530 if (listen(s,SOMAXCONN) < 0) {
531 log_fn(LOG_WARN, "Could not listen on port %u: %s", usePort,
532 tor_socket_strerror(tor_socket_errno(s)));
533 goto err;
536 set_socket_nonblocking(s);
538 conn = connection_new(type);
539 conn->s = s;
540 conn->address = address;
541 address = NULL;
542 conn->port = usePort;
544 if (connection_add(conn) < 0) { /* no space, forget it */
545 log_fn(LOG_WARN,"connection_add failed. Giving up.");
546 connection_free(conn);
547 goto err;
550 log_fn(LOG_DEBUG,"%s listening on port %u.",conn_type_to_string(type), usePort);
552 conn->state = LISTENER_STATE_READY;
553 connection_start_reading(conn);
555 return conn;
557 err:
558 tor_free(address);
559 return NULL;
562 /** Do basic sanity checking on a newly received socket. Return 0
563 * if it looks ok, else return -1. */
564 static int
565 check_sockaddr_in(struct sockaddr *sa, int len, int level)
567 int ok = 1;
568 struct sockaddr_in *sin=(struct sockaddr_in*)sa;
570 if (len != sizeof(struct sockaddr_in)) {
571 log_fn(level, "Length of address not as expected: %d vs %d",
572 len,(int)sizeof(struct sockaddr_in));
573 ok = 0;
575 if (sa->sa_family != AF_INET) {
576 log_fn(level, "Family of address not as expected: %d vs %d",
577 sa->sa_family, AF_INET);
578 ok = 0;
580 if (sin->sin_addr.s_addr == 0 || sin->sin_port == 0) {
581 log_fn(level, "Address for new connection has address/port equal to zero.");
582 ok = 0;
584 return ok ? 0 : -1;
587 /** The listener connection <b>conn</b> told poll() it wanted to read.
588 * Call accept() on conn-\>s, and add the new connection if necessary.
590 static int
591 connection_handle_listener_read(connection_t *conn, int new_type)
593 int news; /* the new socket */
594 connection_t *newconn;
595 /* information about the remote peer when connecting to other routers */
596 struct sockaddr_in remote;
597 char addrbuf[256];
598 /* length of the remote address. Must be whatever accept() needs. */
599 socklen_t remotelen = 256;
600 char tmpbuf[INET_NTOA_BUF_LEN];
601 tor_assert((size_t)remotelen >= sizeof(struct sockaddr_in));
602 memset(addrbuf, 0, sizeof(addrbuf));
604 news = accept(conn->s,(struct sockaddr *)&addrbuf,&remotelen);
605 if (!SOCKET_IS_POLLABLE(news)) {
606 /* accept() error, or too many conns to poll */
607 int e;
608 if (news>=0) {
609 /* Too many conns to poll. */
610 log_fn(LOG_WARN,"Too many connections; couldn't accept connection.");
611 tor_close_socket(news);
612 return 0;
614 e = tor_socket_errno(conn->s);
615 if (ERRNO_IS_ACCEPT_EAGAIN(e)) {
616 return 0; /* he hung up before we could accept(). that's fine. */
617 } else if (ERRNO_IS_ACCEPT_RESOURCE_LIMIT(e)) {
618 log_fn(LOG_NOTICE,"accept failed: %s. Dropping incoming connection.",
619 tor_socket_strerror(e));
620 return 0;
622 /* else there was a real error. */
623 log_fn(LOG_WARN,"accept() failed: %s. Closing listener.",
624 tor_socket_strerror(e));
625 connection_mark_for_close(conn);
626 return -1;
628 log(LOG_INFO,"Connection accepted on socket %d (child of fd %d).",news, conn->s);
630 set_socket_nonblocking(news);
632 if (check_sockaddr_in((struct sockaddr*)addrbuf, remotelen, LOG_INFO)<0) {
633 log_fn(LOG_INFO, "accept() returned a strange address; trying getsockname().");
634 remotelen=256;
635 memset(addrbuf, 0, sizeof(addrbuf));
636 if (getsockname(news, (struct sockaddr*)addrbuf, &remotelen)<0) {
637 log_fn(LOG_WARN, "getsockname() failed.");
638 } else {
639 if (check_sockaddr_in((struct sockaddr*)addrbuf, remotelen, LOG_WARN)<0) {
640 log_fn(LOG_WARN,"Something's wrong with this conn. Closing it.");
641 tor_close_socket(news);
642 return 0;
646 memcpy(&remote, addrbuf, sizeof(struct sockaddr_in));
648 /* process entrance policies here, before we even create the connection */
649 if (new_type == CONN_TYPE_AP) {
650 /* check sockspolicy to see if we should accept it */
651 if (socks_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
652 tor_inet_ntoa(&remote.sin_addr, tmpbuf, sizeof(tmpbuf));
653 log_fn(LOG_NOTICE,"Denying socks connection from untrusted address %s.",
654 tmpbuf);
655 tor_close_socket(news);
656 return 0;
659 if (new_type == CONN_TYPE_DIR) {
660 /* check dirpolicy to see if we should accept it */
661 if (dir_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
662 tor_inet_ntoa(&remote.sin_addr, tmpbuf, sizeof(tmpbuf));
663 log_fn(LOG_NOTICE,"Denying dir connection from address %s.",
664 tmpbuf);
665 tor_close_socket(news);
666 return 0;
670 newconn = connection_new(new_type);
671 newconn->s = news;
673 /* remember the remote address */
674 newconn->addr = ntohl(remote.sin_addr.s_addr);
675 newconn->port = ntohs(remote.sin_port);
676 newconn->address = tor_dup_addr(newconn->addr);
678 if (connection_add(newconn) < 0) { /* no space, forget it */
679 connection_free(newconn);
680 return 0; /* no need to tear down the parent */
683 if (connection_init_accepted_conn(newconn) < 0) {
684 connection_mark_for_close(newconn);
685 return 0;
687 return 0;
690 /** Initialize states for newly accepted connection <b>conn</b>.
691 * If conn is an OR, start the tls handshake.
693 static int
694 connection_init_accepted_conn(connection_t *conn)
696 connection_start_reading(conn);
698 switch (conn->type) {
699 case CONN_TYPE_OR:
700 return connection_tls_start_handshake(conn, 1);
701 case CONN_TYPE_AP:
702 conn->state = AP_CONN_STATE_SOCKS_WAIT;
703 break;
704 case CONN_TYPE_DIR:
705 conn->purpose = DIR_PURPOSE_SERVER;
706 conn->state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
707 break;
708 case CONN_TYPE_CONTROL:
709 conn->state = CONTROL_CONN_STATE_NEEDAUTH_V0;
710 break;
712 return 0;
715 /** Take conn, make a nonblocking socket; try to connect to
716 * addr:port (they arrive in *host order*). If fail, return -1. Else
717 * assign s to conn-\>s: if connected return 1, if EAGAIN return 0.
719 * address is used to make the logs useful.
721 * On success, add conn to the list of polled connections.
724 connection_connect(connection_t *conn, char *address,
725 uint32_t addr, uint16_t port)
727 int s, inprogress = 0;
728 struct sockaddr_in dest_addr;
729 or_options_t *options = get_options();
731 s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
732 if (s < 0) {
733 log_fn(LOG_WARN,"Error creating network socket: %s",
734 tor_socket_strerror(tor_socket_errno(-1)));
735 return -1;
736 } else if (!SOCKET_IS_POLLABLE(s)) {
737 log_fn(LOG_WARN,
738 "Too many connections; can't create pollable connection to %s",
739 safe_str(address));
740 tor_close_socket(s);
741 return -1;
744 if (options->OutboundBindAddress) {
745 struct sockaddr_in ext_addr;
747 memset(&ext_addr, 0, sizeof(ext_addr));
748 ext_addr.sin_family = AF_INET;
749 ext_addr.sin_port = 0;
750 if (!tor_inet_aton(options->OutboundBindAddress, &ext_addr.sin_addr)) {
751 log_fn(LOG_WARN,"Outbound bind address '%s' didn't parse. Ignoring.",
752 options->OutboundBindAddress);
753 } else {
754 if (bind(s, (struct sockaddr*)&ext_addr, sizeof(ext_addr)) < 0) {
755 log_fn(LOG_WARN,"Error binding network socket: %s",
756 tor_socket_strerror(tor_socket_errno(s)));
757 return -1;
762 set_socket_nonblocking(s);
764 memset(&dest_addr,0,sizeof(dest_addr));
765 dest_addr.sin_family = AF_INET;
766 dest_addr.sin_port = htons(port);
767 dest_addr.sin_addr.s_addr = htonl(addr);
769 log_fn(LOG_DEBUG,"Connecting to %s:%u.",safe_str(address),port);
771 if (connect(s,(struct sockaddr *)&dest_addr,sizeof(dest_addr)) < 0) {
772 int e = tor_socket_errno(s);
773 if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
774 /* yuck. kill it. */
775 log_fn(LOG_INFO,"Connect() to %s:%u failed: %s",safe_str(address),port,
776 tor_socket_strerror(e));
777 tor_close_socket(s);
778 return -1;
779 } else {
780 inprogress = 1;
784 if (!server_mode(options))
785 client_check_address_changed(s);
787 /* it succeeded. we're connected. */
788 log_fn(inprogress?LOG_DEBUG:LOG_INFO,
789 "Connection to %s:%u %s (sock %d).",safe_str(address),port,
790 inprogress?"in progress":"established",s);
791 conn->s = s;
792 if (connection_add(conn) < 0) /* no space, forget it */
793 return -1;
794 return inprogress ? 0 : 1;
798 * Launch any configured listener connections of type <b>type</b>. (A
799 * listener is configured if <b>port_option</b> is non-zero. If any
800 * BindAddress configuration options are given in <b>cfg</b>, create a
801 * connection binding to each one. Otherwise, create a single
802 * connection binding to the address <b>default_addr</b>.)
804 * If <b>force</b> is true, close and re-open all listener connections.
805 * Otherwise, only relaunch the listeners of this type if the number of
806 * existing connections is not as configured (e.g., because one died),
807 * or if the existing connections do not match those configured.
809 * Add all old conns that should be closed to <b>replaced_conns</b>.
810 * Add all new connections to <b>new_conns</b>.
812 static int
813 retry_listeners(int type, config_line_t *cfg,
814 int port_option, const char *default_addr, int force,
815 smartlist_t *replaced_conns,
816 smartlist_t *new_conns)
818 smartlist_t *launch = smartlist_create();
819 int free_launch_elts = 1;
820 config_line_t *c;
821 int n_conn, i;
822 connection_t *conn;
823 connection_t **carray;
824 config_line_t *line;
826 if (cfg && port_option) {
827 for (c = cfg; c; c = c->next) {
828 smartlist_add(launch, c);
830 free_launch_elts = 0;
831 } else if (port_option) {
832 line = tor_malloc_zero(sizeof(config_line_t));
833 line->key = tor_strdup("");
834 line->value = tor_strdup(default_addr);
835 smartlist_add(launch, line);
839 SMARTLIST_FOREACH(launch, config_line_t *, l,
840 log_fn(LOG_NOTICE, "#%s#%s", l->key, l->value));
843 get_connection_array(&carray,&n_conn);
844 for (i=0; i < n_conn; ++i) {
845 conn = carray[i];
846 if (conn->type != type || conn->marked_for_close)
847 continue;
848 if (force) {
849 /* It's a listener, and we're relaunching all listeners of this
850 * type. Close this one. */
851 log_fn(LOG_NOTICE, "Closing %s on %s:%d",
852 conn_type_to_string(type), conn->address, conn->port);
853 connection_close_immediate(conn);
854 connection_mark_for_close(conn);
855 continue;
857 /* Okay, so this is a listener. Is it configured? */
858 line = NULL;
859 SMARTLIST_FOREACH(launch, config_line_t *, wanted,
861 char *addr;
862 uint16_t port;
863 if (! parse_addr_port(wanted->value, &addr, NULL, &port)) {
864 if (! port)
865 port = port_option;
866 if (port == conn->port && !strcasecmp(addr, conn->address)) {
867 line = wanted;
868 break;
872 if (! line) {
873 /* This one isn't configured. Close it. */
874 log_fn(LOG_NOTICE, "Closing %s on %s:%d",
875 conn_type_to_string(type), conn->address, conn->port);
876 if (replaced_conns) {
877 smartlist_add(replaced_conns, conn);
878 } else {
879 connection_close_immediate(conn);
880 connection_mark_for_close(conn);
882 } else {
883 /* It's configured; we don't need to launch it. */
884 log_fn(LOG_INFO, "Already have %s on %s:%d",
885 conn_type_to_string(type), conn->address, conn->port);
886 smartlist_remove(launch, line);
890 /* Now open all the listeners that are configured but not opened. */
891 i = 0;
892 SMARTLIST_FOREACH(launch, config_line_t *, cfg,
894 conn = connection_create_listener(cfg->value, (uint16_t) port_option,
895 type);
896 if (!conn) {
897 i = -1;
898 } else {
899 if (new_conns)
900 smartlist_add(new_conns, conn);
904 if (free_launch_elts) {
905 SMARTLIST_FOREACH(launch, config_line_t *, cfg,
906 config_free_lines(cfg));
908 smartlist_free(launch);
910 return i;
913 /** (Re)launch listeners for each port you should have open. If
914 * <b>force</b> is true, close and relaunch all listeners. If <b>force</b>
915 * is false, then only relaunch listeners when we have the wrong number of
916 * connections for a given type.
918 * Add all old conns that should be closed to <b>replaced_conns</b>.
919 * Add all new connections to <b>new_conns</b>.
922 retry_all_listeners(int force, smartlist_t *replaced_conns,
923 smartlist_t *new_conns)
925 or_options_t *options = get_options();
927 if (server_mode(options) &&
928 retry_listeners(CONN_TYPE_OR_LISTENER, options->ORBindAddress,
929 options->ORPort, "0.0.0.0", force,
930 replaced_conns, new_conns)<0)
931 return -1;
932 if (retry_listeners(CONN_TYPE_DIR_LISTENER, options->DirBindAddress,
933 options->DirPort, "0.0.0.0", force,
934 replaced_conns, new_conns)<0)
935 return -1;
936 if (retry_listeners(CONN_TYPE_AP_LISTENER, options->SocksBindAddress,
937 options->SocksPort, "127.0.0.1", force,
938 replaced_conns, new_conns)<0)
939 return -1;
940 if (retry_listeners(CONN_TYPE_CONTROL_LISTENER, NULL,
941 options->ControlPort, "127.0.0.1", force,
942 replaced_conns, new_conns)<0)
943 return -1;
945 return 0;
948 extern int global_read_bucket, global_write_bucket;
950 /** How many bytes at most can we read onto this connection? */
951 static int
952 connection_bucket_read_limit(connection_t *conn)
954 int at_most;
956 /* do a rudimentary round-robin so one circuit can't hog a connection */
957 if (connection_speaks_cells(conn)) {
958 at_most = 32*(CELL_NETWORK_SIZE);
959 } else {
960 at_most = 32*(RELAY_PAYLOAD_SIZE);
963 if (at_most > global_read_bucket)
964 at_most = global_read_bucket;
966 if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN)
967 if (at_most > conn->receiver_bucket)
968 at_most = conn->receiver_bucket;
970 if (at_most < 0)
971 return 0;
972 return at_most;
975 /** We just read num_read onto conn. Decrement buckets appropriately. */
976 static void
977 connection_read_bucket_decrement(connection_t *conn, int num_read)
979 global_read_bucket -= num_read; //tor_assert(global_read_bucket >= 0);
980 if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
981 conn->receiver_bucket -= num_read; //tor_assert(conn->receiver_bucket >= 0);
985 /** DOCDOC */
986 static void
987 connection_consider_empty_buckets(connection_t *conn)
989 if (global_read_bucket <= 0) {
990 LOG_FN_CONN(conn, (LOG_DEBUG,"global bucket exhausted. Pausing."));
991 conn->wants_to_read = 1;
992 connection_stop_reading(conn);
993 return;
995 if (connection_speaks_cells(conn) &&
996 conn->state == OR_CONN_STATE_OPEN &&
997 conn->receiver_bucket <= 0) {
998 LOG_FN_CONN(conn, (LOG_DEBUG,"receiver bucket exhausted. Pausing."));
999 conn->wants_to_read = 1;
1000 connection_stop_reading(conn);
1004 /** Initialize the global read bucket to options->BandwidthBurst,
1005 * and current_time to the current time. */
1006 void
1007 connection_bucket_init(void)
1009 or_options_t *options = get_options();
1010 global_read_bucket = (int)options->BandwidthBurst; /* start it at max traffic */
1011 global_write_bucket = (int)options->BandwidthBurst; /* start it at max traffic */
1014 /** A second has rolled over; increment buckets appropriately. */
1015 void
1016 connection_bucket_refill(struct timeval *now)
1018 int i, n;
1019 connection_t *conn;
1020 connection_t **carray;
1021 or_options_t *options = get_options();
1023 /* refill the global buckets */
1024 if (global_read_bucket < (int)options->BandwidthBurst) {
1025 global_read_bucket += (int)options->BandwidthRate;
1026 log_fn(LOG_DEBUG,"global_read_bucket now %d.", global_read_bucket);
1028 if (global_write_bucket < (int)options->BandwidthBurst) {
1029 global_write_bucket += (int)options->BandwidthRate;
1030 log_fn(LOG_DEBUG,"global_write_bucket now %d.", global_write_bucket);
1033 /* refill the per-connection buckets */
1034 get_connection_array(&carray,&n);
1035 for (i=0;i<n;i++) {
1036 conn = carray[i];
1038 if (connection_receiver_bucket_should_increase(conn)) {
1039 conn->receiver_bucket = conn->bandwidth;
1040 //log_fn(LOG_DEBUG,"Receiver bucket %d now %d.", i, conn->receiver_bucket);
1043 if (conn->wants_to_read == 1 /* it's marked to turn reading back on now */
1044 && global_read_bucket > 0 /* and we're allowed to read */
1045 && global_write_bucket > 0 /* and we're allowed to write (XXXX,
1046 * not the best place to check this.) */
1047 && (!connection_speaks_cells(conn) ||
1048 conn->state != OR_CONN_STATE_OPEN ||
1049 conn->receiver_bucket > 0)) {
1050 /* and either a non-cell conn or a cell conn with non-empty bucket */
1051 LOG_FN_CONN(conn, (LOG_DEBUG,"waking up conn (fd %d)",conn->s));
1052 conn->wants_to_read = 0;
1053 connection_start_reading(conn);
1054 if (conn->wants_to_write == 1) {
1055 conn->wants_to_write = 0;
1056 connection_start_writing(conn);
1062 /** Is the receiver bucket for connection <b>conn</b> low enough that we
1063 * should add another pile of tokens to it?
1065 static int
1066 connection_receiver_bucket_should_increase(connection_t *conn)
1068 tor_assert(conn);
1070 if (!connection_speaks_cells(conn))
1071 return 0; /* edge connections don't use receiver_buckets */
1072 if (conn->state != OR_CONN_STATE_OPEN)
1073 return 0; /* only open connections play the rate limiting game */
1075 if (conn->receiver_bucket >= conn->bandwidth)
1076 return 0;
1078 return 1;
1081 /** Read bytes from conn-\>s and process them.
1083 * This function gets called from conn_read() in main.c, either
1084 * when poll() has declared that conn wants to read, or (for OR conns)
1085 * when there are pending TLS bytes.
1087 * It calls connection_read_to_buf() to bring in any new bytes,
1088 * and then calls connection_process_inbuf() to process them.
1090 * Mark the connection and return -1 if you want to close it, else
1091 * return 0.
1094 connection_handle_read(connection_t *conn)
1096 int max_to_read=-1, try_to_read;
1098 if (conn->marked_for_close)
1099 return 0; /* do nothing */
1101 conn->timestamp_lastread = time(NULL);
1103 switch (conn->type) {
1104 case CONN_TYPE_OR_LISTENER:
1105 return connection_handle_listener_read(conn, CONN_TYPE_OR);
1106 case CONN_TYPE_AP_LISTENER:
1107 return connection_handle_listener_read(conn, CONN_TYPE_AP);
1108 case CONN_TYPE_DIR_LISTENER:
1109 return connection_handle_listener_read(conn, CONN_TYPE_DIR);
1110 case CONN_TYPE_CONTROL_LISTENER:
1111 return connection_handle_listener_read(conn, CONN_TYPE_CONTROL);
1114 loop_again:
1115 try_to_read = max_to_read;
1116 tor_assert(!conn->marked_for_close);
1117 if (connection_read_to_buf(conn, &max_to_read) < 0) {
1118 /* There's a read error; kill the connection.*/
1119 connection_close_immediate(conn); /* Don't flush; connection is dead. */
1120 if (CONN_IS_EDGE(conn)) {
1121 connection_edge_end_errno(conn, conn->cpath_layer);
1122 if (conn->socks_request) /* broken, so don't send a socks reply back */
1123 conn->socks_request->has_finished = 1;
1125 connection_mark_for_close(conn);
1126 return -1;
1128 if (CONN_IS_EDGE(conn) &&
1129 try_to_read != max_to_read) {
1130 /* instruct it not to try to package partial cells. */
1131 if (connection_process_inbuf(conn, 0) < 0) {
1132 return -1;
1134 if (!conn->marked_for_close &&
1135 connection_is_reading(conn) &&
1136 !conn->inbuf_reached_eof &&
1137 max_to_read > 0)
1138 goto loop_again; /* try reading again, in case more is here now */
1140 /* one last try, packaging partial cells and all. */
1141 if (!conn->marked_for_close &&
1142 connection_process_inbuf(conn, 1) < 0) {
1143 return -1;
1145 if (!conn->marked_for_close &&
1146 conn->inbuf_reached_eof &&
1147 connection_reached_eof(conn) < 0) {
1148 return -1;
1150 return 0;
1153 /** Pull in new bytes from conn-\>s onto conn-\>inbuf, either
1154 * directly or via TLS. Reduce the token buckets by the number of
1155 * bytes read.
1157 * If *max_to_read is -1, then decide it ourselves, else go with the
1158 * value passed to us. When returning, if it's changed, subtract the
1159 * number of bytes we read from *max_to_read.
1161 * Return -1 if we want to break conn, else return 0.
1163 static int
1164 connection_read_to_buf(connection_t *conn, int *max_to_read)
1166 int result, at_most = *max_to_read;
1167 size_t bytes_in_buf, more_to_read;
1169 if (at_most == -1) { /* we need to initialize it */
1170 /* how many bytes are we allowed to read? */
1171 at_most = connection_bucket_read_limit(conn);
1174 bytes_in_buf = buf_capacity(conn->inbuf) - buf_datalen(conn->inbuf);
1175 again:
1176 if ((size_t)at_most > bytes_in_buf && bytes_in_buf >= 1024) {
1177 more_to_read = at_most - bytes_in_buf;
1178 at_most = bytes_in_buf;
1179 } else {
1180 more_to_read = 0;
1183 if (connection_speaks_cells(conn) && conn->state > OR_CONN_STATE_PROXY_READING) {
1184 int pending;
1185 if (conn->state == OR_CONN_STATE_HANDSHAKING) {
1186 /* continue handshaking even if global token bucket is empty */
1187 return connection_tls_continue_handshake(conn);
1190 log_fn(LOG_DEBUG,"%d: starting, inbuf_datalen %d (%d pending in tls object). at_most %d.",
1191 conn->s,(int)buf_datalen(conn->inbuf),tor_tls_get_pending_bytes(conn->tls), at_most);
1193 /* else open, or closing */
1194 result = read_to_buf_tls(conn->tls, at_most, conn->inbuf);
1196 switch (result) {
1197 case TOR_TLS_CLOSE:
1198 log_fn(LOG_INFO,"TLS connection closed on read. Closing. (Nickname %s, address %s",
1199 conn->nickname ? conn->nickname : "not set", conn->address);
1200 return -1;
1201 case TOR_TLS_ERROR:
1202 log_fn(LOG_INFO,"tls error. breaking (nickname %s, address %s).",
1203 conn->nickname ? conn->nickname : "not set", conn->address);
1204 return -1;
1205 case TOR_TLS_WANTWRITE:
1206 connection_start_writing(conn);
1207 return 0;
1208 case TOR_TLS_WANTREAD: /* we're already reading */
1209 case TOR_TLS_DONE: /* no data read, so nothing to process */
1210 result = 0;
1211 break; /* so we call bucket_decrement below */
1212 default:
1213 break;
1215 pending = tor_tls_get_pending_bytes(conn->tls);
1216 if (pending) {
1217 /* XXXX If we have any pending bytes, read them now. This *can*
1218 * take us over our read allotment, but really we shouldn't be
1219 * believing that SSL bytes are the same as TCP bytes anyway. */
1220 int r2 = read_to_buf_tls(conn->tls, pending, conn->inbuf);
1221 if (r2<0) {
1222 log_fn(LOG_WARN, "Bug: apparently, reading pending bytes can fail.");
1223 return -1;
1224 } else {
1225 result += r2;
1229 } else {
1230 CONN_LOG_PROTECT(conn,
1231 result = read_to_buf(conn->s, at_most, conn->inbuf,
1232 &conn->inbuf_reached_eof));
1234 // log_fn(LOG_DEBUG,"read_to_buf returned %d.",read_result);
1236 if (result < 0)
1237 return -1;
1240 if (result > 0) { /* change *max_to_read */
1241 *max_to_read = at_most - result;
1244 if (result > 0 && !is_local_IP(conn->addr)) { /* remember it */
1245 rep_hist_note_bytes_read(result, time(NULL));
1246 connection_read_bucket_decrement(conn, result);
1249 if (more_to_read && result == at_most) {
1250 bytes_in_buf = buf_capacity(conn->inbuf) - buf_datalen(conn->inbuf);
1251 tor_assert(bytes_in_buf < 1024);
1252 at_most = more_to_read;
1253 goto again;
1256 /* Call even if result is 0, since the global read bucket may
1257 * have reached 0 on a different conn, and this guy needs to
1258 * know to stop reading. */
1259 connection_consider_empty_buckets(conn);
1261 return 0;
1264 /** A pass-through to fetch_from_buf. */
1266 connection_fetch_from_buf(char *string, size_t len, connection_t *conn)
1268 return fetch_from_buf(string, len, conn->inbuf);
1271 /** Return conn-\>outbuf_flushlen: how many bytes conn wants to flush
1272 * from its outbuf. */
1274 connection_wants_to_flush(connection_t *conn)
1276 return conn->outbuf_flushlen;
1279 /** Are there too many bytes on edge connection <b>conn</b>'s outbuf to
1280 * send back a relay-level sendme yet? Return 1 if so, 0 if not. Used by
1281 * connection_edge_consider_sending_sendme().
1284 connection_outbuf_too_full(connection_t *conn)
1286 return (conn->outbuf_flushlen > 10*CELL_PAYLOAD_SIZE);
1289 /** Try to flush more bytes onto conn-\>s.
1291 * This function gets called either from conn_write() in main.c
1292 * when poll() has declared that conn wants to write, or below
1293 * from connection_write_to_buf() when an entire TLS record is ready.
1295 * Update conn-\>timestamp_lastwritten to now, and call flush_buf
1296 * or flush_buf_tls appropriately. If it succeeds and there no more
1297 * more bytes on conn->outbuf, then call connection_finished_flushing
1298 * on it too.
1300 * Mark the connection and return -1 if you want to close it, else
1301 * return 0.
1304 connection_handle_write(connection_t *conn)
1306 int e;
1307 socklen_t len=sizeof(e);
1308 int result;
1309 time_t now = time(NULL);
1311 tor_assert(!connection_is_listener(conn));
1313 if (conn->marked_for_close)
1314 return 0; /* do nothing */
1316 conn->timestamp_lastwritten = now;
1318 /* Sometimes, "writable" means "connected". */
1319 if (connection_state_is_connecting(conn)) {
1320 if (getsockopt(conn->s, SOL_SOCKET, SO_ERROR, (void*)&e, &len) < 0) {
1321 log_fn(LOG_WARN,"getsockopt() syscall failed?! Please report to tor-ops.");
1322 if (CONN_IS_EDGE(conn))
1323 connection_edge_end_errno(conn, conn->cpath_layer);
1324 connection_mark_for_close(conn);
1325 return -1;
1327 if (e) {
1328 /* some sort of error, but maybe just inprogress still */
1329 if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
1330 log_fn(LOG_INFO,"in-progress connect failed. Removing.");
1331 if (CONN_IS_EDGE(conn))
1332 connection_edge_end_errno(conn, conn->cpath_layer);
1334 connection_close_immediate(conn);
1335 connection_mark_for_close(conn);
1336 /* it's safe to pass OPs to router_mark_as_down(), since it just
1337 * ignores unrecognized routers
1339 if (conn->type == CONN_TYPE_OR && !get_options()->HttpsProxy)
1340 router_mark_as_down(conn->identity_digest);
1341 return -1;
1342 } else {
1343 return 0; /* no change, see if next time is better */
1346 /* The connection is successful. */
1347 if (connection_finished_connecting(conn)<0)
1348 return -1;
1351 if (connection_speaks_cells(conn) && conn->state > OR_CONN_STATE_PROXY_READING) {
1352 if (conn->state == OR_CONN_STATE_HANDSHAKING) {
1353 connection_stop_writing(conn);
1354 if (connection_tls_continue_handshake(conn) < 0) {
1355 connection_close_immediate(conn); /* Don't flush; connection is dead. */
1356 connection_mark_for_close(conn);
1357 return -1;
1359 return 0;
1362 /* else open, or closing */
1363 result = flush_buf_tls(conn->tls, conn->outbuf, &conn->outbuf_flushlen);
1364 switch (result) {
1365 case TOR_TLS_ERROR:
1366 case TOR_TLS_CLOSE:
1367 log_fn(LOG_INFO,result==TOR_TLS_ERROR?
1368 "tls error. breaking.":"TLS connection closed on flush");
1369 connection_close_immediate(conn); /* Don't flush; connection is dead. */
1370 connection_mark_for_close(conn);
1371 return -1;
1372 case TOR_TLS_WANTWRITE:
1373 log_fn(LOG_DEBUG,"wanted write.");
1374 /* we're already writing */
1375 return 0;
1376 case TOR_TLS_WANTREAD:
1377 /* Make sure to avoid a loop if the receive buckets are empty. */
1378 log_fn(LOG_DEBUG,"wanted read.");
1379 if (!connection_is_reading(conn)) {
1380 connection_stop_writing(conn);
1381 conn->wants_to_write = 1;
1382 /* we'll start reading again when the next second arrives,
1383 * and then also start writing again.
1386 /* else no problem, we're already reading */
1387 return 0;
1388 /* case TOR_TLS_DONE:
1389 * for TOR_TLS_DONE, fall through to check if the flushlen
1390 * is empty, so we can stop writing.
1393 } else {
1394 CONN_LOG_PROTECT(conn,
1395 result = flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen));
1396 if (result < 0) {
1397 if (CONN_IS_EDGE(conn))
1398 connection_edge_end_errno(conn, conn->cpath_layer);
1400 connection_close_immediate(conn); /* Don't flush; connection is dead. */
1401 connection_mark_for_close(conn);
1402 return -1;
1406 if (result > 0 && !is_local_IP(conn->addr)) { /* remember it */
1407 rep_hist_note_bytes_written(result, now);
1408 global_write_bucket -= result;
1411 if (!connection_wants_to_flush(conn)) { /* it's done flushing */
1412 if (connection_finished_flushing(conn) < 0) {
1413 /* already marked */
1414 return -1;
1418 return 0;
1421 /* DOCDOC */
1422 void
1423 _connection_controller_force_write(connection_t *conn)
1425 /* XXX This is hideous code duplication, but raising it seems a little
1426 * tricky for now. Think more about this one. We only call it for
1427 * EVENT_ERR_MSG, so messing with buckets a little isn't such a big problem.
1429 int result;
1430 tor_assert(conn);
1431 tor_assert(!conn->tls);
1432 tor_assert(conn->type == CONN_TYPE_CONTROL);
1433 if (conn->marked_for_close || conn->s < 0)
1434 return;
1436 CONN_LOG_PROTECT(conn,
1437 result = flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen));
1438 if (result < 0) {
1439 connection_close_immediate(conn); /* Don't flush; connection is dead. */
1440 connection_mark_for_close(conn);
1441 return;
1444 if (result > 0 && !is_local_IP(conn->addr)) { /* remember it */
1445 rep_hist_note_bytes_written(result, time(NULL));
1446 global_write_bucket -= result;
1449 if (!connection_wants_to_flush(conn)) { /* it's done flushing */
1450 if (connection_finished_flushing(conn) < 0) {
1451 /* already marked */
1452 return;
1457 /** Append <b>len</b> bytes of <b>string</b> onto <b>conn</b>'s
1458 * outbuf, and ask it to start writing.
1460 void
1461 connection_write_to_buf(const char *string, size_t len, connection_t *conn)
1463 int r;
1464 if (!len)
1465 return;
1466 /* if it's marked for close, only allow write if we mean to flush it */
1467 if (conn->marked_for_close && !conn->hold_open_until_flushed)
1468 return;
1470 CONN_LOG_PROTECT(conn, r = write_to_buf(string, len, conn->outbuf));
1471 if (r < 0) {
1472 if (CONN_IS_EDGE(conn)) {
1473 /* if it failed, it means we have our package/delivery windows set
1474 wrong compared to our max outbuf size. close the whole circuit. */
1475 log_fn(LOG_WARN,"write_to_buf failed. Closing circuit (fd %d).", conn->s);
1476 circuit_mark_for_close(circuit_get_by_edge_conn(conn));
1477 } else {
1478 log_fn(LOG_WARN,"write_to_buf failed. Closing connection (fd %d).", conn->s);
1479 connection_mark_for_close(conn);
1481 return;
1484 connection_start_writing(conn);
1485 conn->outbuf_flushlen += len;
1488 /** Return the conn to addr/port that has the most recent
1489 * timestamp_created, or NULL if no such conn exists. */
1490 connection_t *
1491 connection_or_exact_get_by_addr_port(uint32_t addr, uint16_t port)
1493 int i, n;
1494 connection_t *conn, *best=NULL;
1495 connection_t **carray;
1497 get_connection_array(&carray,&n);
1498 for (i=0;i<n;i++) {
1499 conn = carray[i];
1500 if (conn->type == CONN_TYPE_OR &&
1501 conn->addr == addr &&
1502 conn->port == port &&
1503 !conn->marked_for_close &&
1504 (!best || best->timestamp_created < conn->timestamp_created))
1505 best = conn;
1507 return best;
1510 /** Return a connection with give type, address, port, and purpose or NULL if
1511 * no such connection exists. */
1512 connection_t *
1513 connection_get_by_type_addr_port_purpose(int type, uint32_t addr, uint16_t port,
1514 int purpose)
1516 int i, n;
1517 connection_t *conn;
1518 connection_t **carray;
1520 get_connection_array(&carray,&n);
1521 for (i=0;i<n;i++) {
1522 conn = carray[i];
1523 if (conn->type == type &&
1524 conn->addr == addr &&
1525 conn->port == port &&
1526 conn->purpose == purpose &&
1527 !conn->marked_for_close)
1528 return conn;
1530 return NULL;
1533 connection_t *
1534 connection_get_by_identity_digest(const char *digest, int type)
1536 int i, n;
1537 connection_t *conn, *best=NULL;
1538 connection_t **carray;
1540 get_connection_array(&carray,&n);
1541 for (i=0;i<n;i++) {
1542 conn = carray[i];
1543 if (conn->type != type)
1544 continue;
1545 if (!memcmp(conn->identity_digest, digest, DIGEST_LEN) &&
1546 !conn->marked_for_close &&
1547 (!best || best->timestamp_created < conn->timestamp_created))
1548 best = conn;
1550 return best;
1553 /** Return the connection with id <b>id</b> if it is not already
1554 * marked for close.
1556 connection_t *
1557 connection_get_by_global_id(uint32_t id)
1559 int i, n;
1560 connection_t *conn;
1561 connection_t **carray;
1563 get_connection_array(&carray,&n);
1564 for (i=0;i<n;i++) {
1565 conn = carray[i];
1566 if (conn->global_identifier == id) {
1567 if (!conn->marked_for_close)
1568 return conn;
1569 else
1570 return NULL;
1573 return NULL;
1576 /** Return a connection of type <b>type</b> that is not marked for
1577 * close.
1579 connection_t *
1580 connection_get_by_type(int type)
1582 int i, n;
1583 connection_t *conn;
1584 connection_t **carray;
1586 get_connection_array(&carray,&n);
1587 for (i=0;i<n;i++) {
1588 conn = carray[i];
1589 if (conn->type == type && !conn->marked_for_close)
1590 return conn;
1592 return NULL;
1595 /** Return a connection of type <b>type</b> that is in state <b>state</b>,
1596 * and that is not marked for close.
1598 connection_t *
1599 connection_get_by_type_state(int type, int state)
1601 int i, n;
1602 connection_t *conn;
1603 connection_t **carray;
1605 get_connection_array(&carray,&n);
1606 for (i=0;i<n;i++) {
1607 conn = carray[i];
1608 if (conn->type == type && conn->state == state && !conn->marked_for_close)
1609 return conn;
1611 return NULL;
1614 /** Return the connection of type <b>type</b> that is in state
1615 * <b>state</b>, that was written to least recently, and that is not
1616 * marked for close.
1618 connection_t *
1619 connection_get_by_type_state_lastwritten(int type, int state)
1621 int i, n;
1622 connection_t *conn, *best=NULL;
1623 connection_t **carray;
1625 get_connection_array(&carray,&n);
1626 for (i=0;i<n;i++) {
1627 conn = carray[i];
1628 if (conn->type == type && conn->state == state && !conn->marked_for_close)
1629 if (!best || conn->timestamp_lastwritten < best->timestamp_lastwritten)
1630 best = conn;
1632 return best;
1635 /** Return a connection of type <b>type</b> that has rendquery equal
1636 * to <b>rendquery</b>, and that is not marked for close. If state
1637 * is non-zero, conn must be of that state too.
1639 connection_t *
1640 connection_get_by_type_state_rendquery(int type, int state, const char *rendquery)
1642 int i, n;
1643 connection_t *conn;
1644 connection_t **carray;
1646 get_connection_array(&carray,&n);
1647 for (i=0;i<n;i++) {
1648 conn = carray[i];
1649 if (conn->type == type &&
1650 !conn->marked_for_close &&
1651 (!state || state == conn->state) &&
1652 !rend_cmp_service_ids(rendquery, conn->rend_query))
1653 return conn;
1655 return NULL;
1658 /** Return an open, non-marked connection of a given type and purpose, or NULL
1659 * if no such connection exists. */
1660 connection_t *
1661 connection_get_by_type_purpose(int type, int purpose)
1663 int i, n;
1664 connection_t *conn;
1665 connection_t **carray;
1667 get_connection_array(&carray,&n);
1668 for (i=0;i<n;i++) {
1669 conn = carray[i];
1670 if (conn->type == type &&
1671 !conn->marked_for_close &&
1672 (purpose == conn->purpose))
1673 return conn;
1675 return NULL;
1678 /** Return 1 if <b>conn</b> is a listener conn, else return 0. */
1680 connection_is_listener(connection_t *conn)
1682 if (conn->type == CONN_TYPE_OR_LISTENER ||
1683 conn->type == CONN_TYPE_AP_LISTENER ||
1684 conn->type == CONN_TYPE_DIR_LISTENER ||
1685 conn->type == CONN_TYPE_CONTROL_LISTENER)
1686 return 1;
1687 return 0;
1690 /** Return 1 if <b>conn</b> is in state "open" and is not marked
1691 * for close, else return 0.
1694 connection_state_is_open(connection_t *conn)
1696 tor_assert(conn);
1698 if (conn->marked_for_close)
1699 return 0;
1701 if ((conn->type == CONN_TYPE_OR && conn->state == OR_CONN_STATE_OPEN) ||
1702 (conn->type == CONN_TYPE_AP && conn->state == AP_CONN_STATE_OPEN) ||
1703 (conn->type == CONN_TYPE_EXIT && conn->state == EXIT_CONN_STATE_OPEN) ||
1704 (conn->type == CONN_TYPE_CONTROL &&
1705 (conn->state == CONTROL_CONN_STATE_OPEN_V0 ||
1706 conn->state == CONTROL_CONN_STATE_OPEN_V1)))
1707 return 1;
1709 return 0;
1712 /** Return 1 if conn is in 'connecting' state, else return 0. */
1714 connection_state_is_connecting(connection_t *conn)
1716 tor_assert(conn);
1718 if (conn->marked_for_close)
1719 return 0;
1720 switch (conn->type)
1722 case CONN_TYPE_OR:
1723 return conn->state == OR_CONN_STATE_CONNECTING;
1724 case CONN_TYPE_EXIT:
1725 return conn->state == EXIT_CONN_STATE_CONNECTING;
1726 case CONN_TYPE_DIR:
1727 return conn->state == DIR_CONN_STATE_CONNECTING;
1730 return 0;
1733 /** Write a destroy cell with circ ID <b>circ_id</b> onto OR connection
1734 * <b>conn</b>.
1736 * Return 0.
1739 connection_send_destroy(uint16_t circ_id, connection_t *conn)
1741 cell_t cell;
1743 tor_assert(conn);
1744 tor_assert(connection_speaks_cells(conn));
1746 memset(&cell, 0, sizeof(cell_t));
1747 cell.circ_id = circ_id;
1748 cell.command = CELL_DESTROY;
1749 log_fn(LOG_INFO,"Sending destroy (circID %d).", circ_id);
1750 connection_or_write_cell_to_buf(&cell, conn);
1751 return 0;
1754 /** Alloocates a base64'ed authenticator for use in http or https
1755 * auth, based on the input string <b>authenticator</b>. Returns it
1756 * if success, else returns NULL. */
1757 char *
1758 alloc_http_authenticator(const char *authenticator)
1760 /* an authenticator in Basic authentication
1761 * is just the string "username:password" */
1762 const int authenticator_length = strlen(authenticator);
1763 /* The base64_encode function needs a minimum buffer length
1764 * of 66 bytes. */
1765 const int base64_authenticator_length = (authenticator_length/48+1)*66;
1766 char *base64_authenticator = tor_malloc(base64_authenticator_length);
1767 if (base64_encode(base64_authenticator, base64_authenticator_length,
1768 authenticator, authenticator_length) < 0) {
1769 tor_free(base64_authenticator); /* free and set to null */
1770 } else {
1771 /* remove extra \n at end of encoding */
1772 base64_authenticator[strlen(base64_authenticator) - 1] = 0;
1774 return base64_authenticator;
1777 /** DOCDOC
1778 * XXXX ipv6 NM
1780 static void
1781 client_check_address_changed(int sock)
1783 uint32_t iface_ip, ip_out;
1784 struct sockaddr_in out_addr;
1785 socklen_t out_addr_len = sizeof(out_addr);
1786 uint32_t *ip;
1788 if (!last_interface_ip)
1789 get_interface_address(&last_interface_ip);
1790 if (!outgoing_addrs)
1791 outgoing_addrs = smartlist_create();
1793 if (getsockname(sock, (struct sockaddr*)&out_addr, &out_addr_len)<0) {
1794 int e = tor_socket_errno(sock);
1795 log_fn(LOG_WARN, "getsockname() failed: %s", tor_socket_strerror(e));
1796 return;
1799 /* Okay. If we've used this address previously, we're okay. */
1800 ip_out = ntohl(out_addr.sin_addr.s_addr);
1801 SMARTLIST_FOREACH(outgoing_addrs, uint32_t*, ip,
1802 if (*ip == ip_out) return;
1805 /* Uh-oh. We haven't connected from this address before. Has the interface
1806 * address changed? */
1807 if (get_interface_address(&iface_ip)<0)
1808 return;
1809 ip = tor_malloc(sizeof(uint32_t));
1810 *ip = ip_out;
1812 if (iface_ip == last_interface_ip) {
1813 /* Nope, it hasn't changed. Add this address to the list. */
1814 smartlist_add(outgoing_addrs, ip);
1815 } else {
1816 /* The interface changed. We're a client, so we need to regenerate our
1817 * keys. First, reset the state. */
1818 log_fn(LOG_NOTICE, "Our IP has changed. Rotating keys...");
1819 last_interface_ip = iface_ip;
1820 SMARTLIST_FOREACH(outgoing_addrs, void*, ip, tor_free(ip));
1821 smartlist_clear(outgoing_addrs);
1822 smartlist_add(outgoing_addrs, ip);
1823 /* Okay, now change our keys. */
1824 init_keys(); /* XXXX NM return value-- safe to ignore? */
1828 /** Process new bytes that have arrived on conn-\>inbuf.
1830 * This function just passes conn to the connection-specific
1831 * connection_*_process_inbuf() function. It also passes in
1832 * package_partial if wanted.
1834 static int
1835 connection_process_inbuf(connection_t *conn, int package_partial)
1837 tor_assert(conn);
1839 switch (conn->type) {
1840 case CONN_TYPE_OR:
1841 return connection_or_process_inbuf(conn);
1842 case CONN_TYPE_EXIT:
1843 case CONN_TYPE_AP:
1844 return connection_edge_process_inbuf(conn, package_partial);
1845 case CONN_TYPE_DIR:
1846 return connection_dir_process_inbuf(conn);
1847 case CONN_TYPE_DNSWORKER:
1848 return connection_dns_process_inbuf(conn);
1849 case CONN_TYPE_CPUWORKER:
1850 return connection_cpu_process_inbuf(conn);
1851 case CONN_TYPE_CONTROL:
1852 return connection_control_process_inbuf(conn);
1853 default:
1854 log_fn(LOG_WARN,"Bug: got unexpected conn type %d.", conn->type);
1855 tor_fragile_assert();
1856 return -1;
1860 /** We just finished flushing bytes from conn-\>outbuf, and there
1861 * are no more bytes remaining.
1863 * This function just passes conn to the connection-specific
1864 * connection_*_finished_flushing() function.
1866 static int
1867 connection_finished_flushing(connection_t *conn)
1869 tor_assert(conn);
1871 // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
1873 switch (conn->type) {
1874 case CONN_TYPE_OR:
1875 return connection_or_finished_flushing(conn);
1876 case CONN_TYPE_AP:
1877 case CONN_TYPE_EXIT:
1878 return connection_edge_finished_flushing(conn);
1879 case CONN_TYPE_DIR:
1880 return connection_dir_finished_flushing(conn);
1881 case CONN_TYPE_DNSWORKER:
1882 return connection_dns_finished_flushing(conn);
1883 case CONN_TYPE_CPUWORKER:
1884 return connection_cpu_finished_flushing(conn);
1885 case CONN_TYPE_CONTROL:
1886 return connection_control_finished_flushing(conn);
1887 default:
1888 log_fn(LOG_WARN,"Bug: got unexpected conn type %d.", conn->type);
1889 tor_fragile_assert();
1890 return -1;
1894 /** Called when our attempt to connect() to another server has just
1895 * succeeded.
1897 * This function just passes conn to the connection-specific
1898 * connection_*_finished_connecting() function.
1900 static int
1901 connection_finished_connecting(connection_t *conn)
1903 tor_assert(conn);
1904 switch (conn->type)
1906 case CONN_TYPE_OR:
1907 return connection_or_finished_connecting(conn);
1908 case CONN_TYPE_EXIT:
1909 return connection_edge_finished_connecting(conn);
1910 case CONN_TYPE_DIR:
1911 return connection_dir_finished_connecting(conn);
1912 default:
1913 log_fn(LOG_WARN,"Bug: got unexpected conn type %d.", conn->type);
1914 tor_fragile_assert();
1915 return -1;
1919 /** Callback: invoked when a connection reaches an EOF event. */
1920 static int
1921 connection_reached_eof(connection_t *conn)
1923 switch (conn->type) {
1924 case CONN_TYPE_OR:
1925 return connection_or_reached_eof(conn);
1926 case CONN_TYPE_AP:
1927 case CONN_TYPE_EXIT:
1928 return connection_edge_reached_eof(conn);
1929 case CONN_TYPE_DIR:
1930 return connection_dir_reached_eof(conn);
1931 case CONN_TYPE_DNSWORKER:
1932 return connection_dns_reached_eof(conn);
1933 case CONN_TYPE_CPUWORKER:
1934 return connection_cpu_reached_eof(conn);
1935 case CONN_TYPE_CONTROL:
1936 return connection_control_reached_eof(conn);
1937 default:
1938 log_fn(LOG_WARN,"Bug: got unexpected conn type %d.", conn->type);
1939 tor_fragile_assert();
1940 return -1;
1944 /** Verify that connection <b>conn</b> has all of its invariants
1945 * correct. Trigger an assert if anything is invalid.
1947 void
1948 assert_connection_ok(connection_t *conn, time_t now)
1950 tor_assert(conn);
1951 tor_assert(conn->magic == CONNECTION_MAGIC);
1952 tor_assert(conn->type >= _CONN_TYPE_MIN);
1953 tor_assert(conn->type <= _CONN_TYPE_MAX);
1955 if (conn->outbuf_flushlen > 0) {
1956 tor_assert(connection_is_writing(conn) || conn->wants_to_write);
1959 if (conn->hold_open_until_flushed)
1960 tor_assert(conn->marked_for_close);
1962 /* XXX check: wants_to_read, wants_to_write, s, poll_index,
1963 * marked_for_close. */
1965 /* buffers */
1966 if (!connection_is_listener(conn)) {
1967 assert_buf_ok(conn->inbuf);
1968 assert_buf_ok(conn->outbuf);
1971 /* XXX Fix this; no longer so.*/
1972 #if 0
1973 if (conn->type != CONN_TYPE_OR && conn->type != CONN_TYPE_DIR)
1974 tor_assert(!conn->pkey);
1975 /* pkey is set if we're a dir client, or if we're an OR in state OPEN
1976 * connected to another OR.
1978 #endif
1980 if (conn->type != CONN_TYPE_OR) {
1981 tor_assert(!conn->tls);
1982 } else {
1983 if (conn->state == OR_CONN_STATE_OPEN) {
1984 /* tor_assert(conn->bandwidth > 0); */
1985 /* the above isn't necessarily true: if we just did a TLS
1986 * handshake but we didn't recognize the other peer, or it
1987 * gave a bad cert/etc, then we won't have assigned bandwidth,
1988 * yet it will be open. -RD
1990 // tor_assert(conn->receiver_bucket >= 0);
1992 // tor_assert(conn->addr && conn->port);
1993 tor_assert(conn->address);
1994 if (conn->state > OR_CONN_STATE_PROXY_READING)
1995 tor_assert(conn->tls);
1998 if (! CONN_IS_EDGE(conn)) {
1999 tor_assert(!conn->stream_id);
2000 tor_assert(!conn->next_stream);
2001 tor_assert(!conn->cpath_layer);
2002 tor_assert(!conn->package_window);
2003 tor_assert(!conn->deliver_window);
2004 #if 0
2005 tor_assert(!conn->done_sending);
2006 tor_assert(!conn->done_receiving);
2007 #endif
2008 } else {
2009 /* XXX unchecked: package window, deliver window. */
2011 if (conn->type == CONN_TYPE_AP) {
2012 tor_assert(conn->socks_request);
2013 if (conn->state == AP_CONN_STATE_OPEN) {
2014 tor_assert(conn->socks_request->has_finished);
2015 if (!conn->marked_for_close) {
2016 tor_assert(conn->cpath_layer);
2017 assert_cpath_layer_ok(conn->cpath_layer);
2020 } else {
2021 tor_assert(!conn->socks_request);
2023 if (conn->type == CONN_TYPE_EXIT) {
2024 tor_assert(conn->purpose == EXIT_PURPOSE_CONNECT ||
2025 conn->purpose == EXIT_PURPOSE_RESOLVE);
2026 } else if (conn->type != CONN_TYPE_DIR) {
2027 tor_assert(!conn->purpose); /* only used for dir types currently */
2029 if (conn->type != CONN_TYPE_DIR) {
2030 tor_assert(!conn->requested_resource);
2033 switch (conn->type)
2035 case CONN_TYPE_OR_LISTENER:
2036 case CONN_TYPE_AP_LISTENER:
2037 case CONN_TYPE_DIR_LISTENER:
2038 case CONN_TYPE_CONTROL_LISTENER:
2039 tor_assert(conn->state == LISTENER_STATE_READY);
2040 break;
2041 case CONN_TYPE_OR:
2042 tor_assert(conn->state >= _OR_CONN_STATE_MIN);
2043 tor_assert(conn->state <= _OR_CONN_STATE_MAX);
2044 break;
2045 case CONN_TYPE_EXIT:
2046 tor_assert(conn->state >= _EXIT_CONN_STATE_MIN);
2047 tor_assert(conn->state <= _EXIT_CONN_STATE_MAX);
2048 break;
2049 case CONN_TYPE_AP:
2050 tor_assert(conn->state >= _AP_CONN_STATE_MIN);
2051 tor_assert(conn->state <= _AP_CONN_STATE_MAX);
2052 tor_assert(conn->socks_request);
2053 break;
2054 case CONN_TYPE_DIR:
2055 tor_assert(conn->state >= _DIR_CONN_STATE_MIN);
2056 tor_assert(conn->state <= _DIR_CONN_STATE_MAX);
2057 tor_assert(conn->purpose >= _DIR_PURPOSE_MIN);
2058 tor_assert(conn->purpose <= _DIR_PURPOSE_MAX);
2059 break;
2060 case CONN_TYPE_DNSWORKER:
2061 tor_assert(conn->state == DNSWORKER_STATE_IDLE ||
2062 conn->state == DNSWORKER_STATE_BUSY);
2063 break;
2064 case CONN_TYPE_CPUWORKER:
2065 tor_assert(conn->state >= _CPUWORKER_STATE_MIN);
2066 tor_assert(conn->state <= _CPUWORKER_STATE_MAX);
2067 break;
2068 case CONN_TYPE_CONTROL:
2069 tor_assert(conn->state >= _CONTROL_CONN_STATE_MIN);
2070 tor_assert(conn->state <= _CONTROL_CONN_STATE_MAX);
2071 break;
2072 default:
2073 tor_assert(0);