clean up a few confusions brian levine pointed out
[tor.git] / src / or / or.h
blob8d9d52ee7c5af49a8aa3ffdb0a23fe8a29aee197
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2007, Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
5 /* $Id$ */
7 /**
8 * \file or.h
9 * \brief Master header file for Tor-specific functionality.
10 **/
12 #ifndef __OR_H
13 #define __OR_H
14 #define OR_H_ID "$Id$"
16 #include "orconfig.h"
17 #ifdef MS_WINDOWS
18 #define WIN32_WINNT 0x400
19 #define _WIN32_WINNT 0x400
20 #define WIN32_LEAN_AND_MEAN
21 #endif
23 #include <stdio.h>
24 #include <stdlib.h>
25 #ifdef HAVE_UNISTD_H
26 #include <unistd.h>
27 #endif
28 #ifdef HAVE_STRING_H
29 #include <string.h>
30 #endif
31 #ifdef HAVE_SIGNAL_H
32 #include <signal.h>
33 #endif
34 #ifdef HAVE_NETDB_H
35 #include <netdb.h>
36 #endif
37 #ifdef HAVE_CTYPE_H
38 #include <ctype.h>
39 #endif
40 #ifdef HAVE_SYS_PARAM_H
41 #include <sys/param.h> /* FreeBSD needs this to know what version it is */
42 #endif
43 #include "../common/torint.h"
44 #ifdef HAVE_SYS_WAIT_H
45 #include <sys/wait.h>
46 #endif
47 #ifdef HAVE_SYS_FCNTL_H
48 #include <sys/fcntl.h>
49 #endif
50 #ifdef HAVE_FCNTL_H
51 #include <fcntl.h>
52 #endif
53 #ifdef HAVE_SYS_IOCTL_H
54 #include <sys/ioctl.h>
55 #endif
56 #ifdef HAVE_SYS_SOCKET_H
57 #include <sys/socket.h>
58 #endif
59 #ifdef HAVE_SYS_TIME_H
60 #include <sys/time.h>
61 #endif
62 #ifdef HAVE_SYS_STAT_H
63 #include <sys/stat.h>
64 #endif
65 #ifdef HAVE_NETINET_IN_H
66 #include <netinet/in.h>
67 #endif
68 #ifdef HAVE_ARPA_INET_H
69 #include <arpa/inet.h>
70 #endif
71 #ifdef HAVE_ERRNO_H
72 #include <errno.h>
73 #endif
74 #ifdef HAVE_ASSERT_H
75 #include <assert.h>
76 #endif
77 #ifdef HAVE_TIME_H
78 #include <time.h>
79 #endif
81 /** Upper bound on maximum simultaneous connections; can be lowered by
82 * config file. */
83 #if defined(CYGWIN) || defined(__CYGWIN__)
84 /* http://archives.seul.org/or/talk/Aug-2006/msg00210.html */
85 #define MAXCONNECTIONS 3200
86 #else
87 /* very high by default. "nobody should need more than this..." */
88 #define MAXCONNECTIONS 15000
89 #endif
91 #ifdef MS_WINDOWS
92 /* No, we don't need to redefine FD_SETSIZE before including winsock:
93 * we use libevent now, and libevent handles the select() stuff. Yes,
94 * some documents imply that we need to redefine anyway if we're using
95 * select() anywhere in our application or in anything it links to: these
96 * documents are either the holy texts of a cargo cult of network
97 * programmers, or more likely a simplification of what's going on for
98 * people who haven't read winsock[2].h for themselves.
100 #if defined(_MSC_VER) && (_MSC_VER <= 1300)
101 #include <winsock.h>
102 #else
103 #include <winsock2.h>
104 #include <ws2tcpip.h>
105 #endif
106 #endif
108 #ifdef MS_WINDOWS
109 #include <io.h>
110 #include <process.h>
111 #include <direct.h>
112 #include <windows.h>
113 #define snprintf _snprintf
114 #endif
116 #include <event.h>
118 #include "../common/crypto.h"
119 #include "../common/tortls.h"
120 #include "../common/log.h"
121 #include "../common/compat.h"
122 #include "../common/container.h"
123 #include "../common/util.h"
124 #include "../common/torgzip.h"
126 /* These signals are defined to help control_signal_act work.
128 #ifndef SIGHUP
129 #define SIGHUP 1
130 #endif
131 #ifndef SIGINT
132 #define SIGINT 2
133 #endif
134 #ifndef SIGUSR1
135 #define SIGUSR1 10
136 #endif
137 #ifndef SIGUSR2
138 #define SIGUSR2 12
139 #endif
140 #ifndef SIGTERM
141 #define SIGTERM 15
142 #endif
143 /* Controller signals start at a high number so we don't
144 * conflict with system-defined signals. */
145 #define SIGNEWNYM 129
146 #define SIGCLEARDNSCACHE 130
148 #if (SIZEOF_CELL_T != 0)
149 /* On Irix, stdlib.h defines a cell_t type, so we need to make sure
150 * that our stuff always calls cell_t something different. */
151 #define cell_t tor_cell_t
152 #endif
154 /** Length of longest allowable configured nickname. */
155 #define MAX_NICKNAME_LEN 19
156 /** Length of a router identity encoded as a hexadecimal digest, plus
157 * possible dollar sign. */
158 #define MAX_HEX_NICKNAME_LEN (HEX_DIGEST_LEN+1)
159 /** Maximum length of verbose router identifier: dollar sign, hex ID digest,
160 * equal sign or tilde, nickname. */
161 #define MAX_VERBOSE_NICKNAME_LEN (1+HEX_DIGEST_LEN+1+MAX_NICKNAME_LEN)
163 /** Maximum size, in bytes, for resized buffers. */
164 #define MAX_BUF_SIZE ((1<<24)-1) /* 16MB-1 */
165 /** Maximum size, in bytes, for any directory object that we've downloaded. */
166 #define MAX_DIR_DL_SIZE MAX_BUF_SIZE
168 /** For http parsing: Maximum number of bytes we'll accept in the headers
169 * of an HTTP request or response. */
170 #define MAX_HEADERS_SIZE 50000
171 /** Maximum size, in bytes, for any directory object that we're accepting
172 * as an upload. */
173 #define MAX_DIR_UL_SIZE 500000
175 /** How long do we keep DNS cache entries before purging them (regardless of
176 * their TTL)? */
177 #define MAX_DNS_ENTRY_AGE (30*60)
178 /** How long do we cache/tell clients to cache DNS records when no TTL is
179 * known? */
180 #define DEFAULT_DNS_TTL (30*60)
181 /** How long can a TTL be before we stop believing it? */
182 #define MAX_DNS_TTL (3*60*60)
183 /** How small can a TTL be before we stop believing it? */
184 #define MIN_DNS_TTL (60)
186 /** How often do we rotate onion keys? */
187 #define MIN_ONION_KEY_LIFETIME (7*24*60*60)
188 /** How often do we rotate TLS contexts? */
189 #define MAX_SSL_KEY_LIFETIME (2*60*60)
191 /** How old do we allow a router to get before removing it
192 * from the router list? In seconds. */
193 #define ROUTER_MAX_AGE (60*60*48)
194 /** How old can a router get before we (as a server) will no longer
195 * consider it live? In seconds. */
196 #define ROUTER_MAX_AGE_TO_PUBLISH (60*60*20)
197 /** How old do we let a saved descriptor get before force-removing it? */
198 #define OLD_ROUTER_DESC_MAX_AGE (60*60*24*5)
199 /** How old do we let a networkstatus get before ignoring it? */
200 #define NETWORKSTATUS_MAX_AGE (60*60*24)
202 /** Possible rules for generating circuit IDs on an OR connection. */
203 typedef enum {
204 CIRC_ID_TYPE_LOWER=0, /**< Pick from 0..1<<15-1. */
205 CIRC_ID_TYPE_HIGHER=1, /**< Pick from 1<<15..1<<16-1. */
206 /** The other side of a connection is an OP: never create circuits to it,
207 * and let it use any circuit ID it wants. */
208 CIRC_ID_TYPE_NEITHER=2
209 } circ_id_type_t;
211 #define _CONN_TYPE_MIN 3
212 /** Type for sockets listening for OR connections. */
213 #define CONN_TYPE_OR_LISTENER 3
214 /** A bidirectional TLS connection transmitting a sequence of cells.
215 * May be from an OR to an OR, or from an OP to an OR. */
216 #define CONN_TYPE_OR 4
217 /** A TCP connection from an onion router to a stream's destination. */
218 #define CONN_TYPE_EXIT 5
219 /** Type for sockets listening for SOCKS connections. */
220 #define CONN_TYPE_AP_LISTENER 6
221 /** A SOCKS proxy connection from the user application to the onion
222 * proxy. */
223 #define CONN_TYPE_AP 7
224 /** Type for sockets listening for HTTP connections to the directory server. */
225 #define CONN_TYPE_DIR_LISTENER 8
226 /** Type for HTTP connections to the directory server. */
227 #define CONN_TYPE_DIR 9
228 /** Connection from the main process to a CPU worker process. */
229 #define CONN_TYPE_CPUWORKER 10
230 /** Type for listening for connections from user interface process. */
231 #define CONN_TYPE_CONTROL_LISTENER 11
232 /** Type for connections from user interface process. */
233 #define CONN_TYPE_CONTROL 12
234 /** Type for sockets listening for transparent connections redirected by pf or
235 * netfilter. */
236 #define CONN_TYPE_AP_TRANS_LISTENER 13
237 /** Type for sockets listening for transparent connections redirected by
238 * natd. */
239 #define CONN_TYPE_AP_NATD_LISTENER 14
240 /** Type for sockets listening for DNS requests. */
241 #define CONN_TYPE_AP_DNS_LISTENER 15
242 #define _CONN_TYPE_MAX 15
244 #define CONN_IS_EDGE(x) \
245 ((x)->type == CONN_TYPE_EXIT || (x)->type == CONN_TYPE_AP)
247 /** State for any listener connection. */
248 #define LISTENER_STATE_READY 0
250 #define _DNSWORKER_STATE_MIN 1
251 /** State for a connection to a dnsworker process that's idle. */
252 #define DNSWORKER_STATE_IDLE 1
253 /** State for a connection to a dnsworker process that's resolving a
254 * hostname. */
255 #define DNSWORKER_STATE_BUSY 2
256 #define _DNSWORKER_STATE_MAX 2
258 #define _CPUWORKER_STATE_MIN 1
259 /** State for a connection to a cpuworker process that's idle. */
260 #define CPUWORKER_STATE_IDLE 1
261 /** State for a connection to a cpuworker process that's processing a
262 * handshake. */
263 #define CPUWORKER_STATE_BUSY_ONION 2
264 #define _CPUWORKER_STATE_MAX 2
266 #define CPUWORKER_TASK_ONION CPUWORKER_STATE_BUSY_ONION
268 #define _OR_CONN_STATE_MIN 1
269 /** State for a connection to an OR: waiting for connect() to finish. */
270 #define OR_CONN_STATE_CONNECTING 1
271 /** State for a connection to an OR: waiting for proxy command to flush. */
272 #define OR_CONN_STATE_PROXY_FLUSHING 2
273 /** State for a connection to an OR: waiting for proxy response. */
274 #define OR_CONN_STATE_PROXY_READING 3
275 /** State for a connection to an OR: SSL is handshaking, not done yet. */
276 #define OR_CONN_STATE_HANDSHAKING 4
277 /** State for a connection to an OR: Ready to send/receive cells. */
278 #define OR_CONN_STATE_OPEN 5
279 #define _OR_CONN_STATE_MAX 5
281 #define _EXIT_CONN_STATE_MIN 1
282 /** State for an exit connection: waiting for response from dns farm. */
283 #define EXIT_CONN_STATE_RESOLVING 1
284 /** State for an exit connection: waiting for connect() to finish. */
285 #define EXIT_CONN_STATE_CONNECTING 2
286 /** State for an exit connection: open and ready to transmit data. */
287 #define EXIT_CONN_STATE_OPEN 3
288 /** State for an exit connection: waiting to be removed. */
289 #define EXIT_CONN_STATE_RESOLVEFAILED 4
290 #define _EXIT_CONN_STATE_MAX 4
292 /* The AP state values must be disjoint from the EXIT state values. */
293 #define _AP_CONN_STATE_MIN 5
294 /** State for a SOCKS connection: waiting for SOCKS request. */
295 #define AP_CONN_STATE_SOCKS_WAIT 5
296 /** State for a SOCKS connection: got a y.onion URL; waiting to receive
297 * rendezvous descriptor. */
298 #define AP_CONN_STATE_RENDDESC_WAIT 6
299 /** The controller will attach this connection to a circuit; it isn't our
300 * job to do so. */
301 #define AP_CONN_STATE_CONTROLLER_WAIT 7
302 /** State for a SOCKS connection: waiting for a completed circuit. */
303 #define AP_CONN_STATE_CIRCUIT_WAIT 8
304 /** State for a SOCKS connection: sent BEGIN, waiting for CONNECTED. */
305 #define AP_CONN_STATE_CONNECT_WAIT 9
306 /** State for a SOCKS connection: sent RESOLVE, waiting for RESOLVED. */
307 #define AP_CONN_STATE_RESOLVE_WAIT 10
308 /** State for a SOCKS connection: ready to send and receive. */
309 #define AP_CONN_STATE_OPEN 11
310 /** State for a transparent natd connection: waiting for original
311 * destination. */
312 #define AP_CONN_STATE_NATD_WAIT 12
313 #define _AP_CONN_STATE_MAX 12
315 /** True iff the AP_CONN_STATE_* value <b>s</b> means that the corresponding
316 * edge connection is not attached to any circuit. */
317 #define AP_CONN_STATE_IS_UNATTACHED(s) \
318 ((s) <= AP_CONN_STATE_CIRCUIT_WAIT || (s) == AP_CONN_STATE_NATD_WAIT)
320 #define _DIR_CONN_STATE_MIN 1
321 /** State for connection to directory server: waiting for connect(). */
322 #define DIR_CONN_STATE_CONNECTING 1
323 /** State for connection to directory server: sending HTTP request. */
324 #define DIR_CONN_STATE_CLIENT_SENDING 2
325 /** State for connection to directory server: reading HTTP response. */
326 #define DIR_CONN_STATE_CLIENT_READING 3
327 /** State for connection to directory server: happy and finished. */
328 #define DIR_CONN_STATE_CLIENT_FINISHED 4
329 /** State for connection at directory server: waiting for HTTP request. */
330 #define DIR_CONN_STATE_SERVER_COMMAND_WAIT 5
331 /** State for connection at directory server: sending HTTP response. */
332 #define DIR_CONN_STATE_SERVER_WRITING 6
333 #define _DIR_CONN_STATE_MAX 6
335 /** True iff the purpose of <b>conn</b> means that it's a server-side
336 * directory connection. */
337 #define DIR_CONN_IS_SERVER(conn) ((conn)->purpose == DIR_PURPOSE_SERVER)
339 #define _CONTROL_CONN_STATE_MIN 1
340 /** State for a control connection: Authenticated and accepting v1 commands. */
341 #define CONTROL_CONN_STATE_OPEN 1
342 /** State for a control connection: Waiting for authentication; speaking
343 * protocol v1. */
344 #define CONTROL_CONN_STATE_NEEDAUTH 2
345 #define _CONTROL_CONN_STATE_MAX 2
347 #define _DIR_PURPOSE_MIN 1
348 /** A connection to a directory server: download a directory. */
349 #define DIR_PURPOSE_FETCH_DIR 1
350 /** A connection to a directory server: download just the list
351 * of running routers. */
352 #define DIR_PURPOSE_FETCH_RUNNING_LIST 2
353 /** A connection to a directory server: download a rendezvous
354 * descriptor. */
355 #define DIR_PURPOSE_FETCH_RENDDESC 3
356 /** A connection to a directory server: set after a rendezvous
357 * descriptor is downloaded. */
358 #define DIR_PURPOSE_HAS_FETCHED_RENDDESC 4
359 /** A connection to a directory server: download one or more network-status
360 * objects */
361 #define DIR_PURPOSE_FETCH_NETWORKSTATUS 5
362 /** A connection to a directory server: download one or more server
363 * descriptors. */
364 #define DIR_PURPOSE_FETCH_SERVERDESC 6
365 /** A connection to a directory server: download one or more extra-info
366 * documents. */
367 #define DIR_PURPOSE_FETCH_EXTRAINFO 7
368 /** A connection to a directory server: upload a server descriptor. */
369 #define DIR_PURPOSE_UPLOAD_DIR 8
370 /** A connection to a directory server: upload a rendezvous
371 * descriptor. */
372 #define DIR_PURPOSE_UPLOAD_RENDDESC 9
373 /** Purpose for connection at a directory server. */
374 #define DIR_PURPOSE_SERVER 10
375 #define _DIR_PURPOSE_MAX 10
377 #define _EXIT_PURPOSE_MIN 1
378 /** This exit stream wants to do an ordinary connect. */
379 #define EXIT_PURPOSE_CONNECT 1
380 /** This exit stream wants to do a resolve (either normal or reverse). */
381 #define EXIT_PURPOSE_RESOLVE 2
382 #define _EXIT_PURPOSE_MAX 2
384 /** Circuit state: I'm the origin, still haven't done all my handshakes. */
385 #define CIRCUIT_STATE_BUILDING 0
386 /** Circuit state: Waiting to process the onionskin. */
387 #define CIRCUIT_STATE_ONIONSKIN_PENDING 1
388 /** Circuit state: I'd like to deliver a create, but my n_conn is still
389 * connecting. */
390 #define CIRCUIT_STATE_OR_WAIT 2
391 /** Circuit state: onionskin(s) processed, ready to send/receive cells. */
392 #define CIRCUIT_STATE_OPEN 3
394 #define _CIRCUIT_PURPOSE_MIN 1
396 /* these circuits were initiated elsewhere */
397 #define _CIRCUIT_PURPOSE_OR_MIN 1
398 /** OR-side circuit purpose: normal circuit, at OR. */
399 #define CIRCUIT_PURPOSE_OR 1
400 /** OR-side circuit purpose: At OR, from Bob, waiting for intro from Alices. */
401 #define CIRCUIT_PURPOSE_INTRO_POINT 2
402 /** OR-side circuit purpose: At OR, from Alice, waiting for Bob. */
403 #define CIRCUIT_PURPOSE_REND_POINT_WAITING 3
404 /** OR-side circuit purpose: At OR, both circuits have this purpose. */
405 #define CIRCUIT_PURPOSE_REND_ESTABLISHED 4
406 #define _CIRCUIT_PURPOSE_OR_MAX 4
408 /* these circuits originate at this node */
410 /* here's how circ client-side purposes work:
411 * normal circuits are C_GENERAL.
412 * circuits that are c_introducing are either on their way to
413 * becoming open, or they are open and waiting for a
414 * suitable rendcirc before they send the intro.
415 * circuits that are c_introduce_ack_wait have sent the intro,
416 * but haven't gotten a response yet.
417 * circuits that are c_establish_rend are either on their way
418 * to becoming open, or they are open and have sent the
419 * establish_rendezvous cell but haven't received an ack.
420 * circuits that are c_rend_ready are open and have received a
421 * rend ack, but haven't heard from bob yet. if they have a
422 * buildstate->pending_final_cpath then they're expecting a
423 * cell from bob, else they're not.
424 * circuits that are c_rend_ready_intro_acked are open, and
425 * some intro circ has sent its intro and received an ack.
426 * circuits that are c_rend_joined are open, have heard from
427 * bob, and are talking to him.
429 /** Client-side circuit purpose: Normal circuit, with cpath. */
430 #define CIRCUIT_PURPOSE_C_GENERAL 5
431 /** Client-side circuit purpose: at Alice, connecting to intro point. */
432 #define CIRCUIT_PURPOSE_C_INTRODUCING 6
433 /** Client-side circuit purpose: at Alice, sent INTRODUCE1 to intro point,
434 * waiting for ACK/NAK. */
435 #define CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT 7
436 /** Client-side circuit purpose: at Alice, introduced and acked, closing. */
437 #define CIRCUIT_PURPOSE_C_INTRODUCE_ACKED 8
438 /** Client-side circuit purpose: at Alice, waiting for ack. */
439 #define CIRCUIT_PURPOSE_C_ESTABLISH_REND 9
440 /** Client-side circuit purpose: at Alice, waiting for Bob. */
441 #define CIRCUIT_PURPOSE_C_REND_READY 10
442 /** Client-side circuit purpose: at Alice, waiting for Bob, INTRODUCE
443 * has been acknowledged. */
444 #define CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED 11
445 /** Client-side circuit purpose: at Alice, rendezvous established. */
446 #define CIRCUIT_PURPOSE_C_REND_JOINED 12
448 /** Hidden-service-side circuit purpose: at Bob, waiting for introductions. */
449 #define CIRCUIT_PURPOSE_S_ESTABLISH_INTRO 13
450 /** Hidden-service-side circuit purpose: at Bob, successfully established
451 * intro. */
452 #define CIRCUIT_PURPOSE_S_INTRO 14
453 /** Hidden-service-side circuit purpose: at Bob, connecting to rend point. */
454 #define CIRCUIT_PURPOSE_S_CONNECT_REND 15
455 /** Hidden-service-side circuit purpose: at Bob, rendezvous established. */
456 #define CIRCUIT_PURPOSE_S_REND_JOINED 16
457 /** A testing circuit; not meant to be used for actual traffic. */
458 #define CIRCUIT_PURPOSE_TESTING 17
459 /** A controller made this circuit and Tor should not use it. */
460 #define CIRCUIT_PURPOSE_CONTROLLER 18
461 #define _CIRCUIT_PURPOSE_MAX 18
463 /** True iff the circuit purpose <b>p</b> is for a circuit that
464 * originated at this node. */
465 #define CIRCUIT_PURPOSE_IS_ORIGIN(p) ((p)>_CIRCUIT_PURPOSE_OR_MAX)
466 #define CIRCUIT_IS_ORIGIN(c) (CIRCUIT_PURPOSE_IS_ORIGIN((c)->purpose))
468 /** How many circuits do we want simultaneously in-progress to handle
469 * a given stream? */
470 #define MIN_CIRCUITS_HANDLING_STREAM 2
472 #define RELAY_COMMAND_BEGIN 1
473 #define RELAY_COMMAND_DATA 2
474 #define RELAY_COMMAND_END 3
475 #define RELAY_COMMAND_CONNECTED 4
476 #define RELAY_COMMAND_SENDME 5
477 #define RELAY_COMMAND_EXTEND 6
478 #define RELAY_COMMAND_EXTENDED 7
479 #define RELAY_COMMAND_TRUNCATE 8
480 #define RELAY_COMMAND_TRUNCATED 9
481 #define RELAY_COMMAND_DROP 10
482 #define RELAY_COMMAND_RESOLVE 11
483 #define RELAY_COMMAND_RESOLVED 12
484 #define RELAY_COMMAND_BEGIN_DIR 13
486 #define RELAY_COMMAND_ESTABLISH_INTRO 32
487 #define RELAY_COMMAND_ESTABLISH_RENDEZVOUS 33
488 #define RELAY_COMMAND_INTRODUCE1 34
489 #define RELAY_COMMAND_INTRODUCE2 35
490 #define RELAY_COMMAND_RENDEZVOUS1 36
491 #define RELAY_COMMAND_RENDEZVOUS2 37
492 #define RELAY_COMMAND_INTRO_ESTABLISHED 38
493 #define RELAY_COMMAND_RENDEZVOUS_ESTABLISHED 39
494 #define RELAY_COMMAND_INTRODUCE_ACK 40
496 /* Reasons why an OR connection is closed */
497 #define END_OR_CONN_REASON_DONE 1
498 #define END_OR_CONN_REASON_TCP_REFUSED 2
499 #define END_OR_CONN_REASON_OR_IDENTITY 3
500 #define END_OR_CONN_REASON_TLS_CONNRESET 4 /* tls connection reset by peer */
501 #define END_OR_CONN_REASON_TLS_TIMEOUT 5
502 #define END_OR_CONN_REASON_TLS_NO_ROUTE 6 /* no route to host/net */
503 #define END_OR_CONN_REASON_TLS_IO_ERROR 7 /* tls read/write error */
504 #define END_OR_CONN_REASON_TLS_MISC 8
506 /* Reasons why we (or a remote OR) might close a stream. See tor-spec.txt for
507 * documentation of these. */
508 #define END_STREAM_REASON_MISC 1
509 #define END_STREAM_REASON_RESOLVEFAILED 2
510 #define END_STREAM_REASON_CONNECTREFUSED 3
511 #define END_STREAM_REASON_EXITPOLICY 4
512 #define END_STREAM_REASON_DESTROY 5
513 #define END_STREAM_REASON_DONE 6
514 #define END_STREAM_REASON_TIMEOUT 7
515 /* 8 is unallocated for historical reasons. */
516 #define END_STREAM_REASON_HIBERNATING 9
517 #define END_STREAM_REASON_INTERNAL 10
518 #define END_STREAM_REASON_RESOURCELIMIT 11
519 #define END_STREAM_REASON_CONNRESET 12
520 #define END_STREAM_REASON_TORPROTOCOL 13
521 #define END_STREAM_REASON_NOTDIRECTORY 14
523 /* These high-numbered end reasons are not part of the official spec,
524 * and are not intended to be put in relay end cells. They are here
525 * to be more informative when sending back socks replies to the
526 * application. */
527 /* XXXX 256 is no longer used; feel free to reuse it. */
528 /** We were unable to attach the connection to any circuit at all. */
529 /* XXXX the ways we use this one don't make a lot of sense. */
530 #define END_STREAM_REASON_CANT_ATTACH 257
531 /** We can't connect to any directories at all, so we killed our streams
532 * before they can time out. */
533 #define END_STREAM_REASON_NET_UNREACHABLE 258
534 /** This is a SOCKS connection, and the client used (or misused) the SOCKS
535 * protocol in a way we couldn't handle. */
536 #define END_STREAM_REASON_SOCKSPROTOCOL 259
537 /** This is a transparent proxy connection, but we can't extract the original
538 * target address:port. */
539 #define END_STREAM_REASON_CANT_FETCH_ORIG_DEST 260
540 /** This is a connection on the NATD port, and the destination IP:Port was
541 * either ill-formed or out-of-range. */
542 #define END_STREAM_REASON_INVALID_NATD_DEST 261
544 /** Bitwise-and this value with endreason to mask out all flags. */
545 #define END_STREAM_REASON_MASK 511
547 /** Bitwise-or this with the argument to control_event_stream_status
548 * to indicate that the reason came from an END cell. */
549 #define END_STREAM_REASON_FLAG_REMOTE 512
550 /** Bitwise-or this with the argument to control_event_stream_status
551 * to indicate that we already sent a CLOSED stream event. */
552 #define END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED 1024
553 /** Bitwise-or this with endreason to indicate that we already sent
554 * a socks reply, and no further reply needs to be sent from
555 * connection_mark_unattached_ap(). */
556 #define END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED 2048
558 /** Reason for remapping an AP connection's address: we have a cached
559 * answer. */
560 #define REMAP_STREAM_SOURCE_CACHE 1
561 /** Reason for remapping an AP connection's address: the exit node told us an
562 * answer. */
563 #define REMAP_STREAM_SOURCE_EXIT 2
565 /* 'type' values to use in RESOLVED cells. Specified in tor-spec.txt. */
566 #define RESOLVED_TYPE_HOSTNAME 0
567 #define RESOLVED_TYPE_IPV4 4
568 #define RESOLVED_TYPE_IPV6 6
569 #define RESOLVED_TYPE_ERROR_TRANSIENT 0xF0
570 #define RESOLVED_TYPE_ERROR 0xF1
572 /* Negative reasons are internal: we never send them in a DESTROY or TRUNCATE
573 * call; they only go to the controller for tracking */
574 /** We couldn't build a path for this circuit. */
575 #define END_CIRC_REASON_NOPATH -2
576 /** Catch-all "other" reason for closing origin circuits. */
577 #define END_CIRC_AT_ORIGIN -1
579 /* Reasons why we (or a remote OR) might close a circuit. See tor-spec.txt for
580 * documentation of these. */
581 #define _END_CIRC_REASON_MIN 0
582 #define END_CIRC_REASON_NONE 0
583 #define END_CIRC_REASON_TORPROTOCOL 1
584 #define END_CIRC_REASON_INTERNAL 2
585 #define END_CIRC_REASON_REQUESTED 3
586 #define END_CIRC_REASON_HIBERNATING 4
587 #define END_CIRC_REASON_RESOURCELIMIT 5
588 #define END_CIRC_REASON_CONNECTFAILED 6
589 #define END_CIRC_REASON_OR_IDENTITY 7
590 #define END_CIRC_REASON_OR_CONN_CLOSED 8
591 #define END_CIRC_REASON_FINISHED 9
592 #define END_CIRC_REASON_TIMEOUT 10
593 #define END_CIRC_REASON_DESTROYED 11
594 #define END_CIRC_REASON_NOSUCHSERVICE 12
595 #define _END_CIRC_REASON_MAX 12
597 /* OR this with the argument to circuit_mark_for_close, or
598 * control_event_circuit_status to indicate that the reason came from a
599 * destroy or truncate cell. */
600 #define END_CIRC_REASON_FLAG_REMOTE 512
602 /** Length of 'y' portion of 'y.onion' URL. */
603 #define REND_SERVICE_ID_LEN 16
605 #define CELL_DIRECTION_IN 1
606 #define CELL_DIRECTION_OUT 2
608 #ifdef TOR_PERF
609 #define CIRCWINDOW_START 10000
610 #define CIRCWINDOW_INCREMENT 1000
611 #define STREAMWINDOW_START 5000
612 #define STREAMWINDOW_INCREMENT 500
613 #else
614 /** Initial value for both sides of a circuit transmission window when the
615 * circuit is initialized. Measured in cells. */
616 #define CIRCWINDOW_START 1000
617 /** Amount to increment a circuit window when we get a circuit SENDME. */
618 #define CIRCWINDOW_INCREMENT 100
619 /** Initial value on both sides of a stream transmission window when the
620 * stream is initialized. Measured in cells. */
621 #define STREAMWINDOW_START 500
622 /** Amount to increment a stream window when we get a stream SENDME. */
623 #define STREAMWINDOW_INCREMENT 50
624 #endif
626 /* cell commands */
627 #define CELL_PADDING 0
628 #define CELL_CREATE 1
629 #define CELL_CREATED 2
630 #define CELL_RELAY 3
631 #define CELL_DESTROY 4
632 #define CELL_CREATE_FAST 5
633 #define CELL_CREATED_FAST 6
635 /** How long to test reachability before complaining to the user. */
636 #define TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT (20*60)
638 /** Legal characters in a nickname. */
639 #define LEGAL_NICKNAME_CHARACTERS \
640 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
642 /** Name to use in client TLS certificates if no nickname is given. */
643 #define DEFAULT_CLIENT_NICKNAME "client"
645 /** Number of bytes in a SOCKS4 header. */
646 #define SOCKS4_NETWORK_LEN 8
648 /** Specified SOCKS5 status codes. */
649 typedef enum {
650 SOCKS5_SUCCEEDED = 0x00,
651 SOCKS5_GENERAL_ERROR = 0x01,
652 SOCKS5_NOT_ALLOWED = 0x02,
653 SOCKS5_NET_UNREACHABLE = 0x03,
654 SOCKS5_HOST_UNREACHABLE = 0x04,
655 SOCKS5_CONNECTION_REFUSED = 0x05,
656 SOCKS5_TTL_EXPIRED = 0x06,
657 SOCKS5_COMMAND_NOT_SUPPORTED = 0x07,
658 SOCKS5_ADDRESS_TYPE_NOT_SUPPORTED = 0x08,
659 } socks5_reply_status_t;
662 * Relay payload:
663 * Relay command [1 byte]
664 * Recognized [2 bytes]
665 * Stream ID [2 bytes]
666 * Partial SHA-1 [4 bytes]
667 * Length [2 bytes]
668 * Relay payload [498 bytes]
671 /** Number of bytes in a cell, minus cell header. */
672 #define CELL_PAYLOAD_SIZE 509
673 /** Number of bytes in a cell transmitted over the network. */
674 #define CELL_NETWORK_SIZE 512
676 /** Number of bytes in a relay cell's header (not including general cell
677 * header). */
678 #define RELAY_HEADER_SIZE (1+2+2+4+2)
679 /** Largest number of bytes that can fit in a relay cell payload. */
680 #define RELAY_PAYLOAD_SIZE (CELL_PAYLOAD_SIZE-RELAY_HEADER_SIZE)
682 typedef struct cell_t cell_t;
683 /** Parsed onion routing cell. All communication between nodes
684 * is via cells. */
685 struct cell_t {
686 uint16_t circ_id; /**< Circuit which received the cell. */
687 uint8_t command; /**< Type of the cell: one of PADDING, CREATE, RELAY,
688 * or DESTROY. */
689 char payload[CELL_PAYLOAD_SIZE]; /**< Cell body. */
692 typedef struct packed_cell_t packed_cell_t;
693 /** A cell as packed for writing to the network. */
694 struct packed_cell_t {
695 struct packed_cell_t *next; /**< Next cell queued on this circuit. */
696 char body[CELL_NETWORK_SIZE]; /**< Cell as packed for network. */
699 /** A queue of cells on a circuit, waiting to be added to the
700 * or_connection_t's outbuf. */
701 typedef struct cell_queue_t {
702 packed_cell_t *head; /**< The first cell, or NULL if the queue is empty. */
703 packed_cell_t *tail; /**< The last cell, or NULL if the queue is empty. */
704 int n; /**< The number of cells in the queue. */
705 } cell_queue_t;
707 /** Beginning of a RELAY cell payload. */
708 typedef struct {
709 uint8_t command; /**< The end-to-end relay command. */
710 uint16_t recognized; /**< Used to tell whether cell is for us. */
711 uint16_t stream_id; /**< Which stream is this cell associated with? */
712 char integrity[4]; /**< Used to tell whether cell is corrupted. */
713 uint16_t length; /**< How long is the payload body? */
714 } relay_header_t;
716 typedef struct buf_t buf_t;
717 typedef struct socks_request_t socks_request_t;
719 /* Values for connection_t.magic: used to make sure that downcasts (casts from
720 * connection_t to foo_connection_t) are safe. */
721 #define BASE_CONNECTION_MAGIC 0x7C3C304Eu
722 #define OR_CONNECTION_MAGIC 0x7D31FF03u
723 #define EDGE_CONNECTION_MAGIC 0xF0374013u
724 #define DIR_CONNECTION_MAGIC 0x9988ffeeu
725 #define CONTROL_CONNECTION_MAGIC 0x8abc765du
727 /** Description of a connection to another host or process, and associated
728 * data.
730 * A connection is named based on what it's connected to -- an "OR
731 * connection" has a Tor node on the other end, an "exit
732 * connection" has a website or other server on the other end, and an
733 * "AP connection" has an application proxy (and thus a user) on the
734 * other end.
736 * Every connection has a type and a state. Connections never change
737 * their type, but can go through many state changes in their lifetime.
739 * Every connection has two associated input and output buffers.
740 * Listeners don't use them. For non-listener connections, incoming
741 * data is appended to conn->inbuf, and outgoing data is taken from
742 * conn->outbuf. Connections differ primarily in the functions called
743 * to fill and drain these buffers.
745 typedef struct connection_t {
746 uint32_t magic; /**< For memory debugging: must equal one of
747 * *_CONNECTION_MAGIC. */
749 uint8_t type; /**< What kind of connection is this? */
750 uint8_t state; /**< Current state of this connection. */
751 uint8_t purpose; /**< Only used for DIR and EXIT types currently. */
753 /* The next fields are all one-bit booleans. Some are only applicable
754 * to connection subtypes, but we hold them here anyway, to save space.
755 * (Currently, they all fit into a single byte.) */
756 unsigned read_blocked_on_bw:1; /**< Boolean: should we start reading again
757 * once the bandwidth throttler allows it? */
758 unsigned write_blocked_on_bw:1; /**< Boolean: should we start writing again
759 * once the bandwidth throttler allows reads? */
760 unsigned hold_open_until_flushed:1; /**< Despite this connection's being
761 * marked for close, do we flush it
762 * before closing it? */
763 unsigned int inbuf_reached_eof:1; /**< Boolean: did read() return 0 on this
764 * conn? */
765 unsigned int edge_has_sent_end:1; /**< For debugging; only used on edge
766 * connections. Set once we've set the stream end,
767 * and check in connection_about_to_close_connection().
769 /** Edge connections only: true if we've blocked writing until the
770 * circuit has fewer queued cells. */
771 unsigned int edge_blocked_on_circ:1;
772 /** Used for OR conns that shouldn't get any new circs attached to them. */
773 unsigned int or_is_obsolete:1;
774 /** For AP connections only. If 1, and we fail to reach the chosen exit,
775 * stop requiring it. */
776 unsigned int chosen_exit_optional:1;
778 int s; /**< Our socket; -1 if this connection is closed, or has no
779 * socket. */
780 int conn_array_index; /**< Index into the global connection array. */
781 struct event *read_event; /**< Libevent event structure. */
782 struct event *write_event; /**< Libevent event structure. */
783 buf_t *inbuf; /**< Buffer holding data read over this connection. */
784 buf_t *outbuf; /**< Buffer holding data to write over this connection. */
785 size_t outbuf_flushlen; /**< How much data should we try to flush from the
786 * outbuf? */
787 time_t timestamp_lastread; /**< When was the last time libevent said we could
788 * read? */
789 time_t timestamp_lastwritten; /**< When was the last time libevent said we
790 * could write? */
791 time_t timestamp_created; /**< When was this connection_t created? */
793 uint32_t addr; /**< IP of the other side of the connection; used to identify
794 * routers, along with port. */
795 uint16_t port; /**< If non-zero, port on the other end
796 * of the connection. */
797 uint16_t marked_for_close; /**< Should we close this conn on the next
798 * iteration of the main loop? (If true, holds
799 * the line number where this connection was
800 * marked.) */
801 const char *marked_for_close_file; /**< For debugging: in which file were
802 * we marked for close? */
803 char *address; /**< FQDN (or IP) of the guy on the other end.
804 * strdup into this, because free_connection frees it. */
805 /** Annother connection that's connected to this one in lieu of a socket. */
806 struct connection_t *linked_conn;
807 /* XXXX020 NM move these up to the other 1-bit flags. */
808 unsigned int linked:1; /**< True if there is, or has been, a linked_conn. */
809 /** True iff we'd like to be notified about read events from the
810 * linked conn. */
811 unsigned int reading_from_linked_conn:1;
812 /** True iff we're willing to write to the linked conn. */
813 unsigned int writing_to_linked_conn:1;
814 /** True iff we're currently able to read on the linked conn, and our
815 * read_event should be made active with libevent. */
816 unsigned int active_on_link:1;
818 /* XXXX020 move this into a subtype!!! */
819 struct evdns_server_port *dns_server_port;
821 } connection_t;
823 /** Subtype of connection_t for an "OR connection" -- that is, one that speaks
824 * cells over TLS. */
825 typedef struct or_connection_t {
826 connection_t _base;
828 /** Hash of the public RSA key for the other side's identity key, or zeroes
829 * if the other side hasn't shown us a valid identity key. */
830 char identity_digest[DIGEST_LEN];
831 char *nickname; /**< Nickname of OR on other side (if any). */
833 tor_tls_t *tls; /**< TLS connection state. */
834 int tls_error; /**< Last tor_tls error code. */
835 /** Whether we are using this conn for any client traffic. If we're
836 * not, we can rate limit it further. */
837 uint8_t client_used:1;
839 circ_id_type_t circ_id_type:2; /**< When we send CREATE cells along this
840 * connection, which half of the space should
841 * we use? */
842 uint16_t next_circ_id; /**< Which circ_id do we try to use next on
843 * this connection? This is always in the
844 * range 0..1<<15-1. */
846 time_t timestamp_lastempty; /**< When was the outbuf last completely empty?*/
848 /* bandwidth* and read_bucket only used by ORs in OPEN state: */
849 int bandwidthrate; /**< Bytes/s added to the bucket. (OPEN ORs only.) */
850 int bandwidthburst; /**< Max bucket size for this conn. (OPEN ORs only.) */
851 int read_bucket; /**< When this hits 0, stop receiving. Every second we
852 * add 'bandwidthrate' to this, capping it at
853 * bandwidthburst. (OPEN ORs only) */
854 int n_circuits; /**< How many circuits use this connection as p_conn or
855 * n_conn ? */
857 /** Double-linked ring of circuits with queued cells waiting for room to
858 * free up on this connection's outbuf. Every time we pull cells from a
859 * circuit, we advance this pointer to the next circuit in the ring. */
860 struct circuit_t *active_circuits;
861 struct or_connection_t *next_with_same_id; /**< Next connection with same
862 * identity digest as this one. */
863 } or_connection_t;
865 /** Subtype of connection_t for an "edge connection" -- that is, a socks (ap)
866 * connection, or an exit. */
867 typedef struct edge_connection_t {
868 connection_t _base;
870 struct edge_connection_t *next_stream; /**< Points to the next stream at this
871 * edge, if any */
872 struct crypt_path_t *cpath_layer; /**< A pointer to which node in the circ
873 * this conn exits at. */
874 int package_window; /**< How many more relay cells can I send into the
875 * circuit? */
876 int deliver_window; /**< How many more relay cells can end at me? */
878 /** Nickname of planned exit node -- used with .exit support. */
879 char *chosen_exit_name;
881 socks_request_t *socks_request; /**< SOCKS structure describing request (AP
882 * only.) */
883 struct circuit_t *on_circuit; /**< The circuit (if any) that this edge
884 * connection is using. */
886 uint32_t address_ttl; /**< TTL for address-to-addr mapping on exit
887 * connection. Exit connections only. */
889 uint16_t stream_id; /**< The stream ID used for this edge connection on its
890 * circuit */
892 /** The reason why this connection is closing; passed to the controller. */
893 uint16_t end_reason;
895 /** Quasi-global identifier for this connection; used for control.c */
896 /* XXXX NM This can get re-used after 2**32 streams */
897 uint32_t global_identifier;
899 /** Bytes read since last call to control_event_stream_bandwidth_used() */
900 uint32_t n_read;
902 /** Bytes written since last call to control_event_stream_bandwidth_used() */
903 uint32_t n_written;
905 char rend_query[REND_SERVICE_ID_LEN+1]; /**< What rendezvous service are we
906 * querying for? (AP only) */
908 /** Number of times we've reassigned this application connection to
909 * a new circuit. We keep track because the timeout is longer if we've
910 * already retried several times. */
911 uint8_t num_socks_retries;
913 /** If this is a DNSPort connection, this field holds the pending DNS
914 * request that we're going to try to answer. */
915 struct evdns_server_request *dns_server_request;
917 } edge_connection_t;
919 /** Subtype of connection_t for an "directory connection" -- that is, an HTTP
920 * connection to retrieve or serve directory material. */
921 typedef struct dir_connection_t {
922 connection_t _base;
924 char *requested_resource; /**< Which 'resource' did we ask the directory
925 * for? */
926 unsigned int dirconn_direct:1; /**< Is this dirconn direct, or via Tor? */
928 /* Used only for server sides of some dir connections, to implement
929 * "spooling" of directory material to the outbuf. Otherwise, we'd have
930 * to append everything to the outbuf in one enormous chunk. */
931 /** What exactly are we spooling right now? */
932 enum {
933 DIR_SPOOL_NONE=0, DIR_SPOOL_SERVER_BY_DIGEST, DIR_SPOOL_SERVER_BY_FP,
934 DIR_SPOOL_EXTRA_BY_DIGEST, DIR_SPOOL_EXTRA_BY_FP,
935 DIR_SPOOL_CACHED_DIR, DIR_SPOOL_NETWORKSTATUS
936 } dir_spool_src : 3;
937 /** List of fingerprints for networkstatuses or desriptors to be spooled. */
938 smartlist_t *fingerprint_stack;
939 /** A cached_dir_t object that we're currently spooling out */
940 struct cached_dir_t *cached_dir;
941 /** The current offset into cached_dir. */
942 off_t cached_dir_offset;
943 /** The zlib object doing on-the-fly compression for spooled data. */
944 tor_zlib_state_t *zlib_state;
946 char rend_query[REND_SERVICE_ID_LEN+1]; /**< What rendezvous service are we
947 * querying for? */
949 char identity_digest[DIGEST_LEN]; /**< Hash of the public RSA key for
950 * the directory server's signing key. */
952 } dir_connection_t;
954 /** Subtype of connection_t for an connection to a controller. */
955 typedef struct control_connection_t {
956 connection_t _base;
958 uint32_t event_mask; /**< Bitfield: which events does this controller
959 * care about? */
960 unsigned int use_long_names:1; /**< True if we should use long nicknames
961 * on this (v1) connection. Only settable
962 * via v1 controllers. */
963 /** For control connections only. If set, we send extended info with control
964 * events as appropriate. */
965 unsigned int use_extended_events:1;
967 uint32_t incoming_cmd_len;
968 uint32_t incoming_cmd_cur_len;
969 char *incoming_cmd;
970 /* Used only by control v0 connections */
971 uint16_t incoming_cmd_type;
972 } control_connection_t;
974 /** Cast a connection_t subtype pointer to a connection_t **/
975 #define TO_CONN(c) (&(((c)->_base)))
976 /** Helper macro: Given a pointer to to._base, of type from*, return &to. */
977 #define DOWNCAST(to, ptr) ((to*)SUBTYPE_P(ptr, to, _base))
979 /** Convert a connection_t* to an or_connection_t*; assert if the cast is
980 * invalid. */
981 static or_connection_t *TO_OR_CONN(connection_t *);
982 /** Convert a connection_t* to a dir_connection_t*; assert if the cast is
983 * invalid. */
984 static dir_connection_t *TO_DIR_CONN(connection_t *);
985 /** Convert a connection_t* to an edge_connection_t*; assert if the cast is
986 * invalid. */
987 static edge_connection_t *TO_EDGE_CONN(connection_t *);
988 /** Convert a connection_t* to an control_connection_t*; assert if the cast is
989 * invalid. */
990 static control_connection_t *TO_CONTROL_CONN(connection_t *);
992 static INLINE or_connection_t *TO_OR_CONN(connection_t *c)
994 tor_assert(c->magic == OR_CONNECTION_MAGIC);
995 return DOWNCAST(or_connection_t, c);
997 static INLINE dir_connection_t *TO_DIR_CONN(connection_t *c)
999 tor_assert(c->magic == DIR_CONNECTION_MAGIC);
1000 return DOWNCAST(dir_connection_t, c);
1002 static INLINE edge_connection_t *TO_EDGE_CONN(connection_t *c)
1004 tor_assert(c->magic == EDGE_CONNECTION_MAGIC);
1005 return DOWNCAST(edge_connection_t, c);
1007 static INLINE control_connection_t *TO_CONTROL_CONN(connection_t *c)
1009 tor_assert(c->magic == CONTROL_CONNECTION_MAGIC);
1010 return DOWNCAST(control_connection_t, c);
1013 typedef enum {
1014 ADDR_POLICY_ACCEPT=1,
1015 ADDR_POLICY_REJECT=2,
1016 } addr_policy_action_t;
1018 /** A linked list of policy rules */
1019 typedef struct addr_policy_t {
1020 addr_policy_action_t policy_type; /**< What to do when the policy matches.*/
1021 char *string; /**< String representation of this rule. */
1022 uint32_t addr; /**< Base address to accept or reject. */
1023 uint32_t msk; /**< Accept/reject all addresses <b>a</b> such that
1024 * a &amp; msk == <b>addr</b> &amp; msk . */
1025 uint16_t prt_min; /**< Lowest port number to accept/reject. */
1026 uint16_t prt_max; /**< Highest port number to accept/reject. */
1028 struct addr_policy_t *next; /**< Next rule in list. */
1029 } addr_policy_t;
1031 /** A cached_dir_t represents a cacheable directory object, along with its
1032 * compressed form. */
1033 typedef struct cached_dir_t {
1034 char *dir; /**< Contents of this object */
1035 char *dir_z; /**< Compressed contents of this object. */
1036 size_t dir_len; /**< Length of <b>dir</b> */
1037 size_t dir_z_len; /**< Length of <b>dir_z</b> */
1038 time_t published; /**< When was this object published */
1039 int refcnt; /**< Reference count for this cached_dir_t. */
1040 } cached_dir_t;
1042 /** Enum used to remember where a signed_descriptor_t is stored and how to
1043 * manage the memory for signed_descriptor_body. */
1044 typedef enum {
1045 /** The descriptor isn't stored on disk at all: the copy in memory is
1046 * canonical; the saved_offset field is meaningless. */
1047 SAVED_NOWHERE=0,
1048 /** The descriptor is stored in the cached_routers file: the
1049 * signed_descriptor_body is meaningless; the signed_descriptor_len and
1050 * saved_offset are used to index into the mmaped cache file. */
1051 SAVED_IN_CACHE,
1052 /** The descriptor is stored in the cached_routers.new file: the
1053 * signed_descriptor_body and saved_offset fields are both set. */
1054 /* FFFF (We could also mmap the file and grow the mmap as needed, or
1055 * lazy-load the descriptor text by using seek and read. We don't, for
1056 * now.)
1058 SAVED_IN_JOURNAL
1059 } saved_location_t;
1061 /** Information about our plans for retrying downloads for a downloadable
1062 * object. */
1063 typedef struct download_status_t {
1064 time_t next_attempt_at; /**< When should we try downloading this descriptor
1065 * again? */
1066 uint8_t n_download_failures; /**< Number of failures trying to download the
1067 * most recent descriptor. */
1068 } download_status_t;
1070 /** Information need to cache an onion router's descriptor. */
1071 typedef struct signed_descriptor_t {
1072 /** Pointer to the raw server descriptor. Not necessarily NUL-terminated.
1073 * If saved_location is SAVED_IN_CACHE, this pointer is null. */
1074 char *signed_descriptor_body;
1075 /** Length of the server descriptor. */
1076 size_t signed_descriptor_len;
1077 /** Digest of the server descriptor, computed as specified in dir-spec.txt */
1078 char signed_descriptor_digest[DIGEST_LEN];
1079 /** Identity digest of the router. */
1080 char identity_digest[DIGEST_LEN];
1081 /** Declared publication time of the descriptor */
1082 time_t published_on;
1083 /** For routerdescs only: digest of the corresponding extrainfo. */
1084 char extra_info_digest[DIGEST_LEN];
1085 /** For routerdescs only: Status of downloading the corresponding
1086 * extrainfo. */
1087 download_status_t ei_dl_status;
1088 /** Where is the descriptor saved? */
1089 saved_location_t saved_location ;
1090 /** If saved_location is SAVED_IN_CACHE or SAVED_IN_JOURNAL, the offset of
1091 * this descriptor in the corresponding file. */
1092 off_t saved_offset;
1093 /* If true, we do not ever try to save this object in the cache. */
1094 unsigned int do_not_cache : 1;
1095 /* If true, this item is meant to represent an extrainfo. */
1096 unsigned int is_extrainfo : 1;
1097 } signed_descriptor_t;
1099 /** Information about another onion router in the network. */
1100 typedef struct {
1101 signed_descriptor_t cache_info;
1102 char *address; /**< Location of OR: either a hostname or an IP address. */
1103 char *nickname; /**< Human-readable OR name. */
1105 uint32_t addr; /**< IPv4 address of OR, in host order. */
1106 uint16_t or_port; /**< Port for TLS connections. */
1107 uint16_t dir_port; /**< Port for HTTP directory connections. */
1109 crypto_pk_env_t *onion_pkey; /**< Public RSA key for onions. */
1110 crypto_pk_env_t *identity_pkey; /**< Public RSA key for signing. */
1112 char *platform; /**< What software/operating system is this OR using? */
1114 /* link info */
1115 uint32_t bandwidthrate; /**< How many bytes does this OR add to its token
1116 * bucket per second? */
1117 uint32_t bandwidthburst; /**< How large is this OR's token bucket? */
1118 /** How many bytes/s is this router known to handle? */
1119 uint32_t bandwidthcapacity;
1120 addr_policy_t *exit_policy; /**< What streams will this OR permit
1121 * to exit? */
1122 long uptime; /**< How many seconds the router claims to have been up */
1123 smartlist_t *declared_family; /**< Nicknames of router which this router
1124 * claims are its family. */
1125 char *contact_info; /**< Declared contact info for this router. */
1126 unsigned int is_hibernating:1; /**< Whether the router claims to be
1127 * hibernating */
1128 unsigned int has_old_dnsworkers:1; /**< Whether the router is using
1129 * dnsworker code. */
1130 unsigned int caches_extra_info:1; /**< Whether the router caches and serves
1131 * extrainfo documents. */
1133 /* local info */
1134 unsigned int is_running:1; /**< As far as we know, is this OR currently
1135 * running? */
1136 unsigned int is_valid:1; /**< Has a trusted dirserver validated this OR?
1137 * (For Authdir: Have we validated this OR?)
1139 unsigned int is_named:1; /**< Do we believe the nickname that this OR gives
1140 * us? */
1141 unsigned int is_fast:1; /** Do we think this is a fast OR? */
1142 unsigned int is_stable:1; /** Do we think this is a stable OR? */
1143 unsigned int is_possible_guard:1; /**< Do we think this is an OK guard? */
1144 unsigned int is_exit:1; /**< Do we think this is an OK exit? */
1145 unsigned int is_bad_exit:1; /**< Do we think this exit is censored, borked,
1146 * or otherwise nasty? */
1148 /** Tor can use this router for general positions in circuits. */
1149 #define ROUTER_PURPOSE_GENERAL 0
1150 /** Tor should avoid using this router for circuit-building. */
1151 #define ROUTER_PURPOSE_CONTROLLER 1
1152 /** Tor should use this router only for bridge positions in circuits. */
1153 #define ROUTER_PURPOSE_BRIDGE 1
1154 /*XXXX020 Should both of the above be 1? -NM */
1155 uint8_t purpose; /** What positions in a circuit is this router good for? */
1157 /* The below items are used only by authdirservers for
1158 * reachability testing. */
1159 /** When was the last time we could reach this OR? */
1160 time_t last_reachable;
1161 /** When did we start testing reachability for this OR? */
1162 time_t testing_since;
1163 /** How many times has a descriptor been posted and we believed
1164 * this router to be unreachable? We only actually warn on the third. */
1165 int num_unreachable_notifications;
1167 /** What position is this descriptor within routerlist->routers? -1 for
1168 * none. */
1169 int routerlist_index;
1170 } routerinfo_t;
1172 /** DOCDOC */
1173 #define EXTRAINFO_PURPOSE_GENERAL -1
1175 /** Information needed to keep and cache a signed extra-info document. */
1176 typedef struct extrainfo_t {
1177 signed_descriptor_t cache_info;
1178 /** The router's nickname. */
1179 char nickname[MAX_NICKNAME_LEN+1];
1180 /** True iff we found the right key for this extra-info, verified the
1181 * signature, and found it to be bad. */
1182 unsigned int bad_sig : 1;
1183 /** If present, we didn't have the right key to verify this extra-info,
1184 * so this is a copy of the signature in the document. */
1185 char *pending_sig;
1186 /** Length of pending_sig. */
1187 size_t pending_sig_len;
1188 } extrainfo_t;
1190 /** Contents of a single router entry in a network status object.
1192 typedef struct routerstatus_t {
1193 time_t published_on; /**< When was this router published? */
1194 char nickname[MAX_NICKNAME_LEN+1]; /**< The nickname this router says it
1195 * has. */
1196 char identity_digest[DIGEST_LEN]; /**< Digest of the router's identity
1197 * key. */
1198 char descriptor_digest[DIGEST_LEN]; /**< Digest of the router's most recent
1199 * descriptor. */
1200 uint32_t addr; /**< IPv4 address for this router. */
1201 uint16_t or_port; /**< OR port for this router. */
1202 uint16_t dir_port; /**< Directory port for this router. */
1203 unsigned int is_exit:1; /**< True iff this router is a good exit. */
1204 unsigned int is_stable:1; /**< True iff this router stays up a long time. */
1205 unsigned int is_fast:1; /**< True iff this router has good bandwidth. */
1206 unsigned int is_running:1; /**< True iff this router is up. */
1207 unsigned int is_named:1; /**< True iff "nickname" belongs to this router. */
1208 unsigned int is_valid:1; /**< True iff this router is validated. */
1209 unsigned int is_v2_dir:1; /**< True iff this router can serve directory
1210 * information with v2 of the directory
1211 * protocol. (All directory caches cache v1
1212 * directories.) */
1213 unsigned int is_possible_guard:1; /**< True iff this router would be a good
1214 * choice as an entry guard. */
1215 unsigned int is_bad_exit:1; /**< True iff this node is a bad choice for
1216 * an exit node. */
1217 unsigned int is_bad_directory:1; /**< Do we think this directory is junky,
1218 * underpowered, or otherwise useless? */
1219 /** True iff we know version info for this router. (i.e., a "v" entry was
1220 * included.) We'll replace all these with a big tor_version_t or a char[]
1221 * if the number of traits we care about ever becomes incredibly big. */
1222 unsigned int version_known:1;
1223 /** True iff this router is a version that supports BEGIN_DIR cells. */
1224 unsigned int version_supports_begindir:1;
1225 /** True iff this router is a version that we can post extrainfo docs to. */
1226 unsigned int version_supports_extrainfo_upload:1;
1228 /** True if we, as a directory mirror, want to download the corresponding
1229 * routerinfo from the authority who gave us this routerstatus. (That is,
1230 * if we don't have the routerinfo, and if we haven't already tried to get it
1231 * from this authority.)
1233 unsigned int need_to_mirror:1;
1234 } routerstatus_t;
1236 /** Our "local" or combined view of the info from all networkstatus objects
1237 * about a single router. */
1238 typedef struct local_routerstatus_t {
1239 /** What do we believe to be the case about this router? In this field,
1240 * descriptor_digest represents the descriptor we would most like to use for
1241 * this router. */
1242 routerstatus_t status;
1243 time_t last_dir_503_at; /**< When did this router last tell us that it
1244 * was too busy to serve directory info? */
1245 download_status_t dl_status;
1246 unsigned int name_lookup_warned:1; /**< Have we warned the user for referring
1247 * to this (unnamed) router by nickname?
1249 } local_routerstatus_t;
1251 /** How many times will we try to download a router's descriptor before giving
1252 * up? */
1253 #define MAX_ROUTERDESC_DOWNLOAD_FAILURES 8
1255 /** Contents of a (v2 or later) network status object. */
1256 typedef struct networkstatus_t {
1257 /** When did we receive the network-status document? */
1258 time_t received_on;
1260 /** What was the digest of the document? */
1261 char networkstatus_digest[DIGEST_LEN];
1263 unsigned int is_recent; /**< Is this recent enough to influence running
1264 * status? */
1266 /* These fields come from the actual network-status document.*/
1267 time_t published_on; /**< Declared publication date. */
1269 char *source_address; /**< Canonical directory server hostname. */
1270 uint32_t source_addr; /**< Canonical directory server IP. */
1271 uint16_t source_dirport; /**< Canonical directory server dirport. */
1273 unsigned int binds_names:1; /**< True iff this directory server binds
1274 * names. */
1275 unsigned int recommends_versions:1; /**< True iff this directory server
1276 * recommends client and server software
1277 * versions. */
1278 unsigned int lists_bad_exits:1; /**< True iff this directory server marks
1279 * malfunctioning exits as bad. */
1280 /** True iff this directory server marks malfunctioning directories as
1281 * bad. */
1282 unsigned int lists_bad_directories:1;
1284 char identity_digest[DIGEST_LEN]; /**< Digest of signing key. */
1285 char *contact; /**< How to contact directory admin? (may be NULL). */
1286 crypto_pk_env_t *signing_key; /**< Key used to sign this directory. */
1287 char *client_versions; /**< comma-separated list of recommended client
1288 * versions. */
1289 char *server_versions; /**< comma-separated list of recommended server
1290 * versions. */
1292 smartlist_t *entries; /**< List of routerstatus_t*. This list is kept
1293 * sorted by identity_digest. */
1294 } networkstatus_t;
1296 /** Contents of a directory of onion routers. */
1297 typedef struct {
1298 /** Map from server identity digest to a member of routers. */
1299 digestmap_t *identity_map;
1300 /** Map from server descriptor digest to a signed_descriptor_t from
1301 * routers or old_routers. */
1302 digestmap_t *desc_digest_map;
1303 /** Map from extra-info digest to an extrainfo_t. Only exists for
1304 * routers in routers or old_routers. */
1305 digestmap_t *extra_info_map;
1306 /** Map from extra-info digests to a signed_descriptor_t for a router
1307 * descriptor having that extra-info digest. Only exists for
1308 * routers in routers or old_routers. */
1309 digestmap_t *desc_by_eid_map;
1310 /** List of routerinfo_t for all currently live routers we know. */
1311 smartlist_t *routers;
1312 /** List of signed_descriptor_t for older router descriptors we're
1313 * caching. */
1314 smartlist_t *old_routers;
1315 /** Mmaped file holding server descriptors. If present, any router whose
1316 * cache_info.saved_location == SAVED_IN_CACHE is stored in this file
1317 * starting at cache_info.saved_offset */
1318 tor_mmap_t *mmap_descriptors;
1319 /** Mmaped file holding extra-info documents. */
1320 tor_mmap_t *mmap_extrainfo;
1321 } routerlist_t;
1323 /** Information on router used when extending a circuit. We don't need a
1324 * full routerinfo_t to extend: we only need addr:port:keyid to build an OR
1325 * connection, and onion_key to create the onionskin. Note that for onehop
1326 * general-purpose tunnels, the onion_key is NULL. */
1327 typedef struct extend_info_t {
1328 char nickname[MAX_HEX_NICKNAME_LEN+1]; /**< This router's nickname for
1329 * display. */
1330 char identity_digest[DIGEST_LEN]; /**< Hash of this router's identity key. */
1331 uint16_t port; /**< OR port. */
1332 uint8_t router_purpose; /**< General, controller, or bridge. */
1333 uint32_t addr; /**< IP address in host order. */
1334 crypto_pk_env_t *onion_key; /**< Current onionskin key. */
1335 } extend_info_t;
1337 /** Certificate for v3 directory protocol: binds long-term authority identity
1338 * keys to medium-term authority signing keys. */
1339 typedef struct authority_cert_t {
1340 signed_descriptor_t cache_info;
1341 crypto_pk_env_t *identity_key;
1342 crypto_pk_env_t *signing_key;
1343 time_t expires;
1344 } authority_cert_t;
1346 /** Bitfield enum type listing types of directory authority/directory
1347 * server. */
1348 typedef enum {
1349 NO_AUTHORITY = 0,
1350 V1_AUTHORITY = 1 << 0,
1351 V2_AUTHORITY = 1 << 1,
1352 V3_AUTHORITY = 1 << 2,
1353 HIDSERV_AUTHORITY = 1 << 3,
1354 BRIDGE_AUTHORITY = 1 << 4,
1355 EXTRAINFO_CACHE = 1 << 5, /* not precisely an authority type. */
1356 } authority_type_t;
1358 #define CRYPT_PATH_MAGIC 0x70127012u
1360 /** Holds accounting information for a single step in the layered encryption
1361 * performed by a circuit. Used only at the client edge of a circuit. */
1362 typedef struct crypt_path_t {
1363 uint32_t magic;
1365 /* crypto environments */
1366 /** Encryption key and counter for cells heading towards the OR at this
1367 * step. */
1368 crypto_cipher_env_t *f_crypto;
1369 /** Encryption key and counter for cells heading back from the OR at this
1370 * step. */
1371 crypto_cipher_env_t *b_crypto;
1373 /** Digest state for cells heading towards the OR at this step. */
1374 crypto_digest_env_t *f_digest; /* for integrity checking */
1375 /** Digest state for cells heading away from the OR at this step. */
1376 crypto_digest_env_t *b_digest;
1378 /** Current state of Diffie-Hellman key negotiation with the OR at this
1379 * step. */
1380 crypto_dh_env_t *dh_handshake_state;
1381 /** Current state of 'fast' (non-PK) key negotiation with the OR at this
1382 * step. Used to save CPU when TLS is already providing all the
1383 * authentication, secrecy, and integrity we need, and we're already
1384 * distinguishable from an OR.
1386 char fast_handshake_state[DIGEST_LEN];
1387 /** Negotiated key material shared with the OR at this step. */
1388 char handshake_digest[DIGEST_LEN];/* KH in tor-spec.txt */
1390 /** Information to extend to the OR at this step. */
1391 extend_info_t *extend_info;
1393 /** Is the circuit built to this step? Must be one of:
1394 * - CPATH_STATE_CLOSED (The circuit has not been extended to this step)
1395 * - CPATH_STATE_AWAITING_KEYS (We have sent an EXTEND/CREATE to this step
1396 * and not received an EXTENDED/CREATED)
1397 * - CPATH_STATE_OPEN (The circuit has been extended to this step) */
1398 uint8_t state;
1399 #define CPATH_STATE_CLOSED 0
1400 #define CPATH_STATE_AWAITING_KEYS 1
1401 #define CPATH_STATE_OPEN 2
1402 struct crypt_path_t *next; /**< Link to next crypt_path_t in the circuit.
1403 * (The list is circular, so the last node
1404 * links to the first.) */
1405 struct crypt_path_t *prev; /**< Link to previous crypt_path_t in the
1406 * circuit. */
1408 int package_window; /**< How many bytes are we allowed to originate ending
1409 * at this step? */
1410 int deliver_window; /**< How many bytes are we willing to deliver originating
1411 * at this step? */
1412 } crypt_path_t;
1414 #define CPATH_KEY_MATERIAL_LEN (20*2+16*2)
1416 #define DH_KEY_LEN DH_BYTES
1417 #define ONIONSKIN_CHALLENGE_LEN (PKCS1_OAEP_PADDING_OVERHEAD+\
1418 CIPHER_KEY_LEN+\
1419 DH_KEY_LEN)
1420 #define ONIONSKIN_REPLY_LEN (DH_KEY_LEN+DIGEST_LEN)
1421 #define REND_COOKIE_LEN DIGEST_LEN
1423 /** Information used to build a circuit. */
1424 typedef struct {
1425 /** Intended length of the final circuit. */
1426 int desired_path_len;
1427 /** How to extend to the planned exit node. */
1428 extend_info_t *chosen_exit;
1429 /** Whether every node in the circ must have adequate uptime. */
1430 int need_uptime;
1431 /** Whether every node in the circ must have adequate capacity. */
1432 int need_capacity;
1433 /** Whether the last hop was picked with exiting in mind. */
1434 int is_internal;
1435 /** Did we pick this as a one-hop tunnel (not safe for other conns)?
1436 * These are for encrypted connections that exit to this router, not
1437 * for arbitrary exits from the circuit. */
1438 int onehop_tunnel;
1439 /** The crypt_path_t to append after rendezvous: used for rendezvous. */
1440 crypt_path_t *pending_final_cpath;
1441 /** How many times has building a circuit for this task failed? */
1442 int failure_count;
1443 /** At what time should we give up on this task? */
1444 time_t expiry_time;
1445 } cpath_build_state_t;
1447 #define ORIGIN_CIRCUIT_MAGIC 0x35315243u
1448 #define OR_CIRCUIT_MAGIC 0x98ABC04Fu
1450 typedef uint16_t circid_t;
1453 * A circuit is a path over the onion routing
1454 * network. Applications can connect to one end of the circuit, and can
1455 * create exit connections at the other end of the circuit. AP and exit
1456 * connections have only one circuit associated with them (and thus these
1457 * connection types are closed when the circuit is closed), whereas
1458 * OR connections multiplex many circuits at once, and stay standing even
1459 * when there are no circuits running over them.
1461 * A circuit_t structure can fill one of two roles. First, a or_circuit_t
1462 * links two connections together: either an edge connection and an OR
1463 * connection, or two OR connections. (When joined to an OR connection, a
1464 * circuit_t affects only cells sent to a particular circID on that
1465 * connection. When joined to an edge connection, a circuit_t affects all
1466 * data.)
1468 * Second, an origin_circuit_t holds the cipher keys and state for sending data
1469 * along a given circuit. At the OP, it has a sequence of ciphers, each
1470 * of which is shared with a single OR along the circuit. Separate
1471 * ciphers are used for data going "forward" (away from the OP) and
1472 * "backward" (towards the OP). At the OR, a circuit has only two stream
1473 * ciphers: one for data going forward, and one for data going backward.
1475 typedef struct circuit_t {
1476 uint32_t magic; /**< For memory and type debugging: must equal
1477 * ORIGIN_CIRCUIT_MAGIC or OR_CIRCUIT_MAGIC. */
1479 /** Queue of cells waiting to be transmitted on n_conn. */
1480 cell_queue_t n_conn_cells;
1481 /** The OR connection that is next in this circuit. */
1482 or_connection_t *n_conn;
1483 /** The identity hash of n_conn. */
1484 char n_conn_id_digest[DIGEST_LEN];
1485 /** The circuit_id used in the next (forward) hop of this circuit. */
1486 uint16_t n_circ_id;
1487 /** The port for the OR that is next in this circuit. */
1488 uint16_t n_port;
1489 /** The IPv4 address of the OR that is next in this circuit. */
1490 uint32_t n_addr;
1492 /** True iff we are waiting for n_conn_cells to become less full before
1493 * allowing p_streams to add any more cells. (Origin circuit only.) */
1494 unsigned int streams_blocked_on_n_conn : 1;
1495 /** True iff we are waiting for p_conn_cells to become less full before
1496 * allowing n_streams to add any more cells. (OR circuit only.) */
1497 unsigned int streams_blocked_on_p_conn : 1;
1499 uint8_t state; /**< Current status of this circuit. */
1500 uint8_t purpose; /**< Why are we creating this circuit? */
1502 /** How many relay data cells can we package (read from edge streams)
1503 * on this circuit before we receive a circuit-level sendme cell asking
1504 * for more? */
1505 int package_window;
1506 /** How many relay data cells will we deliver (write to edge streams)
1507 * on this circuit? When deliver_window gets low, we send some
1508 * circuit-level sendme cells to indicate that we're willing to accept
1509 * more. */
1510 int deliver_window;
1512 /** For storage while passing to cpuworker (state
1513 * CIRCUIT_STATE_ONIONSKIN_PENDING), or while n_conn is pending
1514 * (state CIRCUIT_STATE_OR_WAIT). When defined, it is always
1515 * length ONIONSKIN_CHALLENGE_LEN. */
1516 char *onionskin;
1518 time_t timestamp_created; /**< When was this circuit created? */
1519 time_t timestamp_dirty; /**< When the circuit was first used, or 0 if the
1520 * circuit is clean. */
1522 uint16_t marked_for_close; /**< Should we close this circuit at the end of
1523 * the main loop? (If true, holds the line number
1524 * where this circuit was marked.) */
1525 const char *marked_for_close_file; /**< For debugging: in which file was this
1526 * circuit marked for close? */
1528 /** Next circuit in the doubly-linked ring of circuits waiting to add
1529 * cells to n_conn. NULL if we have no cells pending, or if we're not
1530 * linked to an OR connection. */
1531 struct circuit_t *next_active_on_n_conn;
1532 /** Previous circuit in the doubly-linked ring of circuits waiting to add
1533 * cells to n_conn. NULL if we have no cells pending, or if we're not
1534 * linked to an OR connection. */
1535 struct circuit_t *prev_active_on_n_conn;
1536 struct circuit_t *next; /**< Next circuit in linked list of all circuits. */
1537 } circuit_t;
1539 /** An origin_circuit_t holds data necessary to build and use a circuit.
1541 typedef struct origin_circuit_t {
1542 circuit_t _base;
1544 /** Linked list of AP streams (or EXIT streams if hidden service)
1545 * associated with this circuit. */
1546 edge_connection_t *p_streams;
1547 /** Build state for this circuit. It includes the intended path
1548 * length, the chosen exit router, rendezvous information, etc.
1550 cpath_build_state_t *build_state;
1551 /** The doubly-linked list of crypt_path_t entries, one per hop,
1552 * for this circuit. This includes ciphers for each hop,
1553 * integrity-checking digests for each hop, and package/delivery
1554 * windows for each hop.
1556 crypt_path_t *cpath;
1558 /** The rend_pk_digest field holds a hash of location-hidden service's
1559 * PK if purpose is S_ESTABLISH_INTRO or S_RENDEZVOUSING.
1561 char rend_pk_digest[DIGEST_LEN];
1563 /** Holds rendezvous cookie if purpose is C_ESTABLISH_REND. Filled with
1564 * zeroes otherwise.
1566 char rend_cookie[REND_COOKIE_LEN];
1569 * The rend_query field holds the y portion of y.onion (nul-terminated)
1570 * if purpose is C_INTRODUCING or C_ESTABLISH_REND, or is a C_GENERAL
1571 * for a hidden service, or is S_*.
1573 char rend_query[REND_SERVICE_ID_LEN+1];
1575 /** The next stream_id that will be tried when we're attempting to
1576 * construct a new AP stream originating at this circuit. */
1577 uint16_t next_stream_id;
1579 /** Quasi-global identifier for this circuit; used for control.c */
1580 /* XXXX NM This can get re-used after 2**32 circuits. */
1581 uint32_t global_identifier;
1583 } origin_circuit_t;
1585 /** An or_circuit_t holds information needed to implement a circuit at an
1586 * OR. */
1587 typedef struct or_circuit_t {
1588 circuit_t _base;
1590 /** Next circuit in the doubly-linked ring of circuits waiting to add
1591 * cells to p_conn. NULL if we have no cells pending, or if we're not
1592 * linked to an OR connection. */
1593 struct circuit_t *next_active_on_p_conn;
1594 /** Previous circuit in the doubly-linked ring of circuits waiting to add
1595 * cells to p_conn. NULL if we have no cells pending, or if we're not
1596 * linked to an OR connection. */
1597 struct circuit_t *prev_active_on_p_conn;
1599 /** The circuit_id used in the previous (backward) hop of this circuit. */
1600 circid_t p_circ_id;
1601 /** Queue of cells waiting to be transmitted on p_conn. */
1602 cell_queue_t p_conn_cells;
1603 /** The OR connection that is previous in this circuit. */
1604 or_connection_t *p_conn;
1605 /** Linked list of Exit streams associated with this circuit. */
1606 edge_connection_t *n_streams;
1607 /** Linked list of Exit streams associated with this circuit that are
1608 * still being resolved. */
1609 edge_connection_t *resolving_streams;
1610 /** The cipher used by intermediate hops for cells heading toward the
1611 * OP. */
1612 crypto_cipher_env_t *p_crypto;
1613 /** The cipher used by intermediate hops for cells heading away from
1614 * the OP. */
1615 crypto_cipher_env_t *n_crypto;
1617 /** The integrity-checking digest used by intermediate hops, for
1618 * cells packaged here and heading towards the OP.
1620 crypto_digest_env_t *p_digest;
1621 /** The integrity-checking digest used by intermediate hops, for
1622 * cells packaged at the OP and arriving here.
1624 crypto_digest_env_t *n_digest;
1626 /** Points to spliced circuit if purpose is REND_ESTABLISHED, and circuit
1627 * is not marked for close. */
1628 struct or_circuit_t *rend_splice;
1630 #if REND_COOKIE_LEN >= DIGEST_LEN
1631 #define REND_TOKEN_LEN REND_COOKIE_LEN
1632 #else
1633 #define REND_TOKEN_LEN DIGEST_LEN
1634 #endif
1636 /** A hash of location-hidden service's PK if purpose is INTRO_POINT, or a
1637 * rendezvous cookie if purpose is REND_POINT_WAITING. Filled with zeroes
1638 * otherwise.
1639 * ???? move to a subtype or adjunct structure? Wastes 20 bytes. -NM
1641 char rend_token[REND_TOKEN_LEN];
1643 /* ???? move to a subtype or adjunct structure? Wastes 20 bytes -NM */
1644 char handshake_digest[DIGEST_LEN]; /**< Stores KH for the handshake. */
1646 /** True iff this circuit was made with a CREATE_FAST cell. */
1647 unsigned int is_first_hop : 1;
1648 } or_circuit_t;
1650 /** Convert a circuit subtype to a circuit_t.*/
1651 #define TO_CIRCUIT(x) (&((x)->_base))
1653 /** Convert a circuit_t* to a pointer to the enclosing or_circuit_t. Asserts
1654 * if the cast is impossible. */
1655 static or_circuit_t *TO_OR_CIRCUIT(circuit_t *);
1656 /** Convert a circuit_t* to a pointer to the enclosing origin_circuit_t.
1657 * Asserts if the cast is impossible. */
1658 static origin_circuit_t *TO_ORIGIN_CIRCUIT(circuit_t *);
1660 static INLINE or_circuit_t *TO_OR_CIRCUIT(circuit_t *x)
1662 tor_assert(x->magic == OR_CIRCUIT_MAGIC);
1663 return DOWNCAST(or_circuit_t, x);
1665 static INLINE origin_circuit_t *TO_ORIGIN_CIRCUIT(circuit_t *x)
1667 tor_assert(x->magic == ORIGIN_CIRCUIT_MAGIC);
1668 return DOWNCAST(origin_circuit_t, x);
1671 #define ALLOW_INVALID_ENTRY 1
1672 #define ALLOW_INVALID_EXIT 2
1673 #define ALLOW_INVALID_MIDDLE 4
1674 #define ALLOW_INVALID_RENDEZVOUS 8
1675 #define ALLOW_INVALID_INTRODUCTION 16
1677 /** An entry specifying a set of addresses and ports that should be remapped
1678 * to another address and port before exiting this exit node. */
1679 typedef struct exit_redirect_t {
1680 uint32_t addr;
1681 uint32_t mask;
1682 uint16_t port_min;
1683 uint16_t port_max;
1685 uint32_t addr_dest;
1686 uint16_t port_dest;
1687 unsigned is_redirect:1;
1688 } exit_redirect_t;
1690 /** A linked list of lines in a config file. */
1691 typedef struct config_line_t {
1692 char *key;
1693 char *value;
1694 struct config_line_t *next;
1695 } config_line_t;
1697 /** Configuration options for a Tor process. */
1698 typedef struct {
1699 uint32_t _magic;
1701 /** What should the tor process actually do? */
1702 enum {
1703 CMD_RUN_TOR=0, CMD_LIST_FINGERPRINT, CMD_HASH_PASSWORD,
1704 CMD_VERIFY_CONFIG, CMD_RUN_UNITTESTS
1705 } command;
1706 const char *command_arg; /**< Argument for command-line option. */
1708 config_line_t *Logs; /**< New-style list of configuration lines
1709 * for logs */
1711 char *DebugLogFile; /**< Where to send verbose log messages. */
1712 char *DataDirectory; /**< OR only: where to store long-term data. */
1713 char *Nickname; /**< OR only: nickname of this onion router. */
1714 char *Address; /**< OR only: configured address for this onion router. */
1715 char *PidFile; /**< Where to store PID of Tor process. */
1717 char *ExitNodes; /**< Comma-separated list of nicknames of ORs to consider
1718 * as exits. */
1719 char *EntryNodes; /**< Comma-separated list of nicknames of ORs to consider
1720 * as entry points. */
1721 int StrictExitNodes; /**< Boolean: When none of our ExitNodes are up, do we
1722 * stop building circuits? */
1723 int StrictEntryNodes; /**< Boolean: When none of our EntryNodes are up, do we
1724 * stop building circuits? */
1725 char *ExcludeNodes; /**< Comma-separated list of nicknames of ORs not to
1726 * use in circuits. */
1728 char *RendNodes; /**< Comma-separated list of nicknames used as introduction
1729 * points. */
1730 char *RendExcludeNodes; /**< Comma-separated list of nicknames not to use
1731 * as introduction points. */
1733 /** List of "entry", "middle", "exit", "introduction", "rendezvous". */
1734 smartlist_t *AllowInvalidNodes;
1735 int _AllowInvalid; /**< Bitmask; derived from AllowInvalidNodes. */
1736 config_line_t *ExitPolicy; /**< Lists of exit policy components. */
1737 int ExitPolicyRejectPrivate; /**< Should we not exit to local addresses? */
1738 config_line_t *SocksPolicy; /**< Lists of socks policy components */
1739 config_line_t *DirPolicy; /**< Lists of dir policy components */
1740 /** Addresses to bind for listening for SOCKS connections. */
1741 config_line_t *SocksListenAddress;
1742 /** Addresses to bind for listening for transparent pf/nefilter
1743 * connections. */
1744 config_line_t *TransListenAddress;
1745 /** Addresses to bind for listening for transparent natd connections */
1746 config_line_t *NatdListenAddress;
1747 /** Addresses to bind for listening for SOCKS connections. */
1748 config_line_t *DNSListenAddress;
1749 /** Addresses to bind for listening for OR connections. */
1750 config_line_t *ORListenAddress;
1751 /** Addresses to bind for listening for directory connections. */
1752 config_line_t *DirListenAddress;
1753 /** Addresses to bind for listening for control connections. */
1754 config_line_t *ControlListenAddress;
1755 /** Local address to bind outbound sockets */
1756 char *OutboundBindAddress;
1757 /** Directory server only: which versions of
1758 * Tor should we tell users to run? */
1759 config_line_t *RecommendedVersions;
1760 config_line_t *RecommendedClientVersions;
1761 config_line_t *RecommendedServerVersions;
1762 /** Whether dirservers refuse router descriptors with private IPs. */
1763 int DirAllowPrivateAddresses;
1764 char *User; /**< Name of user to run Tor as. */
1765 char *Group; /**< Name of group to run Tor as. */
1766 int ORPort; /**< Port to listen on for OR connections. */
1767 int SocksPort; /**< Port to listen on for SOCKS connections. */
1768 /** Port to listen on for transparent pf/netfilter connections. */
1769 int TransPort;
1770 int NatdPort; /**< Port to listen on for transparent natd connections. */
1771 int ControlPort; /**< Port to listen on for control connections. */
1772 int DirPort; /**< Port to listen on for directory connections. */
1773 int DNSPort; /**< Port to listen on for DNS requests. */
1774 int AssumeReachable; /**< Whether to publish our descriptor regardless. */
1775 int AuthoritativeDir; /**< Boolean: is this an authoritative directory? */
1776 int V1AuthoritativeDir; /**< Boolean: is this an authoritative directory
1777 * for version 1 directories? */
1778 int V2AuthoritativeDir; /**< Boolean: is this an authoritative directory
1779 * for version 2 directories? */
1780 int V3AuthoritativeDir; /**< Boolean: is this an authoritative directory
1781 * for version 3 directories? */
1782 int HSAuthoritativeDir; /**< Boolean: does this an authoritative directory
1783 * handle hidden service requests? */
1784 int HSAuthorityRecordStats; /**< Boolean: does this HS authoritative
1785 * directory record statistics? */
1786 int NamingAuthoritativeDir; /**< Boolean: is this an authoritative directory
1787 * that's willing to bind names? */
1788 int VersioningAuthoritativeDir; /**< Boolean: is this an authoritative
1789 * directory that's willing to recommend
1790 * versions? */
1791 int BridgeAuthoritativeDir; /**< Boolean: is this an authoritative directory
1792 * that aggregates bridge descriptors? */
1794 int UseBridges; /**< Boolean: should we start all circuits with a bridge? */
1795 config_line_t *Bridges; /**< List of bootstrap bridge addresses. */
1797 int AvoidDiskWrites; /**< Boolean: should we never cache things to disk?
1798 * Not used yet. */
1799 int ClientOnly; /**< Boolean: should we never evolve into a server role? */
1800 /** Boolean: should we never publish a descriptor? Deprecated. */
1801 int NoPublish;
1802 /** To what authority types do we publish our descriptor? Choices are
1803 * "v1", "v2", "bridge", or "". */
1804 smartlist_t *PublishServerDescriptor;
1805 /** An authority type, derived from PublishServerDescriptor. */
1806 authority_type_t _PublishServerDescriptor;
1807 /** Boolean: do we publish hidden service descriptors to the HS auths? */
1808 int PublishHidServDescriptors;
1809 int FetchServerDescriptors; /**< Do we fetch server descriptors as normal? */
1810 int FetchHidServDescriptors; /** and hidden service descriptors? */
1811 int FetchUselessDescriptors; /**< Do we fetch non-running descriptors too? */
1812 int AllDirActionsPrivate; /**< Should every directory action be sent
1813 * through a Tor circuit? */
1815 int ConnLimit; /**< Demanded minimum number of simultaneous connections. */
1816 int _ConnLimit; /**< Maximum allowed number of simultaneous connections. */
1817 int RunAsDaemon; /**< If true, run in the background. (Unix only) */
1818 int FascistFirewall; /**< Whether to prefer ORs reachable on open ports. */
1819 smartlist_t *FirewallPorts; /**< Which ports our firewall allows
1820 * (strings). */
1821 config_line_t *ReachableAddresses; /**< IP:ports our firewall allows. */
1822 config_line_t *ReachableORAddresses; /**< IP:ports for OR conns. */
1823 config_line_t *ReachableDirAddresses; /**< IP:ports for Dir conns. */
1825 /** Application ports that require all nodes in circ to have sufficient
1826 * uptime. */
1827 smartlist_t *LongLivedPorts;
1828 /** Should we try to reuse the same exit node for a given host */
1829 smartlist_t *TrackHostExits;
1830 int TrackHostExitsExpire; /**< Number of seconds until we expire an
1831 * addressmap */
1832 config_line_t *AddressMap; /**< List of address map directives. */
1833 int AutomapHostsOnResolve; /**< If true, when we get a resolve request for a
1834 * hostname ending with one of the suffixes in
1835 * <b>AutomapHostsSuffixes</b>, map it to a
1836 * virtual address. */
1837 smartlist_t *AutomapHostsSuffixes; /**< List of suffixes for
1838 * <b>AutomapHostsOnResolve</b>. */
1839 int RendPostPeriod; /**< How often do we post each rendezvous service
1840 * descriptor? Remember to publish them independently. */
1841 int KeepalivePeriod; /**< How often do we send padding cells to keep
1842 * connections alive? */
1843 int SocksTimeout; /**< How long do we let a socks connection wait
1844 * unattached before we fail it? */
1845 int CircuitBuildTimeout; /**< Cull non-open circuits that were born
1846 * at least this many seconds ago. */
1847 int CircuitIdleTimeout; /**< Cull open clean circuits that were born
1848 * at least this many seconds ago. */
1849 int MaxOnionsPending; /**< How many circuit CREATE requests do we allow
1850 * to wait simultaneously before we start dropping
1851 * them? */
1852 int NewCircuitPeriod; /**< How long do we use a circuit before building
1853 * a new one? */
1854 int MaxCircuitDirtiness; /**< Never use circs that were first used more than
1855 this interval ago. */
1856 uint64_t BandwidthRate; /**< How much bandwidth, on average, are we willing
1857 * to use in a second? */
1858 uint64_t BandwidthBurst; /**< How much bandwidth, at maximum, are we willing
1859 * to use in a second? */
1860 uint64_t MaxAdvertisedBandwidth; /**< How much bandwidth are we willing to
1861 * tell people we have? */
1862 uint64_t RelayBandwidthRate; /**< How much bandwidth, on average, are we
1863 * willing to use for all relayed conns? */
1864 uint64_t RelayBandwidthBurst; /**< How much bandwidth, at maximum, will we
1865 * use in a second for all relayed conns? */
1866 int NumCpus; /**< How many CPUs should we try to use? */
1867 int RunTesting; /**< If true, create testing circuits to measure how well the
1868 * other ORs are running. */
1869 char *TestVia; /**< When reachability testing, use these as middle hop. */
1870 config_line_t *RendConfigLines; /**< List of configuration lines
1871 * for rendezvous services. */
1872 char *ContactInfo; /**< Contact info to be published in the directory */
1874 char *HttpProxy; /**< hostname[:port] to use as http proxy, if any */
1875 uint32_t HttpProxyAddr; /**< Parsed IPv4 addr for http proxy, if any */
1876 uint16_t HttpProxyPort; /**< Parsed port for http proxy, if any */
1877 char *HttpProxyAuthenticator; /**< username:password string, if any */
1879 char *HttpsProxy; /**< hostname[:port] to use as https proxy, if any */
1880 uint32_t HttpsProxyAddr; /**< Parsed IPv4 addr for https proxy, if any */
1881 uint16_t HttpsProxyPort; /**< Parsed port for https proxy, if any */
1882 char *HttpsProxyAuthenticator; /**< username:password string, if any */
1884 config_line_t *DirServers; /**< List of configuration lines
1885 * for directory servers. */
1886 char *MyFamily; /**< Declared family for this OR. */
1887 config_line_t *NodeFamilies; /**< List of config lines for
1888 * node families */
1889 config_line_t *RedirectExit; /**< List of config lines for simple
1890 * addr/port redirection */
1891 smartlist_t *RedirectExitList; /**< List of exit_redirect_t */
1892 config_line_t *AuthDirBadExit; /**< Address policy for descriptors to
1893 * mark as bad exits. */
1894 config_line_t *AuthDirReject; /**< Address policy for descriptors to
1895 * reject. */
1896 config_line_t *AuthDirInvalid; /**< Address policy for descriptors to
1897 * never mark as valid. */
1898 int AuthDirListBadExits; /**< True iff we should list bad exits,
1899 * and vote for all other exits as good. */
1900 int AuthDirRejectUnlisted; /**< Boolean: do we reject all routers that
1901 * aren't named in our fingerprint file? */
1902 char *AccountingStart; /**< How long is the accounting interval, and when
1903 * does it start? */
1904 uint64_t AccountingMax; /**< How many bytes do we allow per accounting
1905 * interval before hibernation? 0 for "never
1906 * hibernate." */
1908 char *HashedControlPassword; /**< Base64-encoded hash of a password for
1909 * the control system. */
1910 int CookieAuthentication; /**< Boolean: do we enable cookie-based auth for
1911 * the control system? */
1912 int LeaveStreamsUnattached; /**< Boolean: Does Tor attach new streams to
1913 * circuits itself (0), or does it expect a controller
1914 * to cope? (1) */
1915 int DisablePredictedCircuits; /**< Boolean: does Tor preemptively
1916 * make circuits in the background (0),
1917 * or not (1)? */
1918 int ShutdownWaitLength; /**< When we get a SIGINT and we're a server, how
1919 * long do we wait before exiting? */
1920 int SafeLogging; /**< Boolean: are we allowed to log sensitive strings
1921 * such as addresses (0), or do we scrub them first (1)? */
1922 int SafeSocks; /**< Boolean: should we outright refuse application
1923 * connections that use socks4 or socks5-with-local-dns? */
1924 #define LOG_PROTOCOL_WARN (get_options()->ProtocolWarnings ? \
1925 LOG_WARN : LOG_INFO)
1926 int ProtocolWarnings; /**< Boolean: when other parties screw up the Tor
1927 * protocol, is it a warn or an info in our logs? */
1928 int TestSocks; /**< Boolean: when we get a socks connection, do we loudly
1929 * log whether it was DNS-leaking or not? */
1930 int HardwareAccel; /**< Boolean: Should we enable OpenSSL hardware
1931 * acceleration where available? */
1932 int UseEntryGuards; /**< Boolean: Do we try to enter from a smallish number
1933 * of fixed nodes? */
1934 int NumEntryGuards; /**< How many entry guards do we try to establish? */
1935 int RephistTrackTime; /**< How many seconds do we keep rephist info? */
1936 int FastFirstHopPK; /**< If Tor believes it is safe, should we save a third
1937 * of our PK time by sending CREATE_FAST cells? */
1939 addr_policy_t *reachable_addr_policy; /**< Parsed from ReachableAddresses */
1941 char *VirtualAddrNetwork; /**< Address and mask to hand out for virtual
1942 * MAPADDRESS requests. */
1943 int ServerDNSSearchDomains; /**< Boolean: If set, we don't force exit
1944 * addresses to be FQDNs, but rather search for them in
1945 * the local domains. */
1946 int ServerDNSDetectHijacking; /**< Boolean: If true, check for DNS failure
1947 * hijacking. */
1948 char *ServerDNSResolvConfFile; /**< If provided, we configure our internal
1949 * resolver from the file here rather than from
1950 * /etc/resolv.conf (Unix) or the registry (Windows). */
1951 smartlist_t *ServerDNSTestAddresses; /**< A list of addresses that definitely
1952 * should be resolveable. Used for
1953 * testing our DNS server. */
1954 int EnforceDistinctSubnets; /**< If true, don't allow multiple routers in the
1955 * same network zone in the same circuit. */
1956 int TunnelDirConns; /**< If true, use BEGIN_DIR rather than BEGIN when
1957 * possible. */
1958 int PreferTunneledDirConns; /**< If true, avoid dirservers that don't
1959 * support BEGIN_DIR, when possible. */
1960 int AllowNonRFC953Hostnames; /**< If true, we allow connections to hostnames
1961 * with weird characters. */
1962 /** If true, we try resolving hostnames with weird characters. */
1963 int ServerDNSAllowNonRFC953Hostnames;
1965 /** If true, we try to download extra-info documents (and we serve them,
1966 * if we are a cache). For authorities, this is always true. */
1967 int DownloadExtraInfo;
1969 } or_options_t;
1971 /** Persistent state for an onion router, as saved to disk. */
1972 typedef struct {
1973 uint32_t _magic;
1974 /** The time at which we next plan to write the state to the disk. Equal to
1975 * TIME_MAX if there are no saveable changes, 0 if there are changes that
1976 * should be saved right away. */
1977 time_t next_write;
1979 /** When was the state last written to disk? */
1980 time_t LastWritten;
1982 /** Fields for accounting bandwidth use. */
1983 time_t AccountingIntervalStart;
1984 uint64_t AccountingBytesReadInInterval;
1985 uint64_t AccountingBytesWrittenInInterval;
1986 int AccountingSecondsActive;
1987 uint64_t AccountingExpectedUsage;
1989 /** A list of Entry Guard-related configuration lines. */
1990 config_line_t *EntryGuards;
1992 /** These fields hold information on the history of bandwidth usage for
1993 * servers. The "Ends" fields hold the time when we last updated the
1994 * bandwidth usage. The "Interval" fields hold the granularity, in seconds,
1995 * of the entries of Values. The "Values" lists hold decimal string
1996 * representations of the number of bytes read or written in each
1997 * interval. */
1998 time_t BWHistoryReadEnds;
1999 int BWHistoryReadInterval;
2000 smartlist_t *BWHistoryReadValues;
2001 time_t BWHistoryWriteEnds;
2002 int BWHistoryWriteInterval;
2003 smartlist_t *BWHistoryWriteValues;
2005 /** What version of Tor wrote this state file? */
2006 char *TorVersion;
2008 /** Holds any unrecognized values we found in the state file, in the order
2009 * in which we found them. */
2010 config_line_t *ExtraLines;
2012 /** When did we last rotate our onion key? "0" for 'no idea'. */
2013 time_t LastRotatedOnionKey;
2014 } or_state_t;
2016 /** Change the next_write time of <b>state</b> to <b>when</b>, unless the
2017 * state is already scheduled to be written to disk earlier than <b>when</b>.
2019 static INLINE void or_state_mark_dirty(or_state_t *state, time_t when)
2021 if (state->next_write > when)
2022 state->next_write = when;
2025 #define MAX_SOCKS_REPLY_LEN 1024
2026 #define MAX_SOCKS_ADDR_LEN 256
2028 /** Please open a TCP connection to this addr:port. */
2029 #define SOCKS_COMMAND_CONNECT 0x01
2030 /** Please turn this FQDN into an IP address, privately. */
2031 #define SOCKS_COMMAND_RESOLVE 0xF0
2032 /** Please turn this IP address into an FQDN, privately. */
2033 #define SOCKS_COMMAND_RESOLVE_PTR 0xF1
2034 /** Please open an encrypted direct TCP connection to the directory port
2035 * of the Tor server specified by address:port. (In this case address:port
2036 * specifies the ORPort of the server.) */
2037 #define SOCKS_COMMAND_CONNECT_DIR 0xF2
2039 #define SOCKS_COMMAND_IS_CONNECT(c) ((c)==SOCKS_COMMAND_CONNECT || \
2040 (c)==SOCKS_COMMAND_CONNECT_DIR)
2041 #define SOCKS_COMMAND_IS_RESOLVE(c) ((c)==SOCKS_COMMAND_RESOLVE || \
2042 (c)==SOCKS_COMMAND_RESOLVE_PTR)
2044 /** State of a SOCKS request from a user to an OP. Also used to encode other
2045 * information for non-socks user request (such as those on TransPort and
2046 * DNSPort) */
2047 struct socks_request_t {
2048 /** Which version of SOCKS did the client use? One of "0, 4, 5" -- where
2049 * 0 means that no socks handshake ever took place, and this is just a
2050 * stub connection (e.g. see connection_ap_make_bridge()). */
2051 char socks_version;
2052 int command; /**< What is this stream's goal? One from the above list. */
2053 size_t replylen; /**< Length of <b>reply</b>. */
2054 char reply[MAX_SOCKS_REPLY_LEN]; /**< Write an entry into this string if
2055 * we want to specify our own socks reply,
2056 * rather than using the default socks4 or
2057 * socks5 socks reply. We use this for the
2058 * two-stage socks5 handshake.
2060 char address[MAX_SOCKS_ADDR_LEN]; /**< What address did the client ask to
2061 connect to/resolve? */
2062 uint16_t port; /**< What port did the client ask to connect to? */
2063 unsigned has_finished : 1; /**< Has the SOCKS handshake finished? Used to
2064 * make sure we send back a socks reply for
2065 * every connection. */
2068 /* all the function prototypes go here */
2070 /********************************* buffers.c ***************************/
2072 buf_t *buf_new(void);
2073 buf_t *buf_new_with_capacity(size_t size);
2074 void buf_free(buf_t *buf);
2075 void buf_clear(buf_t *buf);
2076 void buf_shrink(buf_t *buf);
2077 void buf_shrink_freelists(void);
2079 size_t buf_datalen(const buf_t *buf);
2080 size_t buf_capacity(const buf_t *buf);
2081 const char *_buf_peek_raw_buffer(const buf_t *buf);
2083 int read_to_buf(int s, size_t at_most, buf_t *buf, int *reached_eof);
2084 int read_to_buf_tls(tor_tls_t *tls, size_t at_most, buf_t *buf);
2086 int flush_buf(int s, buf_t *buf, size_t sz, size_t *buf_flushlen);
2087 int flush_buf_tls(tor_tls_t *tls, buf_t *buf, size_t sz, size_t *buf_flushlen);
2089 int write_to_buf(const char *string, size_t string_len, buf_t *buf);
2090 int write_to_buf_zlib(buf_t *buf, tor_zlib_state_t *state,
2091 const char *data, size_t data_len, int done);
2092 int move_buf_to_buf(buf_t *buf_out, buf_t *buf_in, size_t *buf_flushlen);
2093 int fetch_from_buf(char *string, size_t string_len, buf_t *buf);
2094 int fetch_from_buf_http(buf_t *buf,
2095 char **headers_out, size_t max_headerlen,
2096 char **body_out, size_t *body_used, size_t max_bodylen,
2097 int force_complete);
2098 int fetch_from_buf_socks(buf_t *buf, socks_request_t *req,
2099 int log_sockstype, int safe_socks);
2100 int fetch_from_buf_line(buf_t *buf, char *data_out, size_t *data_len);
2101 int fetch_from_buf_line_lf(buf_t *buf, char *data_out, size_t *data_len);
2103 int peek_buf_has_control0_command(buf_t *buf);
2105 void assert_buf_ok(buf_t *buf);
2107 /********************************* circuitbuild.c **********************/
2109 char *circuit_list_path(origin_circuit_t *circ, int verbose);
2110 char *circuit_list_path_for_controller(origin_circuit_t *circ);
2111 void circuit_log_path(int severity, unsigned int domain,
2112 origin_circuit_t *circ);
2113 void circuit_rep_hist_note_result(origin_circuit_t *circ);
2114 origin_circuit_t *origin_circuit_init(uint8_t purpose, int onehop_tunnel,
2115 int need_uptime,
2116 int need_capacity, int internal);
2117 origin_circuit_t *circuit_establish_circuit(uint8_t purpose,
2118 int onehop_tunnel, extend_info_t *exit,
2119 int need_uptime, int need_capacity,
2120 int internal);
2121 int circuit_handle_first_hop(origin_circuit_t *circ);
2122 void circuit_n_conn_done(or_connection_t *or_conn, int status);
2123 int inform_testing_reachability(void);
2124 int circuit_send_next_onion_skin(origin_circuit_t *circ);
2125 void circuit_note_clock_jumped(int seconds_elapsed);
2126 int circuit_extend(cell_t *cell, circuit_t *circ);
2127 int circuit_init_cpath_crypto(crypt_path_t *cpath, const char *key_data,
2128 int reverse);
2129 int circuit_finish_handshake(origin_circuit_t *circ, uint8_t cell_type,
2130 const char *reply);
2131 int circuit_truncated(origin_circuit_t *circ, crypt_path_t *layer);
2132 int onionskin_answer(or_circuit_t *circ, uint8_t cell_type,
2133 const char *payload, const char *keys);
2134 int circuit_all_predicted_ports_handled(time_t now, int *need_uptime,
2135 int *need_capacity);
2137 int circuit_append_new_exit(origin_circuit_t *circ, extend_info_t *info);
2138 int circuit_extend_to_new_exit(origin_circuit_t *circ, extend_info_t *info);
2139 void onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop);
2140 extend_info_t *extend_info_from_router(routerinfo_t *r);
2141 extend_info_t *extend_info_from_routerstatus(routerstatus_t *s);
2142 extend_info_t *extend_info_dup(extend_info_t *info);
2143 void extend_info_free(extend_info_t *info);
2144 routerinfo_t *build_state_get_exit_router(cpath_build_state_t *state);
2145 const char *build_state_get_exit_nickname(cpath_build_state_t *state);
2147 void entry_guards_compute_status(void);
2148 int entry_guard_register_connect_status(const char *digest, int succeeded,
2149 time_t now);
2150 void entry_nodes_should_be_added(void);
2151 void entry_guards_update_state(or_state_t *state);
2152 int entry_guards_parse_state(or_state_t *state, int set, char **msg);
2153 int getinfo_helper_entry_guards(control_connection_t *conn,
2154 const char *question, char **answer);
2155 void entry_guards_free_all(void);
2157 void clear_bridge_list(void);
2158 void bridge_add_from_config(uint32_t addr, uint16_t port, char *digest);
2160 /********************************* circuitlist.c ***********************/
2162 circuit_t * _circuit_get_global_list(void);
2163 const char *circuit_state_to_string(int state);
2164 void circuit_dump_by_conn(connection_t *conn, int severity);
2165 void circuit_set_p_circid_orconn(or_circuit_t *circ, uint16_t id,
2166 or_connection_t *conn);
2167 void circuit_set_n_circid_orconn(circuit_t *circ, uint16_t id,
2168 or_connection_t *conn);
2169 void circuit_set_state(circuit_t *circ, int state);
2170 void circuit_close_all_marked(void);
2171 origin_circuit_t *origin_circuit_new(void);
2172 or_circuit_t *or_circuit_new(uint16_t p_circ_id, or_connection_t *p_conn);
2173 circuit_t *circuit_get_by_circid_orconn(uint16_t circ_id,
2174 or_connection_t *conn);
2175 circuit_t *circuit_get_by_edge_conn(edge_connection_t *conn);
2176 void circuit_unlink_all_from_or_conn(or_connection_t *conn, int reason);
2177 origin_circuit_t *circuit_get_by_global_id(uint32_t id);
2178 origin_circuit_t *circuit_get_by_rend_query_and_purpose(const char *rend_query,
2179 uint8_t purpose);
2180 origin_circuit_t *circuit_get_next_by_pk_and_purpose(origin_circuit_t *start,
2181 const char *digest, uint8_t purpose);
2182 or_circuit_t *circuit_get_rendezvous(const char *cookie);
2183 or_circuit_t *circuit_get_intro_point(const char *digest);
2184 origin_circuit_t *circuit_find_to_cannibalize(uint8_t purpose,
2185 extend_info_t *info,
2186 int need_uptime,
2187 int need_capacity, int internal);
2188 void circuit_mark_all_unused_circs(void);
2189 void circuit_expire_all_dirty_circs(void);
2190 void _circuit_mark_for_close(circuit_t *circ, int reason,
2191 int line, const char *file);
2192 int circuit_get_cpath_len(origin_circuit_t *circ);
2193 crypt_path_t *circuit_get_cpath_hop(origin_circuit_t *circ, int hopnum);
2194 void circuit_get_all_pending_on_or_conn(smartlist_t *out,
2195 or_connection_t *or_conn);
2196 int circuit_count_pending_on_or_conn(or_connection_t *or_conn);
2198 #define circuit_mark_for_close(c, reason) \
2199 _circuit_mark_for_close((c), (reason), __LINE__, _SHORT_FILE_)
2201 void assert_cpath_layer_ok(const crypt_path_t *cp);
2202 void assert_circuit_ok(const circuit_t *c);
2203 void circuit_free_all(void);
2205 /********************************* circuituse.c ************************/
2207 void circuit_expire_building(time_t now);
2208 void circuit_remove_handled_ports(smartlist_t *needed_ports);
2209 int circuit_stream_is_being_handled(edge_connection_t *conn, uint16_t port,
2210 int min);
2211 void circuit_build_needed_circs(time_t now);
2212 void circuit_detach_stream(circuit_t *circ, edge_connection_t *conn);
2214 void reset_bandwidth_test(void);
2215 int circuit_enough_testing_circs(void);
2217 void circuit_has_opened(origin_circuit_t *circ);
2218 void circuit_build_failed(origin_circuit_t *circ);
2219 origin_circuit_t *circuit_launch_by_nickname(uint8_t purpose,
2220 int onehop_tunnel,
2221 const char *exit_nickname,
2222 int need_uptime, int need_capacity,
2223 int is_internal);
2224 origin_circuit_t *circuit_launch_by_extend_info(uint8_t purpose,
2225 int onehop_tunnel,
2226 extend_info_t *info,
2227 int need_uptime, int need_capacity,
2228 int is_internal);
2229 origin_circuit_t *circuit_launch_by_router(uint8_t purpose,
2230 int onehop_tunnel,
2231 routerinfo_t *exit,
2232 int need_uptime, int need_capacity,
2233 int is_internal);
2234 void circuit_reset_failure_count(int timeout);
2235 int connection_ap_handshake_attach_chosen_circuit(edge_connection_t *conn,
2236 origin_circuit_t *circ,
2237 crypt_path_t *cpath);
2238 int connection_ap_handshake_attach_circuit(edge_connection_t *conn);
2240 /********************************* command.c ***************************/
2242 void command_process_cell(cell_t *cell, or_connection_t *conn);
2244 extern uint64_t stats_n_padding_cells_processed;
2245 extern uint64_t stats_n_create_cells_processed;
2246 extern uint64_t stats_n_created_cells_processed;
2247 extern uint64_t stats_n_relay_cells_processed;
2248 extern uint64_t stats_n_destroy_cells_processed;
2250 /********************************* config.c ***************************/
2252 or_options_t *get_options(void);
2253 int set_options(or_options_t *new_val, char **msg);
2254 void config_free_all(void);
2255 const char *safe_str(const char *address);
2256 const char *escaped_safe_str(const char *address);
2257 const char *get_version(void);
2259 int config_get_lines(char *string, config_line_t **result);
2260 void config_free_lines(config_line_t *front);
2261 int options_trial_assign(config_line_t *list, int use_defaults,
2262 int clear_first, char **msg);
2263 int resolve_my_address(int warn_severity, or_options_t *options,
2264 uint32_t *addr, char **hostname_out);
2265 int is_local_IP(uint32_t ip) ATTR_PURE;
2266 void options_init(or_options_t *options);
2267 int options_init_from_torrc(int argc, char **argv);
2268 int options_init_logs(or_options_t *options, int validate_only);
2269 int option_is_recognized(const char *key);
2270 const char *option_get_canonical_name(const char *key);
2271 config_line_t *option_get_assignment(or_options_t *options,
2272 const char *key);
2273 char *options_dump(or_options_t *options, int minimal);
2274 int options_save_current(void);
2275 const char *get_torrc_fname(void);
2277 or_state_t *get_or_state(void);
2278 int or_state_load(void);
2279 int or_state_save(time_t now);
2281 int getinfo_helper_config(control_connection_t *conn,
2282 const char *question, char **answer);
2284 #ifdef CONFIG_PRIVATE
2285 /* Used only by config.c and test.c */
2286 or_options_t *options_new(void);
2287 #endif
2289 /********************************* connection.c ***************************/
2291 const char *conn_type_to_string(int type);
2292 const char *conn_state_to_string(int type, int state);
2294 connection_t *connection_new(int type);
2295 void connection_link_connections(connection_t *conn_a, connection_t *conn_b);
2296 void connection_unregister_events(connection_t *conn);
2297 void connection_free(connection_t *conn);
2298 void connection_free_all(void);
2299 void connection_about_to_close_connection(connection_t *conn);
2300 void connection_close_immediate(connection_t *conn);
2301 void _connection_mark_for_close(connection_t *conn,int line, const char *file);
2303 #define connection_mark_for_close(c) \
2304 _connection_mark_for_close((c), __LINE__, _SHORT_FILE_)
2306 void connection_expire_held_open(void);
2308 int connection_connect(connection_t *conn, const char *address, uint32_t addr,
2309 uint16_t port);
2310 int retry_all_listeners(int force, smartlist_t *replaced_conns,
2311 smartlist_t *new_conns);
2313 int connection_bucket_write_limit(connection_t *conn);
2314 int global_write_bucket_low(connection_t *conn, size_t attempt, int priority);
2315 void connection_bucket_init(void);
2316 void connection_bucket_refill(int seconds_elapsed);
2318 int connection_handle_read(connection_t *conn);
2320 int connection_fetch_from_buf(char *string, size_t len, connection_t *conn);
2322 int connection_wants_to_flush(connection_t *conn);
2323 int connection_outbuf_too_full(connection_t *conn);
2324 int connection_handle_write(connection_t *conn, int force);
2325 void _connection_write_to_buf_impl(const char *string, size_t len,
2326 connection_t *conn, int zlib);
2327 static void connection_write_to_buf(const char *string, size_t len,
2328 connection_t *conn);
2329 static void connection_write_to_buf_zlib(const char *string, size_t len,
2330 dir_connection_t *conn, int done);
2331 static INLINE void
2332 connection_write_to_buf(const char *string, size_t len, connection_t *conn)
2334 _connection_write_to_buf_impl(string, len, conn, 0);
2336 static INLINE void
2337 connection_write_to_buf_zlib(const char *string, size_t len,
2338 dir_connection_t *conn, int done)
2340 _connection_write_to_buf_impl(string, len, TO_CONN(conn), done ? -1 : 1);
2343 or_connection_t *connection_or_exact_get_by_addr_port(uint32_t addr,
2344 uint16_t port);
2345 edge_connection_t *connection_get_by_global_id(uint32_t id);
2347 connection_t *connection_get_by_type(int type);
2348 connection_t *connection_get_by_type_purpose(int type, int purpose);
2349 connection_t *connection_get_by_type_addr_port_purpose(int type, uint32_t addr,
2350 uint16_t port, int purpose);
2351 connection_t *connection_get_by_type_state(int type, int state);
2352 connection_t *connection_get_by_type_state_lastwritten(int type, int state);
2353 connection_t *connection_get_by_type_state_rendquery(int type, int state,
2354 const char *rendquery);
2356 #define connection_speaks_cells(conn) ((conn)->type == CONN_TYPE_OR)
2357 int connection_is_listener(connection_t *conn);
2358 int connection_state_is_open(connection_t *conn);
2359 int connection_state_is_connecting(connection_t *conn);
2361 char *alloc_http_authenticator(const char *authenticator);
2363 void assert_connection_ok(connection_t *conn, time_t now);
2364 int connection_or_nonopen_was_started_here(or_connection_t *conn);
2365 void connection_dump_buffer_mem_stats(int severity);
2367 /********************************* connection_edge.c *************************/
2369 #define connection_mark_unattached_ap(conn, endreason) \
2370 _connection_mark_unattached_ap((conn), (endreason), __LINE__, _SHORT_FILE_)
2372 void _connection_mark_unattached_ap(edge_connection_t *conn, int endreason,
2373 int line, const char *file);
2374 int connection_edge_reached_eof(edge_connection_t *conn);
2375 int connection_edge_process_inbuf(edge_connection_t *conn,
2376 int package_partial);
2377 int connection_edge_destroy(uint16_t circ_id, edge_connection_t *conn);
2378 int connection_edge_end(edge_connection_t *conn, char reason);
2379 int connection_edge_end_errno(edge_connection_t *conn);
2380 int connection_edge_finished_flushing(edge_connection_t *conn);
2381 int connection_edge_finished_connecting(edge_connection_t *conn);
2383 int connection_ap_handshake_send_begin(edge_connection_t *ap_conn);
2384 int connection_ap_handshake_send_resolve(edge_connection_t *ap_conn);
2386 edge_connection_t *connection_ap_make_bridge(char *address, uint16_t port,
2387 const char *digest, int command);
2388 void connection_ap_handshake_socks_reply(edge_connection_t *conn, char *reply,
2389 size_t replylen,
2390 int endreason);
2391 void connection_ap_handshake_socks_resolved(edge_connection_t *conn,
2392 int answer_type,
2393 size_t answer_len,
2394 const char *answer,
2395 int ttl);
2397 int connection_exit_begin_conn(cell_t *cell, circuit_t *circ);
2398 int connection_exit_begin_resolve(cell_t *cell, or_circuit_t *circ);
2399 void connection_exit_connect(edge_connection_t *conn);
2400 int connection_edge_is_rendezvous_stream(edge_connection_t *conn);
2401 int connection_ap_can_use_exit(edge_connection_t *conn, routerinfo_t *exit);
2402 void connection_ap_expire_beginning(void);
2403 void connection_ap_attach_pending(void);
2404 void circuit_discard_optional_exit_enclaves(extend_info_t *info);
2405 int connection_ap_detach_retriable(edge_connection_t *conn,
2406 origin_circuit_t *circ,
2407 int reason);
2408 int connection_ap_process_transparent(edge_connection_t *conn);
2410 int address_is_invalid_destination(const char *address, int client);
2412 void addressmap_init(void);
2413 void addressmap_clean(time_t now);
2414 void addressmap_clear_configured(void);
2415 void addressmap_clear_transient(void);
2416 void addressmap_free_all(void);
2417 int addressmap_rewrite(char *address, size_t maxlen);
2418 int addressmap_have_mapping(const char *address);
2419 void addressmap_register(const char *address, char *new_address,
2420 time_t expires);
2421 int parse_virtual_addr_network(const char *val, int validate_only,
2422 char **msg);
2423 int client_dns_incr_failures(const char *address);
2424 void client_dns_clear_failures(const char *address);
2425 void client_dns_set_addressmap(const char *address, uint32_t val,
2426 const char *exitname, int ttl);
2427 int address_is_in_virtual_range(const char *addr);
2428 const char *addressmap_register_virtual_address(int type, char *new_address);
2429 void addressmap_get_mappings(smartlist_t *sl, time_t min_expires,
2430 time_t max_expires);
2431 int connection_ap_handshake_rewrite_and_attach(edge_connection_t *conn,
2432 origin_circuit_t *circ,
2433 crypt_path_t *cpath);
2434 int hostname_is_noconnect_address(const char *address);
2436 void set_exit_redirects(smartlist_t *lst);
2437 typedef enum hostname_type_t {
2438 NORMAL_HOSTNAME, ONION_HOSTNAME, EXIT_HOSTNAME, BAD_HOSTNAME
2439 } hostname_type_t;
2440 hostname_type_t parse_extended_hostname(char *address);
2442 /********************************* connection_or.c ***************************/
2444 void connection_or_remove_from_identity_map(or_connection_t *conn);
2445 void connection_or_clear_identity_map(void);
2446 or_connection_t *connection_or_get_by_identity_digest(const char *digest);
2448 int connection_or_reached_eof(or_connection_t *conn);
2449 int connection_or_process_inbuf(or_connection_t *conn);
2450 int connection_or_flushed_some(or_connection_t *conn);
2451 int connection_or_finished_flushing(or_connection_t *conn);
2452 int connection_or_finished_connecting(or_connection_t *conn);
2454 or_connection_t *connection_or_connect(uint32_t addr, uint16_t port,
2455 const char *id_digest);
2457 int connection_tls_start_handshake(or_connection_t *conn, int receiving);
2458 int connection_tls_continue_handshake(or_connection_t *conn);
2460 void connection_or_write_cell_to_buf(const cell_t *cell,
2461 or_connection_t *conn);
2462 int connection_or_send_destroy(uint16_t circ_id, or_connection_t *conn,
2463 int reason);
2465 void cell_pack(packed_cell_t *dest, const cell_t *src);
2467 /********************************* control.c ***************************/
2469 typedef enum circuit_status_event_t {
2470 CIRC_EVENT_LAUNCHED = 0,
2471 CIRC_EVENT_BUILT = 1,
2472 CIRC_EVENT_EXTENDED = 2,
2473 CIRC_EVENT_FAILED = 3,
2474 CIRC_EVENT_CLOSED = 4,
2475 } circuit_status_event_t;
2477 typedef enum stream_status_event_t {
2478 STREAM_EVENT_SENT_CONNECT = 0,
2479 STREAM_EVENT_SENT_RESOLVE = 1,
2480 STREAM_EVENT_SUCCEEDED = 2,
2481 STREAM_EVENT_FAILED = 3,
2482 STREAM_EVENT_CLOSED = 4,
2483 STREAM_EVENT_NEW = 5,
2484 STREAM_EVENT_NEW_RESOLVE = 6,
2485 STREAM_EVENT_FAILED_RETRIABLE = 7,
2486 STREAM_EVENT_REMAP = 8
2487 } stream_status_event_t;
2489 typedef enum or_conn_status_event_t {
2490 OR_CONN_EVENT_LAUNCHED = 0,
2491 OR_CONN_EVENT_CONNECTED = 1,
2492 OR_CONN_EVENT_FAILED = 2,
2493 OR_CONN_EVENT_CLOSED = 3,
2494 OR_CONN_EVENT_NEW = 4,
2495 } or_conn_status_event_t;
2497 void control_update_global_event_mask(void);
2498 void control_adjust_event_log_severity(void);
2500 /** Execute the statement <b>stmt</b>, which may log events concerning the
2501 * connection <b>conn</b>. To prevent infinite loops, disable log messages
2502 * being sent to controllers if <b>conn</b> is a control connection.
2504 * Stmt must not contain any return or goto statements.
2506 #define CONN_LOG_PROTECT(conn, stmt) \
2507 do { \
2508 int _log_conn_is_control = (conn && conn->type == CONN_TYPE_CONTROL); \
2509 if (_log_conn_is_control) \
2510 disable_control_logging(); \
2511 do {stmt;} while (0); \
2512 if (_log_conn_is_control) \
2513 enable_control_logging(); \
2514 } while (0)
2516 /** Log information about the connection <b>conn</b>, protecting it as with
2517 * CONN_LOG_PROTECT. Example:
2519 * LOG_FN_CONN(conn, (LOG_DEBUG, "Socket %d wants to write", conn->s));
2521 #define LOG_FN_CONN(conn, args) \
2522 CONN_LOG_PROTECT(conn, log_fn args)
2524 int connection_control_finished_flushing(control_connection_t *conn);
2525 int connection_control_reached_eof(control_connection_t *conn);
2526 int connection_control_process_inbuf(control_connection_t *conn);
2528 int control_event_circuit_status(origin_circuit_t *circ,
2529 circuit_status_event_t e, int reason);
2530 int control_event_stream_status(edge_connection_t *conn,
2531 stream_status_event_t e,
2532 int reason);
2533 int control_tls_error_to_reason(int e);
2534 int control_event_or_conn_status(or_connection_t *conn,
2535 or_conn_status_event_t e, int reason);
2536 int control_event_bandwidth_used(uint32_t n_read, uint32_t n_written);
2537 int control_event_stream_bandwidth_used(void);
2538 void control_event_logmsg(int severity, unsigned int domain, const char *msg);
2539 int control_event_descriptors_changed(smartlist_t *routers);
2540 int control_event_address_mapped(const char *from, const char *to,
2541 time_t expires);
2542 int control_event_or_authdir_new_descriptor(const char *action,
2543 signed_descriptor_t *desc,
2544 const char *msg);
2545 int control_event_my_descriptor_changed(void);
2546 int control_event_networkstatus_changed(smartlist_t *statuses);
2547 int control_event_networkstatus_changed_single(local_routerstatus_t *rs);
2548 int control_event_general_status(int severity, const char *format, ...)
2549 CHECK_PRINTF(2,3);
2550 int control_event_client_status(int severity, const char *format, ...)
2551 CHECK_PRINTF(2,3);
2552 int control_event_server_status(int severity, const char *format, ...)
2553 CHECK_PRINTF(2,3);
2554 int control_event_guard(const char *nickname, const char *digest,
2555 const char *status);
2557 int init_cookie_authentication(int enabled);
2558 int decode_hashed_password(char *buf, const char *hashed);
2559 void disable_control_logging(void);
2560 void enable_control_logging(void);
2562 #ifdef CONTROL_PRIVATE
2563 /* Used only by control.c and test.c */
2564 size_t write_escaped_data(const char *data, size_t len,
2565 int translate_newlines, char **out);
2566 size_t read_escaped_data(const char *data, size_t len,
2567 int translate_newlines, char **out);
2568 #endif
2570 /********************************* cpuworker.c *****************************/
2572 void cpu_init(void);
2573 void cpuworkers_rotate(void);
2574 int connection_cpu_finished_flushing(connection_t *conn);
2575 int connection_cpu_reached_eof(connection_t *conn);
2576 int connection_cpu_process_inbuf(connection_t *conn);
2577 int assign_to_cpuworker(connection_t *cpuworker, uint8_t question_type,
2578 void *task);
2580 /********************************* directory.c ***************************/
2582 char *authority_type_to_string(authority_type_t auth);
2583 void directory_post_to_dirservers(uint8_t purpose, authority_type_t type,
2584 const char *payload,
2585 size_t payload_len, size_t extrainfo_len);
2586 void directory_get_from_dirserver(uint8_t purpose, const char *resource,
2587 int retry_if_no_servers);
2588 void directory_initiate_command_routerstatus(routerstatus_t *status,
2589 uint8_t purpose,
2590 int anonymized_connection,
2591 const char *resource,
2592 const char *payload,
2593 size_t payload_len);
2595 int parse_http_response(const char *headers, int *code, time_t *date,
2596 compress_method_t *compression, char **response);
2598 int connection_dir_reached_eof(dir_connection_t *conn);
2599 int connection_dir_process_inbuf(dir_connection_t *conn);
2600 int connection_dir_finished_flushing(dir_connection_t *conn);
2601 int connection_dir_finished_connecting(dir_connection_t *conn);
2602 void connection_dir_request_failed(dir_connection_t *conn);
2603 void directory_initiate_command(const char *address, uint32_t addr,
2604 uint16_t or_port, uint16_t dir_port,
2605 int supports_begindir,
2606 const char *digest, uint8_t purpose,
2607 int anonymized_connection,
2608 const char *resource,
2609 const char *payload, size_t payload_len);
2611 int dir_split_resource_into_fingerprints(const char *resource,
2612 smartlist_t *fp_out, int *compresseed_out,
2613 int decode_hex, int sort_uniq);
2614 char *directory_dump_request_log(void);
2615 int router_supports_extrainfo(const char *identity_digest, int is_authority);
2617 /********************************* dirserv.c ***************************/
2619 #define UNNAMED_ROUTER_NICKNAME "Unnamed"
2621 int connection_dirserv_flushed_some(dir_connection_t *conn);
2622 void connection_dirserv_unlink_from_bridge(dir_connection_t *dir_conn);
2623 void connection_dirserv_stop_blocking_all_on_or_conn(or_connection_t *or_conn);
2625 int dirserv_add_own_fingerprint(const char *nickname, crypto_pk_env_t *pk);
2626 int dirserv_load_fingerprint_file(void);
2627 void dirserv_free_fingerprint_list(void);
2628 const char *dirserv_get_nickname_by_digest(const char *digest);
2629 int dirserv_add_multiple_descriptors(const char *desc, const char **msg);
2630 int dirserv_add_descriptor(routerinfo_t *ri, const char **msg);
2631 int getinfo_helper_dirserv_unregistered(control_connection_t *conn,
2632 const char *question, char **answer);
2633 void dirserv_free_descriptors(void);
2634 int dirserv_thinks_router_is_blatantly_unreachable(routerinfo_t *router,
2635 time_t now);
2636 int list_server_status(smartlist_t *routers, char **router_status_out,
2637 int for_controller);
2638 int dirserv_dump_directory_to_string(char **dir_out,
2639 crypto_pk_env_t *private_key,
2640 int complete);
2641 void directory_set_dirty(void);
2642 cached_dir_t *dirserv_get_directory(void);
2643 size_t dirserv_get_runningrouters(const char **rr, int compress);
2644 void dirserv_set_cached_directory(const char *directory, time_t when,
2645 int is_running_routers);
2646 void dirserv_set_cached_networkstatus_v2(const char *directory,
2647 const char *identity,
2648 time_t published);
2649 void dirserv_clear_old_networkstatuses(time_t cutoff);
2650 void dirserv_clear_old_v1_info(time_t now);
2651 void dirserv_get_networkstatus_v2(smartlist_t *result, const char *key);
2652 void dirserv_get_networkstatus_v2_fingerprints(smartlist_t *result,
2653 const char *key);
2654 int dirserv_get_routerdesc_fingerprints(smartlist_t *fps_out, const char *key,
2655 const char **msg);
2656 int dirserv_get_routerdescs(smartlist_t *descs_out, const char *key,
2657 const char **msg);
2658 void dirserv_orconn_tls_done(const char *address,
2659 uint16_t or_port,
2660 const char *digest_rcvd,
2661 int as_advertised);
2662 void dirserv_test_reachability(int try_all);
2663 int authdir_wants_to_reject_router(routerinfo_t *ri, const char **msg,
2664 int complain);
2665 int dirserv_would_reject_router(routerstatus_t *rs);
2666 size_t dirserv_estimate_data_size(smartlist_t *fps, int is_serverdescs,
2667 int compressed);
2668 int routerstatus_format_entry(char *buf, size_t buf_len,
2669 routerstatus_t *rs, const char *platform);
2670 void dirserv_free_all(void);
2671 void cached_dir_decref(cached_dir_t *d);
2673 /********************************* dns.c ***************************/
2675 int dns_init(void);
2676 void dns_free_all(void);
2677 uint32_t dns_clip_ttl(uint32_t ttl);
2678 int dns_reset(void);
2679 void connection_dns_remove(edge_connection_t *conn);
2680 void assert_connection_edge_not_dns_pending(edge_connection_t *conn);
2681 void assert_all_pending_dns_resolves_ok(void);
2682 void dns_cancel_pending_resolve(const char *question);
2683 int dns_resolve(edge_connection_t *exitconn);
2684 void dns_launch_correctness_checks(void);
2685 int dns_seems_to_be_broken(void);
2686 void dns_reset_correctness_checks(void);
2688 /********************************* dnsserv.c ************************/
2690 void dnsserv_configure_listener(connection_t *conn);
2691 void dnsserv_close_listener(connection_t *conn);
2692 void dnsserv_resolved(edge_connection_t *conn,
2693 int answer_type,
2694 size_t answer_len,
2695 const char *answer,
2696 int ttl);
2697 void dnsserv_reject_request(edge_connection_t *conn);
2699 /********************************* hibernate.c **********************/
2701 int accounting_parse_options(or_options_t *options, int validate_only);
2702 int accounting_is_enabled(or_options_t *options);
2703 void configure_accounting(time_t now);
2704 void accounting_run_housekeeping(time_t now);
2705 void accounting_add_bytes(size_t n_read, size_t n_written, int seconds);
2706 int accounting_record_bandwidth_usage(time_t now, or_state_t *state);
2707 void hibernate_begin_shutdown(void);
2708 int we_are_hibernating(void);
2709 void consider_hibernation(time_t now);
2710 int getinfo_helper_accounting(control_connection_t *conn,
2711 const char *question, char **answer);
2712 void accounting_set_bandwidth_usage_from_state(or_state_t *state);
2714 /********************************* main.c ***************************/
2716 extern int has_completed_circuit;
2718 int connection_add(connection_t *conn);
2719 int connection_remove(connection_t *conn);
2720 int connection_in_array(connection_t *conn);
2721 void add_connection_to_closeable_list(connection_t *conn);
2722 int connection_is_on_closeable_list(connection_t *conn);
2724 smartlist_t *get_connection_array(void);
2726 void connection_watch_events(connection_t *conn, short events);
2727 int connection_is_reading(connection_t *conn);
2728 void connection_stop_reading(connection_t *conn);
2729 void connection_start_reading(connection_t *conn);
2731 int connection_is_writing(connection_t *conn);
2732 void connection_stop_writing(connection_t *conn);
2733 void connection_start_writing(connection_t *conn);
2735 void connection_stop_reading_from_linked_conn(connection_t *conn);
2737 void directory_all_unreachable(time_t now);
2738 void directory_info_has_arrived(time_t now, int from_cache);
2740 void ip_address_changed(int at_interface);
2741 void dns_servers_relaunch_checks(void);
2743 void control_signal_act(int the_signal);
2744 void handle_signals(int is_parent);
2745 void tor_cleanup(void);
2746 void tor_free_all(int postfork);
2748 int tor_main(int argc, char *argv[]);
2750 /********************************* onion.c ***************************/
2752 int onion_pending_add(or_circuit_t *circ);
2753 or_circuit_t *onion_next_task(void);
2754 void onion_pending_remove(or_circuit_t *circ);
2756 int onion_skin_create(crypto_pk_env_t *router_key,
2757 crypto_dh_env_t **handshake_state_out,
2758 char *onion_skin_out);
2760 int onion_skin_server_handshake(const char *onion_skin,
2761 crypto_pk_env_t *private_key,
2762 crypto_pk_env_t *prev_private_key,
2763 char *handshake_reply_out,
2764 char *key_out,
2765 size_t key_out_len);
2767 int onion_skin_client_handshake(crypto_dh_env_t *handshake_state,
2768 const char *handshake_reply,
2769 char *key_out,
2770 size_t key_out_len);
2772 int fast_server_handshake(const char *key_in,
2773 char *handshake_reply_out,
2774 char *key_out,
2775 size_t key_out_len);
2777 int fast_client_handshake(const char *handshake_state,
2778 const char *handshake_reply_out,
2779 char *key_out,
2780 size_t key_out_len);
2782 void clear_pending_onions(void);
2784 /********************************* policies.c ************************/
2786 /* (length of "accept 255.255.255.255/255.255.255.255:65535-65535\n" plus a
2787 * nul.)
2789 #define POLICY_BUF_LEN 52
2791 typedef enum {
2792 ADDR_POLICY_ACCEPTED=0,
2793 ADDR_POLICY_REJECTED=-1,
2794 ADDR_POLICY_PROBABLY_ACCEPTED=1,
2795 ADDR_POLICY_PROBABLY_REJECTED=2
2796 } addr_policy_result_t;
2798 int firewall_is_fascist_or(void);
2799 int fascist_firewall_allows_address_or(uint32_t addr, uint16_t port);
2800 int fascist_firewall_allows_address_dir(uint32_t addr, uint16_t port);
2801 int dir_policy_permits_address(uint32_t addr);
2802 int socks_policy_permits_address(uint32_t addr);
2803 int authdir_policy_permits_address(uint32_t addr, uint16_t port);
2804 int authdir_policy_valid_address(uint32_t addr, uint16_t port);
2805 int authdir_policy_badexit_address(uint32_t addr, uint16_t port);
2807 int validate_addr_policies(or_options_t *options, char **msg);
2808 void policies_parse_from_options(or_options_t *options);
2810 int cmp_addr_policies(addr_policy_t *a, addr_policy_t *b);
2811 addr_policy_result_t compare_addr_to_addr_policy(uint32_t addr,
2812 uint16_t port, addr_policy_t *policy);
2813 int policies_parse_exit_policy(config_line_t *cfg,
2814 addr_policy_t **dest,
2815 int rejectprivate);
2816 int exit_policy_is_general_exit(addr_policy_t *policy);
2817 int policy_is_reject_star(addr_policy_t *policy);
2818 int getinfo_helper_policies(control_connection_t *conn,
2819 const char *question, char **answer);
2820 int policy_write_item(char *buf, size_t buflen, addr_policy_t *policy);
2822 void addr_policy_free(addr_policy_t *p);
2823 void policies_free_all(void);
2825 /********************************* relay.c ***************************/
2827 extern uint64_t stats_n_relay_cells_relayed;
2828 extern uint64_t stats_n_relay_cells_delivered;
2830 int circuit_receive_relay_cell(cell_t *cell, circuit_t *circ,
2831 int cell_direction);
2833 void relay_header_pack(char *dest, const relay_header_t *src);
2834 void relay_header_unpack(relay_header_t *dest, const char *src);
2835 int relay_send_command_from_edge(uint16_t stream_id, circuit_t *circ,
2836 int relay_command, const char *payload,
2837 size_t payload_len, crypt_path_t *cpath_layer);
2838 int connection_edge_send_command(edge_connection_t *fromconn,
2839 int relay_command, const char *payload,
2840 size_t payload_len);
2841 int connection_edge_package_raw_inbuf(edge_connection_t *conn,
2842 int package_partial);
2843 void connection_edge_consider_sending_sendme(edge_connection_t *conn);
2844 socks5_reply_status_t connection_edge_end_reason_socks5_response(int reason);
2845 int errno_to_end_reason(int e);
2847 extern uint64_t stats_n_data_cells_packaged;
2848 extern uint64_t stats_n_data_bytes_packaged;
2849 extern uint64_t stats_n_data_cells_received;
2850 extern uint64_t stats_n_data_bytes_received;
2852 void init_cell_pool(void);
2853 void free_cell_pool(void);
2854 void clean_cell_pool(void);
2855 void dump_cell_pool_usage(int severity);
2857 void cell_queue_clear(cell_queue_t *queue);
2858 void cell_queue_append(cell_queue_t *queue, packed_cell_t *cell);
2859 void cell_queue_append_packed_copy(cell_queue_t *queue, const cell_t *cell);
2861 void append_cell_to_circuit_queue(circuit_t *circ, or_connection_t *orconn,
2862 cell_t *cell, int direction);
2863 void connection_or_unlink_all_active_circs(or_connection_t *conn);
2864 int connection_or_flush_from_first_active_circuit(or_connection_t *conn,
2865 int max);
2866 void assert_active_circuits_ok(or_connection_t *orconn);
2867 void make_circuit_inactive_on_conn(circuit_t *circ, or_connection_t *conn);
2868 void make_circuit_active_on_conn(circuit_t *circ, or_connection_t *conn);
2869 void circuit_clear_cell_queue(circuit_t *circ, or_connection_t *orconn);
2871 /********************************* rephist.c ***************************/
2873 void rep_hist_init(void);
2874 void rep_hist_note_connect_failed(const char* nickname, time_t when);
2875 void rep_hist_note_connect_succeeded(const char* nickname, time_t when);
2876 void rep_hist_note_disconnect(const char* nickname, time_t when);
2877 void rep_hist_note_connection_died(const char* nickname, time_t when);
2878 void rep_hist_note_extend_succeeded(const char *from_name,
2879 const char *to_name);
2880 void rep_hist_note_extend_failed(const char *from_name, const char *to_name);
2881 void rep_hist_dump_stats(time_t now, int severity);
2882 void rep_hist_note_bytes_read(int num_bytes, time_t when);
2883 void rep_hist_note_bytes_written(int num_bytes, time_t when);
2884 int rep_hist_bandwidth_assess(void);
2885 char *rep_hist_get_bandwidth_lines(int for_extrainfo);
2886 void rep_hist_update_state(or_state_t *state);
2887 int rep_hist_load_state(or_state_t *state, char **err);
2888 void rep_history_clean(time_t before);
2890 void rep_hist_note_used_port(uint16_t port, time_t now);
2891 smartlist_t *rep_hist_get_predicted_ports(time_t now);
2892 void rep_hist_note_used_resolve(time_t now);
2893 void rep_hist_note_used_internal(time_t now, int need_uptime,
2894 int need_capacity);
2895 int rep_hist_get_predicted_internal(time_t now, int *need_uptime,
2896 int *need_capacity);
2898 int any_predicted_circuits(time_t now);
2899 int rep_hist_circbuilding_dormant(time_t now);
2901 /** Possible public/private key operations in Tor: used to keep track of where
2902 * we're spending our time. */
2903 typedef enum {
2904 SIGN_DIR, SIGN_RTR,
2905 VERIFY_DIR, VERIFY_RTR,
2906 ENC_ONIONSKIN, DEC_ONIONSKIN,
2907 TLS_HANDSHAKE_C, TLS_HANDSHAKE_S,
2908 REND_CLIENT, REND_MID, REND_SERVER,
2909 } pk_op_t;
2910 void note_crypto_pk_op(pk_op_t operation);
2911 void dump_pk_ops(int severity);
2913 void rep_hist_free_all(void);
2915 /* for hidden service usage statistics */
2916 void hs_usage_note_publish_total(const char *service_id, time_t now);
2917 void hs_usage_note_publish_novel(const char *service_id, time_t now);
2918 void hs_usage_note_fetch_total(const char *service_id, time_t now);
2919 void hs_usage_note_fetch_successful(const char *service_id, time_t now);
2920 void hs_usage_write_statistics_to_file(time_t now);
2921 void hs_usage_free_all(void);
2923 /********************************* rendclient.c ***************************/
2925 void rend_client_introcirc_has_opened(origin_circuit_t *circ);
2926 void rend_client_rendcirc_has_opened(origin_circuit_t *circ);
2927 int rend_client_introduction_acked(origin_circuit_t *circ, const char *request,
2928 size_t request_len);
2929 void rend_client_refetch_renddesc(const char *query);
2930 int rend_client_remove_intro_point(extend_info_t *failed_intro,
2931 const char *query);
2932 int rend_client_rendezvous_acked(origin_circuit_t *circ, const char *request,
2933 size_t request_len);
2934 int rend_client_receive_rendezvous(origin_circuit_t *circ, const char *request,
2935 size_t request_len);
2936 void rend_client_desc_here(const char *query);
2938 extend_info_t *rend_client_get_random_intro(const char *query);
2940 int rend_client_send_introduction(origin_circuit_t *introcirc,
2941 origin_circuit_t *rendcirc);
2943 /********************************* rendcommon.c ***************************/
2945 /** Information used to connect to a hidden service. */
2946 typedef struct rend_service_descriptor_t {
2947 crypto_pk_env_t *pk; /**< This service's public key. */
2948 int version; /**< 0 or 1. */
2949 time_t timestamp; /**< Time when the descriptor was generated. */
2950 uint16_t protocols; /**< Bitmask: which rendezvous protocols are supported?
2951 * (We allow bits '0', '1', and '2' to be set.) */
2952 int n_intro_points; /**< Number of introduction points. */
2953 /** Array of n_intro_points elements for this service's introduction points'
2954 * nicknames. Elements are removed from this array if introduction attempts
2955 * fail. */
2956 char **intro_points;
2957 /** Array of n_intro_points elements for this service's introduction points'
2958 * extend_infos, or NULL if this descriptor is V0. Elements are removed
2959 * from this array if introduction attempts fail. If this array is present,
2960 * its elements correspond to the elements of intro_points. */
2961 extend_info_t **intro_point_extend_info;
2962 } rend_service_descriptor_t;
2964 int rend_cmp_service_ids(const char *one, const char *two);
2966 void rend_process_relay_cell(circuit_t *circ, int command, size_t length,
2967 const char *payload);
2969 void rend_service_descriptor_free(rend_service_descriptor_t *desc);
2970 int rend_encode_service_descriptor(rend_service_descriptor_t *desc,
2971 int version,
2972 crypto_pk_env_t *key,
2973 char **str_out,
2974 size_t *len_out);
2975 rend_service_descriptor_t *rend_parse_service_descriptor(const char *str,
2976 size_t len);
2977 int rend_get_service_id(crypto_pk_env_t *pk, char *out);
2979 /** A cached rendezvous descriptor. */
2980 typedef struct rend_cache_entry_t {
2981 size_t len; /**< Length of <b>desc</b> */
2982 time_t received; /**< When was the descriptor received? */
2983 char *desc; /**< Service descriptor */
2984 rend_service_descriptor_t *parsed; /**< Parsed value of 'desc' */
2985 } rend_cache_entry_t;
2987 void rend_cache_init(void);
2988 void rend_cache_clean(void);
2989 void rend_cache_free_all(void);
2990 int rend_valid_service_id(const char *query);
2991 int rend_cache_lookup_desc(const char *query, int version, const char **desc,
2992 size_t *desc_len);
2993 int rend_cache_lookup_entry(const char *query, int version,
2994 rend_cache_entry_t **entry_out);
2995 int rend_cache_store(const char *desc, size_t desc_len, int published);
2996 int rend_cache_size(void);
2998 /********************************* rendservice.c ***************************/
3000 int num_rend_services(void);
3001 int rend_config_services(or_options_t *options, int validate_only);
3002 int rend_service_load_keys(void);
3003 void rend_services_init(void);
3004 void rend_services_introduce(void);
3005 void rend_consider_services_upload(time_t now);
3007 void rend_service_intro_has_opened(origin_circuit_t *circuit);
3008 int rend_service_intro_established(origin_circuit_t *circuit,
3009 const char *request,
3010 size_t request_len);
3011 void rend_service_rendezvous_has_opened(origin_circuit_t *circuit);
3012 int rend_service_introduce(origin_circuit_t *circuit, const char *request,
3013 size_t request_len);
3014 void rend_service_relaunch_rendezvous(origin_circuit_t *oldcirc);
3015 int rend_service_set_connection_addr_port(edge_connection_t *conn,
3016 origin_circuit_t *circ);
3017 void rend_service_dump_stats(int severity);
3018 void rend_service_free_all(void);
3020 /********************************* rendmid.c *******************************/
3021 int rend_mid_establish_intro(or_circuit_t *circ, const char *request,
3022 size_t request_len);
3023 int rend_mid_introduce(or_circuit_t *circ, const char *request,
3024 size_t request_len);
3025 int rend_mid_establish_rendezvous(or_circuit_t *circ, const char *request,
3026 size_t request_len);
3027 int rend_mid_rendezvous(or_circuit_t *circ, const char *request,
3028 size_t request_len);
3030 /********************************* router.c ***************************/
3032 crypto_pk_env_t *get_onion_key(void);
3033 time_t get_onion_key_set_at(void);
3034 void set_identity_key(crypto_pk_env_t *k);
3035 crypto_pk_env_t *get_identity_key(void);
3036 int identity_key_is_set(void);
3037 authority_cert_t *get_my_v3_authority_cert(void);
3038 crypto_pk_env_t *get_my_v3_authority_signing_key(void);
3039 void dup_onion_keys(crypto_pk_env_t **key, crypto_pk_env_t **last);
3040 void rotate_onion_key(void);
3041 crypto_pk_env_t *init_key_from_file(const char *fname, int generate,
3042 int severity);
3043 int init_keys(void);
3045 int check_whether_orport_reachable(void);
3046 int check_whether_dirport_reachable(void);
3047 void consider_testing_reachability(int test_or, int test_dir);
3048 void router_orport_found_reachable(void);
3049 void router_dirport_found_reachable(void);
3050 void router_perform_bandwidth_test(int num_circs, time_t now);
3052 int authdir_mode(or_options_t *options);
3053 int authdir_mode_v1(or_options_t *options);
3054 int authdir_mode_v2(or_options_t *options);
3055 int authdir_mode_handles_descs(or_options_t *options);
3056 int authdir_mode_bridge(or_options_t *options);
3057 int clique_mode(or_options_t *options);
3058 int server_mode(or_options_t *options);
3059 int advertised_server_mode(void);
3060 int proxy_mode(or_options_t *options);
3061 void consider_publishable_server(int force);
3063 int router_is_clique_mode(routerinfo_t *router);
3064 void router_upload_dir_desc_to_dirservers(int force);
3065 void mark_my_descriptor_dirty_if_older_than(time_t when);
3066 void mark_my_descriptor_dirty(void);
3067 void check_descriptor_bandwidth_changed(time_t now);
3068 void check_descriptor_ipaddress_changed(time_t now);
3069 void router_new_address_suggestion(const char *suggestion);
3070 int router_compare_to_my_exit_policy(edge_connection_t *conn);
3071 routerinfo_t *router_get_my_routerinfo(void);
3072 extrainfo_t *router_get_my_extrainfo(void);
3073 const char *router_get_my_descriptor(void);
3074 int router_digest_is_me(const char *digest);
3075 int router_is_me(routerinfo_t *router);
3076 int router_fingerprint_is_me(const char *fp);
3077 int router_pick_published_address(or_options_t *options, uint32_t *addr);
3078 int router_rebuild_descriptor(int force);
3079 int router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
3080 crypto_pk_env_t *ident_key);
3081 int extrainfo_dump_to_string(char *s, size_t maxlen, extrainfo_t *extrainfo,
3082 crypto_pk_env_t *ident_key);
3083 int is_legal_nickname(const char *s);
3084 int is_legal_nickname_or_hexdigest(const char *s);
3085 int is_legal_hexdigest(const char *s);
3086 void router_get_verbose_nickname(char *buf, routerinfo_t *router);
3087 void router_reset_warnings(void);
3088 void router_reset_reachability(void);
3089 void router_free_all(void);
3091 #ifdef ROUTER_PRIVATE
3092 /* Used only by router.c and test.c */
3093 void get_platform_str(char *platform, size_t len);
3094 #endif
3096 /********************************* routerlist.c ***************************/
3098 /** Represents information about a single trusted directory server. */
3099 typedef struct trusted_dir_server_t {
3100 char *description;
3101 char *nickname;
3102 char *address; /**< Hostname. */
3103 uint32_t addr; /**< IPv4 address. */
3104 uint16_t dir_port; /**< Directory port. */
3105 uint16_t or_port; /**< OR port: Used for tunneling connections. */
3106 char digest[DIGEST_LEN]; /**< Digest of identity key. */
3107 char v3_identity_digest[DIGEST_LEN]; /**< Digest of v3 (authority only,
3108 * high-security) identity key. */
3110 unsigned int is_running:1; /**< True iff we think this server is running. */
3112 /** True iff this server has accepted the most recent server descriptor
3113 * we tried to upload to it. */
3114 unsigned int has_accepted_serverdesc:1;
3116 /** What kind of authority is this? (Bitfield.) */
3117 authority_type_t type;
3119 authority_cert_t *v3_cert; /**< V3 key certificate for this authority */
3121 int n_networkstatus_failures; /**< How many times have we asked for this
3122 * server's network-status unsuccessfully? */
3123 local_routerstatus_t fake_status; /**< Used when we need to pass this trusted
3124 * dir_server_t to directory_initiate_command_*
3125 * as a routerstatus_t. Not updated by the
3126 * router-status management code!
3128 } trusted_dir_server_t;
3130 int router_reload_router_list(void);
3131 int router_reload_networkstatus(void);
3132 smartlist_t *router_get_trusted_dir_servers(void);
3133 routerstatus_t *router_pick_directory_server(int requireother,
3134 int fascistfirewall,
3135 authority_type_t type,
3136 int retry_if_no_servers);
3137 routerstatus_t *router_pick_trusteddirserver(authority_type_t type,
3138 int requireother,
3139 int fascistfirewall,
3140 int retry_if_no_servers);
3141 trusted_dir_server_t *router_get_trusteddirserver_by_digest(
3142 const char *digest);
3143 trusted_dir_server_t *trusteddirserver_get_by_v3_auth_digest(
3144 const char *digest);
3145 void routerlist_add_family(smartlist_t *sl, routerinfo_t *router);
3146 void add_nickname_list_to_smartlist(smartlist_t *sl, const char *list,
3147 int must_be_running);
3148 int router_nickname_is_in_list(routerinfo_t *router, const char *list);
3149 routerinfo_t *routerlist_find_my_routerinfo(void);
3150 routerinfo_t *router_find_exact_exit_enclave(const char *address,
3151 uint16_t port);
3153 #define ROUTER_REQUIRED_MIN_BANDWIDTH 10000
3155 #define ROUTER_MAX_DECLARED_BANDWIDTH INT32_MAX
3156 int router_is_unreliable(routerinfo_t *router, int need_uptime,
3157 int need_capacity, int need_guard);
3158 uint32_t router_get_advertised_bandwidth(routerinfo_t *router);
3159 routerinfo_t *routerlist_sl_choose_by_bandwidth(smartlist_t *sl, int for_exit);
3160 routerstatus_t *routerstatus_sl_choose_by_bandwidth(smartlist_t *sl);
3162 routerinfo_t *router_choose_random_node(const char *preferred,
3163 const char *excluded,
3164 smartlist_t *excludedsmartlist,
3165 int need_uptime, int need_bandwidth,
3166 int need_guard,
3167 int allow_invalid, int strict,
3168 int weight_for_exit);
3169 routerinfo_t *router_get_by_nickname(const char *nickname,
3170 int warn_if_unnamed);
3171 int hexdigest_to_digest(const char *hexdigest, char *digest);
3172 routerinfo_t *router_get_by_hexdigest(const char *hexdigest);
3173 routerinfo_t *router_get_by_digest(const char *digest);
3174 signed_descriptor_t *router_get_by_descriptor_digest(const char *digest);
3175 signed_descriptor_t *router_get_by_extrainfo_digest(const char *digest);
3176 signed_descriptor_t *extrainfo_get_by_descriptor_digest(const char *digest);
3177 const char *signed_descriptor_get_body(signed_descriptor_t *desc);
3178 int router_digest_version_as_new_as(const char *digest, const char *cutoff);
3179 int router_digest_is_trusted_dir(const char *digest);
3180 routerlist_t *router_get_routerlist(void);
3181 void routerlist_reset_warnings(void);
3182 void routerlist_free(routerlist_t *routerlist);
3183 void dump_routerlist_mem_usage(int severity);
3184 void routerlist_remove(routerlist_t *rl, routerinfo_t *ri, int idx,
3185 int make_old);
3186 void routerinfo_free(routerinfo_t *router);
3187 void extrainfo_free(extrainfo_t *extrainfo);
3189 void routerstatus_free(routerstatus_t *routerstatus);
3190 void networkstatus_free(networkstatus_t *networkstatus);
3191 void routerlist_free_all(void);
3192 void router_set_status(const char *digest, int up);
3193 void routerlist_remove_old_routers(void);
3194 void networkstatus_list_clean(time_t now);
3195 int router_add_to_routerlist(routerinfo_t *router, const char **msg,
3196 int from_cache, int from_fetch);
3197 void router_add_extrainfo_to_routerlist(extrainfo_t *ei, const char **msg,
3198 int from_cache, int from_fetch);
3199 int router_load_single_router(const char *s, uint8_t purpose,
3200 const char **msg);
3201 void router_load_routers_from_string(const char *s, const char *eos,
3202 saved_location_t saved_location,
3203 smartlist_t *requested_fingerprints);
3204 void router_load_extrainfo_from_string(const char *s, const char *eos,
3205 saved_location_t saved_location,
3206 smartlist_t *requested_fps);
3208 typedef enum {
3209 NS_FROM_CACHE, NS_FROM_DIR_BY_FP, NS_FROM_DIR_ALL, NS_GENERATED
3210 } networkstatus_source_t;
3211 int router_set_networkstatus(const char *s, time_t arrived_at,
3212 networkstatus_source_t source,
3213 smartlist_t *requested_fingerprints);
3214 char *networkstatus_get_cache_filename(const char *identity_digest);
3216 int router_exit_policy_all_routers_reject(uint32_t addr, uint16_t port,
3217 int need_uptime);
3218 int router_exit_policy_rejects_all(routerinfo_t *router);
3220 void add_trusted_dir_server(const char *nickname, const char *address,
3221 uint16_t dir_port, uint16_t or_port,
3222 const char *digest, authority_type_t type);
3223 void clear_trusted_dir_servers(void);
3224 int any_trusted_dir_is_v1_authority(void);
3225 networkstatus_t *networkstatus_get_by_digest(const char *digest);
3226 local_routerstatus_t *router_get_combined_status_by_digest(const char *digest);
3227 local_routerstatus_t *router_get_combined_status_by_descriptor_digest(
3228 const char *digest);
3230 routerstatus_t *routerstatus_get_by_hexdigest(const char *hexdigest);
3231 void update_networkstatus_downloads(time_t now);
3232 void update_router_descriptor_downloads(time_t now);
3233 void update_extrainfo_downloads(time_t now);
3234 void routers_update_all_from_networkstatus(time_t now);
3235 void routers_update_status_from_networkstatus(smartlist_t *routers,
3236 int reset_failures);
3237 smartlist_t *router_list_superseded(void);
3238 int router_have_minimum_dir_info(void);
3239 void networkstatus_list_update_recent(time_t now);
3240 void router_reset_descriptor_download_failures(void);
3241 void router_reset_status_download_failures(void);
3242 int router_differences_are_cosmetic(routerinfo_t *r1, routerinfo_t *r2);
3243 int routerinfo_incompatible_with_extrainfo(routerinfo_t *ri, extrainfo_t *ei,
3244 const char **msg);
3245 const char *esc_router_info(routerinfo_t *router);
3247 char *networkstatus_getinfo_helper_single(routerstatus_t *rs);
3248 int getinfo_helper_networkstatus(control_connection_t *conn,
3249 const char *question, char **answer);
3251 void routerlist_assert_ok(routerlist_t *rl);
3252 void routerlist_check_bug_417(void);
3254 int trusted_dirs_reload_certs(void);
3255 int trusted_dirs_load_certs_from_string(const char *contents, int from_store);
3256 void trusted_dirs_flush_certs_to_disk(void);
3258 /********************************* routerparse.c ************************/
3260 #define MAX_STATUS_TAG_LEN 32
3261 /** Structure to hold parsed Tor versions. This is a little messier
3262 * than we would like it to be, because we changed version schemes with 0.1.0.
3264 * See version-spec.txt for the whole business.
3266 typedef struct tor_version_t {
3267 int major;
3268 int minor;
3269 int micro;
3270 /** Release status. For version in the post-0.1 format, this is always
3271 * VER_RELEASE. */
3272 enum { VER_PRE=0, VER_RC=1, VER_RELEASE=2, } status;
3273 int patchlevel;
3274 char status_tag[MAX_STATUS_TAG_LEN];
3275 int svn_revision;
3276 } tor_version_t;
3278 typedef enum version_status_t {
3279 VS_RECOMMENDED=0, /**< This version is listed as recommended. */
3280 VS_OLD=1, /**< This version is older than any recommended version. */
3281 VS_NEW=2, /**< This version is newer than any recommended version. */
3282 VS_NEW_IN_SERIES=3, /**< This version is newer than any recommended version
3283 * in its series, but later recommended versions exist.
3285 VS_UNRECOMMENDED=4 /**< This version is not recommended (general case) */
3286 } version_status_t;
3288 typedef struct combined_version_status_t {
3289 /** How many networkstatuses claim to know about versions? */
3290 int n_versioning;
3291 /** What do the majority of networkstatuses believe about this version? */
3292 version_status_t consensus;
3293 /** How many networkstatuses constitute the majority? */
3294 int n_concurring;
3295 } combined_version_status_t;
3296 char *compute_recommended_versions(time_t now, int client,
3297 const char *my_version,
3298 combined_version_status_t *status_out);
3300 int router_get_router_hash(const char *s, char *digest);
3301 int router_get_dir_hash(const char *s, char *digest);
3302 int router_get_runningrouters_hash(const char *s, char *digest);
3303 int router_get_networkstatus_v2_hash(const char *s, char *digest);
3304 int router_get_networkstatus_v3_hash(const char *s, char *digest);
3305 int router_get_extrainfo_hash(const char *s, char *digest);
3306 int router_append_dirobj_signature(char *buf, size_t buf_len,
3307 const char *digest,
3308 crypto_pk_env_t *private_key);
3309 int router_parse_list_from_string(const char **s, const char *eos,
3310 smartlist_t *dest,
3311 saved_location_t saved_location,
3312 int is_extrainfo);
3313 int router_parse_routerlist_from_directory(const char *s,
3314 routerlist_t **dest,
3315 crypto_pk_env_t *pkey,
3316 int check_version,
3317 int write_to_cache);
3318 int router_parse_runningrouters(const char *str);
3319 int router_parse_directory(const char *str);
3320 routerinfo_t *router_parse_entry_from_string(const char *s, const char *end,
3321 int cache_copy);
3322 extrainfo_t *extrainfo_parse_entry_from_string(const char *s, const char *end,
3323 int cache_copy, digestmap_t *routermap);
3324 addr_policy_t *router_parse_addr_policy_from_string(const char *s,
3325 int assume_action);
3326 version_status_t tor_version_is_obsolete(const char *myversion,
3327 const char *versionlist);
3328 version_status_t version_status_join(version_status_t a, version_status_t b);
3329 int tor_version_parse(const char *s, tor_version_t *out);
3330 int tor_version_as_new_as(const char *platform, const char *cutoff);
3331 int tor_version_compare(tor_version_t *a, tor_version_t *b);
3332 void sort_version_list(smartlist_t *lst, int remove_duplicates);
3333 void assert_addr_policy_ok(addr_policy_t *t);
3334 void dump_distinct_digest_count(int severity);
3336 networkstatus_t *networkstatus_parse_from_string(const char *s);
3338 void authority_cert_free(authority_cert_t *cert);
3339 authority_cert_t *authority_cert_parse_from_string(const char *s,
3340 const char **end_of_string);
3342 #endif