update copyright notices.
[tor.git] / src / or / connection.c
blobee51ef8d9c7daddd5cfac6d99ea6f6bab80b286b
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 /********* START VARIABLES **********/
18 /** Array of strings to make conn-\>type human-readable. */
19 const char *conn_type_to_string[] = {
20 "", /* 0 */
21 "OP listener", /* 1 */
22 "OP", /* 2 */
23 "OR listener", /* 3 */
24 "OR", /* 4 */
25 "Exit", /* 5 */
26 "App listener",/* 6 */
27 "App", /* 7 */
28 "Dir listener",/* 8 */
29 "Dir", /* 9 */
30 "DNS worker", /* 10 */
31 "CPU worker", /* 11 */
32 "Control listener", /* 12 */
33 "Control", /* 13 */
36 /** Array of string arrays to make {conn-\>type,conn-\>state} human-readable. */
37 const char *conn_state_to_string[][_CONN_TYPE_MAX+1] = {
38 { NULL }, /* no type associated with 0 */
39 { NULL }, /* op listener, obsolete */
40 { NULL }, /* op, obsolete */
41 { "ready" }, /* or listener, 0 */
42 { "", /* OR, 0 */
43 "connect()ing", /* 1 */
44 "handshaking", /* 2 */
45 "open" }, /* 3 */
46 { "", /* exit, 0 */
47 "waiting for dest info", /* 1 */
48 "connecting", /* 2 */
49 "open", /* 3 */
50 "resolve failed" }, /* 4 */
51 { "ready" }, /* app listener, 0 */
52 { "", /* 0 */
53 "", /* 1 */
54 "", /* 2 */
55 "", /* 3 */
56 "", /* 4 */
57 "awaiting dest info", /* app, 5 */
58 "waiting for rendezvous desc", /* 6 */
59 "waiting for controller", /* 7 */
60 "waiting for safe circuit", /* 8 */
61 "waiting for connected", /* 9 */
62 "waiting for resolve", /* 10 */
63 "open" }, /* 11 */
64 { "ready" }, /* dir listener, 0 */
65 { "", /* dir, 0 */
66 "connecting", /* 1 */
67 "client sending", /* 2 */
68 "client reading", /* 3 */
69 "awaiting command", /* 4 */
70 "writing" }, /* 5 */
71 { "", /* dns worker, 0 */
72 "idle", /* 1 */
73 "busy" }, /* 2 */
74 { "", /* cpu worker, 0 */
75 "idle", /* 1 */
76 "busy with onion", /* 2 */
77 "busy with handshake" }, /* 3 */
78 { "ready" }, /* control listener, 0 */
79 { "", /* control, 0 */
80 "ready", /* 1 */
81 "waiting for authentication", }, /* 2 */
84 /********* END VARIABLES ************/
86 static int connection_create_listener(const char *bindaddress,
87 uint16_t bindport, int type);
88 static int connection_init_accepted_conn(connection_t *conn);
89 static int connection_handle_listener_read(connection_t *conn, int new_type);
90 static int connection_receiver_bucket_should_increase(connection_t *conn);
91 static int connection_finished_flushing(connection_t *conn);
92 static int connection_finished_connecting(connection_t *conn);
93 static int connection_reached_eof(connection_t *conn);
94 static int connection_read_to_buf(connection_t *conn, int *max_to_read);
95 static int connection_process_inbuf(connection_t *conn, int package_partial);
96 static int connection_bucket_read_limit(connection_t *conn);
98 /**************************************************************/
100 /** Allocate space for a new connection_t. This function just initializes
101 * conn; you must call connection_add() to link it into the main array.
103 * Set conn-\>type to <b>type</b>. Set conn-\>s and conn-\>poll_index to
104 * -1 to signify they are not yet assigned.
106 * If conn is not a listener type, allocate buffers for it. If it's
107 * an AP type, allocate space to store the socks_request.
109 * Assign a pseudorandom next_circ_id between 0 and 2**15.
111 * Initialize conn's timestamps to now.
113 connection_t *connection_new(int type) {
114 static uint32_t n_connections_allocated = 0;
115 connection_t *conn;
116 time_t now = time(NULL);
118 conn = tor_malloc_zero(sizeof(connection_t));
119 conn->magic = CONNECTION_MAGIC;
120 conn->s = -1; /* give it a default of 'not used' */
121 conn->poll_index = -1; /* also default to 'not used' */
122 conn->global_identifier = n_connections_allocated++;
124 conn->type = type;
125 if (!connection_is_listener(conn)) { /* listeners never use their buf */
126 conn->inbuf = buf_new();
127 conn->outbuf = buf_new();
129 if (type == CONN_TYPE_AP) {
130 conn->socks_request = tor_malloc_zero(sizeof(socks_request_t));
133 conn->next_circ_id = crypto_pseudo_rand_int(1<<15);
135 conn->timestamp_created = now;
136 conn->timestamp_lastread = now;
137 conn->timestamp_lastwritten = now;
139 return conn;
142 /** Tell libevent that we don't care about <b>conn</b> any more. */
143 void
144 connection_unregister(connection_t *conn)
146 if (conn->read_event) {
147 if (event_del(conn->read_event))
148 log_fn(LOG_WARN, "Error removing read event for %d", (int)conn->s);
149 tor_free(conn->read_event);
151 if (conn->write_event) {
152 if (event_del(conn->write_event))
153 log_fn(LOG_WARN, "Error removing write event for %d", (int)conn->s);
154 tor_free(conn->write_event);
158 /** Deallocate memory used by <b>conn</b>. Deallocate its buffers if necessary,
159 * close its socket if necessary, and mark the directory as dirty if <b>conn</b>
160 * is an OR or OP connection.
162 static void
163 _connection_free(connection_t *conn) {
164 tor_assert(conn->magic == CONNECTION_MAGIC);
166 if (!connection_is_listener(conn)) {
167 buf_free(conn->inbuf);
168 buf_free(conn->outbuf);
170 tor_free(conn->address);
171 tor_free(conn->chosen_exit_name);
173 if (connection_speaks_cells(conn)) {
174 if (conn->state == OR_CONN_STATE_OPEN)
175 directory_set_dirty();
176 if (conn->tls) {
177 tor_tls_free(conn->tls);
178 conn->tls = NULL;
182 if (conn->identity_pkey)
183 crypto_free_pk_env(conn->identity_pkey);
184 tor_free(conn->nickname);
185 tor_free(conn->socks_request);
187 connection_unregister(conn);
189 if (conn->s >= 0) {
190 log_fn(LOG_INFO,"closing fd %d.",conn->s);
191 tor_close_socket(conn->s);
194 memset(conn, 0xAA, sizeof(connection_t)); /* poison memory */
195 tor_free(conn);
198 /** Make sure <b>conn</b> isn't in any of the global conn lists; then free it.
200 void connection_free(connection_t *conn) {
201 tor_assert(conn);
202 tor_assert(!connection_is_on_closeable_list(conn));
203 tor_assert(!connection_in_array(conn));
204 _connection_free(conn);
207 /** Call _connection_free() on every connection in our array.
208 * This is used by cpuworkers and dnsworkers when they fork,
209 * so they don't keep resources held open (especially sockets).
211 * Don't do the checks in connection_free(), because they will
212 * fail.
214 void connection_free_all(void) {
215 int i, n;
216 connection_t **carray;
218 get_connection_array(&carray,&n);
219 for (i=0;i<n;i++)
220 _connection_free(carray[i]);
223 /** Do any cleanup needed:
224 * - Directory conns that failed to fetch a rendezvous descriptor
225 * need to inform pending rendezvous streams.
226 * - OR conns need to call rep_hist_note_*() to record status.
227 * - AP conns need to send a socks reject if necessary.
228 * - Exit conns need to call connection_dns_remove() if necessary.
229 * - AP and Exit conns need to send an end cell if they can.
230 * - DNS conns need to fail any resolves that are pending on them.
232 void connection_about_to_close_connection(connection_t *conn)
234 circuit_t *circ;
236 assert(conn->marked_for_close);
238 if (CONN_IS_EDGE(conn)) {
239 if (!conn->has_sent_end) {
240 log_fn(LOG_WARN,"Harmless bug: Edge connection (marked at %s:%d) hasn't sent end yet?", conn->marked_for_close_file, conn->marked_for_close);
241 #ifdef TOR_FRAGILE
242 tor_assert(0);
243 #endif
247 switch (conn->type) {
248 case CONN_TYPE_DIR:
249 if (conn->state == DIR_CONN_STATE_CONNECTING) {
250 /* it's a directory server and connecting failed: forget about
251 this router */
252 connection_dir_connect_failed(conn);
254 if (conn->purpose == DIR_PURPOSE_FETCH_RENDDESC)
255 rend_client_desc_here(conn->rend_query); /* give it a try */
256 break;
257 case CONN_TYPE_OR:
258 /* Remember why we're closing this connection. */
259 if (conn->state != OR_CONN_STATE_OPEN) {
260 if (connection_or_nonopen_was_started_here(conn)) {
261 rep_hist_note_connect_failed(conn->identity_digest, time(NULL));
262 control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED);
264 } else if (conn->hold_open_until_flushed) {
265 /* XXXX009 We used to have an arg that told us whether we closed the
266 * connection on purpose or not. Can we use hold_open_until_flushed
267 * instead? We only set it when we are intentionally closing a
268 * connection. -NM
270 * (Of course, now things we set to close which expire rather than
271 * flushing still get noted as dead, not disconnected. But this is an
272 * improvement. -NM
274 rep_hist_note_disconnect(conn->identity_digest, time(NULL));
275 control_event_or_conn_status(conn, OR_CONN_EVENT_CLOSED);
276 } else if (conn->identity_digest) {
277 rep_hist_note_connection_died(conn->identity_digest, time(NULL));
278 control_event_or_conn_status(conn, OR_CONN_EVENT_CLOSED);
280 break;
281 case CONN_TYPE_AP:
282 if (conn->socks_request->has_finished == 0) {
283 /* since conn gets removed right after this function finishes,
284 * there's no point trying to send back a reply at this point. */
285 log_fn(LOG_WARN,"Bug: Closing stream (marked at %s:%d) without sending back a socks reply.",
286 conn->marked_for_close_file, conn->marked_for_close);
287 } else {
288 control_event_stream_status(conn, STREAM_EVENT_CLOSED);
290 break;
291 case CONN_TYPE_EXIT:
292 if (conn->state == EXIT_CONN_STATE_RESOLVING) {
293 circ = circuit_get_by_conn(conn);
294 if (circ)
295 circuit_detach_stream(circ, conn);
296 connection_dns_remove(conn);
298 break;
299 case CONN_TYPE_DNSWORKER:
300 if (conn->state == DNSWORKER_STATE_BUSY) {
301 dns_cancel_pending_resolve(conn->address);
303 break;
307 /** Close the underlying socket for <b>conn</b>, so we don't try to
308 * flush it. Must be used in conjunction with (right before)
309 * connection_mark_for_close().
311 void connection_close_immediate(connection_t *conn)
313 assert_connection_ok(conn,0);
314 if (conn->s < 0) {
315 log_fn(LOG_WARN,"Bug: Attempt to close already-closed connection.");
316 #ifdef TOR_FRAGILE
317 tor_assert(0);
318 #endif
319 return;
321 if (conn->outbuf_flushlen) {
322 log_fn(LOG_INFO,"fd %d, type %s, state %d, %d bytes on outbuf.",
323 conn->s, CONN_TYPE_TO_STRING(conn->type),
324 conn->state, (int)conn->outbuf_flushlen);
327 connection_unregister(conn);
329 tor_close_socket(conn->s);
330 conn->s = -1;
331 if (!connection_is_listener(conn)) {
332 buf_clear(conn->outbuf);
333 conn->outbuf_flushlen = 0;
337 /** Mark <b>conn</b> to be closed next time we loop through
338 * conn_close_if_marked() in main.c. */
340 _connection_mark_for_close(connection_t *conn)
342 assert_connection_ok(conn,0);
344 if (conn->marked_for_close) {
345 log(LOG_WARN, "Bug: Double mark-for-close on connection.");
346 #ifdef TOR_FRAGILE
347 tor_assert(0);
348 #endif
349 return -1;
352 conn->marked_for_close = 1;
353 add_connection_to_closeable_list(conn);
355 /* in case we're going to be held-open-til-flushed, reset
356 * the number of seconds since last successful write, so
357 * we get our whole 15 seconds */
358 conn->timestamp_lastwritten = time(NULL);
360 return 0;
363 /** Find each connection that has hold_open_until_flushed set to
364 * 1 but hasn't written in the past 15 seconds, and set
365 * hold_open_until_flushed to 0. This means it will get cleaned
366 * up in the next loop through close_if_marked() in main.c.
368 void connection_expire_held_open(void)
370 connection_t **carray, *conn;
371 int n, i;
372 time_t now;
374 now = time(NULL);
376 get_connection_array(&carray, &n);
377 for (i = 0; i < n; ++i) {
378 conn = carray[i];
379 /* If we've been holding the connection open, but we haven't written
380 * for 15 seconds...
382 if (conn->hold_open_until_flushed) {
383 tor_assert(conn->marked_for_close);
384 if (now - conn->timestamp_lastwritten >= 15) {
385 log_fn(LOG_NOTICE,"Giving up on marked_for_close conn that's been flushing for 15s (fd %d, type %s, state %d).",
386 conn->s, CONN_TYPE_TO_STRING(conn->type), conn->state);
387 conn->hold_open_until_flushed = 0;
393 /** Bind a new non-blocking socket listening to
394 * <b>bindaddress</b>:<b>bindport</b>, and add this new connection
395 * (of type <b>type</b>) to the connection array.
397 * If <b>bindaddress</b> includes a port, we bind on that port; otherwise, we
398 * use bindport.
400 static int connection_create_listener(const char *bindaddress, uint16_t bindport, int type) {
401 struct sockaddr_in bindaddr; /* where to bind */
402 connection_t *conn;
403 uint16_t usePort;
404 uint32_t addr;
405 int s; /* the socket we're going to make */
406 #ifndef MS_WINDOWS
407 int one=1;
408 #endif
410 memset(&bindaddr,0,sizeof(struct sockaddr_in));
411 if (parse_addr_port(bindaddress, NULL, &addr, &usePort)<0) {
412 log_fn(LOG_WARN, "Error parsing/resolving BindAddress %s",bindaddress);
413 return -1;
416 if (usePort==0)
417 usePort = bindport;
418 bindaddr.sin_addr.s_addr = htonl(addr);
419 bindaddr.sin_family = AF_INET;
420 bindaddr.sin_port = htons((uint16_t) usePort);
422 s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
423 if (s < 0) {
424 log_fn(LOG_WARN,"Socket creation failed.");
425 return -1;
426 } else if (!SOCKET_IS_POLLABLE(s)) {
427 log_fn(LOG_WARN,"Too many connections; can't create pollable listener.");
428 tor_close_socket(s);
429 return -1;
432 #ifndef MS_WINDOWS
433 /* REUSEADDR on normal places means you can rebind to the port
434 * right after somebody else has let it go. But REUSEADDR on win32
435 * means to let you bind to the port _even when somebody else
436 * already has it bound_. So, don't do that on Win32. */
437 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*) &one, sizeof(one));
438 #endif
440 if (bind(s,(struct sockaddr *)&bindaddr,sizeof(bindaddr)) < 0) {
441 log_fn(LOG_WARN,"Could not bind to port %u: %s",usePort,
442 tor_socket_strerror(tor_socket_errno(s)));
443 return -1;
446 if (listen(s,SOMAXCONN) < 0) {
447 log_fn(LOG_WARN,"Could not listen on port %u: %s",usePort,
448 tor_socket_strerror(tor_socket_errno(s)));
449 return -1;
452 set_socket_nonblocking(s);
454 conn = connection_new(type);
455 conn->s = s;
457 if (connection_add(conn) < 0) { /* no space, forget it */
458 log_fn(LOG_WARN,"connection_add failed. Giving up.");
459 connection_free(conn);
460 return -1;
463 log_fn(LOG_DEBUG,"%s listening on port %u.",conn_type_to_string[type], usePort);
465 conn->state = LISTENER_STATE_READY;
466 connection_start_reading(conn);
468 return 0;
471 /** The listener connection <b>conn</b> told poll() it wanted to read.
472 * Call accept() on conn-\>s, and add the new connection if necessary.
474 static int connection_handle_listener_read(connection_t *conn, int new_type) {
475 int news; /* the new socket */
476 connection_t *newconn;
477 /* information about the remote peer when connecting to other routers */
478 struct sockaddr_in remote;
479 /* length of the remote address. Must be an int, since accept() needs that. */
480 int remotelen = sizeof(struct sockaddr_in);
481 char tmpbuf[INET_NTOA_BUF_LEN];
483 news = accept(conn->s,(struct sockaddr *)&remote,&remotelen);
484 if (!SOCKET_IS_POLLABLE(news)) {
485 /* accept() error, or too many conns to poll */
486 int e;
487 if (news>=0) {
488 /* Too many conns to poll. */
489 log_fn(LOG_WARN,"Too many connections; couldn't accept connection.");
490 tor_close_socket(news);
491 return 0;
493 e = tor_socket_errno(conn->s);
494 if (ERRNO_IS_ACCEPT_EAGAIN(e)) {
495 return 0; /* he hung up before we could accept(). that's fine. */
496 } else if (ERRNO_IS_ACCEPT_RESOURCE_LIMIT(e)) {
497 log_fn(LOG_NOTICE,"accept failed: %s. Dropping incoming connection.",
498 tor_socket_strerror(e));
499 return 0;
501 /* else there was a real error. */
502 log_fn(LOG_WARN,"accept() failed: %s. Closing listener.",
503 tor_socket_strerror(e));
504 connection_mark_for_close(conn);
505 return -1;
507 log(LOG_INFO,"Connection accepted on socket %d (child of fd %d).",news, conn->s);
509 set_socket_nonblocking(news);
511 /* process entrance policies here, before we even create the connection */
512 if (new_type == CONN_TYPE_AP) {
513 /* check sockspolicy to see if we should accept it */
514 if (socks_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
515 tor_inet_ntoa(&remote.sin_addr, tmpbuf, sizeof(tmpbuf));
516 log_fn(LOG_NOTICE,"Denying socks connection from untrusted address %s.",
517 tmpbuf);
518 tor_close_socket(news);
519 return 0;
522 if (new_type == CONN_TYPE_DIR) {
523 /* check dirpolicy to see if we should accept it */
524 if (dir_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
525 tor_inet_ntoa(&remote.sin_addr, tmpbuf, sizeof(tmpbuf));
526 log_fn(LOG_NOTICE,"Denying dir connection from address %s.",
527 tmpbuf);
528 tor_close_socket(news);
529 return 0;
533 newconn = connection_new(new_type);
534 newconn->s = news;
536 /* remember the remote address */
537 newconn->address = tor_malloc(INET_NTOA_BUF_LEN);
538 tor_inet_ntoa(&remote.sin_addr, newconn->address, INET_NTOA_BUF_LEN);
540 newconn->addr = ntohl(remote.sin_addr.s_addr);
541 newconn->port = ntohs(remote.sin_port);
543 if (connection_add(newconn) < 0) { /* no space, forget it */
544 connection_free(newconn);
545 return 0; /* no need to tear down the parent */
548 if (connection_init_accepted_conn(newconn) < 0) {
549 connection_mark_for_close(newconn);
550 return 0;
552 return 0;
555 /** Initialize states for newly accepted connection <b>conn</b>.
556 * If conn is an OR, start the tls handshake.
558 static int connection_init_accepted_conn(connection_t *conn) {
560 connection_start_reading(conn);
562 switch (conn->type) {
563 case CONN_TYPE_OR:
564 return connection_tls_start_handshake(conn, 1);
565 case CONN_TYPE_AP:
566 conn->state = AP_CONN_STATE_SOCKS_WAIT;
567 break;
568 case CONN_TYPE_DIR:
569 conn->purpose = DIR_PURPOSE_SERVER;
570 conn->state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
571 break;
572 case CONN_TYPE_CONTROL:
573 conn->state = CONTROL_CONN_STATE_NEEDAUTH;
574 break;
576 return 0;
579 /** Take conn, make a nonblocking socket; try to connect to
580 * addr:port (they arrive in *host order*). If fail, return -1. Else
581 * assign s to conn->\s: if connected return 1, if EAGAIN return 0.
583 * address is used to make the logs useful.
585 * On success, add conn to the list of polled connections.
587 int connection_connect(connection_t *conn, char *address, uint32_t addr, uint16_t port) {
588 int s;
589 struct sockaddr_in dest_addr;
590 or_options_t *options = get_options();
592 s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
593 if (s < 0) {
594 log_fn(LOG_WARN,"Error creating network socket: %s",
595 tor_socket_strerror(tor_socket_errno(-1)));
596 return -1;
597 } else if (!SOCKET_IS_POLLABLE(s)) {
598 log_fn(LOG_WARN,
599 "Too many connections; can't create pollable connection to %s", address);
600 tor_close_socket(s);
601 return -1;
604 if (options->OutboundBindAddress) {
605 struct sockaddr_in ext_addr;
607 memset(&ext_addr, 0, sizeof(ext_addr));
608 ext_addr.sin_family = AF_INET;
609 ext_addr.sin_port = 0;
610 if (!tor_inet_aton(options->OutboundBindAddress, &ext_addr.sin_addr)) {
611 log_fn(LOG_WARN,"Outbound bind address '%s' didn't parse. Ignoring.",
612 options->OutboundBindAddress);
613 } else {
614 if (bind(s, (struct sockaddr*)&ext_addr, sizeof(ext_addr)) < 0) {
615 log_fn(LOG_WARN,"Error binding network socket: %s",
616 tor_socket_strerror(tor_socket_errno(s)));
617 return -1;
622 set_socket_nonblocking(s);
624 memset(&dest_addr,0,sizeof(dest_addr));
625 dest_addr.sin_family = AF_INET;
626 dest_addr.sin_port = htons(port);
627 dest_addr.sin_addr.s_addr = htonl(addr);
629 log_fn(LOG_DEBUG,"Connecting to %s:%u.",address,port);
631 if (connect(s,(struct sockaddr *)&dest_addr,sizeof(dest_addr)) < 0) {
632 int e = tor_socket_errno(s);
633 if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
634 /* yuck. kill it. */
635 log_fn(LOG_INFO,"Connect() to %s:%u failed: %s",address,port,
636 tor_socket_strerror(e));
637 tor_close_socket(s);
638 return -1;
639 } else {
640 /* it's in progress. set state appropriately and return. */
641 conn->s = s;
642 if (connection_add(conn) < 0) /* no space, forget it */
643 return -1;
644 log_fn(LOG_DEBUG,"connect in progress, socket %d.",s);
645 return 0;
649 /* it succeeded. we're connected. */
650 log_fn(LOG_INFO,"Connection to %s:%u established.",address,port);
651 conn->s = s;
652 if (connection_add(conn) < 0) /* no space, forget it */
653 return -1;
654 return 1;
657 /** If there exist any listeners of type <b>type</b> in the connection
658 * array, mark them for close.
660 static void listener_close_if_present(int type) {
661 connection_t *conn;
662 connection_t **carray;
663 int i,n;
664 tor_assert(type == CONN_TYPE_OR_LISTENER ||
665 type == CONN_TYPE_AP_LISTENER ||
666 type == CONN_TYPE_DIR_LISTENER ||
667 type == CONN_TYPE_CONTROL_LISTENER);
668 get_connection_array(&carray,&n);
669 for (i=0;i<n;i++) {
670 conn = carray[i];
671 if (conn->type == type && !conn->marked_for_close) {
672 connection_close_immediate(conn);
673 connection_mark_for_close(conn);
679 * Launch any configured listener connections of type <b>type</b>. (A
680 * listener is configured if <b>port_option</b> is non-zero. If any
681 * BindAddress configuration options are given in <b>cfg</b>, create a
682 * connection binding to each one. Otherwise, create a single
683 * connection binding to the address <b>default_addr</b>.)
685 * If <b>force</b> is true, close and re-open all listener connections.
686 * Otherwise, only relaunch the listeners of this type if the number of
687 * existing connections is not as configured (e.g., because one died).
689 static int retry_listeners(int type, struct config_line_t *cfg,
690 int port_option, const char *default_addr,
691 int force)
693 if (!force) {
694 int want, have, n_conn, i;
695 struct config_line_t *c;
696 connection_t *conn;
697 connection_t **carray;
698 /* How many should there be? */
699 if (cfg && port_option) {
700 want = 0;
701 for (c = cfg; c; c = c->next)
702 ++want;
703 } else if (port_option) {
704 want = 1;
705 } else {
706 want = 0;
709 /* How many are there actually? */
710 have = 0;
711 get_connection_array(&carray,&n_conn);
712 for (i=0;i<n_conn;i++) {
713 conn = carray[i];
714 if (conn->type == type && !conn->marked_for_close)
715 ++have;
718 /* If we have the right number of listeners, do nothing. */
719 if (have == want)
720 return 0;
722 /* Otherwise, warn the user and relaunch. */
723 log_fn(LOG_NOTICE,"We have %d %s(s) open, but we want %d; relaunching.",
724 have, conn_type_to_string[type], want);
727 listener_close_if_present(type);
728 if (port_option) {
729 if (!cfg) {
730 if (connection_create_listener(default_addr, (uint16_t) port_option,
731 type)<0)
732 return -1;
733 } else {
734 for ( ; cfg; cfg = cfg->next) {
735 if (connection_create_listener(cfg->value, (uint16_t) port_option,
736 type)<0)
737 return -1;
741 return 0;
744 /** (Re)launch listeners for each port you should have open. If
745 * <b>force</b> is true, close and relaunch all listeners. If <b>force</b>
746 * is false, then only relaunch listeners when we have the wrong number of
747 * connections for a given type.
749 int retry_all_listeners(int force) {
750 or_options_t *options = get_options();
752 if (retry_listeners(CONN_TYPE_OR_LISTENER, options->ORBindAddress,
753 options->ORPort, "0.0.0.0", force)<0)
754 return -1;
755 if (retry_listeners(CONN_TYPE_DIR_LISTENER, options->DirBindAddress,
756 options->DirPort, "0.0.0.0", force)<0)
757 return -1;
758 if (retry_listeners(CONN_TYPE_AP_LISTENER, options->SocksBindAddress,
759 options->SocksPort, "127.0.0.1", force)<0)
760 return -1;
761 if (retry_listeners(CONN_TYPE_CONTROL_LISTENER, NULL,
762 options->ControlPort, "127.0.0.1", force)<0)
763 return -1;
765 return 0;
768 extern int global_read_bucket, global_write_bucket;
770 /** How many bytes at most can we read onto this connection? */
771 static int connection_bucket_read_limit(connection_t *conn) {
772 int at_most;
774 /* do a rudimentary round-robin so one circuit can't hog a connection */
775 if (connection_speaks_cells(conn)) {
776 at_most = 32*(CELL_NETWORK_SIZE);
777 } else {
778 at_most = 32*(RELAY_PAYLOAD_SIZE);
781 if (at_most > global_read_bucket)
782 at_most = global_read_bucket;
784 if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN)
785 if (at_most > conn->receiver_bucket)
786 at_most = conn->receiver_bucket;
788 if (at_most < 0)
789 return 0;
790 return at_most;
793 /** We just read num_read onto conn. Decrement buckets appropriately. */
794 static void connection_read_bucket_decrement(connection_t *conn, int num_read) {
795 global_read_bucket -= num_read; //tor_assert(global_read_bucket >= 0);
796 if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
797 conn->receiver_bucket -= num_read; //tor_assert(conn->receiver_bucket >= 0);
801 static void connection_consider_empty_buckets(connection_t *conn) {
802 if (global_read_bucket <= 0) {
803 log_fn(LOG_DEBUG,"global bucket exhausted. Pausing.");
804 conn->wants_to_read = 1;
805 connection_stop_reading(conn);
806 return;
808 if (connection_speaks_cells(conn) &&
809 conn->state == OR_CONN_STATE_OPEN &&
810 conn->receiver_bucket <= 0) {
811 log_fn(LOG_DEBUG,"receiver bucket exhausted. Pausing.");
812 conn->wants_to_read = 1;
813 connection_stop_reading(conn);
817 /** Initialize the global read bucket to options->BandwidthBurst,
818 * and current_time to the current time. */
819 void connection_bucket_init(void) {
820 or_options_t *options = get_options();
821 global_read_bucket = (int)options->BandwidthBurst; /* start it at max traffic */
822 global_write_bucket = (int)options->BandwidthBurst; /* start it at max traffic */
825 /** A second has rolled over; increment buckets appropriately. */
826 void connection_bucket_refill(struct timeval *now) {
827 int i, n;
828 connection_t *conn;
829 connection_t **carray;
830 or_options_t *options = get_options();
832 /* refill the global buckets */
833 if (global_read_bucket < (int)options->BandwidthBurst) {
834 global_read_bucket += (int)options->BandwidthRate;
835 log_fn(LOG_DEBUG,"global_read_bucket now %d.", global_read_bucket);
837 if (global_write_bucket < (int)options->BandwidthBurst) {
838 global_write_bucket += (int)options->BandwidthRate;
839 log_fn(LOG_DEBUG,"global_write_bucket now %d.", global_write_bucket);
842 /* refill the per-connection buckets */
843 get_connection_array(&carray,&n);
844 for (i=0;i<n;i++) {
845 conn = carray[i];
847 if (connection_receiver_bucket_should_increase(conn)) {
848 conn->receiver_bucket = conn->bandwidth;
849 //log_fn(LOG_DEBUG,"Receiver bucket %d now %d.", i, conn->receiver_bucket);
852 if (conn->wants_to_read == 1 /* it's marked to turn reading back on now */
853 && global_read_bucket > 0 /* and we're allowed to read */
854 && global_write_bucket > 0 /* and we're allowed to write (XXXX,
855 * not the best place to check this.) */
856 && (!connection_speaks_cells(conn) ||
857 conn->state != OR_CONN_STATE_OPEN ||
858 conn->receiver_bucket > 0)) {
859 /* and either a non-cell conn or a cell conn with non-empty bucket */
860 log_fn(LOG_DEBUG,"waking up conn (fd %d)",conn->s);
861 conn->wants_to_read = 0;
862 connection_start_reading(conn);
863 if (conn->wants_to_write == 1) {
864 conn->wants_to_write = 0;
865 connection_start_writing(conn);
871 /** Is the receiver bucket for connection <b>conn</b> low enough that we
872 * should add another pile of tokens to it?
874 static int connection_receiver_bucket_should_increase(connection_t *conn) {
875 tor_assert(conn);
877 if (!connection_speaks_cells(conn))
878 return 0; /* edge connections don't use receiver_buckets */
879 if (conn->state != OR_CONN_STATE_OPEN)
880 return 0; /* only open connections play the rate limiting game */
882 if (conn->receiver_bucket >= conn->bandwidth)
883 return 0;
885 return 1;
888 /** Read bytes from conn->\s and process them.
890 * This function gets called from conn_read() in main.c, either
891 * when poll() has declared that conn wants to read, or (for OR conns)
892 * when there are pending TLS bytes.
894 * It calls connection_read_to_buf() to bring in any new bytes,
895 * and then calls connection_process_inbuf() to process them.
897 * Mark the connection and return -1 if you want to close it, else
898 * return 0.
900 int connection_handle_read(connection_t *conn) {
901 int max_to_read=-1, try_to_read;
903 conn->timestamp_lastread = time(NULL);
905 switch (conn->type) {
906 case CONN_TYPE_OR_LISTENER:
907 return connection_handle_listener_read(conn, CONN_TYPE_OR);
908 case CONN_TYPE_AP_LISTENER:
909 return connection_handle_listener_read(conn, CONN_TYPE_AP);
910 case CONN_TYPE_DIR_LISTENER:
911 return connection_handle_listener_read(conn, CONN_TYPE_DIR);
912 case CONN_TYPE_CONTROL_LISTENER:
913 return connection_handle_listener_read(conn, CONN_TYPE_CONTROL);
916 loop_again:
917 try_to_read = max_to_read;
918 tor_assert(!conn->marked_for_close);
919 if (connection_read_to_buf(conn, &max_to_read) < 0) {
920 /* There's a read error; kill the connection.*/
921 connection_close_immediate(conn); /* Don't flush; connection is dead. */
922 if (CONN_IS_EDGE(conn)) {
923 connection_edge_end_errno(conn, conn->cpath_layer);
925 connection_mark_for_close(conn);
926 return -1;
928 if (CONN_IS_EDGE(conn) &&
929 try_to_read != max_to_read) {
930 /* instruct it not to try to package partial cells. */
931 if (connection_process_inbuf(conn, 0) < 0) {
932 return -1;
934 if (!conn->marked_for_close &&
935 connection_is_reading(conn) &&
936 !conn->inbuf_reached_eof &&
937 max_to_read > 0)
938 goto loop_again; /* try reading again, in case more is here now */
940 /* one last try, packaging partial cells and all. */
941 if (!conn->marked_for_close &&
942 connection_process_inbuf(conn, 1) < 0) {
943 return -1;
945 if (!conn->marked_for_close &&
946 conn->inbuf_reached_eof &&
947 connection_reached_eof(conn) < 0) {
948 return -1;
950 return 0;
953 /** Pull in new bytes from conn-\>s onto conn-\>inbuf, either
954 * directly or via TLS. Reduce the token buckets by the number of
955 * bytes read.
957 * If *max_to_read is -1, then decide it ourselves, else go with the
958 * value passed to us. When returning, if it's changed, subtract the
959 * number of bytes we read from *max_to_read.
961 * Return -1 if we want to break conn, else return 0.
963 static int connection_read_to_buf(connection_t *conn, int *max_to_read) {
964 int result, at_most = *max_to_read;
966 if (at_most == -1) { /* we need to initialize it */
967 /* how many bytes are we allowed to read? */
968 at_most = connection_bucket_read_limit(conn);
971 if (connection_speaks_cells(conn) && conn->state > OR_CONN_STATE_PROXY_READING) {
972 int pending;
973 if (conn->state == OR_CONN_STATE_HANDSHAKING) {
974 /* continue handshaking even if global token bucket is empty */
975 return connection_tls_continue_handshake(conn);
978 log_fn(LOG_DEBUG,"%d: starting, inbuf_datalen %d (%d pending in tls object). at_most %d.",
979 conn->s,(int)buf_datalen(conn->inbuf),tor_tls_get_pending_bytes(conn->tls), at_most);
981 /* else open, or closing */
982 result = read_to_buf_tls(conn->tls, at_most, conn->inbuf);
984 switch (result) {
985 case TOR_TLS_CLOSE:
986 log_fn(LOG_INFO,"TLS connection closed on read. Closing. (Nickname %s, address %s",
987 conn->nickname ? conn->nickname : "not set", conn->address);
988 return -1;
989 case TOR_TLS_ERROR:
990 log_fn(LOG_INFO,"tls error. breaking (nickname %s, address %s).",
991 conn->nickname ? conn->nickname : "not set", conn->address);
992 return -1;
993 case TOR_TLS_WANTWRITE:
994 connection_start_writing(conn);
995 return 0;
996 case TOR_TLS_WANTREAD: /* we're already reading */
997 case TOR_TLS_DONE: /* no data read, so nothing to process */
998 result = 0;
999 break; /* so we call bucket_decrement below */
1000 default:
1001 break;
1003 pending = tor_tls_get_pending_bytes(conn->tls);
1004 if (pending) {
1005 /* XXXX If we have any pending bytes, read them now. This *can*
1006 * take us over our read alotment, but really we shouldn't be
1007 * believing that SSL bytes are the same as TCP bytes anyway. */
1008 int r2 = read_to_buf_tls(conn->tls, pending, conn->inbuf);
1009 if (r2<0) {
1010 log_fn(LOG_WARN, "Bug: apparently, reading pending bytes can fail.");
1011 return -1;
1012 } else {
1013 result += r2;
1017 } else {
1018 result = read_to_buf(conn->s, at_most, conn->inbuf,
1019 &conn->inbuf_reached_eof);
1021 // log_fn(LOG_DEBUG,"read_to_buf returned %d.",read_result);
1023 if (result < 0)
1024 return -1;
1027 if (result > 0) { /* change *max_to_read */
1028 *max_to_read = at_most - result;
1031 if (result > 0 && !is_local_IP(conn->addr)) { /* remember it */
1032 rep_hist_note_bytes_read(result, time(NULL));
1033 connection_read_bucket_decrement(conn, result);
1036 /* Call even if result is 0, since the global read bucket may
1037 * have reached 0 on a different conn, and this guy needs to
1038 * know to stop reading. */
1039 connection_consider_empty_buckets(conn);
1041 return 0;
1044 /** A pass-through to fetch_from_buf. */
1045 int connection_fetch_from_buf(char *string, size_t len, connection_t *conn) {
1046 return fetch_from_buf(string, len, conn->inbuf);
1049 /** Return conn-\>outbuf_flushlen: how many bytes conn wants to flush
1050 * from its outbuf. */
1051 int connection_wants_to_flush(connection_t *conn) {
1052 return conn->outbuf_flushlen;
1055 /** Are there too many bytes on edge connection <b>conn</b>'s outbuf to
1056 * send back a relay-level sendme yet? Return 1 if so, 0 if not. Used by
1057 * connection_edge_consider_sending_sendme().
1059 int connection_outbuf_too_full(connection_t *conn) {
1060 return (conn->outbuf_flushlen > 10*CELL_PAYLOAD_SIZE);
1063 /** Try to flush more bytes onto conn-\>s.
1065 * This function gets called either from conn_write() in main.c
1066 * when poll() has declared that conn wants to write, or below
1067 * from connection_write_to_buf() when an entire TLS record is ready.
1069 * Update conn-\>timestamp_lastwritten to now, and call flush_buf
1070 * or flush_buf_tls appropriately. If it succeeds and there no more
1071 * more bytes on conn->outbuf, then call connection_finished_flushing
1072 * on it too.
1074 * Mark the connection and return -1 if you want to close it, else
1075 * return 0.
1077 int connection_handle_write(connection_t *conn) {
1078 int e, len=sizeof(e);
1079 int result;
1080 time_t now = time(NULL);
1082 tor_assert(!connection_is_listener(conn));
1084 conn->timestamp_lastwritten = now;
1086 /* Sometimes, "writable" means "connected". */
1087 if (connection_state_is_connecting(conn)) {
1088 if (getsockopt(conn->s, SOL_SOCKET, SO_ERROR, (void*)&e, &len) < 0) {
1089 log_fn(LOG_WARN,"getsockopt() syscall failed?! Please report to tor-ops.");
1090 if (CONN_IS_EDGE(conn))
1091 connection_edge_end_errno(conn, conn->cpath_layer);
1092 connection_mark_for_close(conn);
1093 return -1;
1095 if (e) {
1096 /* some sort of error, but maybe just inprogress still */
1097 if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
1098 log_fn(LOG_INFO,"in-progress connect failed. Removing.");
1099 if (CONN_IS_EDGE(conn))
1100 connection_edge_end_errno(conn, conn->cpath_layer);
1102 connection_close_immediate(conn);
1103 connection_mark_for_close(conn);
1104 /* it's safe to pass OPs to router_mark_as_down(), since it just
1105 * ignores unrecognized routers
1107 if (conn->type == CONN_TYPE_OR && !get_options()->HttpsProxy)
1108 router_mark_as_down(conn->identity_digest);
1109 return -1;
1110 } else {
1111 return 0; /* no change, see if next time is better */
1114 /* The connection is successful. */
1115 if (connection_finished_connecting(conn)<0)
1116 return -1;
1119 if (connection_speaks_cells(conn) && conn->state > OR_CONN_STATE_PROXY_READING) {
1120 if (conn->state == OR_CONN_STATE_HANDSHAKING) {
1121 connection_stop_writing(conn);
1122 if (connection_tls_continue_handshake(conn) < 0) {
1123 connection_close_immediate(conn); /* Don't flush; connection is dead. */
1124 connection_mark_for_close(conn);
1125 return -1;
1127 return 0;
1130 /* else open, or closing */
1131 result = flush_buf_tls(conn->tls, conn->outbuf, &conn->outbuf_flushlen);
1132 switch (result) {
1133 case TOR_TLS_ERROR:
1134 case TOR_TLS_CLOSE:
1135 log_fn(LOG_INFO,result==TOR_TLS_ERROR?
1136 "tls error. breaking.":"TLS connection closed on flush");
1137 connection_close_immediate(conn); /* Don't flush; connection is dead. */
1138 connection_mark_for_close(conn);
1139 return -1;
1140 case TOR_TLS_WANTWRITE:
1141 log_fn(LOG_DEBUG,"wanted write.");
1142 /* we're already writing */
1143 return 0;
1144 case TOR_TLS_WANTREAD:
1145 /* Make sure to avoid a loop if the receive buckets are empty. */
1146 log_fn(LOG_DEBUG,"wanted read.");
1147 if (!connection_is_reading(conn)) {
1148 connection_stop_writing(conn);
1149 conn->wants_to_write = 1;
1150 /* we'll start reading again when the next second arrives,
1151 * and then also start writing again.
1154 /* else no problem, we're already reading */
1155 return 0;
1156 /* case TOR_TLS_DONE:
1157 * for TOR_TLS_DONE, fall through to check if the flushlen
1158 * is empty, so we can stop writing.
1161 } else {
1162 result = flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen);
1163 if (result < 0) {
1164 if (CONN_IS_EDGE(conn))
1165 connection_edge_end_errno(conn, conn->cpath_layer);
1167 connection_close_immediate(conn); /* Don't flush; connection is dead. */
1168 connection_mark_for_close(conn);
1169 return -1;
1173 if (result > 0 && !is_local_IP(conn->addr)) { /* remember it */
1174 rep_hist_note_bytes_written(result, now);
1175 global_write_bucket -= result;
1178 if (!connection_wants_to_flush(conn)) { /* it's done flushing */
1179 if (connection_finished_flushing(conn) < 0) {
1180 /* already marked */
1181 return -1;
1185 return 0;
1188 /** Append <b>len</b> bytes of <b>string</b> onto <b>conn</b>'s
1189 * outbuf, and ask it to start writing.
1191 void connection_write_to_buf(const char *string, size_t len, connection_t *conn) {
1193 if (!len)
1194 return;
1195 /* if it's marked for close, only allow write if we mean to flush it */
1196 if (conn->marked_for_close && !conn->hold_open_until_flushed)
1197 return;
1199 if (write_to_buf(string, len, conn->outbuf) < 0) {
1200 if (CONN_IS_EDGE(conn)) {
1201 /* if it failed, it means we have our package/delivery windows set
1202 wrong compared to our max outbuf size. close the whole circuit. */
1203 log_fn(LOG_WARN,"write_to_buf failed. Closing circuit (fd %d).", conn->s);
1204 circuit_mark_for_close(circuit_get_by_conn(conn));
1205 } else {
1206 log_fn(LOG_WARN,"write_to_buf failed. Closing connection (fd %d).", conn->s);
1207 connection_mark_for_close(conn);
1209 return;
1212 connection_start_writing(conn);
1213 conn->outbuf_flushlen += len;
1216 /** Return the conn to addr/port that has the most recent
1217 * timestamp_created, or NULL if no such conn exists. */
1218 connection_t *connection_exact_get_by_addr_port(uint32_t addr, uint16_t port) {
1219 int i, n;
1220 connection_t *conn, *best=NULL;
1221 connection_t **carray;
1223 get_connection_array(&carray,&n);
1224 for (i=0;i<n;i++) {
1225 conn = carray[i];
1226 if (conn->addr == addr && conn->port == port && !conn->marked_for_close &&
1227 (!best || best->timestamp_created < conn->timestamp_created))
1228 best = conn;
1230 return best;
1233 connection_t *connection_get_by_identity_digest(const char *digest, int type)
1235 int i, n;
1236 connection_t *conn, *best=NULL;
1237 connection_t **carray;
1239 get_connection_array(&carray,&n);
1240 for (i=0;i<n;i++) {
1241 conn = carray[i];
1242 if (conn->type != type)
1243 continue;
1244 if (!memcmp(conn->identity_digest, digest, DIGEST_LEN) &&
1245 !conn->marked_for_close &&
1246 (!best || best->timestamp_created < conn->timestamp_created))
1247 best = conn;
1249 return best;
1252 /** Return the connection with id <b>id</b> if it is not already
1253 * marked for close.
1255 connection_t *
1256 connection_get_by_global_id(uint32_t id) {
1257 int i, n;
1258 connection_t *conn;
1259 connection_t **carray;
1261 get_connection_array(&carray,&n);
1262 for (i=0;i<n;i++) {
1263 conn = carray[i];
1264 if (conn->global_identifier == id) {
1265 if (!conn->marked_for_close)
1266 return conn;
1267 else
1268 return NULL;
1271 return NULL;
1274 /** Return a connection of type <b>type</b> that is not marked for
1275 * close.
1277 connection_t *connection_get_by_type(int type) {
1278 int i, n;
1279 connection_t *conn;
1280 connection_t **carray;
1282 get_connection_array(&carray,&n);
1283 for (i=0;i<n;i++) {
1284 conn = carray[i];
1285 if (conn->type == type && !conn->marked_for_close)
1286 return conn;
1288 return NULL;
1291 /** Return a connection of type <b>type</b> that is in state <b>state</b>,
1292 * and that is not marked for close.
1294 connection_t *connection_get_by_type_state(int type, int state) {
1295 int i, n;
1296 connection_t *conn;
1297 connection_t **carray;
1299 get_connection_array(&carray,&n);
1300 for (i=0;i<n;i++) {
1301 conn = carray[i];
1302 if (conn->type == type && conn->state == state && !conn->marked_for_close)
1303 return conn;
1305 return NULL;
1308 /** Return a connection of type <b>type</b> that has purpose <b>purpose</b>,
1309 * and that is not marked for close.
1311 connection_t *connection_get_by_type_purpose(int type, int purpose) {
1312 int i, n;
1313 connection_t *conn;
1314 connection_t **carray;
1316 get_connection_array(&carray,&n);
1317 for (i=0;i<n;i++) {
1318 conn = carray[i];
1319 if (conn->type == type && conn->purpose == purpose && !conn->marked_for_close)
1320 return conn;
1322 return NULL;
1325 /** Return the connection of type <b>type</b> that is in state
1326 * <b>state</b>, that was written to least recently, and that is not
1327 * marked for close.
1329 connection_t *connection_get_by_type_state_lastwritten(int type, int state) {
1330 int i, n;
1331 connection_t *conn, *best=NULL;
1332 connection_t **carray;
1334 get_connection_array(&carray,&n);
1335 for (i=0;i<n;i++) {
1336 conn = carray[i];
1337 if (conn->type == type && conn->state == state && !conn->marked_for_close)
1338 if (!best || conn->timestamp_lastwritten < best->timestamp_lastwritten)
1339 best = conn;
1341 return best;
1344 /** Return a connection of type <b>type</b> that has rendquery equal
1345 * to <b>rendquery</b>, and that is not marked for close. If state
1346 * is non-zero, conn must be of that state too.
1348 connection_t *
1349 connection_get_by_type_state_rendquery(int type, int state, const char *rendquery) {
1350 int i, n;
1351 connection_t *conn;
1352 connection_t **carray;
1354 get_connection_array(&carray,&n);
1355 for (i=0;i<n;i++) {
1356 conn = carray[i];
1357 if (conn->type == type &&
1358 !conn->marked_for_close &&
1359 (!state || state == conn->state) &&
1360 !rend_cmp_service_ids(rendquery, conn->rend_query))
1361 return conn;
1363 return NULL;
1366 /** Return 1 if <b>conn</b> is a listener conn, else return 0. */
1367 int connection_is_listener(connection_t *conn) {
1368 if (conn->type == CONN_TYPE_OR_LISTENER ||
1369 conn->type == CONN_TYPE_AP_LISTENER ||
1370 conn->type == CONN_TYPE_DIR_LISTENER ||
1371 conn->type == CONN_TYPE_CONTROL_LISTENER)
1372 return 1;
1373 return 0;
1376 /** Return 1 if <b>conn</b> is in state "open" and is not marked
1377 * for close, else return 0.
1379 int connection_state_is_open(connection_t *conn) {
1380 tor_assert(conn);
1382 if (conn->marked_for_close)
1383 return 0;
1385 if ((conn->type == CONN_TYPE_OR && conn->state == OR_CONN_STATE_OPEN) ||
1386 (conn->type == CONN_TYPE_AP && conn->state == AP_CONN_STATE_OPEN) ||
1387 (conn->type == CONN_TYPE_EXIT && conn->state == EXIT_CONN_STATE_OPEN) ||
1388 (conn->type == CONN_TYPE_CONTROL && conn->state ==CONTROL_CONN_STATE_OPEN))
1389 return 1;
1391 return 0;
1394 /** Return 1 if conn is in 'connecting' state, else return 0. */
1395 int connection_state_is_connecting(connection_t *conn) {
1396 tor_assert(conn);
1398 if (conn->marked_for_close)
1399 return 0;
1400 switch (conn->type)
1402 case CONN_TYPE_OR:
1403 return conn->state == OR_CONN_STATE_CONNECTING;
1404 case CONN_TYPE_EXIT:
1405 return conn->state == EXIT_CONN_STATE_CONNECTING;
1406 case CONN_TYPE_DIR:
1407 return conn->state == DIR_CONN_STATE_CONNECTING;
1410 return 0;
1413 /** Write a destroy cell with circ ID <b>circ_id</b> onto OR connection
1414 * <b>conn</b>.
1416 * Return 0.
1418 int connection_send_destroy(uint16_t circ_id, connection_t *conn) {
1419 cell_t cell;
1421 tor_assert(conn);
1422 tor_assert(connection_speaks_cells(conn));
1424 memset(&cell, 0, sizeof(cell_t));
1425 cell.circ_id = circ_id;
1426 cell.command = CELL_DESTROY;
1427 log_fn(LOG_INFO,"Sending destroy (circID %d).", circ_id);
1428 connection_or_write_cell_to_buf(&cell, conn);
1429 return 0;
1432 /** Process new bytes that have arrived on conn-\>inbuf.
1434 * This function just passes conn to the connection-specific
1435 * connection_*_process_inbuf() function. It also passes in
1436 * package_partial if wanted.
1438 static int connection_process_inbuf(connection_t *conn, int package_partial) {
1440 tor_assert(conn);
1442 switch (conn->type) {
1443 case CONN_TYPE_OR:
1444 return connection_or_process_inbuf(conn);
1445 case CONN_TYPE_EXIT:
1446 case CONN_TYPE_AP:
1447 return connection_edge_process_inbuf(conn, package_partial);
1448 case CONN_TYPE_DIR:
1449 return connection_dir_process_inbuf(conn);
1450 case CONN_TYPE_DNSWORKER:
1451 return connection_dns_process_inbuf(conn);
1452 case CONN_TYPE_CPUWORKER:
1453 return connection_cpu_process_inbuf(conn);
1454 case CONN_TYPE_CONTROL:
1455 return connection_control_process_inbuf(conn);
1456 default:
1457 log_fn(LOG_WARN,"Bug: got unexpected conn type %d.", conn->type);
1458 #ifdef TOR_FRAGILE
1459 tor_assert(0);
1460 #endif
1461 return -1;
1465 /** We just finished flushing bytes from conn-\>outbuf, and there
1466 * are no more bytes remaining.
1468 * This function just passes conn to the connection-specific
1469 * connection_*_finished_flushing() function.
1471 static int connection_finished_flushing(connection_t *conn) {
1473 tor_assert(conn);
1475 // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
1477 switch (conn->type) {
1478 case CONN_TYPE_OR:
1479 return connection_or_finished_flushing(conn);
1480 case CONN_TYPE_AP:
1481 case CONN_TYPE_EXIT:
1482 return connection_edge_finished_flushing(conn);
1483 case CONN_TYPE_DIR:
1484 return connection_dir_finished_flushing(conn);
1485 case CONN_TYPE_DNSWORKER:
1486 return connection_dns_finished_flushing(conn);
1487 case CONN_TYPE_CPUWORKER:
1488 return connection_cpu_finished_flushing(conn);
1489 case CONN_TYPE_CONTROL:
1490 return connection_control_finished_flushing(conn);
1491 default:
1492 log_fn(LOG_WARN,"Bug: got unexpected conn type %d.", conn->type);
1493 #ifdef TOR_FRAGILE
1494 tor_assert(0);
1495 #endif
1496 return -1;
1500 /** Called when our attempt to connect() to another server has just
1501 * succeeded.
1503 * This function just passes conn to the connection-specific
1504 * connection_*_finished_connecting() function.
1506 static int connection_finished_connecting(connection_t *conn)
1508 tor_assert(conn);
1509 switch (conn->type)
1511 case CONN_TYPE_OR:
1512 return connection_or_finished_connecting(conn);
1513 case CONN_TYPE_EXIT:
1514 return connection_edge_finished_connecting(conn);
1515 case CONN_TYPE_DIR:
1516 return connection_dir_finished_connecting(conn);
1517 default:
1518 log_fn(LOG_WARN,"Bug: got unexpected conn type %d.", conn->type);
1519 #ifdef TOR_FRAGILE
1520 tor_assert(0);
1521 #endif
1522 return -1;
1526 static int connection_reached_eof(connection_t *conn)
1528 switch (conn->type) {
1529 case CONN_TYPE_OR:
1530 return connection_or_reached_eof(conn);
1531 case CONN_TYPE_AP:
1532 case CONN_TYPE_EXIT:
1533 return connection_edge_reached_eof(conn);
1534 case CONN_TYPE_DIR:
1535 return connection_dir_reached_eof(conn);
1536 case CONN_TYPE_DNSWORKER:
1537 return connection_dns_reached_eof(conn);
1538 case CONN_TYPE_CPUWORKER:
1539 return connection_cpu_reached_eof(conn);
1540 case CONN_TYPE_CONTROL:
1541 return connection_control_reached_eof(conn);
1542 default:
1543 log_fn(LOG_WARN,"Bug: got unexpected conn type %d.", conn->type);
1544 #ifdef TOR_FRAGILE
1545 tor_assert(0);
1546 #endif
1547 return -1;
1551 /** Verify that connection <b>conn</b> has all of its invariants
1552 * correct. Trigger an assert if anything is invalid.
1554 void assert_connection_ok(connection_t *conn, time_t now)
1556 tor_assert(conn);
1557 tor_assert(conn->magic == CONNECTION_MAGIC);
1558 tor_assert(conn->type >= _CONN_TYPE_MIN);
1559 tor_assert(conn->type <= _CONN_TYPE_MAX);
1561 if (conn->outbuf_flushlen > 0) {
1562 tor_assert(connection_is_writing(conn) || conn->wants_to_write);
1565 if (conn->hold_open_until_flushed)
1566 tor_assert(conn->marked_for_close);
1568 /* XXX check: wants_to_read, wants_to_write, s, poll_index,
1569 * marked_for_close. */
1571 /* buffers */
1572 if (!connection_is_listener(conn)) {
1573 assert_buf_ok(conn->inbuf);
1574 assert_buf_ok(conn->outbuf);
1577 #if 0 /* computers often go back in time; no way to know */
1578 tor_assert(!now || conn->timestamp_lastread <= now);
1579 tor_assert(!now || conn->timestamp_lastwritten <= now);
1580 tor_assert(conn->timestamp_created <= conn->timestamp_lastread);
1581 tor_assert(conn->timestamp_created <= conn->timestamp_lastwritten);
1582 #endif
1584 /* XXX Fix this; no longer so.*/
1585 #if 0
1586 if (conn->type != CONN_TYPE_OR && conn->type != CONN_TYPE_DIR)
1587 tor_assert(!conn->pkey);
1588 /* pkey is set if we're a dir client, or if we're an OR in state OPEN
1589 * connected to another OR.
1591 #endif
1593 if (conn->type != CONN_TYPE_OR) {
1594 tor_assert(!conn->tls);
1595 } else {
1596 if (conn->state == OR_CONN_STATE_OPEN) {
1597 /* tor_assert(conn->bandwidth > 0); */
1598 /* the above isn't necessarily true: if we just did a TLS
1599 * handshake but we didn't recognize the other peer, or it
1600 * gave a bad cert/etc, then we won't have assigned bandwidth,
1601 * yet it will be open. -RD
1603 // tor_assert(conn->receiver_bucket >= 0);
1605 // tor_assert(conn->addr && conn->port);
1606 tor_assert(conn->address);
1607 if (conn->state > OR_CONN_STATE_PROXY_READING)
1608 tor_assert(conn->tls);
1611 if (! CONN_IS_EDGE(conn)) {
1612 tor_assert(!conn->stream_id);
1613 tor_assert(!conn->next_stream);
1614 tor_assert(!conn->cpath_layer);
1615 tor_assert(!conn->package_window);
1616 tor_assert(!conn->deliver_window);
1617 tor_assert(!conn->done_sending);
1618 tor_assert(!conn->done_receiving);
1619 } else {
1620 /* XXX unchecked: package window, deliver window. */
1622 if (conn->type == CONN_TYPE_AP) {
1623 tor_assert(conn->socks_request);
1624 if (conn->state == AP_CONN_STATE_OPEN) {
1625 tor_assert(conn->socks_request->has_finished);
1626 if (!conn->marked_for_close) {
1627 tor_assert(conn->cpath_layer);
1628 assert_cpath_layer_ok(conn->cpath_layer);
1631 } else {
1632 tor_assert(!conn->socks_request);
1634 if (conn->type == CONN_TYPE_EXIT) {
1635 tor_assert(conn->purpose == EXIT_PURPOSE_CONNECT ||
1636 conn->purpose == EXIT_PURPOSE_RESOLVE);
1637 } else if (conn->type != CONN_TYPE_DIR) {
1638 tor_assert(!conn->purpose); /* only used for dir types currently */
1641 switch (conn->type)
1643 case CONN_TYPE_OR_LISTENER:
1644 case CONN_TYPE_AP_LISTENER:
1645 case CONN_TYPE_DIR_LISTENER:
1646 case CONN_TYPE_CONTROL_LISTENER:
1647 tor_assert(conn->state == LISTENER_STATE_READY);
1648 break;
1649 case CONN_TYPE_OR:
1650 tor_assert(conn->state >= _OR_CONN_STATE_MIN);
1651 tor_assert(conn->state <= _OR_CONN_STATE_MAX);
1652 break;
1653 case CONN_TYPE_EXIT:
1654 tor_assert(conn->state >= _EXIT_CONN_STATE_MIN);
1655 tor_assert(conn->state <= _EXIT_CONN_STATE_MAX);
1656 break;
1657 case CONN_TYPE_AP:
1658 tor_assert(conn->state >= _AP_CONN_STATE_MIN);
1659 tor_assert(conn->state <= _AP_CONN_STATE_MAX);
1660 tor_assert(conn->socks_request);
1661 break;
1662 case CONN_TYPE_DIR:
1663 tor_assert(conn->state >= _DIR_CONN_STATE_MIN);
1664 tor_assert(conn->state <= _DIR_CONN_STATE_MAX);
1665 tor_assert(conn->purpose >= _DIR_PURPOSE_MIN);
1666 tor_assert(conn->purpose <= _DIR_PURPOSE_MAX);
1667 break;
1668 case CONN_TYPE_DNSWORKER:
1669 tor_assert(conn->state == DNSWORKER_STATE_IDLE ||
1670 conn->state == DNSWORKER_STATE_BUSY);
1671 break;
1672 case CONN_TYPE_CPUWORKER:
1673 tor_assert(conn->state >= _CPUWORKER_STATE_MIN);
1674 tor_assert(conn->state <= _CPUWORKER_STATE_MAX);
1675 break;
1676 case CONN_TYPE_CONTROL:
1677 tor_assert(conn->state >= _CONTROL_CONN_STATE_MIN);
1678 tor_assert(conn->state <= _CONTROL_CONN_STATE_MAX);
1679 break;
1680 default:
1681 tor_assert(0);