Normalize space: add one between every control keyword and control clause.
[tor.git] / src / or / connection.c
blob7eb77fb5edd10db880560e33e44e5c100ebcd9f3
1 /* Copyright 2001 Matej Pfajfar.
2 * Copyright 2001-2004 Roger Dingledine.
3 * Copyright 2004 Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
5 /* $Id$ */
7 /**
8 * \file connection.c
9 * \brief General high-level functions to handle reading and writing
10 * on connections.
11 **/
13 #include "or.h"
15 /********* START VARIABLES **********/
17 /** Array of strings to make conn-\>type human-readable. */
18 const char *conn_type_to_string[] = {
19 "", /* 0 */
20 "OP listener", /* 1 */
21 "OP", /* 2 */
22 "OR listener", /* 3 */
23 "OR", /* 4 */
24 "Exit", /* 5 */
25 "App listener",/* 6 */
26 "App", /* 7 */
27 "Dir listener",/* 8 */
28 "Dir", /* 9 */
29 "DNS worker", /* 10 */
30 "CPU worker", /* 11 */
31 "Control listener", /* 12 */
32 "Control", /* 13 */
35 /** Array of string arrays to make {conn-\>type,conn-\>state} human-readable. */
36 const char *conn_state_to_string[][_CONN_TYPE_MAX+1] = {
37 { NULL }, /* no type associated with 0 */
38 { NULL }, /* op listener, obsolete */
39 { NULL }, /* op, obsolete */
40 { "ready" }, /* or listener, 0 */
41 { "", /* OR, 0 */
42 "connect()ing", /* 1 */
43 "handshaking", /* 2 */
44 "open" }, /* 3 */
45 { "", /* exit, 0 */
46 "waiting for dest info", /* 1 */
47 "connecting", /* 2 */
48 "open", /* 3 */
49 "resolve failed" }, /* 4 */
50 { "ready" }, /* app listener, 0 */
51 { "", /* 0 */
52 "", /* 1 */
53 "", /* 2 */
54 "", /* 3 */
55 "", /* 4 */
56 "awaiting dest info", /* app, 5 */
57 "waiting for rendezvous desc", /* 6 */
58 "waiting for safe circuit", /* 7 */
59 "waiting for connected", /* 8 */
60 "waiting for resolve", /* 9 */
61 "open" }, /* 10 */
62 { "ready" }, /* dir listener, 0 */
63 { "", /* dir, 0 */
64 "connecting", /* 1 */
65 "client sending", /* 2 */
66 "client reading", /* 3 */
67 "awaiting command", /* 4 */
68 "writing" }, /* 5 */
69 { "", /* dns worker, 0 */
70 "idle", /* 1 */
71 "busy" }, /* 2 */
72 { "", /* cpu worker, 0 */
73 "idle", /* 1 */
74 "busy with onion", /* 2 */
75 "busy with handshake" }, /* 3 */
76 { "ready" }, /* control listener, 0 */
77 { "", /* control, 0 */
78 "ready", /* 1 */
79 "waiting for authentication", }, /* 2 */
82 /********* END VARIABLES ************/
84 static int connection_create_listener(const char *bindaddress,
85 uint16_t bindport, int type);
86 static int connection_init_accepted_conn(connection_t *conn);
87 static int connection_handle_listener_read(connection_t *conn, int new_type);
88 static int connection_receiver_bucket_should_increase(connection_t *conn);
89 static int connection_finished_flushing(connection_t *conn);
90 static int connection_finished_connecting(connection_t *conn);
91 static int connection_reached_eof(connection_t *conn);
92 static int connection_read_to_buf(connection_t *conn, int *max_to_read);
93 static int connection_process_inbuf(connection_t *conn, int package_partial);
94 static int connection_bucket_read_limit(connection_t *conn);
96 /**************************************************************/
98 /** Allocate space for a new connection_t. This function just initializes
99 * conn; you must call connection_add() to link it into the main array.
101 * Set conn-\>type to <b>type</b>. Set conn-\>s and conn-\>poll_index to
102 * -1 to signify they are not yet assigned.
104 * If conn is not a listener type, allocate buffers for it. If it's
105 * an AP type, allocate space to store the socks_request.
107 * Assign a pseudorandom next_circ_id between 0 and 2**15.
109 * Initialize conn's timestamps to now.
111 connection_t *connection_new(int type) {
112 connection_t *conn;
113 time_t now = time(NULL);
115 conn = tor_malloc_zero(sizeof(connection_t));
116 conn->magic = CONNECTION_MAGIC;
117 conn->s = -1; /* give it a default of 'not used' */
118 conn->poll_index = -1; /* also default to 'not used' */
120 conn->type = type;
121 if (!connection_is_listener(conn)) { /* listeners never use their buf */
122 conn->inbuf = buf_new();
123 conn->outbuf = buf_new();
125 if (type == CONN_TYPE_AP) {
126 conn->socks_request = tor_malloc_zero(sizeof(socks_request_t));
129 conn->next_circ_id = crypto_pseudo_rand_int(1<<15);
131 conn->timestamp_created = now;
132 conn->timestamp_lastread = now;
133 conn->timestamp_lastwritten = now;
135 return conn;
138 /** Deallocate memory used by <b>conn</b>. Deallocate its buffers if necessary,
139 * close its socket if necessary, and mark the directory as dirty if <b>conn</b>
140 * is an OR or OP connection.
142 void connection_free(connection_t *conn) {
143 tor_assert(conn);
144 tor_assert(conn->magic == CONNECTION_MAGIC);
146 if (!connection_is_listener(conn)) {
147 buf_free(conn->inbuf);
148 buf_free(conn->outbuf);
150 tor_free(conn->address);
152 if (connection_speaks_cells(conn)) {
153 if (conn->state == OR_CONN_STATE_OPEN)
154 directory_set_dirty();
155 if (conn->tls)
156 tor_tls_free(conn->tls);
159 if (conn->identity_pkey)
160 crypto_free_pk_env(conn->identity_pkey);
161 tor_free(conn->nickname);
162 tor_free(conn->socks_request);
164 if (conn->s >= 0) {
165 log_fn(LOG_INFO,"closing fd %d.",conn->s);
166 tor_close_socket(conn->s);
168 memset(conn, 0xAA, sizeof(connection_t)); /* poison memory */
169 tor_free(conn);
172 /** Call connection_free() on every connection in our array.
173 * This is used by cpuworkers and dnsworkers when they fork,
174 * so they don't keep resources held open (especially sockets).
176 void connection_free_all(void) {
177 int i, n;
178 connection_t **carray;
180 get_connection_array(&carray,&n);
181 for (i=0;i<n;i++)
182 connection_free(carray[i]);
185 /** Do any cleanup needed:
186 * - Directory conns that failed to fetch a rendezvous descriptor
187 * need to inform pending rendezvous streams.
188 * - OR conns need to call rep_hist_note_*() to record status.
189 * - AP conns need to send a socks reject if necessary.
190 * - Exit conns need to call connection_dns_remove() if necessary.
191 * - AP and Exit conns need to send an end cell if they can.
192 * - DNS conns need to fail any resolves that are pending on them.
194 void connection_about_to_close_connection(connection_t *conn)
197 assert(conn->marked_for_close);
199 if (conn->type == CONN_TYPE_AP || conn->type == CONN_TYPE_EXIT) {
200 if (!conn->has_sent_end)
201 log_fn(LOG_WARN,"Edge connection hasn't sent end yet? Bug.");
204 switch (conn->type) {
205 case CONN_TYPE_DIR:
206 if (conn->purpose == DIR_PURPOSE_FETCH_RENDDESC)
207 rend_client_desc_fetched(conn->rend_query, 0);
208 break;
209 case CONN_TYPE_OR:
210 /* Remember why we're closing this connection. */
211 if (conn->state != OR_CONN_STATE_OPEN) {
212 if (connection_or_nonopen_was_started_here(conn)) {
213 rep_hist_note_connect_failed(conn->identity_digest, time(NULL));
214 control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED);
216 } else if (conn->hold_open_until_flushed) {
217 /* XXXX009 We used to have an arg that told us whether we closed the
218 * connection on purpose or not. Can we use hold_open_until_flushed
219 * instead? We only set it when we are intentionally closing a
220 * connection. -NM
222 * (Of course, now things we set to close which expire rather than
223 * flushing still get noted as dead, not disconnected. But this is an
224 * improvement. -NM
226 rep_hist_note_disconnect(conn->identity_digest, time(NULL));
227 control_event_or_conn_status(conn, OR_CONN_EVENT_CLOSED);
228 } else if (conn->identity_digest) {
229 rep_hist_note_connection_died(conn->identity_digest, time(NULL));
230 control_event_or_conn_status(conn, OR_CONN_EVENT_CLOSED);
232 break;
233 case CONN_TYPE_AP:
234 if (conn->socks_request->has_finished == 0) {
235 log_fn(LOG_INFO,"Cleaning up AP -- sending socks reject.");
236 connection_ap_handshake_socks_reply(conn, NULL, 0, -1);
237 conn->socks_request->has_finished = 1;
238 conn->hold_open_until_flushed = 1;
239 } else {
240 control_event_stream_status(conn, STREAM_EVENT_CLOSED);
242 break;
243 case CONN_TYPE_EXIT:
244 if (conn->state == EXIT_CONN_STATE_RESOLVING) {
245 circuit_detach_stream(circuit_get_by_conn(conn), conn);
246 connection_dns_remove(conn);
248 break;
249 case CONN_TYPE_DNSWORKER:
250 if (conn->state == DNSWORKER_STATE_BUSY) {
251 dns_cancel_pending_resolve(conn->address);
253 break;
257 /** Close the underlying socket for <b>conn</b>, so we don't try to
258 * flush it. Must be used in conjunction with (right before)
259 * connection_mark_for_close().
261 void connection_close_immediate(connection_t *conn)
263 assert_connection_ok(conn,0);
264 if (conn->s < 0) {
265 log_fn(LOG_WARN,"Attempt to close already-closed connection.");
266 return;
268 if (conn->outbuf_flushlen) {
269 log_fn(LOG_INFO,"fd %d, type %s, state %d, %d bytes on outbuf.",
270 conn->s, CONN_TYPE_TO_STRING(conn->type),
271 conn->state, (int)conn->outbuf_flushlen);
273 tor_close_socket(conn->s);
274 conn->s = -1;
275 if (!connection_is_listener(conn)) {
276 buf_clear(conn->outbuf);
277 conn->outbuf_flushlen = 0;
281 /** Mark <b>conn</b> to be closed next time we loop through
282 * conn_close_if_marked() in main.c. */
284 _connection_mark_for_close(connection_t *conn)
286 assert_connection_ok(conn,0);
288 if (conn->marked_for_close) {
289 log(LOG_WARN, "Double mark-for-close on connection.");
290 return -1;
293 conn->marked_for_close = 1;
295 /* in case we're going to be held-open-til-flushed, reset
296 * the number of seconds since last successful write, so
297 * we get our whole 15 seconds */
298 conn->timestamp_lastwritten = time(NULL);
300 return 0;
303 /** Find each connection that has hold_open_until_flushed set to
304 * 1 but hasn't written in the past 15 seconds, and set
305 * hold_open_until_flushed to 0. This means it will get cleaned
306 * up in the next loop through close_if_marked() in main.c.
308 void connection_expire_held_open(void)
310 connection_t **carray, *conn;
311 int n, i;
312 time_t now;
314 now = time(NULL);
316 get_connection_array(&carray, &n);
317 for (i = 0; i < n; ++i) {
318 conn = carray[i];
319 /* If we've been holding the connection open, but we haven't written
320 * for 15 seconds...
322 if (conn->hold_open_until_flushed) {
323 tor_assert(conn->marked_for_close);
324 if (now - conn->timestamp_lastwritten >= 15) {
325 log_fn(LOG_WARN,"Giving up on marked_for_close conn that's been flushing for 15s (fd %d, type %s, state %d).",
326 conn->s, CONN_TYPE_TO_STRING(conn->type), conn->state);
327 conn->hold_open_until_flushed = 0;
333 /** Bind a new non-blocking socket listening to
334 * <b>bindaddress</b>:<b>bindport</b>, and add this new connection
335 * (of type <b>type</b>) to the connection array.
337 * If <b>bindaddress</b> includes a port, we bind on that port; otherwise, we
338 * use bindport.
340 static int connection_create_listener(const char *bindaddress, uint16_t bindport, int type) {
341 struct sockaddr_in bindaddr; /* where to bind */
342 connection_t *conn;
343 uint16_t usePort;
344 uint32_t addr;
345 int s; /* the socket we're going to make */
346 int one=1;
348 memset(&bindaddr,0,sizeof(struct sockaddr_in));
349 if (parse_addr_port(bindaddress, NULL, &addr, &usePort)<0) {
350 log_fn(LOG_WARN, "Error parsing/resolving BindAddress %s",bindaddress);
351 return -1;
354 if (usePort==0)
355 usePort = bindport;
356 bindaddr.sin_addr.s_addr = htonl(addr);
357 bindaddr.sin_family = AF_INET;
358 bindaddr.sin_port = htons((uint16_t) usePort);
360 s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
361 if (s < 0) {
362 log_fn(LOG_WARN,"Socket creation failed.");
363 return -1;
366 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*) &one, sizeof(one));
368 if (bind(s,(struct sockaddr *)&bindaddr,sizeof(bindaddr)) < 0) {
369 log_fn(LOG_WARN,"Could not bind to port %u: %s",usePort,
370 tor_socket_strerror(tor_socket_errno(s)));
371 return -1;
374 if (listen(s,SOMAXCONN) < 0) {
375 log_fn(LOG_WARN,"Could not listen on port %u: %s",usePort,
376 tor_socket_strerror(tor_socket_errno(s)));
377 return -1;
380 set_socket_nonblocking(s);
382 conn = connection_new(type);
383 conn->s = s;
385 if (connection_add(conn) < 0) { /* no space, forget it */
386 log_fn(LOG_WARN,"connection_add failed. Giving up.");
387 connection_free(conn);
388 return -1;
391 log_fn(LOG_DEBUG,"%s listening on port %u.",conn_type_to_string[type], usePort);
393 conn->state = LISTENER_STATE_READY;
394 connection_start_reading(conn);
396 return 0;
399 /** The listener connection <b>conn</b> told poll() it wanted to read.
400 * Call accept() on conn-\>s, and add the new connection if necessary.
402 static int connection_handle_listener_read(connection_t *conn, int new_type) {
403 int news; /* the new socket */
404 connection_t *newconn;
405 /* information about the remote peer when connecting to other routers */
406 struct sockaddr_in remote;
407 /* length of the remote address. Must be an int, since accept() needs that. */
408 int remotelen = sizeof(struct sockaddr_in);
410 news = accept(conn->s,(struct sockaddr *)&remote,&remotelen);
411 if (news == -1) { /* accept() error */
412 int e = tor_socket_errno(conn->s);
413 if (ERRNO_IS_ACCEPT_EAGAIN(e)) {
414 return 0; /* he hung up before we could accept(). that's fine. */
415 } else if (ERRNO_IS_ACCEPT_RESOURCE_LIMIT(e)) {
416 log_fn(LOG_WARN,"accept failed: %s. Dropping incoming connection.",
417 tor_socket_strerror(e));
418 return 0;
420 /* else there was a real error. */
421 log_fn(LOG_WARN,"accept() failed: %s. Closing listener.",
422 tor_socket_strerror(e));
423 connection_mark_for_close(conn);
424 return -1;
426 log(LOG_INFO,"Connection accepted on socket %d (child of fd %d).",news, conn->s);
428 set_socket_nonblocking(news);
430 /* process entrance policies here, before we even create the connection */
431 if (new_type == CONN_TYPE_AP) {
432 /* check sockspolicy to see if we should accept it */
433 if (socks_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
434 log_fn(LOG_WARN,"Denying socks connection from untrusted address %s.",
435 inet_ntoa(remote.sin_addr));
436 tor_close_socket(news);
437 return 0;
440 if (new_type == CONN_TYPE_DIR) {
441 /* check dirpolicy to see if we should accept it */
442 if (dir_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
443 log_fn(LOG_WARN,"Denying dir connection from address %s.",
444 inet_ntoa(remote.sin_addr));
445 tor_close_socket(news);
446 return 0;
450 newconn = connection_new(new_type);
451 newconn->s = news;
453 newconn->address = tor_strdup(inet_ntoa(remote.sin_addr)); /* remember the remote address */
454 newconn->addr = ntohl(remote.sin_addr.s_addr);
455 newconn->port = ntohs(remote.sin_port);
457 if (connection_add(newconn) < 0) { /* no space, forget it */
458 connection_free(newconn);
459 return 0; /* no need to tear down the parent */
462 if (connection_init_accepted_conn(newconn) < 0) {
463 connection_mark_for_close(newconn);
464 return 0;
466 return 0;
469 /** Initialize states for newly accepted connection <b>conn</b>.
470 * If conn is an OR, start the tls handshake.
472 static int connection_init_accepted_conn(connection_t *conn) {
474 connection_start_reading(conn);
476 switch (conn->type) {
477 case CONN_TYPE_OR:
478 return connection_tls_start_handshake(conn, 1);
479 case CONN_TYPE_AP:
480 conn->state = AP_CONN_STATE_SOCKS_WAIT;
481 break;
482 case CONN_TYPE_DIR:
483 conn->purpose = DIR_PURPOSE_SERVER;
484 conn->state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
485 break;
486 case CONN_TYPE_CONTROL:
487 conn->state = CONTROL_CONN_STATE_NEEDAUTH;
488 break;
490 return 0;
493 /** Take conn, make a nonblocking socket; try to connect to
494 * addr:port (they arrive in *host order*). If fail, return -1. Else
495 * assign s to conn->\s: if connected return 1, if EAGAIN return 0.
497 * address is used to make the logs useful.
499 * On success, add conn to the list of polled connections.
501 int connection_connect(connection_t *conn, char *address, uint32_t addr, uint16_t port) {
502 int s;
503 struct sockaddr_in dest_addr;
504 or_options_t *options = get_options();
506 s=socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
507 if (s < 0) {
508 log_fn(LOG_WARN,"Error creating network socket: %s",
509 tor_socket_strerror(tor_socket_errno(-1)));
510 return -1;
513 if (options->OutboundBindAddress) {
514 struct sockaddr_in ext_addr;
516 memset(&ext_addr, 0, sizeof(ext_addr));
517 ext_addr.sin_family = AF_INET;
518 ext_addr.sin_port = 0;
519 if (!tor_inet_aton(options->OutboundBindAddress, &ext_addr.sin_addr)) {
520 log_fn(LOG_WARN,"Outbound bind address '%s' didn't parse. Ignoring.",
521 options->OutboundBindAddress);
522 } else {
523 if (bind(s, (struct sockaddr*)&ext_addr, sizeof(ext_addr)) < 0) {
524 log_fn(LOG_WARN,"Error binding network socket: %s",
525 tor_socket_strerror(tor_socket_errno(s)));
526 return -1;
531 set_socket_nonblocking(s);
533 memset(&dest_addr,0,sizeof(dest_addr));
534 dest_addr.sin_family = AF_INET;
535 dest_addr.sin_port = htons(port);
536 dest_addr.sin_addr.s_addr = htonl(addr);
538 log_fn(LOG_DEBUG,"Connecting to %s:%u.",address,port);
540 if (connect(s,(struct sockaddr *)&dest_addr,sizeof(dest_addr)) < 0) {
541 int e = tor_socket_errno(s);
542 if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
543 /* yuck. kill it. */
544 log_fn(LOG_INFO,"Connect() to %s:%u failed: %s",address,port,
545 tor_socket_strerror(e));
546 tor_close_socket(s);
547 return -1;
548 } else {
549 /* it's in progress. set state appropriately and return. */
550 conn->s = s;
551 if (connection_add(conn) < 0) /* no space, forget it */
552 return -1;
553 log_fn(LOG_DEBUG,"connect in progress, socket %d.",s);
554 return 0;
558 /* it succeeded. we're connected. */
559 log_fn(LOG_INFO,"Connection to %s:%u established.",address,port);
560 conn->s = s;
561 if (connection_add(conn) < 0) /* no space, forget it */
562 return -1;
563 return 1;
566 /** If there exist any listeners of type <b>type</b> in the connection
567 * array, mark them for close.
569 static void listener_close_if_present(int type) {
570 connection_t *conn;
571 connection_t **carray;
572 int i,n;
573 tor_assert(type == CONN_TYPE_OR_LISTENER ||
574 type == CONN_TYPE_AP_LISTENER ||
575 type == CONN_TYPE_DIR_LISTENER ||
576 type == CONN_TYPE_CONTROL_LISTENER);
577 get_connection_array(&carray,&n);
578 for (i=0;i<n;i++) {
579 conn = carray[i];
580 if (conn->type == type && !conn->marked_for_close) {
581 connection_close_immediate(conn);
582 connection_mark_for_close(conn);
588 * Launch any configured listener connections of type <b>type</b>. (A
589 * listener is configured if <b>port_option</b> is non-zero. If any
590 * BindAddress configuration options are given in <b>cfg</b>, create a
591 * connection binding to each one. Otherwise, create a single
592 * connection binding to the address <b>default_addr</b>.)
594 * If <b>force</b> is true, close and re-open all listener connections.
595 * Otherwise, only relaunch the listeners of this type if the number of
596 * existing connections is not as configured (e.g., because one died).
598 static int retry_listeners(int type, struct config_line_t *cfg,
599 int port_option, const char *default_addr,
600 int force)
602 if (!force) {
603 int want, have, n_conn, i;
604 struct config_line_t *c;
605 connection_t *conn;
606 connection_t **carray;
607 /* How many should there be? */
608 if (cfg && port_option) {
609 want = 0;
610 for (c = cfg; c; c = c->next)
611 ++want;
612 } else if (port_option) {
613 want = 1;
614 } else {
615 want = 0;
618 /* How many are there actually? */
619 have = 0;
620 get_connection_array(&carray,&n_conn);
621 for (i=0;i<n_conn;i++) {
622 conn = carray[i];
623 if (conn->type == type && !conn->marked_for_close)
624 ++have;
627 /* If we have the right number of listeners, do nothing. */
628 if (have == want)
629 return 0;
631 /* Otherwise, warn the user and relaunch. */
632 log_fn(LOG_WARN,"We have %d %s(s) open, but we want %d; relaunching.",
633 have, conn_type_to_string[type], want);
636 listener_close_if_present(type);
637 if (port_option) {
638 if (!cfg) {
639 if (connection_create_listener(default_addr, (uint16_t) port_option,
640 type)<0)
641 return -1;
642 } else {
643 for ( ; cfg; cfg = cfg->next) {
644 if (connection_create_listener(cfg->value, (uint16_t) port_option,
645 type)<0)
646 return -1;
650 return 0;
653 /** (Re)launch listeners for each port you should have open. If
654 * <b>force</b> is true, close and relaunch all listeners. If <b>force</b>
655 * is false, then only relaunch listeners when we have the wrong number of
656 * connections for a given type.
658 int retry_all_listeners(int force) {
659 or_options_t *options = get_options();
661 if (retry_listeners(CONN_TYPE_OR_LISTENER, options->ORBindAddress,
662 options->ORPort, "0.0.0.0", force)<0)
663 return -1;
664 if (retry_listeners(CONN_TYPE_DIR_LISTENER, options->DirBindAddress,
665 options->DirPort, "0.0.0.0", force)<0)
666 return -1;
667 if (retry_listeners(CONN_TYPE_AP_LISTENER, options->SocksBindAddress,
668 options->SocksPort, "127.0.0.1", force)<0)
669 return -1;
670 if (retry_listeners(CONN_TYPE_CONTROL_LISTENER, NULL,
671 options->ControlPort, "127.0.0.1", force)<0)
672 return -1;
674 return 0;
677 extern int global_read_bucket, global_write_bucket;
679 /** How many bytes at most can we read onto this connection? */
680 static int connection_bucket_read_limit(connection_t *conn) {
681 int at_most;
683 /* do a rudimentary round-robin so one circuit can't hog a connection */
684 if (connection_speaks_cells(conn)) {
685 at_most = 32*(CELL_NETWORK_SIZE);
686 } else {
687 at_most = 32*(RELAY_PAYLOAD_SIZE);
690 if (at_most > global_read_bucket)
691 at_most = global_read_bucket;
693 if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN)
694 if (at_most > conn->receiver_bucket)
695 at_most = conn->receiver_bucket;
697 return at_most;
700 /** We just read num_read onto conn. Decrement buckets appropriately. */
701 static void connection_read_bucket_decrement(connection_t *conn, int num_read) {
702 global_read_bucket -= num_read; tor_assert(global_read_bucket >= 0);
703 if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
704 conn->receiver_bucket -= num_read; tor_assert(conn->receiver_bucket >= 0);
708 static void connection_consider_empty_buckets(connection_t *conn) {
709 if (global_read_bucket == 0) {
710 log_fn(LOG_DEBUG,"global bucket exhausted. Pausing.");
711 conn->wants_to_read = 1;
712 connection_stop_reading(conn);
713 return;
715 if (connection_speaks_cells(conn) &&
716 conn->state == OR_CONN_STATE_OPEN &&
717 conn->receiver_bucket == 0) {
718 log_fn(LOG_DEBUG,"receiver bucket exhausted. Pausing.");
719 conn->wants_to_read = 1;
720 connection_stop_reading(conn);
724 /** Initialize the global read bucket to options->BandwidthBurst,
725 * and current_time to the current time. */
726 void connection_bucket_init(void) {
727 or_options_t *options = get_options();
728 global_read_bucket = (int)options->BandwidthBurst; /* start it at max traffic */
729 global_write_bucket = (int)options->BandwidthBurst; /* start it at max traffic */
732 /** A second has rolled over; increment buckets appropriately. */
733 void connection_bucket_refill(struct timeval *now) {
734 int i, n;
735 connection_t *conn;
736 connection_t **carray;
737 or_options_t *options = get_options();
739 /* refill the global buckets */
740 if ((unsigned)global_read_bucket < options->BandwidthBurst) {
741 global_read_bucket += (int)options->BandwidthRate;
742 log_fn(LOG_DEBUG,"global_read_bucket now %d.", global_read_bucket);
744 if ((unsigned)global_write_bucket < options->BandwidthBurst) {
745 global_write_bucket += (int)options->BandwidthRate;
746 log_fn(LOG_DEBUG,"global_write_bucket now %d.", global_write_bucket);
749 /* refill the per-connection buckets */
750 get_connection_array(&carray,&n);
751 for (i=0;i<n;i++) {
752 conn = carray[i];
754 if (connection_receiver_bucket_should_increase(conn)) {
755 conn->receiver_bucket += conn->bandwidth;
756 //log_fn(LOG_DEBUG,"Receiver bucket %d now %d.", i, conn->receiver_bucket);
759 if (conn->wants_to_read == 1 /* it's marked to turn reading back on now */
760 && global_read_bucket > 0 /* and we're allowed to read */
761 && global_write_bucket > 0 /* and we're allowed to write (XXXX,
762 * not the best place to check this.) */
763 && (!connection_speaks_cells(conn) ||
764 conn->state != OR_CONN_STATE_OPEN ||
765 conn->receiver_bucket > 0)) {
766 /* and either a non-cell conn or a cell conn with non-empty bucket */
767 log_fn(LOG_DEBUG,"waking up conn (fd %d)",conn->s);
768 conn->wants_to_read = 0;
769 connection_start_reading(conn);
770 if (conn->wants_to_write == 1) {
771 conn->wants_to_write = 0;
772 connection_start_writing(conn);
778 /** Is the receiver bucket for connection <b>conn</b> low enough that we
779 * should add another pile of tokens to it?
781 static int connection_receiver_bucket_should_increase(connection_t *conn) {
782 tor_assert(conn);
784 if (!connection_speaks_cells(conn))
785 return 0; /* edge connections don't use receiver_buckets */
786 if (conn->state != OR_CONN_STATE_OPEN)
787 return 0; /* only open connections play the rate limiting game */
789 tor_assert(conn->bandwidth > 0);
790 if (conn->receiver_bucket > 9*conn->bandwidth)
791 return 0;
793 return 1;
796 /** Read bytes from conn->\s and process them.
798 * This function gets called from conn_read() in main.c, either
799 * when poll() has declared that conn wants to read, or (for OR conns)
800 * when there are pending TLS bytes.
802 * It calls connection_read_to_buf() to bring in any new bytes,
803 * and then calls connection_process_inbuf() to process them.
805 * Mark the connection and return -1 if you want to close it, else
806 * return 0.
808 int connection_handle_read(connection_t *conn) {
809 int max_to_read=-1, try_to_read;
811 conn->timestamp_lastread = time(NULL);
813 switch (conn->type) {
814 case CONN_TYPE_OR_LISTENER:
815 return connection_handle_listener_read(conn, CONN_TYPE_OR);
816 case CONN_TYPE_AP_LISTENER:
817 return connection_handle_listener_read(conn, CONN_TYPE_AP);
818 case CONN_TYPE_DIR_LISTENER:
819 return connection_handle_listener_read(conn, CONN_TYPE_DIR);
820 case CONN_TYPE_CONTROL_LISTENER:
821 return connection_handle_listener_read(conn, CONN_TYPE_CONTROL);
824 loop_again:
825 try_to_read = max_to_read;
826 tor_assert(!conn->marked_for_close);
827 if (connection_read_to_buf(conn, &max_to_read) < 0) {
828 /* There's a read error; kill the connection.*/
829 connection_close_immediate(conn); /* Don't flush; connection is dead. */
830 if (conn->type == CONN_TYPE_AP || conn->type == CONN_TYPE_EXIT) {
831 connection_edge_end(conn, (char)(connection_state_is_open(conn) ?
832 END_STREAM_REASON_MISC : END_STREAM_REASON_CONNECTFAILED),
833 conn->cpath_layer);
835 connection_mark_for_close(conn);
836 if (conn->type == CONN_TYPE_DIR &&
837 conn->state == DIR_CONN_STATE_CONNECTING) {
838 /* it's a directory server and connecting failed: forget about this router */
839 /* XXX I suspect pollerr may make Windows not get to this point. :( */
840 router_mark_as_down(conn->identity_digest);
841 if (conn->purpose == DIR_PURPOSE_FETCH_DIR &&
842 !all_trusted_directory_servers_down()) {
843 log_fn(LOG_INFO,"Giving up on dirserver %s; trying another.", conn->address);
844 directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL);
847 return -1;
849 if (CONN_IS_EDGE(conn) &&
850 try_to_read != max_to_read) {
851 /* instruct it not to try to package partial cells. */
852 if (connection_process_inbuf(conn, 0) < 0) {
853 return -1;
855 if (!conn->marked_for_close &&
856 connection_is_reading(conn) &&
857 !conn->inbuf_reached_eof)
858 goto loop_again; /* try reading again, in case more is here now */
860 /* one last try, packaging partial cells and all. */
861 if (!conn->marked_for_close &&
862 connection_process_inbuf(conn, 1) < 0) {
863 return -1;
865 if (!conn->marked_for_close &&
866 conn->inbuf_reached_eof &&
867 connection_reached_eof(conn) < 0) {
868 return -1;
870 return 0;
873 /** Pull in new bytes from conn-\>s onto conn-\>inbuf, either
874 * directly or via TLS. Reduce the token buckets by the number of
875 * bytes read.
877 * If *max_to_read is -1, then decide it ourselves, else go with the
878 * value passed to us. When returning, if it's changed, subtract the
879 * number of bytes we read from *max_to_read.
881 * Return -1 if we want to break conn, else return 0.
883 static int connection_read_to_buf(connection_t *conn, int *max_to_read) {
884 int result, at_most = *max_to_read;
886 if (at_most == -1) { /* we need to initialize it */
887 /* how many bytes are we allowed to read? */
888 at_most = connection_bucket_read_limit(conn);
891 if (connection_speaks_cells(conn) && conn->state != OR_CONN_STATE_CONNECTING) {
892 if (conn->state == OR_CONN_STATE_HANDSHAKING) {
893 /* continue handshaking even if global token bucket is empty */
894 return connection_tls_continue_handshake(conn);
897 log_fn(LOG_DEBUG,"%d: starting, inbuf_datalen %d (%d pending in tls object). at_most %d.",
898 conn->s,(int)buf_datalen(conn->inbuf),tor_tls_get_pending_bytes(conn->tls), at_most);
900 /* else open, or closing */
901 result = read_to_buf_tls(conn->tls, at_most, conn->inbuf);
903 switch (result) {
904 case TOR_TLS_CLOSE:
905 log_fn(LOG_INFO,"TLS connection closed on read. Closing. (Nickname %s, address %s",
906 conn->nickname ? conn->nickname : "not set", conn->address);
907 return -1;
908 case TOR_TLS_ERROR:
909 log_fn(LOG_INFO,"tls error. breaking (nickname %s, address %s).",
910 conn->nickname ? conn->nickname : "not set", conn->address);
911 return -1;
912 case TOR_TLS_WANTWRITE:
913 connection_start_writing(conn);
914 return 0;
915 case TOR_TLS_WANTREAD: /* we're already reading */
916 case TOR_TLS_DONE: /* no data read, so nothing to process */
917 result = 0;
918 break; /* so we call bucket_decrement below */
920 } else {
921 result = read_to_buf(conn->s, at_most, conn->inbuf,
922 &conn->inbuf_reached_eof);
924 // log(LOG_DEBUG,"connection_read_to_buf(): read_to_buf returned %d.",read_result);
926 if (result < 0)
927 return -1;
930 if (result > 0) { /* change *max_to_read */
931 *max_to_read = at_most - result;
934 if (result > 0 && !is_local_IP(conn->addr)) { /* remember it */
935 rep_hist_note_bytes_read(result, time(NULL));
936 connection_read_bucket_decrement(conn, result);
939 /* Call even if result is 0, since the global read bucket may
940 * have reached 0 on a different conn, and this guy needs to
941 * know to stop reading. */
942 connection_consider_empty_buckets(conn);
944 return 0;
947 /** A pass-through to fetch_from_buf. */
948 int connection_fetch_from_buf(char *string, size_t len, connection_t *conn) {
949 return fetch_from_buf(string, len, conn->inbuf);
952 /** Return conn-\>outbuf_flushlen: how many bytes conn wants to flush
953 * from its outbuf. */
954 int connection_wants_to_flush(connection_t *conn) {
955 return conn->outbuf_flushlen;
958 /** Are there too many bytes on edge connection <b>conn</b>'s outbuf to
959 * send back a relay-level sendme yet? Return 1 if so, 0 if not. Used by
960 * connection_edge_consider_sending_sendme().
962 int connection_outbuf_too_full(connection_t *conn) {
963 return (conn->outbuf_flushlen > 10*CELL_PAYLOAD_SIZE);
966 /** Try to flush more bytes onto conn-\>s.
968 * This function gets called either from conn_write() in main.c
969 * when poll() has declared that conn wants to write, or below
970 * from connection_write_to_buf() when an entire TLS record is ready.
972 * Update conn-\>timestamp_lastwritten to now, and call flush_buf
973 * or flush_buf_tls appropriately. If it succeeds and there no more
974 * more bytes on conn->outbuf, then call connection_finished_flushing
975 * on it too.
977 * Mark the connection and return -1 if you want to close it, else
978 * return 0.
980 int connection_handle_write(connection_t *conn) {
981 int e, len=sizeof(e);
982 int result;
983 time_t now = time(NULL);
985 tor_assert(!connection_is_listener(conn));
987 conn->timestamp_lastwritten = now;
989 /* Sometimes, "writeable" means "connected". */
990 if (connection_state_is_connecting(conn)) {
991 if (getsockopt(conn->s, SOL_SOCKET, SO_ERROR, (void*)&e, &len) < 0) {
992 log_fn(LOG_WARN,"getsockopt() syscall failed?! Please report to tor-ops.");
993 connection_close_immediate(conn);
994 connection_mark_for_close(conn);
995 return -1;
997 if (e) {
998 /* some sort of error, but maybe just inprogress still */
999 if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
1000 log_fn(LOG_INFO,"in-progress connect failed. Removing.");
1001 connection_close_immediate(conn);
1002 connection_mark_for_close(conn);
1003 /* it's safe to pass OPs to router_mark_as_down(), since it just
1004 * ignores unrecognized routers
1006 if (conn->type == CONN_TYPE_OR)
1007 router_mark_as_down(conn->identity_digest);
1008 return -1;
1009 } else {
1010 return 0; /* no change, see if next time is better */
1013 /* The connection is successful. */
1014 return connection_finished_connecting(conn);
1017 if (connection_speaks_cells(conn)) {
1018 if (conn->state == OR_CONN_STATE_HANDSHAKING) {
1019 connection_stop_writing(conn);
1020 if (connection_tls_continue_handshake(conn) < 0) {
1021 connection_close_immediate(conn); /* Don't flush; connection is dead. */
1022 connection_mark_for_close(conn);
1023 return -1;
1025 return 0;
1028 /* else open, or closing */
1029 result = flush_buf_tls(conn->tls, conn->outbuf, &conn->outbuf_flushlen);
1030 switch (result) {
1031 case TOR_TLS_ERROR:
1032 case TOR_TLS_CLOSE:
1033 log_fn(LOG_INFO,result==TOR_TLS_ERROR?
1034 "tls error. breaking.":"TLS connection closed on flush");
1035 connection_close_immediate(conn); /* Don't flush; connection is dead. */
1036 connection_mark_for_close(conn);
1037 return -1;
1038 case TOR_TLS_WANTWRITE:
1039 log_fn(LOG_DEBUG,"wanted write.");
1040 /* we're already writing */
1041 return 0;
1042 case TOR_TLS_WANTREAD:
1043 /* Make sure to avoid a loop if the receive buckets are empty. */
1044 log_fn(LOG_DEBUG,"wanted read.");
1045 if (!connection_is_reading(conn)) {
1046 connection_stop_writing(conn);
1047 conn->wants_to_write = 1;
1048 /* we'll start reading again when the next second arrives,
1049 * and then also start writing again.
1052 /* else no problem, we're already reading */
1053 return 0;
1054 /* case TOR_TLS_DONE:
1055 * for TOR_TLS_DONE, fall through to check if the flushlen
1056 * is empty, so we can stop writing.
1059 } else {
1060 result = flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen);
1061 if (result < 0) {
1062 connection_close_immediate(conn); /* Don't flush; connection is dead. */
1063 conn->has_sent_end = 1;
1064 connection_mark_for_close(conn);
1065 return -1;
1069 if (result > 0 && !is_local_IP(conn->addr)) { /* remember it */
1070 rep_hist_note_bytes_written(result, now);
1071 global_write_bucket -= result;
1074 if (!connection_wants_to_flush(conn)) { /* it's done flushing */
1075 if (connection_finished_flushing(conn) < 0) {
1076 /* already marked */
1077 return -1;
1081 return 0;
1084 /** Append <b>len</b> bytes of <b>string</b> onto <b>conn</b>'s
1085 * outbuf, and ask it to start writing.
1087 void connection_write_to_buf(const char *string, size_t len, connection_t *conn) {
1089 if (!len || conn->marked_for_close)
1090 return;
1092 if (write_to_buf(string, len, conn->outbuf) < 0) {
1093 if (conn->type == CONN_TYPE_AP || conn->type == CONN_TYPE_EXIT) {
1094 /* if it failed, it means we have our package/delivery windows set
1095 wrong compared to our max outbuf size. close the whole circuit. */
1096 log_fn(LOG_WARN,"write_to_buf failed. Closing circuit (fd %d).", conn->s);
1097 circuit_mark_for_close(circuit_get_by_conn(conn));
1098 } else {
1099 log_fn(LOG_WARN,"write_to_buf failed. Closing connection (fd %d).", conn->s);
1100 connection_mark_for_close(conn);
1102 return;
1105 connection_start_writing(conn);
1106 conn->outbuf_flushlen += len;
1109 /** Return the conn to addr/port that has the most recent
1110 * timestamp_created, or NULL if no such conn exists. */
1111 connection_t *connection_exact_get_by_addr_port(uint32_t addr, uint16_t port) {
1112 int i, n;
1113 connection_t *conn, *best=NULL;
1114 connection_t **carray;
1116 get_connection_array(&carray,&n);
1117 for (i=0;i<n;i++) {
1118 conn = carray[i];
1119 if (conn->addr == addr && conn->port == port && !conn->marked_for_close &&
1120 (!best || best->timestamp_created < conn->timestamp_created))
1121 best = conn;
1123 return best;
1126 connection_t *connection_get_by_identity_digest(const char *digest, int type)
1128 int i, n;
1129 connection_t *conn, *best=NULL;
1130 connection_t **carray;
1132 get_connection_array(&carray,&n);
1133 for (i=0;i<n;i++) {
1134 conn = carray[i];
1135 if (conn->type != type)
1136 continue;
1137 if (!memcmp(conn->identity_digest, digest, DIGEST_LEN)
1138 && !conn->marked_for_close
1139 && (!best || best->timestamp_created < conn->timestamp_created))
1140 best = conn;
1142 return best;
1145 /** Return a connection of type <b>type</b> that is not marked for
1146 * close.
1148 connection_t *connection_get_by_type(int type) {
1149 int i, n;
1150 connection_t *conn;
1151 connection_t **carray;
1153 get_connection_array(&carray,&n);
1154 for (i=0;i<n;i++) {
1155 conn = carray[i];
1156 if (conn->type == type && !conn->marked_for_close)
1157 return conn;
1159 return NULL;
1162 /** Return a connection of type <b>type</b> that is in state <b>state</b>,
1163 * and that is not marked for close.
1165 connection_t *connection_get_by_type_state(int type, int state) {
1166 int i, n;
1167 connection_t *conn;
1168 connection_t **carray;
1170 get_connection_array(&carray,&n);
1171 for (i=0;i<n;i++) {
1172 conn = carray[i];
1173 if (conn->type == type && conn->state == state && !conn->marked_for_close)
1174 return conn;
1176 return NULL;
1179 /** Return the connection of type <b>type</b> that is in state
1180 * <b>state</b>, that was written to least recently, and that is not
1181 * marked for close.
1183 connection_t *connection_get_by_type_state_lastwritten(int type, int state) {
1184 int i, n;
1185 connection_t *conn, *best=NULL;
1186 connection_t **carray;
1188 get_connection_array(&carray,&n);
1189 for (i=0;i<n;i++) {
1190 conn = carray[i];
1191 if (conn->type == type && conn->state == state && !conn->marked_for_close)
1192 if (!best || conn->timestamp_lastwritten < best->timestamp_lastwritten)
1193 best = conn;
1195 return best;
1198 /** Return a connection of type <b>type</b> that has rendquery equal
1199 * to <b>rendquery</b>, and that is not marked for close.
1201 connection_t *connection_get_by_type_rendquery(int type, const char *rendquery) {
1202 int i, n;
1203 connection_t *conn;
1204 connection_t **carray;
1206 get_connection_array(&carray,&n);
1207 for (i=0;i<n;i++) {
1208 conn = carray[i];
1209 if (conn->type == type &&
1210 !conn->marked_for_close &&
1211 !rend_cmp_service_ids(rendquery, conn->rend_query))
1212 return conn;
1214 return NULL;
1217 /** Return 1 if <b>conn</b> is a listener conn, else return 0. */
1218 int connection_is_listener(connection_t *conn) {
1219 if (conn->type == CONN_TYPE_OR_LISTENER ||
1220 conn->type == CONN_TYPE_AP_LISTENER ||
1221 conn->type == CONN_TYPE_DIR_LISTENER ||
1222 conn->type == CONN_TYPE_CONTROL_LISTENER)
1223 return 1;
1224 return 0;
1227 /** Return 1 if <b>conn</b> is in state "open" and is not marked
1228 * for close, else return 0.
1230 int connection_state_is_open(connection_t *conn) {
1231 tor_assert(conn);
1233 if (conn->marked_for_close)
1234 return 0;
1236 if ((conn->type == CONN_TYPE_OR && conn->state == OR_CONN_STATE_OPEN) ||
1237 (conn->type == CONN_TYPE_AP && conn->state == AP_CONN_STATE_OPEN) ||
1238 (conn->type == CONN_TYPE_EXIT && conn->state == EXIT_CONN_STATE_OPEN) ||
1239 (conn->type == CONN_TYPE_CONTROL && conn->state ==CONTROL_CONN_STATE_OPEN))
1240 return 1;
1242 return 0;
1245 /** Return 1 if conn is in 'connecting' state, else return 0. */
1246 int connection_state_is_connecting(connection_t *conn) {
1247 tor_assert(conn);
1249 if (conn->marked_for_close)
1250 return 0;
1251 switch (conn->type)
1253 case CONN_TYPE_OR:
1254 return conn->state == OR_CONN_STATE_CONNECTING;
1255 case CONN_TYPE_EXIT:
1256 return conn->state == EXIT_CONN_STATE_CONNECTING;
1257 case CONN_TYPE_DIR:
1258 return conn->state == DIR_CONN_STATE_CONNECTING;
1261 return 0;
1264 /** Write a destroy cell with circ ID <b>circ_id</b> onto OR connection
1265 * <b>conn</b>.
1267 * Return 0.
1269 int connection_send_destroy(uint16_t circ_id, connection_t *conn) {
1270 cell_t cell;
1272 tor_assert(conn);
1273 tor_assert(connection_speaks_cells(conn));
1275 memset(&cell, 0, sizeof(cell_t));
1276 cell.circ_id = circ_id;
1277 cell.command = CELL_DESTROY;
1278 log_fn(LOG_INFO,"Sending destroy (circID %d).", circ_id);
1279 connection_or_write_cell_to_buf(&cell, conn);
1280 return 0;
1283 /** Process new bytes that have arrived on conn-\>inbuf.
1285 * This function just passes conn to the connection-specific
1286 * connection_*_process_inbuf() function. It also passes in
1287 * package_partial if wanted.
1289 static int connection_process_inbuf(connection_t *conn, int package_partial) {
1291 tor_assert(conn);
1293 switch (conn->type) {
1294 case CONN_TYPE_OR:
1295 return connection_or_process_inbuf(conn);
1296 case CONN_TYPE_EXIT:
1297 case CONN_TYPE_AP:
1298 return connection_edge_process_inbuf(conn, package_partial);
1299 case CONN_TYPE_DIR:
1300 return connection_dir_process_inbuf(conn);
1301 case CONN_TYPE_DNSWORKER:
1302 return connection_dns_process_inbuf(conn);
1303 case CONN_TYPE_CPUWORKER:
1304 return connection_cpu_process_inbuf(conn);
1305 case CONN_TYPE_CONTROL:
1306 return connection_control_process_inbuf(conn);
1307 default:
1308 log_fn(LOG_WARN,"got unexpected conn type %d.", conn->type);
1309 return -1;
1313 /** We just finished flushing bytes from conn-\>outbuf, and there
1314 * are no more bytes remaining.
1316 * This function just passes conn to the connection-specific
1317 * connection_*_finished_flushing() function.
1319 static int connection_finished_flushing(connection_t *conn) {
1321 tor_assert(conn);
1323 // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
1325 switch (conn->type) {
1326 case CONN_TYPE_OR:
1327 return connection_or_finished_flushing(conn);
1328 case CONN_TYPE_AP:
1329 case CONN_TYPE_EXIT:
1330 return connection_edge_finished_flushing(conn);
1331 case CONN_TYPE_DIR:
1332 return connection_dir_finished_flushing(conn);
1333 case CONN_TYPE_DNSWORKER:
1334 return connection_dns_finished_flushing(conn);
1335 case CONN_TYPE_CPUWORKER:
1336 return connection_cpu_finished_flushing(conn);
1337 case CONN_TYPE_CONTROL:
1338 return connection_control_finished_flushing(conn);
1339 default:
1340 log_fn(LOG_WARN,"got unexpected conn type %d.", conn->type);
1341 return -1;
1345 /** Called when our attempt to connect() to another server has just
1346 * succeeded.
1348 * This function just passes conn to the connection-specific
1349 * connection_*_finished_connecting() function.
1351 static int connection_finished_connecting(connection_t *conn)
1353 tor_assert(conn);
1354 switch (conn->type)
1356 case CONN_TYPE_OR:
1357 return connection_or_finished_connecting(conn);
1358 case CONN_TYPE_EXIT:
1359 return connection_edge_finished_connecting(conn);
1360 case CONN_TYPE_DIR:
1361 return connection_dir_finished_connecting(conn);
1362 default:
1363 log_fn(LOG_WARN,"got unexpected conn type %d.", conn->type);
1364 return -1;
1368 static int connection_reached_eof(connection_t *conn)
1370 switch (conn->type) {
1371 case CONN_TYPE_OR:
1372 return connection_or_reached_eof(conn);
1373 case CONN_TYPE_AP:
1374 case CONN_TYPE_EXIT:
1375 return connection_edge_reached_eof(conn);
1376 case CONN_TYPE_DIR:
1377 return connection_dir_reached_eof(conn);
1378 case CONN_TYPE_DNSWORKER:
1379 return connection_dns_reached_eof(conn);
1380 case CONN_TYPE_CPUWORKER:
1381 return connection_cpu_reached_eof(conn);
1382 case CONN_TYPE_CONTROL:
1383 return connection_control_reached_eof(conn);
1384 default:
1385 log_fn(LOG_WARN,"got unexpected conn type %d.", conn->type);
1386 return -1;
1390 /** Verify that connection <b>conn</b> has all of its invariants
1391 * correct. Trigger an assert if anything is invalid.
1393 void assert_connection_ok(connection_t *conn, time_t now)
1395 tor_assert(conn);
1396 tor_assert(conn->magic == CONNECTION_MAGIC);
1397 tor_assert(conn->type >= _CONN_TYPE_MIN);
1398 tor_assert(conn->type <= _CONN_TYPE_MAX);
1400 if (conn->outbuf_flushlen > 0) {
1401 tor_assert(connection_is_writing(conn) || conn->wants_to_write);
1404 if (conn->hold_open_until_flushed)
1405 tor_assert(conn->marked_for_close);
1407 /* XXX check: wants_to_read, wants_to_write, s, poll_index,
1408 * marked_for_close. */
1410 /* buffers */
1411 if (!connection_is_listener(conn)) {
1412 assert_buf_ok(conn->inbuf);
1413 assert_buf_ok(conn->outbuf);
1416 #if 0 /* computers often go back in time; no way to know */
1417 tor_assert(!now || conn->timestamp_lastread <= now);
1418 tor_assert(!now || conn->timestamp_lastwritten <= now);
1419 tor_assert(conn->timestamp_created <= conn->timestamp_lastread);
1420 tor_assert(conn->timestamp_created <= conn->timestamp_lastwritten);
1421 #endif
1423 /* XXX Fix this; no longer so.*/
1424 #if 0
1425 if (conn->type != CONN_TYPE_OR && conn->type != CONN_TYPE_DIR)
1426 tor_assert(!conn->pkey);
1427 /* pkey is set if we're a dir client, or if we're an OR in state OPEN
1428 * connected to another OR.
1430 #endif
1432 if (conn->type != CONN_TYPE_OR) {
1433 tor_assert(!conn->tls);
1434 } else {
1435 if (conn->state == OR_CONN_STATE_OPEN) {
1436 /* tor_assert(conn->bandwidth > 0); */
1437 /* the above isn't necessarily true: if we just did a TLS
1438 * handshake but we didn't recognize the other peer, or it
1439 * gave a bad cert/etc, then we won't have assigned bandwidth,
1440 * yet it will be open. -RD
1442 tor_assert(conn->receiver_bucket >= 0);
1444 tor_assert(conn->addr && conn->port);
1445 tor_assert(conn->address);
1446 if (conn->state != OR_CONN_STATE_CONNECTING)
1447 tor_assert(conn->tls);
1450 if (conn->type != CONN_TYPE_EXIT && conn->type != CONN_TYPE_AP) {
1451 tor_assert(!conn->stream_id);
1452 tor_assert(!conn->next_stream);
1453 tor_assert(!conn->cpath_layer);
1454 tor_assert(!conn->package_window);
1455 tor_assert(!conn->deliver_window);
1456 tor_assert(!conn->done_sending);
1457 tor_assert(!conn->done_receiving);
1458 } else {
1459 /* XXX unchecked: package window, deliver window. */
1461 if (conn->type == CONN_TYPE_AP) {
1462 tor_assert(conn->socks_request);
1463 if (conn->state == AP_CONN_STATE_OPEN) {
1464 tor_assert(conn->socks_request->has_finished);
1465 tor_assert(conn->cpath_layer);
1466 assert_cpath_layer_ok(conn->cpath_layer);
1468 } else {
1469 tor_assert(!conn->socks_request);
1471 if (conn->type == CONN_TYPE_EXIT) {
1472 tor_assert(conn->purpose == EXIT_PURPOSE_CONNECT ||
1473 conn->purpose == EXIT_PURPOSE_RESOLVE);
1474 } else if (conn->type != CONN_TYPE_DIR) {
1475 tor_assert(!conn->purpose); /* only used for dir types currently */
1478 switch (conn->type)
1480 case CONN_TYPE_OR_LISTENER:
1481 case CONN_TYPE_AP_LISTENER:
1482 case CONN_TYPE_DIR_LISTENER:
1483 case CONN_TYPE_CONTROL_LISTENER:
1484 tor_assert(conn->state == LISTENER_STATE_READY);
1485 break;
1486 case CONN_TYPE_OR:
1487 tor_assert(conn->state >= _OR_CONN_STATE_MIN);
1488 tor_assert(conn->state <= _OR_CONN_STATE_MAX);
1489 break;
1490 case CONN_TYPE_EXIT:
1491 tor_assert(conn->state >= _EXIT_CONN_STATE_MIN);
1492 tor_assert(conn->state <= _EXIT_CONN_STATE_MAX);
1493 break;
1494 case CONN_TYPE_AP:
1495 tor_assert(conn->state >= _AP_CONN_STATE_MIN);
1496 tor_assert(conn->state <= _AP_CONN_STATE_MAX);
1497 tor_assert(conn->socks_request);
1498 break;
1499 case CONN_TYPE_DIR:
1500 tor_assert(conn->state >= _DIR_CONN_STATE_MIN);
1501 tor_assert(conn->state <= _DIR_CONN_STATE_MAX);
1502 tor_assert(conn->purpose >= _DIR_PURPOSE_MIN);
1503 tor_assert(conn->purpose <= _DIR_PURPOSE_MAX);
1504 break;
1505 case CONN_TYPE_DNSWORKER:
1506 tor_assert(conn->state == DNSWORKER_STATE_IDLE ||
1507 conn->state == DNSWORKER_STATE_BUSY);
1508 break;
1509 case CONN_TYPE_CPUWORKER:
1510 tor_assert(conn->state >= _CPUWORKER_STATE_MIN);
1511 tor_assert(conn->state <= _CPUWORKER_STATE_MAX);
1512 break;
1513 case CONN_TYPE_CONTROL:
1514 tor_assert(conn->state >= _CONTROL_CONN_STATE_MIN);
1515 tor_assert(conn->state <= _CONTROL_CONN_STATE_MAX);
1516 break;
1517 default:
1518 tor_assert(0);