missed one
[tor.git] / src / or / connection.c
blobfe72c361113c6d101ac2a81f125c4a9850aea2f9
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 "Socks listener";
42 case CONN_TYPE_AP: return "Socks";
43 case CONN_TYPE_DIR_LISTENER: return "Directory listener";
44 case CONN_TYPE_DIR: return "Directory";
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 char *address = NULL;
458 connection_t *conn;
459 uint16_t usePort;
460 uint32_t addr;
461 int s; /* the socket we're going to make */
462 #ifndef MS_WINDOWS
463 int one=1;
464 #endif
466 memset(&bindaddr,0,sizeof(struct sockaddr_in));
467 if (parse_addr_port(bindaddress, &address, &addr, &usePort)<0) {
468 log_fn(LOG_WARN, "Error parsing/resolving BindAddress %s",bindaddress);
469 return -1;
472 if (usePort==0)
473 usePort = bindport;
474 bindaddr.sin_addr.s_addr = htonl(addr);
475 bindaddr.sin_family = AF_INET;
476 bindaddr.sin_port = htons((uint16_t) usePort);
478 log_fn(LOG_NOTICE, "Opening %s on %s:%d",
479 conn_type_to_string(type), address, usePort);
481 s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
482 if (s < 0) {
483 log_fn(LOG_WARN,"Socket creation failed.");
484 goto err;
485 } else if (!SOCKET_IS_POLLABLE(s)) {
486 log_fn(LOG_WARN,"Too many connections; can't create pollable listener.");
487 tor_close_socket(s);
488 goto err;
491 #ifndef MS_WINDOWS
492 /* REUSEADDR on normal places means you can rebind to the port
493 * right after somebody else has let it go. But REUSEADDR on win32
494 * means you can bind to the port _even when somebody else
495 * already has it bound_. So, don't do that on Win32. */
496 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*) &one, sizeof(one));
497 #endif
499 if (bind(s,(struct sockaddr *)&bindaddr,sizeof(bindaddr)) < 0) {
500 log_fn(LOG_WARN, "Could not bind to port %u: %s", usePort,
501 tor_socket_strerror(tor_socket_errno(s)));
502 goto err;
505 if (listen(s,SOMAXCONN) < 0) {
506 log_fn(LOG_WARN, "Could not listen on port %u: %s", usePort,
507 tor_socket_strerror(tor_socket_errno(s)));
508 goto err;
511 set_socket_nonblocking(s);
513 conn = connection_new(type);
514 conn->s = s;
515 conn->address = address;
516 address = NULL;
517 conn->port = usePort;
519 if (connection_add(conn) < 0) { /* no space, forget it */
520 log_fn(LOG_WARN,"connection_add failed. Giving up.");
521 connection_free(conn);
522 goto err;
525 log_fn(LOG_DEBUG,"%s listening on port %u.",conn_type_to_string(type), usePort);
527 conn->state = LISTENER_STATE_READY;
528 connection_start_reading(conn);
530 return 0;
532 err:
533 tor_free(address);
534 return -1;
537 /** Do basic sanity checking on a newly received socket. Return 0
538 * if it looks ok, else return -1. */
539 static int
540 check_sockaddr_in(struct sockaddr *sa, int len, int level)
542 int ok = 1;
543 struct sockaddr_in *sin=(struct sockaddr_in*)sa;
545 if (len != sizeof(struct sockaddr_in)) {
546 log_fn(level, "Length of address not as expected: %d vs %d",
547 len,(int)sizeof(struct sockaddr_in));
548 ok = 0;
550 if (sa->sa_family != AF_INET) {
551 log_fn(level, "Family of address not as expected: %d vs %d",
552 sa->sa_family, AF_INET);
553 ok = 0;
555 if (sin->sin_addr.s_addr == 0 || sin->sin_port == 0) {
556 log_fn(level, "Address for new connection has address/port equal to zero.");
557 ok = 0;
559 return ok ? 0 : -1;
562 /** The listener connection <b>conn</b> told poll() it wanted to read.
563 * Call accept() on conn-\>s, and add the new connection if necessary.
565 static int
566 connection_handle_listener_read(connection_t *conn, int new_type)
568 int news; /* the new socket */
569 connection_t *newconn;
570 /* information about the remote peer when connecting to other routers */
571 struct sockaddr_in remote;
572 char addrbuf[256];
573 /* length of the remote address. Must be whatever accept() needs. */
574 socklen_t remotelen = 256;
575 char tmpbuf[INET_NTOA_BUF_LEN];
576 tor_assert((size_t)remotelen >= sizeof(struct sockaddr_in));
577 memset(addrbuf, 0, sizeof(addrbuf));
579 news = accept(conn->s,(struct sockaddr *)&addrbuf,&remotelen);
580 if (!SOCKET_IS_POLLABLE(news)) {
581 /* accept() error, or too many conns to poll */
582 int e;
583 if (news>=0) {
584 /* Too many conns to poll. */
585 log_fn(LOG_WARN,"Too many connections; couldn't accept connection.");
586 tor_close_socket(news);
587 return 0;
589 e = tor_socket_errno(conn->s);
590 if (ERRNO_IS_ACCEPT_EAGAIN(e)) {
591 return 0; /* he hung up before we could accept(). that's fine. */
592 } else if (ERRNO_IS_ACCEPT_RESOURCE_LIMIT(e)) {
593 log_fn(LOG_NOTICE,"accept failed: %s. Dropping incoming connection.",
594 tor_socket_strerror(e));
595 return 0;
597 /* else there was a real error. */
598 log_fn(LOG_WARN,"accept() failed: %s. Closing listener.",
599 tor_socket_strerror(e));
600 connection_mark_for_close(conn);
601 return -1;
603 log(LOG_INFO,"Connection accepted on socket %d (child of fd %d).",news, conn->s);
605 set_socket_nonblocking(news);
607 if (check_sockaddr_in((struct sockaddr*)addrbuf, remotelen, LOG_INFO)<0) {
608 log_fn(LOG_INFO, "accept() returned a strange address; trying getsockname().");
609 remotelen=256;
610 memset(addrbuf, 0, sizeof(addrbuf));
611 if (getsockname(news, (struct sockaddr*)addrbuf, &remotelen)<0) {
612 log_fn(LOG_WARN, "getsockname() failed.");
613 } else {
614 if (check_sockaddr_in((struct sockaddr*)addrbuf, remotelen, LOG_WARN)<0) {
615 log_fn(LOG_WARN,"Something's wrong with this conn. Closing it.");
616 tor_close_socket(news);
617 return 0;
621 memcpy(&remote, addrbuf, sizeof(struct sockaddr_in));
623 /* process entrance policies here, before we even create the connection */
624 if (new_type == CONN_TYPE_AP) {
625 /* check sockspolicy to see if we should accept it */
626 if (socks_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
627 tor_inet_ntoa(&remote.sin_addr, tmpbuf, sizeof(tmpbuf));
628 log_fn(LOG_NOTICE,"Denying socks connection from untrusted address %s.",
629 tmpbuf);
630 tor_close_socket(news);
631 return 0;
634 if (new_type == CONN_TYPE_DIR) {
635 /* check dirpolicy to see if we should accept it */
636 if (dir_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
637 tor_inet_ntoa(&remote.sin_addr, tmpbuf, sizeof(tmpbuf));
638 log_fn(LOG_NOTICE,"Denying dir connection from address %s.",
639 tmpbuf);
640 tor_close_socket(news);
641 return 0;
645 newconn = connection_new(new_type);
646 newconn->s = news;
648 /* remember the remote address */
649 newconn->address = tor_malloc(INET_NTOA_BUF_LEN);
650 tor_inet_ntoa(&remote.sin_addr, newconn->address, INET_NTOA_BUF_LEN);
651 newconn->addr = ntohl(remote.sin_addr.s_addr);
652 newconn->port = ntohs(remote.sin_port);
654 if (connection_add(newconn) < 0) { /* no space, forget it */
655 connection_free(newconn);
656 return 0; /* no need to tear down the parent */
659 if (connection_init_accepted_conn(newconn) < 0) {
660 connection_mark_for_close(newconn);
661 return 0;
663 return 0;
666 /** Initialize states for newly accepted connection <b>conn</b>.
667 * If conn is an OR, start the tls handshake.
669 static int
670 connection_init_accepted_conn(connection_t *conn)
672 connection_start_reading(conn);
674 switch (conn->type) {
675 case CONN_TYPE_OR:
676 return connection_tls_start_handshake(conn, 1);
677 case CONN_TYPE_AP:
678 conn->state = AP_CONN_STATE_SOCKS_WAIT;
679 break;
680 case CONN_TYPE_DIR:
681 conn->purpose = DIR_PURPOSE_SERVER;
682 conn->state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
683 break;
684 case CONN_TYPE_CONTROL:
685 conn->state = CONTROL_CONN_STATE_NEEDAUTH_V0;
686 break;
688 return 0;
691 /** Take conn, make a nonblocking socket; try to connect to
692 * addr:port (they arrive in *host order*). If fail, return -1. Else
693 * assign s to conn-\>s: if connected return 1, if EAGAIN return 0.
695 * address is used to make the logs useful.
697 * On success, add conn to the list of polled connections.
700 connection_connect(connection_t *conn, char *address,
701 uint32_t addr, uint16_t port)
703 int s;
704 struct sockaddr_in dest_addr;
705 or_options_t *options = get_options();
707 s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
708 if (s < 0) {
709 log_fn(LOG_WARN,"Error creating network socket: %s",
710 tor_socket_strerror(tor_socket_errno(-1)));
711 return -1;
712 } else if (!SOCKET_IS_POLLABLE(s)) {
713 log_fn(LOG_WARN,
714 "Too many connections; can't create pollable connection to %s",
715 safe_str(address));
716 tor_close_socket(s);
717 return -1;
720 if (options->OutboundBindAddress) {
721 struct sockaddr_in ext_addr;
723 memset(&ext_addr, 0, sizeof(ext_addr));
724 ext_addr.sin_family = AF_INET;
725 ext_addr.sin_port = 0;
726 if (!tor_inet_aton(options->OutboundBindAddress, &ext_addr.sin_addr)) {
727 log_fn(LOG_WARN,"Outbound bind address '%s' didn't parse. Ignoring.",
728 options->OutboundBindAddress);
729 } else {
730 if (bind(s, (struct sockaddr*)&ext_addr, sizeof(ext_addr)) < 0) {
731 log_fn(LOG_WARN,"Error binding network socket: %s",
732 tor_socket_strerror(tor_socket_errno(s)));
733 return -1;
738 set_socket_nonblocking(s);
740 memset(&dest_addr,0,sizeof(dest_addr));
741 dest_addr.sin_family = AF_INET;
742 dest_addr.sin_port = htons(port);
743 dest_addr.sin_addr.s_addr = htonl(addr);
745 log_fn(LOG_DEBUG,"Connecting to %s:%u.",safe_str(address),port);
747 if (connect(s,(struct sockaddr *)&dest_addr,sizeof(dest_addr)) < 0) {
748 int e = tor_socket_errno(s);
749 if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
750 /* yuck. kill it. */
751 log_fn(LOG_INFO,"Connect() to %s:%u failed: %s",safe_str(address),port,
752 tor_socket_strerror(e));
753 tor_close_socket(s);
754 return -1;
755 } else {
756 /* it's in progress. set state appropriately and return. */
757 conn->s = s;
758 if (connection_add(conn) < 0) /* no space, forget it */
759 return -1;
760 log_fn(LOG_DEBUG,"connect in progress, socket %d.",s);
761 return 0;
765 /* it succeeded. we're connected. */
766 log_fn(LOG_INFO,"Connection to %s:%u established.",safe_str(address),port);
767 conn->s = s;
768 if (connection_add(conn) < 0) /* no space, forget it */
769 return -1;
770 return 1;
774 * Launch any configured listener connections of type <b>type</b>. (A
775 * listener is configured if <b>port_option</b> is non-zero. If any
776 * BindAddress configuration options are given in <b>cfg</b>, create a
777 * connection binding to each one. Otherwise, create a single
778 * connection binding to the address <b>default_addr</b>.)
780 * If <b>force</b> is true, close and re-open all listener connections.
781 * Otherwise, only relaunch the listeners of this type if the number of
782 * existing connections is not as configured (e.g., because one died),
783 * or if the existing connections do not match those configured.
785 static int
786 retry_listeners(int type, struct config_line_t *cfg,
787 int port_option, const char *default_addr, int force)
789 struct smartlist_t *launch = smartlist_create();
790 int free_launch_elts = 1;
791 struct config_line_t *c;
792 int n_conn, i;
793 connection_t *conn;
794 connection_t **carray;
795 struct config_line_t *line;
797 if (cfg && port_option) {
798 for (c = cfg; c; c = c->next) {
799 smartlist_add(launch, c);
801 free_launch_elts = 0;
802 } else if (port_option) {
803 line = tor_malloc_zero(sizeof(struct config_line_t));
804 line->key = tor_strdup("");
805 line->value = tor_strdup(default_addr);
806 smartlist_add(launch, line);
809 get_connection_array(&carray,&n_conn);
810 for (i=0; i < n_conn; ++i) {
811 conn = carray[i];
812 if (conn->type != type || conn->marked_for_close)
813 continue;
814 if (force) {
815 /* It's a listener, and we're relaunching all listeners of this
816 * type. Close this one. */
817 log_fn(LOG_NOTICE, "Closing %s on %s:%d",
818 conn_type_to_string(type), conn->address, conn->port);
819 connection_close_immediate(conn);
820 connection_mark_for_close(conn);
821 continue;
823 /* Okay, so this is a listener. Is it configured? */
824 line = NULL;
825 SMARTLIST_FOREACH(launch, struct config_line_t *, wanted,
827 char *addr;
828 uint16_t port;
829 if (! parse_addr_port(wanted->value, &addr, NULL, &port)) {
830 if (! port)
831 port = port_option;
832 if (port == conn->port && !strcasecmp(addr, conn->address)) {
833 line = wanted;
834 break;
838 if (! line) {
839 /* This one isn't configured. Close it. */
840 log_fn(LOG_NOTICE, "Closing %s on %s:%d",
841 conn_type_to_string(type), conn->address, conn->port);
842 connection_close_immediate(conn);
843 connection_mark_for_close(conn);
844 } else {
845 /* It's configured; we don't need to launch it. */
846 log_fn(LOG_INFO, "Already have %s on %s:%d",
847 conn_type_to_string(type), conn->address, conn->port);
848 smartlist_remove(launch, line);
852 /* Now open all the listeners that are configured but not opened. */
853 i = 0;
854 SMARTLIST_FOREACH(launch, struct config_line_t *, cfg,
856 if (connection_create_listener(cfg->value, (uint16_t) port_option,
857 type)<0)
858 i = -1;
861 if (free_launch_elts) {
862 SMARTLIST_FOREACH(launch, struct config_line_t *, cfg,
863 config_free_lines(cfg));
865 smartlist_free(launch);
867 return i;
870 /** (Re)launch listeners for each port you should have open. If
871 * <b>force</b> is true, close and relaunch all listeners. If <b>force</b>
872 * is false, then only relaunch listeners when we have the wrong number of
873 * connections for a given type.
876 retry_all_listeners(int force)
878 or_options_t *options = get_options();
880 if (server_mode(options) &&
881 retry_listeners(CONN_TYPE_OR_LISTENER, options->ORBindAddress,
882 options->ORPort, "0.0.0.0", force)<0)
883 return -1;
884 if (retry_listeners(CONN_TYPE_DIR_LISTENER, options->DirBindAddress,
885 options->DirPort, "0.0.0.0", force)<0)
886 return -1;
887 if (retry_listeners(CONN_TYPE_AP_LISTENER, options->SocksBindAddress,
888 options->SocksPort, "127.0.0.1", force)<0)
889 return -1;
890 if (retry_listeners(CONN_TYPE_CONTROL_LISTENER, NULL,
891 options->ControlPort, "127.0.0.1", force)<0)
892 return -1;
894 return 0;
897 extern int global_read_bucket, global_write_bucket;
899 /** How many bytes at most can we read onto this connection? */
900 static int
901 connection_bucket_read_limit(connection_t *conn)
903 int at_most;
905 /* do a rudimentary round-robin so one circuit can't hog a connection */
906 if (connection_speaks_cells(conn)) {
907 at_most = 32*(CELL_NETWORK_SIZE);
908 } else {
909 at_most = 32*(RELAY_PAYLOAD_SIZE);
912 if (at_most > global_read_bucket)
913 at_most = global_read_bucket;
915 if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN)
916 if (at_most > conn->receiver_bucket)
917 at_most = conn->receiver_bucket;
919 if (at_most < 0)
920 return 0;
921 return at_most;
924 /** We just read num_read onto conn. Decrement buckets appropriately. */
925 static void
926 connection_read_bucket_decrement(connection_t *conn, int num_read)
928 global_read_bucket -= num_read; //tor_assert(global_read_bucket >= 0);
929 if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
930 conn->receiver_bucket -= num_read; //tor_assert(conn->receiver_bucket >= 0);
934 /** DOCDOC */
935 static void
936 connection_consider_empty_buckets(connection_t *conn)
938 if (global_read_bucket <= 0) {
939 LOG_FN_CONN(conn, (LOG_DEBUG,"global bucket exhausted. Pausing."));
940 conn->wants_to_read = 1;
941 connection_stop_reading(conn);
942 return;
944 if (connection_speaks_cells(conn) &&
945 conn->state == OR_CONN_STATE_OPEN &&
946 conn->receiver_bucket <= 0) {
947 LOG_FN_CONN(conn, (LOG_DEBUG,"receiver bucket exhausted. Pausing."));
948 conn->wants_to_read = 1;
949 connection_stop_reading(conn);
953 /** Initialize the global read bucket to options->BandwidthBurst,
954 * and current_time to the current time. */
955 void
956 connection_bucket_init(void)
958 or_options_t *options = get_options();
959 global_read_bucket = (int)options->BandwidthBurst; /* start it at max traffic */
960 global_write_bucket = (int)options->BandwidthBurst; /* start it at max traffic */
963 /** A second has rolled over; increment buckets appropriately. */
964 void
965 connection_bucket_refill(struct timeval *now)
967 int i, n;
968 connection_t *conn;
969 connection_t **carray;
970 or_options_t *options = get_options();
972 /* refill the global buckets */
973 if (global_read_bucket < (int)options->BandwidthBurst) {
974 global_read_bucket += (int)options->BandwidthRate;
975 log_fn(LOG_DEBUG,"global_read_bucket now %d.", global_read_bucket);
977 if (global_write_bucket < (int)options->BandwidthBurst) {
978 global_write_bucket += (int)options->BandwidthRate;
979 log_fn(LOG_DEBUG,"global_write_bucket now %d.", global_write_bucket);
982 /* refill the per-connection buckets */
983 get_connection_array(&carray,&n);
984 for (i=0;i<n;i++) {
985 conn = carray[i];
987 if (connection_receiver_bucket_should_increase(conn)) {
988 conn->receiver_bucket = conn->bandwidth;
989 //log_fn(LOG_DEBUG,"Receiver bucket %d now %d.", i, conn->receiver_bucket);
992 if (conn->wants_to_read == 1 /* it's marked to turn reading back on now */
993 && global_read_bucket > 0 /* and we're allowed to read */
994 && global_write_bucket > 0 /* and we're allowed to write (XXXX,
995 * not the best place to check this.) */
996 && (!connection_speaks_cells(conn) ||
997 conn->state != OR_CONN_STATE_OPEN ||
998 conn->receiver_bucket > 0)) {
999 /* and either a non-cell conn or a cell conn with non-empty bucket */
1000 LOG_FN_CONN(conn, (LOG_DEBUG,"waking up conn (fd %d)",conn->s));
1001 conn->wants_to_read = 0;
1002 connection_start_reading(conn);
1003 if (conn->wants_to_write == 1) {
1004 conn->wants_to_write = 0;
1005 connection_start_writing(conn);
1011 /** Is the receiver bucket for connection <b>conn</b> low enough that we
1012 * should add another pile of tokens to it?
1014 static int
1015 connection_receiver_bucket_should_increase(connection_t *conn)
1017 tor_assert(conn);
1019 if (!connection_speaks_cells(conn))
1020 return 0; /* edge connections don't use receiver_buckets */
1021 if (conn->state != OR_CONN_STATE_OPEN)
1022 return 0; /* only open connections play the rate limiting game */
1024 if (conn->receiver_bucket >= conn->bandwidth)
1025 return 0;
1027 return 1;
1030 /** Read bytes from conn-\>s and process them.
1032 * This function gets called from conn_read() in main.c, either
1033 * when poll() has declared that conn wants to read, or (for OR conns)
1034 * when there are pending TLS bytes.
1036 * It calls connection_read_to_buf() to bring in any new bytes,
1037 * and then calls connection_process_inbuf() to process them.
1039 * Mark the connection and return -1 if you want to close it, else
1040 * return 0.
1043 connection_handle_read(connection_t *conn)
1045 int max_to_read=-1, try_to_read;
1047 if (conn->marked_for_close)
1048 return 0; /* do nothing */
1050 conn->timestamp_lastread = time(NULL);
1052 switch (conn->type) {
1053 case CONN_TYPE_OR_LISTENER:
1054 return connection_handle_listener_read(conn, CONN_TYPE_OR);
1055 case CONN_TYPE_AP_LISTENER:
1056 return connection_handle_listener_read(conn, CONN_TYPE_AP);
1057 case CONN_TYPE_DIR_LISTENER:
1058 return connection_handle_listener_read(conn, CONN_TYPE_DIR);
1059 case CONN_TYPE_CONTROL_LISTENER:
1060 return connection_handle_listener_read(conn, CONN_TYPE_CONTROL);
1063 loop_again:
1064 try_to_read = max_to_read;
1065 tor_assert(!conn->marked_for_close);
1066 if (connection_read_to_buf(conn, &max_to_read) < 0) {
1067 /* There's a read error; kill the connection.*/
1068 connection_close_immediate(conn); /* Don't flush; connection is dead. */
1069 if (CONN_IS_EDGE(conn)) {
1070 connection_edge_end_errno(conn, conn->cpath_layer);
1071 if (conn->socks_request) /* broken, so don't send a socks reply back */
1072 conn->socks_request->has_finished = 1;
1074 connection_mark_for_close(conn);
1075 return -1;
1077 if (CONN_IS_EDGE(conn) &&
1078 try_to_read != max_to_read) {
1079 /* instruct it not to try to package partial cells. */
1080 if (connection_process_inbuf(conn, 0) < 0) {
1081 return -1;
1083 if (!conn->marked_for_close &&
1084 connection_is_reading(conn) &&
1085 !conn->inbuf_reached_eof &&
1086 max_to_read > 0)
1087 goto loop_again; /* try reading again, in case more is here now */
1089 /* one last try, packaging partial cells and all. */
1090 if (!conn->marked_for_close &&
1091 connection_process_inbuf(conn, 1) < 0) {
1092 return -1;
1094 if (!conn->marked_for_close &&
1095 conn->inbuf_reached_eof &&
1096 connection_reached_eof(conn) < 0) {
1097 return -1;
1099 return 0;
1102 /** Pull in new bytes from conn-\>s onto conn-\>inbuf, either
1103 * directly or via TLS. Reduce the token buckets by the number of
1104 * bytes read.
1106 * If *max_to_read is -1, then decide it ourselves, else go with the
1107 * value passed to us. When returning, if it's changed, subtract the
1108 * number of bytes we read from *max_to_read.
1110 * Return -1 if we want to break conn, else return 0.
1112 static int
1113 connection_read_to_buf(connection_t *conn, int *max_to_read)
1115 int result, at_most = *max_to_read;
1116 size_t bytes_in_buf, more_to_read;
1118 if (at_most == -1) { /* we need to initialize it */
1119 /* how many bytes are we allowed to read? */
1120 at_most = connection_bucket_read_limit(conn);
1123 bytes_in_buf = buf_capacity(conn->inbuf) - buf_datalen(conn->inbuf);
1124 again:
1125 if ((size_t)at_most > bytes_in_buf && bytes_in_buf >= 1024) {
1126 more_to_read = at_most - bytes_in_buf;
1127 at_most = bytes_in_buf;
1128 } else {
1129 more_to_read = 0;
1132 if (connection_speaks_cells(conn) && conn->state > OR_CONN_STATE_PROXY_READING) {
1133 int pending;
1134 if (conn->state == OR_CONN_STATE_HANDSHAKING) {
1135 /* continue handshaking even if global token bucket is empty */
1136 return connection_tls_continue_handshake(conn);
1139 log_fn(LOG_DEBUG,"%d: starting, inbuf_datalen %d (%d pending in tls object). at_most %d.",
1140 conn->s,(int)buf_datalen(conn->inbuf),tor_tls_get_pending_bytes(conn->tls), at_most);
1142 /* else open, or closing */
1143 result = read_to_buf_tls(conn->tls, at_most, conn->inbuf);
1145 switch (result) {
1146 case TOR_TLS_CLOSE:
1147 log_fn(LOG_INFO,"TLS connection closed on read. Closing. (Nickname %s, address %s",
1148 conn->nickname ? conn->nickname : "not set", conn->address);
1149 return -1;
1150 case TOR_TLS_ERROR:
1151 log_fn(LOG_INFO,"tls error. breaking (nickname %s, address %s).",
1152 conn->nickname ? conn->nickname : "not set", conn->address);
1153 return -1;
1154 case TOR_TLS_WANTWRITE:
1155 connection_start_writing(conn);
1156 return 0;
1157 case TOR_TLS_WANTREAD: /* we're already reading */
1158 case TOR_TLS_DONE: /* no data read, so nothing to process */
1159 result = 0;
1160 break; /* so we call bucket_decrement below */
1161 default:
1162 break;
1164 pending = tor_tls_get_pending_bytes(conn->tls);
1165 if (pending) {
1166 /* XXXX If we have any pending bytes, read them now. This *can*
1167 * take us over our read allotment, but really we shouldn't be
1168 * believing that SSL bytes are the same as TCP bytes anyway. */
1169 int r2 = read_to_buf_tls(conn->tls, pending, conn->inbuf);
1170 if (r2<0) {
1171 log_fn(LOG_WARN, "Bug: apparently, reading pending bytes can fail.");
1172 return -1;
1173 } else {
1174 result += r2;
1178 } else {
1179 CONN_LOG_PROTECT(conn,
1180 result = read_to_buf(conn->s, at_most, conn->inbuf,
1181 &conn->inbuf_reached_eof));
1183 // log_fn(LOG_DEBUG,"read_to_buf returned %d.",read_result);
1185 if (result < 0)
1186 return -1;
1189 if (result > 0) { /* change *max_to_read */
1190 *max_to_read = at_most - result;
1193 if (result > 0 && !is_local_IP(conn->addr)) { /* remember it */
1194 rep_hist_note_bytes_read(result, time(NULL));
1195 connection_read_bucket_decrement(conn, result);
1198 if (more_to_read && result == at_most) {
1199 bytes_in_buf = buf_capacity(conn->inbuf) - buf_datalen(conn->inbuf);
1200 tor_assert(bytes_in_buf < 1024);
1201 at_most = more_to_read;
1202 goto again;
1205 /* Call even if result is 0, since the global read bucket may
1206 * have reached 0 on a different conn, and this guy needs to
1207 * know to stop reading. */
1208 connection_consider_empty_buckets(conn);
1210 return 0;
1213 /** A pass-through to fetch_from_buf. */
1215 connection_fetch_from_buf(char *string, size_t len, connection_t *conn)
1217 return fetch_from_buf(string, len, conn->inbuf);
1220 /** Return conn-\>outbuf_flushlen: how many bytes conn wants to flush
1221 * from its outbuf. */
1223 connection_wants_to_flush(connection_t *conn)
1225 return conn->outbuf_flushlen;
1228 /** Are there too many bytes on edge connection <b>conn</b>'s outbuf to
1229 * send back a relay-level sendme yet? Return 1 if so, 0 if not. Used by
1230 * connection_edge_consider_sending_sendme().
1233 connection_outbuf_too_full(connection_t *conn)
1235 return (conn->outbuf_flushlen > 10*CELL_PAYLOAD_SIZE);
1238 /** Try to flush more bytes onto conn-\>s.
1240 * This function gets called either from conn_write() in main.c
1241 * when poll() has declared that conn wants to write, or below
1242 * from connection_write_to_buf() when an entire TLS record is ready.
1244 * Update conn-\>timestamp_lastwritten to now, and call flush_buf
1245 * or flush_buf_tls appropriately. If it succeeds and there no more
1246 * more bytes on conn->outbuf, then call connection_finished_flushing
1247 * on it too.
1249 * Mark the connection and return -1 if you want to close it, else
1250 * return 0.
1253 connection_handle_write(connection_t *conn)
1255 int e;
1256 socklen_t len=sizeof(e);
1257 int result;
1258 time_t now = time(NULL);
1260 tor_assert(!connection_is_listener(conn));
1262 if (conn->marked_for_close)
1263 return 0; /* do nothing */
1265 conn->timestamp_lastwritten = now;
1267 /* Sometimes, "writable" means "connected". */
1268 if (connection_state_is_connecting(conn)) {
1269 if (getsockopt(conn->s, SOL_SOCKET, SO_ERROR, (void*)&e, &len) < 0) {
1270 log_fn(LOG_WARN,"getsockopt() syscall failed?! Please report to tor-ops.");
1271 if (CONN_IS_EDGE(conn))
1272 connection_edge_end_errno(conn, conn->cpath_layer);
1273 connection_mark_for_close(conn);
1274 return -1;
1276 if (e) {
1277 /* some sort of error, but maybe just inprogress still */
1278 if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
1279 log_fn(LOG_INFO,"in-progress connect failed. Removing.");
1280 if (CONN_IS_EDGE(conn))
1281 connection_edge_end_errno(conn, conn->cpath_layer);
1283 connection_close_immediate(conn);
1284 connection_mark_for_close(conn);
1285 /* it's safe to pass OPs to router_mark_as_down(), since it just
1286 * ignores unrecognized routers
1288 if (conn->type == CONN_TYPE_OR && !get_options()->HttpsProxy)
1289 router_mark_as_down(conn->identity_digest);
1290 return -1;
1291 } else {
1292 return 0; /* no change, see if next time is better */
1295 /* The connection is successful. */
1296 if (connection_finished_connecting(conn)<0)
1297 return -1;
1300 if (connection_speaks_cells(conn) && conn->state > OR_CONN_STATE_PROXY_READING) {
1301 if (conn->state == OR_CONN_STATE_HANDSHAKING) {
1302 connection_stop_writing(conn);
1303 if (connection_tls_continue_handshake(conn) < 0) {
1304 connection_close_immediate(conn); /* Don't flush; connection is dead. */
1305 connection_mark_for_close(conn);
1306 return -1;
1308 return 0;
1311 /* else open, or closing */
1312 result = flush_buf_tls(conn->tls, conn->outbuf, &conn->outbuf_flushlen);
1313 switch (result) {
1314 case TOR_TLS_ERROR:
1315 case TOR_TLS_CLOSE:
1316 log_fn(LOG_INFO,result==TOR_TLS_ERROR?
1317 "tls error. breaking.":"TLS connection closed on flush");
1318 connection_close_immediate(conn); /* Don't flush; connection is dead. */
1319 connection_mark_for_close(conn);
1320 return -1;
1321 case TOR_TLS_WANTWRITE:
1322 log_fn(LOG_DEBUG,"wanted write.");
1323 /* we're already writing */
1324 return 0;
1325 case TOR_TLS_WANTREAD:
1326 /* Make sure to avoid a loop if the receive buckets are empty. */
1327 log_fn(LOG_DEBUG,"wanted read.");
1328 if (!connection_is_reading(conn)) {
1329 connection_stop_writing(conn);
1330 conn->wants_to_write = 1;
1331 /* we'll start reading again when the next second arrives,
1332 * and then also start writing again.
1335 /* else no problem, we're already reading */
1336 return 0;
1337 /* case TOR_TLS_DONE:
1338 * for TOR_TLS_DONE, fall through to check if the flushlen
1339 * is empty, so we can stop writing.
1342 } else {
1343 CONN_LOG_PROTECT(conn,
1344 result = flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen));
1345 if (result < 0) {
1346 if (CONN_IS_EDGE(conn))
1347 connection_edge_end_errno(conn, conn->cpath_layer);
1349 connection_close_immediate(conn); /* Don't flush; connection is dead. */
1350 connection_mark_for_close(conn);
1351 return -1;
1355 if (result > 0 && !is_local_IP(conn->addr)) { /* remember it */
1356 rep_hist_note_bytes_written(result, now);
1357 global_write_bucket -= result;
1360 if (!connection_wants_to_flush(conn)) { /* it's done flushing */
1361 if (connection_finished_flushing(conn) < 0) {
1362 /* already marked */
1363 return -1;
1367 return 0;
1370 /* DOCDOC */
1371 void
1372 _connection_controller_force_write(connection_t *conn)
1374 /* XXX This is hideous code duplication, but raising it seems a little
1375 * tricky for now. Think more about this one. We only call it for
1376 * EVENT_ERR_MSG, so messing with buckets a little isn't such a big problem.
1378 int result;
1379 tor_assert(conn);
1380 tor_assert(!conn->tls);
1381 tor_assert(conn->type == CONN_TYPE_CONTROL);
1382 if (conn->marked_for_close || conn->s < 0)
1383 return;
1385 CONN_LOG_PROTECT(conn,
1386 result = flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen));
1387 if (result < 0) {
1388 connection_close_immediate(conn); /* Don't flush; connection is dead. */
1389 connection_mark_for_close(conn);
1390 return;
1393 if (result > 0 && !is_local_IP(conn->addr)) { /* remember it */
1394 rep_hist_note_bytes_written(result, time(NULL));
1395 global_write_bucket -= result;
1398 if (!connection_wants_to_flush(conn)) { /* it's done flushing */
1399 if (connection_finished_flushing(conn) < 0) {
1400 /* already marked */
1401 return;
1406 /** Append <b>len</b> bytes of <b>string</b> onto <b>conn</b>'s
1407 * outbuf, and ask it to start writing.
1409 void
1410 connection_write_to_buf(const char *string, size_t len, connection_t *conn)
1412 int r;
1413 if (!len)
1414 return;
1415 /* if it's marked for close, only allow write if we mean to flush it */
1416 if (conn->marked_for_close && !conn->hold_open_until_flushed)
1417 return;
1419 CONN_LOG_PROTECT(conn, r = write_to_buf(string, len, conn->outbuf));
1420 if (r < 0) {
1421 if (CONN_IS_EDGE(conn)) {
1422 /* if it failed, it means we have our package/delivery windows set
1423 wrong compared to our max outbuf size. close the whole circuit. */
1424 log_fn(LOG_WARN,"write_to_buf failed. Closing circuit (fd %d).", conn->s);
1425 circuit_mark_for_close(circuit_get_by_edge_conn(conn));
1426 } else {
1427 log_fn(LOG_WARN,"write_to_buf failed. Closing connection (fd %d).", conn->s);
1428 connection_mark_for_close(conn);
1430 return;
1433 connection_start_writing(conn);
1434 conn->outbuf_flushlen += len;
1437 /** Return the conn to addr/port that has the most recent
1438 * timestamp_created, or NULL if no such conn exists. */
1439 connection_t *
1440 connection_or_exact_get_by_addr_port(uint32_t addr, uint16_t port)
1442 int i, n;
1443 connection_t *conn, *best=NULL;
1444 connection_t **carray;
1446 get_connection_array(&carray,&n);
1447 for (i=0;i<n;i++) {
1448 conn = carray[i];
1449 if (conn->type == CONN_TYPE_OR &&
1450 conn->addr == addr &&
1451 conn->port == port &&
1452 !conn->marked_for_close &&
1453 (!best || best->timestamp_created < conn->timestamp_created))
1454 best = conn;
1456 return best;
1459 connection_t *
1460 connection_get_by_identity_digest(const char *digest, int type)
1462 int i, n;
1463 connection_t *conn, *best=NULL;
1464 connection_t **carray;
1466 get_connection_array(&carray,&n);
1467 for (i=0;i<n;i++) {
1468 conn = carray[i];
1469 if (conn->type != type)
1470 continue;
1471 if (!memcmp(conn->identity_digest, digest, DIGEST_LEN) &&
1472 !conn->marked_for_close &&
1473 (!best || best->timestamp_created < conn->timestamp_created))
1474 best = conn;
1476 return best;
1479 /** Return the connection with id <b>id</b> if it is not already
1480 * marked for close.
1482 connection_t *
1483 connection_get_by_global_id(uint32_t id)
1485 int i, n;
1486 connection_t *conn;
1487 connection_t **carray;
1489 get_connection_array(&carray,&n);
1490 for (i=0;i<n;i++) {
1491 conn = carray[i];
1492 if (conn->global_identifier == id) {
1493 if (!conn->marked_for_close)
1494 return conn;
1495 else
1496 return NULL;
1499 return NULL;
1502 /** Return a connection of type <b>type</b> that is not marked for
1503 * close.
1505 connection_t *
1506 connection_get_by_type(int type)
1508 int i, n;
1509 connection_t *conn;
1510 connection_t **carray;
1512 get_connection_array(&carray,&n);
1513 for (i=0;i<n;i++) {
1514 conn = carray[i];
1515 if (conn->type == type && !conn->marked_for_close)
1516 return conn;
1518 return NULL;
1521 /** Return a connection of type <b>type</b> that is in state <b>state</b>,
1522 * and that is not marked for close.
1524 connection_t *
1525 connection_get_by_type_state(int type, int state)
1527 int i, n;
1528 connection_t *conn;
1529 connection_t **carray;
1531 get_connection_array(&carray,&n);
1532 for (i=0;i<n;i++) {
1533 conn = carray[i];
1534 if (conn->type == type && conn->state == state && !conn->marked_for_close)
1535 return conn;
1537 return NULL;
1540 /** Return the connection of type <b>type</b> that is in state
1541 * <b>state</b>, that was written to least recently, and that is not
1542 * marked for close.
1544 connection_t *
1545 connection_get_by_type_state_lastwritten(int type, int state)
1547 int i, n;
1548 connection_t *conn, *best=NULL;
1549 connection_t **carray;
1551 get_connection_array(&carray,&n);
1552 for (i=0;i<n;i++) {
1553 conn = carray[i];
1554 if (conn->type == type && conn->state == state && !conn->marked_for_close)
1555 if (!best || conn->timestamp_lastwritten < best->timestamp_lastwritten)
1556 best = conn;
1558 return best;
1561 /** Return a connection of type <b>type</b> that has rendquery equal
1562 * to <b>rendquery</b>, and that is not marked for close. If state
1563 * is non-zero, conn must be of that state too.
1565 connection_t *
1566 connection_get_by_type_state_rendquery(int type, int state, const char *rendquery) {
1567 int i, n;
1568 connection_t *conn;
1569 connection_t **carray;
1571 get_connection_array(&carray,&n);
1572 for (i=0;i<n;i++) {
1573 conn = carray[i];
1574 if (conn->type == type &&
1575 !conn->marked_for_close &&
1576 (!state || state == conn->state) &&
1577 !rend_cmp_service_ids(rendquery, conn->rend_query))
1578 return conn;
1580 return NULL;
1583 /** Return 1 if <b>conn</b> is a listener conn, else return 0. */
1585 connection_is_listener(connection_t *conn)
1587 if (conn->type == CONN_TYPE_OR_LISTENER ||
1588 conn->type == CONN_TYPE_AP_LISTENER ||
1589 conn->type == CONN_TYPE_DIR_LISTENER ||
1590 conn->type == CONN_TYPE_CONTROL_LISTENER)
1591 return 1;
1592 return 0;
1595 /** Return 1 if <b>conn</b> is in state "open" and is not marked
1596 * for close, else return 0.
1599 connection_state_is_open(connection_t *conn)
1601 tor_assert(conn);
1603 if (conn->marked_for_close)
1604 return 0;
1606 if ((conn->type == CONN_TYPE_OR && conn->state == OR_CONN_STATE_OPEN) ||
1607 (conn->type == CONN_TYPE_AP && conn->state == AP_CONN_STATE_OPEN) ||
1608 (conn->type == CONN_TYPE_EXIT && conn->state == EXIT_CONN_STATE_OPEN) ||
1609 (conn->type == CONN_TYPE_CONTROL &&
1610 (conn->state == CONTROL_CONN_STATE_OPEN_V0 ||
1611 conn->state == CONTROL_CONN_STATE_OPEN_V1)))
1612 return 1;
1614 return 0;
1617 /** Return 1 if conn is in 'connecting' state, else return 0. */
1619 connection_state_is_connecting(connection_t *conn)
1621 tor_assert(conn);
1623 if (conn->marked_for_close)
1624 return 0;
1625 switch (conn->type)
1627 case CONN_TYPE_OR:
1628 return conn->state == OR_CONN_STATE_CONNECTING;
1629 case CONN_TYPE_EXIT:
1630 return conn->state == EXIT_CONN_STATE_CONNECTING;
1631 case CONN_TYPE_DIR:
1632 return conn->state == DIR_CONN_STATE_CONNECTING;
1635 return 0;
1638 /** Write a destroy cell with circ ID <b>circ_id</b> onto OR connection
1639 * <b>conn</b>.
1641 * Return 0.
1644 connection_send_destroy(uint16_t circ_id, connection_t *conn)
1646 cell_t cell;
1648 tor_assert(conn);
1649 tor_assert(connection_speaks_cells(conn));
1651 memset(&cell, 0, sizeof(cell_t));
1652 cell.circ_id = circ_id;
1653 cell.command = CELL_DESTROY;
1654 log_fn(LOG_INFO,"Sending destroy (circID %d).", circ_id);
1655 connection_or_write_cell_to_buf(&cell, conn);
1656 return 0;
1659 /** Alloocates a base64'ed authenticator for use in http or https
1660 * auth, based on the input string <b>authenticator</b>. Returns it
1661 * if success, else returns NULL. */
1662 char *
1663 alloc_http_authenticator(const char *authenticator)
1665 /* an authenticator in Basic authentication
1666 * is just the string "username:password" */
1667 const int authenticator_length = strlen(authenticator);
1668 /* The base64_encode function needs a minimum buffer length
1669 * of 66 bytes. */
1670 const int base64_authenticator_length = (authenticator_length/48+1)*66;
1671 char *base64_authenticator = tor_malloc(base64_authenticator_length);
1672 if (base64_encode(base64_authenticator, base64_authenticator_length,
1673 authenticator, authenticator_length) < 0) {
1674 tor_free(base64_authenticator); /* free and set to null */
1675 } else {
1676 /* remove extra \n at end of encoding */
1677 base64_authenticator[strlen(base64_authenticator) - 1] = 0;
1679 return base64_authenticator;
1682 /** Process new bytes that have arrived on conn-\>inbuf.
1684 * This function just passes conn to the connection-specific
1685 * connection_*_process_inbuf() function. It also passes in
1686 * package_partial if wanted.
1688 static int
1689 connection_process_inbuf(connection_t *conn, int package_partial)
1691 tor_assert(conn);
1693 switch (conn->type) {
1694 case CONN_TYPE_OR:
1695 return connection_or_process_inbuf(conn);
1696 case CONN_TYPE_EXIT:
1697 case CONN_TYPE_AP:
1698 return connection_edge_process_inbuf(conn, package_partial);
1699 case CONN_TYPE_DIR:
1700 return connection_dir_process_inbuf(conn);
1701 case CONN_TYPE_DNSWORKER:
1702 return connection_dns_process_inbuf(conn);
1703 case CONN_TYPE_CPUWORKER:
1704 return connection_cpu_process_inbuf(conn);
1705 case CONN_TYPE_CONTROL:
1706 return connection_control_process_inbuf(conn);
1707 default:
1708 log_fn(LOG_WARN,"Bug: got unexpected conn type %d.", conn->type);
1709 tor_fragile_assert();
1710 return -1;
1714 /** We just finished flushing bytes from conn-\>outbuf, and there
1715 * are no more bytes remaining.
1717 * This function just passes conn to the connection-specific
1718 * connection_*_finished_flushing() function.
1720 static int
1721 connection_finished_flushing(connection_t *conn)
1723 tor_assert(conn);
1725 // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
1727 switch (conn->type) {
1728 case CONN_TYPE_OR:
1729 return connection_or_finished_flushing(conn);
1730 case CONN_TYPE_AP:
1731 case CONN_TYPE_EXIT:
1732 return connection_edge_finished_flushing(conn);
1733 case CONN_TYPE_DIR:
1734 return connection_dir_finished_flushing(conn);
1735 case CONN_TYPE_DNSWORKER:
1736 return connection_dns_finished_flushing(conn);
1737 case CONN_TYPE_CPUWORKER:
1738 return connection_cpu_finished_flushing(conn);
1739 case CONN_TYPE_CONTROL:
1740 return connection_control_finished_flushing(conn);
1741 default:
1742 log_fn(LOG_WARN,"Bug: got unexpected conn type %d.", conn->type);
1743 tor_fragile_assert();
1744 return -1;
1748 /** Called when our attempt to connect() to another server has just
1749 * succeeded.
1751 * This function just passes conn to the connection-specific
1752 * connection_*_finished_connecting() function.
1754 static int
1755 connection_finished_connecting(connection_t *conn)
1757 tor_assert(conn);
1758 switch (conn->type)
1760 case CONN_TYPE_OR:
1761 return connection_or_finished_connecting(conn);
1762 case CONN_TYPE_EXIT:
1763 return connection_edge_finished_connecting(conn);
1764 case CONN_TYPE_DIR:
1765 return connection_dir_finished_connecting(conn);
1766 default:
1767 log_fn(LOG_WARN,"Bug: got unexpected conn type %d.", conn->type);
1768 tor_fragile_assert();
1769 return -1;
1773 /** Callback: invoked when a connection reaches an EOF event. */
1774 static int
1775 connection_reached_eof(connection_t *conn)
1777 switch (conn->type) {
1778 case CONN_TYPE_OR:
1779 return connection_or_reached_eof(conn);
1780 case CONN_TYPE_AP:
1781 case CONN_TYPE_EXIT:
1782 return connection_edge_reached_eof(conn);
1783 case CONN_TYPE_DIR:
1784 return connection_dir_reached_eof(conn);
1785 case CONN_TYPE_DNSWORKER:
1786 return connection_dns_reached_eof(conn);
1787 case CONN_TYPE_CPUWORKER:
1788 return connection_cpu_reached_eof(conn);
1789 case CONN_TYPE_CONTROL:
1790 return connection_control_reached_eof(conn);
1791 default:
1792 log_fn(LOG_WARN,"Bug: got unexpected conn type %d.", conn->type);
1793 tor_fragile_assert();
1794 return -1;
1798 /** Verify that connection <b>conn</b> has all of its invariants
1799 * correct. Trigger an assert if anything is invalid.
1801 void
1802 assert_connection_ok(connection_t *conn, time_t now)
1804 tor_assert(conn);
1805 tor_assert(conn->magic == CONNECTION_MAGIC);
1806 tor_assert(conn->type >= _CONN_TYPE_MIN);
1807 tor_assert(conn->type <= _CONN_TYPE_MAX);
1809 if (conn->outbuf_flushlen > 0) {
1810 tor_assert(connection_is_writing(conn) || conn->wants_to_write);
1813 if (conn->hold_open_until_flushed)
1814 tor_assert(conn->marked_for_close);
1816 /* XXX check: wants_to_read, wants_to_write, s, poll_index,
1817 * marked_for_close. */
1819 /* buffers */
1820 if (!connection_is_listener(conn)) {
1821 assert_buf_ok(conn->inbuf);
1822 assert_buf_ok(conn->outbuf);
1825 /* XXX Fix this; no longer so.*/
1826 #if 0
1827 if (conn->type != CONN_TYPE_OR && conn->type != CONN_TYPE_DIR)
1828 tor_assert(!conn->pkey);
1829 /* pkey is set if we're a dir client, or if we're an OR in state OPEN
1830 * connected to another OR.
1832 #endif
1834 if (conn->type != CONN_TYPE_OR) {
1835 tor_assert(!conn->tls);
1836 } else {
1837 if (conn->state == OR_CONN_STATE_OPEN) {
1838 /* tor_assert(conn->bandwidth > 0); */
1839 /* the above isn't necessarily true: if we just did a TLS
1840 * handshake but we didn't recognize the other peer, or it
1841 * gave a bad cert/etc, then we won't have assigned bandwidth,
1842 * yet it will be open. -RD
1844 // tor_assert(conn->receiver_bucket >= 0);
1846 // tor_assert(conn->addr && conn->port);
1847 tor_assert(conn->address);
1848 if (conn->state > OR_CONN_STATE_PROXY_READING)
1849 tor_assert(conn->tls);
1852 if (! CONN_IS_EDGE(conn)) {
1853 tor_assert(!conn->stream_id);
1854 tor_assert(!conn->next_stream);
1855 tor_assert(!conn->cpath_layer);
1856 tor_assert(!conn->package_window);
1857 tor_assert(!conn->deliver_window);
1858 tor_assert(!conn->done_sending);
1859 tor_assert(!conn->done_receiving);
1860 } else {
1861 /* XXX unchecked: package window, deliver window. */
1863 if (conn->type == CONN_TYPE_AP) {
1864 tor_assert(conn->socks_request);
1865 if (conn->state == AP_CONN_STATE_OPEN) {
1866 tor_assert(conn->socks_request->has_finished);
1867 if (!conn->marked_for_close) {
1868 tor_assert(conn->cpath_layer);
1869 assert_cpath_layer_ok(conn->cpath_layer);
1872 } else {
1873 tor_assert(!conn->socks_request);
1875 if (conn->type == CONN_TYPE_EXIT) {
1876 tor_assert(conn->purpose == EXIT_PURPOSE_CONNECT ||
1877 conn->purpose == EXIT_PURPOSE_RESOLVE);
1878 } else if (conn->type != CONN_TYPE_DIR) {
1879 tor_assert(!conn->purpose); /* only used for dir types currently */
1882 switch (conn->type)
1884 case CONN_TYPE_OR_LISTENER:
1885 case CONN_TYPE_AP_LISTENER:
1886 case CONN_TYPE_DIR_LISTENER:
1887 case CONN_TYPE_CONTROL_LISTENER:
1888 tor_assert(conn->state == LISTENER_STATE_READY);
1889 break;
1890 case CONN_TYPE_OR:
1891 tor_assert(conn->state >= _OR_CONN_STATE_MIN);
1892 tor_assert(conn->state <= _OR_CONN_STATE_MAX);
1893 break;
1894 case CONN_TYPE_EXIT:
1895 tor_assert(conn->state >= _EXIT_CONN_STATE_MIN);
1896 tor_assert(conn->state <= _EXIT_CONN_STATE_MAX);
1897 break;
1898 case CONN_TYPE_AP:
1899 tor_assert(conn->state >= _AP_CONN_STATE_MIN);
1900 tor_assert(conn->state <= _AP_CONN_STATE_MAX);
1901 tor_assert(conn->socks_request);
1902 break;
1903 case CONN_TYPE_DIR:
1904 tor_assert(conn->state >= _DIR_CONN_STATE_MIN);
1905 tor_assert(conn->state <= _DIR_CONN_STATE_MAX);
1906 tor_assert(conn->purpose >= _DIR_PURPOSE_MIN);
1907 tor_assert(conn->purpose <= _DIR_PURPOSE_MAX);
1908 break;
1909 case CONN_TYPE_DNSWORKER:
1910 tor_assert(conn->state == DNSWORKER_STATE_IDLE ||
1911 conn->state == DNSWORKER_STATE_BUSY);
1912 break;
1913 case CONN_TYPE_CPUWORKER:
1914 tor_assert(conn->state >= _CPUWORKER_STATE_MIN);
1915 tor_assert(conn->state <= _CPUWORKER_STATE_MAX);
1916 break;
1917 case CONN_TYPE_CONTROL:
1918 tor_assert(conn->state >= _CONTROL_CONN_STATE_MIN);
1919 tor_assert(conn->state <= _CONTROL_CONN_STATE_MAX);
1920 break;
1921 default:
1922 tor_assert(0);