fix the latest bug: don't explode when some router declares a
[tor.git] / src / or / connection.c
blobcf42edba81c8a8f3ec884dfb8ebd8f07fa107a76
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 static void
144 _connection_free(connection_t *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 /** Make sure <b>conn</b> isn't in any of the global conn lists; then free it.
184 void connection_free(connection_t *conn) {
185 tor_assert(conn);
186 tor_assert(!connection_is_on_closeable_list(conn));
187 tor_assert(!connection_in_array(conn));
188 _connection_free(conn);
191 /** Call _connection_free() on every connection in our array.
192 * This is used by cpuworkers and dnsworkers when they fork,
193 * so they don't keep resources held open (especially sockets).
195 * Don't do the checks in connection_free(), because they will
196 * fail.
198 void connection_free_all(void) {
199 int i, n;
200 connection_t **carray;
202 get_connection_array(&carray,&n);
203 for (i=0;i<n;i++)
204 _connection_free(carray[i]);
207 /** Do any cleanup needed:
208 * - Directory conns that failed to fetch a rendezvous descriptor
209 * need to inform pending rendezvous streams.
210 * - OR conns need to call rep_hist_note_*() to record status.
211 * - AP conns need to send a socks reject if necessary.
212 * - Exit conns need to call connection_dns_remove() if necessary.
213 * - AP and Exit conns need to send an end cell if they can.
214 * - DNS conns need to fail any resolves that are pending on them.
216 void connection_about_to_close_connection(connection_t *conn)
218 circuit_t *circ;
220 assert(conn->marked_for_close);
222 if (conn->type == CONN_TYPE_AP || conn->type == CONN_TYPE_EXIT) {
223 if (!conn->has_sent_end) {
224 log_fn(LOG_WARN,"Bug: Edge connection hasn't sent end yet?");
225 #ifdef TOR_FRAGILE
226 tor_assert(0);
227 #endif
231 switch (conn->type) {
232 case CONN_TYPE_DIR:
233 if (conn->state == DIR_CONN_STATE_CONNECTING) {
234 /* it's a directory server and connecting failed: forget about
235 this router */
236 connection_dir_connect_failed(conn);
238 if (conn->purpose == DIR_PURPOSE_FETCH_RENDDESC)
239 rend_client_desc_here(conn->rend_query); /* give it a try */
240 break;
241 case CONN_TYPE_OR:
242 /* Remember why we're closing this connection. */
243 if (conn->state != OR_CONN_STATE_OPEN) {
244 if (connection_or_nonopen_was_started_here(conn)) {
245 rep_hist_note_connect_failed(conn->identity_digest, time(NULL));
246 control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED);
248 } else if (conn->hold_open_until_flushed) {
249 /* XXXX009 We used to have an arg that told us whether we closed the
250 * connection on purpose or not. Can we use hold_open_until_flushed
251 * instead? We only set it when we are intentionally closing a
252 * connection. -NM
254 * (Of course, now things we set to close which expire rather than
255 * flushing still get noted as dead, not disconnected. But this is an
256 * improvement. -NM
258 rep_hist_note_disconnect(conn->identity_digest, time(NULL));
259 control_event_or_conn_status(conn, OR_CONN_EVENT_CLOSED);
260 } else if (conn->identity_digest) {
261 rep_hist_note_connection_died(conn->identity_digest, time(NULL));
262 control_event_or_conn_status(conn, OR_CONN_EVENT_CLOSED);
264 break;
265 case CONN_TYPE_AP:
266 if (conn->socks_request->has_finished == 0) {
267 log_fn(LOG_INFO,"Cleaning up AP -- sending socks reject.");
268 conn->hold_open_until_flushed = 1;
269 /* XXX this socks_reply never gets sent, since conn
270 * gets removed right after this function finishes. */
271 connection_ap_handshake_socks_reply(conn, NULL, 0, -1);
272 conn->socks_request->has_finished = 1;
273 } else {
274 control_event_stream_status(conn, STREAM_EVENT_CLOSED);
276 break;
277 case CONN_TYPE_EXIT:
278 if (conn->state == EXIT_CONN_STATE_RESOLVING) {
279 circ = circuit_get_by_conn(conn);
280 if (circ)
281 circuit_detach_stream(circ, conn);
282 connection_dns_remove(conn);
284 break;
285 case CONN_TYPE_DNSWORKER:
286 if (conn->state == DNSWORKER_STATE_BUSY) {
287 dns_cancel_pending_resolve(conn->address);
289 break;
293 /** Close the underlying socket for <b>conn</b>, so we don't try to
294 * flush it. Must be used in conjunction with (right before)
295 * connection_mark_for_close().
297 void connection_close_immediate(connection_t *conn)
299 assert_connection_ok(conn,0);
300 if (conn->s < 0) {
301 log_fn(LOG_WARN,"Bug: Attempt to close already-closed connection.");
302 #ifdef TOR_FRAGILE
303 tor_assert(0);
304 #endif
305 return;
307 if (conn->outbuf_flushlen) {
308 log_fn(LOG_INFO,"fd %d, type %s, state %d, %d bytes on outbuf.",
309 conn->s, CONN_TYPE_TO_STRING(conn->type),
310 conn->state, (int)conn->outbuf_flushlen);
312 tor_close_socket(conn->s);
313 conn->s = -1;
314 if (!connection_is_listener(conn)) {
315 buf_clear(conn->outbuf);
316 conn->outbuf_flushlen = 0;
320 /** Mark <b>conn</b> to be closed next time we loop through
321 * conn_close_if_marked() in main.c. */
323 _connection_mark_for_close(connection_t *conn)
325 assert_connection_ok(conn,0);
327 if (conn->marked_for_close) {
328 log(LOG_WARN, "Bug: Double mark-for-close on connection.");
329 #ifdef TOR_FRAGILE
330 tor_assert(0);
331 #endif
332 return -1;
335 conn->marked_for_close = 1;
336 add_connection_to_closeable_list(conn);
338 /* in case we're going to be held-open-til-flushed, reset
339 * the number of seconds since last successful write, so
340 * we get our whole 15 seconds */
341 conn->timestamp_lastwritten = time(NULL);
343 return 0;
346 /** Find each connection that has hold_open_until_flushed set to
347 * 1 but hasn't written in the past 15 seconds, and set
348 * hold_open_until_flushed to 0. This means it will get cleaned
349 * up in the next loop through close_if_marked() in main.c.
351 void connection_expire_held_open(void)
353 connection_t **carray, *conn;
354 int n, i;
355 time_t now;
357 now = time(NULL);
359 get_connection_array(&carray, &n);
360 for (i = 0; i < n; ++i) {
361 conn = carray[i];
362 /* If we've been holding the connection open, but we haven't written
363 * for 15 seconds...
365 if (conn->hold_open_until_flushed) {
366 tor_assert(conn->marked_for_close);
367 if (now - conn->timestamp_lastwritten >= 15) {
368 log_fn(LOG_NOTICE,"Giving up on marked_for_close conn that's been flushing for 15s (fd %d, type %s, state %d).",
369 conn->s, CONN_TYPE_TO_STRING(conn->type), conn->state);
370 conn->hold_open_until_flushed = 0;
376 /** Bind a new non-blocking socket listening to
377 * <b>bindaddress</b>:<b>bindport</b>, and add this new connection
378 * (of type <b>type</b>) to the connection array.
380 * If <b>bindaddress</b> includes a port, we bind on that port; otherwise, we
381 * use bindport.
383 static int connection_create_listener(const char *bindaddress, uint16_t bindport, int type) {
384 struct sockaddr_in bindaddr; /* where to bind */
385 connection_t *conn;
386 uint16_t usePort;
387 uint32_t addr;
388 int s; /* the socket we're going to make */
389 int one=1;
391 memset(&bindaddr,0,sizeof(struct sockaddr_in));
392 if (parse_addr_port(bindaddress, NULL, &addr, &usePort)<0) {
393 log_fn(LOG_WARN, "Error parsing/resolving BindAddress %s",bindaddress);
394 return -1;
397 if (usePort==0)
398 usePort = bindport;
399 bindaddr.sin_addr.s_addr = htonl(addr);
400 bindaddr.sin_family = AF_INET;
401 bindaddr.sin_port = htons((uint16_t) usePort);
403 s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
404 if (s < 0) {
405 log_fn(LOG_WARN,"Socket creation failed.");
406 return -1;
407 } else if (!SOCKET_IS_POLLABLE(s)) {
408 log_fn(LOG_WARN,"Too many connections; can't create pollable listener.");
409 tor_close_socket(s);
410 return -1;
413 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*) &one, sizeof(one));
415 if (bind(s,(struct sockaddr *)&bindaddr,sizeof(bindaddr)) < 0) {
416 log_fn(LOG_WARN,"Could not bind to port %u: %s",usePort,
417 tor_socket_strerror(tor_socket_errno(s)));
418 return -1;
421 if (listen(s,SOMAXCONN) < 0) {
422 log_fn(LOG_WARN,"Could not listen on port %u: %s",usePort,
423 tor_socket_strerror(tor_socket_errno(s)));
424 return -1;
427 set_socket_nonblocking(s);
429 conn = connection_new(type);
430 conn->s = s;
432 if (connection_add(conn) < 0) { /* no space, forget it */
433 log_fn(LOG_WARN,"connection_add failed. Giving up.");
434 connection_free(conn);
435 return -1;
438 log_fn(LOG_DEBUG,"%s listening on port %u.",conn_type_to_string[type], usePort);
440 conn->state = LISTENER_STATE_READY;
441 connection_start_reading(conn);
443 return 0;
446 /** The listener connection <b>conn</b> told poll() it wanted to read.
447 * Call accept() on conn-\>s, and add the new connection if necessary.
449 static int connection_handle_listener_read(connection_t *conn, int new_type) {
450 int news; /* the new socket */
451 connection_t *newconn;
452 /* information about the remote peer when connecting to other routers */
453 struct sockaddr_in remote;
454 /* length of the remote address. Must be an int, since accept() needs that. */
455 int remotelen = sizeof(struct sockaddr_in);
457 news = accept(conn->s,(struct sockaddr *)&remote,&remotelen);
458 if (!SOCKET_IS_POLLABLE(news)) {
459 /* accept() error, or too many conns to poll */
460 int e;
461 if (news>=0) {
462 /* Too many conns to poll. */
463 log_fn(LOG_WARN,"Too many connections; couldn't accept connection.");
464 tor_close_socket(news);
465 return 0;
467 e = tor_socket_errno(conn->s);
468 if (ERRNO_IS_ACCEPT_EAGAIN(e)) {
469 return 0; /* he hung up before we could accept(). that's fine. */
470 } else if (ERRNO_IS_ACCEPT_RESOURCE_LIMIT(e)) {
471 log_fn(LOG_NOTICE,"accept failed: %s. Dropping incoming connection.",
472 tor_socket_strerror(e));
473 return 0;
475 /* else there was a real error. */
476 log_fn(LOG_WARN,"accept() failed: %s. Closing listener.",
477 tor_socket_strerror(e));
478 connection_mark_for_close(conn);
479 return -1;
481 log(LOG_INFO,"Connection accepted on socket %d (child of fd %d).",news, conn->s);
483 set_socket_nonblocking(news);
485 /* process entrance policies here, before we even create the connection */
486 if (new_type == CONN_TYPE_AP) {
487 /* check sockspolicy to see if we should accept it */
488 if (socks_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
489 log_fn(LOG_NOTICE,"Denying socks connection from untrusted address %s.",
490 inet_ntoa(remote.sin_addr));
491 tor_close_socket(news);
492 return 0;
495 if (new_type == CONN_TYPE_DIR) {
496 /* check dirpolicy to see if we should accept it */
497 if (dir_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
498 log_fn(LOG_NOTICE,"Denying dir connection from address %s.",
499 inet_ntoa(remote.sin_addr));
500 tor_close_socket(news);
501 return 0;
505 newconn = connection_new(new_type);
506 newconn->s = news;
508 newconn->address = tor_strdup(inet_ntoa(remote.sin_addr)); /* remember the remote address */
509 newconn->addr = ntohl(remote.sin_addr.s_addr);
510 newconn->port = ntohs(remote.sin_port);
512 if (connection_add(newconn) < 0) { /* no space, forget it */
513 connection_free(newconn);
514 return 0; /* no need to tear down the parent */
517 if (connection_init_accepted_conn(newconn) < 0) {
518 connection_mark_for_close(newconn);
519 return 0;
521 return 0;
524 /** Initialize states for newly accepted connection <b>conn</b>.
525 * If conn is an OR, start the tls handshake.
527 static int connection_init_accepted_conn(connection_t *conn) {
529 connection_start_reading(conn);
531 switch (conn->type) {
532 case CONN_TYPE_OR:
533 return connection_tls_start_handshake(conn, 1);
534 case CONN_TYPE_AP:
535 conn->state = AP_CONN_STATE_SOCKS_WAIT;
536 break;
537 case CONN_TYPE_DIR:
538 conn->purpose = DIR_PURPOSE_SERVER;
539 conn->state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
540 break;
541 case CONN_TYPE_CONTROL:
542 conn->state = CONTROL_CONN_STATE_NEEDAUTH;
543 break;
545 return 0;
548 /** Take conn, make a nonblocking socket; try to connect to
549 * addr:port (they arrive in *host order*). If fail, return -1. Else
550 * assign s to conn->\s: if connected return 1, if EAGAIN return 0.
552 * address is used to make the logs useful.
554 * On success, add conn to the list of polled connections.
556 int connection_connect(connection_t *conn, char *address, uint32_t addr, uint16_t port) {
557 int s;
558 struct sockaddr_in dest_addr;
559 or_options_t *options = get_options();
561 s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
562 if (s < 0) {
563 log_fn(LOG_WARN,"Error creating network socket: %s",
564 tor_socket_strerror(tor_socket_errno(-1)));
565 return -1;
566 } else if (!SOCKET_IS_POLLABLE(s)) {
567 log_fn(LOG_WARN,
568 "Too many connections; can't create pollable connection to %s", address);
569 tor_close_socket(s);
570 return -1;
573 if (options->OutboundBindAddress) {
574 struct sockaddr_in ext_addr;
576 memset(&ext_addr, 0, sizeof(ext_addr));
577 ext_addr.sin_family = AF_INET;
578 ext_addr.sin_port = 0;
579 if (!tor_inet_aton(options->OutboundBindAddress, &ext_addr.sin_addr)) {
580 log_fn(LOG_WARN,"Outbound bind address '%s' didn't parse. Ignoring.",
581 options->OutboundBindAddress);
582 } else {
583 if (bind(s, (struct sockaddr*)&ext_addr, sizeof(ext_addr)) < 0) {
584 log_fn(LOG_WARN,"Error binding network socket: %s",
585 tor_socket_strerror(tor_socket_errno(s)));
586 return -1;
591 set_socket_nonblocking(s);
593 memset(&dest_addr,0,sizeof(dest_addr));
594 dest_addr.sin_family = AF_INET;
595 dest_addr.sin_port = htons(port);
596 dest_addr.sin_addr.s_addr = htonl(addr);
598 log_fn(LOG_DEBUG,"Connecting to %s:%u.",address,port);
600 if (connect(s,(struct sockaddr *)&dest_addr,sizeof(dest_addr)) < 0) {
601 int e = tor_socket_errno(s);
602 if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
603 /* yuck. kill it. */
604 log_fn(LOG_INFO,"Connect() to %s:%u failed: %s",address,port,
605 tor_socket_strerror(e));
606 tor_close_socket(s);
607 return -1;
608 } else {
609 /* it's in progress. set state appropriately and return. */
610 conn->s = s;
611 if (connection_add(conn) < 0) /* no space, forget it */
612 return -1;
613 log_fn(LOG_DEBUG,"connect in progress, socket %d.",s);
614 return 0;
618 /* it succeeded. we're connected. */
619 log_fn(LOG_INFO,"Connection to %s:%u established.",address,port);
620 conn->s = s;
621 if (connection_add(conn) < 0) /* no space, forget it */
622 return -1;
623 return 1;
626 /** If there exist any listeners of type <b>type</b> in the connection
627 * array, mark them for close.
629 static void listener_close_if_present(int type) {
630 connection_t *conn;
631 connection_t **carray;
632 int i,n;
633 tor_assert(type == CONN_TYPE_OR_LISTENER ||
634 type == CONN_TYPE_AP_LISTENER ||
635 type == CONN_TYPE_DIR_LISTENER ||
636 type == CONN_TYPE_CONTROL_LISTENER);
637 get_connection_array(&carray,&n);
638 for (i=0;i<n;i++) {
639 conn = carray[i];
640 if (conn->type == type && !conn->marked_for_close) {
641 connection_close_immediate(conn);
642 connection_mark_for_close(conn);
648 * Launch any configured listener connections of type <b>type</b>. (A
649 * listener is configured if <b>port_option</b> is non-zero. If any
650 * BindAddress configuration options are given in <b>cfg</b>, create a
651 * connection binding to each one. Otherwise, create a single
652 * connection binding to the address <b>default_addr</b>.)
654 * If <b>force</b> is true, close and re-open all listener connections.
655 * Otherwise, only relaunch the listeners of this type if the number of
656 * existing connections is not as configured (e.g., because one died).
658 static int retry_listeners(int type, struct config_line_t *cfg,
659 int port_option, const char *default_addr,
660 int force)
662 if (!force) {
663 int want, have, n_conn, i;
664 struct config_line_t *c;
665 connection_t *conn;
666 connection_t **carray;
667 /* How many should there be? */
668 if (cfg && port_option) {
669 want = 0;
670 for (c = cfg; c; c = c->next)
671 ++want;
672 } else if (port_option) {
673 want = 1;
674 } else {
675 want = 0;
678 /* How many are there actually? */
679 have = 0;
680 get_connection_array(&carray,&n_conn);
681 for (i=0;i<n_conn;i++) {
682 conn = carray[i];
683 if (conn->type == type && !conn->marked_for_close)
684 ++have;
687 /* If we have the right number of listeners, do nothing. */
688 if (have == want)
689 return 0;
691 /* Otherwise, warn the user and relaunch. */
692 log_fn(LOG_NOTICE,"We have %d %s(s) open, but we want %d; relaunching.",
693 have, conn_type_to_string[type], want);
696 listener_close_if_present(type);
697 if (port_option) {
698 if (!cfg) {
699 if (connection_create_listener(default_addr, (uint16_t) port_option,
700 type)<0)
701 return -1;
702 } else {
703 for ( ; cfg; cfg = cfg->next) {
704 if (connection_create_listener(cfg->value, (uint16_t) port_option,
705 type)<0)
706 return -1;
710 return 0;
713 /** (Re)launch listeners for each port you should have open. If
714 * <b>force</b> is true, close and relaunch all listeners. If <b>force</b>
715 * is false, then only relaunch listeners when we have the wrong number of
716 * connections for a given type.
718 int retry_all_listeners(int force) {
719 or_options_t *options = get_options();
721 if (retry_listeners(CONN_TYPE_OR_LISTENER, options->ORBindAddress,
722 options->ORPort, "0.0.0.0", force)<0)
723 return -1;
724 if (retry_listeners(CONN_TYPE_DIR_LISTENER, options->DirBindAddress,
725 options->DirPort, "0.0.0.0", force)<0)
726 return -1;
727 if (retry_listeners(CONN_TYPE_AP_LISTENER, options->SocksBindAddress,
728 options->SocksPort, "127.0.0.1", force)<0)
729 return -1;
730 if (retry_listeners(CONN_TYPE_CONTROL_LISTENER, NULL,
731 options->ControlPort, "127.0.0.1", force)<0)
732 return -1;
734 return 0;
737 extern int global_read_bucket, global_write_bucket;
739 /** How many bytes at most can we read onto this connection? */
740 static int connection_bucket_read_limit(connection_t *conn) {
741 int at_most;
743 /* do a rudimentary round-robin so one circuit can't hog a connection */
744 if (connection_speaks_cells(conn)) {
745 at_most = 32*(CELL_NETWORK_SIZE);
746 } else {
747 at_most = 32*(RELAY_PAYLOAD_SIZE);
750 if (at_most > global_read_bucket)
751 at_most = global_read_bucket;
753 if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN)
754 if (at_most > conn->receiver_bucket)
755 at_most = conn->receiver_bucket;
757 if (at_most < 0)
758 return 0;
759 return at_most;
762 /** We just read num_read onto conn. Decrement buckets appropriately. */
763 static void connection_read_bucket_decrement(connection_t *conn, int num_read) {
764 global_read_bucket -= num_read; //tor_assert(global_read_bucket >= 0);
765 if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
766 conn->receiver_bucket -= num_read; //tor_assert(conn->receiver_bucket >= 0);
770 static void connection_consider_empty_buckets(connection_t *conn) {
771 if (global_read_bucket <= 0) {
772 log_fn(LOG_DEBUG,"global bucket exhausted. Pausing.");
773 conn->wants_to_read = 1;
774 connection_stop_reading(conn);
775 return;
777 if (connection_speaks_cells(conn) &&
778 conn->state == OR_CONN_STATE_OPEN &&
779 conn->receiver_bucket <= 0) {
780 log_fn(LOG_DEBUG,"receiver bucket exhausted. Pausing.");
781 conn->wants_to_read = 1;
782 connection_stop_reading(conn);
786 /** Initialize the global read bucket to options->BandwidthBurst,
787 * and current_time to the current time. */
788 void connection_bucket_init(void) {
789 or_options_t *options = get_options();
790 global_read_bucket = (int)options->BandwidthBurst; /* start it at max traffic */
791 global_write_bucket = (int)options->BandwidthBurst; /* start it at max traffic */
794 /** A second has rolled over; increment buckets appropriately. */
795 void connection_bucket_refill(struct timeval *now) {
796 int i, n;
797 connection_t *conn;
798 connection_t **carray;
799 or_options_t *options = get_options();
801 /* refill the global buckets */
802 if (global_read_bucket < (int)options->BandwidthBurst) {
803 global_read_bucket += (int)options->BandwidthRate;
804 log_fn(LOG_DEBUG,"global_read_bucket now %d.", global_read_bucket);
806 if (global_write_bucket < (int)options->BandwidthBurst) {
807 global_write_bucket += (int)options->BandwidthRate;
808 log_fn(LOG_DEBUG,"global_write_bucket now %d.", global_write_bucket);
811 /* refill the per-connection buckets */
812 get_connection_array(&carray,&n);
813 for (i=0;i<n;i++) {
814 conn = carray[i];
816 if (connection_receiver_bucket_should_increase(conn)) {
817 conn->receiver_bucket = conn->bandwidth;
818 //log_fn(LOG_DEBUG,"Receiver bucket %d now %d.", i, conn->receiver_bucket);
821 if (conn->wants_to_read == 1 /* it's marked to turn reading back on now */
822 && global_read_bucket > 0 /* and we're allowed to read */
823 && global_write_bucket > 0 /* and we're allowed to write (XXXX,
824 * not the best place to check this.) */
825 && (!connection_speaks_cells(conn) ||
826 conn->state != OR_CONN_STATE_OPEN ||
827 conn->receiver_bucket > 0)) {
828 /* and either a non-cell conn or a cell conn with non-empty bucket */
829 log_fn(LOG_DEBUG,"waking up conn (fd %d)",conn->s);
830 conn->wants_to_read = 0;
831 connection_start_reading(conn);
832 if (conn->wants_to_write == 1) {
833 conn->wants_to_write = 0;
834 connection_start_writing(conn);
840 /** Is the receiver bucket for connection <b>conn</b> low enough that we
841 * should add another pile of tokens to it?
843 static int connection_receiver_bucket_should_increase(connection_t *conn) {
844 tor_assert(conn);
846 if (!connection_speaks_cells(conn))
847 return 0; /* edge connections don't use receiver_buckets */
848 if (conn->state != OR_CONN_STATE_OPEN)
849 return 0; /* only open connections play the rate limiting game */
851 if (conn->receiver_bucket >= conn->bandwidth)
852 return 0;
854 return 1;
857 /** Read bytes from conn->\s and process them.
859 * This function gets called from conn_read() in main.c, either
860 * when poll() has declared that conn wants to read, or (for OR conns)
861 * when there are pending TLS bytes.
863 * It calls connection_read_to_buf() to bring in any new bytes,
864 * and then calls connection_process_inbuf() to process them.
866 * Mark the connection and return -1 if you want to close it, else
867 * return 0.
869 int connection_handle_read(connection_t *conn) {
870 int max_to_read=-1, try_to_read;
872 conn->timestamp_lastread = time(NULL);
874 switch (conn->type) {
875 case CONN_TYPE_OR_LISTENER:
876 return connection_handle_listener_read(conn, CONN_TYPE_OR);
877 case CONN_TYPE_AP_LISTENER:
878 return connection_handle_listener_read(conn, CONN_TYPE_AP);
879 case CONN_TYPE_DIR_LISTENER:
880 return connection_handle_listener_read(conn, CONN_TYPE_DIR);
881 case CONN_TYPE_CONTROL_LISTENER:
882 return connection_handle_listener_read(conn, CONN_TYPE_CONTROL);
885 loop_again:
886 try_to_read = max_to_read;
887 tor_assert(!conn->marked_for_close);
888 if (connection_read_to_buf(conn, &max_to_read) < 0) {
889 /* There's a read error; kill the connection.*/
890 connection_close_immediate(conn); /* Don't flush; connection is dead. */
891 if (conn->type == CONN_TYPE_AP || conn->type == CONN_TYPE_EXIT) {
892 connection_edge_end(conn, (char)(connection_state_is_open(conn) ?
893 END_STREAM_REASON_MISC : END_STREAM_REASON_CONNECTFAILED),
894 conn->cpath_layer);
896 connection_mark_for_close(conn);
897 return -1;
899 if (CONN_IS_EDGE(conn) &&
900 try_to_read != max_to_read) {
901 /* instruct it not to try to package partial cells. */
902 if (connection_process_inbuf(conn, 0) < 0) {
903 return -1;
905 if (!conn->marked_for_close &&
906 connection_is_reading(conn) &&
907 !conn->inbuf_reached_eof &&
908 max_to_read > 0)
909 goto loop_again; /* try reading again, in case more is here now */
911 /* one last try, packaging partial cells and all. */
912 if (!conn->marked_for_close &&
913 connection_process_inbuf(conn, 1) < 0) {
914 return -1;
916 if (!conn->marked_for_close &&
917 conn->inbuf_reached_eof &&
918 connection_reached_eof(conn) < 0) {
919 return -1;
921 return 0;
924 /** Pull in new bytes from conn-\>s onto conn-\>inbuf, either
925 * directly or via TLS. Reduce the token buckets by the number of
926 * bytes read.
928 * If *max_to_read is -1, then decide it ourselves, else go with the
929 * value passed to us. When returning, if it's changed, subtract the
930 * number of bytes we read from *max_to_read.
932 * Return -1 if we want to break conn, else return 0.
934 static int connection_read_to_buf(connection_t *conn, int *max_to_read) {
935 int result, at_most = *max_to_read;
937 if (at_most == -1) { /* we need to initialize it */
938 /* how many bytes are we allowed to read? */
939 at_most = connection_bucket_read_limit(conn);
942 if (connection_speaks_cells(conn) && conn->state != OR_CONN_STATE_CONNECTING) {
943 int pending;
944 if (conn->state == OR_CONN_STATE_HANDSHAKING) {
945 /* continue handshaking even if global token bucket is empty */
946 return connection_tls_continue_handshake(conn);
949 log_fn(LOG_DEBUG,"%d: starting, inbuf_datalen %d (%d pending in tls object). at_most %d.",
950 conn->s,(int)buf_datalen(conn->inbuf),tor_tls_get_pending_bytes(conn->tls), at_most);
952 /* else open, or closing */
953 result = read_to_buf_tls(conn->tls, at_most, conn->inbuf);
955 switch (result) {
956 case TOR_TLS_CLOSE:
957 log_fn(LOG_INFO,"TLS connection closed on read. Closing. (Nickname %s, address %s",
958 conn->nickname ? conn->nickname : "not set", conn->address);
959 return -1;
960 case TOR_TLS_ERROR:
961 log_fn(LOG_INFO,"tls error. breaking (nickname %s, address %s).",
962 conn->nickname ? conn->nickname : "not set", conn->address);
963 return -1;
964 case TOR_TLS_WANTWRITE:
965 connection_start_writing(conn);
966 return 0;
967 case TOR_TLS_WANTREAD: /* we're already reading */
968 case TOR_TLS_DONE: /* no data read, so nothing to process */
969 result = 0;
970 break; /* so we call bucket_decrement below */
971 default:
972 break;
974 pending = tor_tls_get_pending_bytes(conn->tls);
975 if (pending) {
976 /* XXXX If we have any pending bytes, read them now. This *can*
977 * take us over our read alotment, but really we shouldn't be
978 * believing that SSL bytes are the same as TCP bytes anyway. */
979 int r2 = read_to_buf_tls(conn->tls, pending, conn->inbuf);
980 if (r2<0) {
981 log_fn(LOG_WARN, "Bug: apparently, reading pending bytes can fail.");
982 return -1;
983 } else {
984 result += r2;
988 } else {
989 result = read_to_buf(conn->s, at_most, conn->inbuf,
990 &conn->inbuf_reached_eof);
992 // log_fn(LOG_DEBUG,"read_to_buf returned %d.",read_result);
994 if (result < 0)
995 return -1;
998 if (result > 0) { /* change *max_to_read */
999 *max_to_read = at_most - result;
1002 if (result > 0 && !is_local_IP(conn->addr)) { /* remember it */
1003 rep_hist_note_bytes_read(result, time(NULL));
1004 connection_read_bucket_decrement(conn, result);
1007 /* Call even if result is 0, since the global read bucket may
1008 * have reached 0 on a different conn, and this guy needs to
1009 * know to stop reading. */
1010 connection_consider_empty_buckets(conn);
1012 return 0;
1015 /** A pass-through to fetch_from_buf. */
1016 int connection_fetch_from_buf(char *string, size_t len, connection_t *conn) {
1017 return fetch_from_buf(string, len, conn->inbuf);
1020 /** Return conn-\>outbuf_flushlen: how many bytes conn wants to flush
1021 * from its outbuf. */
1022 int connection_wants_to_flush(connection_t *conn) {
1023 return conn->outbuf_flushlen;
1026 /** Are there too many bytes on edge connection <b>conn</b>'s outbuf to
1027 * send back a relay-level sendme yet? Return 1 if so, 0 if not. Used by
1028 * connection_edge_consider_sending_sendme().
1030 int connection_outbuf_too_full(connection_t *conn) {
1031 return (conn->outbuf_flushlen > 10*CELL_PAYLOAD_SIZE);
1034 /** Try to flush more bytes onto conn-\>s.
1036 * This function gets called either from conn_write() in main.c
1037 * when poll() has declared that conn wants to write, or below
1038 * from connection_write_to_buf() when an entire TLS record is ready.
1040 * Update conn-\>timestamp_lastwritten to now, and call flush_buf
1041 * or flush_buf_tls appropriately. If it succeeds and there no more
1042 * more bytes on conn->outbuf, then call connection_finished_flushing
1043 * on it too.
1045 * Mark the connection and return -1 if you want to close it, else
1046 * return 0.
1048 int connection_handle_write(connection_t *conn) {
1049 int e, len=sizeof(e);
1050 int result;
1051 time_t now = time(NULL);
1053 tor_assert(!connection_is_listener(conn));
1055 conn->timestamp_lastwritten = now;
1057 /* Sometimes, "writable" means "connected". */
1058 if (connection_state_is_connecting(conn)) {
1059 if (getsockopt(conn->s, SOL_SOCKET, SO_ERROR, (void*)&e, &len) < 0) {
1060 log_fn(LOG_WARN,"getsockopt() syscall failed?! Please report to tor-ops.");
1061 connection_close_immediate(conn);
1062 connection_mark_for_close(conn);
1063 return -1;
1065 if (e) {
1066 /* some sort of error, but maybe just inprogress still */
1067 if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
1068 log_fn(LOG_INFO,"in-progress connect failed. Removing.");
1069 connection_close_immediate(conn);
1070 connection_mark_for_close(conn);
1071 /* it's safe to pass OPs to router_mark_as_down(), since it just
1072 * ignores unrecognized routers
1074 if (conn->type == CONN_TYPE_OR)
1075 router_mark_as_down(conn->identity_digest);
1076 return -1;
1077 } else {
1078 return 0; /* no change, see if next time is better */
1081 /* The connection is successful. */
1082 return connection_finished_connecting(conn);
1085 if (connection_speaks_cells(conn)) {
1086 if (conn->state == OR_CONN_STATE_HANDSHAKING) {
1087 connection_stop_writing(conn);
1088 if (connection_tls_continue_handshake(conn) < 0) {
1089 connection_close_immediate(conn); /* Don't flush; connection is dead. */
1090 connection_mark_for_close(conn);
1091 return -1;
1093 return 0;
1096 /* else open, or closing */
1097 result = flush_buf_tls(conn->tls, conn->outbuf, &conn->outbuf_flushlen);
1098 switch (result) {
1099 case TOR_TLS_ERROR:
1100 case TOR_TLS_CLOSE:
1101 log_fn(LOG_INFO,result==TOR_TLS_ERROR?
1102 "tls error. breaking.":"TLS connection closed on flush");
1103 connection_close_immediate(conn); /* Don't flush; connection is dead. */
1104 connection_mark_for_close(conn);
1105 return -1;
1106 case TOR_TLS_WANTWRITE:
1107 log_fn(LOG_DEBUG,"wanted write.");
1108 /* we're already writing */
1109 return 0;
1110 case TOR_TLS_WANTREAD:
1111 /* Make sure to avoid a loop if the receive buckets are empty. */
1112 log_fn(LOG_DEBUG,"wanted read.");
1113 if (!connection_is_reading(conn)) {
1114 connection_stop_writing(conn);
1115 conn->wants_to_write = 1;
1116 /* we'll start reading again when the next second arrives,
1117 * and then also start writing again.
1120 /* else no problem, we're already reading */
1121 return 0;
1122 /* case TOR_TLS_DONE:
1123 * for TOR_TLS_DONE, fall through to check if the flushlen
1124 * is empty, so we can stop writing.
1127 } else {
1128 result = flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen);
1129 if (result < 0) {
1130 connection_close_immediate(conn); /* Don't flush; connection is dead. */
1131 conn->has_sent_end = 1;
1132 connection_mark_for_close(conn);
1133 return -1;
1137 if (result > 0 && !is_local_IP(conn->addr)) { /* remember it */
1138 rep_hist_note_bytes_written(result, now);
1139 global_write_bucket -= result;
1142 if (!connection_wants_to_flush(conn)) { /* it's done flushing */
1143 if (connection_finished_flushing(conn) < 0) {
1144 /* already marked */
1145 return -1;
1149 return 0;
1152 /** Append <b>len</b> bytes of <b>string</b> onto <b>conn</b>'s
1153 * outbuf, and ask it to start writing.
1155 void connection_write_to_buf(const char *string, size_t len, connection_t *conn) {
1157 if (!len)
1158 return;
1159 /* if it's marked for close, only allow write if we mean to flush it */
1160 if (conn->marked_for_close && !conn->hold_open_until_flushed)
1161 return;
1163 if (write_to_buf(string, len, conn->outbuf) < 0) {
1164 if (conn->type == CONN_TYPE_AP || conn->type == CONN_TYPE_EXIT) {
1165 /* if it failed, it means we have our package/delivery windows set
1166 wrong compared to our max outbuf size. close the whole circuit. */
1167 log_fn(LOG_WARN,"write_to_buf failed. Closing circuit (fd %d).", conn->s);
1168 circuit_mark_for_close(circuit_get_by_conn(conn));
1169 } else {
1170 log_fn(LOG_WARN,"write_to_buf failed. Closing connection (fd %d).", conn->s);
1171 connection_mark_for_close(conn);
1173 return;
1176 connection_start_writing(conn);
1177 conn->outbuf_flushlen += len;
1180 /** Return the conn to addr/port that has the most recent
1181 * timestamp_created, or NULL if no such conn exists. */
1182 connection_t *connection_exact_get_by_addr_port(uint32_t addr, uint16_t port) {
1183 int i, n;
1184 connection_t *conn, *best=NULL;
1185 connection_t **carray;
1187 get_connection_array(&carray,&n);
1188 for (i=0;i<n;i++) {
1189 conn = carray[i];
1190 if (conn->addr == addr && conn->port == port && !conn->marked_for_close &&
1191 (!best || best->timestamp_created < conn->timestamp_created))
1192 best = conn;
1194 return best;
1197 connection_t *connection_get_by_identity_digest(const char *digest, int type)
1199 int i, n;
1200 connection_t *conn, *best=NULL;
1201 connection_t **carray;
1203 get_connection_array(&carray,&n);
1204 for (i=0;i<n;i++) {
1205 conn = carray[i];
1206 if (conn->type != type)
1207 continue;
1208 if (!memcmp(conn->identity_digest, digest, DIGEST_LEN) &&
1209 !conn->marked_for_close &&
1210 (!best || best->timestamp_created < conn->timestamp_created))
1211 best = conn;
1213 return best;
1216 /** Return a connection of type <b>type</b> that is not marked for
1217 * close.
1219 connection_t *connection_get_by_type(int type) {
1220 int i, n;
1221 connection_t *conn;
1222 connection_t **carray;
1224 get_connection_array(&carray,&n);
1225 for (i=0;i<n;i++) {
1226 conn = carray[i];
1227 if (conn->type == type && !conn->marked_for_close)
1228 return conn;
1230 return NULL;
1233 /** Return a connection of type <b>type</b> that is in state <b>state</b>,
1234 * and that is not marked for close.
1236 connection_t *connection_get_by_type_state(int type, int state) {
1237 int i, n;
1238 connection_t *conn;
1239 connection_t **carray;
1241 get_connection_array(&carray,&n);
1242 for (i=0;i<n;i++) {
1243 conn = carray[i];
1244 if (conn->type == type && conn->state == state && !conn->marked_for_close)
1245 return conn;
1247 return NULL;
1250 /** Return the connection of type <b>type</b> that is in state
1251 * <b>state</b>, that was written to least recently, and that is not
1252 * marked for close.
1254 connection_t *connection_get_by_type_state_lastwritten(int type, int state) {
1255 int i, n;
1256 connection_t *conn, *best=NULL;
1257 connection_t **carray;
1259 get_connection_array(&carray,&n);
1260 for (i=0;i<n;i++) {
1261 conn = carray[i];
1262 if (conn->type == type && conn->state == state && !conn->marked_for_close)
1263 if (!best || conn->timestamp_lastwritten < best->timestamp_lastwritten)
1264 best = conn;
1266 return best;
1269 /** Return a connection of type <b>type</b> that has rendquery equal
1270 * to <b>rendquery</b>, and that is not marked for close. If state
1271 * is non-zero, conn must be of that state too.
1273 connection_t *
1274 connection_get_by_type_state_rendquery(int type, int state, const char *rendquery) {
1275 int i, n;
1276 connection_t *conn;
1277 connection_t **carray;
1279 get_connection_array(&carray,&n);
1280 for (i=0;i<n;i++) {
1281 conn = carray[i];
1282 if (conn->type == type &&
1283 !conn->marked_for_close &&
1284 (!state || state == conn->state) &&
1285 !rend_cmp_service_ids(rendquery, conn->rend_query))
1286 return conn;
1288 return NULL;
1291 /** Return 1 if <b>conn</b> is a listener conn, else return 0. */
1292 int connection_is_listener(connection_t *conn) {
1293 if (conn->type == CONN_TYPE_OR_LISTENER ||
1294 conn->type == CONN_TYPE_AP_LISTENER ||
1295 conn->type == CONN_TYPE_DIR_LISTENER ||
1296 conn->type == CONN_TYPE_CONTROL_LISTENER)
1297 return 1;
1298 return 0;
1301 /** Return 1 if <b>conn</b> is in state "open" and is not marked
1302 * for close, else return 0.
1304 int connection_state_is_open(connection_t *conn) {
1305 tor_assert(conn);
1307 if (conn->marked_for_close)
1308 return 0;
1310 if ((conn->type == CONN_TYPE_OR && conn->state == OR_CONN_STATE_OPEN) ||
1311 (conn->type == CONN_TYPE_AP && conn->state == AP_CONN_STATE_OPEN) ||
1312 (conn->type == CONN_TYPE_EXIT && conn->state == EXIT_CONN_STATE_OPEN) ||
1313 (conn->type == CONN_TYPE_CONTROL && conn->state ==CONTROL_CONN_STATE_OPEN))
1314 return 1;
1316 return 0;
1319 /** Return 1 if conn is in 'connecting' state, else return 0. */
1320 int connection_state_is_connecting(connection_t *conn) {
1321 tor_assert(conn);
1323 if (conn->marked_for_close)
1324 return 0;
1325 switch (conn->type)
1327 case CONN_TYPE_OR:
1328 return conn->state == OR_CONN_STATE_CONNECTING;
1329 case CONN_TYPE_EXIT:
1330 return conn->state == EXIT_CONN_STATE_CONNECTING;
1331 case CONN_TYPE_DIR:
1332 return conn->state == DIR_CONN_STATE_CONNECTING;
1335 return 0;
1338 /** Write a destroy cell with circ ID <b>circ_id</b> onto OR connection
1339 * <b>conn</b>.
1341 * Return 0.
1343 int connection_send_destroy(uint16_t circ_id, connection_t *conn) {
1344 cell_t cell;
1346 tor_assert(conn);
1347 tor_assert(connection_speaks_cells(conn));
1349 memset(&cell, 0, sizeof(cell_t));
1350 cell.circ_id = circ_id;
1351 cell.command = CELL_DESTROY;
1352 log_fn(LOG_INFO,"Sending destroy (circID %d).", circ_id);
1353 connection_or_write_cell_to_buf(&cell, conn);
1354 return 0;
1357 /** Process new bytes that have arrived on conn-\>inbuf.
1359 * This function just passes conn to the connection-specific
1360 * connection_*_process_inbuf() function. It also passes in
1361 * package_partial if wanted.
1363 static int connection_process_inbuf(connection_t *conn, int package_partial) {
1365 tor_assert(conn);
1367 switch (conn->type) {
1368 case CONN_TYPE_OR:
1369 return connection_or_process_inbuf(conn);
1370 case CONN_TYPE_EXIT:
1371 case CONN_TYPE_AP:
1372 return connection_edge_process_inbuf(conn, package_partial);
1373 case CONN_TYPE_DIR:
1374 return connection_dir_process_inbuf(conn);
1375 case CONN_TYPE_DNSWORKER:
1376 return connection_dns_process_inbuf(conn);
1377 case CONN_TYPE_CPUWORKER:
1378 return connection_cpu_process_inbuf(conn);
1379 case CONN_TYPE_CONTROL:
1380 return connection_control_process_inbuf(conn);
1381 default:
1382 log_fn(LOG_WARN,"Bug: got unexpected conn type %d.", conn->type);
1383 #ifdef TOR_FRAGILE
1384 tor_assert(0);
1385 #endif
1386 return -1;
1390 /** We just finished flushing bytes from conn-\>outbuf, and there
1391 * are no more bytes remaining.
1393 * This function just passes conn to the connection-specific
1394 * connection_*_finished_flushing() function.
1396 static int connection_finished_flushing(connection_t *conn) {
1398 tor_assert(conn);
1400 // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
1402 switch (conn->type) {
1403 case CONN_TYPE_OR:
1404 return connection_or_finished_flushing(conn);
1405 case CONN_TYPE_AP:
1406 case CONN_TYPE_EXIT:
1407 return connection_edge_finished_flushing(conn);
1408 case CONN_TYPE_DIR:
1409 return connection_dir_finished_flushing(conn);
1410 case CONN_TYPE_DNSWORKER:
1411 return connection_dns_finished_flushing(conn);
1412 case CONN_TYPE_CPUWORKER:
1413 return connection_cpu_finished_flushing(conn);
1414 case CONN_TYPE_CONTROL:
1415 return connection_control_finished_flushing(conn);
1416 default:
1417 log_fn(LOG_WARN,"Bug: got unexpected conn type %d.", conn->type);
1418 #ifdef TOR_FRAGILE
1419 tor_assert(0);
1420 #endif
1421 return -1;
1425 /** Called when our attempt to connect() to another server has just
1426 * succeeded.
1428 * This function just passes conn to the connection-specific
1429 * connection_*_finished_connecting() function.
1431 static int connection_finished_connecting(connection_t *conn)
1433 tor_assert(conn);
1434 switch (conn->type)
1436 case CONN_TYPE_OR:
1437 return connection_or_finished_connecting(conn);
1438 case CONN_TYPE_EXIT:
1439 return connection_edge_finished_connecting(conn);
1440 case CONN_TYPE_DIR:
1441 return connection_dir_finished_connecting(conn);
1442 default:
1443 log_fn(LOG_WARN,"Bug: got unexpected conn type %d.", conn->type);
1444 #ifdef TOR_FRAGILE
1445 tor_assert(0);
1446 #endif
1447 return -1;
1451 static int connection_reached_eof(connection_t *conn)
1453 switch (conn->type) {
1454 case CONN_TYPE_OR:
1455 return connection_or_reached_eof(conn);
1456 case CONN_TYPE_AP:
1457 case CONN_TYPE_EXIT:
1458 return connection_edge_reached_eof(conn);
1459 case CONN_TYPE_DIR:
1460 return connection_dir_reached_eof(conn);
1461 case CONN_TYPE_DNSWORKER:
1462 return connection_dns_reached_eof(conn);
1463 case CONN_TYPE_CPUWORKER:
1464 return connection_cpu_reached_eof(conn);
1465 case CONN_TYPE_CONTROL:
1466 return connection_control_reached_eof(conn);
1467 default:
1468 log_fn(LOG_WARN,"Bug: got unexpected conn type %d.", conn->type);
1469 #ifdef TOR_FRAGILE
1470 tor_assert(0);
1471 #endif
1472 return -1;
1476 /** Verify that connection <b>conn</b> has all of its invariants
1477 * correct. Trigger an assert if anything is invalid.
1479 void assert_connection_ok(connection_t *conn, time_t now)
1481 tor_assert(conn);
1482 tor_assert(conn->magic == CONNECTION_MAGIC);
1483 tor_assert(conn->type >= _CONN_TYPE_MIN);
1484 tor_assert(conn->type <= _CONN_TYPE_MAX);
1486 if (conn->outbuf_flushlen > 0) {
1487 tor_assert(connection_is_writing(conn) || conn->wants_to_write);
1490 if (conn->hold_open_until_flushed)
1491 tor_assert(conn->marked_for_close);
1493 /* XXX check: wants_to_read, wants_to_write, s, poll_index,
1494 * marked_for_close. */
1496 /* buffers */
1497 if (!connection_is_listener(conn)) {
1498 assert_buf_ok(conn->inbuf);
1499 assert_buf_ok(conn->outbuf);
1502 #if 0 /* computers often go back in time; no way to know */
1503 tor_assert(!now || conn->timestamp_lastread <= now);
1504 tor_assert(!now || conn->timestamp_lastwritten <= now);
1505 tor_assert(conn->timestamp_created <= conn->timestamp_lastread);
1506 tor_assert(conn->timestamp_created <= conn->timestamp_lastwritten);
1507 #endif
1509 /* XXX Fix this; no longer so.*/
1510 #if 0
1511 if (conn->type != CONN_TYPE_OR && conn->type != CONN_TYPE_DIR)
1512 tor_assert(!conn->pkey);
1513 /* pkey is set if we're a dir client, or if we're an OR in state OPEN
1514 * connected to another OR.
1516 #endif
1518 if (conn->type != CONN_TYPE_OR) {
1519 tor_assert(!conn->tls);
1520 } else {
1521 if (conn->state == OR_CONN_STATE_OPEN) {
1522 /* tor_assert(conn->bandwidth > 0); */
1523 /* the above isn't necessarily true: if we just did a TLS
1524 * handshake but we didn't recognize the other peer, or it
1525 * gave a bad cert/etc, then we won't have assigned bandwidth,
1526 * yet it will be open. -RD
1528 // tor_assert(conn->receiver_bucket >= 0);
1530 tor_assert(conn->addr && conn->port);
1531 tor_assert(conn->address);
1532 if (conn->state != OR_CONN_STATE_CONNECTING)
1533 tor_assert(conn->tls);
1536 if (conn->type != CONN_TYPE_EXIT && conn->type != CONN_TYPE_AP) {
1537 tor_assert(!conn->stream_id);
1538 tor_assert(!conn->next_stream);
1539 tor_assert(!conn->cpath_layer);
1540 tor_assert(!conn->package_window);
1541 tor_assert(!conn->deliver_window);
1542 tor_assert(!conn->done_sending);
1543 tor_assert(!conn->done_receiving);
1544 } else {
1545 /* XXX unchecked: package window, deliver window. */
1547 if (conn->type == CONN_TYPE_AP) {
1548 tor_assert(conn->socks_request);
1549 if (conn->state == AP_CONN_STATE_OPEN) {
1550 tor_assert(conn->socks_request->has_finished);
1551 tor_assert(conn->cpath_layer);
1552 assert_cpath_layer_ok(conn->cpath_layer);
1554 } else {
1555 tor_assert(!conn->socks_request);
1557 if (conn->type == CONN_TYPE_EXIT) {
1558 tor_assert(conn->purpose == EXIT_PURPOSE_CONNECT ||
1559 conn->purpose == EXIT_PURPOSE_RESOLVE);
1560 } else if (conn->type != CONN_TYPE_DIR) {
1561 tor_assert(!conn->purpose); /* only used for dir types currently */
1564 switch (conn->type)
1566 case CONN_TYPE_OR_LISTENER:
1567 case CONN_TYPE_AP_LISTENER:
1568 case CONN_TYPE_DIR_LISTENER:
1569 case CONN_TYPE_CONTROL_LISTENER:
1570 tor_assert(conn->state == LISTENER_STATE_READY);
1571 break;
1572 case CONN_TYPE_OR:
1573 tor_assert(conn->state >= _OR_CONN_STATE_MIN);
1574 tor_assert(conn->state <= _OR_CONN_STATE_MAX);
1575 break;
1576 case CONN_TYPE_EXIT:
1577 tor_assert(conn->state >= _EXIT_CONN_STATE_MIN);
1578 tor_assert(conn->state <= _EXIT_CONN_STATE_MAX);
1579 break;
1580 case CONN_TYPE_AP:
1581 tor_assert(conn->state >= _AP_CONN_STATE_MIN);
1582 tor_assert(conn->state <= _AP_CONN_STATE_MAX);
1583 tor_assert(conn->socks_request);
1584 break;
1585 case CONN_TYPE_DIR:
1586 tor_assert(conn->state >= _DIR_CONN_STATE_MIN);
1587 tor_assert(conn->state <= _DIR_CONN_STATE_MAX);
1588 tor_assert(conn->purpose >= _DIR_PURPOSE_MIN);
1589 tor_assert(conn->purpose <= _DIR_PURPOSE_MAX);
1590 break;
1591 case CONN_TYPE_DNSWORKER:
1592 tor_assert(conn->state == DNSWORKER_STATE_IDLE ||
1593 conn->state == DNSWORKER_STATE_BUSY);
1594 break;
1595 case CONN_TYPE_CPUWORKER:
1596 tor_assert(conn->state >= _CPUWORKER_STATE_MIN);
1597 tor_assert(conn->state <= _CPUWORKER_STATE_MAX);
1598 break;
1599 case CONN_TYPE_CONTROL:
1600 tor_assert(conn->state >= _CONTROL_CONN_STATE_MIN);
1601 tor_assert(conn->state <= _CONTROL_CONN_STATE_MAX);
1602 break;
1603 default:
1604 tor_assert(0);