Change retry_listeners: when force is false, close and re-open a minimal set of liste...
[tor.git] / src / or / connection.c
blob21cdf2a447bcf2c72bcfa2b85b701cfb4f58e009
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 int 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);
28 /**************************************************************/
30 /**
31 * Return the human-readable name for the connection type <b>type</b>
33 const char *
34 conn_type_to_string(int type)
36 static char buf[64];
37 switch (type) {
38 case CONN_TYPE_OR_LISTENER: return "OR listener";
39 case CONN_TYPE_OR: return "OR";
40 case CONN_TYPE_EXIT: return "Exit";
41 case CONN_TYPE_AP_LISTENER: return "App listener";
42 case CONN_TYPE_AP: return "App";
43 case CONN_TYPE_DIR_LISTENER: return "Dir listener";
44 case CONN_TYPE_DIR: return "Dir";
45 case CONN_TYPE_DNSWORKER: return "DNS worker";
46 case CONN_TYPE_CPUWORKER: return "CPU worker";
47 case CONN_TYPE_CONTROL_LISTENER: return "Control listener";
48 case CONN_TYPE_CONTROL: return "Control";
49 default:
50 log_fn(LOG_WARN, "Bug: unknown connection type %d", type);
51 tor_snprintf(buf, sizeof(buf), "unknown [%d]", type);
52 return buf;
56 /**
57 * Return the human-readable name for the connection state <b>state</b>
58 * for the connection type <b>type</b>
60 const char *
61 conn_state_to_string(int type, int state)
63 static char buf[96];
64 switch (type) {
65 case CONN_TYPE_OR_LISTENER:
66 case CONN_TYPE_AP_LISTENER:
67 case CONN_TYPE_DIR_LISTENER:
68 case CONN_TYPE_CONTROL_LISTENER:
69 if (state == LISTENER_STATE_READY)
70 return "ready";
71 break;
72 case CONN_TYPE_OR:
73 switch (state) {
74 case OR_CONN_STATE_CONNECTING: return "connect()ing";
75 case OR_CONN_STATE_PROXY_FLUSHING: return "proxy flushing";
76 case OR_CONN_STATE_PROXY_READING: return "proxy reading";
77 case OR_CONN_STATE_HANDSHAKING: return "proxy reading";
78 case OR_CONN_STATE_OPEN: return "open";
80 break;
81 case CONN_TYPE_EXIT:
82 switch (state) {
83 case EXIT_CONN_STATE_RESOLVING: return "waiting for dest info";
84 case EXIT_CONN_STATE_CONNECTING: return "connecting";
85 case EXIT_CONN_STATE_OPEN: return "open";
86 case EXIT_CONN_STATE_RESOLVEFAILED: return "resolve failed";
88 break;
89 case CONN_TYPE_AP:
90 switch (state) {
91 case AP_CONN_STATE_SOCKS_WAIT: return "waiting for dest info";
92 case AP_CONN_STATE_RENDDESC_WAIT: return "waiting for rendezvous desc";
93 case AP_CONN_STATE_CONTROLLER_WAIT: return "waiting for controller";
94 case AP_CONN_STATE_CIRCUIT_WAIT: return "waiting for safe circuit";
95 case AP_CONN_STATE_CONNECT_WAIT: return "waiting for connect";
96 case AP_CONN_STATE_RESOLVE_WAIT: return "waiting for resolve";
97 case AP_CONN_STATE_OPEN: return "open";
99 break;
100 case CONN_TYPE_DIR:
101 switch (state) {
102 case DIR_CONN_STATE_CONNECTING: return "connecting";
103 case DIR_CONN_STATE_CLIENT_SENDING: return "client sending";
104 case DIR_CONN_STATE_CLIENT_READING: return "cleint reading";
105 case DIR_CONN_STATE_SERVER_COMMAND_WAIT: return "waiting for command";
106 case DIR_CONN_STATE_SERVER_WRITING: return "writing";
108 break;
109 case CONN_TYPE_DNSWORKER:
110 switch (state) {
111 case DNSWORKER_STATE_IDLE: return "idle";
112 case DNSWORKER_STATE_BUSY: return "busy";
114 break;
115 case CONN_TYPE_CPUWORKER:
116 switch (state) {
117 case CPUWORKER_STATE_IDLE: return "idle";
118 case CPUWORKER_STATE_BUSY_ONION: return "busy with onion";
120 break;
121 case CONN_TYPE_CONTROL:
122 switch (state) {
123 case CONTROL_CONN_STATE_OPEN_V0: return "open (protocol v0)";
124 case CONTROL_CONN_STATE_OPEN_V1: return "open (protocol v1)";
125 case CONTROL_CONN_STATE_NEEDAUTH_V0:
126 return "waiting for authentication (protocol unknown)";
127 case CONTROL_CONN_STATE_NEEDAUTH_V1:
128 return "waiting for authentication (protocol v1)";
130 break;
133 log_fn(LOG_WARN, "Bug: unknown connection state %d (type %d)", state, type);
134 tor_snprintf(buf, sizeof(buf),
135 "unknown state [%d] on unknown [%s] connection",
136 state, conn_type_to_string(type));
137 return buf;
140 /** Allocate space for a new connection_t. This function just initializes
141 * conn; you must call connection_add() to link it into the main array.
143 * Set conn-\>type to <b>type</b>. Set conn-\>s and conn-\>poll_index to
144 * -1 to signify they are not yet assigned.
146 * If conn is not a listener type, allocate buffers for it. If it's
147 * an AP type, allocate space to store the socks_request.
149 * Assign a pseudorandom next_circ_id between 0 and 2**15.
151 * Initialize conn's timestamps to now.
153 connection_t *
154 connection_new(int type)
156 static uint32_t n_connections_allocated = 0;
157 connection_t *conn;
158 time_t now = time(NULL);
160 conn = tor_malloc_zero(sizeof(connection_t));
161 conn->magic = CONNECTION_MAGIC;
162 conn->s = -1; /* give it a default of 'not used' */
163 conn->poll_index = -1; /* also default to 'not used' */
164 conn->global_identifier = n_connections_allocated++;
166 conn->type = type;
167 if (!connection_is_listener(conn)) { /* listeners never use their buf */
168 conn->inbuf = buf_new();
169 conn->outbuf = buf_new();
171 if (type == CONN_TYPE_AP) {
172 conn->socks_request = tor_malloc_zero(sizeof(socks_request_t));
175 conn->next_circ_id = crypto_pseudo_rand_int(1<<15);
177 conn->timestamp_created = now;
178 conn->timestamp_lastread = now;
179 conn->timestamp_lastwritten = now;
181 return conn;
184 /** Tell libevent that we don't care about <b>conn</b> any more. */
185 void
186 connection_unregister(connection_t *conn)
188 if (conn->read_event) {
189 if (event_del(conn->read_event))
190 log_fn(LOG_WARN, "Error removing read event for %d", conn->s);
191 tor_free(conn->read_event);
193 if (conn->write_event) {
194 if (event_del(conn->write_event))
195 log_fn(LOG_WARN, "Error removing write event for %d", conn->s);
196 tor_free(conn->write_event);
200 /** Deallocate memory used by <b>conn</b>. Deallocate its buffers if necessary,
201 * close its socket if necessary, and mark the directory as dirty if <b>conn</b>
202 * is an OR or OP connection.
204 static void
205 _connection_free(connection_t *conn)
207 tor_assert(conn->magic == CONNECTION_MAGIC);
209 if (!connection_is_listener(conn)) {
210 buf_free(conn->inbuf);
211 buf_free(conn->outbuf);
213 tor_free(conn->address);
214 tor_free(conn->chosen_exit_name);
216 if (connection_speaks_cells(conn)) {
217 if (conn->tls) {
218 tor_tls_free(conn->tls);
219 conn->tls = NULL;
223 if (conn->identity_pkey)
224 crypto_free_pk_env(conn->identity_pkey);
225 tor_free(conn->nickname);
226 tor_free(conn->socks_request);
227 tor_free(conn->incoming_cmd);
228 tor_free(conn->read_event); /* Probably already freed by connection_free. */
229 tor_free(conn->write_event); /* Probably already freed by connection_free. */
231 if (conn->s >= 0) {
232 log_fn(LOG_INFO,"closing fd %d.",conn->s);
233 tor_close_socket(conn->s);
236 memset(conn, 0xAA, sizeof(connection_t)); /* poison memory */
237 tor_free(conn);
240 /** Make sure <b>conn</b> isn't in any of the global conn lists; then free it.
242 void
243 connection_free(connection_t *conn)
245 tor_assert(conn);
246 tor_assert(!connection_is_on_closeable_list(conn));
247 tor_assert(!connection_in_array(conn));
248 if (connection_speaks_cells(conn)) {
249 if (conn->state == OR_CONN_STATE_OPEN)
250 directory_set_dirty();
252 connection_unregister(conn);
253 _connection_free(conn);
256 /** Call _connection_free() on every connection in our array.
257 * This is used by cpuworkers and dnsworkers when they fork,
258 * so they don't keep resources held open (especially sockets).
260 * Don't do the checks in connection_free(), because they will
261 * fail.
263 void
264 connection_free_all(void)
266 int i, n;
267 connection_t **carray;
269 get_connection_array(&carray,&n);
270 for (i=0;i<n;i++)
271 _connection_free(carray[i]);
274 /** Do any cleanup needed:
275 * - Directory conns that failed to fetch a rendezvous descriptor
276 * need to inform pending rendezvous streams.
277 * - OR conns need to call rep_hist_note_*() to record status.
278 * - AP conns need to send a socks reject if necessary.
279 * - Exit conns need to call connection_dns_remove() if necessary.
280 * - AP and Exit conns need to send an end cell if they can.
281 * - DNS conns need to fail any resolves that are pending on them.
283 void
284 connection_about_to_close_connection(connection_t *conn)
286 circuit_t *circ;
288 assert(conn->marked_for_close);
290 if (CONN_IS_EDGE(conn)) {
291 if (!conn->has_sent_end) {
292 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);
293 tor_fragile_assert();
297 switch (conn->type) {
298 case CONN_TYPE_DIR:
299 if (conn->state == DIR_CONN_STATE_CONNECTING) {
300 /* it's a directory server and connecting failed: forget about
301 this router */
302 connection_dir_connect_failed(conn);
304 if (conn->purpose == DIR_PURPOSE_FETCH_RENDDESC)
305 rend_client_desc_here(conn->rend_query); /* give it a try */
306 break;
307 case CONN_TYPE_OR:
308 /* Remember why we're closing this connection. */
309 if (conn->state != OR_CONN_STATE_OPEN) {
310 if (connection_or_nonopen_was_started_here(conn)) {
311 rep_hist_note_connect_failed(conn->identity_digest, time(NULL));
312 control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED);
314 } else if (conn->hold_open_until_flushed) {
315 /* XXXX009 We used to have an arg that told us whether we closed the
316 * connection on purpose or not. Can we use hold_open_until_flushed
317 * instead? We only set it when we are intentionally closing a
318 * connection. -NM
320 * (Of course, now things we set to close which expire rather than
321 * flushing still get noted as dead, not disconnected. But this is an
322 * improvement. -NM
324 rep_hist_note_disconnect(conn->identity_digest, time(NULL));
325 control_event_or_conn_status(conn, OR_CONN_EVENT_CLOSED);
326 } else if (conn->identity_digest) {
327 rep_hist_note_connection_died(conn->identity_digest, time(NULL));
328 control_event_or_conn_status(conn, OR_CONN_EVENT_CLOSED);
330 break;
331 case CONN_TYPE_AP:
332 if (conn->socks_request->has_finished == 0) {
333 /* since conn gets removed right after this function finishes,
334 * there's no point trying to send back a reply at this point. */
335 log_fn(LOG_WARN,"Bug: Closing stream (marked at %s:%d) without sending back a socks reply.",
336 conn->marked_for_close_file, conn->marked_for_close);
337 } else {
338 control_event_stream_status(conn, STREAM_EVENT_CLOSED);
340 break;
341 case CONN_TYPE_EXIT:
342 if (conn->state == EXIT_CONN_STATE_RESOLVING) {
343 circ = circuit_get_by_edge_conn(conn);
344 if (circ)
345 circuit_detach_stream(circ, conn);
346 connection_dns_remove(conn);
348 break;
349 case CONN_TYPE_DNSWORKER:
350 if (conn->state == DNSWORKER_STATE_BUSY) {
351 dns_cancel_pending_resolve(conn->address);
353 break;
357 /** Close the underlying socket for <b>conn</b>, so we don't try to
358 * flush it. Must be used in conjunction with (right before)
359 * connection_mark_for_close().
361 void
362 connection_close_immediate(connection_t *conn)
364 assert_connection_ok(conn,0);
365 if (conn->s < 0) {
366 log_fn(LOG_WARN,"Bug: Attempt to close already-closed connection.");
367 tor_fragile_assert();
368 return;
370 if (conn->outbuf_flushlen) {
371 log_fn(LOG_INFO,"fd %d, type %s, state %s, %d bytes on outbuf.",
372 conn->s, conn_type_to_string(conn->type),
373 conn_state_to_string(conn->type, conn->state),
374 (int)conn->outbuf_flushlen);
377 connection_unregister(conn);
379 tor_close_socket(conn->s);
380 conn->s = -1;
381 if (!connection_is_listener(conn)) {
382 buf_clear(conn->outbuf);
383 conn->outbuf_flushlen = 0;
387 /** Mark <b>conn</b> to be closed next time we loop through
388 * conn_close_if_marked() in main.c. */
389 void
390 _connection_mark_for_close(connection_t *conn, int line, const char *file)
392 assert_connection_ok(conn,0);
393 tor_assert(line);
394 tor_assert(file);
396 if (conn->marked_for_close) {
397 log(LOG_WARN, "Duplicate call to connection_mark_for_close at %s:%d"
398 " (first at %s:%d)", file, line, conn->marked_for_close_file,
399 conn->marked_for_close);
400 tor_fragile_assert();
401 return;
404 conn->marked_for_close = line;
405 conn->marked_for_close_file = file;
406 add_connection_to_closeable_list(conn);
408 /* in case we're going to be held-open-til-flushed, reset
409 * the number of seconds since last successful write, so
410 * we get our whole 15 seconds */
411 conn->timestamp_lastwritten = time(NULL);
414 /** Find each connection that has hold_open_until_flushed set to
415 * 1 but hasn't written in the past 15 seconds, and set
416 * hold_open_until_flushed to 0. This means it will get cleaned
417 * up in the next loop through close_if_marked() in main.c.
419 void
420 connection_expire_held_open(void)
422 connection_t **carray, *conn;
423 int n, i;
424 time_t now;
426 now = time(NULL);
428 get_connection_array(&carray, &n);
429 for (i = 0; i < n; ++i) {
430 conn = carray[i];
431 /* If we've been holding the connection open, but we haven't written
432 * for 15 seconds...
434 if (conn->hold_open_until_flushed) {
435 tor_assert(conn->marked_for_close);
436 if (now - conn->timestamp_lastwritten >= 15) {
437 log_fn(LOG_NOTICE,"Giving up on marked_for_close conn that's been flushing for 15s (fd %d, type %s, state %s).",
438 conn->s, conn_type_to_string(conn->type),
439 conn_state_to_string(conn->type, conn->state));
440 conn->hold_open_until_flushed = 0;
446 /** Bind a new non-blocking socket listening to
447 * <b>bindaddress</b>:<b>bindport</b>, and add this new connection
448 * (of type <b>type</b>) to the connection array.
450 * If <b>bindaddress</b> includes a port, we bind on that port; otherwise, we
451 * use bindport.
453 static int
454 connection_create_listener(const char *bindaddress, uint16_t bindport, int type)
456 struct sockaddr_in bindaddr; /* where to bind */
457 connection_t *conn;
458 uint16_t usePort;
459 uint32_t addr;
460 int s; /* the socket we're going to make */
461 #ifndef MS_WINDOWS
462 int one=1;
463 #endif
465 memset(&bindaddr,0,sizeof(struct sockaddr_in));
466 if (parse_addr_port(bindaddress, NULL, &addr, &usePort)<0) {
467 log_fn(LOG_WARN, "Error parsing/resolving BindAddress %s",bindaddress);
468 return -1;
471 if (usePort==0)
472 usePort = bindport;
473 bindaddr.sin_addr.s_addr = htonl(addr);
474 bindaddr.sin_family = AF_INET;
475 bindaddr.sin_port = htons((uint16_t) usePort);
477 s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
478 if (s < 0) {
479 log_fn(LOG_WARN,"Socket creation failed.");
480 return -1;
481 } else if (!SOCKET_IS_POLLABLE(s)) {
482 log_fn(LOG_WARN,"Too many connections; can't create pollable listener.");
483 tor_close_socket(s);
484 return -1;
487 #ifndef MS_WINDOWS
488 /* REUSEADDR on normal places means you can rebind to the port
489 * right after somebody else has let it go. But REUSEADDR on win32
490 * means you can bind to the port _even when somebody else
491 * already has it bound_. So, don't do that on Win32. */
492 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*) &one, sizeof(one));
493 #endif
495 if (bind(s,(struct sockaddr *)&bindaddr,sizeof(bindaddr)) < 0) {
496 log_fn(LOG_WARN,"Could not bind to port %u: %s",usePort,
497 tor_socket_strerror(tor_socket_errno(s)));
498 return -1;
501 if (listen(s,SOMAXCONN) < 0) {
502 log_fn(LOG_WARN,"Could not listen on port %u: %s",usePort,
503 tor_socket_strerror(tor_socket_errno(s)));
504 return -1;
507 set_socket_nonblocking(s);
509 conn = connection_new(type);
510 conn->s = s;
511 conn->address = tor_strdup(bindaddress);
512 conn->port = usePort;
514 if (connection_add(conn) < 0) { /* no space, forget it */
515 log_fn(LOG_WARN,"connection_add failed. Giving up.");
516 connection_free(conn);
517 return -1;
520 log_fn(LOG_DEBUG,"%s listening on port %u.",conn_type_to_string(type), usePort);
522 conn->state = LISTENER_STATE_READY;
523 connection_start_reading(conn);
525 return 0;
528 /** Do basic sanity checking on a newly received socket. Return 0
529 * if it looks ok, else return -1. */
530 static int
531 check_sockaddr_in(struct sockaddr *sa, int len, int level)
533 int ok = 1;
534 struct sockaddr_in *sin=(struct sockaddr_in*)sa;
536 if (len != sizeof(struct sockaddr_in)) {
537 log_fn(level, "Length of address not as expected: %d vs %d",
538 len,(int)sizeof(struct sockaddr_in));
539 ok = 0;
541 if (sa->sa_family != AF_INET) {
542 log_fn(level, "Family of address not as expected: %d vs %d",
543 sa->sa_family, AF_INET);
544 ok = 0;
546 if (sin->sin_addr.s_addr == 0 || sin->sin_port == 0) {
547 log_fn(level, "Address for new connection has address/port equal to zero.");
548 ok = 0;
550 return ok ? 0 : -1;
553 /** The listener connection <b>conn</b> told poll() it wanted to read.
554 * Call accept() on conn-\>s, and add the new connection if necessary.
556 static int
557 connection_handle_listener_read(connection_t *conn, int new_type)
559 int news; /* the new socket */
560 connection_t *newconn;
561 /* information about the remote peer when connecting to other routers */
562 struct sockaddr_in remote;
563 char addrbuf[256];
564 /* length of the remote address. Must be whatever accept() needs. */
565 socklen_t remotelen = 256;
566 char tmpbuf[INET_NTOA_BUF_LEN];
567 tor_assert((size_t)remotelen >= sizeof(struct sockaddr_in));
568 memset(addrbuf, 0, sizeof(addrbuf));
570 news = accept(conn->s,(struct sockaddr *)&addrbuf,&remotelen);
571 if (!SOCKET_IS_POLLABLE(news)) {
572 /* accept() error, or too many conns to poll */
573 int e;
574 if (news>=0) {
575 /* Too many conns to poll. */
576 log_fn(LOG_WARN,"Too many connections; couldn't accept connection.");
577 tor_close_socket(news);
578 return 0;
580 e = tor_socket_errno(conn->s);
581 if (ERRNO_IS_ACCEPT_EAGAIN(e)) {
582 return 0; /* he hung up before we could accept(). that's fine. */
583 } else if (ERRNO_IS_ACCEPT_RESOURCE_LIMIT(e)) {
584 log_fn(LOG_NOTICE,"accept failed: %s. Dropping incoming connection.",
585 tor_socket_strerror(e));
586 return 0;
588 /* else there was a real error. */
589 log_fn(LOG_WARN,"accept() failed: %s. Closing listener.",
590 tor_socket_strerror(e));
591 connection_mark_for_close(conn);
592 return -1;
594 log(LOG_INFO,"Connection accepted on socket %d (child of fd %d).",news, conn->s);
596 set_socket_nonblocking(news);
598 if (check_sockaddr_in((struct sockaddr*)addrbuf, remotelen, LOG_INFO)<0) {
599 log_fn(LOG_INFO, "accept() returned a strange address; trying getsockname().");
600 remotelen=256;
601 memset(addrbuf, 0, sizeof(addrbuf));
602 if (getsockname(news, (struct sockaddr*)addrbuf, &remotelen)<0) {
603 log_fn(LOG_WARN, "getsockname() failed.");
604 } else {
605 if (check_sockaddr_in((struct sockaddr*)addrbuf, remotelen, LOG_WARN)<0) {
606 log_fn(LOG_WARN,"Something's wrong with this conn. Closing it.");
607 tor_close_socket(news);
608 return 0;
612 memcpy(&remote, addrbuf, sizeof(struct sockaddr_in));
614 /* process entrance policies here, before we even create the connection */
615 if (new_type == CONN_TYPE_AP) {
616 /* check sockspolicy to see if we should accept it */
617 if (socks_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
618 tor_inet_ntoa(&remote.sin_addr, tmpbuf, sizeof(tmpbuf));
619 log_fn(LOG_NOTICE,"Denying socks connection from untrusted address %s.",
620 tmpbuf);
621 tor_close_socket(news);
622 return 0;
625 if (new_type == CONN_TYPE_DIR) {
626 /* check dirpolicy to see if we should accept it */
627 if (dir_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
628 tor_inet_ntoa(&remote.sin_addr, tmpbuf, sizeof(tmpbuf));
629 log_fn(LOG_NOTICE,"Denying dir connection from address %s.",
630 tmpbuf);
631 tor_close_socket(news);
632 return 0;
636 newconn = connection_new(new_type);
637 newconn->s = news;
639 /* remember the remote address */
640 newconn->address = tor_malloc(INET_NTOA_BUF_LEN);
641 tor_inet_ntoa(&remote.sin_addr, newconn->address, INET_NTOA_BUF_LEN);
642 newconn->addr = ntohl(remote.sin_addr.s_addr);
643 newconn->port = ntohs(remote.sin_port);
645 if (connection_add(newconn) < 0) { /* no space, forget it */
646 connection_free(newconn);
647 return 0; /* no need to tear down the parent */
650 if (connection_init_accepted_conn(newconn) < 0) {
651 connection_mark_for_close(newconn);
652 return 0;
654 return 0;
657 /** Initialize states for newly accepted connection <b>conn</b>.
658 * If conn is an OR, start the tls handshake.
660 static int
661 connection_init_accepted_conn(connection_t *conn)
663 connection_start_reading(conn);
665 switch (conn->type) {
666 case CONN_TYPE_OR:
667 return connection_tls_start_handshake(conn, 1);
668 case CONN_TYPE_AP:
669 conn->state = AP_CONN_STATE_SOCKS_WAIT;
670 break;
671 case CONN_TYPE_DIR:
672 conn->purpose = DIR_PURPOSE_SERVER;
673 conn->state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
674 break;
675 case CONN_TYPE_CONTROL:
676 conn->state = CONTROL_CONN_STATE_NEEDAUTH_V0;
677 break;
679 return 0;
682 /** Take conn, make a nonblocking socket; try to connect to
683 * addr:port (they arrive in *host order*). If fail, return -1. Else
684 * assign s to conn-\>s: if connected return 1, if EAGAIN return 0.
686 * address is used to make the logs useful.
688 * On success, add conn to the list of polled connections.
691 connection_connect(connection_t *conn, char *address,
692 uint32_t addr, uint16_t port)
694 int s;
695 struct sockaddr_in dest_addr;
696 or_options_t *options = get_options();
698 s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
699 if (s < 0) {
700 log_fn(LOG_WARN,"Error creating network socket: %s",
701 tor_socket_strerror(tor_socket_errno(-1)));
702 return -1;
703 } else if (!SOCKET_IS_POLLABLE(s)) {
704 log_fn(LOG_WARN,
705 "Too many connections; can't create pollable connection to %s",
706 safe_str(address));
707 tor_close_socket(s);
708 return -1;
711 if (options->OutboundBindAddress) {
712 struct sockaddr_in ext_addr;
714 memset(&ext_addr, 0, sizeof(ext_addr));
715 ext_addr.sin_family = AF_INET;
716 ext_addr.sin_port = 0;
717 if (!tor_inet_aton(options->OutboundBindAddress, &ext_addr.sin_addr)) {
718 log_fn(LOG_WARN,"Outbound bind address '%s' didn't parse. Ignoring.",
719 options->OutboundBindAddress);
720 } else {
721 if (bind(s, (struct sockaddr*)&ext_addr, sizeof(ext_addr)) < 0) {
722 log_fn(LOG_WARN,"Error binding network socket: %s",
723 tor_socket_strerror(tor_socket_errno(s)));
724 return -1;
729 set_socket_nonblocking(s);
731 memset(&dest_addr,0,sizeof(dest_addr));
732 dest_addr.sin_family = AF_INET;
733 dest_addr.sin_port = htons(port);
734 dest_addr.sin_addr.s_addr = htonl(addr);
736 log_fn(LOG_DEBUG,"Connecting to %s:%u.",safe_str(address),port);
738 if (connect(s,(struct sockaddr *)&dest_addr,sizeof(dest_addr)) < 0) {
739 int e = tor_socket_errno(s);
740 if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
741 /* yuck. kill it. */
742 log_fn(LOG_INFO,"Connect() to %s:%u failed: %s",safe_str(address),port,
743 tor_socket_strerror(e));
744 tor_close_socket(s);
745 return -1;
746 } else {
747 /* it's in progress. set state appropriately and return. */
748 conn->s = s;
749 if (connection_add(conn) < 0) /* no space, forget it */
750 return -1;
751 log_fn(LOG_DEBUG,"connect in progress, socket %d.",s);
752 return 0;
756 /* it succeeded. we're connected. */
757 log_fn(LOG_INFO,"Connection to %s:%u established.",safe_str(address),port);
758 conn->s = s;
759 if (connection_add(conn) < 0) /* no space, forget it */
760 return -1;
761 return 1;
765 * Launch any configured listener connections of type <b>type</b>. (A
766 * listener is configured if <b>port_option</b> is non-zero. If any
767 * BindAddress configuration options are given in <b>cfg</b>, create a
768 * connection binding to each one. Otherwise, create a single
769 * connection binding to the address <b>default_addr</b>.)
771 * If <b>force</b> is true, close and re-open all listener connections.
772 * Otherwise, only relaunch the listeners of this type if the number of
773 * existing connections is not as configured (e.g., because one died),
774 * or if the existing connections do not match those configured.
776 static int
777 retry_listeners(int type, struct config_line_t *cfg,
778 int port_option, const char *default_addr, int force)
780 struct smartlist_t *launch = smartlist_create();
781 int free_launch_elts = 1;
782 struct config_line_t *c;
783 int n_conn, i;
784 connection_t *conn;
785 connection_t **carray;
786 struct config_line_t *line;
788 if (cfg && port_option) {
789 for (c = cfg; c; c = c->next) {
790 smartlist_add(launch, c);
792 free_launch_elts = 0;
793 } else if (port_option) {
794 line = tor_malloc_zero(sizeof(struct config_line_t));
795 line->key = tor_strdup("");
796 line->value = tor_strdup(default_addr);
797 smartlist_add(launch, line);
800 get_connection_array(&carray,&n_conn);
801 for (i=0; i < n_conn; ++i) {
802 conn = carray[i];
803 if (conn->type != type || conn->marked_for_close)
804 continue;
805 if (force) {
806 /* It's a listener, and we're relaunching all listeners of this
807 * type. Close this one. */
808 log_fn(LOG_NOTICE, "Closing listener on %s:%d", conn->address, conn->port);
809 connection_close_immediate(conn);
810 connection_mark_for_close(conn);
811 continue;
813 /* Okay, so this is a listener. Is it configured? */
814 line = NULL;
815 SMARTLIST_FOREACH(launch, struct config_line_t *, wanted,
817 char *addr;
818 uint16_t port;
819 if (! parse_addr_port(wanted->value, &addr, NULL, &port)) {
820 if (! port)
821 port = port_option;
822 if (port == conn->port && !strcasecmp(addr, conn->address)) {
823 line = wanted;
824 break;
828 if (! line) {
829 /* This one isn't configured. Close it. */
830 log_fn(LOG_NOTICE, "Closing listener on %s:%d", conn->address, conn->port);
831 connection_close_immediate(conn);
832 connection_mark_for_close(conn);
833 } else {
834 /* It's configured; we don't need to launch it. */
835 log_fn(LOG_INFO, "Already have listener on %s:%d",conn->address,conn->port);
836 smartlist_remove(launch, line);
840 /* Now open all the listeners that are configured but not opened. */
841 i = 0;
842 SMARTLIST_FOREACH(launch, struct config_line_t *, cfg,
844 log_fn(LOG_NOTICE, "Opening listener on %s:%d", cfg->value, port_option);
845 if (connection_create_listener(cfg->value, (uint16_t) port_option,
846 type)<0)
847 i = -1;
850 if (free_launch_elts) {
851 SMARTLIST_FOREACH(launch, struct config_line_t *, cfg,
852 config_free_lines(cfg));
854 smartlist_free(launch);
856 return i;
859 /** (Re)launch listeners for each port you should have open. If
860 * <b>force</b> is true, close and relaunch all listeners. If <b>force</b>
861 * is false, then only relaunch listeners when we have the wrong number of
862 * connections for a given type.
865 retry_all_listeners(int force)
867 or_options_t *options = get_options();
869 if (server_mode(options) &&
870 retry_listeners(CONN_TYPE_OR_LISTENER, options->ORBindAddress,
871 options->ORPort, "0.0.0.0", force)<0)
872 return -1;
873 if (retry_listeners(CONN_TYPE_DIR_LISTENER, options->DirBindAddress,
874 options->DirPort, "0.0.0.0", force)<0)
875 return -1;
876 if (retry_listeners(CONN_TYPE_AP_LISTENER, options->SocksBindAddress,
877 options->SocksPort, "127.0.0.1", force)<0)
878 return -1;
879 if (retry_listeners(CONN_TYPE_CONTROL_LISTENER, NULL,
880 options->ControlPort, "127.0.0.1", force)<0)
881 return -1;
883 return 0;
886 extern int global_read_bucket, global_write_bucket;
888 /** How many bytes at most can we read onto this connection? */
889 static int
890 connection_bucket_read_limit(connection_t *conn)
892 int at_most;
894 /* do a rudimentary round-robin so one circuit can't hog a connection */
895 if (connection_speaks_cells(conn)) {
896 at_most = 32*(CELL_NETWORK_SIZE);
897 } else {
898 at_most = 32*(RELAY_PAYLOAD_SIZE);
901 if (at_most > global_read_bucket)
902 at_most = global_read_bucket;
904 if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN)
905 if (at_most > conn->receiver_bucket)
906 at_most = conn->receiver_bucket;
908 if (at_most < 0)
909 return 0;
910 return at_most;
913 /** We just read num_read onto conn. Decrement buckets appropriately. */
914 static void
915 connection_read_bucket_decrement(connection_t *conn, int num_read)
917 global_read_bucket -= num_read; //tor_assert(global_read_bucket >= 0);
918 if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
919 conn->receiver_bucket -= num_read; //tor_assert(conn->receiver_bucket >= 0);
923 /** DOCDOC */
924 static void
925 connection_consider_empty_buckets(connection_t *conn)
927 if (global_read_bucket <= 0) {
928 log_fn(LOG_DEBUG,"global bucket exhausted. Pausing.");
929 conn->wants_to_read = 1;
930 connection_stop_reading(conn);
931 return;
933 if (connection_speaks_cells(conn) &&
934 conn->state == OR_CONN_STATE_OPEN &&
935 conn->receiver_bucket <= 0) {
936 log_fn(LOG_DEBUG,"receiver bucket exhausted. Pausing.");
937 conn->wants_to_read = 1;
938 connection_stop_reading(conn);
942 /** Initialize the global read bucket to options->BandwidthBurst,
943 * and current_time to the current time. */
944 void
945 connection_bucket_init(void)
947 or_options_t *options = get_options();
948 global_read_bucket = (int)options->BandwidthBurst; /* start it at max traffic */
949 global_write_bucket = (int)options->BandwidthBurst; /* start it at max traffic */
952 /** A second has rolled over; increment buckets appropriately. */
953 void
954 connection_bucket_refill(struct timeval *now)
956 int i, n;
957 connection_t *conn;
958 connection_t **carray;
959 or_options_t *options = get_options();
961 /* refill the global buckets */
962 if (global_read_bucket < (int)options->BandwidthBurst) {
963 global_read_bucket += (int)options->BandwidthRate;
964 log_fn(LOG_DEBUG,"global_read_bucket now %d.", global_read_bucket);
966 if (global_write_bucket < (int)options->BandwidthBurst) {
967 global_write_bucket += (int)options->BandwidthRate;
968 log_fn(LOG_DEBUG,"global_write_bucket now %d.", global_write_bucket);
971 /* refill the per-connection buckets */
972 get_connection_array(&carray,&n);
973 for (i=0;i<n;i++) {
974 conn = carray[i];
976 if (connection_receiver_bucket_should_increase(conn)) {
977 conn->receiver_bucket = conn->bandwidth;
978 //log_fn(LOG_DEBUG,"Receiver bucket %d now %d.", i, conn->receiver_bucket);
981 if (conn->wants_to_read == 1 /* it's marked to turn reading back on now */
982 && global_read_bucket > 0 /* and we're allowed to read */
983 && global_write_bucket > 0 /* and we're allowed to write (XXXX,
984 * not the best place to check this.) */
985 && (!connection_speaks_cells(conn) ||
986 conn->state != OR_CONN_STATE_OPEN ||
987 conn->receiver_bucket > 0)) {
988 /* and either a non-cell conn or a cell conn with non-empty bucket */
989 log_fn(LOG_DEBUG,"waking up conn (fd %d)",conn->s);
990 conn->wants_to_read = 0;
991 connection_start_reading(conn);
992 if (conn->wants_to_write == 1) {
993 conn->wants_to_write = 0;
994 connection_start_writing(conn);
1000 /** Is the receiver bucket for connection <b>conn</b> low enough that we
1001 * should add another pile of tokens to it?
1003 static int
1004 connection_receiver_bucket_should_increase(connection_t *conn)
1006 tor_assert(conn);
1008 if (!connection_speaks_cells(conn))
1009 return 0; /* edge connections don't use receiver_buckets */
1010 if (conn->state != OR_CONN_STATE_OPEN)
1011 return 0; /* only open connections play the rate limiting game */
1013 if (conn->receiver_bucket >= conn->bandwidth)
1014 return 0;
1016 return 1;
1019 /** Read bytes from conn-\>s and process them.
1021 * This function gets called from conn_read() in main.c, either
1022 * when poll() has declared that conn wants to read, or (for OR conns)
1023 * when there are pending TLS bytes.
1025 * It calls connection_read_to_buf() to bring in any new bytes,
1026 * and then calls connection_process_inbuf() to process them.
1028 * Mark the connection and return -1 if you want to close it, else
1029 * return 0.
1032 connection_handle_read(connection_t *conn)
1034 int max_to_read=-1, try_to_read;
1036 if (conn->marked_for_close)
1037 return 0; /* do nothing */
1039 conn->timestamp_lastread = time(NULL);
1041 switch (conn->type) {
1042 case CONN_TYPE_OR_LISTENER:
1043 return connection_handle_listener_read(conn, CONN_TYPE_OR);
1044 case CONN_TYPE_AP_LISTENER:
1045 return connection_handle_listener_read(conn, CONN_TYPE_AP);
1046 case CONN_TYPE_DIR_LISTENER:
1047 return connection_handle_listener_read(conn, CONN_TYPE_DIR);
1048 case CONN_TYPE_CONTROL_LISTENER:
1049 return connection_handle_listener_read(conn, CONN_TYPE_CONTROL);
1052 loop_again:
1053 try_to_read = max_to_read;
1054 tor_assert(!conn->marked_for_close);
1055 if (connection_read_to_buf(conn, &max_to_read) < 0) {
1056 /* There's a read error; kill the connection.*/
1057 connection_close_immediate(conn); /* Don't flush; connection is dead. */
1058 if (CONN_IS_EDGE(conn)) {
1059 connection_edge_end_errno(conn, conn->cpath_layer);
1060 if (conn->socks_request) /* broken, so don't send a socks reply back */
1061 conn->socks_request->has_finished = 1;
1063 connection_mark_for_close(conn);
1064 return -1;
1066 if (CONN_IS_EDGE(conn) &&
1067 try_to_read != max_to_read) {
1068 /* instruct it not to try to package partial cells. */
1069 if (connection_process_inbuf(conn, 0) < 0) {
1070 return -1;
1072 if (!conn->marked_for_close &&
1073 connection_is_reading(conn) &&
1074 !conn->inbuf_reached_eof &&
1075 max_to_read > 0)
1076 goto loop_again; /* try reading again, in case more is here now */
1078 /* one last try, packaging partial cells and all. */
1079 if (!conn->marked_for_close &&
1080 connection_process_inbuf(conn, 1) < 0) {
1081 return -1;
1083 if (!conn->marked_for_close &&
1084 conn->inbuf_reached_eof &&
1085 connection_reached_eof(conn) < 0) {
1086 return -1;
1088 return 0;
1091 /** Pull in new bytes from conn-\>s onto conn-\>inbuf, either
1092 * directly or via TLS. Reduce the token buckets by the number of
1093 * bytes read.
1095 * If *max_to_read is -1, then decide it ourselves, else go with the
1096 * value passed to us. When returning, if it's changed, subtract the
1097 * number of bytes we read from *max_to_read.
1099 * Return -1 if we want to break conn, else return 0.
1101 static int
1102 connection_read_to_buf(connection_t *conn, int *max_to_read)
1104 int result, at_most = *max_to_read;
1105 size_t bytes_in_buf, more_to_read;
1107 if (at_most == -1) { /* we need to initialize it */
1108 /* how many bytes are we allowed to read? */
1109 at_most = connection_bucket_read_limit(conn);
1112 bytes_in_buf = buf_capacity(conn->inbuf) - buf_datalen(conn->inbuf);
1113 again:
1114 if ((size_t)at_most > bytes_in_buf && bytes_in_buf >= 1024) {
1115 more_to_read = at_most - bytes_in_buf;
1116 at_most = bytes_in_buf;
1117 } else {
1118 more_to_read = 0;
1121 if (connection_speaks_cells(conn) && conn->state > OR_CONN_STATE_PROXY_READING) {
1122 int pending;
1123 if (conn->state == OR_CONN_STATE_HANDSHAKING) {
1124 /* continue handshaking even if global token bucket is empty */
1125 return connection_tls_continue_handshake(conn);
1128 log_fn(LOG_DEBUG,"%d: starting, inbuf_datalen %d (%d pending in tls object). at_most %d.",
1129 conn->s,(int)buf_datalen(conn->inbuf),tor_tls_get_pending_bytes(conn->tls), at_most);
1131 /* else open, or closing */
1132 result = read_to_buf_tls(conn->tls, at_most, conn->inbuf);
1134 switch (result) {
1135 case TOR_TLS_CLOSE:
1136 log_fn(LOG_INFO,"TLS connection closed on read. Closing. (Nickname %s, address %s",
1137 conn->nickname ? conn->nickname : "not set", conn->address);
1138 return -1;
1139 case TOR_TLS_ERROR:
1140 log_fn(LOG_INFO,"tls error. breaking (nickname %s, address %s).",
1141 conn->nickname ? conn->nickname : "not set", conn->address);
1142 return -1;
1143 case TOR_TLS_WANTWRITE:
1144 connection_start_writing(conn);
1145 return 0;
1146 case TOR_TLS_WANTREAD: /* we're already reading */
1147 case TOR_TLS_DONE: /* no data read, so nothing to process */
1148 result = 0;
1149 break; /* so we call bucket_decrement below */
1150 default:
1151 break;
1153 pending = tor_tls_get_pending_bytes(conn->tls);
1154 if (pending) {
1155 /* XXXX If we have any pending bytes, read them now. This *can*
1156 * take us over our read allotment, but really we shouldn't be
1157 * believing that SSL bytes are the same as TCP bytes anyway. */
1158 int r2 = read_to_buf_tls(conn->tls, pending, conn->inbuf);
1159 if (r2<0) {
1160 log_fn(LOG_WARN, "Bug: apparently, reading pending bytes can fail.");
1161 return -1;
1162 } else {
1163 result += r2;
1167 } else {
1168 result = read_to_buf(conn->s, at_most, conn->inbuf,
1169 &conn->inbuf_reached_eof);
1171 // log_fn(LOG_DEBUG,"read_to_buf returned %d.",read_result);
1173 if (result < 0)
1174 return -1;
1177 if (result > 0) { /* change *max_to_read */
1178 *max_to_read = at_most - result;
1181 if (result > 0 && !is_local_IP(conn->addr)) { /* remember it */
1182 rep_hist_note_bytes_read(result, time(NULL));
1183 connection_read_bucket_decrement(conn, result);
1186 if (more_to_read && result == at_most) {
1187 bytes_in_buf = buf_capacity(conn->inbuf) - buf_datalen(conn->inbuf);
1188 tor_assert(bytes_in_buf < 1024);
1189 at_most = more_to_read;
1190 goto again;
1193 /* Call even if result is 0, since the global read bucket may
1194 * have reached 0 on a different conn, and this guy needs to
1195 * know to stop reading. */
1196 connection_consider_empty_buckets(conn);
1198 return 0;
1201 /** A pass-through to fetch_from_buf. */
1203 connection_fetch_from_buf(char *string, size_t len, connection_t *conn)
1205 return fetch_from_buf(string, len, conn->inbuf);
1208 /** Return conn-\>outbuf_flushlen: how many bytes conn wants to flush
1209 * from its outbuf. */
1211 connection_wants_to_flush(connection_t *conn)
1213 return conn->outbuf_flushlen;
1216 /** Are there too many bytes on edge connection <b>conn</b>'s outbuf to
1217 * send back a relay-level sendme yet? Return 1 if so, 0 if not. Used by
1218 * connection_edge_consider_sending_sendme().
1221 connection_outbuf_too_full(connection_t *conn)
1223 return (conn->outbuf_flushlen > 10*CELL_PAYLOAD_SIZE);
1226 /** Try to flush more bytes onto conn-\>s.
1228 * This function gets called either from conn_write() in main.c
1229 * when poll() has declared that conn wants to write, or below
1230 * from connection_write_to_buf() when an entire TLS record is ready.
1232 * Update conn-\>timestamp_lastwritten to now, and call flush_buf
1233 * or flush_buf_tls appropriately. If it succeeds and there no more
1234 * more bytes on conn->outbuf, then call connection_finished_flushing
1235 * on it too.
1237 * Mark the connection and return -1 if you want to close it, else
1238 * return 0.
1241 connection_handle_write(connection_t *conn)
1243 int e;
1244 socklen_t len=sizeof(e);
1245 int result;
1246 time_t now = time(NULL);
1248 tor_assert(!connection_is_listener(conn));
1250 if (conn->marked_for_close)
1251 return 0; /* do nothing */
1253 conn->timestamp_lastwritten = now;
1255 /* Sometimes, "writable" means "connected". */
1256 if (connection_state_is_connecting(conn)) {
1257 if (getsockopt(conn->s, SOL_SOCKET, SO_ERROR, (void*)&e, &len) < 0) {
1258 log_fn(LOG_WARN,"getsockopt() syscall failed?! Please report to tor-ops.");
1259 if (CONN_IS_EDGE(conn))
1260 connection_edge_end_errno(conn, conn->cpath_layer);
1261 connection_mark_for_close(conn);
1262 return -1;
1264 if (e) {
1265 /* some sort of error, but maybe just inprogress still */
1266 if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
1267 log_fn(LOG_INFO,"in-progress connect failed. Removing.");
1268 if (CONN_IS_EDGE(conn))
1269 connection_edge_end_errno(conn, conn->cpath_layer);
1271 connection_close_immediate(conn);
1272 connection_mark_for_close(conn);
1273 /* it's safe to pass OPs to router_mark_as_down(), since it just
1274 * ignores unrecognized routers
1276 if (conn->type == CONN_TYPE_OR && !get_options()->HttpsProxy)
1277 router_mark_as_down(conn->identity_digest);
1278 return -1;
1279 } else {
1280 return 0; /* no change, see if next time is better */
1283 /* The connection is successful. */
1284 if (connection_finished_connecting(conn)<0)
1285 return -1;
1288 if (connection_speaks_cells(conn) && conn->state > OR_CONN_STATE_PROXY_READING) {
1289 if (conn->state == OR_CONN_STATE_HANDSHAKING) {
1290 connection_stop_writing(conn);
1291 if (connection_tls_continue_handshake(conn) < 0) {
1292 connection_close_immediate(conn); /* Don't flush; connection is dead. */
1293 connection_mark_for_close(conn);
1294 return -1;
1296 return 0;
1299 /* else open, or closing */
1300 result = flush_buf_tls(conn->tls, conn->outbuf, &conn->outbuf_flushlen);
1301 switch (result) {
1302 case TOR_TLS_ERROR:
1303 case TOR_TLS_CLOSE:
1304 log_fn(LOG_INFO,result==TOR_TLS_ERROR?
1305 "tls error. breaking.":"TLS connection closed on flush");
1306 connection_close_immediate(conn); /* Don't flush; connection is dead. */
1307 connection_mark_for_close(conn);
1308 return -1;
1309 case TOR_TLS_WANTWRITE:
1310 log_fn(LOG_DEBUG,"wanted write.");
1311 /* we're already writing */
1312 return 0;
1313 case TOR_TLS_WANTREAD:
1314 /* Make sure to avoid a loop if the receive buckets are empty. */
1315 log_fn(LOG_DEBUG,"wanted read.");
1316 if (!connection_is_reading(conn)) {
1317 connection_stop_writing(conn);
1318 conn->wants_to_write = 1;
1319 /* we'll start reading again when the next second arrives,
1320 * and then also start writing again.
1323 /* else no problem, we're already reading */
1324 return 0;
1325 /* case TOR_TLS_DONE:
1326 * for TOR_TLS_DONE, fall through to check if the flushlen
1327 * is empty, so we can stop writing.
1330 } else {
1331 result = flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen);
1332 if (result < 0) {
1333 if (CONN_IS_EDGE(conn))
1334 connection_edge_end_errno(conn, conn->cpath_layer);
1336 connection_close_immediate(conn); /* Don't flush; connection is dead. */
1337 connection_mark_for_close(conn);
1338 return -1;
1342 if (result > 0 && !is_local_IP(conn->addr)) { /* remember it */
1343 rep_hist_note_bytes_written(result, now);
1344 global_write_bucket -= result;
1347 if (!connection_wants_to_flush(conn)) { /* it's done flushing */
1348 if (connection_finished_flushing(conn) < 0) {
1349 /* already marked */
1350 return -1;
1354 return 0;
1357 /* DOCDOC */
1358 void
1359 _connection_controller_force_write(connection_t *conn)
1361 /* XXX This is hideous code duplication, but raising it seems a little
1362 * tricky for now. Think more about this one. We only call it for
1363 * EVENT_ERR_MSG, so messing with buckets a little isn't such a big problem.
1365 int result;
1366 tor_assert(conn);
1367 tor_assert(!conn->tls);
1368 tor_assert(conn->type == CONN_TYPE_CONTROL);
1369 if (conn->marked_for_close || conn->s < 0)
1370 return;
1372 result = flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen);
1373 if (result < 0) {
1374 connection_close_immediate(conn); /* Don't flush; connection is dead. */
1375 connection_mark_for_close(conn);
1376 return;
1379 if (result > 0 && !is_local_IP(conn->addr)) { /* remember it */
1380 rep_hist_note_bytes_written(result, time(NULL));
1381 global_write_bucket -= result;
1384 if (!connection_wants_to_flush(conn)) { /* it's done flushing */
1385 if (connection_finished_flushing(conn) < 0) {
1386 /* already marked */
1387 return;
1392 /** Append <b>len</b> bytes of <b>string</b> onto <b>conn</b>'s
1393 * outbuf, and ask it to start writing.
1395 void
1396 connection_write_to_buf(const char *string, size_t len, connection_t *conn)
1398 if (!len)
1399 return;
1400 /* if it's marked for close, only allow write if we mean to flush it */
1401 if (conn->marked_for_close && !conn->hold_open_until_flushed)
1402 return;
1404 if (write_to_buf(string, len, conn->outbuf) < 0) {
1405 if (CONN_IS_EDGE(conn)) {
1406 /* if it failed, it means we have our package/delivery windows set
1407 wrong compared to our max outbuf size. close the whole circuit. */
1408 log_fn(LOG_WARN,"write_to_buf failed. Closing circuit (fd %d).", conn->s);
1409 circuit_mark_for_close(circuit_get_by_edge_conn(conn));
1410 } else {
1411 log_fn(LOG_WARN,"write_to_buf failed. Closing connection (fd %d).", conn->s);
1412 connection_mark_for_close(conn);
1414 return;
1417 connection_start_writing(conn);
1418 conn->outbuf_flushlen += len;
1421 /** Return the conn to addr/port that has the most recent
1422 * timestamp_created, or NULL if no such conn exists. */
1423 connection_t *
1424 connection_or_exact_get_by_addr_port(uint32_t addr, uint16_t port)
1426 int i, n;
1427 connection_t *conn, *best=NULL;
1428 connection_t **carray;
1430 get_connection_array(&carray,&n);
1431 for (i=0;i<n;i++) {
1432 conn = carray[i];
1433 if (conn->type == CONN_TYPE_OR &&
1434 conn->addr == addr &&
1435 conn->port == port &&
1436 !conn->marked_for_close &&
1437 (!best || best->timestamp_created < conn->timestamp_created))
1438 best = conn;
1440 return best;
1443 connection_t *
1444 connection_get_by_identity_digest(const char *digest, int type)
1446 int i, n;
1447 connection_t *conn, *best=NULL;
1448 connection_t **carray;
1450 get_connection_array(&carray,&n);
1451 for (i=0;i<n;i++) {
1452 conn = carray[i];
1453 if (conn->type != type)
1454 continue;
1455 if (!memcmp(conn->identity_digest, digest, DIGEST_LEN) &&
1456 !conn->marked_for_close &&
1457 (!best || best->timestamp_created < conn->timestamp_created))
1458 best = conn;
1460 return best;
1463 /** Return the connection with id <b>id</b> if it is not already
1464 * marked for close.
1466 connection_t *
1467 connection_get_by_global_id(uint32_t id)
1469 int i, n;
1470 connection_t *conn;
1471 connection_t **carray;
1473 get_connection_array(&carray,&n);
1474 for (i=0;i<n;i++) {
1475 conn = carray[i];
1476 if (conn->global_identifier == id) {
1477 if (!conn->marked_for_close)
1478 return conn;
1479 else
1480 return NULL;
1483 return NULL;
1486 /** Return a connection of type <b>type</b> that is not marked for
1487 * close.
1489 connection_t *
1490 connection_get_by_type(int type)
1492 int i, n;
1493 connection_t *conn;
1494 connection_t **carray;
1496 get_connection_array(&carray,&n);
1497 for (i=0;i<n;i++) {
1498 conn = carray[i];
1499 if (conn->type == type && !conn->marked_for_close)
1500 return conn;
1502 return NULL;
1505 /** Return a connection of type <b>type</b> that is in state <b>state</b>,
1506 * and that is not marked for close.
1508 connection_t *
1509 connection_get_by_type_state(int type, int state)
1511 int i, n;
1512 connection_t *conn;
1513 connection_t **carray;
1515 get_connection_array(&carray,&n);
1516 for (i=0;i<n;i++) {
1517 conn = carray[i];
1518 if (conn->type == type && conn->state == state && !conn->marked_for_close)
1519 return conn;
1521 return NULL;
1524 /** Return the connection of type <b>type</b> that is in state
1525 * <b>state</b>, that was written to least recently, and that is not
1526 * marked for close.
1528 connection_t *
1529 connection_get_by_type_state_lastwritten(int type, int state)
1531 int i, n;
1532 connection_t *conn, *best=NULL;
1533 connection_t **carray;
1535 get_connection_array(&carray,&n);
1536 for (i=0;i<n;i++) {
1537 conn = carray[i];
1538 if (conn->type == type && conn->state == state && !conn->marked_for_close)
1539 if (!best || conn->timestamp_lastwritten < best->timestamp_lastwritten)
1540 best = conn;
1542 return best;
1545 /** Return a connection of type <b>type</b> that has rendquery equal
1546 * to <b>rendquery</b>, and that is not marked for close. If state
1547 * is non-zero, conn must be of that state too.
1549 connection_t *
1550 connection_get_by_type_state_rendquery(int type, int state, const char *rendquery) {
1551 int i, n;
1552 connection_t *conn;
1553 connection_t **carray;
1555 get_connection_array(&carray,&n);
1556 for (i=0;i<n;i++) {
1557 conn = carray[i];
1558 if (conn->type == type &&
1559 !conn->marked_for_close &&
1560 (!state || state == conn->state) &&
1561 !rend_cmp_service_ids(rendquery, conn->rend_query))
1562 return conn;
1564 return NULL;
1567 /** Return 1 if <b>conn</b> is a listener conn, else return 0. */
1569 connection_is_listener(connection_t *conn)
1571 if (conn->type == CONN_TYPE_OR_LISTENER ||
1572 conn->type == CONN_TYPE_AP_LISTENER ||
1573 conn->type == CONN_TYPE_DIR_LISTENER ||
1574 conn->type == CONN_TYPE_CONTROL_LISTENER)
1575 return 1;
1576 return 0;
1579 /** Return 1 if <b>conn</b> is in state "open" and is not marked
1580 * for close, else return 0.
1583 connection_state_is_open(connection_t *conn)
1585 tor_assert(conn);
1587 if (conn->marked_for_close)
1588 return 0;
1590 if ((conn->type == CONN_TYPE_OR && conn->state == OR_CONN_STATE_OPEN) ||
1591 (conn->type == CONN_TYPE_AP && conn->state == AP_CONN_STATE_OPEN) ||
1592 (conn->type == CONN_TYPE_EXIT && conn->state == EXIT_CONN_STATE_OPEN) ||
1593 (conn->type == CONN_TYPE_CONTROL &&
1594 (conn->state == CONTROL_CONN_STATE_OPEN_V0 ||
1595 conn->state == CONTROL_CONN_STATE_OPEN_V1)))
1596 return 1;
1598 return 0;
1601 /** Return 1 if conn is in 'connecting' state, else return 0. */
1603 connection_state_is_connecting(connection_t *conn)
1605 tor_assert(conn);
1607 if (conn->marked_for_close)
1608 return 0;
1609 switch (conn->type)
1611 case CONN_TYPE_OR:
1612 return conn->state == OR_CONN_STATE_CONNECTING;
1613 case CONN_TYPE_EXIT:
1614 return conn->state == EXIT_CONN_STATE_CONNECTING;
1615 case CONN_TYPE_DIR:
1616 return conn->state == DIR_CONN_STATE_CONNECTING;
1619 return 0;
1622 /** Write a destroy cell with circ ID <b>circ_id</b> onto OR connection
1623 * <b>conn</b>.
1625 * Return 0.
1628 connection_send_destroy(uint16_t circ_id, connection_t *conn)
1630 cell_t cell;
1632 tor_assert(conn);
1633 tor_assert(connection_speaks_cells(conn));
1635 memset(&cell, 0, sizeof(cell_t));
1636 cell.circ_id = circ_id;
1637 cell.command = CELL_DESTROY;
1638 log_fn(LOG_INFO,"Sending destroy (circID %d).", circ_id);
1639 connection_or_write_cell_to_buf(&cell, conn);
1640 return 0;
1643 /** Alloocates a base64'ed authenticator for use in http or https
1644 * auth, based on the input string <b>authenticator</b>. Returns it
1645 * if success, else returns NULL. */
1646 char *
1647 alloc_http_authenticator(const char *authenticator)
1649 /* an authenticator in Basic authentication
1650 * is just the string "username:password" */
1651 const int authenticator_length = strlen(authenticator);
1652 /* The base64_encode function needs a minimum buffer length
1653 * of 66 bytes. */
1654 const int base64_authenticator_length = (authenticator_length/48+1)*66;
1655 char *base64_authenticator = tor_malloc(base64_authenticator_length);
1656 if (base64_encode(base64_authenticator, base64_authenticator_length,
1657 authenticator, authenticator_length) < 0) {
1658 tor_free(base64_authenticator); /* free and set to null */
1659 } else {
1660 /* remove extra \n at end of encoding */
1661 base64_authenticator[strlen(base64_authenticator) - 1] = 0;
1663 return base64_authenticator;
1666 /** Process new bytes that have arrived on conn-\>inbuf.
1668 * This function just passes conn to the connection-specific
1669 * connection_*_process_inbuf() function. It also passes in
1670 * package_partial if wanted.
1672 static int
1673 connection_process_inbuf(connection_t *conn, int package_partial)
1675 tor_assert(conn);
1677 switch (conn->type) {
1678 case CONN_TYPE_OR:
1679 return connection_or_process_inbuf(conn);
1680 case CONN_TYPE_EXIT:
1681 case CONN_TYPE_AP:
1682 return connection_edge_process_inbuf(conn, package_partial);
1683 case CONN_TYPE_DIR:
1684 return connection_dir_process_inbuf(conn);
1685 case CONN_TYPE_DNSWORKER:
1686 return connection_dns_process_inbuf(conn);
1687 case CONN_TYPE_CPUWORKER:
1688 return connection_cpu_process_inbuf(conn);
1689 case CONN_TYPE_CONTROL:
1690 return connection_control_process_inbuf(conn);
1691 default:
1692 log_fn(LOG_WARN,"Bug: got unexpected conn type %d.", conn->type);
1693 tor_fragile_assert();
1694 return -1;
1698 /** We just finished flushing bytes from conn-\>outbuf, and there
1699 * are no more bytes remaining.
1701 * This function just passes conn to the connection-specific
1702 * connection_*_finished_flushing() function.
1704 static int
1705 connection_finished_flushing(connection_t *conn)
1707 tor_assert(conn);
1709 // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
1711 switch (conn->type) {
1712 case CONN_TYPE_OR:
1713 return connection_or_finished_flushing(conn);
1714 case CONN_TYPE_AP:
1715 case CONN_TYPE_EXIT:
1716 return connection_edge_finished_flushing(conn);
1717 case CONN_TYPE_DIR:
1718 return connection_dir_finished_flushing(conn);
1719 case CONN_TYPE_DNSWORKER:
1720 return connection_dns_finished_flushing(conn);
1721 case CONN_TYPE_CPUWORKER:
1722 return connection_cpu_finished_flushing(conn);
1723 case CONN_TYPE_CONTROL:
1724 return connection_control_finished_flushing(conn);
1725 default:
1726 log_fn(LOG_WARN,"Bug: got unexpected conn type %d.", conn->type);
1727 tor_fragile_assert();
1728 return -1;
1732 /** Called when our attempt to connect() to another server has just
1733 * succeeded.
1735 * This function just passes conn to the connection-specific
1736 * connection_*_finished_connecting() function.
1738 static int
1739 connection_finished_connecting(connection_t *conn)
1741 tor_assert(conn);
1742 switch (conn->type)
1744 case CONN_TYPE_OR:
1745 return connection_or_finished_connecting(conn);
1746 case CONN_TYPE_EXIT:
1747 return connection_edge_finished_connecting(conn);
1748 case CONN_TYPE_DIR:
1749 return connection_dir_finished_connecting(conn);
1750 default:
1751 log_fn(LOG_WARN,"Bug: got unexpected conn type %d.", conn->type);
1752 tor_fragile_assert();
1753 return -1;
1757 /** Callback: invoked when a connection reaches an EOF event. */
1758 static int
1759 connection_reached_eof(connection_t *conn)
1761 switch (conn->type) {
1762 case CONN_TYPE_OR:
1763 return connection_or_reached_eof(conn);
1764 case CONN_TYPE_AP:
1765 case CONN_TYPE_EXIT:
1766 return connection_edge_reached_eof(conn);
1767 case CONN_TYPE_DIR:
1768 return connection_dir_reached_eof(conn);
1769 case CONN_TYPE_DNSWORKER:
1770 return connection_dns_reached_eof(conn);
1771 case CONN_TYPE_CPUWORKER:
1772 return connection_cpu_reached_eof(conn);
1773 case CONN_TYPE_CONTROL:
1774 return connection_control_reached_eof(conn);
1775 default:
1776 log_fn(LOG_WARN,"Bug: got unexpected conn type %d.", conn->type);
1777 tor_fragile_assert();
1778 return -1;
1782 /** Verify that connection <b>conn</b> has all of its invariants
1783 * correct. Trigger an assert if anything is invalid.
1785 void
1786 assert_connection_ok(connection_t *conn, time_t now)
1788 tor_assert(conn);
1789 tor_assert(conn->magic == CONNECTION_MAGIC);
1790 tor_assert(conn->type >= _CONN_TYPE_MIN);
1791 tor_assert(conn->type <= _CONN_TYPE_MAX);
1793 if (conn->outbuf_flushlen > 0) {
1794 tor_assert(connection_is_writing(conn) || conn->wants_to_write);
1797 if (conn->hold_open_until_flushed)
1798 tor_assert(conn->marked_for_close);
1800 /* XXX check: wants_to_read, wants_to_write, s, poll_index,
1801 * marked_for_close. */
1803 /* buffers */
1804 if (!connection_is_listener(conn)) {
1805 assert_buf_ok(conn->inbuf);
1806 assert_buf_ok(conn->outbuf);
1809 /* XXX Fix this; no longer so.*/
1810 #if 0
1811 if (conn->type != CONN_TYPE_OR && conn->type != CONN_TYPE_DIR)
1812 tor_assert(!conn->pkey);
1813 /* pkey is set if we're a dir client, or if we're an OR in state OPEN
1814 * connected to another OR.
1816 #endif
1818 if (conn->type != CONN_TYPE_OR) {
1819 tor_assert(!conn->tls);
1820 } else {
1821 if (conn->state == OR_CONN_STATE_OPEN) {
1822 /* tor_assert(conn->bandwidth > 0); */
1823 /* the above isn't necessarily true: if we just did a TLS
1824 * handshake but we didn't recognize the other peer, or it
1825 * gave a bad cert/etc, then we won't have assigned bandwidth,
1826 * yet it will be open. -RD
1828 // tor_assert(conn->receiver_bucket >= 0);
1830 // tor_assert(conn->addr && conn->port);
1831 tor_assert(conn->address);
1832 if (conn->state > OR_CONN_STATE_PROXY_READING)
1833 tor_assert(conn->tls);
1836 if (! CONN_IS_EDGE(conn)) {
1837 tor_assert(!conn->stream_id);
1838 tor_assert(!conn->next_stream);
1839 tor_assert(!conn->cpath_layer);
1840 tor_assert(!conn->package_window);
1841 tor_assert(!conn->deliver_window);
1842 tor_assert(!conn->done_sending);
1843 tor_assert(!conn->done_receiving);
1844 } else {
1845 /* XXX unchecked: package window, deliver window. */
1847 if (conn->type == CONN_TYPE_AP) {
1848 tor_assert(conn->socks_request);
1849 if (conn->state == AP_CONN_STATE_OPEN) {
1850 tor_assert(conn->socks_request->has_finished);
1851 if (!conn->marked_for_close) {
1852 tor_assert(conn->cpath_layer);
1853 assert_cpath_layer_ok(conn->cpath_layer);
1856 } else {
1857 tor_assert(!conn->socks_request);
1859 if (conn->type == CONN_TYPE_EXIT) {
1860 tor_assert(conn->purpose == EXIT_PURPOSE_CONNECT ||
1861 conn->purpose == EXIT_PURPOSE_RESOLVE);
1862 } else if (conn->type != CONN_TYPE_DIR) {
1863 tor_assert(!conn->purpose); /* only used for dir types currently */
1866 switch (conn->type)
1868 case CONN_TYPE_OR_LISTENER:
1869 case CONN_TYPE_AP_LISTENER:
1870 case CONN_TYPE_DIR_LISTENER:
1871 case CONN_TYPE_CONTROL_LISTENER:
1872 tor_assert(conn->state == LISTENER_STATE_READY);
1873 break;
1874 case CONN_TYPE_OR:
1875 tor_assert(conn->state >= _OR_CONN_STATE_MIN);
1876 tor_assert(conn->state <= _OR_CONN_STATE_MAX);
1877 break;
1878 case CONN_TYPE_EXIT:
1879 tor_assert(conn->state >= _EXIT_CONN_STATE_MIN);
1880 tor_assert(conn->state <= _EXIT_CONN_STATE_MAX);
1881 break;
1882 case CONN_TYPE_AP:
1883 tor_assert(conn->state >= _AP_CONN_STATE_MIN);
1884 tor_assert(conn->state <= _AP_CONN_STATE_MAX);
1885 tor_assert(conn->socks_request);
1886 break;
1887 case CONN_TYPE_DIR:
1888 tor_assert(conn->state >= _DIR_CONN_STATE_MIN);
1889 tor_assert(conn->state <= _DIR_CONN_STATE_MAX);
1890 tor_assert(conn->purpose >= _DIR_PURPOSE_MIN);
1891 tor_assert(conn->purpose <= _DIR_PURPOSE_MAX);
1892 break;
1893 case CONN_TYPE_DNSWORKER:
1894 tor_assert(conn->state == DNSWORKER_STATE_IDLE ||
1895 conn->state == DNSWORKER_STATE_BUSY);
1896 break;
1897 case CONN_TYPE_CPUWORKER:
1898 tor_assert(conn->state >= _CPUWORKER_STATE_MIN);
1899 tor_assert(conn->state <= _CPUWORKER_STATE_MAX);
1900 break;
1901 case CONN_TYPE_CONTROL:
1902 tor_assert(conn->state >= _CONTROL_CONN_STATE_MIN);
1903 tor_assert(conn->state <= _CONTROL_CONN_STATE_MAX);
1904 break;
1905 default:
1906 tor_assert(0);