tolerate bandwidtch buckets going negative (i hope)
[tor.git] / src / or / connection.c
blob8df204ff7f2c6f1091f785f4995e021ece588bca
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$ */
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 safe circuit", /* 7 */
60 "waiting for connected", /* 8 */
61 "waiting for resolve", /* 9 */
62 "open" }, /* 10 */
63 { "ready" }, /* dir listener, 0 */
64 { "", /* dir, 0 */
65 "connecting", /* 1 */
66 "client sending", /* 2 */
67 "client reading", /* 3 */
68 "awaiting command", /* 4 */
69 "writing" }, /* 5 */
70 { "", /* dns worker, 0 */
71 "idle", /* 1 */
72 "busy" }, /* 2 */
73 { "", /* cpu worker, 0 */
74 "idle", /* 1 */
75 "busy with onion", /* 2 */
76 "busy with handshake" }, /* 3 */
77 { "ready" }, /* control listener, 0 */
78 { "", /* control, 0 */
79 "ready", /* 1 */
80 "waiting for authentication", }, /* 2 */
83 /********* END VARIABLES ************/
85 static int connection_create_listener(const char *bindaddress,
86 uint16_t bindport, int type);
87 static int connection_init_accepted_conn(connection_t *conn);
88 static int connection_handle_listener_read(connection_t *conn, int new_type);
89 static int connection_receiver_bucket_should_increase(connection_t *conn);
90 static int connection_finished_flushing(connection_t *conn);
91 static int connection_finished_connecting(connection_t *conn);
92 static int connection_reached_eof(connection_t *conn);
93 static int connection_read_to_buf(connection_t *conn, int *max_to_read);
94 static int connection_process_inbuf(connection_t *conn, int package_partial);
95 static int connection_bucket_read_limit(connection_t *conn);
97 /**************************************************************/
99 /** Allocate space for a new connection_t. This function just initializes
100 * conn; you must call connection_add() to link it into the main array.
102 * Set conn-\>type to <b>type</b>. Set conn-\>s and conn-\>poll_index to
103 * -1 to signify they are not yet assigned.
105 * If conn is not a listener type, allocate buffers for it. If it's
106 * an AP type, allocate space to store the socks_request.
108 * Assign a pseudorandom next_circ_id between 0 and 2**15.
110 * Initialize conn's timestamps to now.
112 connection_t *connection_new(int type) {
113 connection_t *conn;
114 time_t now = time(NULL);
116 conn = tor_malloc_zero(sizeof(connection_t));
117 conn->magic = CONNECTION_MAGIC;
118 conn->s = -1; /* give it a default of 'not used' */
119 conn->poll_index = -1; /* also default to 'not used' */
121 conn->type = type;
122 if (!connection_is_listener(conn)) { /* listeners never use their buf */
123 conn->inbuf = buf_new();
124 conn->outbuf = buf_new();
126 if (type == CONN_TYPE_AP) {
127 conn->socks_request = tor_malloc_zero(sizeof(socks_request_t));
130 conn->next_circ_id = crypto_pseudo_rand_int(1<<15);
132 conn->timestamp_created = now;
133 conn->timestamp_lastread = now;
134 conn->timestamp_lastwritten = now;
136 return conn;
139 /** Deallocate memory used by <b>conn</b>. Deallocate its buffers if necessary,
140 * close its socket if necessary, and mark the directory as dirty if <b>conn</b>
141 * is an OR or OP connection.
143 void connection_free(connection_t *conn) {
144 tor_assert(conn);
145 tor_assert(conn->magic == CONNECTION_MAGIC);
147 if (!connection_is_listener(conn)) {
148 buf_free(conn->inbuf);
149 buf_free(conn->outbuf);
151 tor_free(conn->address);
152 tor_free(conn->chosen_exit_name);
154 if (connection_speaks_cells(conn)) {
155 if (conn->state == OR_CONN_STATE_OPEN)
156 directory_set_dirty();
157 if (conn->tls)
158 tor_tls_free(conn->tls);
161 if (conn->identity_pkey)
162 crypto_free_pk_env(conn->identity_pkey);
163 tor_free(conn->nickname);
164 tor_free(conn->socks_request);
166 if (conn->s >= 0) {
167 log_fn(LOG_INFO,"closing fd %d.",conn->s);
168 tor_close_socket(conn->s);
170 if (conn->read_event) {
171 event_del(conn->read_event);
172 tor_free(conn->read_event);
174 if (conn->write_event) {
175 event_del(conn->write_event);
176 tor_free(conn->write_event);
178 memset(conn, 0xAA, sizeof(connection_t)); /* poison memory */
179 tor_free(conn);
182 /** Call connection_free() on every connection in our array.
183 * This is used by cpuworkers and dnsworkers when they fork,
184 * so they don't keep resources held open (especially sockets).
186 void connection_free_all(void) {
187 int i, n;
188 connection_t **carray;
190 get_connection_array(&carray,&n);
191 for (i=0;i<n;i++)
192 connection_free(carray[i]);
195 /** Do any cleanup needed:
196 * - Directory conns that failed to fetch a rendezvous descriptor
197 * need to inform pending rendezvous streams.
198 * - OR conns need to call rep_hist_note_*() to record status.
199 * - AP conns need to send a socks reject if necessary.
200 * - Exit conns need to call connection_dns_remove() if necessary.
201 * - AP and Exit conns need to send an end cell if they can.
202 * - DNS conns need to fail any resolves that are pending on them.
204 void connection_about_to_close_connection(connection_t *conn)
207 assert(conn->marked_for_close);
209 if (conn->type == CONN_TYPE_AP || conn->type == CONN_TYPE_EXIT) {
210 if (!conn->has_sent_end)
211 log_fn(LOG_WARN,"Bug: Edge connection hasn't sent end yet?");
214 switch (conn->type) {
215 case CONN_TYPE_DIR:
216 if (conn->state == DIR_CONN_STATE_CONNECTING) {
217 /* it's a directory server and connecting failed: forget about
218 this router */
219 connection_dir_connect_failed(conn);
221 if (conn->purpose == DIR_PURPOSE_FETCH_RENDDESC)
222 rend_client_desc_fetched(conn->rend_query, 0);
223 break;
224 case CONN_TYPE_OR:
225 /* Remember why we're closing this connection. */
226 if (conn->state != OR_CONN_STATE_OPEN) {
227 if (connection_or_nonopen_was_started_here(conn)) {
228 rep_hist_note_connect_failed(conn->identity_digest, time(NULL));
229 control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED);
231 } else if (conn->hold_open_until_flushed) {
232 /* XXXX009 We used to have an arg that told us whether we closed the
233 * connection on purpose or not. Can we use hold_open_until_flushed
234 * instead? We only set it when we are intentionally closing a
235 * connection. -NM
237 * (Of course, now things we set to close which expire rather than
238 * flushing still get noted as dead, not disconnected. But this is an
239 * improvement. -NM
241 rep_hist_note_disconnect(conn->identity_digest, time(NULL));
242 control_event_or_conn_status(conn, OR_CONN_EVENT_CLOSED);
243 } else if (conn->identity_digest) {
244 rep_hist_note_connection_died(conn->identity_digest, time(NULL));
245 control_event_or_conn_status(conn, OR_CONN_EVENT_CLOSED);
247 break;
248 case CONN_TYPE_AP:
249 if (conn->socks_request->has_finished == 0) {
250 log_fn(LOG_INFO,"Cleaning up AP -- sending socks reject.");
251 conn->hold_open_until_flushed = 1;
252 /* XXX this socks_reply never gets sent, since conn
253 * gets removed right after this function finishes. */
254 connection_ap_handshake_socks_reply(conn, NULL, 0, -1);
255 conn->socks_request->has_finished = 1;
256 } else {
257 control_event_stream_status(conn, STREAM_EVENT_CLOSED);
259 break;
260 case CONN_TYPE_EXIT:
261 if (conn->state == EXIT_CONN_STATE_RESOLVING) {
262 circuit_detach_stream(circuit_get_by_conn(conn), conn);
263 connection_dns_remove(conn);
265 break;
266 case CONN_TYPE_DNSWORKER:
267 if (conn->state == DNSWORKER_STATE_BUSY) {
268 dns_cancel_pending_resolve(conn->address);
270 break;
274 /** Close the underlying socket for <b>conn</b>, so we don't try to
275 * flush it. Must be used in conjunction with (right before)
276 * connection_mark_for_close().
278 void connection_close_immediate(connection_t *conn)
280 assert_connection_ok(conn,0);
281 if (conn->s < 0) {
282 log_fn(LOG_WARN,"Bug: Attempt to close already-closed connection.");
283 return;
285 if (conn->outbuf_flushlen) {
286 log_fn(LOG_INFO,"fd %d, type %s, state %d, %d bytes on outbuf.",
287 conn->s, CONN_TYPE_TO_STRING(conn->type),
288 conn->state, (int)conn->outbuf_flushlen);
290 tor_close_socket(conn->s);
291 conn->s = -1;
292 if (!connection_is_listener(conn)) {
293 buf_clear(conn->outbuf);
294 conn->outbuf_flushlen = 0;
298 /** Mark <b>conn</b> to be closed next time we loop through
299 * conn_close_if_marked() in main.c. */
301 _connection_mark_for_close(connection_t *conn)
303 assert_connection_ok(conn,0);
305 if (conn->marked_for_close) {
306 log(LOG_WARN, "Bug: Double mark-for-close on connection.");
307 return -1;
310 conn->marked_for_close = 1;
311 add_connection_to_closeable_list(conn);
313 /* in case we're going to be held-open-til-flushed, reset
314 * the number of seconds since last successful write, so
315 * we get our whole 15 seconds */
316 conn->timestamp_lastwritten = time(NULL);
318 return 0;
321 /** Find each connection that has hold_open_until_flushed set to
322 * 1 but hasn't written in the past 15 seconds, and set
323 * hold_open_until_flushed to 0. This means it will get cleaned
324 * up in the next loop through close_if_marked() in main.c.
326 void connection_expire_held_open(void)
328 connection_t **carray, *conn;
329 int n, i;
330 time_t now;
332 now = time(NULL);
334 get_connection_array(&carray, &n);
335 for (i = 0; i < n; ++i) {
336 conn = carray[i];
337 /* If we've been holding the connection open, but we haven't written
338 * for 15 seconds...
340 if (conn->hold_open_until_flushed) {
341 tor_assert(conn->marked_for_close);
342 if (now - conn->timestamp_lastwritten >= 15) {
343 log_fn(LOG_NOTICE,"Giving up on marked_for_close conn that's been flushing for 15s (fd %d, type %s, state %d).",
344 conn->s, CONN_TYPE_TO_STRING(conn->type), conn->state);
345 conn->hold_open_until_flushed = 0;
351 /** Bind a new non-blocking socket listening to
352 * <b>bindaddress</b>:<b>bindport</b>, and add this new connection
353 * (of type <b>type</b>) to the connection array.
355 * If <b>bindaddress</b> includes a port, we bind on that port; otherwise, we
356 * use bindport.
358 static int connection_create_listener(const char *bindaddress, uint16_t bindport, int type) {
359 struct sockaddr_in bindaddr; /* where to bind */
360 connection_t *conn;
361 uint16_t usePort;
362 uint32_t addr;
363 int s; /* the socket we're going to make */
364 int one=1;
366 memset(&bindaddr,0,sizeof(struct sockaddr_in));
367 if (parse_addr_port(bindaddress, NULL, &addr, &usePort)<0) {
368 log_fn(LOG_WARN, "Error parsing/resolving BindAddress %s",bindaddress);
369 return -1;
372 if (usePort==0)
373 usePort = bindport;
374 bindaddr.sin_addr.s_addr = htonl(addr);
375 bindaddr.sin_family = AF_INET;
376 bindaddr.sin_port = htons((uint16_t) usePort);
378 s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
379 if (s < 0) {
380 log_fn(LOG_WARN,"Socket creation failed.");
381 return -1;
382 } else if (!SOCKET_IS_POLLABLE(s)) {
383 log_fn(LOG_WARN,"Too many connections; can't create pollable listener.");
384 tor_close_socket(s);
385 return -1;
388 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*) &one, sizeof(one));
390 if (bind(s,(struct sockaddr *)&bindaddr,sizeof(bindaddr)) < 0) {
391 log_fn(LOG_WARN,"Could not bind to port %u: %s",usePort,
392 tor_socket_strerror(tor_socket_errno(s)));
393 return -1;
396 if (listen(s,SOMAXCONN) < 0) {
397 log_fn(LOG_WARN,"Could not listen on port %u: %s",usePort,
398 tor_socket_strerror(tor_socket_errno(s)));
399 return -1;
402 set_socket_nonblocking(s);
404 conn = connection_new(type);
405 conn->s = s;
407 if (connection_add(conn) < 0) { /* no space, forget it */
408 log_fn(LOG_WARN,"connection_add failed. Giving up.");
409 connection_free(conn);
410 return -1;
413 log_fn(LOG_DEBUG,"%s listening on port %u.",conn_type_to_string[type], usePort);
415 conn->state = LISTENER_STATE_READY;
416 connection_start_reading(conn);
418 return 0;
421 /** The listener connection <b>conn</b> told poll() it wanted to read.
422 * Call accept() on conn-\>s, and add the new connection if necessary.
424 static int connection_handle_listener_read(connection_t *conn, int new_type) {
425 int news; /* the new socket */
426 connection_t *newconn;
427 /* information about the remote peer when connecting to other routers */
428 struct sockaddr_in remote;
429 /* length of the remote address. Must be an int, since accept() needs that. */
430 int remotelen = sizeof(struct sockaddr_in);
432 news = accept(conn->s,(struct sockaddr *)&remote,&remotelen);
433 if (!SOCKET_IS_POLLABLE(news)) {
434 /* accept() error, or too many conns to poll */
435 int e;
436 if (news>=0) {
437 /* Too many conns to poll. */
438 log_fn(LOG_WARN,"Too many connections; couldn't accept connection.");
439 tor_close_socket(news);
440 return 0;
442 e = tor_socket_errno(conn->s);
443 if (ERRNO_IS_ACCEPT_EAGAIN(e)) {
444 return 0; /* he hung up before we could accept(). that's fine. */
445 } else if (ERRNO_IS_ACCEPT_RESOURCE_LIMIT(e)) {
446 log_fn(LOG_NOTICE,"accept failed: %s. Dropping incoming connection.",
447 tor_socket_strerror(e));
448 return 0;
450 /* else there was a real error. */
451 log_fn(LOG_WARN,"accept() failed: %s. Closing listener.",
452 tor_socket_strerror(e));
453 connection_mark_for_close(conn);
454 return -1;
456 log(LOG_INFO,"Connection accepted on socket %d (child of fd %d).",news, conn->s);
458 set_socket_nonblocking(news);
460 /* process entrance policies here, before we even create the connection */
461 if (new_type == CONN_TYPE_AP) {
462 /* check sockspolicy to see if we should accept it */
463 if (socks_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
464 log_fn(LOG_NOTICE,"Denying socks connection from untrusted address %s.",
465 inet_ntoa(remote.sin_addr));
466 tor_close_socket(news);
467 return 0;
470 if (new_type == CONN_TYPE_DIR) {
471 /* check dirpolicy to see if we should accept it */
472 if (dir_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
473 log_fn(LOG_NOTICE,"Denying dir connection from address %s.",
474 inet_ntoa(remote.sin_addr));
475 tor_close_socket(news);
476 return 0;
480 newconn = connection_new(new_type);
481 newconn->s = news;
483 newconn->address = tor_strdup(inet_ntoa(remote.sin_addr)); /* remember the remote address */
484 newconn->addr = ntohl(remote.sin_addr.s_addr);
485 newconn->port = ntohs(remote.sin_port);
487 if (connection_add(newconn) < 0) { /* no space, forget it */
488 connection_free(newconn);
489 return 0; /* no need to tear down the parent */
492 if (connection_init_accepted_conn(newconn) < 0) {
493 connection_mark_for_close(newconn);
494 return 0;
496 return 0;
499 /** Initialize states for newly accepted connection <b>conn</b>.
500 * If conn is an OR, start the tls handshake.
502 static int connection_init_accepted_conn(connection_t *conn) {
504 connection_start_reading(conn);
506 switch (conn->type) {
507 case CONN_TYPE_OR:
508 return connection_tls_start_handshake(conn, 1);
509 case CONN_TYPE_AP:
510 conn->state = AP_CONN_STATE_SOCKS_WAIT;
511 break;
512 case CONN_TYPE_DIR:
513 conn->purpose = DIR_PURPOSE_SERVER;
514 conn->state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
515 break;
516 case CONN_TYPE_CONTROL:
517 conn->state = CONTROL_CONN_STATE_NEEDAUTH;
518 break;
520 return 0;
523 /** Take conn, make a nonblocking socket; try to connect to
524 * addr:port (they arrive in *host order*). If fail, return -1. Else
525 * assign s to conn->\s: if connected return 1, if EAGAIN return 0.
527 * address is used to make the logs useful.
529 * On success, add conn to the list of polled connections.
531 int connection_connect(connection_t *conn, char *address, uint32_t addr, uint16_t port) {
532 int s;
533 struct sockaddr_in dest_addr;
534 or_options_t *options = get_options();
536 s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
537 if (s < 0) {
538 log_fn(LOG_WARN,"Error creating network socket: %s",
539 tor_socket_strerror(tor_socket_errno(-1)));
540 return -1;
541 } else if (!SOCKET_IS_POLLABLE(s)) {
542 log_fn(LOG_WARN,
543 "Too many connections; can't create pollable connection to %s", address);
544 tor_close_socket(s);
545 return -1;
548 if (options->OutboundBindAddress) {
549 struct sockaddr_in ext_addr;
551 memset(&ext_addr, 0, sizeof(ext_addr));
552 ext_addr.sin_family = AF_INET;
553 ext_addr.sin_port = 0;
554 if (!tor_inet_aton(options->OutboundBindAddress, &ext_addr.sin_addr)) {
555 log_fn(LOG_WARN,"Outbound bind address '%s' didn't parse. Ignoring.",
556 options->OutboundBindAddress);
557 } else {
558 if (bind(s, (struct sockaddr*)&ext_addr, sizeof(ext_addr)) < 0) {
559 log_fn(LOG_WARN,"Error binding network socket: %s",
560 tor_socket_strerror(tor_socket_errno(s)));
561 return -1;
566 set_socket_nonblocking(s);
568 memset(&dest_addr,0,sizeof(dest_addr));
569 dest_addr.sin_family = AF_INET;
570 dest_addr.sin_port = htons(port);
571 dest_addr.sin_addr.s_addr = htonl(addr);
573 log_fn(LOG_DEBUG,"Connecting to %s:%u.",address,port);
575 if (connect(s,(struct sockaddr *)&dest_addr,sizeof(dest_addr)) < 0) {
576 int e = tor_socket_errno(s);
577 if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
578 /* yuck. kill it. */
579 log_fn(LOG_INFO,"Connect() to %s:%u failed: %s",address,port,
580 tor_socket_strerror(e));
581 tor_close_socket(s);
582 return -1;
583 } else {
584 /* it's in progress. set state appropriately and return. */
585 conn->s = s;
586 if (connection_add(conn) < 0) /* no space, forget it */
587 return -1;
588 log_fn(LOG_DEBUG,"connect in progress, socket %d.",s);
589 return 0;
593 /* it succeeded. we're connected. */
594 log_fn(LOG_INFO,"Connection to %s:%u established.",address,port);
595 conn->s = s;
596 if (connection_add(conn) < 0) /* no space, forget it */
597 return -1;
598 return 1;
601 /** If there exist any listeners of type <b>type</b> in the connection
602 * array, mark them for close.
604 static void listener_close_if_present(int type) {
605 connection_t *conn;
606 connection_t **carray;
607 int i,n;
608 tor_assert(type == CONN_TYPE_OR_LISTENER ||
609 type == CONN_TYPE_AP_LISTENER ||
610 type == CONN_TYPE_DIR_LISTENER ||
611 type == CONN_TYPE_CONTROL_LISTENER);
612 get_connection_array(&carray,&n);
613 for (i=0;i<n;i++) {
614 conn = carray[i];
615 if (conn->type == type && !conn->marked_for_close) {
616 connection_close_immediate(conn);
617 connection_mark_for_close(conn);
623 * Launch any configured listener connections of type <b>type</b>. (A
624 * listener is configured if <b>port_option</b> is non-zero. If any
625 * BindAddress configuration options are given in <b>cfg</b>, create a
626 * connection binding to each one. Otherwise, create a single
627 * connection binding to the address <b>default_addr</b>.)
629 * If <b>force</b> is true, close and re-open all listener connections.
630 * Otherwise, only relaunch the listeners of this type if the number of
631 * existing connections is not as configured (e.g., because one died).
633 static int retry_listeners(int type, struct config_line_t *cfg,
634 int port_option, const char *default_addr,
635 int force)
637 if (!force) {
638 int want, have, n_conn, i;
639 struct config_line_t *c;
640 connection_t *conn;
641 connection_t **carray;
642 /* How many should there be? */
643 if (cfg && port_option) {
644 want = 0;
645 for (c = cfg; c; c = c->next)
646 ++want;
647 } else if (port_option) {
648 want = 1;
649 } else {
650 want = 0;
653 /* How many are there actually? */
654 have = 0;
655 get_connection_array(&carray,&n_conn);
656 for (i=0;i<n_conn;i++) {
657 conn = carray[i];
658 if (conn->type == type && !conn->marked_for_close)
659 ++have;
662 /* If we have the right number of listeners, do nothing. */
663 if (have == want)
664 return 0;
666 /* Otherwise, warn the user and relaunch. */
667 log_fn(LOG_NOTICE,"We have %d %s(s) open, but we want %d; relaunching.",
668 have, conn_type_to_string[type], want);
671 listener_close_if_present(type);
672 if (port_option) {
673 if (!cfg) {
674 if (connection_create_listener(default_addr, (uint16_t) port_option,
675 type)<0)
676 return -1;
677 } else {
678 for ( ; cfg; cfg = cfg->next) {
679 if (connection_create_listener(cfg->value, (uint16_t) port_option,
680 type)<0)
681 return -1;
685 return 0;
688 /** (Re)launch listeners for each port you should have open. If
689 * <b>force</b> is true, close and relaunch all listeners. If <b>force</b>
690 * is false, then only relaunch listeners when we have the wrong number of
691 * connections for a given type.
693 int retry_all_listeners(int force) {
694 or_options_t *options = get_options();
696 if (retry_listeners(CONN_TYPE_OR_LISTENER, options->ORBindAddress,
697 options->ORPort, "0.0.0.0", force)<0)
698 return -1;
699 if (retry_listeners(CONN_TYPE_DIR_LISTENER, options->DirBindAddress,
700 options->DirPort, "0.0.0.0", force)<0)
701 return -1;
702 if (retry_listeners(CONN_TYPE_AP_LISTENER, options->SocksBindAddress,
703 options->SocksPort, "127.0.0.1", force)<0)
704 return -1;
705 if (retry_listeners(CONN_TYPE_CONTROL_LISTENER, NULL,
706 options->ControlPort, "127.0.0.1", force)<0)
707 return -1;
709 return 0;
712 extern int global_read_bucket, global_write_bucket;
714 /** How many bytes at most can we read onto this connection? */
715 static int connection_bucket_read_limit(connection_t *conn) {
716 int at_most;
718 /* do a rudimentary round-robin so one circuit can't hog a connection */
719 if (connection_speaks_cells(conn)) {
720 at_most = 32*(CELL_NETWORK_SIZE);
721 } else {
722 at_most = 32*(RELAY_PAYLOAD_SIZE);
725 if (at_most > global_read_bucket)
726 at_most = global_read_bucket;
728 if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN)
729 if (at_most > conn->receiver_bucket)
730 at_most = conn->receiver_bucket;
732 return at_most;
735 /** We just read num_read onto conn. Decrement buckets appropriately. */
736 static void connection_read_bucket_decrement(connection_t *conn, int num_read) {
737 global_read_bucket -= num_read; //tor_assert(global_read_bucket >= 0);
738 if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
739 conn->receiver_bucket -= num_read; //tor_assert(conn->receiver_bucket >= 0);
743 static void connection_consider_empty_buckets(connection_t *conn) {
744 if (global_read_bucket <= 0) {
745 log_fn(LOG_DEBUG,"global bucket exhausted. Pausing.");
746 conn->wants_to_read = 1;
747 connection_stop_reading(conn);
748 return;
750 if (connection_speaks_cells(conn) &&
751 conn->state == OR_CONN_STATE_OPEN &&
752 conn->receiver_bucket <= 0) {
753 log_fn(LOG_DEBUG,"receiver bucket exhausted. Pausing.");
754 conn->wants_to_read = 1;
755 connection_stop_reading(conn);
759 /** Initialize the global read bucket to options->BandwidthBurst,
760 * and current_time to the current time. */
761 void connection_bucket_init(void) {
762 or_options_t *options = get_options();
763 global_read_bucket = (int)options->BandwidthBurst; /* start it at max traffic */
764 global_write_bucket = (int)options->BandwidthBurst; /* start it at max traffic */
767 /** A second has rolled over; increment buckets appropriately. */
768 void connection_bucket_refill(struct timeval *now) {
769 int i, n;
770 connection_t *conn;
771 connection_t **carray;
772 or_options_t *options = get_options();
774 /* refill the global buckets */
775 if (global_read_bucket < (int)options->BandwidthBurst) {
776 global_read_bucket += (int)options->BandwidthRate;
777 log_fn(LOG_DEBUG,"global_read_bucket now %d.", global_read_bucket);
779 if (global_write_bucket < (int)options->BandwidthBurst) {
780 global_write_bucket += (int)options->BandwidthRate;
781 log_fn(LOG_DEBUG,"global_write_bucket now %d.", global_write_bucket);
784 /* refill the per-connection buckets */
785 get_connection_array(&carray,&n);
786 for (i=0;i<n;i++) {
787 conn = carray[i];
789 if (connection_receiver_bucket_should_increase(conn)) {
790 conn->receiver_bucket += conn->bandwidth;
791 //log_fn(LOG_DEBUG,"Receiver bucket %d now %d.", i, conn->receiver_bucket);
794 if (conn->wants_to_read == 1 /* it's marked to turn reading back on now */
795 && global_read_bucket > 0 /* and we're allowed to read */
796 && global_write_bucket > 0 /* and we're allowed to write (XXXX,
797 * not the best place to check this.) */
798 && (!connection_speaks_cells(conn) ||
799 conn->state != OR_CONN_STATE_OPEN ||
800 conn->receiver_bucket > 0)) {
801 /* and either a non-cell conn or a cell conn with non-empty bucket */
802 log_fn(LOG_DEBUG,"waking up conn (fd %d)",conn->s);
803 conn->wants_to_read = 0;
804 connection_start_reading(conn);
805 if (conn->wants_to_write == 1) {
806 conn->wants_to_write = 0;
807 connection_start_writing(conn);
813 /** Is the receiver bucket for connection <b>conn</b> low enough that we
814 * should add another pile of tokens to it?
816 static int connection_receiver_bucket_should_increase(connection_t *conn) {
817 tor_assert(conn);
819 if (!connection_speaks_cells(conn))
820 return 0; /* edge connections don't use receiver_buckets */
821 if (conn->state != OR_CONN_STATE_OPEN)
822 return 0; /* only open connections play the rate limiting game */
824 tor_assert(conn->bandwidth > 0);
825 if (conn->receiver_bucket > 9*conn->bandwidth)
826 return 0;
828 return 1;
831 /** Read bytes from conn->\s and process them.
833 * This function gets called from conn_read() in main.c, either
834 * when poll() has declared that conn wants to read, or (for OR conns)
835 * when there are pending TLS bytes.
837 * It calls connection_read_to_buf() to bring in any new bytes,
838 * and then calls connection_process_inbuf() to process them.
840 * Mark the connection and return -1 if you want to close it, else
841 * return 0.
843 int connection_handle_read(connection_t *conn) {
844 int max_to_read=-1, try_to_read;
846 conn->timestamp_lastread = time(NULL);
848 switch (conn->type) {
849 case CONN_TYPE_OR_LISTENER:
850 return connection_handle_listener_read(conn, CONN_TYPE_OR);
851 case CONN_TYPE_AP_LISTENER:
852 return connection_handle_listener_read(conn, CONN_TYPE_AP);
853 case CONN_TYPE_DIR_LISTENER:
854 return connection_handle_listener_read(conn, CONN_TYPE_DIR);
855 case CONN_TYPE_CONTROL_LISTENER:
856 return connection_handle_listener_read(conn, CONN_TYPE_CONTROL);
859 loop_again:
860 try_to_read = max_to_read;
861 tor_assert(!conn->marked_for_close);
862 if (connection_read_to_buf(conn, &max_to_read) < 0) {
863 /* There's a read error; kill the connection.*/
864 connection_close_immediate(conn); /* Don't flush; connection is dead. */
865 if (conn->type == CONN_TYPE_AP || conn->type == CONN_TYPE_EXIT) {
866 connection_edge_end(conn, (char)(connection_state_is_open(conn) ?
867 END_STREAM_REASON_MISC : END_STREAM_REASON_CONNECTFAILED),
868 conn->cpath_layer);
870 connection_mark_for_close(conn);
871 return -1;
873 if (CONN_IS_EDGE(conn) &&
874 try_to_read != max_to_read) {
875 /* instruct it not to try to package partial cells. */
876 if (connection_process_inbuf(conn, 0) < 0) {
877 return -1;
879 if (!conn->marked_for_close &&
880 connection_is_reading(conn) &&
881 !conn->inbuf_reached_eof &&
882 max_to_read > 0)
883 goto loop_again; /* try reading again, in case more is here now */
885 /* one last try, packaging partial cells and all. */
886 if (!conn->marked_for_close &&
887 connection_process_inbuf(conn, 1) < 0) {
888 return -1;
890 if (!conn->marked_for_close &&
891 conn->inbuf_reached_eof &&
892 connection_reached_eof(conn) < 0) {
893 return -1;
895 return 0;
898 /** Pull in new bytes from conn-\>s onto conn-\>inbuf, either
899 * directly or via TLS. Reduce the token buckets by the number of
900 * bytes read.
902 * If *max_to_read is -1, then decide it ourselves, else go with the
903 * value passed to us. When returning, if it's changed, subtract the
904 * number of bytes we read from *max_to_read.
906 * Return -1 if we want to break conn, else return 0.
908 static int connection_read_to_buf(connection_t *conn, int *max_to_read) {
909 int result, at_most = *max_to_read;
911 if (at_most == -1) { /* we need to initialize it */
912 /* how many bytes are we allowed to read? */
913 at_most = connection_bucket_read_limit(conn);
916 if (connection_speaks_cells(conn) && conn->state != OR_CONN_STATE_CONNECTING) {
917 int pending;
918 if (conn->state == OR_CONN_STATE_HANDSHAKING) {
919 /* continue handshaking even if global token bucket is empty */
920 return connection_tls_continue_handshake(conn);
923 log_fn(LOG_DEBUG,"%d: starting, inbuf_datalen %d (%d pending in tls object). at_most %d.",
924 conn->s,(int)buf_datalen(conn->inbuf),tor_tls_get_pending_bytes(conn->tls), at_most);
926 /* else open, or closing */
927 result = read_to_buf_tls(conn->tls, at_most, conn->inbuf);
929 switch (result) {
930 case TOR_TLS_CLOSE:
931 log_fn(LOG_INFO,"TLS connection closed on read. Closing. (Nickname %s, address %s",
932 conn->nickname ? conn->nickname : "not set", conn->address);
933 return -1;
934 case TOR_TLS_ERROR:
935 log_fn(LOG_INFO,"tls error. breaking (nickname %s, address %s).",
936 conn->nickname ? conn->nickname : "not set", conn->address);
937 return -1;
938 case TOR_TLS_WANTWRITE:
939 connection_start_writing(conn);
940 return 0;
941 case TOR_TLS_WANTREAD: /* we're already reading */
942 case TOR_TLS_DONE: /* no data read, so nothing to process */
943 result = 0;
944 break; /* so we call bucket_decrement below */
945 default:
946 break;
948 pending = tor_tls_get_pending_bytes(conn->tls);
949 if (pending) {
950 /* XXXX If we have any pending bytes, read them now. This *can*
951 * take us over our read alotment, but really we shouldn't be
952 * believing that SSL bytes are the same as TCP bytes anyway. */
953 int r2 = read_to_buf_tls(conn->tls, pending, conn->inbuf);
954 if (r2<0) {
955 log_fn(LOG_WARN, "Bug: apparently, reading pending bytes can fail.");
956 return -1;
957 } else {
958 result += r2;
962 } else {
963 result = read_to_buf(conn->s, at_most, conn->inbuf,
964 &conn->inbuf_reached_eof);
966 // log_fn(LOG_DEBUG,"read_to_buf returned %d.",read_result);
968 if (result < 0)
969 return -1;
972 if (result > 0) { /* change *max_to_read */
973 *max_to_read = at_most - result;
976 if (result > 0 && !is_local_IP(conn->addr)) { /* remember it */
977 rep_hist_note_bytes_read(result, time(NULL));
978 connection_read_bucket_decrement(conn, result);
981 /* Call even if result is 0, since the global read bucket may
982 * have reached 0 on a different conn, and this guy needs to
983 * know to stop reading. */
984 connection_consider_empty_buckets(conn);
986 return 0;
989 /** A pass-through to fetch_from_buf. */
990 int connection_fetch_from_buf(char *string, size_t len, connection_t *conn) {
991 return fetch_from_buf(string, len, conn->inbuf);
994 /** Return conn-\>outbuf_flushlen: how many bytes conn wants to flush
995 * from its outbuf. */
996 int connection_wants_to_flush(connection_t *conn) {
997 return conn->outbuf_flushlen;
1000 /** Are there too many bytes on edge connection <b>conn</b>'s outbuf to
1001 * send back a relay-level sendme yet? Return 1 if so, 0 if not. Used by
1002 * connection_edge_consider_sending_sendme().
1004 int connection_outbuf_too_full(connection_t *conn) {
1005 return (conn->outbuf_flushlen > 10*CELL_PAYLOAD_SIZE);
1008 /** Try to flush more bytes onto conn-\>s.
1010 * This function gets called either from conn_write() in main.c
1011 * when poll() has declared that conn wants to write, or below
1012 * from connection_write_to_buf() when an entire TLS record is ready.
1014 * Update conn-\>timestamp_lastwritten to now, and call flush_buf
1015 * or flush_buf_tls appropriately. If it succeeds and there no more
1016 * more bytes on conn->outbuf, then call connection_finished_flushing
1017 * on it too.
1019 * Mark the connection and return -1 if you want to close it, else
1020 * return 0.
1022 int connection_handle_write(connection_t *conn) {
1023 int e, len=sizeof(e);
1024 int result;
1025 time_t now = time(NULL);
1027 tor_assert(!connection_is_listener(conn));
1029 conn->timestamp_lastwritten = now;
1031 /* Sometimes, "writable" means "connected". */
1032 if (connection_state_is_connecting(conn)) {
1033 if (getsockopt(conn->s, SOL_SOCKET, SO_ERROR, (void*)&e, &len) < 0) {
1034 log_fn(LOG_WARN,"getsockopt() syscall failed?! Please report to tor-ops.");
1035 connection_close_immediate(conn);
1036 connection_mark_for_close(conn);
1037 return -1;
1039 if (e) {
1040 /* some sort of error, but maybe just inprogress still */
1041 if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
1042 log_fn(LOG_INFO,"in-progress connect failed. Removing.");
1043 connection_close_immediate(conn);
1044 connection_mark_for_close(conn);
1045 /* it's safe to pass OPs to router_mark_as_down(), since it just
1046 * ignores unrecognized routers
1048 if (conn->type == CONN_TYPE_OR)
1049 router_mark_as_down(conn->identity_digest);
1050 return -1;
1051 } else {
1052 return 0; /* no change, see if next time is better */
1055 /* The connection is successful. */
1056 return connection_finished_connecting(conn);
1059 if (connection_speaks_cells(conn)) {
1060 if (conn->state == OR_CONN_STATE_HANDSHAKING) {
1061 connection_stop_writing(conn);
1062 if (connection_tls_continue_handshake(conn) < 0) {
1063 connection_close_immediate(conn); /* Don't flush; connection is dead. */
1064 connection_mark_for_close(conn);
1065 return -1;
1067 return 0;
1070 /* else open, or closing */
1071 result = flush_buf_tls(conn->tls, conn->outbuf, &conn->outbuf_flushlen);
1072 switch (result) {
1073 case TOR_TLS_ERROR:
1074 case TOR_TLS_CLOSE:
1075 log_fn(LOG_INFO,result==TOR_TLS_ERROR?
1076 "tls error. breaking.":"TLS connection closed on flush");
1077 connection_close_immediate(conn); /* Don't flush; connection is dead. */
1078 connection_mark_for_close(conn);
1079 return -1;
1080 case TOR_TLS_WANTWRITE:
1081 log_fn(LOG_DEBUG,"wanted write.");
1082 /* we're already writing */
1083 return 0;
1084 case TOR_TLS_WANTREAD:
1085 /* Make sure to avoid a loop if the receive buckets are empty. */
1086 log_fn(LOG_DEBUG,"wanted read.");
1087 if (!connection_is_reading(conn)) {
1088 connection_stop_writing(conn);
1089 conn->wants_to_write = 1;
1090 /* we'll start reading again when the next second arrives,
1091 * and then also start writing again.
1094 /* else no problem, we're already reading */
1095 return 0;
1096 /* case TOR_TLS_DONE:
1097 * for TOR_TLS_DONE, fall through to check if the flushlen
1098 * is empty, so we can stop writing.
1101 } else {
1102 result = flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen);
1103 if (result < 0) {
1104 connection_close_immediate(conn); /* Don't flush; connection is dead. */
1105 conn->has_sent_end = 1;
1106 connection_mark_for_close(conn);
1107 return -1;
1111 if (result > 0 && !is_local_IP(conn->addr)) { /* remember it */
1112 rep_hist_note_bytes_written(result, now);
1113 global_write_bucket -= result;
1116 if (!connection_wants_to_flush(conn)) { /* it's done flushing */
1117 if (connection_finished_flushing(conn) < 0) {
1118 /* already marked */
1119 return -1;
1123 return 0;
1126 /** Append <b>len</b> bytes of <b>string</b> onto <b>conn</b>'s
1127 * outbuf, and ask it to start writing.
1129 void connection_write_to_buf(const char *string, size_t len, connection_t *conn) {
1131 if (!len)
1132 return;
1133 /* if it's marked for close, only allow write if we mean to flush it */
1134 if (conn->marked_for_close && !conn->hold_open_until_flushed)
1135 return;
1137 if (write_to_buf(string, len, conn->outbuf) < 0) {
1138 if (conn->type == CONN_TYPE_AP || conn->type == CONN_TYPE_EXIT) {
1139 /* if it failed, it means we have our package/delivery windows set
1140 wrong compared to our max outbuf size. close the whole circuit. */
1141 log_fn(LOG_WARN,"write_to_buf failed. Closing circuit (fd %d).", conn->s);
1142 circuit_mark_for_close(circuit_get_by_conn(conn));
1143 } else {
1144 log_fn(LOG_WARN,"write_to_buf failed. Closing connection (fd %d).", conn->s);
1145 connection_mark_for_close(conn);
1147 return;
1150 connection_start_writing(conn);
1151 conn->outbuf_flushlen += len;
1154 /** Return the conn to addr/port that has the most recent
1155 * timestamp_created, or NULL if no such conn exists. */
1156 connection_t *connection_exact_get_by_addr_port(uint32_t addr, uint16_t port) {
1157 int i, n;
1158 connection_t *conn, *best=NULL;
1159 connection_t **carray;
1161 get_connection_array(&carray,&n);
1162 for (i=0;i<n;i++) {
1163 conn = carray[i];
1164 if (conn->addr == addr && conn->port == port && !conn->marked_for_close &&
1165 (!best || best->timestamp_created < conn->timestamp_created))
1166 best = conn;
1168 return best;
1171 connection_t *connection_get_by_identity_digest(const char *digest, int type)
1173 int i, n;
1174 connection_t *conn, *best=NULL;
1175 connection_t **carray;
1177 get_connection_array(&carray,&n);
1178 for (i=0;i<n;i++) {
1179 conn = carray[i];
1180 if (conn->type != type)
1181 continue;
1182 if (!memcmp(conn->identity_digest, digest, DIGEST_LEN) &&
1183 !conn->marked_for_close &&
1184 (!best || best->timestamp_created < conn->timestamp_created))
1185 best = conn;
1187 return best;
1190 /** Return a connection of type <b>type</b> that is not marked for
1191 * close.
1193 connection_t *connection_get_by_type(int type) {
1194 int i, n;
1195 connection_t *conn;
1196 connection_t **carray;
1198 get_connection_array(&carray,&n);
1199 for (i=0;i<n;i++) {
1200 conn = carray[i];
1201 if (conn->type == type && !conn->marked_for_close)
1202 return conn;
1204 return NULL;
1207 /** Return a connection of type <b>type</b> that is in state <b>state</b>,
1208 * and that is not marked for close.
1210 connection_t *connection_get_by_type_state(int type, int state) {
1211 int i, n;
1212 connection_t *conn;
1213 connection_t **carray;
1215 get_connection_array(&carray,&n);
1216 for (i=0;i<n;i++) {
1217 conn = carray[i];
1218 if (conn->type == type && conn->state == state && !conn->marked_for_close)
1219 return conn;
1221 return NULL;
1224 /** Return the connection of type <b>type</b> that is in state
1225 * <b>state</b>, that was written to least recently, and that is not
1226 * marked for close.
1228 connection_t *connection_get_by_type_state_lastwritten(int type, int state) {
1229 int i, n;
1230 connection_t *conn, *best=NULL;
1231 connection_t **carray;
1233 get_connection_array(&carray,&n);
1234 for (i=0;i<n;i++) {
1235 conn = carray[i];
1236 if (conn->type == type && conn->state == state && !conn->marked_for_close)
1237 if (!best || conn->timestamp_lastwritten < best->timestamp_lastwritten)
1238 best = conn;
1240 return best;
1243 /** Return a connection of type <b>type</b> that has rendquery equal
1244 * to <b>rendquery</b>, and that is not marked for close.
1246 connection_t *connection_get_by_type_rendquery(int type, const char *rendquery) {
1247 int i, n;
1248 connection_t *conn;
1249 connection_t **carray;
1251 get_connection_array(&carray,&n);
1252 for (i=0;i<n;i++) {
1253 conn = carray[i];
1254 if (conn->type == type &&
1255 !conn->marked_for_close &&
1256 !rend_cmp_service_ids(rendquery, conn->rend_query))
1257 return conn;
1259 return NULL;
1262 /** Return 1 if <b>conn</b> is a listener conn, else return 0. */
1263 int connection_is_listener(connection_t *conn) {
1264 if (conn->type == CONN_TYPE_OR_LISTENER ||
1265 conn->type == CONN_TYPE_AP_LISTENER ||
1266 conn->type == CONN_TYPE_DIR_LISTENER ||
1267 conn->type == CONN_TYPE_CONTROL_LISTENER)
1268 return 1;
1269 return 0;
1272 /** Return 1 if <b>conn</b> is in state "open" and is not marked
1273 * for close, else return 0.
1275 int connection_state_is_open(connection_t *conn) {
1276 tor_assert(conn);
1278 if (conn->marked_for_close)
1279 return 0;
1281 if ((conn->type == CONN_TYPE_OR && conn->state == OR_CONN_STATE_OPEN) ||
1282 (conn->type == CONN_TYPE_AP && conn->state == AP_CONN_STATE_OPEN) ||
1283 (conn->type == CONN_TYPE_EXIT && conn->state == EXIT_CONN_STATE_OPEN) ||
1284 (conn->type == CONN_TYPE_CONTROL && conn->state ==CONTROL_CONN_STATE_OPEN))
1285 return 1;
1287 return 0;
1290 /** Return 1 if conn is in 'connecting' state, else return 0. */
1291 int connection_state_is_connecting(connection_t *conn) {
1292 tor_assert(conn);
1294 if (conn->marked_for_close)
1295 return 0;
1296 switch (conn->type)
1298 case CONN_TYPE_OR:
1299 return conn->state == OR_CONN_STATE_CONNECTING;
1300 case CONN_TYPE_EXIT:
1301 return conn->state == EXIT_CONN_STATE_CONNECTING;
1302 case CONN_TYPE_DIR:
1303 return conn->state == DIR_CONN_STATE_CONNECTING;
1306 return 0;
1309 /** Write a destroy cell with circ ID <b>circ_id</b> onto OR connection
1310 * <b>conn</b>.
1312 * Return 0.
1314 int connection_send_destroy(uint16_t circ_id, connection_t *conn) {
1315 cell_t cell;
1317 tor_assert(conn);
1318 tor_assert(connection_speaks_cells(conn));
1320 memset(&cell, 0, sizeof(cell_t));
1321 cell.circ_id = circ_id;
1322 cell.command = CELL_DESTROY;
1323 log_fn(LOG_INFO,"Sending destroy (circID %d).", circ_id);
1324 connection_or_write_cell_to_buf(&cell, conn);
1325 return 0;
1328 /** Process new bytes that have arrived on conn-\>inbuf.
1330 * This function just passes conn to the connection-specific
1331 * connection_*_process_inbuf() function. It also passes in
1332 * package_partial if wanted.
1334 static int connection_process_inbuf(connection_t *conn, int package_partial) {
1336 tor_assert(conn);
1338 switch (conn->type) {
1339 case CONN_TYPE_OR:
1340 return connection_or_process_inbuf(conn);
1341 case CONN_TYPE_EXIT:
1342 case CONN_TYPE_AP:
1343 return connection_edge_process_inbuf(conn, package_partial);
1344 case CONN_TYPE_DIR:
1345 return connection_dir_process_inbuf(conn);
1346 case CONN_TYPE_DNSWORKER:
1347 return connection_dns_process_inbuf(conn);
1348 case CONN_TYPE_CPUWORKER:
1349 return connection_cpu_process_inbuf(conn);
1350 case CONN_TYPE_CONTROL:
1351 return connection_control_process_inbuf(conn);
1352 default:
1353 log_fn(LOG_WARN,"Bug: got unexpected conn type %d.", conn->type);
1354 return -1;
1358 /** We just finished flushing bytes from conn-\>outbuf, and there
1359 * are no more bytes remaining.
1361 * This function just passes conn to the connection-specific
1362 * connection_*_finished_flushing() function.
1364 static int connection_finished_flushing(connection_t *conn) {
1366 tor_assert(conn);
1368 // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
1370 switch (conn->type) {
1371 case CONN_TYPE_OR:
1372 return connection_or_finished_flushing(conn);
1373 case CONN_TYPE_AP:
1374 case CONN_TYPE_EXIT:
1375 return connection_edge_finished_flushing(conn);
1376 case CONN_TYPE_DIR:
1377 return connection_dir_finished_flushing(conn);
1378 case CONN_TYPE_DNSWORKER:
1379 return connection_dns_finished_flushing(conn);
1380 case CONN_TYPE_CPUWORKER:
1381 return connection_cpu_finished_flushing(conn);
1382 case CONN_TYPE_CONTROL:
1383 return connection_control_finished_flushing(conn);
1384 default:
1385 log_fn(LOG_WARN,"Bug: got unexpected conn type %d.", conn->type);
1386 return -1;
1390 /** Called when our attempt to connect() to another server has just
1391 * succeeded.
1393 * This function just passes conn to the connection-specific
1394 * connection_*_finished_connecting() function.
1396 static int connection_finished_connecting(connection_t *conn)
1398 tor_assert(conn);
1399 switch (conn->type)
1401 case CONN_TYPE_OR:
1402 return connection_or_finished_connecting(conn);
1403 case CONN_TYPE_EXIT:
1404 return connection_edge_finished_connecting(conn);
1405 case CONN_TYPE_DIR:
1406 return connection_dir_finished_connecting(conn);
1407 default:
1408 log_fn(LOG_WARN,"Bug: got unexpected conn type %d.", conn->type);
1409 return -1;
1413 static int connection_reached_eof(connection_t *conn)
1415 switch (conn->type) {
1416 case CONN_TYPE_OR:
1417 return connection_or_reached_eof(conn);
1418 case CONN_TYPE_AP:
1419 case CONN_TYPE_EXIT:
1420 return connection_edge_reached_eof(conn);
1421 case CONN_TYPE_DIR:
1422 return connection_dir_reached_eof(conn);
1423 case CONN_TYPE_DNSWORKER:
1424 return connection_dns_reached_eof(conn);
1425 case CONN_TYPE_CPUWORKER:
1426 return connection_cpu_reached_eof(conn);
1427 case CONN_TYPE_CONTROL:
1428 return connection_control_reached_eof(conn);
1429 default:
1430 log_fn(LOG_WARN,"Bug: got unexpected conn type %d.", conn->type);
1431 return -1;
1435 /** Verify that connection <b>conn</b> has all of its invariants
1436 * correct. Trigger an assert if anything is invalid.
1438 void assert_connection_ok(connection_t *conn, time_t now)
1440 tor_assert(conn);
1441 tor_assert(conn->magic == CONNECTION_MAGIC);
1442 tor_assert(conn->type >= _CONN_TYPE_MIN);
1443 tor_assert(conn->type <= _CONN_TYPE_MAX);
1445 if (conn->outbuf_flushlen > 0) {
1446 tor_assert(connection_is_writing(conn) || conn->wants_to_write);
1449 if (conn->hold_open_until_flushed)
1450 tor_assert(conn->marked_for_close);
1452 /* XXX check: wants_to_read, wants_to_write, s, poll_index,
1453 * marked_for_close. */
1455 /* buffers */
1456 if (!connection_is_listener(conn)) {
1457 assert_buf_ok(conn->inbuf);
1458 assert_buf_ok(conn->outbuf);
1461 #if 0 /* computers often go back in time; no way to know */
1462 tor_assert(!now || conn->timestamp_lastread <= now);
1463 tor_assert(!now || conn->timestamp_lastwritten <= now);
1464 tor_assert(conn->timestamp_created <= conn->timestamp_lastread);
1465 tor_assert(conn->timestamp_created <= conn->timestamp_lastwritten);
1466 #endif
1468 /* XXX Fix this; no longer so.*/
1469 #if 0
1470 if (conn->type != CONN_TYPE_OR && conn->type != CONN_TYPE_DIR)
1471 tor_assert(!conn->pkey);
1472 /* pkey is set if we're a dir client, or if we're an OR in state OPEN
1473 * connected to another OR.
1475 #endif
1477 if (conn->type != CONN_TYPE_OR) {
1478 tor_assert(!conn->tls);
1479 } else {
1480 if (conn->state == OR_CONN_STATE_OPEN) {
1481 /* tor_assert(conn->bandwidth > 0); */
1482 /* the above isn't necessarily true: if we just did a TLS
1483 * handshake but we didn't recognize the other peer, or it
1484 * gave a bad cert/etc, then we won't have assigned bandwidth,
1485 * yet it will be open. -RD
1487 // tor_assert(conn->receiver_bucket >= 0);
1489 tor_assert(conn->addr && conn->port);
1490 tor_assert(conn->address);
1491 if (conn->state != OR_CONN_STATE_CONNECTING)
1492 tor_assert(conn->tls);
1495 if (conn->type != CONN_TYPE_EXIT && conn->type != CONN_TYPE_AP) {
1496 tor_assert(!conn->stream_id);
1497 tor_assert(!conn->next_stream);
1498 tor_assert(!conn->cpath_layer);
1499 tor_assert(!conn->package_window);
1500 tor_assert(!conn->deliver_window);
1501 tor_assert(!conn->done_sending);
1502 tor_assert(!conn->done_receiving);
1503 } else {
1504 /* XXX unchecked: package window, deliver window. */
1506 if (conn->type == CONN_TYPE_AP) {
1507 tor_assert(conn->socks_request);
1508 if (conn->state == AP_CONN_STATE_OPEN) {
1509 tor_assert(conn->socks_request->has_finished);
1510 tor_assert(conn->cpath_layer);
1511 assert_cpath_layer_ok(conn->cpath_layer);
1513 } else {
1514 tor_assert(!conn->socks_request);
1516 if (conn->type == CONN_TYPE_EXIT) {
1517 tor_assert(conn->purpose == EXIT_PURPOSE_CONNECT ||
1518 conn->purpose == EXIT_PURPOSE_RESOLVE);
1519 } else if (conn->type != CONN_TYPE_DIR) {
1520 tor_assert(!conn->purpose); /* only used for dir types currently */
1523 switch (conn->type)
1525 case CONN_TYPE_OR_LISTENER:
1526 case CONN_TYPE_AP_LISTENER:
1527 case CONN_TYPE_DIR_LISTENER:
1528 case CONN_TYPE_CONTROL_LISTENER:
1529 tor_assert(conn->state == LISTENER_STATE_READY);
1530 break;
1531 case CONN_TYPE_OR:
1532 tor_assert(conn->state >= _OR_CONN_STATE_MIN);
1533 tor_assert(conn->state <= _OR_CONN_STATE_MAX);
1534 break;
1535 case CONN_TYPE_EXIT:
1536 tor_assert(conn->state >= _EXIT_CONN_STATE_MIN);
1537 tor_assert(conn->state <= _EXIT_CONN_STATE_MAX);
1538 break;
1539 case CONN_TYPE_AP:
1540 tor_assert(conn->state >= _AP_CONN_STATE_MIN);
1541 tor_assert(conn->state <= _AP_CONN_STATE_MAX);
1542 tor_assert(conn->socks_request);
1543 break;
1544 case CONN_TYPE_DIR:
1545 tor_assert(conn->state >= _DIR_CONN_STATE_MIN);
1546 tor_assert(conn->state <= _DIR_CONN_STATE_MAX);
1547 tor_assert(conn->purpose >= _DIR_PURPOSE_MIN);
1548 tor_assert(conn->purpose <= _DIR_PURPOSE_MAX);
1549 break;
1550 case CONN_TYPE_DNSWORKER:
1551 tor_assert(conn->state == DNSWORKER_STATE_IDLE ||
1552 conn->state == DNSWORKER_STATE_BUSY);
1553 break;
1554 case CONN_TYPE_CPUWORKER:
1555 tor_assert(conn->state >= _CPUWORKER_STATE_MIN);
1556 tor_assert(conn->state <= _CPUWORKER_STATE_MAX);
1557 break;
1558 case CONN_TYPE_CONTROL:
1559 tor_assert(conn->state >= _CONTROL_CONN_STATE_MIN);
1560 tor_assert(conn->state <= _CONTROL_CONN_STATE_MAX);
1561 break;
1562 default:
1563 tor_assert(0);