Merge branch 'protover_v2_squashed'
[tor.git] / src / or / or.h
blob66717792b4f81139b41e8dc9ea6a4278c5d9a6cf
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2016, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file or.h
9 * \brief Master header file for Tor-specific functionality.
10 **/
12 #ifndef TOR_OR_H
13 #define TOR_OR_H
15 #include "orconfig.h"
17 #ifdef HAVE_UNISTD_H
18 #include <unistd.h>
19 #endif
20 #ifdef HAVE_SIGNAL_H
21 #include <signal.h>
22 #endif
23 #ifdef HAVE_NETDB_H
24 #include <netdb.h>
25 #endif
26 #ifdef HAVE_SYS_PARAM_H
27 #include <sys/param.h> /* FreeBSD needs this to know what version it is */
28 #endif
29 #include "torint.h"
30 #ifdef HAVE_SYS_FCNTL_H
31 #include <sys/fcntl.h>
32 #endif
33 #ifdef HAVE_FCNTL_H
34 #include <fcntl.h>
35 #endif
36 #ifdef HAVE_SYS_IOCTL_H
37 #include <sys/ioctl.h>
38 #endif
39 #ifdef HAVE_SYS_UN_H
40 #include <sys/un.h>
41 #endif
42 #ifdef HAVE_SYS_STAT_H
43 #include <sys/stat.h>
44 #endif
45 #ifdef HAVE_NETINET_IN_H
46 #include <netinet/in.h>
47 #endif
48 #ifdef HAVE_ARPA_INET_H
49 #include <arpa/inet.h>
50 #endif
51 #ifdef HAVE_ERRNO_H
52 #include <errno.h>
53 #endif
54 #ifdef HAVE_ASSERT_H
55 #include <assert.h>
56 #endif
57 #ifdef HAVE_TIME_H
58 #include <time.h>
59 #endif
61 #ifdef _WIN32
62 #include <winsock2.h>
63 #include <io.h>
64 #include <process.h>
65 #include <direct.h>
66 #include <windows.h>
67 #endif
69 #include "crypto.h"
70 #include "crypto_format.h"
71 #include "tortls.h"
72 #include "torlog.h"
73 #include "container.h"
74 #include "torgzip.h"
75 #include "address.h"
76 #include "compat_libevent.h"
77 #include "ht.h"
78 #include "replaycache.h"
79 #include "crypto_curve25519.h"
80 #include "crypto_ed25519.h"
81 #include "tor_queue.h"
82 #include "util_format.h"
84 /* These signals are defined to help handle_control_signal work.
86 #ifndef SIGHUP
87 #define SIGHUP 1
88 #endif
89 #ifndef SIGINT
90 #define SIGINT 2
91 #endif
92 #ifndef SIGUSR1
93 #define SIGUSR1 10
94 #endif
95 #ifndef SIGUSR2
96 #define SIGUSR2 12
97 #endif
98 #ifndef SIGTERM
99 #define SIGTERM 15
100 #endif
101 /* Controller signals start at a high number so we don't
102 * conflict with system-defined signals. */
103 #define SIGNEWNYM 129
104 #define SIGCLEARDNSCACHE 130
105 #define SIGHEARTBEAT 131
107 #if (SIZEOF_CELL_T != 0)
108 /* On Irix, stdlib.h defines a cell_t type, so we need to make sure
109 * that our stuff always calls cell_t something different. */
110 #define cell_t tor_cell_t
111 #endif
113 #ifdef ENABLE_TOR2WEB_MODE
114 #define NON_ANONYMOUS_MODE_ENABLED 1
115 #endif
117 /** Length of longest allowable configured nickname. */
118 #define MAX_NICKNAME_LEN 19
119 /** Length of a router identity encoded as a hexadecimal digest, plus
120 * possible dollar sign. */
121 #define MAX_HEX_NICKNAME_LEN (HEX_DIGEST_LEN+1)
122 /** Maximum length of verbose router identifier: dollar sign, hex ID digest,
123 * equal sign or tilde, nickname. */
124 #define MAX_VERBOSE_NICKNAME_LEN (1+HEX_DIGEST_LEN+1+MAX_NICKNAME_LEN)
126 /** Maximum size, in bytes, for resized buffers. */
127 #define MAX_BUF_SIZE ((1<<24)-1) /* 16MB-1 */
128 /** Maximum size, in bytes, for any directory object that we've downloaded. */
129 #define MAX_DIR_DL_SIZE MAX_BUF_SIZE
131 /** For HTTP parsing: Maximum number of bytes we'll accept in the headers
132 * of an HTTP request or response. */
133 #define MAX_HEADERS_SIZE 50000
134 /** Maximum size, in bytes, for any directory object that we're accepting
135 * as an upload. */
136 #define MAX_DIR_UL_SIZE MAX_BUF_SIZE
138 /** Maximum size, in bytes, of a single router descriptor uploaded to us
139 * as a directory authority. Caches and clients fetch whatever descriptors
140 * the authorities tell them to fetch, and don't care about size. */
141 #define MAX_DESCRIPTOR_UPLOAD_SIZE 20000
143 /** Maximum size of a single extrainfo document, as above. */
144 #define MAX_EXTRAINFO_UPLOAD_SIZE 50000
146 /** How long do we keep DNS cache entries before purging them (regardless of
147 * their TTL)? */
148 #define MAX_DNS_ENTRY_AGE (30*60)
149 /** How long do we cache/tell clients to cache DNS records when no TTL is
150 * known? */
151 #define DEFAULT_DNS_TTL (30*60)
152 /** How long can a TTL be before we stop believing it? */
153 #define MAX_DNS_TTL (3*60*60)
154 /** How small can a TTL be before we stop believing it? Provides rudimentary
155 * pinning. */
156 #define MIN_DNS_TTL 60
158 /** How often do we rotate onion keys? */
159 #define MIN_ONION_KEY_LIFETIME (7*24*60*60)
160 /** How often do we rotate TLS contexts? */
161 #define MAX_SSL_KEY_LIFETIME_INTERNAL (2*60*60)
163 /** How old do we allow a router to get before removing it
164 * from the router list? In seconds. */
165 #define ROUTER_MAX_AGE (60*60*48)
166 /** How old can a router get before we (as a server) will no longer
167 * consider it live? In seconds. */
168 #define ROUTER_MAX_AGE_TO_PUBLISH (60*60*24)
169 /** How old do we let a saved descriptor get before force-removing it? */
170 #define OLD_ROUTER_DESC_MAX_AGE (60*60*24*5)
172 /** Possible rules for generating circuit IDs on an OR connection. */
173 typedef enum {
174 CIRC_ID_TYPE_LOWER=0, /**< Pick from 0..1<<15-1. */
175 CIRC_ID_TYPE_HIGHER=1, /**< Pick from 1<<15..1<<16-1. */
176 /** The other side of a connection is an OP: never create circuits to it,
177 * and let it use any circuit ID it wants. */
178 CIRC_ID_TYPE_NEITHER=2
179 } circ_id_type_t;
180 #define circ_id_type_bitfield_t ENUM_BF(circ_id_type_t)
182 #define CONN_TYPE_MIN_ 3
183 /** Type for sockets listening for OR connections. */
184 #define CONN_TYPE_OR_LISTENER 3
185 /** A bidirectional TLS connection transmitting a sequence of cells.
186 * May be from an OR to an OR, or from an OP to an OR. */
187 #define CONN_TYPE_OR 4
188 /** A TCP connection from an onion router to a stream's destination. */
189 #define CONN_TYPE_EXIT 5
190 /** Type for sockets listening for SOCKS connections. */
191 #define CONN_TYPE_AP_LISTENER 6
192 /** A SOCKS proxy connection from the user application to the onion
193 * proxy. */
194 #define CONN_TYPE_AP 7
195 /** Type for sockets listening for HTTP connections to the directory server. */
196 #define CONN_TYPE_DIR_LISTENER 8
197 /** Type for HTTP connections to the directory server. */
198 #define CONN_TYPE_DIR 9
199 /* Type 10 is unused. */
200 /** Type for listening for connections from user interface process. */
201 #define CONN_TYPE_CONTROL_LISTENER 11
202 /** Type for connections from user interface process. */
203 #define CONN_TYPE_CONTROL 12
204 /** Type for sockets listening for transparent connections redirected by pf or
205 * netfilter. */
206 #define CONN_TYPE_AP_TRANS_LISTENER 13
207 /** Type for sockets listening for transparent connections redirected by
208 * natd. */
209 #define CONN_TYPE_AP_NATD_LISTENER 14
210 /** Type for sockets listening for DNS requests. */
211 #define CONN_TYPE_AP_DNS_LISTENER 15
213 /** Type for connections from the Extended ORPort. */
214 #define CONN_TYPE_EXT_OR 16
215 /** Type for sockets listening for Extended ORPort connections. */
216 #define CONN_TYPE_EXT_OR_LISTENER 17
218 #define CONN_TYPE_MAX_ 17
219 /* !!!! If _CONN_TYPE_MAX is ever over 31, we must grow the type field in
220 * connection_t. */
222 /* Proxy client types */
223 #define PROXY_NONE 0
224 #define PROXY_CONNECT 1
225 #define PROXY_SOCKS4 2
226 #define PROXY_SOCKS5 3
227 /* !!!! If there is ever a PROXY_* type over 3, we must grow the proxy_type
228 * field in or_connection_t */
230 /* Pluggable transport proxy type. Don't use this in or_connection_t,
231 * instead use the actual underlying proxy type (see above). */
232 #define PROXY_PLUGGABLE 4
234 /* Proxy client handshake states */
235 /* We use a proxy but we haven't even connected to it yet. */
236 #define PROXY_INFANT 1
237 /* We use an HTTP proxy and we've sent the CONNECT command. */
238 #define PROXY_HTTPS_WANT_CONNECT_OK 2
239 /* We use a SOCKS4 proxy and we've sent the CONNECT command. */
240 #define PROXY_SOCKS4_WANT_CONNECT_OK 3
241 /* We use a SOCKS5 proxy and we try to negotiate without
242 any authentication . */
243 #define PROXY_SOCKS5_WANT_AUTH_METHOD_NONE 4
244 /* We use a SOCKS5 proxy and we try to negotiate with
245 Username/Password authentication . */
246 #define PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929 5
247 /* We use a SOCKS5 proxy and we just sent our credentials. */
248 #define PROXY_SOCKS5_WANT_AUTH_RFC1929_OK 6
249 /* We use a SOCKS5 proxy and we just sent our CONNECT command. */
250 #define PROXY_SOCKS5_WANT_CONNECT_OK 7
251 /* We use a proxy and we CONNECTed successfully!. */
252 #define PROXY_CONNECTED 8
254 /** True iff <b>x</b> is an edge connection. */
255 #define CONN_IS_EDGE(x) \
256 ((x)->type == CONN_TYPE_EXIT || (x)->type == CONN_TYPE_AP)
258 /** State for any listener connection. */
259 #define LISTENER_STATE_READY 0
261 #define OR_CONN_STATE_MIN_ 1
262 /** State for a connection to an OR: waiting for connect() to finish. */
263 #define OR_CONN_STATE_CONNECTING 1
264 /** State for a connection to an OR: waiting for proxy handshake to complete */
265 #define OR_CONN_STATE_PROXY_HANDSHAKING 2
266 /** State for an OR connection client: SSL is handshaking, not done
267 * yet. */
268 #define OR_CONN_STATE_TLS_HANDSHAKING 3
269 /** State for a connection to an OR: We're doing a second SSL handshake for
270 * renegotiation purposes. (V2 handshake only.) */
271 #define OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING 4
272 /** State for a connection at an OR: We're waiting for the client to
273 * renegotiate (to indicate a v2 handshake) or send a versions cell (to
274 * indicate a v3 handshake) */
275 #define OR_CONN_STATE_TLS_SERVER_RENEGOTIATING 5
276 /** State for an OR connection: We're done with our SSL handshake, we've done
277 * renegotiation, but we haven't yet negotiated link protocol versions and
278 * sent a netinfo cell. */
279 #define OR_CONN_STATE_OR_HANDSHAKING_V2 6
280 /** State for an OR connection: We're done with our SSL handshake, but we
281 * haven't yet negotiated link protocol versions, done a V3 handshake, and
282 * sent a netinfo cell. */
283 #define OR_CONN_STATE_OR_HANDSHAKING_V3 7
284 /** State for an OR connection: Ready to send/receive cells. */
285 #define OR_CONN_STATE_OPEN 8
286 #define OR_CONN_STATE_MAX_ 8
288 /** States of the Extended ORPort protocol. Be careful before changing
289 * the numbers: they matter. */
290 #define EXT_OR_CONN_STATE_MIN_ 1
291 /** Extended ORPort authentication is waiting for the authentication
292 * type selected by the client. */
293 #define EXT_OR_CONN_STATE_AUTH_WAIT_AUTH_TYPE 1
294 /** Extended ORPort authentication is waiting for the client nonce. */
295 #define EXT_OR_CONN_STATE_AUTH_WAIT_CLIENT_NONCE 2
296 /** Extended ORPort authentication is waiting for the client hash. */
297 #define EXT_OR_CONN_STATE_AUTH_WAIT_CLIENT_HASH 3
298 #define EXT_OR_CONN_STATE_AUTH_MAX 3
299 /** Authentication finished and the Extended ORPort is now accepting
300 * traffic. */
301 #define EXT_OR_CONN_STATE_OPEN 4
302 /** Extended ORPort is flushing its last messages and preparing to
303 * start accepting OR connections. */
304 #define EXT_OR_CONN_STATE_FLUSHING 5
305 #define EXT_OR_CONN_STATE_MAX_ 5
307 #define EXIT_CONN_STATE_MIN_ 1
308 /** State for an exit connection: waiting for response from DNS farm. */
309 #define EXIT_CONN_STATE_RESOLVING 1
310 /** State for an exit connection: waiting for connect() to finish. */
311 #define EXIT_CONN_STATE_CONNECTING 2
312 /** State for an exit connection: open and ready to transmit data. */
313 #define EXIT_CONN_STATE_OPEN 3
314 /** State for an exit connection: waiting to be removed. */
315 #define EXIT_CONN_STATE_RESOLVEFAILED 4
316 #define EXIT_CONN_STATE_MAX_ 4
318 /* The AP state values must be disjoint from the EXIT state values. */
319 #define AP_CONN_STATE_MIN_ 5
320 /** State for a SOCKS connection: waiting for SOCKS request. */
321 #define AP_CONN_STATE_SOCKS_WAIT 5
322 /** State for a SOCKS connection: got a y.onion URL; waiting to receive
323 * rendezvous descriptor. */
324 #define AP_CONN_STATE_RENDDESC_WAIT 6
325 /** The controller will attach this connection to a circuit; it isn't our
326 * job to do so. */
327 #define AP_CONN_STATE_CONTROLLER_WAIT 7
328 /** State for a SOCKS connection: waiting for a completed circuit. */
329 #define AP_CONN_STATE_CIRCUIT_WAIT 8
330 /** State for a SOCKS connection: sent BEGIN, waiting for CONNECTED. */
331 #define AP_CONN_STATE_CONNECT_WAIT 9
332 /** State for a SOCKS connection: sent RESOLVE, waiting for RESOLVED. */
333 #define AP_CONN_STATE_RESOLVE_WAIT 10
334 /** State for a SOCKS connection: ready to send and receive. */
335 #define AP_CONN_STATE_OPEN 11
336 /** State for a transparent natd connection: waiting for original
337 * destination. */
338 #define AP_CONN_STATE_NATD_WAIT 12
339 #define AP_CONN_STATE_MAX_ 12
341 /** True iff the AP_CONN_STATE_* value <b>s</b> means that the corresponding
342 * edge connection is not attached to any circuit. */
343 #define AP_CONN_STATE_IS_UNATTACHED(s) \
344 ((s) <= AP_CONN_STATE_CIRCUIT_WAIT || (s) == AP_CONN_STATE_NATD_WAIT)
346 #define DIR_CONN_STATE_MIN_ 1
347 /** State for connection to directory server: waiting for connect(). */
348 #define DIR_CONN_STATE_CONNECTING 1
349 /** State for connection to directory server: sending HTTP request. */
350 #define DIR_CONN_STATE_CLIENT_SENDING 2
351 /** State for connection to directory server: reading HTTP response. */
352 #define DIR_CONN_STATE_CLIENT_READING 3
353 /** State for connection to directory server: happy and finished. */
354 #define DIR_CONN_STATE_CLIENT_FINISHED 4
355 /** State for connection at directory server: waiting for HTTP request. */
356 #define DIR_CONN_STATE_SERVER_COMMAND_WAIT 5
357 /** State for connection at directory server: sending HTTP response. */
358 #define DIR_CONN_STATE_SERVER_WRITING 6
359 #define DIR_CONN_STATE_MAX_ 6
361 /** True iff the purpose of <b>conn</b> means that it's a server-side
362 * directory connection. */
363 #define DIR_CONN_IS_SERVER(conn) ((conn)->purpose == DIR_PURPOSE_SERVER)
365 #define CONTROL_CONN_STATE_MIN_ 1
366 /** State for a control connection: Authenticated and accepting v1 commands. */
367 #define CONTROL_CONN_STATE_OPEN 1
368 /** State for a control connection: Waiting for authentication; speaking
369 * protocol v1. */
370 #define CONTROL_CONN_STATE_NEEDAUTH 2
371 #define CONTROL_CONN_STATE_MAX_ 2
373 #define DIR_PURPOSE_MIN_ 4
374 /** A connection to a directory server: set after a v2 rendezvous
375 * descriptor is downloaded. */
376 #define DIR_PURPOSE_HAS_FETCHED_RENDDESC_V2 4
377 /** A connection to a directory server: download one or more server
378 * descriptors. */
379 #define DIR_PURPOSE_FETCH_SERVERDESC 6
380 /** A connection to a directory server: download one or more extra-info
381 * documents. */
382 #define DIR_PURPOSE_FETCH_EXTRAINFO 7
383 /** A connection to a directory server: upload a server descriptor. */
384 #define DIR_PURPOSE_UPLOAD_DIR 8
385 /** A connection to a directory server: upload a v3 networkstatus vote. */
386 #define DIR_PURPOSE_UPLOAD_VOTE 10
387 /** A connection to a directory server: upload a v3 consensus signature */
388 #define DIR_PURPOSE_UPLOAD_SIGNATURES 11
389 /** A connection to a directory server: download one or more v3 networkstatus
390 * votes. */
391 #define DIR_PURPOSE_FETCH_STATUS_VOTE 12
392 /** A connection to a directory server: download a v3 detached signatures
393 * object for a consensus. */
394 #define DIR_PURPOSE_FETCH_DETACHED_SIGNATURES 13
395 /** A connection to a directory server: download a v3 networkstatus
396 * consensus. */
397 #define DIR_PURPOSE_FETCH_CONSENSUS 14
398 /** A connection to a directory server: download one or more directory
399 * authority certificates. */
400 #define DIR_PURPOSE_FETCH_CERTIFICATE 15
402 /** Purpose for connection at a directory server. */
403 #define DIR_PURPOSE_SERVER 16
404 /** A connection to a hidden service directory server: upload a v2 rendezvous
405 * descriptor. */
406 #define DIR_PURPOSE_UPLOAD_RENDDESC_V2 17
407 /** A connection to a hidden service directory server: download a v2 rendezvous
408 * descriptor. */
409 #define DIR_PURPOSE_FETCH_RENDDESC_V2 18
410 /** A connection to a directory server: download a microdescriptor. */
411 #define DIR_PURPOSE_FETCH_MICRODESC 19
412 #define DIR_PURPOSE_MAX_ 19
414 /** True iff <b>p</b> is a purpose corresponding to uploading data to a
415 * directory server. */
416 #define DIR_PURPOSE_IS_UPLOAD(p) \
417 ((p)==DIR_PURPOSE_UPLOAD_DIR || \
418 (p)==DIR_PURPOSE_UPLOAD_VOTE || \
419 (p)==DIR_PURPOSE_UPLOAD_SIGNATURES)
421 #define EXIT_PURPOSE_MIN_ 1
422 /** This exit stream wants to do an ordinary connect. */
423 #define EXIT_PURPOSE_CONNECT 1
424 /** This exit stream wants to do a resolve (either normal or reverse). */
425 #define EXIT_PURPOSE_RESOLVE 2
426 #define EXIT_PURPOSE_MAX_ 2
428 /* !!!! If any connection purpose is ever over 31, we must grow the type
429 * field in connection_t. */
431 /** Circuit state: I'm the origin, still haven't done all my handshakes. */
432 #define CIRCUIT_STATE_BUILDING 0
433 /** Circuit state: Waiting to process the onionskin. */
434 #define CIRCUIT_STATE_ONIONSKIN_PENDING 1
435 /** Circuit state: I'd like to deliver a create, but my n_chan is still
436 * connecting. */
437 #define CIRCUIT_STATE_CHAN_WAIT 2
438 /** Circuit state: onionskin(s) processed, ready to send/receive cells. */
439 #define CIRCUIT_STATE_OPEN 3
441 #define CIRCUIT_PURPOSE_MIN_ 1
443 /* these circuits were initiated elsewhere */
444 #define CIRCUIT_PURPOSE_OR_MIN_ 1
445 /** OR-side circuit purpose: normal circuit, at OR. */
446 #define CIRCUIT_PURPOSE_OR 1
447 /** OR-side circuit purpose: At OR, from the service, waiting for intro from
448 * clients. */
449 #define CIRCUIT_PURPOSE_INTRO_POINT 2
450 /** OR-side circuit purpose: At OR, from the client, waiting for the service.
452 #define CIRCUIT_PURPOSE_REND_POINT_WAITING 3
453 /** OR-side circuit purpose: At OR, both circuits have this purpose. */
454 #define CIRCUIT_PURPOSE_REND_ESTABLISHED 4
455 #define CIRCUIT_PURPOSE_OR_MAX_ 4
457 /* these circuits originate at this node */
459 /* here's how circ client-side purposes work:
460 * normal circuits are C_GENERAL.
461 * circuits that are c_introducing are either on their way to
462 * becoming open, or they are open and waiting for a
463 * suitable rendcirc before they send the intro.
464 * circuits that are c_introduce_ack_wait have sent the intro,
465 * but haven't gotten a response yet.
466 * circuits that are c_establish_rend are either on their way
467 * to becoming open, or they are open and have sent the
468 * establish_rendezvous cell but haven't received an ack.
469 * circuits that are c_rend_ready are open and have received a
470 * rend ack, but haven't heard from the service yet. if they have a
471 * buildstate->pending_final_cpath then they're expecting a
472 * cell from the service, else they're not.
473 * circuits that are c_rend_ready_intro_acked are open, and
474 * some intro circ has sent its intro and received an ack.
475 * circuits that are c_rend_joined are open, have heard from
476 * the service, and are talking to it.
478 /** Client-side circuit purpose: Normal circuit, with cpath. */
479 #define CIRCUIT_PURPOSE_C_GENERAL 5
480 /** Client-side circuit purpose: at the client, connecting to intro point. */
481 #define CIRCUIT_PURPOSE_C_INTRODUCING 6
482 /** Client-side circuit purpose: at the client, sent INTRODUCE1 to intro point,
483 * waiting for ACK/NAK. */
484 #define CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT 7
485 /** Client-side circuit purpose: at the client, introduced and acked, closing.
487 #define CIRCUIT_PURPOSE_C_INTRODUCE_ACKED 8
488 /** Client-side circuit purpose: at the client, waiting for ack. */
489 #define CIRCUIT_PURPOSE_C_ESTABLISH_REND 9
490 /** Client-side circuit purpose: at the client, waiting for the service. */
491 #define CIRCUIT_PURPOSE_C_REND_READY 10
492 /** Client-side circuit purpose: at the client, waiting for the service,
493 * INTRODUCE has been acknowledged. */
494 #define CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED 11
495 /** Client-side circuit purpose: at the client, rendezvous established. */
496 #define CIRCUIT_PURPOSE_C_REND_JOINED 12
497 /** This circuit is used for build time measurement only */
498 #define CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT 13
499 #define CIRCUIT_PURPOSE_C_MAX_ 13
500 /** Hidden-service-side circuit purpose: at the service, waiting for
501 * introductions. */
502 #define CIRCUIT_PURPOSE_S_ESTABLISH_INTRO 14
503 /** Hidden-service-side circuit purpose: at the service, successfully
504 * established intro. */
505 #define CIRCUIT_PURPOSE_S_INTRO 15
506 /** Hidden-service-side circuit purpose: at the service, connecting to rend
507 * point. */
508 #define CIRCUIT_PURPOSE_S_CONNECT_REND 16
509 /** Hidden-service-side circuit purpose: at the service, rendezvous
510 * established. */
511 #define CIRCUIT_PURPOSE_S_REND_JOINED 17
512 /** A testing circuit; not meant to be used for actual traffic. */
513 #define CIRCUIT_PURPOSE_TESTING 18
514 /** A controller made this circuit and Tor should not use it. */
515 #define CIRCUIT_PURPOSE_CONTROLLER 19
516 /** This circuit is used for path bias probing only */
517 #define CIRCUIT_PURPOSE_PATH_BIAS_TESTING 20
518 #define CIRCUIT_PURPOSE_MAX_ 20
519 /** A catch-all for unrecognized purposes. Currently we don't expect
520 * to make or see any circuits with this purpose. */
521 #define CIRCUIT_PURPOSE_UNKNOWN 255
523 /** True iff the circuit purpose <b>p</b> is for a circuit that
524 * originated at this node. */
525 #define CIRCUIT_PURPOSE_IS_ORIGIN(p) ((p)>CIRCUIT_PURPOSE_OR_MAX_)
526 /** True iff the circuit purpose <b>p</b> is for a circuit that originated
527 * here to serve as a client. (Hidden services don't count here.) */
528 #define CIRCUIT_PURPOSE_IS_CLIENT(p) \
529 ((p)> CIRCUIT_PURPOSE_OR_MAX_ && \
530 (p)<=CIRCUIT_PURPOSE_C_MAX_)
531 /** True iff the circuit_t <b>c</b> is actually an origin_circuit_t. */
532 #define CIRCUIT_IS_ORIGIN(c) (CIRCUIT_PURPOSE_IS_ORIGIN((c)->purpose))
533 /** True iff the circuit purpose <b>p</b> is for an established rendezvous
534 * circuit. */
535 #define CIRCUIT_PURPOSE_IS_ESTABLISHED_REND(p) \
536 ((p) == CIRCUIT_PURPOSE_C_REND_JOINED || \
537 (p) == CIRCUIT_PURPOSE_S_REND_JOINED)
538 /** True iff the circuit_t c is actually an or_circuit_t */
539 #define CIRCUIT_IS_ORCIRC(c) (((circuit_t *)(c))->magic == OR_CIRCUIT_MAGIC)
541 /** How many circuits do we want simultaneously in-progress to handle
542 * a given stream? */
543 #define MIN_CIRCUITS_HANDLING_STREAM 2
545 /* These RELAY_COMMAND constants define values for relay cell commands, and
546 * must match those defined in tor-spec.txt. */
547 #define RELAY_COMMAND_BEGIN 1
548 #define RELAY_COMMAND_DATA 2
549 #define RELAY_COMMAND_END 3
550 #define RELAY_COMMAND_CONNECTED 4
551 #define RELAY_COMMAND_SENDME 5
552 #define RELAY_COMMAND_EXTEND 6
553 #define RELAY_COMMAND_EXTENDED 7
554 #define RELAY_COMMAND_TRUNCATE 8
555 #define RELAY_COMMAND_TRUNCATED 9
556 #define RELAY_COMMAND_DROP 10
557 #define RELAY_COMMAND_RESOLVE 11
558 #define RELAY_COMMAND_RESOLVED 12
559 #define RELAY_COMMAND_BEGIN_DIR 13
560 #define RELAY_COMMAND_EXTEND2 14
561 #define RELAY_COMMAND_EXTENDED2 15
563 #define RELAY_COMMAND_ESTABLISH_INTRO 32
564 #define RELAY_COMMAND_ESTABLISH_RENDEZVOUS 33
565 #define RELAY_COMMAND_INTRODUCE1 34
566 #define RELAY_COMMAND_INTRODUCE2 35
567 #define RELAY_COMMAND_RENDEZVOUS1 36
568 #define RELAY_COMMAND_RENDEZVOUS2 37
569 #define RELAY_COMMAND_INTRO_ESTABLISHED 38
570 #define RELAY_COMMAND_RENDEZVOUS_ESTABLISHED 39
571 #define RELAY_COMMAND_INTRODUCE_ACK 40
573 /* Reasons why an OR connection is closed. */
574 #define END_OR_CONN_REASON_DONE 1
575 #define END_OR_CONN_REASON_REFUSED 2 /* connection refused */
576 #define END_OR_CONN_REASON_OR_IDENTITY 3
577 #define END_OR_CONN_REASON_CONNRESET 4 /* connection reset by peer */
578 #define END_OR_CONN_REASON_TIMEOUT 5
579 #define END_OR_CONN_REASON_NO_ROUTE 6 /* no route to host/net */
580 #define END_OR_CONN_REASON_IO_ERROR 7 /* read/write error */
581 #define END_OR_CONN_REASON_RESOURCE_LIMIT 8 /* sockets, buffers, etc */
582 #define END_OR_CONN_REASON_PT_MISSING 9 /* PT failed or not available */
583 #define END_OR_CONN_REASON_MISC 10
585 /* Reasons why we (or a remote OR) might close a stream. See tor-spec.txt for
586 * documentation of these. The values must match. */
587 #define END_STREAM_REASON_MISC 1
588 #define END_STREAM_REASON_RESOLVEFAILED 2
589 #define END_STREAM_REASON_CONNECTREFUSED 3
590 #define END_STREAM_REASON_EXITPOLICY 4
591 #define END_STREAM_REASON_DESTROY 5
592 #define END_STREAM_REASON_DONE 6
593 #define END_STREAM_REASON_TIMEOUT 7
594 #define END_STREAM_REASON_NOROUTE 8
595 #define END_STREAM_REASON_HIBERNATING 9
596 #define END_STREAM_REASON_INTERNAL 10
597 #define END_STREAM_REASON_RESOURCELIMIT 11
598 #define END_STREAM_REASON_CONNRESET 12
599 #define END_STREAM_REASON_TORPROTOCOL 13
600 #define END_STREAM_REASON_NOTDIRECTORY 14
601 #define END_STREAM_REASON_ENTRYPOLICY 15
603 /* These high-numbered end reasons are not part of the official spec,
604 * and are not intended to be put in relay end cells. They are here
605 * to be more informative when sending back socks replies to the
606 * application. */
607 /* XXXX 256 is no longer used; feel free to reuse it. */
608 /** We were unable to attach the connection to any circuit at all. */
609 /* XXXX the ways we use this one don't make a lot of sense. */
610 #define END_STREAM_REASON_CANT_ATTACH 257
611 /** We can't connect to any directories at all, so we killed our streams
612 * before they can time out. */
613 #define END_STREAM_REASON_NET_UNREACHABLE 258
614 /** This is a SOCKS connection, and the client used (or misused) the SOCKS
615 * protocol in a way we couldn't handle. */
616 #define END_STREAM_REASON_SOCKSPROTOCOL 259
617 /** This is a transparent proxy connection, but we can't extract the original
618 * target address:port. */
619 #define END_STREAM_REASON_CANT_FETCH_ORIG_DEST 260
620 /** This is a connection on the NATD port, and the destination IP:Port was
621 * either ill-formed or out-of-range. */
622 #define END_STREAM_REASON_INVALID_NATD_DEST 261
623 /** The target address is in a private network (like 127.0.0.1 or 10.0.0.1);
624 * you don't want to do that over a randomly chosen exit */
625 #define END_STREAM_REASON_PRIVATE_ADDR 262
627 /** Bitwise-and this value with endreason to mask out all flags. */
628 #define END_STREAM_REASON_MASK 511
630 /** Bitwise-or this with the argument to control_event_stream_status
631 * to indicate that the reason came from an END cell. */
632 #define END_STREAM_REASON_FLAG_REMOTE 512
633 /** Bitwise-or this with the argument to control_event_stream_status
634 * to indicate that we already sent a CLOSED stream event. */
635 #define END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED 1024
636 /** Bitwise-or this with endreason to indicate that we already sent
637 * a socks reply, and no further reply needs to be sent from
638 * connection_mark_unattached_ap(). */
639 #define END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED 2048
641 /** Reason for remapping an AP connection's address: we have a cached
642 * answer. */
643 #define REMAP_STREAM_SOURCE_CACHE 1
644 /** Reason for remapping an AP connection's address: the exit node told us an
645 * answer. */
646 #define REMAP_STREAM_SOURCE_EXIT 2
648 /* 'type' values to use in RESOLVED cells. Specified in tor-spec.txt. */
649 #define RESOLVED_TYPE_HOSTNAME 0
650 #define RESOLVED_TYPE_IPV4 4
651 #define RESOLVED_TYPE_IPV6 6
652 #define RESOLVED_TYPE_ERROR_TRANSIENT 0xF0
653 #define RESOLVED_TYPE_ERROR 0xF1
655 /* Negative reasons are internal: we never send them in a DESTROY or TRUNCATE
656 * call; they only go to the controller for tracking */
658 /* Closing introduction point that were opened in parallel. */
659 #define END_CIRC_REASON_IP_NOW_REDUNDANT -4
661 /** Our post-timeout circuit time measurement period expired.
662 * We must give up now */
663 #define END_CIRC_REASON_MEASUREMENT_EXPIRED -3
665 /** We couldn't build a path for this circuit. */
666 #define END_CIRC_REASON_NOPATH -2
667 /** Catch-all "other" reason for closing origin circuits. */
668 #define END_CIRC_AT_ORIGIN -1
670 /* Reasons why we (or a remote OR) might close a circuit. See tor-spec.txt for
671 * documentation of these. */
672 #define END_CIRC_REASON_MIN_ 0
673 #define END_CIRC_REASON_NONE 0
674 #define END_CIRC_REASON_TORPROTOCOL 1
675 #define END_CIRC_REASON_INTERNAL 2
676 #define END_CIRC_REASON_REQUESTED 3
677 #define END_CIRC_REASON_HIBERNATING 4
678 #define END_CIRC_REASON_RESOURCELIMIT 5
679 #define END_CIRC_REASON_CONNECTFAILED 6
680 #define END_CIRC_REASON_OR_IDENTITY 7
681 #define END_CIRC_REASON_CHANNEL_CLOSED 8
682 #define END_CIRC_REASON_FINISHED 9
683 #define END_CIRC_REASON_TIMEOUT 10
684 #define END_CIRC_REASON_DESTROYED 11
685 #define END_CIRC_REASON_NOSUCHSERVICE 12
686 #define END_CIRC_REASON_MAX_ 12
688 /** Bitwise-OR this with the argument to circuit_mark_for_close() or
689 * control_event_circuit_status() to indicate that the reason was
690 * passed through from a destroy or truncate cell. */
691 #define END_CIRC_REASON_FLAG_REMOTE 512
693 /** Length of 'y' portion of 'y.onion' URL. */
694 #define REND_SERVICE_ID_LEN_BASE32 16
696 /** Length of 'y.onion' including '.onion' URL. */
697 #define REND_SERVICE_ADDRESS_LEN (16+1+5)
699 /** Length of a binary-encoded rendezvous service ID. */
700 #define REND_SERVICE_ID_LEN 10
702 /** Time period for which a v2 descriptor will be valid. */
703 #define REND_TIME_PERIOD_V2_DESC_VALIDITY (24*60*60)
705 /** Time period within which two sets of v2 descriptors will be uploaded in
706 * parallel. */
707 #define REND_TIME_PERIOD_OVERLAPPING_V2_DESCS (60*60)
709 /** Number of non-consecutive replicas (i.e. distributed somewhere
710 * in the ring) for a descriptor. */
711 #define REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS 2
713 /** Number of consecutive replicas for a descriptor. */
714 #define REND_NUMBER_OF_CONSECUTIVE_REPLICAS 3
716 /** Length of v2 descriptor ID (32 base32 chars = 160 bits). */
717 #define REND_DESC_ID_V2_LEN_BASE32 32
719 /** Length of the base32-encoded secret ID part of versioned hidden service
720 * descriptors. */
721 #define REND_SECRET_ID_PART_LEN_BASE32 32
723 /** Length of the base32-encoded hash of an introduction point's
724 * identity key. */
725 #define REND_INTRO_POINT_ID_LEN_BASE32 32
727 /** Length of the descriptor cookie that is used for client authorization
728 * to hidden services. */
729 #define REND_DESC_COOKIE_LEN 16
731 /** Length of the base64-encoded descriptor cookie that is used for
732 * exchanging client authorization between hidden service and client. */
733 #define REND_DESC_COOKIE_LEN_BASE64 22
735 /** Length of client identifier in encrypted introduction points for hidden
736 * service authorization type 'basic'. */
737 #define REND_BASIC_AUTH_CLIENT_ID_LEN 4
739 /** Multiple of the number of clients to which the real number of clients
740 * is padded with fake clients for hidden service authorization type
741 * 'basic'. */
742 #define REND_BASIC_AUTH_CLIENT_MULTIPLE 16
744 /** Length of client entry consisting of client identifier and encrypted
745 * session key for hidden service authorization type 'basic'. */
746 #define REND_BASIC_AUTH_CLIENT_ENTRY_LEN (REND_BASIC_AUTH_CLIENT_ID_LEN \
747 + CIPHER_KEY_LEN)
749 /** Maximum size of v2 hidden service descriptors. */
750 #define REND_DESC_MAX_SIZE (20 * 1024)
752 /** Legal characters for use in authorized client names for a hidden
753 * service. */
754 #define REND_LEGAL_CLIENTNAME_CHARACTERS \
755 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-_"
757 /** Maximum length of authorized client names for a hidden service. */
758 #define REND_CLIENTNAME_MAX_LEN 16
760 /** Length of the rendezvous cookie that is used to connect circuits at the
761 * rendezvous point. */
762 #define REND_COOKIE_LEN DIGEST_LEN
764 /** Client authorization type that a hidden service performs. */
765 typedef enum rend_auth_type_t {
766 REND_NO_AUTH = 0,
767 REND_BASIC_AUTH = 1,
768 REND_STEALTH_AUTH = 2,
769 } rend_auth_type_t;
771 /** Client-side configuration of authorization for a hidden service. */
772 typedef struct rend_service_authorization_t {
773 uint8_t descriptor_cookie[REND_DESC_COOKIE_LEN];
774 char onion_address[REND_SERVICE_ADDRESS_LEN+1];
775 rend_auth_type_t auth_type;
776 } rend_service_authorization_t;
778 /** Client- and server-side data that is used for hidden service connection
779 * establishment. Not all fields contain data depending on where this struct
780 * is used. */
781 typedef struct rend_data_t {
782 /** Onion address (without the .onion part) that a client requests. */
783 char onion_address[REND_SERVICE_ID_LEN_BASE32+1];
785 /** Descriptor ID for each replicas computed from the onion address. If
786 * the onion address is empty, this array MUST be empty. We keep them so
787 * we know when to purge our entry in the last hsdir request table. */
788 char descriptor_id[REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS][DIGEST_LEN];
790 /** (Optional) descriptor cookie that is used by a client. */
791 char descriptor_cookie[REND_DESC_COOKIE_LEN];
793 /** Authorization type for accessing a service used by a client. */
794 rend_auth_type_t auth_type;
796 /** Descriptor ID for a client request. The control port command HSFETCH
797 * uses this. It's set if the descriptor query should only use this
798 * descriptor ID. */
799 char desc_id_fetch[DIGEST_LEN];
801 /** Hash of the hidden service's PK used by a service. */
802 char rend_pk_digest[DIGEST_LEN];
804 /** Rendezvous cookie used by both, client and service. */
805 char rend_cookie[REND_COOKIE_LEN];
807 /** List of HSDir fingerprints on which this request has been sent to.
808 * This contains binary identity digest of the directory. */
809 smartlist_t *hsdirs_fp;
811 /** Number of streams associated with this rendezvous circuit. */
812 int nr_streams;
813 } rend_data_t;
815 /** Time interval for tracking replays of DH public keys received in
816 * INTRODUCE2 cells. Used only to avoid launching multiple
817 * simultaneous attempts to connect to the same rendezvous point. */
818 #define REND_REPLAY_TIME_INTERVAL (5 * 60)
820 /** Used to indicate which way a cell is going on a circuit. */
821 typedef enum {
822 CELL_DIRECTION_IN=1, /**< The cell is moving towards the origin. */
823 CELL_DIRECTION_OUT=2, /**< The cell is moving away from the origin. */
824 } cell_direction_t;
826 /** Initial value for both sides of a circuit transmission window when the
827 * circuit is initialized. Measured in cells. */
828 #define CIRCWINDOW_START 1000
829 #define CIRCWINDOW_START_MIN 100
830 #define CIRCWINDOW_START_MAX 1000
831 /** Amount to increment a circuit window when we get a circuit SENDME. */
832 #define CIRCWINDOW_INCREMENT 100
833 /** Initial value on both sides of a stream transmission window when the
834 * stream is initialized. Measured in cells. */
835 #define STREAMWINDOW_START 500
836 /** Amount to increment a stream window when we get a stream SENDME. */
837 #define STREAMWINDOW_INCREMENT 50
839 /** Maximum number of queued cells on a circuit for which we are the
840 * midpoint before we give up and kill it. This must be >= circwindow
841 * to avoid killing innocent circuits, and >= circwindow*2 to give
842 * leaky-pipe a chance of working someday. The ORCIRC_MAX_MIDDLE_KILL_THRESH
843 * ratio controls the margin of error between emitting a warning and
844 * killing the circuit.
846 #define ORCIRC_MAX_MIDDLE_CELLS (CIRCWINDOW_START_MAX*2)
847 /** Ratio of hard (circuit kill) to soft (warning) thresholds for the
848 * ORCIRC_MAX_MIDDLE_CELLS tests.
850 #define ORCIRC_MAX_MIDDLE_KILL_THRESH (1.1f)
852 /* Cell commands. These values are defined in tor-spec.txt. */
853 #define CELL_PADDING 0
854 #define CELL_CREATE 1
855 #define CELL_CREATED 2
856 #define CELL_RELAY 3
857 #define CELL_DESTROY 4
858 #define CELL_CREATE_FAST 5
859 #define CELL_CREATED_FAST 6
860 #define CELL_VERSIONS 7
861 #define CELL_NETINFO 8
862 #define CELL_RELAY_EARLY 9
863 #define CELL_CREATE2 10
864 #define CELL_CREATED2 11
866 #define CELL_VPADDING 128
867 #define CELL_CERTS 129
868 #define CELL_AUTH_CHALLENGE 130
869 #define CELL_AUTHENTICATE 131
870 #define CELL_AUTHORIZE 132
871 #define CELL_COMMAND_MAX_ 132
873 /** How long to test reachability before complaining to the user. */
874 #define TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT (20*60)
876 /** Legal characters in a nickname. */
877 #define LEGAL_NICKNAME_CHARACTERS \
878 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
880 /** Name to use in client TLS certificates if no nickname is given. Once
881 * Tor 0.1.2.x is obsolete, we can remove this. */
882 #define DEFAULT_CLIENT_NICKNAME "client"
884 /** Name chosen by routers that don't configure nicknames */
885 #define UNNAMED_ROUTER_NICKNAME "Unnamed"
887 /** Number of bytes in a SOCKS4 header. */
888 #define SOCKS4_NETWORK_LEN 8
891 * Relay payload:
892 * Relay command [1 byte]
893 * Recognized [2 bytes]
894 * Stream ID [2 bytes]
895 * Partial SHA-1 [4 bytes]
896 * Length [2 bytes]
897 * Relay payload [498 bytes]
900 /** Number of bytes in a cell, minus cell header. */
901 #define CELL_PAYLOAD_SIZE 509
902 /** Number of bytes in a cell transmitted over the network, in the longest
903 * form */
904 #define CELL_MAX_NETWORK_SIZE 514
906 /** Maximum length of a header on a variable-length cell. */
907 #define VAR_CELL_MAX_HEADER_SIZE 7
909 static int get_cell_network_size(int wide_circ_ids);
910 static inline int get_cell_network_size(int wide_circ_ids)
912 return wide_circ_ids ? CELL_MAX_NETWORK_SIZE : CELL_MAX_NETWORK_SIZE - 2;
914 static int get_var_cell_header_size(int wide_circ_ids);
915 static inline int get_var_cell_header_size(int wide_circ_ids)
917 return wide_circ_ids ? VAR_CELL_MAX_HEADER_SIZE :
918 VAR_CELL_MAX_HEADER_SIZE - 2;
920 static int get_circ_id_size(int wide_circ_ids);
921 static inline int get_circ_id_size(int wide_circ_ids)
923 return wide_circ_ids ? 4 : 2;
926 /** Number of bytes in a relay cell's header (not including general cell
927 * header). */
928 #define RELAY_HEADER_SIZE (1+2+2+4+2)
929 /** Largest number of bytes that can fit in a relay cell payload. */
930 #define RELAY_PAYLOAD_SIZE (CELL_PAYLOAD_SIZE-RELAY_HEADER_SIZE)
932 /** Identifies a circuit on an or_connection */
933 typedef uint32_t circid_t;
934 /** Identifies a stream on a circuit */
935 typedef uint16_t streamid_t;
937 /* channel_t typedef; struct channel_s is in channel.h */
939 typedef struct channel_s channel_t;
941 /* channel_listener_t typedef; struct channel_listener_s is in channel.h */
943 typedef struct channel_listener_s channel_listener_t;
945 /* channel states for channel_t */
947 typedef enum {
949 * Closed state - channel is inactive
951 * Permitted transitions from:
952 * - CHANNEL_STATE_CLOSING
953 * Permitted transitions to:
954 * - CHANNEL_STATE_OPENING
956 CHANNEL_STATE_CLOSED = 0,
958 * Opening state - channel is trying to connect
960 * Permitted transitions from:
961 * - CHANNEL_STATE_CLOSED
962 * Permitted transitions to:
963 * - CHANNEL_STATE_CLOSING
964 * - CHANNEL_STATE_ERROR
965 * - CHANNEL_STATE_OPEN
967 CHANNEL_STATE_OPENING,
969 * Open state - channel is active and ready for use
971 * Permitted transitions from:
972 * - CHANNEL_STATE_MAINT
973 * - CHANNEL_STATE_OPENING
974 * Permitted transitions to:
975 * - CHANNEL_STATE_CLOSING
976 * - CHANNEL_STATE_ERROR
977 * - CHANNEL_STATE_MAINT
979 CHANNEL_STATE_OPEN,
981 * Maintenance state - channel is temporarily offline for subclass specific
982 * maintenance activities such as TLS renegotiation.
984 * Permitted transitions from:
985 * - CHANNEL_STATE_OPEN
986 * Permitted transitions to:
987 * - CHANNEL_STATE_CLOSING
988 * - CHANNEL_STATE_ERROR
989 * - CHANNEL_STATE_OPEN
991 CHANNEL_STATE_MAINT,
993 * Closing state - channel is shutting down
995 * Permitted transitions from:
996 * - CHANNEL_STATE_MAINT
997 * - CHANNEL_STATE_OPEN
998 * Permitted transitions to:
999 * - CHANNEL_STATE_CLOSED,
1000 * - CHANNEL_STATE_ERROR
1002 CHANNEL_STATE_CLOSING,
1004 * Error state - channel has experienced a permanent error
1006 * Permitted transitions from:
1007 * - CHANNEL_STATE_CLOSING
1008 * - CHANNEL_STATE_MAINT
1009 * - CHANNEL_STATE_OPENING
1010 * - CHANNEL_STATE_OPEN
1011 * Permitted transitions to:
1012 * - None
1014 CHANNEL_STATE_ERROR,
1016 * Placeholder for maximum state value
1018 CHANNEL_STATE_LAST
1019 } channel_state_t;
1021 /* channel listener states for channel_listener_t */
1023 typedef enum {
1025 * Closed state - channel listener is inactive
1027 * Permitted transitions from:
1028 * - CHANNEL_LISTENER_STATE_CLOSING
1029 * Permitted transitions to:
1030 * - CHANNEL_LISTENER_STATE_LISTENING
1032 CHANNEL_LISTENER_STATE_CLOSED = 0,
1034 * Listening state - channel listener is listening for incoming
1035 * connections
1037 * Permitted transitions from:
1038 * - CHANNEL_LISTENER_STATE_CLOSED
1039 * Permitted transitions to:
1040 * - CHANNEL_LISTENER_STATE_CLOSING
1041 * - CHANNEL_LISTENER_STATE_ERROR
1043 CHANNEL_LISTENER_STATE_LISTENING,
1045 * Closing state - channel listener is shutting down
1047 * Permitted transitions from:
1048 * - CHANNEL_LISTENER_STATE_LISTENING
1049 * Permitted transitions to:
1050 * - CHANNEL_LISTENER_STATE_CLOSED,
1051 * - CHANNEL_LISTENER_STATE_ERROR
1053 CHANNEL_LISTENER_STATE_CLOSING,
1055 * Error state - channel listener has experienced a permanent error
1057 * Permitted transitions from:
1058 * - CHANNEL_STATE_CLOSING
1059 * - CHANNEL_STATE_LISTENING
1060 * Permitted transitions to:
1061 * - None
1063 CHANNEL_LISTENER_STATE_ERROR,
1065 * Placeholder for maximum state value
1067 CHANNEL_LISTENER_STATE_LAST
1068 } channel_listener_state_t;
1070 /* TLS channel stuff */
1072 typedef struct channel_tls_s channel_tls_t;
1074 /* circuitmux_t typedef; struct circuitmux_s is in circuitmux.h */
1076 typedef struct circuitmux_s circuitmux_t;
1078 /** Parsed onion routing cell. All communication between nodes
1079 * is via cells. */
1080 typedef struct cell_t {
1081 circid_t circ_id; /**< Circuit which received the cell. */
1082 uint8_t command; /**< Type of the cell: one of CELL_PADDING, CELL_CREATE,
1083 * CELL_DESTROY, etc */
1084 uint8_t payload[CELL_PAYLOAD_SIZE]; /**< Cell body. */
1085 } cell_t;
1087 /** Parsed variable-length onion routing cell. */
1088 typedef struct var_cell_t {
1089 /** Type of the cell: CELL_VERSIONS, etc. */
1090 uint8_t command;
1091 /** Circuit thich received the cell */
1092 circid_t circ_id;
1093 /** Number of bytes actually stored in <b>payload</b> */
1094 uint16_t payload_len;
1095 /** Payload of this cell */
1096 uint8_t payload[FLEXIBLE_ARRAY_MEMBER];
1097 } var_cell_t;
1099 /** A parsed Extended ORPort message. */
1100 typedef struct ext_or_cmd_t {
1101 uint16_t cmd; /** Command type */
1102 uint16_t len; /** Body length */
1103 char body[FLEXIBLE_ARRAY_MEMBER]; /** Message body */
1104 } ext_or_cmd_t;
1106 /** A cell as packed for writing to the network. */
1107 typedef struct packed_cell_t {
1108 /** Next cell queued on this circuit. */
1109 TOR_SIMPLEQ_ENTRY(packed_cell_t) next;
1110 char body[CELL_MAX_NETWORK_SIZE]; /**< Cell as packed for network. */
1111 uint32_t inserted_time; /**< Time (in milliseconds since epoch, with high
1112 * bits truncated) when this cell was inserted. */
1113 } packed_cell_t;
1115 /** A queue of cells on a circuit, waiting to be added to the
1116 * or_connection_t's outbuf. */
1117 typedef struct cell_queue_t {
1118 /** Linked list of packed_cell_t*/
1119 TOR_SIMPLEQ_HEAD(cell_simpleq, packed_cell_t) head;
1120 int n; /**< The number of cells in the queue. */
1121 } cell_queue_t;
1123 /** Beginning of a RELAY cell payload. */
1124 typedef struct {
1125 uint8_t command; /**< The end-to-end relay command. */
1126 uint16_t recognized; /**< Used to tell whether cell is for us. */
1127 streamid_t stream_id; /**< Which stream is this cell associated with? */
1128 char integrity[4]; /**< Used to tell whether cell is corrupted. */
1129 uint16_t length; /**< How long is the payload body? */
1130 } relay_header_t;
1132 typedef struct buf_t buf_t;
1133 typedef struct socks_request_t socks_request_t;
1135 #define buf_t buf_t
1137 typedef struct entry_port_cfg_t {
1138 /* Client port types (socks, dns, trans, natd) only: */
1139 uint8_t isolation_flags; /**< Zero or more isolation flags */
1140 int session_group; /**< A session group, or -1 if this port is not in a
1141 * session group. */
1143 /* Socks only: */
1144 /** When both no-auth and user/pass are advertised by a SOCKS client, select
1145 * no-auth. */
1146 unsigned int socks_prefer_no_auth : 1;
1147 /** When ISO_SOCKSAUTH is in use, Keep-Alive circuits indefinitely. */
1148 unsigned int socks_iso_keep_alive : 1;
1150 /* Client port types only: */
1151 unsigned int ipv4_traffic : 1;
1152 unsigned int ipv6_traffic : 1;
1153 unsigned int prefer_ipv6 : 1;
1154 unsigned int dns_request : 1;
1155 unsigned int onion_traffic : 1;
1157 /** For a socks listener: should we cache IPv4/IPv6 DNS information that
1158 * exit nodes tell us?
1160 * @{ */
1161 unsigned int cache_ipv4_answers : 1;
1162 unsigned int cache_ipv6_answers : 1;
1163 /** @} */
1164 /** For a socks listeners: if we find an answer in our client-side DNS cache,
1165 * should we use it?
1167 * @{ */
1168 unsigned int use_cached_ipv4_answers : 1;
1169 unsigned int use_cached_ipv6_answers : 1;
1170 /** @} */
1171 /** For socks listeners: When we can automap an address to IPv4 or IPv6,
1172 * do we prefer IPv6? */
1173 unsigned int prefer_ipv6_virtaddr : 1;
1175 } entry_port_cfg_t;
1177 typedef struct server_port_cfg_t {
1178 /* Server port types (or, dir) only: */
1179 unsigned int no_advertise : 1;
1180 unsigned int no_listen : 1;
1181 unsigned int all_addrs : 1;
1182 unsigned int bind_ipv4_only : 1;
1183 unsigned int bind_ipv6_only : 1;
1184 } server_port_cfg_t;
1186 /* Values for connection_t.magic: used to make sure that downcasts (casts from
1187 * connection_t to foo_connection_t) are safe. */
1188 #define BASE_CONNECTION_MAGIC 0x7C3C304Eu
1189 #define OR_CONNECTION_MAGIC 0x7D31FF03u
1190 #define EDGE_CONNECTION_MAGIC 0xF0374013u
1191 #define ENTRY_CONNECTION_MAGIC 0xbb4a5703
1192 #define DIR_CONNECTION_MAGIC 0x9988ffeeu
1193 #define CONTROL_CONNECTION_MAGIC 0x8abc765du
1194 #define LISTENER_CONNECTION_MAGIC 0x1a1ac741u
1196 /** Description of a connection to another host or process, and associated
1197 * data.
1199 * A connection is named based on what it's connected to -- an "OR
1200 * connection" has a Tor node on the other end, an "exit
1201 * connection" has a website or other server on the other end, and an
1202 * "AP connection" has an application proxy (and thus a user) on the
1203 * other end.
1205 * Every connection has a type and a state. Connections never change
1206 * their type, but can go through many state changes in their lifetime.
1208 * Every connection has two associated input and output buffers.
1209 * Listeners don't use them. For non-listener connections, incoming
1210 * data is appended to conn->inbuf, and outgoing data is taken from
1211 * conn->outbuf. Connections differ primarily in the functions called
1212 * to fill and drain these buffers.
1214 typedef struct connection_t {
1215 uint32_t magic; /**< For memory debugging: must equal one of
1216 * *_CONNECTION_MAGIC. */
1218 uint8_t state; /**< Current state of this connection. */
1219 unsigned int type:5; /**< What kind of connection is this? */
1220 unsigned int purpose:5; /**< Only used for DIR and EXIT types currently. */
1222 /* The next fields are all one-bit booleans. Some are only applicable to
1223 * connection subtypes, but we hold them here anyway, to save space.
1225 unsigned int read_blocked_on_bw:1; /**< Boolean: should we start reading
1226 * again once the bandwidth throttler allows it? */
1227 unsigned int write_blocked_on_bw:1; /**< Boolean: should we start writing
1228 * again once the bandwidth throttler allows
1229 * writes? */
1230 unsigned int hold_open_until_flushed:1; /**< Despite this connection's being
1231 * marked for close, do we flush it
1232 * before closing it? */
1233 unsigned int inbuf_reached_eof:1; /**< Boolean: did read() return 0 on this
1234 * conn? */
1235 /** Set to 1 when we're inside connection_flushed_some to keep us from
1236 * calling connection_handle_write() recursively. */
1237 unsigned int in_flushed_some:1;
1238 /** True if connection_handle_write is currently running on this connection.
1240 unsigned int in_connection_handle_write:1;
1242 /* For linked connections:
1244 unsigned int linked:1; /**< True if there is, or has been, a linked_conn. */
1245 /** True iff we'd like to be notified about read events from the
1246 * linked conn. */
1247 unsigned int reading_from_linked_conn:1;
1248 /** True iff we're willing to write to the linked conn. */
1249 unsigned int writing_to_linked_conn:1;
1250 /** True iff we're currently able to read on the linked conn, and our
1251 * read_event should be made active with libevent. */
1252 unsigned int active_on_link:1;
1253 /** True iff we've called connection_close_immediate() on this linked
1254 * connection. */
1255 unsigned int linked_conn_is_closed:1;
1257 /** CONNECT/SOCKS proxy client handshake state (for outgoing connections). */
1258 unsigned int proxy_state:4;
1260 /** Our socket; set to TOR_INVALID_SOCKET if this connection is closed,
1261 * or has no socket. */
1262 tor_socket_t s;
1263 int conn_array_index; /**< Index into the global connection array. */
1265 struct event *read_event; /**< Libevent event structure. */
1266 struct event *write_event; /**< Libevent event structure. */
1267 buf_t *inbuf; /**< Buffer holding data read over this connection. */
1268 buf_t *outbuf; /**< Buffer holding data to write over this connection. */
1269 size_t outbuf_flushlen; /**< How much data should we try to flush from the
1270 * outbuf? */
1271 time_t timestamp_lastread; /**< When was the last time libevent said we could
1272 * read? */
1273 time_t timestamp_lastwritten; /**< When was the last time libevent said we
1274 * could write? */
1276 time_t timestamp_created; /**< When was this connection_t created? */
1278 int socket_family; /**< Address family of this connection's socket. Usually
1279 * AF_INET, but it can also be AF_UNIX, or AF_INET6 */
1280 tor_addr_t addr; /**< IP that socket "s" is directly connected to;
1281 * may be the IP address for a proxy or pluggable transport,
1282 * see "address" for the address of the final destination.
1284 uint16_t port; /**< If non-zero, port that socket "s" is directly connected
1285 * to; may be the port for a proxy or pluggable transport,
1286 * see "address" for the port at the final destination. */
1287 uint16_t marked_for_close; /**< Should we close this conn on the next
1288 * iteration of the main loop? (If true, holds
1289 * the line number where this connection was
1290 * marked.) */
1291 const char *marked_for_close_file; /**< For debugging: in which file were
1292 * we marked for close? */
1293 char *address; /**< FQDN (or IP) and port of the final destination for this
1294 * connection; this is always the remote address, it is
1295 * passed to a proxy or pluggable transport if one in use.
1296 * See "addr" and "port" for the address that socket "s" is
1297 * directly connected to.
1298 * strdup into this, because free_connection() frees it. */
1299 /** Another connection that's connected to this one in lieu of a socket. */
1300 struct connection_t *linked_conn;
1302 /** Unique identifier for this connection on this Tor instance. */
1303 uint64_t global_identifier;
1305 /** Bytes read since last call to control_event_conn_bandwidth_used().
1306 * Only used if we're configured to emit CONN_BW events. */
1307 uint32_t n_read_conn_bw;
1309 /** Bytes written since last call to control_event_conn_bandwidth_used().
1310 * Only used if we're configured to emit CONN_BW events. */
1311 uint32_t n_written_conn_bw;
1312 } connection_t;
1314 /** Subtype of connection_t; used for a listener socket. */
1315 typedef struct listener_connection_t {
1316 connection_t base_;
1318 /** If the connection is a CONN_TYPE_AP_DNS_LISTENER, this field points
1319 * to the evdns_server_port it uses to listen to and answer connections. */
1320 struct evdns_server_port *dns_server_port;
1322 entry_port_cfg_t entry_cfg;
1324 } listener_connection_t;
1326 /** Minimum length of the random part of an AUTH_CHALLENGE cell. */
1327 #define OR_AUTH_CHALLENGE_LEN 32
1330 * @name Certificate types for CERTS cells.
1332 * These values are defined by the protocol, and affect how an X509
1333 * certificate in a CERTS cell is interpreted and used.
1335 * @{ */
1336 /** A certificate that authenticates a TLS link key. The subject key
1337 * must match the key used in the TLS handshake; it must be signed by
1338 * the identity key. */
1339 #define OR_CERT_TYPE_TLS_LINK 1
1340 /** A self-signed identity certificate. The subject key must be a
1341 * 1024-bit RSA key. */
1342 #define OR_CERT_TYPE_ID_1024 2
1343 /** A certificate that authenticates a key used in an AUTHENTICATE cell
1344 * in the v3 handshake. The subject key must be a 1024-bit RSA key; it
1345 * must be signed by the identity key */
1346 #define OR_CERT_TYPE_AUTH_1024 3
1347 /* DOCDOC */
1348 #define OR_CERT_TYPE_RSA_ED_CROSSCERT 7
1349 /**@}*/
1351 /** The one currently supported type of AUTHENTICATE cell. It contains
1352 * a bunch of structures signed with an RSA1024 key. The signed
1353 * structures include a HMAC using negotiated TLS secrets, and a digest
1354 * of all cells sent or received before the AUTHENTICATE cell (including
1355 * the random server-generated AUTH_CHALLENGE cell).
1357 #define AUTHTYPE_RSA_SHA256_TLSSECRET 1
1359 /** The length of the part of the AUTHENTICATE cell body that the client and
1360 * server can generate independently (when using RSA_SHA256_TLSSECRET). It
1361 * contains everything except the client's timestamp, the client's randomly
1362 * generated nonce, and the signature. */
1363 #define V3_AUTH_FIXED_PART_LEN (8+(32*6))
1364 /** The length of the part of the AUTHENTICATE cell body that the client
1365 * signs. */
1366 #define V3_AUTH_BODY_LEN (V3_AUTH_FIXED_PART_LEN + 8 + 16)
1368 /** Stores flags and information related to the portion of a v2/v3 Tor OR
1369 * connection handshake that happens after the TLS handshake is finished.
1371 typedef struct or_handshake_state_t {
1372 /** When was the VERSIONS cell sent on this connection? Used to get
1373 * an estimate of the skew in the returning NETINFO reply. */
1374 time_t sent_versions_at;
1375 /** True iff we originated this connection */
1376 unsigned int started_here : 1;
1377 /** True iff we have received and processed a VERSIONS cell. */
1378 unsigned int received_versions : 1;
1379 /** True iff we have received and processed an AUTH_CHALLENGE cell */
1380 unsigned int received_auth_challenge : 1;
1381 /** True iff we have received and processed a CERTS cell. */
1382 unsigned int received_certs_cell : 1;
1383 /** True iff we have received and processed an AUTHENTICATE cell */
1384 unsigned int received_authenticate : 1;
1386 /* True iff we've received valid authentication to some identity. */
1387 unsigned int authenticated : 1;
1389 /* True iff we have sent a netinfo cell */
1390 unsigned int sent_netinfo : 1;
1392 /** True iff we should feed outgoing cells into digest_sent and
1393 * digest_received respectively.
1395 * From the server's side of the v3 handshake, we want to capture everything
1396 * from the VERSIONS cell through and including the AUTH_CHALLENGE cell.
1397 * From the client's, we want to capture everything from the VERSIONS cell
1398 * through but *not* including the AUTHENTICATE cell.
1400 * @{ */
1401 unsigned int digest_sent_data : 1;
1402 unsigned int digest_received_data : 1;
1403 /**@}*/
1405 /** Identity digest that we have received and authenticated for our peer
1406 * on this connection. */
1407 uint8_t authenticated_peer_id[DIGEST_LEN];
1409 /** Digests of the cells that we have sent or received as part of a V3
1410 * handshake. Used for making and checking AUTHENTICATE cells.
1412 * @{
1414 crypto_digest_t *digest_sent;
1415 crypto_digest_t *digest_received;
1416 /** @} */
1418 /** Certificates that a connection initiator sent us in a CERTS cell; we're
1419 * holding on to them until we get an AUTHENTICATE cell.
1421 * @{
1423 /** The cert for the key that's supposed to sign the AUTHENTICATE cell */
1424 tor_x509_cert_t *auth_cert;
1425 /** A self-signed identity certificate */
1426 tor_x509_cert_t *id_cert;
1427 /**@}*/
1428 } or_handshake_state_t;
1430 /** Length of Extended ORPort connection identifier. */
1431 #define EXT_OR_CONN_ID_LEN DIGEST_LEN /* 20 */
1433 * OR_CONN_HIGHWATER and OR_CONN_LOWWATER moved from connection_or.c so
1434 * channeltls.c can see them too.
1437 /** When adding cells to an OR connection's outbuf, keep adding until the
1438 * outbuf is at least this long, or we run out of cells. */
1439 #define OR_CONN_HIGHWATER (32*1024)
1441 /** Add cells to an OR connection's outbuf whenever the outbuf's data length
1442 * drops below this size. */
1443 #define OR_CONN_LOWWATER (16*1024)
1445 /** Subtype of connection_t for an "OR connection" -- that is, one that speaks
1446 * cells over TLS. */
1447 typedef struct or_connection_t {
1448 connection_t base_;
1450 /** Hash of the public RSA key for the other side's identity key, or zeroes
1451 * if the other side hasn't shown us a valid identity key. */
1452 char identity_digest[DIGEST_LEN];
1454 /** Extended ORPort connection identifier. */
1455 char *ext_or_conn_id;
1456 /** This is the ClientHash value we expect to receive from the
1457 * client during the Extended ORPort authentication protocol. We
1458 * compute it upon receiving the ClientNoce from the client, and we
1459 * compare it with the acual ClientHash value sent by the
1460 * client. */
1461 char *ext_or_auth_correct_client_hash;
1462 /** String carrying the name of the pluggable transport
1463 * (e.g. "obfs2") that is obfuscating this connection. If no
1464 * pluggable transports are used, it's NULL. */
1465 char *ext_or_transport;
1467 char *nickname; /**< Nickname of OR on other side (if any). */
1469 tor_tls_t *tls; /**< TLS connection state. */
1470 int tls_error; /**< Last tor_tls error code. */
1471 /** When we last used this conn for any client traffic. If not
1472 * recent, we can rate limit it further. */
1474 /* Channel using this connection */
1475 channel_tls_t *chan;
1477 tor_addr_t real_addr; /**< The actual address that this connection came from
1478 * or went to. The <b>addr</b> field is prone to
1479 * getting overridden by the address from the router
1480 * descriptor matching <b>identity_digest</b>. */
1482 /** Should this connection be used for extending circuits to the server
1483 * matching the <b>identity_digest</b> field? Set to true if we're pretty
1484 * sure we aren't getting MITMed, either because we're connected to an
1485 * address listed in a server descriptor, or because an authenticated
1486 * NETINFO cell listed the address we're connected to as recognized. */
1487 unsigned int is_canonical:1;
1489 /** True iff we have decided that the other end of this connection
1490 * is a client. Connections with this flag set should never be used
1491 * to satisfy an EXTEND request. */
1492 unsigned int is_connection_with_client:1;
1493 /** True iff this is an outgoing connection. */
1494 unsigned int is_outgoing:1;
1495 unsigned int proxy_type:2; /**< One of PROXY_NONE...PROXY_SOCKS5 */
1496 unsigned int wide_circ_ids:1;
1497 /** True iff this connection has had its bootstrap failure logged with
1498 * control_event_bootstrap_problem. */
1499 unsigned int have_noted_bootstrap_problem:1;
1501 uint16_t link_proto; /**< What protocol version are we using? 0 for
1502 * "none negotiated yet." */
1503 uint16_t idle_timeout; /**< How long can this connection sit with no
1504 * circuits on it before we close it? Based on
1505 * IDLE_CIRCUIT_TIMEOUT_{NON,}CANONICAL and
1506 * on is_canonical, randomized. */
1507 or_handshake_state_t *handshake_state; /**< If we are setting this connection
1508 * up, state information to do so. */
1510 time_t timestamp_lastempty; /**< When was the outbuf last completely empty?*/
1512 /* bandwidth* and *_bucket only used by ORs in OPEN state: */
1513 int bandwidthrate; /**< Bytes/s added to the bucket. (OPEN ORs only.) */
1514 int bandwidthburst; /**< Max bucket size for this conn. (OPEN ORs only.) */
1515 int read_bucket; /**< When this hits 0, stop receiving. Every second we
1516 * add 'bandwidthrate' to this, capping it at
1517 * bandwidthburst. (OPEN ORs only) */
1518 int write_bucket; /**< When this hits 0, stop writing. Like read_bucket. */
1520 struct or_connection_t *next_with_same_id; /**< Next connection with same
1521 * identity digest as this one. */
1522 /** Last emptied read token bucket in msec since midnight; only used if
1523 * TB_EMPTY events are enabled. */
1524 uint32_t read_emptied_time;
1525 /** Last emptied write token bucket in msec since midnight; only used if
1526 * TB_EMPTY events are enabled. */
1527 uint32_t write_emptied_time;
1530 * Count the number of bytes flushed out on this orconn, and the number of
1531 * bytes TLS actually sent - used for overhead estimation for scheduling.
1533 uint64_t bytes_xmitted, bytes_xmitted_by_tls;
1534 } or_connection_t;
1536 /** Subtype of connection_t for an "edge connection" -- that is, an entry (ap)
1537 * connection, or an exit. */
1538 typedef struct edge_connection_t {
1539 connection_t base_;
1541 struct edge_connection_t *next_stream; /**< Points to the next stream at this
1542 * edge, if any */
1543 int package_window; /**< How many more relay cells can I send into the
1544 * circuit? */
1545 int deliver_window; /**< How many more relay cells can end at me? */
1547 struct circuit_t *on_circuit; /**< The circuit (if any) that this edge
1548 * connection is using. */
1550 /** A pointer to which node in the circ this conn exits at. Set for AP
1551 * connections and for hidden service exit connections. */
1552 struct crypt_path_t *cpath_layer;
1553 /** What rendezvous service are we querying for (if an AP) or providing (if
1554 * an exit)? */
1555 rend_data_t *rend_data;
1557 uint32_t address_ttl; /**< TTL for address-to-addr mapping on exit
1558 * connection. Exit connections only. */
1559 uint32_t begincell_flags; /** Flags sent or received in the BEGIN cell
1560 * for this connection */
1562 streamid_t stream_id; /**< The stream ID used for this edge connection on its
1563 * circuit */
1565 /** The reason why this connection is closing; passed to the controller. */
1566 uint16_t end_reason;
1568 /** Bytes read since last call to control_event_stream_bandwidth_used() */
1569 uint32_t n_read;
1571 /** Bytes written since last call to control_event_stream_bandwidth_used() */
1572 uint32_t n_written;
1574 /** True iff this connection is for a DNS request only. */
1575 unsigned int is_dns_request:1;
1576 /** True iff this connection is for a PTR DNS request. (exit only) */
1577 unsigned int is_reverse_dns_lookup:1;
1579 unsigned int edge_has_sent_end:1; /**< For debugging; only used on edge
1580 * connections. Set once we've set the stream end,
1581 * and check in connection_about_to_close_connection().
1583 /** True iff we've blocked reading until the circuit has fewer queued
1584 * cells. */
1585 unsigned int edge_blocked_on_circ:1;
1587 /** Unique ID for directory requests; this used to be in connection_t, but
1588 * that's going away and being used on channels instead. We still tag
1589 * edge connections with dirreq_id from circuits, so it's copied here. */
1590 uint64_t dirreq_id;
1591 } edge_connection_t;
1593 /** Subtype of edge_connection_t for an "entry connection" -- that is, a SOCKS
1594 * connection, a DNS request, a TransPort connection or a NATD connection */
1595 typedef struct entry_connection_t {
1596 edge_connection_t edge_;
1598 /** Nickname of planned exit node -- used with .exit support. */
1599 char *chosen_exit_name;
1601 socks_request_t *socks_request; /**< SOCKS structure describing request (AP
1602 * only.) */
1604 /* === Isolation related, AP only. === */
1605 entry_port_cfg_t entry_cfg;
1606 /** AP only: The newnym epoch in which we created this connection. */
1607 unsigned nym_epoch;
1609 /** AP only: The original requested address before we rewrote it. */
1610 char *original_dest_address;
1611 /* Other fields to isolate on already exist. The ClientAddr is addr. The
1612 ClientProtocol is a combination of type and socks_request->
1613 socks_version. SocksAuth is socks_request->username/password.
1614 DestAddr is in socks_request->address. */
1616 /** Number of times we've reassigned this application connection to
1617 * a new circuit. We keep track because the timeout is longer if we've
1618 * already retried several times. */
1619 uint8_t num_socks_retries;
1621 /** For AP connections only: buffer for data that we have sent
1622 * optimistically, which we might need to re-send if we have to
1623 * retry this connection. */
1624 buf_t *pending_optimistic_data;
1625 /* For AP connections only: buffer for data that we previously sent
1626 * optimistically which we are currently re-sending as we retry this
1627 * connection. */
1628 buf_t *sending_optimistic_data;
1630 /** If this is a DNSPort connection, this field holds the pending DNS
1631 * request that we're going to try to answer. */
1632 struct evdns_server_request *dns_server_request;
1634 #define DEBUGGING_17659
1636 #ifdef DEBUGGING_17659
1637 uint16_t marked_pending_circ_line;
1638 const char *marked_pending_circ_file;
1639 #endif
1641 #define NUM_CIRCUITS_LAUNCHED_THRESHOLD 10
1642 /** Number of times we've launched a circuit to handle this stream. If
1643 * it gets too high, that could indicate an inconsistency between our
1644 * "launch a circuit to handle this stream" logic and our "attach our
1645 * stream to one of the available circuits" logic. */
1646 unsigned int num_circuits_launched:4;
1648 /** True iff this stream must attach to a one-hop circuit (e.g. for
1649 * begin_dir). */
1650 unsigned int want_onehop:1;
1651 /** True iff this stream should use a BEGIN_DIR relay command to establish
1652 * itself rather than BEGIN (either via onehop or via a whole circuit). */
1653 unsigned int use_begindir:1;
1655 /** For AP connections only. If 1, and we fail to reach the chosen exit,
1656 * stop requiring it. */
1657 unsigned int chosen_exit_optional:1;
1658 /** For AP connections only. If non-zero, this exit node was picked as
1659 * a result of the TrackHostExit, and the value decrements every time
1660 * we fail to complete a circuit to our chosen exit -- if it reaches
1661 * zero, abandon the associated mapaddress. */
1662 unsigned int chosen_exit_retries:3;
1664 /** True iff this is an AP connection that came from a transparent or
1665 * NATd connection */
1666 unsigned int is_transparent_ap:1;
1668 /** For AP connections only: Set if this connection's target exit node
1669 * allows optimistic data (that is, data sent on this stream before
1670 * the exit has sent a CONNECTED cell) and we have chosen to use it.
1672 unsigned int may_use_optimistic_data : 1;
1674 /** Are we a socks SocksSocket listener? */
1675 unsigned int is_socks_socket:1;
1676 } entry_connection_t;
1678 typedef enum {
1679 DIR_SPOOL_NONE=0, DIR_SPOOL_SERVER_BY_DIGEST, DIR_SPOOL_SERVER_BY_FP,
1680 DIR_SPOOL_EXTRA_BY_DIGEST, DIR_SPOOL_EXTRA_BY_FP,
1681 DIR_SPOOL_CACHED_DIR, DIR_SPOOL_NETWORKSTATUS,
1682 DIR_SPOOL_MICRODESC, /* NOTE: if we add another entry, add another bit. */
1683 } dir_spool_source_t;
1684 #define dir_spool_source_bitfield_t ENUM_BF(dir_spool_source_t)
1686 /** Subtype of connection_t for an "directory connection" -- that is, an HTTP
1687 * connection to retrieve or serve directory material. */
1688 typedef struct dir_connection_t {
1689 connection_t base_;
1691 /** Which 'resource' did we ask the directory for? This is typically the part
1692 * of the URL string that defines, relative to the directory conn purpose,
1693 * what thing we want. For example, in router descriptor downloads by
1694 * descriptor digest, it contains "d/", then one ore more +-separated
1695 * fingerprints.
1697 char *requested_resource;
1698 unsigned int dirconn_direct:1; /**< Is this dirconn direct, or via Tor? */
1700 /* Used only for server sides of some dir connections, to implement
1701 * "spooling" of directory material to the outbuf. Otherwise, we'd have
1702 * to append everything to the outbuf in one enormous chunk. */
1703 /** What exactly are we spooling right now? */
1704 dir_spool_source_bitfield_t dir_spool_src : 3;
1706 /** If we're fetching descriptors, what router purpose shall we assign
1707 * to them? */
1708 uint8_t router_purpose;
1709 /** List of fingerprints for networkstatuses or descriptors to be spooled. */
1710 smartlist_t *fingerprint_stack;
1711 /** A cached_dir_t object that we're currently spooling out */
1712 struct cached_dir_t *cached_dir;
1713 /** The current offset into cached_dir. */
1714 off_t cached_dir_offset;
1715 /** The zlib object doing on-the-fly compression for spooled data. */
1716 tor_zlib_state_t *zlib_state;
1718 /** What rendezvous service are we querying for? */
1719 rend_data_t *rend_data;
1721 char identity_digest[DIGEST_LEN]; /**< Hash of the public RSA key for
1722 * the directory server's signing key. */
1724 /** Unique ID for directory requests; this used to be in connection_t, but
1725 * that's going away and being used on channels instead. The dirserver still
1726 * needs this for the incoming side, so it's moved here. */
1727 uint64_t dirreq_id;
1728 } dir_connection_t;
1730 /** Subtype of connection_t for an connection to a controller. */
1731 typedef struct control_connection_t {
1732 connection_t base_;
1734 uint64_t event_mask; /**< Bitfield: which events does this controller
1735 * care about?
1736 * EVENT_MAX_ is >31, so we need a 64 bit mask */
1738 /** True if we have sent a protocolinfo reply on this connection. */
1739 unsigned int have_sent_protocolinfo:1;
1740 /** True if we have received a takeownership command on this
1741 * connection. */
1742 unsigned int is_owning_control_connection:1;
1744 /** List of ephemeral onion services belonging to this connection. */
1745 smartlist_t *ephemeral_onion_services;
1747 /** If we have sent an AUTHCHALLENGE reply on this connection and
1748 * have not received a successful AUTHENTICATE command, points to
1749 * the value which the client must send to authenticate itself;
1750 * otherwise, NULL. */
1751 char *safecookie_client_hash;
1753 /** Amount of space allocated in incoming_cmd. */
1754 uint32_t incoming_cmd_len;
1755 /** Number of bytes currently stored in incoming_cmd. */
1756 uint32_t incoming_cmd_cur_len;
1757 /** A control command that we're reading from the inbuf, but which has not
1758 * yet arrived completely. */
1759 char *incoming_cmd;
1760 } control_connection_t;
1762 /** Cast a connection_t subtype pointer to a connection_t **/
1763 #define TO_CONN(c) (&(((c)->base_)))
1764 /** Helper macro: Given a pointer to to.base_, of type from*, return &to. */
1765 #define DOWNCAST(to, ptr) ((to*)SUBTYPE_P(ptr, to, base_))
1767 /** Cast a entry_connection_t subtype pointer to a edge_connection_t **/
1768 #define ENTRY_TO_EDGE_CONN(c) (&(((c))->edge_))
1769 /** Cast a entry_connection_t subtype pointer to a connection_t **/
1770 #define ENTRY_TO_CONN(c) (TO_CONN(ENTRY_TO_EDGE_CONN(c)))
1772 /** Convert a connection_t* to an or_connection_t*; assert if the cast is
1773 * invalid. */
1774 static or_connection_t *TO_OR_CONN(connection_t *);
1775 /** Convert a connection_t* to a dir_connection_t*; assert if the cast is
1776 * invalid. */
1777 static dir_connection_t *TO_DIR_CONN(connection_t *);
1778 /** Convert a connection_t* to an edge_connection_t*; assert if the cast is
1779 * invalid. */
1780 static edge_connection_t *TO_EDGE_CONN(connection_t *);
1781 /** Convert a connection_t* to an entry_connection_t*; assert if the cast is
1782 * invalid. */
1783 static entry_connection_t *TO_ENTRY_CONN(connection_t *);
1784 /** Convert a edge_connection_t* to an entry_connection_t*; assert if the cast
1785 * is invalid. */
1786 static entry_connection_t *EDGE_TO_ENTRY_CONN(edge_connection_t *);
1787 /** Convert a connection_t* to an control_connection_t*; assert if the cast is
1788 * invalid. */
1789 static control_connection_t *TO_CONTROL_CONN(connection_t *);
1790 /** Convert a connection_t* to an listener_connection_t*; assert if the cast is
1791 * invalid. */
1792 static listener_connection_t *TO_LISTENER_CONN(connection_t *);
1794 static inline or_connection_t *TO_OR_CONN(connection_t *c)
1796 tor_assert(c->magic == OR_CONNECTION_MAGIC);
1797 return DOWNCAST(or_connection_t, c);
1799 static inline dir_connection_t *TO_DIR_CONN(connection_t *c)
1801 tor_assert(c->magic == DIR_CONNECTION_MAGIC);
1802 return DOWNCAST(dir_connection_t, c);
1804 static inline edge_connection_t *TO_EDGE_CONN(connection_t *c)
1806 tor_assert(c->magic == EDGE_CONNECTION_MAGIC ||
1807 c->magic == ENTRY_CONNECTION_MAGIC);
1808 return DOWNCAST(edge_connection_t, c);
1810 static inline entry_connection_t *TO_ENTRY_CONN(connection_t *c)
1812 tor_assert(c->magic == ENTRY_CONNECTION_MAGIC);
1813 return (entry_connection_t*) SUBTYPE_P(c, entry_connection_t, edge_.base_);
1815 static inline entry_connection_t *EDGE_TO_ENTRY_CONN(edge_connection_t *c)
1817 tor_assert(c->base_.magic == ENTRY_CONNECTION_MAGIC);
1818 return (entry_connection_t*) SUBTYPE_P(c, entry_connection_t, edge_);
1820 static inline control_connection_t *TO_CONTROL_CONN(connection_t *c)
1822 tor_assert(c->magic == CONTROL_CONNECTION_MAGIC);
1823 return DOWNCAST(control_connection_t, c);
1825 static inline listener_connection_t *TO_LISTENER_CONN(connection_t *c)
1827 tor_assert(c->magic == LISTENER_CONNECTION_MAGIC);
1828 return DOWNCAST(listener_connection_t, c);
1831 /** What action type does an address policy indicate: accept or reject? */
1832 typedef enum {
1833 ADDR_POLICY_ACCEPT=1,
1834 ADDR_POLICY_REJECT=2,
1835 } addr_policy_action_t;
1836 #define addr_policy_action_bitfield_t ENUM_BF(addr_policy_action_t)
1838 /** A reference-counted address policy rule. */
1839 typedef struct addr_policy_t {
1840 int refcnt; /**< Reference count */
1841 /** What to do when the policy matches.*/
1842 addr_policy_action_bitfield_t policy_type:2;
1843 unsigned int is_private:1; /**< True iff this is the pseudo-address,
1844 * "private". */
1845 unsigned int is_canonical:1; /**< True iff this policy is the canonical
1846 * copy (stored in a hash table to avoid
1847 * duplication of common policies) */
1848 maskbits_t maskbits; /**< Accept/reject all addresses <b>a</b> such that the
1849 * first <b>maskbits</b> bits of <b>a</b> match
1850 * <b>addr</b>. */
1851 /** Base address to accept or reject.
1853 * Note that wildcards are treated
1854 * differntly depending on address family. An AF_UNSPEC address means
1855 * "All addresses, IPv4 or IPv6." An AF_INET address with maskbits==0 means
1856 * "All IPv4 addresses" and an AF_INET6 address with maskbits == 0 means
1857 * "All IPv6 addresses".
1859 tor_addr_t addr;
1860 uint16_t prt_min; /**< Lowest port number to accept/reject. */
1861 uint16_t prt_max; /**< Highest port number to accept/reject. */
1862 } addr_policy_t;
1864 /** A cached_dir_t represents a cacheable directory object, along with its
1865 * compressed form. */
1866 typedef struct cached_dir_t {
1867 char *dir; /**< Contents of this object, NUL-terminated. */
1868 char *dir_z; /**< Compressed contents of this object. */
1869 size_t dir_len; /**< Length of <b>dir</b> (not counting its NUL). */
1870 size_t dir_z_len; /**< Length of <b>dir_z</b>. */
1871 time_t published; /**< When was this object published. */
1872 common_digests_t digests; /**< Digests of this object (networkstatus only) */
1873 int refcnt; /**< Reference count for this cached_dir_t. */
1874 } cached_dir_t;
1876 /** Enum used to remember where a signed_descriptor_t is stored and how to
1877 * manage the memory for signed_descriptor_body. */
1878 typedef enum {
1879 /** The descriptor isn't stored on disk at all: the copy in memory is
1880 * canonical; the saved_offset field is meaningless. */
1881 SAVED_NOWHERE=0,
1882 /** The descriptor is stored in the cached_routers file: the
1883 * signed_descriptor_body is meaningless; the signed_descriptor_len and
1884 * saved_offset are used to index into the mmaped cache file. */
1885 SAVED_IN_CACHE,
1886 /** The descriptor is stored in the cached_routers.new file: the
1887 * signed_descriptor_body and saved_offset fields are both set. */
1888 /* FFFF (We could also mmap the file and grow the mmap as needed, or
1889 * lazy-load the descriptor text by using seek and read. We don't, for
1890 * now.)
1892 SAVED_IN_JOURNAL
1893 } saved_location_t;
1894 #define saved_location_bitfield_t ENUM_BF(saved_location_t)
1896 /** Enumeration: what directory object is being downloaded?
1897 * This determines which schedule is selected to perform the download. */
1898 typedef enum {
1899 DL_SCHED_GENERIC = 0,
1900 DL_SCHED_CONSENSUS = 1,
1901 DL_SCHED_BRIDGE = 2,
1902 } download_schedule_t;
1903 #define download_schedule_bitfield_t ENUM_BF(download_schedule_t)
1905 /** Enumeration: is the download schedule for downloading from an authority,
1906 * or from any available directory mirror?
1907 * During bootstrap, "any" means a fallback (or an authority, if there
1908 * are no fallbacks).
1909 * When we have a valid consensus, "any" means any directory server. */
1910 typedef enum {
1911 DL_WANT_ANY_DIRSERVER = 0,
1912 DL_WANT_AUTHORITY = 1,
1913 } download_want_authority_t;
1914 #define download_want_authority_bitfield_t \
1915 ENUM_BF(download_want_authority_t)
1917 /** Enumeration: do we want to increment the schedule position each time a
1918 * connection is attempted (these attempts can be concurrent), or do we want
1919 * to increment the schedule position after a connection fails? */
1920 typedef enum {
1921 DL_SCHED_INCREMENT_FAILURE = 0,
1922 DL_SCHED_INCREMENT_ATTEMPT = 1,
1923 } download_schedule_increment_t;
1924 #define download_schedule_increment_bitfield_t \
1925 ENUM_BF(download_schedule_increment_t)
1927 /** Enumeration: do we want to use the random exponential backoff
1928 * mechanism? */
1929 typedef enum {
1930 DL_SCHED_DETERMINISTIC = 0,
1931 DL_SCHED_RANDOM_EXPONENTIAL = 1,
1932 } download_schedule_backoff_t;
1933 #define download_schedule_backoff_bitfield_t \
1934 ENUM_BF(download_schedule_backoff_t)
1936 /** Information about our plans for retrying downloads for a downloadable
1937 * directory object.
1938 * Each type of downloadable directory object has a corresponding retry
1939 * <b>schedule</b>, which can be different depending on whether the object is
1940 * being downloaded from an authority or a mirror (<b>want_authority</b>).
1941 * <b>next_attempt_at</b> contains the next time we will attempt to download
1942 * the object.
1943 * For schedules that <b>increment_on</b> failure, <b>n_download_failures</b>
1944 * is used to determine the position in the schedule. (Each schedule is a
1945 * smartlist of integer delays, parsed from a CSV option.) Every time a
1946 * connection attempt fails, <b>n_download_failures</b> is incremented,
1947 * the new delay value is looked up from the schedule, and
1948 * <b>next_attempt_at</b> is set delay seconds from the time the previous
1949 * connection failed. Therefore, at most one failure-based connection can be
1950 * in progress for each download_status_t.
1951 * For schedules that <b>increment_on</b> attempt, <b>n_download_attempts</b>
1952 * is used to determine the position in the schedule. Every time a
1953 * connection attempt is made, <b>n_download_attempts</b> is incremented,
1954 * the new delay value is looked up from the schedule, and
1955 * <b>next_attempt_at</b> is set delay seconds from the time the previous
1956 * connection was attempted. Therefore, multiple concurrent attempted-based
1957 * connections can be in progress for each download_status_t.
1958 * After an object is successfully downloaded, any other concurrent connections
1959 * are terminated. A new schedule which starts at position 0 is used for
1960 * subsequent downloads of the same object.
1962 typedef struct download_status_t {
1963 time_t next_attempt_at; /**< When should we try downloading this object
1964 * again? */
1965 uint8_t n_download_failures; /**< Number of failed downloads of the most
1966 * recent object, since the last success. */
1967 uint8_t n_download_attempts; /**< Number of (potentially concurrent) attempts
1968 * to download the most recent object, since
1969 * the last success. */
1970 download_schedule_bitfield_t schedule : 8; /**< What kind of object is being
1971 * downloaded? This determines the
1972 * schedule used for the download.
1974 download_want_authority_bitfield_t want_authority : 1; /**< Is the download
1975 * happening from an authority
1976 * or a mirror? This determines
1977 * the schedule used for the
1978 * download. */
1979 download_schedule_increment_bitfield_t increment_on : 1; /**< does this
1980 * schedule increment on each attempt,
1981 * or after each failure? */
1982 download_schedule_backoff_bitfield_t backoff : 1; /**< do we use the
1983 * deterministic schedule, or random
1984 * exponential backoffs? */
1985 uint8_t last_backoff_position; /**< number of attempts/failures, depending
1986 * on increment_on, when we last recalculated
1987 * the delay. Only updated if backoff
1988 * == 1. */
1989 int last_delay_used; /**< last delay used for random exponential backoff;
1990 * only updated if backoff == 1 */
1991 } download_status_t;
1993 /** If n_download_failures is this high, the download can never happen. */
1994 #define IMPOSSIBLE_TO_DOWNLOAD 255
1996 /** The max size we expect router descriptor annotations we create to
1997 * be. We'll accept larger ones if we see them on disk, but we won't
1998 * create any that are larger than this. */
1999 #define ROUTER_ANNOTATION_BUF_LEN 256
2001 /** Information need to cache an onion router's descriptor. */
2002 typedef struct signed_descriptor_t {
2003 /** Pointer to the raw server descriptor, preceded by annotations. Not
2004 * necessarily NUL-terminated. If saved_location is SAVED_IN_CACHE, this
2005 * pointer is null. */
2006 char *signed_descriptor_body;
2007 /** Length of the annotations preceding the server descriptor. */
2008 size_t annotations_len;
2009 /** Length of the server descriptor. */
2010 size_t signed_descriptor_len;
2011 /** Digest of the server descriptor, computed as specified in
2012 * dir-spec.txt. */
2013 char signed_descriptor_digest[DIGEST_LEN];
2014 /** Identity digest of the router. */
2015 char identity_digest[DIGEST_LEN];
2016 /** Declared publication time of the descriptor. */
2017 time_t published_on;
2018 /** For routerdescs only: digest of the corresponding extrainfo. */
2019 char extra_info_digest[DIGEST_LEN];
2020 /** For routerdescs only: A SHA256-digest of the extrainfo (if any) */
2021 char extra_info_digest256[DIGEST256_LEN];
2022 /** Certificate for ed25519 signing key. */
2023 struct tor_cert_st *signing_key_cert;
2024 /** For routerdescs only: Status of downloading the corresponding
2025 * extrainfo. */
2026 download_status_t ei_dl_status;
2027 /** Where is the descriptor saved? */
2028 saved_location_t saved_location;
2029 /** If saved_location is SAVED_IN_CACHE or SAVED_IN_JOURNAL, the offset of
2030 * this descriptor in the corresponding file. */
2031 off_t saved_offset;
2032 /** What position is this descriptor within routerlist->routers or
2033 * routerlist->old_routers? -1 for none. */
2034 int routerlist_index;
2035 /** The valid-until time of the most recent consensus that listed this
2036 * descriptor. 0 for "never listed in a consensus, so far as we know." */
2037 time_t last_listed_as_valid_until;
2038 /* If true, we do not ever try to save this object in the cache. */
2039 unsigned int do_not_cache : 1;
2040 /* If true, this item is meant to represent an extrainfo. */
2041 unsigned int is_extrainfo : 1;
2042 /* If true, we got an extrainfo for this item, and the digest was right,
2043 * but it was incompatible. */
2044 unsigned int extrainfo_is_bogus : 1;
2045 /* If true, we are willing to transmit this item unencrypted. */
2046 unsigned int send_unencrypted : 1;
2047 } signed_descriptor_t;
2049 /** A signed integer representing a country code. */
2050 typedef int16_t country_t;
2052 /** Information about another onion router in the network. */
2053 typedef struct {
2054 signed_descriptor_t cache_info;
2055 char *nickname; /**< Human-readable OR name. */
2057 uint32_t addr; /**< IPv4 address of OR, in host order. */
2058 uint16_t or_port; /**< Port for TLS connections. */
2059 uint16_t dir_port; /**< Port for HTTP directory connections. */
2061 /** A router's IPv6 address, if it has one. */
2062 /* XXXXX187 Actually these should probably be part of a list of addresses,
2063 * not just a special case. Use abstractions to access these; don't do it
2064 * directly. */
2065 tor_addr_t ipv6_addr;
2066 uint16_t ipv6_orport;
2068 crypto_pk_t *onion_pkey; /**< Public RSA key for onions. */
2069 crypto_pk_t *identity_pkey; /**< Public RSA key for signing. */
2070 /** Public curve25519 key for onions */
2071 curve25519_public_key_t *onion_curve25519_pkey;
2072 /** What's the earliest expiration time on all the certs in this
2073 * routerinfo? */
2074 time_t cert_expiration_time;
2076 char *platform; /**< What software/operating system is this OR using? */
2078 char *protocol_list; /**< Encoded list of subprotocol versions supported
2079 * by this OR */
2081 /* link info */
2082 uint32_t bandwidthrate; /**< How many bytes does this OR add to its token
2083 * bucket per second? */
2084 uint32_t bandwidthburst; /**< How large is this OR's token bucket? */
2085 /** How many bytes/s is this router known to handle? */
2086 uint32_t bandwidthcapacity;
2087 smartlist_t *exit_policy; /**< What streams will this OR permit
2088 * to exit on IPv4? NULL for 'reject *:*'. */
2089 /** What streams will this OR permit to exit on IPv6?
2090 * NULL for 'reject *:*' */
2091 struct short_policy_t *ipv6_exit_policy;
2092 long uptime; /**< How many seconds the router claims to have been up */
2093 smartlist_t *declared_family; /**< Nicknames of router which this router
2094 * claims are its family. */
2095 char *contact_info; /**< Declared contact info for this router. */
2096 unsigned int is_hibernating:1; /**< Whether the router claims to be
2097 * hibernating */
2098 unsigned int caches_extra_info:1; /**< Whether the router says it caches and
2099 * serves extrainfo documents. */
2100 unsigned int allow_single_hop_exits:1; /**< Whether the router says
2101 * it allows single hop exits. */
2103 unsigned int wants_to_be_hs_dir:1; /**< True iff this router claims to be
2104 * a hidden service directory. */
2105 unsigned int policy_is_reject_star:1; /**< True iff the exit policy for this
2106 * router rejects everything. */
2107 /** True if, after we have added this router, we should re-launch
2108 * tests for it. */
2109 unsigned int needs_retest_if_added:1;
2111 /** True iff this router included "tunnelled-dir-server" in its descriptor,
2112 * implying it accepts tunnelled directory requests, or it advertised
2113 * dir_port > 0. */
2114 unsigned int supports_tunnelled_dir_requests:1;
2116 /** Used during voting to indicate that we should not include an entry for
2117 * this routerinfo. Used only during voting. */
2118 unsigned int omit_from_vote:1;
2120 /** Tor can use this router for general positions in circuits; we got it
2121 * from a directory server as usual, or we're an authority and a server
2122 * uploaded it. */
2123 #define ROUTER_PURPOSE_GENERAL 0
2124 /** Tor should avoid using this router for circuit-building: we got it
2125 * from a crontroller. If the controller wants to use it, it'll have to
2126 * ask for it by identity. */
2127 #define ROUTER_PURPOSE_CONTROLLER 1
2128 /** Tor should use this router only for bridge positions in circuits: we got
2129 * it via a directory request from the bridge itself, or a bridge
2130 * authority. x*/
2131 #define ROUTER_PURPOSE_BRIDGE 2
2132 /** Tor should not use this router; it was marked in cached-descriptors with
2133 * a purpose we didn't recognize. */
2134 #define ROUTER_PURPOSE_UNKNOWN 255
2136 /* In what way did we find out about this router? One of ROUTER_PURPOSE_*.
2137 * Routers of different purposes are kept segregated and used for different
2138 * things; see notes on ROUTER_PURPOSE_* macros above.
2140 uint8_t purpose;
2141 } routerinfo_t;
2143 /** Information needed to keep and cache a signed extra-info document. */
2144 typedef struct extrainfo_t {
2145 signed_descriptor_t cache_info;
2146 /** SHA256 digest of this document */
2147 uint8_t digest256[DIGEST256_LEN];
2148 /** The router's nickname. */
2149 char nickname[MAX_NICKNAME_LEN+1];
2150 /** True iff we found the right key for this extra-info, verified the
2151 * signature, and found it to be bad. */
2152 unsigned int bad_sig : 1;
2153 /** If present, we didn't have the right key to verify this extra-info,
2154 * so this is a copy of the signature in the document. */
2155 char *pending_sig;
2156 /** Length of pending_sig. */
2157 size_t pending_sig_len;
2158 } extrainfo_t;
2160 /** Contents of a single router entry in a network status object.
2162 typedef struct routerstatus_t {
2163 time_t published_on; /**< When was this router published? */
2164 char nickname[MAX_NICKNAME_LEN+1]; /**< The nickname this router says it
2165 * has. */
2166 char identity_digest[DIGEST_LEN]; /**< Digest of the router's identity
2167 * key. */
2168 /** Digest of the router's most recent descriptor or microdescriptor.
2169 * If it's a descriptor, we only use the first DIGEST_LEN bytes. */
2170 char descriptor_digest[DIGEST256_LEN];
2171 uint32_t addr; /**< IPv4 address for this router, in host order. */
2172 uint16_t or_port; /**< OR port for this router. */
2173 uint16_t dir_port; /**< Directory port for this router. */
2174 tor_addr_t ipv6_addr; /**< IPv6 address for this router. */
2175 uint16_t ipv6_orport; /**<IPV6 OR port for this router. */
2176 unsigned int is_authority:1; /**< True iff this router is an authority. */
2177 unsigned int is_exit:1; /**< True iff this router is a good exit. */
2178 unsigned int is_stable:1; /**< True iff this router stays up a long time. */
2179 unsigned int is_fast:1; /**< True iff this router has good bandwidth. */
2180 /** True iff this router is called 'running' in the consensus. We give it
2181 * this funny name so that we don't accidentally use this bit as a view of
2182 * whether we think the router is *currently* running. If that's what you
2183 * want to know, look at is_running in node_t. */
2184 unsigned int is_flagged_running:1;
2185 unsigned int is_named:1; /**< True iff "nickname" belongs to this router. */
2186 unsigned int is_unnamed:1; /**< True iff "nickname" belongs to another
2187 * router. */
2188 unsigned int is_valid:1; /**< True iff this router isn't invalid. */
2189 unsigned int is_possible_guard:1; /**< True iff this router would be a good
2190 * choice as an entry guard. */
2191 unsigned int is_bad_exit:1; /**< True iff this node is a bad choice for
2192 * an exit node. */
2193 unsigned int is_hs_dir:1; /**< True iff this router is a v2-or-later hidden
2194 * service directory. */
2195 unsigned int is_v2_dir:1; /** True iff this router publishes an open DirPort
2196 * or it claims to accept tunnelled dir requests.
2198 /** True iff we have a proto line for this router, or a versions line
2199 * from which we could infer the protocols. */
2200 unsigned int protocols_known:1;
2202 /** True iff this router has a version or protocol list that allows it to
2203 * accept EXTEND2 cells */
2204 unsigned int supports_extend2_cells:1;
2206 unsigned int has_bandwidth:1; /**< The vote/consensus had bw info */
2207 unsigned int has_exitsummary:1; /**< The vote/consensus had exit summaries */
2208 unsigned int bw_is_unmeasured:1; /**< This is a consensus entry, with
2209 * the Unmeasured flag set. */
2211 uint32_t bandwidth_kb; /**< Bandwidth (capacity) of the router as reported in
2212 * the vote/consensus, in kilobytes/sec. */
2214 /** The consensus has guardfraction information for this router. */
2215 unsigned int has_guardfraction:1;
2216 /** The guardfraction value of this router. */
2217 uint32_t guardfraction_percentage;
2219 char *exitsummary; /**< exit policy summary -
2220 * XXX weasel: this probably should not stay a string. */
2222 /* ---- The fields below aren't derived from the networkstatus; they
2223 * hold local information only. */
2225 time_t last_dir_503_at; /**< When did this router last tell us that it
2226 * was too busy to serve directory info? */
2227 download_status_t dl_status;
2229 } routerstatus_t;
2231 /** A single entry in a parsed policy summary, describing a range of ports. */
2232 typedef struct short_policy_entry_t {
2233 uint16_t min_port, max_port;
2234 } short_policy_entry_t;
2236 /** A short_poliy_t is the parsed version of a policy summary. */
2237 typedef struct short_policy_t {
2238 /** True if the members of 'entries' are port ranges to accept; false if
2239 * they are port ranges to reject */
2240 unsigned int is_accept : 1;
2241 /** The actual number of values in 'entries'. */
2242 unsigned int n_entries : 31;
2243 /** An array of 0 or more short_policy_entry_t values, each describing a
2244 * range of ports that this policy accepts or rejects (depending on the
2245 * value of is_accept).
2247 short_policy_entry_t entries[FLEXIBLE_ARRAY_MEMBER];
2248 } short_policy_t;
2250 /** A microdescriptor is the smallest amount of information needed to build a
2251 * circuit through a router. They are generated by the directory authorities,
2252 * using information from the uploaded routerinfo documents. They are not
2253 * self-signed, but are rather authenticated by having their hash in a signed
2254 * networkstatus document. */
2255 typedef struct microdesc_t {
2256 /** Hashtable node, used to look up the microdesc by its digest. */
2257 HT_ENTRY(microdesc_t) node;
2259 /* Cache information */
2261 /** When was this microdescriptor last listed in a consensus document?
2262 * Once a microdesc has been unlisted long enough, we can drop it.
2264 time_t last_listed;
2265 /** Where is this microdescriptor currently stored? */
2266 saved_location_bitfield_t saved_location : 3;
2267 /** If true, do not attempt to cache this microdescriptor on disk. */
2268 unsigned int no_save : 1;
2269 /** If true, this microdesc has an entry in the microdesc_map */
2270 unsigned int held_in_map : 1;
2271 /** Reference count: how many node_ts have a reference to this microdesc? */
2272 unsigned int held_by_nodes;
2274 /** If saved_location == SAVED_IN_CACHE, this field holds the offset of the
2275 * microdescriptor in the cache. */
2276 off_t off;
2278 /* The string containing the microdesc. */
2280 /** A pointer to the encoded body of the microdescriptor. If the
2281 * saved_location is SAVED_IN_CACHE, then the body is a pointer into an
2282 * mmap'd region. Otherwise, it is a malloc'd string. The string might not
2283 * be NUL-terminated; take the length from <b>bodylen</b>. */
2284 char *body;
2285 /** The length of the microdescriptor in <b>body</b>. */
2286 size_t bodylen;
2287 /** A SHA256-digest of the microdescriptor. */
2288 char digest[DIGEST256_LEN];
2290 /* Fields in the microdescriptor. */
2292 /** As routerinfo_t.onion_pkey */
2293 crypto_pk_t *onion_pkey;
2294 /** As routerinfo_t.onion_curve25519_pkey */
2295 curve25519_public_key_t *onion_curve25519_pkey;
2296 /** Ed25519 identity key, if included. */
2297 ed25519_public_key_t *ed25519_identity_pkey;
2298 /** As routerinfo_t.ipv6_addr */
2299 tor_addr_t ipv6_addr;
2300 /** As routerinfo_t.ipv6_orport */
2301 uint16_t ipv6_orport;
2302 /** As routerinfo_t.family */
2303 smartlist_t *family;
2304 /** IPv4 exit policy summary */
2305 short_policy_t *exit_policy;
2306 /** IPv6 exit policy summary */
2307 short_policy_t *ipv6_exit_policy;
2309 } microdesc_t;
2311 /** A node_t represents a Tor router.
2313 * Specifically, a node_t is a Tor router as we are using it: a router that
2314 * we are considering for circuits, connections, and so on. A node_t is a
2315 * thin wrapper around the routerstatus, routerinfo, and microdesc for a
2316 * single router, and provides a consistent interface for all of them.
2318 * Also, a node_t has mutable state. While a routerinfo, a routerstatus,
2319 * and a microdesc have[*] only the information read from a router
2320 * descriptor, a consensus entry, and a microdescriptor (respectively)...
2321 * a node_t has flags based on *our own current opinion* of the node.
2323 * [*] Actually, there is some leftover information in each that is mutable.
2324 * We should try to excise that.
2326 typedef struct node_t {
2327 /* Indexing information */
2329 /** Used to look up the node_t by its identity digest. */
2330 HT_ENTRY(node_t) ht_ent;
2331 /** Position of the node within the list of nodes */
2332 int nodelist_idx;
2334 /** The identity digest of this node_t. No more than one node_t per
2335 * identity may exist at a time. */
2336 char identity[DIGEST_LEN];
2338 microdesc_t *md;
2339 routerinfo_t *ri;
2340 routerstatus_t *rs;
2342 /* local info: copied from routerstatus, then possibly frobbed based
2343 * on experience. Authorities set this stuff directly. Note that
2344 * these reflect knowledge of the primary (IPv4) OR port only. */
2346 unsigned int is_running:1; /**< As far as we know, is this OR currently
2347 * running? */
2348 unsigned int is_valid:1; /**< Has a trusted dirserver validated this OR?
2349 * (For Authdir: Have we validated this OR?) */
2350 unsigned int is_fast:1; /** Do we think this is a fast OR? */
2351 unsigned int is_stable:1; /** Do we think this is a stable OR? */
2352 unsigned int is_possible_guard:1; /**< Do we think this is an OK guard? */
2353 unsigned int is_exit:1; /**< Do we think this is an OK exit? */
2354 unsigned int is_bad_exit:1; /**< Do we think this exit is censored, borked,
2355 * or otherwise nasty? */
2356 unsigned int is_hs_dir:1; /**< True iff this router is a hidden service
2357 * directory according to the authorities. */
2359 /* Local info: warning state. */
2361 unsigned int name_lookup_warned:1; /**< Have we warned the user for referring
2362 * to this (unnamed) router by nickname?
2365 /** Local info: we treat this node as if it rejects everything */
2366 unsigned int rejects_all:1;
2368 /** Local info: this node is in our list of guards */
2369 unsigned int using_as_guard:1;
2371 /* Local info: derived. */
2373 /** True if the IPv6 OR port is preferred over the IPv4 OR port.
2374 * XX/teor - can this become out of date if the torrc changes? */
2375 unsigned int ipv6_preferred:1;
2377 /** According to the geoip db what country is this router in? */
2378 /* XXXprop186 what is this suppose to mean with multiple OR ports? */
2379 country_t country;
2381 /* The below items are used only by authdirservers for
2382 * reachability testing. */
2384 /** When was the last time we could reach this OR? */
2385 time_t last_reachable; /* IPv4. */
2386 time_t last_reachable6; /* IPv6. */
2388 } node_t;
2390 /** Linked list of microdesc hash lines for a single router in a directory
2391 * vote.
2393 typedef struct vote_microdesc_hash_t {
2394 /** Next element in the list, or NULL. */
2395 struct vote_microdesc_hash_t *next;
2396 /** The raw contents of the microdesc hash line, from the "m" through the
2397 * newline. */
2398 char *microdesc_hash_line;
2399 } vote_microdesc_hash_t;
2401 /** The claim about a single router, made in a vote. */
2402 typedef struct vote_routerstatus_t {
2403 routerstatus_t status; /**< Underlying 'status' object for this router.
2404 * Flags are redundant. */
2405 /** How many known-flags are allowed in a vote? This is the width of
2406 * the flags field of vote_routerstatus_t */
2407 #define MAX_KNOWN_FLAGS_IN_VOTE 64
2408 uint64_t flags; /**< Bit-field for all recognized flags; index into
2409 * networkstatus_t.known_flags. */
2410 char *version; /**< The version that the authority says this router is
2411 * running. */
2412 char *protocols; /**< The protocols that this authority says this router
2413 * provides. */
2414 unsigned int has_measured_bw:1; /**< The vote had a measured bw */
2415 /** True iff the vote included an entry for ed25519 ID, or included
2416 * "id ed25519 none" to indicate that there was no ed25519 ID. */
2417 unsigned int has_ed25519_listing:1;
2418 /** True if the Ed25519 listing here is the consensus-opinion for the
2419 * Ed25519 listing; false if there was no consensus on Ed25519 key status,
2420 * or if this VRS doesn't reflect it. */
2421 unsigned int ed25519_reflects_consensus:1;
2422 uint32_t measured_bw_kb; /**< Measured bandwidth (capacity) of the router */
2423 /** The hash or hashes that the authority claims this microdesc has. */
2424 vote_microdesc_hash_t *microdesc;
2425 /** Ed25519 identity for this router, or zero if it has none. */
2426 uint8_t ed25519_id[ED25519_PUBKEY_LEN];
2427 } vote_routerstatus_t;
2429 /** A signature of some document by an authority. */
2430 typedef struct document_signature_t {
2431 /** Declared SHA-1 digest of this voter's identity key */
2432 char identity_digest[DIGEST_LEN];
2433 /** Declared SHA-1 digest of signing key used by this voter. */
2434 char signing_key_digest[DIGEST_LEN];
2435 /** Algorithm used to compute the digest of the document. */
2436 digest_algorithm_t alg;
2437 /** Signature of the signed thing. */
2438 char *signature;
2439 /** Length of <b>signature</b> */
2440 int signature_len;
2441 unsigned int bad_signature : 1; /**< Set to true if we've tried to verify
2442 * the sig, and we know it's bad. */
2443 unsigned int good_signature : 1; /**< Set to true if we've verified the sig
2444 * as good. */
2445 } document_signature_t;
2447 /** Information about a single voter in a vote or a consensus. */
2448 typedef struct networkstatus_voter_info_t {
2449 /** Declared SHA-1 digest of this voter's identity key */
2450 char identity_digest[DIGEST_LEN];
2451 char *nickname; /**< Nickname of this voter */
2452 /** Digest of this voter's "legacy" identity key, if any. In vote only; for
2453 * consensuses, we treat legacy keys as additional signers. */
2454 char legacy_id_digest[DIGEST_LEN];
2455 char *address; /**< Address of this voter, in string format. */
2456 uint32_t addr; /**< Address of this voter, in IPv4, in host order. */
2457 uint16_t dir_port; /**< Directory port of this voter */
2458 uint16_t or_port; /**< OR port of this voter */
2459 char *contact; /**< Contact information for this voter. */
2460 char vote_digest[DIGEST_LEN]; /**< Digest of this voter's vote, as signed. */
2462 /* Nothing from here on is signed. */
2463 /** The signature of the document and the signature's status. */
2464 smartlist_t *sigs;
2465 } networkstatus_voter_info_t;
2467 typedef struct networkstatus_sr_info_t {
2468 /* Indicate if the dirauth partitipates in the SR protocol with its vote.
2469 * This is tied to the SR flag in the vote. */
2470 unsigned int participate:1;
2471 /* Both vote and consensus: Current and previous SRV. If list is empty,
2472 * this means none were found in either the consensus or vote. */
2473 struct sr_srv_t *previous_srv;
2474 struct sr_srv_t *current_srv;
2475 /* Vote only: List of commitments. */
2476 smartlist_t *commits;
2477 } networkstatus_sr_info_t;
2479 /** Enumerates the possible seriousness values of a networkstatus document. */
2480 typedef enum {
2481 NS_TYPE_VOTE,
2482 NS_TYPE_CONSENSUS,
2483 NS_TYPE_OPINION,
2484 } networkstatus_type_t;
2486 /** Enumerates recognized flavors of a consensus networkstatus document. All
2487 * flavors of a consensus are generated from the same set of votes, but they
2488 * present different types information to different versions of Tor. */
2489 typedef enum {
2490 FLAV_NS = 0,
2491 FLAV_MICRODESC = 1,
2492 } consensus_flavor_t;
2494 /** How many different consensus flavors are there? */
2495 #define N_CONSENSUS_FLAVORS ((int)(FLAV_MICRODESC)+1)
2497 /** A common structure to hold a v3 network status vote, or a v3 network
2498 * status consensus. */
2499 typedef struct networkstatus_t {
2500 networkstatus_type_t type; /**< Vote, consensus, or opinion? */
2501 consensus_flavor_t flavor; /**< If a consensus, what kind? */
2502 unsigned int has_measured_bws : 1;/**< True iff this networkstatus contains
2503 * measured= bandwidth values. */
2505 time_t published; /**< Vote only: Time when vote was written. */
2506 time_t valid_after; /**< Time after which this vote or consensus applies. */
2507 time_t fresh_until; /**< Time before which this is the most recent vote or
2508 * consensus. */
2509 time_t valid_until; /**< Time after which this vote or consensus should not
2510 * be used. */
2512 /** Consensus only: what method was used to produce this consensus? */
2513 int consensus_method;
2514 /** Vote only: what methods is this voter willing to use? */
2515 smartlist_t *supported_methods;
2517 /** List of 'package' lines describing hashes of downloadable packages */
2518 smartlist_t *package_lines;
2520 /** How long does this vote/consensus claim that authorities take to
2521 * distribute their votes to one another? */
2522 int vote_seconds;
2523 /** How long does this vote/consensus claim that authorities take to
2524 * distribute their consensus signatures to one another? */
2525 int dist_seconds;
2527 /** Comma-separated list of recommended client software, or NULL if this
2528 * voter has no opinion. */
2529 char *client_versions;
2530 char *server_versions;
2532 /** Lists of subprotocol versions which are _recommended_ for relays and
2533 * clients, or which are _require_ for relays and clients. Tor shouldn't
2534 * make any more network connections if a required protocol is missing.
2536 char *recommended_relay_protocols;
2537 char *recommended_client_protocols;
2538 char *required_relay_protocols;
2539 char *required_client_protocols;
2541 /** List of flags that this vote/consensus applies to routers. If a flag is
2542 * not listed here, the voter has no opinion on what its value should be. */
2543 smartlist_t *known_flags;
2545 /** List of key=value strings for the parameters in this vote or
2546 * consensus, sorted by key. */
2547 smartlist_t *net_params;
2549 /** List of key=value strings for the bw weight parameters in the
2550 * consensus. */
2551 smartlist_t *weight_params;
2553 /** List of networkstatus_voter_info_t. For a vote, only one element
2554 * is included. For a consensus, one element is included for every voter
2555 * whose vote contributed to the consensus. */
2556 smartlist_t *voters;
2558 struct authority_cert_t *cert; /**< Vote only: the voter's certificate. */
2560 /** Digests of this document, as signed. */
2561 common_digests_t digests;
2563 /** List of router statuses, sorted by identity digest. For a vote,
2564 * the elements are vote_routerstatus_t; for a consensus, the elements
2565 * are routerstatus_t. */
2566 smartlist_t *routerstatus_list;
2568 /** If present, a map from descriptor digest to elements of
2569 * routerstatus_list. */
2570 digestmap_t *desc_digest_map;
2572 /** Contains the shared random protocol data from a vote or consensus. */
2573 networkstatus_sr_info_t sr_info;
2574 } networkstatus_t;
2576 /** A set of signatures for a networkstatus consensus. Unless otherwise
2577 * noted, all fields are as for networkstatus_t. */
2578 typedef struct ns_detached_signatures_t {
2579 time_t valid_after;
2580 time_t fresh_until;
2581 time_t valid_until;
2582 strmap_t *digests; /**< Map from flavor name to digestset_t */
2583 strmap_t *signatures; /**< Map from flavor name to list of
2584 * document_signature_t */
2585 } ns_detached_signatures_t;
2587 /** Allowable types of desc_store_t. */
2588 typedef enum store_type_t {
2589 ROUTER_STORE = 0,
2590 EXTRAINFO_STORE = 1
2591 } store_type_t;
2593 /** A 'store' is a set of descriptors saved on disk, with accompanying
2594 * journal, mmaped as needed, rebuilt as needed. */
2595 typedef struct desc_store_t {
2596 /** Filename (within DataDir) for the store. We append .tmp to this
2597 * filename for a temporary file when rebuilding the store, and .new to this
2598 * filename for the journal. */
2599 const char *fname_base;
2600 /** Human-readable description of what this store contains. */
2601 const char *description;
2603 tor_mmap_t *mmap; /**< A mmap for the main file in the store. */
2605 store_type_t type; /**< What's stored in this store? */
2607 /** The size of the router log, in bytes. */
2608 size_t journal_len;
2609 /** The size of the router store, in bytes. */
2610 size_t store_len;
2611 /** Total bytes dropped since last rebuild: this is space currently
2612 * used in the cache and the journal that could be freed by a rebuild. */
2613 size_t bytes_dropped;
2614 } desc_store_t;
2616 /** Contents of a directory of onion routers. */
2617 typedef struct {
2618 /** Map from server identity digest to a member of routers. */
2619 struct digest_ri_map_t *identity_map;
2620 /** Map from server descriptor digest to a signed_descriptor_t from
2621 * routers or old_routers. */
2622 struct digest_sd_map_t *desc_digest_map;
2623 /** Map from extra-info digest to an extrainfo_t. Only exists for
2624 * routers in routers or old_routers. */
2625 struct digest_ei_map_t *extra_info_map;
2626 /** Map from extra-info digests to a signed_descriptor_t for a router
2627 * descriptor having that extra-info digest. Only exists for
2628 * routers in routers or old_routers. */
2629 struct digest_sd_map_t *desc_by_eid_map;
2630 /** List of routerinfo_t for all currently live routers we know. */
2631 smartlist_t *routers;
2632 /** List of signed_descriptor_t for older router descriptors we're
2633 * caching. */
2634 smartlist_t *old_routers;
2635 /** Store holding server descriptors. If present, any router whose
2636 * cache_info.saved_location == SAVED_IN_CACHE is stored in this file
2637 * starting at cache_info.saved_offset */
2638 desc_store_t desc_store;
2639 /** Store holding extra-info documents. */
2640 desc_store_t extrainfo_store;
2641 } routerlist_t;
2643 /** Information on router used when extending a circuit. We don't need a
2644 * full routerinfo_t to extend: we only need addr:port:keyid to build an OR
2645 * connection, and onion_key to create the onionskin. Note that for onehop
2646 * general-purpose tunnels, the onion_key is NULL. */
2647 typedef struct extend_info_t {
2648 char nickname[MAX_HEX_NICKNAME_LEN+1]; /**< This router's nickname for
2649 * display. */
2650 char identity_digest[DIGEST_LEN]; /**< Hash of this router's identity key. */
2651 uint16_t port; /**< OR port. */
2652 tor_addr_t addr; /**< IP address. */
2653 crypto_pk_t *onion_key; /**< Current onionskin key. */
2654 curve25519_public_key_t curve25519_onion_key;
2655 } extend_info_t;
2657 /** Certificate for v3 directory protocol: binds long-term authority identity
2658 * keys to medium-term authority signing keys. */
2659 typedef struct authority_cert_t {
2660 /** Information relating to caching this cert on disk and looking it up. */
2661 signed_descriptor_t cache_info;
2662 /** This authority's long-term authority identity key. */
2663 crypto_pk_t *identity_key;
2664 /** This authority's medium-term signing key. */
2665 crypto_pk_t *signing_key;
2666 /** The digest of <b>signing_key</b> */
2667 char signing_key_digest[DIGEST_LEN];
2668 /** The listed expiration time of this certificate. */
2669 time_t expires;
2670 /** This authority's IPv4 address, in host order. */
2671 uint32_t addr;
2672 /** This authority's directory port. */
2673 uint16_t dir_port;
2674 } authority_cert_t;
2676 /** Bitfield enum type listing types of information that directory authorities
2677 * can be authoritative about, and that directory caches may or may not cache.
2679 * Note that the granularity here is based on authority granularity and on
2680 * cache capabilities. Thus, one particular bit may correspond in practice to
2681 * a few types of directory info, so long as every authority that pronounces
2682 * officially about one of the types prounounces officially about all of them,
2683 * and so long as every cache that caches one of them caches all of them.
2685 typedef enum {
2686 NO_DIRINFO = 0,
2687 /** Serves/signs v3 directory information: votes, consensuses, certs */
2688 V3_DIRINFO = 1 << 2,
2689 /** Serves bridge descriptors. */
2690 BRIDGE_DIRINFO = 1 << 4,
2691 /** Serves extrainfo documents. */
2692 EXTRAINFO_DIRINFO=1 << 5,
2693 /** Serves microdescriptors. */
2694 MICRODESC_DIRINFO=1 << 6,
2695 } dirinfo_type_t;
2697 #define ALL_DIRINFO ((dirinfo_type_t)((1<<7)-1))
2699 #define CRYPT_PATH_MAGIC 0x70127012u
2701 struct fast_handshake_state_t;
2702 struct ntor_handshake_state_t;
2703 #define ONION_HANDSHAKE_TYPE_TAP 0x0000
2704 #define ONION_HANDSHAKE_TYPE_FAST 0x0001
2705 #define ONION_HANDSHAKE_TYPE_NTOR 0x0002
2706 #define MAX_ONION_HANDSHAKE_TYPE 0x0002
2707 typedef struct {
2708 uint16_t tag;
2709 union {
2710 struct fast_handshake_state_t *fast;
2711 crypto_dh_t *tap;
2712 struct ntor_handshake_state_t *ntor;
2713 } u;
2714 } onion_handshake_state_t;
2716 /** Holds accounting information for a single step in the layered encryption
2717 * performed by a circuit. Used only at the client edge of a circuit. */
2718 typedef struct crypt_path_t {
2719 uint32_t magic;
2721 /* crypto environments */
2722 /** Encryption key and counter for cells heading towards the OR at this
2723 * step. */
2724 crypto_cipher_t *f_crypto;
2725 /** Encryption key and counter for cells heading back from the OR at this
2726 * step. */
2727 crypto_cipher_t *b_crypto;
2729 /** Digest state for cells heading towards the OR at this step. */
2730 crypto_digest_t *f_digest; /* for integrity checking */
2731 /** Digest state for cells heading away from the OR at this step. */
2732 crypto_digest_t *b_digest;
2734 /** Current state of the handshake as performed with the OR at this
2735 * step. */
2736 onion_handshake_state_t handshake_state;
2737 /** Diffie-hellman handshake state for performing an introduction
2738 * operations */
2739 crypto_dh_t *rend_dh_handshake_state;
2741 /** Negotiated key material shared with the OR at this step. */
2742 char rend_circ_nonce[DIGEST_LEN];/* KH in tor-spec.txt */
2744 /** Information to extend to the OR at this step. */
2745 extend_info_t *extend_info;
2747 /** Is the circuit built to this step? Must be one of:
2748 * - CPATH_STATE_CLOSED (The circuit has not been extended to this step)
2749 * - CPATH_STATE_AWAITING_KEYS (We have sent an EXTEND/CREATE to this step
2750 * and not received an EXTENDED/CREATED)
2751 * - CPATH_STATE_OPEN (The circuit has been extended to this step) */
2752 uint8_t state;
2753 #define CPATH_STATE_CLOSED 0
2754 #define CPATH_STATE_AWAITING_KEYS 1
2755 #define CPATH_STATE_OPEN 2
2756 struct crypt_path_t *next; /**< Link to next crypt_path_t in the circuit.
2757 * (The list is circular, so the last node
2758 * links to the first.) */
2759 struct crypt_path_t *prev; /**< Link to previous crypt_path_t in the
2760 * circuit. */
2762 int package_window; /**< How many cells are we allowed to originate ending
2763 * at this step? */
2764 int deliver_window; /**< How many cells are we willing to deliver originating
2765 * at this step? */
2766 } crypt_path_t;
2768 /** A reference-counted pointer to a crypt_path_t, used only to share
2769 * the final rendezvous cpath to be used on a service-side rendezvous
2770 * circuit among multiple circuits built in parallel to the same
2771 * destination rendezvous point. */
2772 typedef struct {
2773 /** The reference count. */
2774 unsigned int refcount;
2775 /** The pointer. Set to NULL when the crypt_path_t is put into use
2776 * on an opened rendezvous circuit. */
2777 crypt_path_t *cpath;
2778 } crypt_path_reference_t;
2780 #define CPATH_KEY_MATERIAL_LEN (20*2+16*2)
2782 #define DH_KEY_LEN DH_BYTES
2784 /** Information used to build a circuit. */
2785 typedef struct {
2786 /** Intended length of the final circuit. */
2787 int desired_path_len;
2788 /** How to extend to the planned exit node. */
2789 extend_info_t *chosen_exit;
2790 /** Whether every node in the circ must have adequate uptime. */
2791 unsigned int need_uptime : 1;
2792 /** Whether every node in the circ must have adequate capacity. */
2793 unsigned int need_capacity : 1;
2794 /** Whether the last hop was picked with exiting in mind. */
2795 unsigned int is_internal : 1;
2796 /** Did we pick this as a one-hop tunnel (not safe for other streams)?
2797 * These are for encrypted dir conns that exit to this router, not
2798 * for arbitrary exits from the circuit. */
2799 unsigned int onehop_tunnel : 1;
2800 /** The crypt_path_t to append after rendezvous: used for rendezvous. */
2801 crypt_path_t *pending_final_cpath;
2802 /** A ref-counted reference to the crypt_path_t to append after
2803 * rendezvous; used on the service side. */
2804 crypt_path_reference_t *service_pending_final_cpath_ref;
2805 /** How many times has building a circuit for this task failed? */
2806 int failure_count;
2807 /** At what time should we give up on this task? */
2808 time_t expiry_time;
2809 } cpath_build_state_t;
2811 /** "magic" value for an origin_circuit_t */
2812 #define ORIGIN_CIRCUIT_MAGIC 0x35315243u
2813 /** "magic" value for an or_circuit_t */
2814 #define OR_CIRCUIT_MAGIC 0x98ABC04Fu
2815 /** "magic" value for a circuit that would have been freed by circuit_free,
2816 * but which we're keeping around until a cpuworker reply arrives. See
2817 * circuit_free() for more documentation. */
2818 #define DEAD_CIRCUIT_MAGIC 0xdeadc14c
2820 struct create_cell_t;
2822 /** Entry in the cell stats list of a circuit; used only if CELL_STATS
2823 * events are enabled. */
2824 typedef struct testing_cell_stats_entry_t {
2825 uint8_t command; /**< cell command number. */
2826 /** Waiting time in centiseconds if this event is for a removed cell,
2827 * or 0 if this event is for adding a cell to the queue. 22 bits can
2828 * store more than 11 hours, enough to assume that a circuit with this
2829 * delay would long have been closed. */
2830 unsigned int waiting_time:22;
2831 unsigned int removed:1; /**< 0 for added to, 1 for removed from queue. */
2832 unsigned int exitward:1; /**< 0 for app-ward, 1 for exit-ward. */
2833 } testing_cell_stats_entry_t;
2836 * A circuit is a path over the onion routing
2837 * network. Applications can connect to one end of the circuit, and can
2838 * create exit connections at the other end of the circuit. AP and exit
2839 * connections have only one circuit associated with them (and thus these
2840 * connection types are closed when the circuit is closed), whereas
2841 * OR connections multiplex many circuits at once, and stay standing even
2842 * when there are no circuits running over them.
2844 * A circuit_t structure can fill one of two roles. First, a or_circuit_t
2845 * links two connections together: either an edge connection and an OR
2846 * connection, or two OR connections. (When joined to an OR connection, a
2847 * circuit_t affects only cells sent to a particular circID on that
2848 * connection. When joined to an edge connection, a circuit_t affects all
2849 * data.)
2851 * Second, an origin_circuit_t holds the cipher keys and state for sending data
2852 * along a given circuit. At the OP, it has a sequence of ciphers, each
2853 * of which is shared with a single OR along the circuit. Separate
2854 * ciphers are used for data going "forward" (away from the OP) and
2855 * "backward" (towards the OP). At the OR, a circuit has only two stream
2856 * ciphers: one for data going forward, and one for data going backward.
2858 typedef struct circuit_t {
2859 uint32_t magic; /**< For memory and type debugging: must equal
2860 * ORIGIN_CIRCUIT_MAGIC or OR_CIRCUIT_MAGIC. */
2862 /** The channel that is next in this circuit. */
2863 channel_t *n_chan;
2866 * The circuit_id used in the next (forward) hop of this circuit;
2867 * this is unique to n_chan, but this ordered pair is globally
2868 * unique:
2870 * (n_chan->global_identifier, n_circ_id)
2872 circid_t n_circ_id;
2875 * Circuit mux associated with n_chan to which this circuit is attached;
2876 * NULL if we have no n_chan.
2878 circuitmux_t *n_mux;
2880 /** Queue of cells waiting to be transmitted on n_chan */
2881 cell_queue_t n_chan_cells;
2884 * The hop to which we want to extend this circuit. Should be NULL if
2885 * the circuit has attached to a channel.
2887 extend_info_t *n_hop;
2889 /** True iff we are waiting for n_chan_cells to become less full before
2890 * allowing p_streams to add any more cells. (Origin circuit only.) */
2891 unsigned int streams_blocked_on_n_chan : 1;
2892 /** True iff we are waiting for p_chan_cells to become less full before
2893 * allowing n_streams to add any more cells. (OR circuit only.) */
2894 unsigned int streams_blocked_on_p_chan : 1;
2896 /** True iff we have queued a delete backwards on this circuit, but not put
2897 * it on the output buffer. */
2898 unsigned int p_delete_pending : 1;
2899 /** True iff we have queued a delete forwards on this circuit, but not put
2900 * it on the output buffer. */
2901 unsigned int n_delete_pending : 1;
2903 /** True iff this circuit has received a DESTROY cell in either direction */
2904 unsigned int received_destroy : 1;
2906 uint8_t state; /**< Current status of this circuit. */
2907 uint8_t purpose; /**< Why are we creating this circuit? */
2909 /** How many relay data cells can we package (read from edge streams)
2910 * on this circuit before we receive a circuit-level sendme cell asking
2911 * for more? */
2912 int package_window;
2913 /** How many relay data cells will we deliver (write to edge streams)
2914 * on this circuit? When deliver_window gets low, we send some
2915 * circuit-level sendme cells to indicate that we're willing to accept
2916 * more. */
2917 int deliver_window;
2919 /** Temporary field used during circuits_handle_oom. */
2920 uint32_t age_tmp;
2922 /** For storage while n_chan is pending (state CIRCUIT_STATE_CHAN_WAIT). */
2923 struct create_cell_t *n_chan_create_cell;
2925 /** When did circuit construction actually begin (ie send the
2926 * CREATE cell or begin cannibalization).
2928 * Note: This timer will get reset if we decide to cannibalize
2929 * a circuit. It may also get reset during certain phases of hidden
2930 * service circuit use.
2932 * We keep this timestamp with a higher resolution than most so that the
2933 * circuit-build-time tracking code can get millisecond resolution.
2935 struct timeval timestamp_began;
2937 /** This timestamp marks when the init_circuit_base constructor ran. */
2938 struct timeval timestamp_created;
2940 /** When the circuit was first used, or 0 if the circuit is clean.
2942 * XXXX Note that some code will artifically adjust this value backward
2943 * in time in order to indicate that a circuit shouldn't be used for new
2944 * streams, but that it can stay alive as long as it has streams on it.
2945 * That's a kludge we should fix.
2947 * XXX The CBT code uses this field to record when HS-related
2948 * circuits entered certain states. This usage probably won't
2949 * interfere with this field's primary purpose, but we should
2950 * document it more thoroughly to make sure of that.
2952 * XXX The SocksPort option KeepaliveIsolateSOCKSAuth will artificially
2953 * adjust this value forward each time a suitable stream is attached to an
2954 * already constructed circuit, potentially keeping the circuit alive
2955 * indefinitely.
2957 time_t timestamp_dirty;
2959 uint16_t marked_for_close; /**< Should we close this circuit at the end of
2960 * the main loop? (If true, holds the line number
2961 * where this circuit was marked.) */
2962 const char *marked_for_close_file; /**< For debugging: in which file was this
2963 * circuit marked for close? */
2964 /** For what reason (See END_CIRC_REASON...) is this circuit being closed?
2965 * This field is set in circuit_mark_for_close and used later in
2966 * circuit_about_to_free. */
2967 uint16_t marked_for_close_reason;
2968 /** As marked_for_close_reason, but reflects the underlying reason for
2969 * closing this circuit.
2971 uint16_t marked_for_close_orig_reason;
2973 /** Unique ID for measuring tunneled network status requests. */
2974 uint64_t dirreq_id;
2976 /** Index in smartlist of all circuits (global_circuitlist). */
2977 int global_circuitlist_idx;
2979 /** Next circuit in the doubly-linked ring of circuits waiting to add
2980 * cells to n_conn. NULL if we have no cells pending, or if we're not
2981 * linked to an OR connection. */
2982 struct circuit_t *next_active_on_n_chan;
2983 /** Previous circuit in the doubly-linked ring of circuits waiting to add
2984 * cells to n_conn. NULL if we have no cells pending, or if we're not
2985 * linked to an OR connection. */
2986 struct circuit_t *prev_active_on_n_chan;
2988 /** Various statistics about cells being added to or removed from this
2989 * circuit's queues; used only if CELL_STATS events are enabled and
2990 * cleared after being sent to control port. */
2991 smartlist_t *testing_cell_stats;
2992 } circuit_t;
2994 /** Largest number of relay_early cells that we can send on a given
2995 * circuit. */
2996 #define MAX_RELAY_EARLY_CELLS_PER_CIRCUIT 8
2999 * Describes the circuit building process in simplified terms based
3000 * on the path bias accounting state for a circuit.
3002 * NOTE: These state values are enumerated in the order for which we
3003 * expect circuits to transition through them. If you add states,
3004 * you need to preserve this overall ordering. The various pathbias
3005 * state transition and accounting functions (pathbias_mark_* and
3006 * pathbias_count_*) contain ordinal comparisons to enforce proper
3007 * state transitions for corrections.
3009 * This state machine and the associated logic was created to prevent
3010 * miscounting due to unknown cases of circuit reuse. See also tickets
3011 * #6475 and #7802.
3013 typedef enum {
3014 /** This circuit is "new". It has not yet completed a first hop
3015 * or been counted by the path bias code. */
3016 PATH_STATE_NEW_CIRC = 0,
3017 /** This circuit has completed one/two hops, and has been counted by
3018 * the path bias logic. */
3019 PATH_STATE_BUILD_ATTEMPTED = 1,
3020 /** This circuit has been completely built */
3021 PATH_STATE_BUILD_SUCCEEDED = 2,
3022 /** Did we try to attach any SOCKS streams or hidserv introductions to
3023 * this circuit?
3025 * Note: If we ever implement end-to-end stream timing through test
3026 * stream probes (#5707), we must *not* set this for those probes
3027 * (or any other automatic streams) because the adversary could
3028 * just tag at a later point.
3030 PATH_STATE_USE_ATTEMPTED = 3,
3031 /** Did any SOCKS streams or hidserv introductions actually succeed on
3032 * this circuit?
3034 * If any streams detatch/fail from this circuit, the code transitions
3035 * the circuit back to PATH_STATE_USE_ATTEMPTED to ensure we probe. See
3036 * pathbias_mark_use_rollback() for that.
3038 PATH_STATE_USE_SUCCEEDED = 4,
3041 * This is a special state to indicate that we got a corrupted
3042 * relay cell on a circuit and we don't intend to probe it.
3044 PATH_STATE_USE_FAILED = 5,
3047 * This is a special state to indicate that we already counted
3048 * the circuit. Used to guard against potential state machine
3049 * violations.
3051 PATH_STATE_ALREADY_COUNTED = 6,
3052 } path_state_t;
3053 #define path_state_bitfield_t ENUM_BF(path_state_t)
3055 /** An origin_circuit_t holds data necessary to build and use a circuit.
3057 typedef struct origin_circuit_t {
3058 circuit_t base_;
3060 /** Linked list of AP streams (or EXIT streams if hidden service)
3061 * associated with this circuit. */
3062 edge_connection_t *p_streams;
3064 /** Bytes read from any attached stream since last call to
3065 * control_event_circ_bandwidth_used(). Only used if we're configured
3066 * to emit CIRC_BW events. */
3067 uint32_t n_read_circ_bw;
3069 /** Bytes written to any attached stream since last call to
3070 * control_event_circ_bandwidth_used(). Only used if we're configured
3071 * to emit CIRC_BW events. */
3072 uint32_t n_written_circ_bw;
3074 /** Build state for this circuit. It includes the intended path
3075 * length, the chosen exit router, rendezvous information, etc.
3077 cpath_build_state_t *build_state;
3078 /** The doubly-linked list of crypt_path_t entries, one per hop,
3079 * for this circuit. This includes ciphers for each hop,
3080 * integrity-checking digests for each hop, and package/delivery
3081 * windows for each hop.
3083 crypt_path_t *cpath;
3085 /** Holds all rendezvous data on either client or service side. */
3086 rend_data_t *rend_data;
3088 /** How many more relay_early cells can we send on this circuit, according
3089 * to the specification? */
3090 unsigned int remaining_relay_early_cells : 4;
3092 /** Set if this circuit is insanely old and we already informed the user */
3093 unsigned int is_ancient : 1;
3095 /** Set if this circuit has already been opened. Used to detect
3096 * cannibalized circuits. */
3097 unsigned int has_opened : 1;
3100 * Path bias state machine. Used to ensure integrity of our
3101 * circuit building and usage accounting. See path_state_t
3102 * for more details.
3104 path_state_bitfield_t path_state : 3;
3106 /* If this flag is set, we should not consider attaching any more
3107 * connections to this circuit. */
3108 unsigned int unusable_for_new_conns : 1;
3111 * Tristate variable to guard against pathbias miscounting
3112 * due to circuit purpose transitions changing the decision
3113 * of pathbias_should_count(). This variable is informational
3114 * only. The current results of pathbias_should_count() are
3115 * the official decision for pathbias accounting.
3117 uint8_t pathbias_shouldcount;
3118 #define PATHBIAS_SHOULDCOUNT_UNDECIDED 0
3119 #define PATHBIAS_SHOULDCOUNT_IGNORED 1
3120 #define PATHBIAS_SHOULDCOUNT_COUNTED 2
3122 /** For path probing. Store the temporary probe stream ID
3123 * for response comparison */
3124 streamid_t pathbias_probe_id;
3126 /** For path probing. Store the temporary probe address nonce
3127 * (in host byte order) for response comparison. */
3128 uint32_t pathbias_probe_nonce;
3130 /** Set iff this is a hidden-service circuit which has timed out
3131 * according to our current circuit-build timeout, but which has
3132 * been kept around because it might still succeed in connecting to
3133 * its destination, and which is not a fully-connected rendezvous
3134 * circuit.
3136 * (We clear this flag for client-side rendezvous circuits when they
3137 * are 'joined' to the other side's rendezvous circuit, so that
3138 * connection_ap_handshake_attach_circuit can put client streams on
3139 * the circuit. We also clear this flag for service-side rendezvous
3140 * circuits when they are 'joined' to a client's rend circ, but only
3141 * for symmetry with the client case. Client-side introduction
3142 * circuits are closed when we get a joined rend circ, and
3143 * service-side introduction circuits never have this flag set.) */
3144 unsigned int hs_circ_has_timed_out : 1;
3146 /** Set iff this circuit has been given a relaxed timeout because
3147 * no circuits have opened. Used to prevent spamming logs. */
3148 unsigned int relaxed_timeout : 1;
3150 /** Set iff this is a service-side rendezvous circuit for which a
3151 * new connection attempt has been launched. We consider launching
3152 * a new service-side rend circ to a client when the previous one
3153 * fails; now that we don't necessarily close a service-side rend
3154 * circ when we launch a new one to the same client, this flag keeps
3155 * us from launching two retries for the same failed rend circ. */
3156 unsigned int hs_service_side_rend_circ_has_been_relaunched : 1;
3158 /** What commands were sent over this circuit that decremented the
3159 * RELAY_EARLY counter? This is for debugging task 878. */
3160 uint8_t relay_early_commands[MAX_RELAY_EARLY_CELLS_PER_CIRCUIT];
3162 /** How many RELAY_EARLY cells have been sent over this circuit? This is
3163 * for debugging task 878, too. */
3164 int relay_early_cells_sent;
3166 /** The next stream_id that will be tried when we're attempting to
3167 * construct a new AP stream originating at this circuit. */
3168 streamid_t next_stream_id;
3170 /* The intro key replaces the hidden service's public key if purpose is
3171 * S_ESTABLISH_INTRO or S_INTRO, provided that no unversioned rendezvous
3172 * descriptor is used. */
3173 crypto_pk_t *intro_key;
3175 /** Quasi-global identifier for this circuit; used for control.c */
3176 /* XXXX NM This can get re-used after 2**32 circuits. */
3177 uint32_t global_identifier;
3179 /** True if we have associated one stream to this circuit, thereby setting
3180 * the isolation paramaters for this circuit. Note that this doesn't
3181 * necessarily mean that we've <em>attached</em> any streams to the circuit:
3182 * we may only have marked up this circuit during the launch process.
3184 unsigned int isolation_values_set : 1;
3185 /** True iff any stream has <em>ever</em> been attached to this circuit.
3187 * In a better world we could use timestamp_dirty for this, but
3188 * timestamp_dirty is far too overloaded at the moment.
3190 unsigned int isolation_any_streams_attached : 1;
3192 /** A bitfield of ISO_* flags for every isolation field such that this
3193 * circuit has had streams with more than one value for that field
3194 * attached to it. */
3195 uint8_t isolation_flags_mixed;
3197 /** @name Isolation parameters
3199 * If any streams have been associated with this circ (isolation_values_set
3200 * == 1), and all streams associated with the circuit have had the same
3201 * value for some field ((isolation_flags_mixed & ISO_FOO) == 0), then these
3202 * elements hold the value for that field.
3204 * Note again that "associated" is not the same as "attached": we
3205 * preliminarily associate streams with a circuit while the circuit is being
3206 * launched, so that we can tell whether we need to launch more circuits.
3208 * @{
3210 uint8_t client_proto_type;
3211 uint8_t client_proto_socksver;
3212 uint16_t dest_port;
3213 tor_addr_t client_addr;
3214 char *dest_address;
3215 int session_group;
3216 unsigned nym_epoch;
3217 size_t socks_username_len;
3218 uint8_t socks_password_len;
3219 /* Note that the next two values are NOT NUL-terminated; see
3220 socks_username_len and socks_password_len for their lengths. */
3221 char *socks_username;
3222 char *socks_password;
3223 /** Global identifier for the first stream attached here; used by
3224 * ISO_STREAM. */
3225 uint64_t associated_isolated_stream_global_id;
3226 /**@}*/
3227 /** A list of addr_policy_t for this circuit in particular. Used by
3228 * adjust_exit_policy_from_exitpolicy_failure.
3230 smartlist_t *prepend_policy;
3231 } origin_circuit_t;
3233 struct onion_queue_t;
3235 /** An or_circuit_t holds information needed to implement a circuit at an
3236 * OR. */
3237 typedef struct or_circuit_t {
3238 circuit_t base_;
3240 /** Next circuit in the doubly-linked ring of circuits waiting to add
3241 * cells to p_chan. NULL if we have no cells pending, or if we're not
3242 * linked to an OR connection. */
3243 struct circuit_t *next_active_on_p_chan;
3244 /** Previous circuit in the doubly-linked ring of circuits waiting to add
3245 * cells to p_chan. NULL if we have no cells pending, or if we're not
3246 * linked to an OR connection. */
3247 struct circuit_t *prev_active_on_p_chan;
3248 /** Pointer to an entry on the onion queue, if this circuit is waiting for a
3249 * chance to give an onionskin to a cpuworker. Used only in onion.c */
3250 struct onion_queue_t *onionqueue_entry;
3251 /** Pointer to a workqueue entry, if this circuit has given an onionskin to
3252 * a cpuworker and is waiting for a response. Used to decide whether it is
3253 * safe to free a circuit or if it is still in use by a cpuworker. */
3254 struct workqueue_entry_s *workqueue_entry;
3256 /** The circuit_id used in the previous (backward) hop of this circuit. */
3257 circid_t p_circ_id;
3258 /** Queue of cells waiting to be transmitted on p_conn. */
3259 cell_queue_t p_chan_cells;
3260 /** The channel that is previous in this circuit. */
3261 channel_t *p_chan;
3263 * Circuit mux associated with p_chan to which this circuit is attached;
3264 * NULL if we have no p_chan.
3266 circuitmux_t *p_mux;
3267 /** Linked list of Exit streams associated with this circuit. */
3268 edge_connection_t *n_streams;
3269 /** Linked list of Exit streams associated with this circuit that are
3270 * still being resolved. */
3271 edge_connection_t *resolving_streams;
3272 /** The cipher used by intermediate hops for cells heading toward the
3273 * OP. */
3274 crypto_cipher_t *p_crypto;
3275 /** The cipher used by intermediate hops for cells heading away from
3276 * the OP. */
3277 crypto_cipher_t *n_crypto;
3279 /** The integrity-checking digest used by intermediate hops, for
3280 * cells packaged here and heading towards the OP.
3282 crypto_digest_t *p_digest;
3283 /** The integrity-checking digest used by intermediate hops, for
3284 * cells packaged at the OP and arriving here.
3286 crypto_digest_t *n_digest;
3288 /** Points to spliced circuit if purpose is REND_ESTABLISHED, and circuit
3289 * is not marked for close. */
3290 struct or_circuit_t *rend_splice;
3292 struct or_circuit_rendinfo_s *rendinfo;
3294 /** Stores KH for the handshake. */
3295 char rend_circ_nonce[DIGEST_LEN];/* KH in tor-spec.txt */
3297 /** How many more relay_early cells can we send on this circuit, according
3298 * to the specification? */
3299 unsigned int remaining_relay_early_cells : 4;
3301 /* We have already received an INTRODUCE1 cell on this circuit. */
3302 unsigned int already_received_introduce1 : 1;
3304 /** True iff this circuit was made with a CREATE_FAST cell. */
3305 unsigned int is_first_hop : 1;
3307 /** If set, this circuit carries HS traffic. Consider it in any HS
3308 * statistics. */
3309 unsigned int circuit_carries_hs_traffic_stats : 1;
3311 /** Number of cells that were removed from circuit queue; reset every
3312 * time when writing buffer stats to disk. */
3313 uint32_t processed_cells;
3315 /** Total time in milliseconds that cells spent in both app-ward and
3316 * exit-ward queues of this circuit; reset every time when writing
3317 * buffer stats to disk. */
3318 uint64_t total_cell_waiting_time;
3320 /** Maximum cell queue size for a middle relay; this is stored per circuit
3321 * so append_cell_to_circuit_queue() can adjust it if it changes. If set
3322 * to zero, it is initialized to the default value.
3324 uint32_t max_middle_cells;
3325 } or_circuit_t;
3327 typedef struct or_circuit_rendinfo_s {
3329 #if REND_COOKIE_LEN != DIGEST_LEN
3330 #error "The REND_TOKEN_LEN macro assumes REND_COOKIE_LEN == DIGEST_LEN"
3331 #endif
3332 #define REND_TOKEN_LEN DIGEST_LEN
3334 /** A hash of location-hidden service's PK if purpose is INTRO_POINT, or a
3335 * rendezvous cookie if purpose is REND_POINT_WAITING. Filled with zeroes
3336 * otherwise.
3338 char rend_token[REND_TOKEN_LEN];
3340 /** True if this is a rendezvous point circuit; false if this is an
3341 * introduction point. */
3342 unsigned is_rend_circ;
3344 } or_circuit_rendinfo_t;
3346 /** Convert a circuit subtype to a circuit_t. */
3347 #define TO_CIRCUIT(x) (&((x)->base_))
3349 /** Convert a circuit_t* to a pointer to the enclosing or_circuit_t. Assert
3350 * if the cast is impossible. */
3351 static or_circuit_t *TO_OR_CIRCUIT(circuit_t *);
3352 static const or_circuit_t *CONST_TO_OR_CIRCUIT(const circuit_t *);
3353 /** Convert a circuit_t* to a pointer to the enclosing origin_circuit_t.
3354 * Assert if the cast is impossible. */
3355 static origin_circuit_t *TO_ORIGIN_CIRCUIT(circuit_t *);
3356 static const origin_circuit_t *CONST_TO_ORIGIN_CIRCUIT(const circuit_t *);
3358 /** Return 1 iff <b>node</b> has Exit flag and no BadExit flag.
3359 * Otherwise, return 0.
3361 static inline int node_is_good_exit(const node_t *node)
3363 return node->is_exit && ! node->is_bad_exit;
3366 static inline or_circuit_t *TO_OR_CIRCUIT(circuit_t *x)
3368 tor_assert(x->magic == OR_CIRCUIT_MAGIC);
3369 return DOWNCAST(or_circuit_t, x);
3371 static inline const or_circuit_t *CONST_TO_OR_CIRCUIT(const circuit_t *x)
3373 tor_assert(x->magic == OR_CIRCUIT_MAGIC);
3374 return DOWNCAST(or_circuit_t, x);
3376 static inline origin_circuit_t *TO_ORIGIN_CIRCUIT(circuit_t *x)
3378 tor_assert(x->magic == ORIGIN_CIRCUIT_MAGIC);
3379 return DOWNCAST(origin_circuit_t, x);
3381 static inline const origin_circuit_t *CONST_TO_ORIGIN_CIRCUIT(
3382 const circuit_t *x)
3384 tor_assert(x->magic == ORIGIN_CIRCUIT_MAGIC);
3385 return DOWNCAST(origin_circuit_t, x);
3388 /** Bitfield type: things that we're willing to use invalid routers for. */
3389 typedef enum invalid_router_usage_t {
3390 ALLOW_INVALID_ENTRY =1,
3391 ALLOW_INVALID_EXIT =2,
3392 ALLOW_INVALID_MIDDLE =4,
3393 ALLOW_INVALID_RENDEZVOUS =8,
3394 ALLOW_INVALID_INTRODUCTION=16,
3395 } invalid_router_usage_t;
3397 /* limits for TCP send and recv buffer size used for constrained sockets */
3398 #define MIN_CONSTRAINED_TCP_BUFFER 2048
3399 #define MAX_CONSTRAINED_TCP_BUFFER 262144 /* 256k */
3401 /** @name Isolation flags
3403 Ways to isolate client streams
3407 /** Isolate based on destination port */
3408 #define ISO_DESTPORT (1u<<0)
3409 /** Isolate based on destination address */
3410 #define ISO_DESTADDR (1u<<1)
3411 /** Isolate based on SOCKS authentication */
3412 #define ISO_SOCKSAUTH (1u<<2)
3413 /** Isolate based on client protocol choice */
3414 #define ISO_CLIENTPROTO (1u<<3)
3415 /** Isolate based on client address */
3416 #define ISO_CLIENTADDR (1u<<4)
3417 /** Isolate based on session group (always on). */
3418 #define ISO_SESSIONGRP (1u<<5)
3419 /** Isolate based on newnym epoch (always on). */
3420 #define ISO_NYM_EPOCH (1u<<6)
3421 /** Isolate all streams (Internal only). */
3422 #define ISO_STREAM (1u<<7)
3423 /**@}*/
3425 /** Default isolation level for ports. */
3426 #define ISO_DEFAULT (ISO_CLIENTADDR|ISO_SOCKSAUTH|ISO_SESSIONGRP|ISO_NYM_EPOCH)
3428 /** Indicates that we haven't yet set a session group on a port_cfg_t. */
3429 #define SESSION_GROUP_UNSET -1
3430 /** Session group reserved for directory connections */
3431 #define SESSION_GROUP_DIRCONN -2
3432 /** Session group reserved for resolve requests launched by a controller */
3433 #define SESSION_GROUP_CONTROL_RESOLVE -3
3434 /** First automatically allocated session group number */
3435 #define SESSION_GROUP_FIRST_AUTO -4
3437 /** Configuration for a single port that we're listening on. */
3438 typedef struct port_cfg_t {
3439 tor_addr_t addr; /**< The actual IP to listen on, if !is_unix_addr. */
3440 int port; /**< The configured port, or CFG_AUTO_PORT to tell Tor to pick its
3441 * own port. */
3442 uint8_t type; /**< One of CONN_TYPE_*_LISTENER */
3443 unsigned is_unix_addr : 1; /**< True iff this is an AF_UNIX address. */
3445 unsigned is_group_writable : 1;
3446 unsigned is_world_writable : 1;
3447 unsigned relax_dirmode_check : 1;
3449 entry_port_cfg_t entry_cfg;
3451 server_port_cfg_t server_cfg;
3453 /* Unix sockets only: */
3454 /** Path for an AF_UNIX address */
3455 char unix_addr[FLEXIBLE_ARRAY_MEMBER];
3456 } port_cfg_t;
3458 /** Ordinary configuration line. */
3459 #define CONFIG_LINE_NORMAL 0
3460 /** Appends to previous configuration for the same option, even if we
3461 * would ordinary replace it. */
3462 #define CONFIG_LINE_APPEND 1
3463 /* Removes all previous configuration for an option. */
3464 #define CONFIG_LINE_CLEAR 2
3466 /** A linked list of lines in a config file. */
3467 typedef struct config_line_t {
3468 char *key;
3469 char *value;
3470 struct config_line_t *next;
3471 /** What special treatment (if any) does this line require? */
3472 unsigned int command:2;
3473 /** If true, subsequent assignments to this linelist should replace
3474 * it, not extend it. Set only on the first item in a linelist in an
3475 * or_options_t. */
3476 unsigned int fragile:1;
3477 } config_line_t;
3479 typedef struct routerset_t routerset_t;
3481 /** A magic value for the (Socks|OR|...)Port options below, telling Tor
3482 * to pick its own port. */
3483 #define CFG_AUTO_PORT 0xc4005e
3485 /** Configuration options for a Tor process. */
3486 typedef struct {
3487 uint32_t magic_;
3489 /** What should the tor process actually do? */
3490 enum {
3491 CMD_RUN_TOR=0, CMD_LIST_FINGERPRINT, CMD_HASH_PASSWORD,
3492 CMD_VERIFY_CONFIG, CMD_RUN_UNITTESTS, CMD_DUMP_CONFIG,
3493 CMD_KEYGEN
3494 } command;
3495 char *command_arg; /**< Argument for command-line option. */
3497 config_line_t *Logs; /**< New-style list of configuration lines
3498 * for logs */
3499 int LogTimeGranularity; /**< Log resolution in milliseconds. */
3501 int LogMessageDomains; /**< Boolean: Should we log the domain(s) in which
3502 * each log message occurs? */
3503 int TruncateLogFile; /**< Boolean: Should we truncate the log file
3504 before we start writing? */
3505 char *SyslogIdentityTag; /**< Identity tag to add for syslog logging. */
3507 char *DebugLogFile; /**< Where to send verbose log messages. */
3508 char *DataDirectory; /**< OR only: where to store long-term data. */
3509 int DataDirectoryGroupReadable; /**< Boolean: Is the DataDirectory g+r? */
3510 char *Nickname; /**< OR only: nickname of this onion router. */
3511 char *Address; /**< OR only: configured address for this onion router. */
3512 char *PidFile; /**< Where to store PID of Tor process. */
3514 routerset_t *ExitNodes; /**< Structure containing nicknames, digests,
3515 * country codes and IP address patterns of ORs to
3516 * consider as exits. */
3517 routerset_t *EntryNodes;/**< Structure containing nicknames, digests,
3518 * country codes and IP address patterns of ORs to
3519 * consider as entry points. */
3520 int StrictNodes; /**< Boolean: When none of our EntryNodes or ExitNodes
3521 * are up, or we need to access a node in ExcludeNodes,
3522 * do we just fail instead? */
3523 routerset_t *ExcludeNodes;/**< Structure containing nicknames, digests,
3524 * country codes and IP address patterns of ORs
3525 * not to use in circuits. But see StrictNodes
3526 * above. */
3527 routerset_t *ExcludeExitNodes;/**< Structure containing nicknames, digests,
3528 * country codes and IP address patterns of
3529 * ORs not to consider as exits. */
3531 /** Union of ExcludeNodes and ExcludeExitNodes */
3532 routerset_t *ExcludeExitNodesUnion_;
3534 int DisableAllSwap; /**< Boolean: Attempt to call mlockall() on our
3535 * process for all current and future memory. */
3537 /** List of "entry", "middle", "exit", "introduction", "rendezvous". */
3538 smartlist_t *AllowInvalidNodes;
3539 /** Bitmask; derived from AllowInvalidNodes. */
3540 invalid_router_usage_t AllowInvalid_;
3541 config_line_t *ExitPolicy; /**< Lists of exit policy components. */
3542 int ExitPolicyRejectPrivate; /**< Should we not exit to reserved private
3543 * addresses, and our own published addresses?
3545 int ExitPolicyRejectLocalInterfaces; /**< Should we not exit to local
3546 * interface addresses?
3547 * Includes OutboundBindAddresses and
3548 * configured ports. */
3549 config_line_t *SocksPolicy; /**< Lists of socks policy components */
3550 config_line_t *DirPolicy; /**< Lists of dir policy components */
3551 /** Addresses to bind for listening for SOCKS connections. */
3552 config_line_t *SocksListenAddress;
3553 /** Addresses to bind for listening for transparent pf/netfilter
3554 * connections. */
3555 config_line_t *TransListenAddress;
3556 /** Addresses to bind for listening for transparent natd connections */
3557 config_line_t *NATDListenAddress;
3558 /** Addresses to bind for listening for SOCKS connections. */
3559 config_line_t *DNSListenAddress;
3560 /** Addresses to bind for listening for OR connections. */
3561 config_line_t *ORListenAddress;
3562 /** Addresses to bind for listening for directory connections. */
3563 config_line_t *DirListenAddress;
3564 /** Addresses to bind for listening for control connections. */
3565 config_line_t *ControlListenAddress;
3566 /** Local address to bind outbound sockets */
3567 config_line_t *OutboundBindAddress;
3568 /** IPv4 address derived from OutboundBindAddress. */
3569 tor_addr_t OutboundBindAddressIPv4_;
3570 /** IPv6 address derived from OutboundBindAddress. */
3571 tor_addr_t OutboundBindAddressIPv6_;
3572 /** Directory server only: which versions of
3573 * Tor should we tell users to run? */
3574 config_line_t *RecommendedVersions;
3575 config_line_t *RecommendedClientVersions;
3576 config_line_t *RecommendedServerVersions;
3577 config_line_t *RecommendedPackages;
3578 /** Whether dirservers allow router descriptors with private IPs. */
3579 int DirAllowPrivateAddresses;
3580 /** Whether routers accept EXTEND cells to routers with private IPs. */
3581 int ExtendAllowPrivateAddresses;
3582 char *User; /**< Name of user to run Tor as. */
3583 char *Group; /**< Name of group to run Tor as. */
3584 config_line_t *ORPort_lines; /**< Ports to listen on for OR connections. */
3585 /** Ports to listen on for extended OR connections. */
3586 config_line_t *ExtORPort_lines;
3587 /** Ports to listen on for SOCKS connections. */
3588 config_line_t *SocksPort_lines;
3589 /** Ports to listen on for transparent pf/netfilter connections. */
3590 config_line_t *TransPort_lines;
3591 const char *TransProxyType; /**< What kind of transparent proxy
3592 * implementation are we using? */
3593 /** Parsed value of TransProxyType. */
3594 enum {
3595 TPT_DEFAULT,
3596 TPT_PF_DIVERT,
3597 TPT_IPFW,
3598 TPT_TPROXY,
3599 } TransProxyType_parsed;
3600 config_line_t *NATDPort_lines; /**< Ports to listen on for transparent natd
3601 * connections. */
3602 config_line_t *ControlPort_lines; /**< Ports to listen on for control
3603 * connections. */
3604 config_line_t *ControlSocket; /**< List of Unix Domain Sockets to listen on
3605 * for control connections. */
3607 int ControlSocketsGroupWritable; /**< Boolean: Are control sockets g+rw? */
3608 int SocksSocketsGroupWritable; /**< Boolean: Are SOCKS sockets g+rw? */
3609 /** Ports to listen on for directory connections. */
3610 config_line_t *DirPort_lines;
3611 config_line_t *DNSPort_lines; /**< Ports to listen on for DNS requests. */
3613 /* MaxMemInQueues value as input by the user. We clean this up to be
3614 * MaxMemInQueues. */
3615 uint64_t MaxMemInQueues_raw;
3616 uint64_t MaxMemInQueues;/**< If we have more memory than this allocated
3617 * for queues and buffers, run the OOM handler */
3618 /** Above this value, consider ourselves low on RAM. */
3619 uint64_t MaxMemInQueues_low_threshold;
3621 /** @name port booleans
3623 * Derived booleans: For server ports and ControlPort, true iff there is a
3624 * non-listener port on an AF_INET or AF_INET6 address of the given type
3625 * configured in one of the _lines options above.
3626 * For client ports, also true if there is a unix socket configured.
3627 * If you are checking for client ports, you may want to use:
3628 * SocksPort_set || TransPort_set || NATDPort_set || DNSPort_set
3629 * rather than SocksPort_set.
3631 * @{
3633 unsigned int ORPort_set : 1;
3634 unsigned int SocksPort_set : 1;
3635 unsigned int TransPort_set : 1;
3636 unsigned int NATDPort_set : 1;
3637 unsigned int ControlPort_set : 1;
3638 unsigned int DirPort_set : 1;
3639 unsigned int DNSPort_set : 1;
3640 unsigned int ExtORPort_set : 1;
3641 /**@}*/
3643 int AssumeReachable; /**< Whether to publish our descriptor regardless. */
3644 int AuthoritativeDir; /**< Boolean: is this an authoritative directory? */
3645 int V3AuthoritativeDir; /**< Boolean: is this an authoritative directory
3646 * for version 3 directories? */
3647 int VersioningAuthoritativeDir; /**< Boolean: is this an authoritative
3648 * directory that's willing to recommend
3649 * versions? */
3650 int BridgeAuthoritativeDir; /**< Boolean: is this an authoritative directory
3651 * that aggregates bridge descriptors? */
3653 /** If set on a bridge authority, it will answer requests on its dirport
3654 * for bridge statuses -- but only if the requests use this password. */
3655 char *BridgePassword;
3656 /** If BridgePassword is set, this is a SHA256 digest of the basic http
3657 * authenticator for it. Used so we can do a time-independent comparison. */
3658 char *BridgePassword_AuthDigest_;
3660 int UseBridges; /**< Boolean: should we start all circuits with a bridge? */
3661 config_line_t *Bridges; /**< List of bootstrap bridge addresses. */
3663 config_line_t *ClientTransportPlugin; /**< List of client
3664 transport plugins. */
3666 config_line_t *ServerTransportPlugin; /**< List of client
3667 transport plugins. */
3669 /** List of TCP/IP addresses that transports should listen at. */
3670 config_line_t *ServerTransportListenAddr;
3672 /** List of options that must be passed to pluggable transports. */
3673 config_line_t *ServerTransportOptions;
3675 int BridgeRelay; /**< Boolean: are we acting as a bridge relay? We make
3676 * this explicit so we can change how we behave in the
3677 * future. */
3679 /** Boolean: if we know the bridge's digest, should we get new
3680 * descriptors from the bridge authorities or from the bridge itself? */
3681 int UpdateBridgesFromAuthority;
3683 int AvoidDiskWrites; /**< Boolean: should we never cache things to disk?
3684 * Not used yet. */
3685 int ClientOnly; /**< Boolean: should we never evolve into a server role? */
3686 /** To what authority types do we publish our descriptor? Choices are
3687 * "v1", "v2", "v3", "bridge", or "". */
3688 smartlist_t *PublishServerDescriptor;
3689 /** A bitfield of authority types, derived from PublishServerDescriptor. */
3690 dirinfo_type_t PublishServerDescriptor_;
3691 /** Boolean: do we publish hidden service descriptors to the HS auths? */
3692 int PublishHidServDescriptors;
3693 int FetchServerDescriptors; /**< Do we fetch server descriptors as normal? */
3694 int FetchHidServDescriptors; /**< and hidden service descriptors? */
3696 int MinUptimeHidServDirectoryV2; /**< As directory authority, accept hidden
3697 * service directories after what time? */
3699 int FetchUselessDescriptors; /**< Do we fetch non-running descriptors too? */
3700 int AllDirActionsPrivate; /**< Should every directory action be sent
3701 * through a Tor circuit? */
3703 /** Run in 'tor2web mode'? (I.e. only make client connections to hidden
3704 * services, and use a single hop for all hidden-service-related
3705 * circuits.) */
3706 int Tor2webMode;
3708 /** A routerset that should be used when picking RPs for HS circuits. */
3709 routerset_t *Tor2webRendezvousPoints;
3711 /** Close hidden service client circuits immediately when they reach
3712 * the normal circuit-build timeout, even if they have already sent
3713 * an INTRODUCE1 cell on its way to the service. */
3714 int CloseHSClientCircuitsImmediatelyOnTimeout;
3716 /** Close hidden-service-side rendezvous circuits immediately when
3717 * they reach the normal circuit-build timeout. */
3718 int CloseHSServiceRendCircuitsImmediatelyOnTimeout;
3720 /** Onion Services in HiddenServiceSingleHopMode make one-hop (direct)
3721 * circuits between the onion service server, and the introduction and
3722 * rendezvous points. (Onion service descriptors are still posted using
3723 * 3-hop paths, to avoid onion service directories blocking the service.)
3724 * This option makes every hidden service instance hosted by
3725 * this tor instance a Single Onion Service.
3726 * HiddenServiceSingleHopMode requires HiddenServiceNonAnonymousMode to be
3727 * set to 1.
3728 * Use rend_service_allow_non_anonymous_connection() or
3729 * rend_service_reveal_startup_time() instead of using this option directly.
3731 int HiddenServiceSingleHopMode;
3732 /* Makes hidden service clients and servers non-anonymous on this tor
3733 * instance. Allows the non-anonymous HiddenServiceSingleHopMode. Enables
3734 * non-anonymous behaviour in the hidden service protocol.
3735 * Use rend_service_non_anonymous_mode_enabled() instead of using this option
3736 * directly.
3738 int HiddenServiceNonAnonymousMode;
3740 int ConnLimit; /**< Demanded minimum number of simultaneous connections. */
3741 int ConnLimit_; /**< Maximum allowed number of simultaneous connections. */
3742 int ConnLimit_high_thresh; /**< start trying to lower socket usage if we
3743 * have this many. */
3744 int ConnLimit_low_thresh; /**< try to get down to here after socket
3745 * exhaustion. */
3746 int RunAsDaemon; /**< If true, run in the background. (Unix only) */
3747 int FascistFirewall; /**< Whether to prefer ORs reachable on open ports. */
3748 smartlist_t *FirewallPorts; /**< Which ports our firewall allows
3749 * (strings). */
3750 config_line_t *ReachableAddresses; /**< IP:ports our firewall allows. */
3751 config_line_t *ReachableORAddresses; /**< IP:ports for OR conns. */
3752 config_line_t *ReachableDirAddresses; /**< IP:ports for Dir conns. */
3754 int ConstrainedSockets; /**< Shrink xmit and recv socket buffers. */
3755 uint64_t ConstrainedSockSize; /**< Size of constrained buffers. */
3757 /** Whether we should drop exit streams from Tors that we don't know are
3758 * relays. One of "0" (never refuse), "1" (always refuse), or "-1" (do
3759 * what the consensus says, defaulting to 'refuse' if the consensus says
3760 * nothing). */
3761 int RefuseUnknownExits;
3763 /** Application ports that require all nodes in circ to have sufficient
3764 * uptime. */
3765 smartlist_t *LongLivedPorts;
3766 /** Application ports that are likely to be unencrypted and
3767 * unauthenticated; we reject requests for them to prevent the
3768 * user from screwing up and leaking plaintext secrets to an
3769 * observer somewhere on the Internet. */
3770 smartlist_t *RejectPlaintextPorts;
3771 /** Related to RejectPlaintextPorts above, except this config option
3772 * controls whether we warn (in the log and via a controller status
3773 * event) every time a risky connection is attempted. */
3774 smartlist_t *WarnPlaintextPorts;
3775 /** Should we try to reuse the same exit node for a given host */
3776 smartlist_t *TrackHostExits;
3777 int TrackHostExitsExpire; /**< Number of seconds until we expire an
3778 * addressmap */
3779 config_line_t *AddressMap; /**< List of address map directives. */
3780 int AutomapHostsOnResolve; /**< If true, when we get a resolve request for a
3781 * hostname ending with one of the suffixes in
3782 * <b>AutomapHostsSuffixes</b>, map it to a
3783 * virtual address. */
3784 /** List of suffixes for <b>AutomapHostsOnResolve</b>. The special value
3785 * "." means "match everything." */
3786 smartlist_t *AutomapHostsSuffixes;
3787 int RendPostPeriod; /**< How often do we post each rendezvous service
3788 * descriptor? Remember to publish them independently. */
3789 int KeepalivePeriod; /**< How often do we send padding cells to keep
3790 * connections alive? */
3791 int SocksTimeout; /**< How long do we let a socks connection wait
3792 * unattached before we fail it? */
3793 int LearnCircuitBuildTimeout; /**< If non-zero, we attempt to learn a value
3794 * for CircuitBuildTimeout based on timeout
3795 * history. Use circuit_build_times_disabled()
3796 * rather than checking this value directly. */
3797 int CircuitBuildTimeout; /**< Cull non-open circuits that were born at
3798 * least this many seconds ago. Used until
3799 * adaptive algorithm learns a new value. */
3800 int CircuitIdleTimeout; /**< Cull open clean circuits that were born
3801 * at least this many seconds ago. */
3802 int CircuitStreamTimeout; /**< If non-zero, detach streams from circuits
3803 * and try a new circuit if the stream has been
3804 * waiting for this many seconds. If zero, use
3805 * our default internal timeout schedule. */
3806 int MaxOnionQueueDelay; /*< DOCDOC */
3807 int NewCircuitPeriod; /**< How long do we use a circuit before building
3808 * a new one? */
3809 int MaxCircuitDirtiness; /**< Never use circs that were first used more than
3810 this interval ago. */
3811 int PredictedPortsRelevanceTime; /** How long after we've requested a
3812 * connection for a given port, do we want
3813 * to continue to pick exits that support
3814 * that port? */
3815 uint64_t BandwidthRate; /**< How much bandwidth, on average, are we willing
3816 * to use in a second? */
3817 uint64_t BandwidthBurst; /**< How much bandwidth, at maximum, are we willing
3818 * to use in a second? */
3819 uint64_t MaxAdvertisedBandwidth; /**< How much bandwidth are we willing to
3820 * tell people we have? */
3821 uint64_t RelayBandwidthRate; /**< How much bandwidth, on average, are we
3822 * willing to use for all relayed conns? */
3823 uint64_t RelayBandwidthBurst; /**< How much bandwidth, at maximum, will we
3824 * use in a second for all relayed conns? */
3825 uint64_t PerConnBWRate; /**< Long-term bw on a single TLS conn, if set. */
3826 uint64_t PerConnBWBurst; /**< Allowed burst on a single TLS conn, if set. */
3827 int NumCPUs; /**< How many CPUs should we try to use? */
3828 //int RunTesting; /**< If true, create testing circuits to measure how well the
3829 // * other ORs are running. */
3830 config_line_t *RendConfigLines; /**< List of configuration lines
3831 * for rendezvous services. */
3832 config_line_t *HidServAuth; /**< List of configuration lines for client-side
3833 * authorizations for hidden services */
3834 char *ContactInfo; /**< Contact info to be published in the directory. */
3836 int HeartbeatPeriod; /**< Log heartbeat messages after this many seconds
3837 * have passed. */
3839 char *HTTPProxy; /**< hostname[:port] to use as http proxy, if any. */
3840 tor_addr_t HTTPProxyAddr; /**< Parsed IPv4 addr for http proxy, if any. */
3841 uint16_t HTTPProxyPort; /**< Parsed port for http proxy, if any. */
3842 char *HTTPProxyAuthenticator; /**< username:password string, if any. */
3844 char *HTTPSProxy; /**< hostname[:port] to use as https proxy, if any. */
3845 tor_addr_t HTTPSProxyAddr; /**< Parsed addr for https proxy, if any. */
3846 uint16_t HTTPSProxyPort; /**< Parsed port for https proxy, if any. */
3847 char *HTTPSProxyAuthenticator; /**< username:password string, if any. */
3849 char *Socks4Proxy; /**< hostname:port to use as a SOCKS4 proxy, if any. */
3850 tor_addr_t Socks4ProxyAddr; /**< Derived from Socks4Proxy. */
3851 uint16_t Socks4ProxyPort; /**< Derived from Socks4Proxy. */
3853 char *Socks5Proxy; /**< hostname:port to use as a SOCKS5 proxy, if any. */
3854 tor_addr_t Socks5ProxyAddr; /**< Derived from Sock5Proxy. */
3855 uint16_t Socks5ProxyPort; /**< Derived from Socks5Proxy. */
3856 char *Socks5ProxyUsername; /**< Username for SOCKS5 authentication, if any */
3857 char *Socks5ProxyPassword; /**< Password for SOCKS5 authentication, if any */
3859 /** List of configuration lines for replacement directory authorities.
3860 * If you just want to replace one class of authority at a time,
3861 * use the "Alternate*Authority" options below instead. */
3862 config_line_t *DirAuthorities;
3864 /** List of fallback directory servers */
3865 config_line_t *FallbackDir;
3866 /** Whether to use the default hard-coded FallbackDirs */
3867 int UseDefaultFallbackDirs;
3869 /** Weight to apply to all directory authority rates if considering them
3870 * along with fallbackdirs */
3871 double DirAuthorityFallbackRate;
3873 /** If set, use these main (currently v3) directory authorities and
3874 * not the default ones. */
3875 config_line_t *AlternateDirAuthority;
3877 /** If set, use these bridge authorities and not the default one. */
3878 config_line_t *AlternateBridgeAuthority;
3880 char *MyFamily; /**< Declared family for this OR. */
3881 config_line_t *NodeFamilies; /**< List of config lines for
3882 * node families */
3883 smartlist_t *NodeFamilySets; /**< List of parsed NodeFamilies values. */
3884 config_line_t *AuthDirBadExit; /**< Address policy for descriptors to
3885 * mark as bad exits. */
3886 config_line_t *AuthDirReject; /**< Address policy for descriptors to
3887 * reject. */
3888 config_line_t *AuthDirInvalid; /**< Address policy for descriptors to
3889 * never mark as valid. */
3890 /** @name AuthDir...CC
3892 * Lists of country codes to mark as BadExit, or Invalid, or to
3893 * reject entirely.
3895 * @{
3897 smartlist_t *AuthDirBadExitCCs;
3898 smartlist_t *AuthDirInvalidCCs;
3899 smartlist_t *AuthDirRejectCCs;
3900 /**@}*/
3902 int AuthDirListBadExits; /**< True iff we should list bad exits,
3903 * and vote for all other exits as good. */
3904 int AuthDirMaxServersPerAddr; /**< Do not permit more than this
3905 * number of servers per IP address. */
3906 int AuthDirMaxServersPerAuthAddr; /**< Do not permit more than this
3907 * number of servers per IP address shared
3908 * with an authority. */
3909 int AuthDirHasIPv6Connectivity; /**< Boolean: are we on IPv6? */
3910 int AuthDirPinKeys; /**< Boolean: Do we enforce key-pinning? */
3912 /** If non-zero, always vote the Fast flag for any relay advertising
3913 * this amount of capacity or more. */
3914 uint64_t AuthDirFastGuarantee;
3916 /** If non-zero, this advertised capacity or more is always sufficient
3917 * to satisfy the bandwidth requirement for the Guard flag. */
3918 uint64_t AuthDirGuardBWGuarantee;
3920 char *AccountingStart; /**< How long is the accounting interval, and when
3921 * does it start? */
3922 uint64_t AccountingMax; /**< How many bytes do we allow per accounting
3923 * interval before hibernation? 0 for "never
3924 * hibernate." */
3925 /** How do we determine when our AccountingMax has been reached?
3926 * "max" for when in or out reaches AccountingMax
3927 * "sum" for when in plus out reaches AccountingMax
3928 * "in" for when in reaches AccountingMax
3929 * "out" for when out reaches AccountingMax */
3930 char *AccountingRule_option;
3931 enum { ACCT_MAX, ACCT_SUM, ACCT_IN, ACCT_OUT } AccountingRule;
3933 /** Base64-encoded hash of accepted passwords for the control system. */
3934 config_line_t *HashedControlPassword;
3935 /** As HashedControlPassword, but not saved. */
3936 config_line_t *HashedControlSessionPassword;
3938 int CookieAuthentication; /**< Boolean: do we enable cookie-based auth for
3939 * the control system? */
3940 char *CookieAuthFile; /**< Filesystem location of a ControlPort
3941 * authentication cookie. */
3942 char *ExtORPortCookieAuthFile; /**< Filesystem location of Extended
3943 * ORPort authentication cookie. */
3944 int CookieAuthFileGroupReadable; /**< Boolean: Is the CookieAuthFile g+r? */
3945 int ExtORPortCookieAuthFileGroupReadable; /**< Boolean: Is the
3946 * ExtORPortCookieAuthFile g+r? */
3947 int LeaveStreamsUnattached; /**< Boolean: Does Tor attach new streams to
3948 * circuits itself (0), or does it expect a controller
3949 * to cope? (1) */
3950 int DisablePredictedCircuits; /**< Boolean: does Tor preemptively
3951 * make circuits in the background (0),
3952 * or not (1)? */
3954 /** Process specifier for a controller that ‘owns’ this Tor
3955 * instance. Tor will terminate if its owning controller does. */
3956 char *OwningControllerProcess;
3958 int ShutdownWaitLength; /**< When we get a SIGINT and we're a server, how
3959 * long do we wait before exiting? */
3960 char *SafeLogging; /**< Contains "relay", "1", "0" (meaning no scrubbing). */
3962 /* Derived from SafeLogging */
3963 enum {
3964 SAFELOG_SCRUB_ALL, SAFELOG_SCRUB_RELAY, SAFELOG_SCRUB_NONE
3965 } SafeLogging_;
3967 int Sandbox; /**< Boolean: should sandboxing be enabled? */
3968 int SafeSocks; /**< Boolean: should we outright refuse application
3969 * connections that use socks4 or socks5-with-local-dns? */
3970 #define LOG_PROTOCOL_WARN (get_options()->ProtocolWarnings ? \
3971 LOG_WARN : LOG_INFO)
3972 int ProtocolWarnings; /**< Boolean: when other parties screw up the Tor
3973 * protocol, is it a warn or an info in our logs? */
3974 int TestSocks; /**< Boolean: when we get a socks connection, do we loudly
3975 * log whether it was DNS-leaking or not? */
3976 int HardwareAccel; /**< Boolean: Should we enable OpenSSL hardware
3977 * acceleration where available? */
3978 /** Token Bucket Refill resolution in milliseconds. */
3979 int TokenBucketRefillInterval;
3980 char *AccelName; /**< Optional hardware acceleration engine name. */
3981 char *AccelDir; /**< Optional hardware acceleration engine search dir. */
3983 /** Boolean: Do we try to enter from a smallish number
3984 * of fixed nodes? */
3985 int UseEntryGuards_option;
3986 /** Internal variable to remember whether we're actually acting on
3987 * UseEntryGuards_option -- when we're a non-anonymous Tor2web client or
3988 * Single Onion Service, it is alwasy false, otherwise we use the value of
3989 * UseEntryGuards_option. */
3990 int UseEntryGuards;
3992 int NumEntryGuards; /**< How many entry guards do we try to establish? */
3993 int UseEntryGuardsAsDirGuards; /** Boolean: Do we try to get directory info
3994 * from a smallish number of fixed nodes? */
3996 /** If 1, we use any guardfraction information we see in the
3997 * consensus. If 0, we don't. If -1, let the consensus parameter
3998 * decide. */
3999 int UseGuardFraction;
4001 int NumDirectoryGuards; /**< How many dir guards do we try to establish?
4002 * If 0, use value from NumEntryGuards. */
4003 int RephistTrackTime; /**< How many seconds do we keep rephist info? */
4004 int FastFirstHopPK; /**< If Tor believes it is safe, should we save a third
4005 * of our PK time by sending CREATE_FAST cells? */
4006 /** Should we always fetch our dir info on the mirror schedule (which
4007 * means directly from the authorities) no matter our other config? */
4008 int FetchDirInfoEarly;
4010 /** Should we fetch our dir info at the start of the consensus period? */
4011 int FetchDirInfoExtraEarly;
4013 int DirCache; /**< Cache all directory documents and accept requests via
4014 * tunnelled dir conns from clients. If 1, enabled (default);
4015 * If 0, disabled. */
4017 char *VirtualAddrNetworkIPv4; /**< Address and mask to hand out for virtual
4018 * MAPADDRESS requests for IPv4 addresses */
4019 char *VirtualAddrNetworkIPv6; /**< Address and mask to hand out for virtual
4020 * MAPADDRESS requests for IPv6 addresses */
4021 int ServerDNSSearchDomains; /**< Boolean: If set, we don't force exit
4022 * addresses to be FQDNs, but rather search for them in
4023 * the local domains. */
4024 int ServerDNSDetectHijacking; /**< Boolean: If true, check for DNS failure
4025 * hijacking. */
4026 int ServerDNSRandomizeCase; /**< Boolean: Use the 0x20-hack to prevent
4027 * DNS poisoning attacks. */
4028 char *ServerDNSResolvConfFile; /**< If provided, we configure our internal
4029 * resolver from the file here rather than from
4030 * /etc/resolv.conf (Unix) or the registry (Windows). */
4031 char *DirPortFrontPage; /**< This is a full path to a file with an html
4032 disclaimer. This allows a server administrator to show
4033 that they're running Tor and anyone visiting their server
4034 will know this without any specialized knowledge. */
4035 int DisableDebuggerAttachment; /**< Currently Linux only specific attempt to
4036 disable ptrace; needs BSD testing. */
4037 /** Boolean: if set, we start even if our resolv.conf file is missing
4038 * or broken. */
4039 int ServerDNSAllowBrokenConfig;
4040 /** Boolean: if set, then even connections to private addresses will get
4041 * rate-limited. */
4042 int CountPrivateBandwidth;
4043 smartlist_t *ServerDNSTestAddresses; /**< A list of addresses that definitely
4044 * should be resolvable. Used for
4045 * testing our DNS server. */
4046 int EnforceDistinctSubnets; /**< If true, don't allow multiple routers in the
4047 * same network zone in the same circuit. */
4048 int PortForwarding; /**< If true, use NAT-PMP or UPnP to automatically
4049 * forward the DirPort and ORPort on the NAT device */
4050 char *PortForwardingHelper; /** < Filename or full path of the port
4051 forwarding helper executable */
4052 int AllowNonRFC953Hostnames; /**< If true, we allow connections to hostnames
4053 * with weird characters. */
4054 /** If true, we try resolving hostnames with weird characters. */
4055 int ServerDNSAllowNonRFC953Hostnames;
4057 /** If true, we try to download extra-info documents (and we serve them,
4058 * if we are a cache). For authorities, this is always true. */
4059 int DownloadExtraInfo;
4061 /** If true, and we are acting as a relay, allow exit circuits even when
4062 * we are the first hop of a circuit. */
4063 int AllowSingleHopExits;
4064 /** If true, don't allow relays with AllowSingleHopExits=1 to be used in
4065 * circuits that we build. */
4066 int ExcludeSingleHopRelays;
4067 /** If true, and the controller tells us to use a one-hop circuit, and the
4068 * exit allows it, we use it. */
4069 int AllowSingleHopCircuits;
4071 /** If true, we convert "www.google.com.foo.exit" addresses on the
4072 * socks/trans/natd ports into "www.google.com" addresses that
4073 * exit from the node "foo". Disabled by default since attacking
4074 * websites and exit relays can use it to manipulate your path
4075 * selection. */
4076 int AllowDotExit;
4078 /** If true, we will warn if a user gives us only an IP address
4079 * instead of a hostname. */
4080 int WarnUnsafeSocks;
4082 /** If true, we're configured to collect statistics on clients
4083 * requesting network statuses from us as directory. */
4084 int DirReqStatistics_option;
4085 /** Internal variable to remember whether we're actually acting on
4086 * DirReqStatistics_option -- yes if it's set and we're a server, else no. */
4087 int DirReqStatistics;
4089 /** If true, the user wants us to collect statistics on port usage. */
4090 int ExitPortStatistics;
4092 /** If true, the user wants us to collect connection statistics. */
4093 int ConnDirectionStatistics;
4095 /** If true, the user wants us to collect cell statistics. */
4096 int CellStatistics;
4098 /** If true, the user wants us to collect statistics as entry node. */
4099 int EntryStatistics;
4101 /** If true, the user wants us to collect statistics as hidden service
4102 * directory, introduction point, or rendezvous point. */
4103 int HiddenServiceStatistics;
4105 /** If true, include statistics file contents in extra-info documents. */
4106 int ExtraInfoStatistics;
4108 /** If true, do not believe anybody who tells us that a domain resolves
4109 * to an internal address, or that an internal address has a PTR mapping.
4110 * Helps avoid some cross-site attacks. */
4111 int ClientDNSRejectInternalAddresses;
4113 /** If true, do not accept any requests to connect to internal addresses
4114 * over randomly chosen exits. */
4115 int ClientRejectInternalAddresses;
4117 /** If true, clients may connect over IPv4. If false, they will avoid
4118 * connecting over IPv4. We enforce this for OR and Dir connections. */
4119 int ClientUseIPv4;
4120 /** If true, clients may connect over IPv6. If false, they will avoid
4121 * connecting over IPv4. We enforce this for OR and Dir connections.
4122 * Use fascist_firewall_use_ipv6() instead of accessing this value
4123 * directly. */
4124 int ClientUseIPv6;
4125 /** If true, prefer an IPv6 OR port over an IPv4 one for entry node
4126 * connections. If auto, bridge clients prefer IPv6, and other clients
4127 * prefer IPv4. Use node_ipv6_or_preferred() instead of accessing this value
4128 * directly. */
4129 int ClientPreferIPv6ORPort;
4130 /** If true, prefer an IPv6 directory port over an IPv4 one for direct
4131 * directory connections. If auto, bridge clients prefer IPv6, and other
4132 * clients prefer IPv4. Use fascist_firewall_prefer_ipv6_dirport() instead of
4133 * accessing this value directly. */
4134 int ClientPreferIPv6DirPort;
4136 /** The length of time that we think a consensus should be fresh. */
4137 int V3AuthVotingInterval;
4138 /** The length of time we think it will take to distribute votes. */
4139 int V3AuthVoteDelay;
4140 /** The length of time we think it will take to distribute signatures. */
4141 int V3AuthDistDelay;
4142 /** The number of intervals we think a consensus should be valid. */
4143 int V3AuthNIntervalsValid;
4145 /** Should advertise and sign consensuses with a legacy key, for key
4146 * migration purposes? */
4147 int V3AuthUseLegacyKey;
4149 /** Location of bandwidth measurement file */
4150 char *V3BandwidthsFile;
4152 /** Location of guardfraction file */
4153 char *GuardfractionFile;
4155 /** Authority only: key=value pairs that we add to our networkstatus
4156 * consensus vote on the 'params' line. */
4157 char *ConsensusParams;
4159 /** Authority only: minimum number of measured bandwidths we must see
4160 * before we only believe measured bandwidths to assign flags. */
4161 int MinMeasuredBWsForAuthToIgnoreAdvertised;
4163 /** The length of time that we think an initial consensus should be fresh.
4164 * Only altered on testing networks. */
4165 int TestingV3AuthInitialVotingInterval;
4167 /** The length of time we think it will take to distribute initial votes.
4168 * Only altered on testing networks. */
4169 int TestingV3AuthInitialVoteDelay;
4171 /** The length of time we think it will take to distribute initial
4172 * signatures. Only altered on testing networks.*/
4173 int TestingV3AuthInitialDistDelay;
4175 /** Offset in seconds added to the starting time for consensus
4176 voting. Only altered on testing networks. */
4177 int TestingV3AuthVotingStartOffset;
4179 /** If an authority has been around for less than this amount of time, it
4180 * does not believe its reachability information is accurate. Only
4181 * altered on testing networks. */
4182 int TestingAuthDirTimeToLearnReachability;
4184 /** Clients don't download any descriptor this recent, since it will
4185 * probably not have propagated to enough caches. Only altered on testing
4186 * networks. */
4187 int TestingEstimatedDescriptorPropagationTime;
4189 /** Schedule for when servers should download things in general. Only
4190 * altered on testing networks. */
4191 smartlist_t *TestingServerDownloadSchedule;
4193 /** Schedule for when clients should download things in general. Only
4194 * altered on testing networks. */
4195 smartlist_t *TestingClientDownloadSchedule;
4197 /** Schedule for when servers should download consensuses. Only altered
4198 * on testing networks. */
4199 smartlist_t *TestingServerConsensusDownloadSchedule;
4201 /** Schedule for when clients should download consensuses. Only altered
4202 * on testing networks. */
4203 smartlist_t *TestingClientConsensusDownloadSchedule;
4205 /** Schedule for when clients should download consensuses from authorities
4206 * if they are bootstrapping (that is, they don't have a usable, reasonably
4207 * live consensus). Only used by clients fetching from a list of fallback
4208 * directory mirrors.
4210 * This schedule is incremented by (potentially concurrent) connection
4211 * attempts, unlike other schedules, which are incremented by connection
4212 * failures. Only altered on testing networks. */
4213 smartlist_t *ClientBootstrapConsensusAuthorityDownloadSchedule;
4215 /** Schedule for when clients should download consensuses from fallback
4216 * directory mirrors if they are bootstrapping (that is, they don't have a
4217 * usable, reasonably live consensus). Only used by clients fetching from a
4218 * list of fallback directory mirrors.
4220 * This schedule is incremented by (potentially concurrent) connection
4221 * attempts, unlike other schedules, which are incremented by connection
4222 * failures. Only altered on testing networks. */
4223 smartlist_t *ClientBootstrapConsensusFallbackDownloadSchedule;
4225 /** Schedule for when clients should download consensuses from authorities
4226 * if they are bootstrapping (that is, they don't have a usable, reasonably
4227 * live consensus). Only used by clients which don't have or won't fetch
4228 * from a list of fallback directory mirrors.
4230 * This schedule is incremented by (potentially concurrent) connection
4231 * attempts, unlike other schedules, which are incremented by connection
4232 * failures. Only altered on testing networks. */
4233 smartlist_t *ClientBootstrapConsensusAuthorityOnlyDownloadSchedule;
4235 /** Schedule for when clients should download bridge descriptors. Only
4236 * altered on testing networks. */
4237 smartlist_t *TestingBridgeDownloadSchedule;
4239 /** When directory clients have only a few descriptors to request, they
4240 * batch them until they have more, or until this amount of time has
4241 * passed. Only altered on testing networks. */
4242 int TestingClientMaxIntervalWithoutRequest;
4244 /** How long do we let a directory connection stall before expiring
4245 * it? Only altered on testing networks. */
4246 int TestingDirConnectionMaxStall;
4248 /** How many times will we try to fetch a consensus before we give
4249 * up? Only altered on testing networks. */
4250 int TestingConsensusMaxDownloadTries;
4252 /** How many times will a client try to fetch a consensus while
4253 * bootstrapping using a list of fallback directories, before it gives up?
4254 * Only altered on testing networks. */
4255 int ClientBootstrapConsensusMaxDownloadTries;
4257 /** How many times will a client try to fetch a consensus while
4258 * bootstrapping using only a list of authorities, before it gives up?
4259 * Only altered on testing networks. */
4260 int ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries;
4262 /** How many simultaneous in-progress connections will we make when trying
4263 * to fetch a consensus before we wait for one to complete, timeout, or
4264 * error out? Only altered on testing networks. */
4265 int ClientBootstrapConsensusMaxInProgressTries;
4267 /** How many times will we try to download a router's descriptor before
4268 * giving up? Only altered on testing networks. */
4269 int TestingDescriptorMaxDownloadTries;
4271 /** How many times will we try to download a microdescriptor before
4272 * giving up? Only altered on testing networks. */
4273 int TestingMicrodescMaxDownloadTries;
4275 /** How many times will we try to fetch a certificate before giving
4276 * up? Only altered on testing networks. */
4277 int TestingCertMaxDownloadTries;
4279 /** If true, we take part in a testing network. Change the defaults of a
4280 * couple of other configuration options and allow to change the values
4281 * of certain configuration options. */
4282 int TestingTorNetwork;
4284 /** Minimum value for the Exit flag threshold on testing networks. */
4285 uint64_t TestingMinExitFlagThreshold;
4287 /** Minimum value for the Fast flag threshold on testing networks. */
4288 uint64_t TestingMinFastFlagThreshold;
4290 /** Relays in a testing network which should be voted Exit
4291 * regardless of exit policy. */
4292 routerset_t *TestingDirAuthVoteExit;
4293 int TestingDirAuthVoteExitIsStrict;
4295 /** Relays in a testing network which should be voted Guard
4296 * regardless of uptime and bandwidth. */
4297 routerset_t *TestingDirAuthVoteGuard;
4298 int TestingDirAuthVoteGuardIsStrict;
4300 /** Relays in a testing network which should be voted HSDir
4301 * regardless of uptime and DirPort.
4302 * Respects VoteOnHidServDirectoriesV2. */
4303 routerset_t *TestingDirAuthVoteHSDir;
4304 int TestingDirAuthVoteHSDirIsStrict;
4306 /** Enable CONN_BW events. Only altered on testing networks. */
4307 int TestingEnableConnBwEvent;
4309 /** Enable CELL_STATS events. Only altered on testing networks. */
4310 int TestingEnableCellStatsEvent;
4312 /** Enable TB_EMPTY events. Only altered on testing networks. */
4313 int TestingEnableTbEmptyEvent;
4315 /** If true, and we have GeoIP data, and we're a bridge, keep a per-country
4316 * count of how many client addresses have contacted us so that we can help
4317 * the bridge authority guess which countries have blocked access to us. */
4318 int BridgeRecordUsageByCountry;
4320 /** Optionally, IPv4 and IPv6 GeoIP data. */
4321 char *GeoIPFile;
4322 char *GeoIPv6File;
4324 /** Autobool: if auto, then any attempt to Exclude{Exit,}Nodes a particular
4325 * country code will exclude all nodes in ?? and A1. If true, all nodes in
4326 * ?? and A1 are excluded. Has no effect if we don't know any GeoIP data. */
4327 int GeoIPExcludeUnknown;
4329 /** If true, SIGHUP should reload the torrc. Sometimes controllers want
4330 * to make this false. */
4331 int ReloadTorrcOnSIGHUP;
4333 /* The main parameter for picking circuits within a connection.
4335 * If this value is positive, when picking a cell to relay on a connection,
4336 * we always relay from the circuit whose weighted cell count is lowest.
4337 * Cells are weighted exponentially such that if one cell is sent
4338 * 'CircuitPriorityHalflife' seconds before another, it counts for half as
4339 * much.
4341 * If this value is zero, we're disabling the cell-EWMA algorithm.
4343 * If this value is negative, we're using the default approach
4344 * according to either Tor or a parameter set in the consensus.
4346 double CircuitPriorityHalflife;
4348 /** Set to true if the TestingTorNetwork configuration option is set.
4349 * This is used so that options_validate() has a chance to realize that
4350 * the defaults have changed. */
4351 int UsingTestNetworkDefaults_;
4353 /** If 1, we try to use microdescriptors to build circuits. If 0, we don't.
4354 * If -1, Tor decides. */
4355 int UseMicrodescriptors;
4357 /** File where we should write the ControlPort. */
4358 char *ControlPortWriteToFile;
4359 /** Should that file be group-readable? */
4360 int ControlPortFileGroupReadable;
4362 #define MAX_MAX_CLIENT_CIRCUITS_PENDING 1024
4363 /** Maximum number of non-open general-purpose origin circuits to allow at
4364 * once. */
4365 int MaxClientCircuitsPending;
4367 /** If 1, we always send optimistic data when it's supported. If 0, we
4368 * never use it. If -1, we do what the consensus says. */
4369 int OptimisticData;
4371 /** If 1, we accept and launch no external network connections, except on
4372 * control ports. */
4373 int DisableNetwork;
4376 * Parameters for path-bias detection.
4377 * @{
4378 * These options override the default behavior of Tor's (**currently
4379 * experimental**) path bias detection algorithm. To try to find broken or
4380 * misbehaving guard nodes, Tor looks for nodes where more than a certain
4381 * fraction of circuits through that guard fail to get built.
4383 * The PathBiasCircThreshold option controls how many circuits we need to
4384 * build through a guard before we make these checks. The
4385 * PathBiasNoticeRate, PathBiasWarnRate and PathBiasExtremeRate options
4386 * control what fraction of circuits must succeed through a guard so we
4387 * won't write log messages. If less than PathBiasExtremeRate circuits
4388 * succeed *and* PathBiasDropGuards is set to 1, we disable use of that
4389 * guard.
4391 * When we have seen more than PathBiasScaleThreshold circuits through a
4392 * guard, we scale our observations by 0.5 (governed by the consensus) so
4393 * that new observations don't get swamped by old ones.
4395 * By default, or if a negative value is provided for one of these options,
4396 * Tor uses reasonable defaults from the networkstatus consensus document.
4397 * If no defaults are available there, these options default to 150, .70,
4398 * .50, .30, 0, and 300 respectively.
4400 int PathBiasCircThreshold;
4401 double PathBiasNoticeRate;
4402 double PathBiasWarnRate;
4403 double PathBiasExtremeRate;
4404 int PathBiasDropGuards;
4405 int PathBiasScaleThreshold;
4406 /** @} */
4409 * Parameters for path-bias use detection
4410 * @{
4411 * Similar to the above options, these options override the default behavior
4412 * of Tor's (**currently experimental**) path use bias detection algorithm.
4414 * Where as the path bias parameters govern thresholds for successfully
4415 * building circuits, these four path use bias parameters govern thresholds
4416 * only for circuit usage. Circuits which receive no stream usage are not
4417 * counted by this detection algorithm. A used circuit is considered
4418 * successful if it is capable of carrying streams or otherwise receiving
4419 * well-formed responses to RELAY cells.
4421 * By default, or if a negative value is provided for one of these options,
4422 * Tor uses reasonable defaults from the networkstatus consensus document.
4423 * If no defaults are available there, these options default to 20, .80,
4424 * .60, and 100, respectively.
4426 int PathBiasUseThreshold;
4427 double PathBiasNoticeUseRate;
4428 double PathBiasExtremeUseRate;
4429 int PathBiasScaleUseThreshold;
4430 /** @} */
4432 int IPv6Exit; /**< Do we support exiting to IPv6 addresses? */
4434 char *TLSECGroup; /**< One of "P256", "P224", or nil for auto */
4436 /** Fraction: */
4437 double PathsNeededToBuildCircuits;
4439 /** What expiry time shall we place on our SSL certs? "0" means we
4440 * should guess a suitable value. */
4441 int SSLKeyLifetime;
4443 /** How long (seconds) do we keep a guard before picking a new one? */
4444 int GuardLifetime;
4446 /** Low-water mark for global scheduler - start sending when estimated
4447 * queued size falls below this threshold.
4449 uint64_t SchedulerLowWaterMark__;
4450 /** High-water mark for global scheduler - stop sending when estimated
4451 * queued size exceeds this threshold.
4453 uint64_t SchedulerHighWaterMark__;
4454 /** Flush size for global scheduler - flush this many cells at a time
4455 * when sending.
4457 int SchedulerMaxFlushCells__;
4459 /** Is this an exit node? This is a tristate, where "1" means "yes, and use
4460 * the default exit policy if none is given" and "0" means "no; exit policy
4461 * is 'reject *'" and "auto" (-1) means "same as 1, but warn the user."
4463 * XXXX Eventually, the default will be 0. */
4464 int ExitRelay;
4466 /** For how long (seconds) do we declare our singning keys to be valid? */
4467 int SigningKeyLifetime;
4468 /** For how long (seconds) do we declare our link keys to be valid? */
4469 int TestingLinkCertLifetime;
4470 /** For how long (seconds) do we declare our auth keys to be valid? */
4471 int TestingAuthKeyLifetime;
4473 /** How long before signing keys expire will we try to make a new one? */
4474 int TestingSigningKeySlop;
4475 /** How long before link keys expire will we try to make a new one? */
4476 int TestingLinkKeySlop;
4477 /** How long before auth keys expire will we try to make a new one? */
4478 int TestingAuthKeySlop;
4480 /** Force use of offline master key features: never generate a master
4481 * ed25519 identity key except from tor --keygen */
4482 int OfflineMasterKey;
4484 enum {
4485 FORCE_PASSPHRASE_AUTO=0,
4486 FORCE_PASSPHRASE_ON,
4487 FORCE_PASSPHRASE_OFF
4488 } keygen_force_passphrase;
4489 int use_keygen_passphrase_fd;
4490 int keygen_passphrase_fd;
4491 int change_key_passphrase;
4492 char *master_key_fname;
4494 /** Autobool: Do we try to retain capabilities if we can? */
4495 int KeepBindCapabilities;
4497 /** Maximum total size of unparseable descriptors to log during the
4498 * lifetime of this Tor process.
4500 uint64_t MaxUnparseableDescSizeToLog;
4502 /** Bool (default: 1): Switch for the shared random protocol. Only
4503 * relevant to a directory authority. If off, the authority won't
4504 * participate in the protocol. If on (default), a flag is added to the
4505 * vote indicating participation. */
4506 int AuthDirSharedRandomness;
4508 /** If 1, we skip all OOS checks. */
4509 int DisableOOSCheck;
4510 } or_options_t;
4512 /** Persistent state for an onion router, as saved to disk. */
4513 typedef struct {
4514 uint32_t magic_;
4515 /** The time at which we next plan to write the state to the disk. Equal to
4516 * TIME_MAX if there are no savable changes, 0 if there are changes that
4517 * should be saved right away. */
4518 time_t next_write;
4520 /** When was the state last written to disk? */
4521 time_t LastWritten;
4523 /** Fields for accounting bandwidth use. */
4524 time_t AccountingIntervalStart;
4525 uint64_t AccountingBytesReadInInterval;
4526 uint64_t AccountingBytesWrittenInInterval;
4527 int AccountingSecondsActive;
4528 int AccountingSecondsToReachSoftLimit;
4529 time_t AccountingSoftLimitHitAt;
4530 uint64_t AccountingBytesAtSoftLimit;
4531 uint64_t AccountingExpectedUsage;
4533 /** A list of Entry Guard-related configuration lines. */
4534 config_line_t *EntryGuards;
4536 config_line_t *TransportProxies;
4538 /** These fields hold information on the history of bandwidth usage for
4539 * servers. The "Ends" fields hold the time when we last updated the
4540 * bandwidth usage. The "Interval" fields hold the granularity, in seconds,
4541 * of the entries of Values. The "Values" lists hold decimal string
4542 * representations of the number of bytes read or written in each
4543 * interval. The "Maxima" list holds decimal strings describing the highest
4544 * rate achieved during the interval.
4546 time_t BWHistoryReadEnds;
4547 int BWHistoryReadInterval;
4548 smartlist_t *BWHistoryReadValues;
4549 smartlist_t *BWHistoryReadMaxima;
4550 time_t BWHistoryWriteEnds;
4551 int BWHistoryWriteInterval;
4552 smartlist_t *BWHistoryWriteValues;
4553 smartlist_t *BWHistoryWriteMaxima;
4554 time_t BWHistoryDirReadEnds;
4555 int BWHistoryDirReadInterval;
4556 smartlist_t *BWHistoryDirReadValues;
4557 smartlist_t *BWHistoryDirReadMaxima;
4558 time_t BWHistoryDirWriteEnds;
4559 int BWHistoryDirWriteInterval;
4560 smartlist_t *BWHistoryDirWriteValues;
4561 smartlist_t *BWHistoryDirWriteMaxima;
4563 /** Build time histogram */
4564 config_line_t * BuildtimeHistogram;
4565 unsigned int TotalBuildTimes;
4566 unsigned int CircuitBuildAbandonedCount;
4568 /** What version of Tor wrote this state file? */
4569 char *TorVersion;
4571 /** Holds any unrecognized values we found in the state file, in the order
4572 * in which we found them. */
4573 config_line_t *ExtraLines;
4575 /** When did we last rotate our onion key? "0" for 'no idea'. */
4576 time_t LastRotatedOnionKey;
4577 } or_state_t;
4579 /** Change the next_write time of <b>state</b> to <b>when</b>, unless the
4580 * state is already scheduled to be written to disk earlier than <b>when</b>.
4582 static inline void or_state_mark_dirty(or_state_t *state, time_t when)
4584 if (state->next_write > when)
4585 state->next_write = when;
4588 #define MAX_SOCKS_REPLY_LEN 1024
4589 #define MAX_SOCKS_ADDR_LEN 256
4590 #define SOCKS_NO_AUTH 0x00
4591 #define SOCKS_USER_PASS 0x02
4593 /** Please open a TCP connection to this addr:port. */
4594 #define SOCKS_COMMAND_CONNECT 0x01
4595 /** Please turn this FQDN into an IP address, privately. */
4596 #define SOCKS_COMMAND_RESOLVE 0xF0
4597 /** Please turn this IP address into an FQDN, privately. */
4598 #define SOCKS_COMMAND_RESOLVE_PTR 0xF1
4600 /* || 0 is for -Wparentheses-equality (-Wall?) appeasement under clang */
4601 #define SOCKS_COMMAND_IS_CONNECT(c) (((c)==SOCKS_COMMAND_CONNECT) || 0)
4602 #define SOCKS_COMMAND_IS_RESOLVE(c) ((c)==SOCKS_COMMAND_RESOLVE || \
4603 (c)==SOCKS_COMMAND_RESOLVE_PTR)
4605 /** State of a SOCKS request from a user to an OP. Also used to encode other
4606 * information for non-socks user request (such as those on TransPort and
4607 * DNSPort) */
4608 struct socks_request_t {
4609 /** Which version of SOCKS did the client use? One of "0, 4, 5" -- where
4610 * 0 means that no socks handshake ever took place, and this is just a
4611 * stub connection (e.g. see connection_ap_make_link()). */
4612 uint8_t socks_version;
4613 /** If using socks5 authentication, which authentication type did we
4614 * negotiate? currently we support 0 (no authentication) and 2
4615 * (username/password). */
4616 uint8_t auth_type;
4617 /** What is this stream's goal? One of the SOCKS_COMMAND_* values */
4618 uint8_t command;
4619 /** Which kind of listener created this stream? */
4620 uint8_t listener_type;
4621 size_t replylen; /**< Length of <b>reply</b>. */
4622 uint8_t reply[MAX_SOCKS_REPLY_LEN]; /**< Write an entry into this string if
4623 * we want to specify our own socks reply,
4624 * rather than using the default socks4 or
4625 * socks5 socks reply. We use this for the
4626 * two-stage socks5 handshake.
4628 char address[MAX_SOCKS_ADDR_LEN]; /**< What address did the client ask to
4629 connect to/resolve? */
4630 uint16_t port; /**< What port did the client ask to connect to? */
4631 unsigned int has_finished : 1; /**< Has the SOCKS handshake finished? Used to
4632 * make sure we send back a socks reply for
4633 * every connection. */
4634 unsigned int got_auth : 1; /**< Have we received any authentication data? */
4635 /** If this is set, we will choose "no authentication" instead of
4636 * "username/password" authentication if both are offered. Used as input to
4637 * parse_socks. */
4638 unsigned int socks_prefer_no_auth : 1;
4640 /** Number of bytes in username; 0 if username is NULL */
4641 size_t usernamelen;
4642 /** Number of bytes in password; 0 if password is NULL */
4643 uint8_t passwordlen;
4644 /** The negotiated username value if any (for socks5), or the entire
4645 * authentication string (for socks4). This value is NOT nul-terminated;
4646 * see usernamelen for its length. */
4647 char *username;
4648 /** The negotiated password value if any (for socks5). This value is NOT
4649 * nul-terminated; see passwordlen for its length. */
4650 char *password;
4653 /********************************* circuitbuild.c **********************/
4655 /** How many hops does a general-purpose circuit have by default? */
4656 #define DEFAULT_ROUTE_LEN 3
4658 /* Circuit Build Timeout "public" structures. */
4660 /** Precision multiplier for the Bw weights */
4661 #define BW_WEIGHT_SCALE 10000
4662 #define BW_MIN_WEIGHT_SCALE 1
4663 #define BW_MAX_WEIGHT_SCALE INT32_MAX
4665 /** Total size of the circuit timeout history to accumulate.
4666 * 1000 is approx 2.5 days worth of continual-use circuits. */
4667 #define CBT_NCIRCUITS_TO_OBSERVE 1000
4669 /** Width of the histogram bins in milliseconds */
4670 #define CBT_BIN_WIDTH ((build_time_t)50)
4672 /** Number of modes to use in the weighted-avg computation of Xm */
4673 #define CBT_DEFAULT_NUM_XM_MODES 3
4674 #define CBT_MIN_NUM_XM_MODES 1
4675 #define CBT_MAX_NUM_XM_MODES 20
4677 /** A build_time_t is milliseconds */
4678 typedef uint32_t build_time_t;
4681 * CBT_BUILD_ABANDONED is our flag value to represent a force-closed
4682 * circuit (Aka a 'right-censored' pareto value).
4684 #define CBT_BUILD_ABANDONED ((build_time_t)(INT32_MAX-1))
4685 #define CBT_BUILD_TIME_MAX ((build_time_t)(INT32_MAX))
4687 /** Save state every 10 circuits */
4688 #define CBT_SAVE_STATE_EVERY 10
4690 /* Circuit build times consensus parameters */
4693 * How long to wait before actually closing circuits that take too long to
4694 * build in terms of CDF quantile.
4696 #define CBT_DEFAULT_CLOSE_QUANTILE 95
4697 #define CBT_MIN_CLOSE_QUANTILE CBT_MIN_QUANTILE_CUTOFF
4698 #define CBT_MAX_CLOSE_QUANTILE CBT_MAX_QUANTILE_CUTOFF
4701 * How many circuits count as recent when considering if the
4702 * connection has gone gimpy or changed.
4704 #define CBT_DEFAULT_RECENT_CIRCUITS 20
4705 #define CBT_MIN_RECENT_CIRCUITS 3
4706 #define CBT_MAX_RECENT_CIRCUITS 1000
4709 * Maximum count of timeouts that finish the first hop in the past
4710 * RECENT_CIRCUITS before calculating a new timeout.
4712 * This tells us whether to abandon timeout history and set
4713 * the timeout back to whatever circuit_build_times_get_initial_timeout()
4714 * gives us.
4716 #define CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT (CBT_DEFAULT_RECENT_CIRCUITS*9/10)
4717 #define CBT_MIN_MAX_RECENT_TIMEOUT_COUNT 3
4718 #define CBT_MAX_MAX_RECENT_TIMEOUT_COUNT 10000
4720 /** Minimum circuits before estimating a timeout */
4721 #define CBT_DEFAULT_MIN_CIRCUITS_TO_OBSERVE 100
4722 #define CBT_MIN_MIN_CIRCUITS_TO_OBSERVE 1
4723 #define CBT_MAX_MIN_CIRCUITS_TO_OBSERVE 10000
4725 /** Cutoff percentile on the CDF for our timeout estimation. */
4726 #define CBT_DEFAULT_QUANTILE_CUTOFF 80
4727 #define CBT_MIN_QUANTILE_CUTOFF 10
4728 #define CBT_MAX_QUANTILE_CUTOFF 99
4729 double circuit_build_times_quantile_cutoff(void);
4731 /** How often in seconds should we build a test circuit */
4732 #define CBT_DEFAULT_TEST_FREQUENCY 60
4733 #define CBT_MIN_TEST_FREQUENCY 1
4734 #define CBT_MAX_TEST_FREQUENCY INT32_MAX
4736 /** Lowest allowable value for CircuitBuildTimeout in milliseconds */
4737 #define CBT_DEFAULT_TIMEOUT_MIN_VALUE (1500)
4738 #define CBT_MIN_TIMEOUT_MIN_VALUE 500
4739 #define CBT_MAX_TIMEOUT_MIN_VALUE INT32_MAX
4741 /** Initial circuit build timeout in milliseconds */
4742 #define CBT_DEFAULT_TIMEOUT_INITIAL_VALUE (60*1000)
4743 #define CBT_MIN_TIMEOUT_INITIAL_VALUE CBT_MIN_TIMEOUT_MIN_VALUE
4744 #define CBT_MAX_TIMEOUT_INITIAL_VALUE INT32_MAX
4745 int32_t circuit_build_times_initial_timeout(void);
4747 #if CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT < CBT_MIN_MAX_RECENT_TIMEOUT_COUNT
4748 #error "RECENT_CIRCUITS is set too low."
4749 #endif
4751 /** Information about the state of our local network connection */
4752 typedef struct {
4753 /** The timestamp we last completed a TLS handshake or received a cell */
4754 time_t network_last_live;
4755 /** If the network is not live, how many timeouts has this caused? */
4756 int nonlive_timeouts;
4757 /** Circular array of circuits that have made it to the first hop. Slot is
4758 * 1 if circuit timed out, 0 if circuit succeeded */
4759 int8_t *timeouts_after_firsthop;
4760 /** Number of elements allocated for the above array */
4761 int num_recent_circs;
4762 /** Index into circular array. */
4763 int after_firsthop_idx;
4764 } network_liveness_t;
4766 typedef struct circuit_build_times_s circuit_build_times_t;
4768 /********************************* config.c ***************************/
4770 /** An error from options_trial_assign() or options_init_from_string(). */
4771 typedef enum setopt_err_t {
4772 SETOPT_OK = 0,
4773 SETOPT_ERR_MISC = -1,
4774 SETOPT_ERR_PARSE = -2,
4775 SETOPT_ERR_TRANSITION = -3,
4776 SETOPT_ERR_SETTING = -4,
4777 } setopt_err_t;
4779 /********************************* connection_edge.c *************************/
4781 /** Enumerates possible origins of a client-side address mapping. */
4782 typedef enum {
4783 /** We're remapping this address because the controller told us to. */
4784 ADDRMAPSRC_CONTROLLER,
4785 /** We're remapping this address because of an AutomapHostsOnResolve
4786 * configuration. */
4787 ADDRMAPSRC_AUTOMAP,
4788 /** We're remapping this address because our configuration (via torrc, the
4789 * command line, or a SETCONF command) told us to. */
4790 ADDRMAPSRC_TORRC,
4791 /** We're remapping this address because we have TrackHostExit configured,
4792 * and we want to remember to use the same exit next time. */
4793 ADDRMAPSRC_TRACKEXIT,
4794 /** We're remapping this address because we got a DNS resolution from a
4795 * Tor server that told us what its value was. */
4796 ADDRMAPSRC_DNS,
4798 /** No remapping has occurred. This isn't a possible value for an
4799 * addrmap_entry_t; it's used as a null value when we need to answer "Why
4800 * did this remapping happen." */
4801 ADDRMAPSRC_NONE
4802 } addressmap_entry_source_t;
4803 #define addressmap_entry_source_bitfield_t ENUM_BF(addressmap_entry_source_t)
4805 /********************************* control.c ***************************/
4807 /** Used to indicate the type of a circuit event passed to the controller.
4808 * The various types are defined in control-spec.txt */
4809 typedef enum circuit_status_event_t {
4810 CIRC_EVENT_LAUNCHED = 0,
4811 CIRC_EVENT_BUILT = 1,
4812 CIRC_EVENT_EXTENDED = 2,
4813 CIRC_EVENT_FAILED = 3,
4814 CIRC_EVENT_CLOSED = 4,
4815 } circuit_status_event_t;
4817 /** Used to indicate the type of a CIRC_MINOR event passed to the controller.
4818 * The various types are defined in control-spec.txt . */
4819 typedef enum circuit_status_minor_event_t {
4820 CIRC_MINOR_EVENT_PURPOSE_CHANGED,
4821 CIRC_MINOR_EVENT_CANNIBALIZED,
4822 } circuit_status_minor_event_t;
4824 /** Used to indicate the type of a stream event passed to the controller.
4825 * The various types are defined in control-spec.txt */
4826 typedef enum stream_status_event_t {
4827 STREAM_EVENT_SENT_CONNECT = 0,
4828 STREAM_EVENT_SENT_RESOLVE = 1,
4829 STREAM_EVENT_SUCCEEDED = 2,
4830 STREAM_EVENT_FAILED = 3,
4831 STREAM_EVENT_CLOSED = 4,
4832 STREAM_EVENT_NEW = 5,
4833 STREAM_EVENT_NEW_RESOLVE = 6,
4834 STREAM_EVENT_FAILED_RETRIABLE = 7,
4835 STREAM_EVENT_REMAP = 8
4836 } stream_status_event_t;
4838 /** Used to indicate the type of an OR connection event passed to the
4839 * controller. The various types are defined in control-spec.txt */
4840 typedef enum or_conn_status_event_t {
4841 OR_CONN_EVENT_LAUNCHED = 0,
4842 OR_CONN_EVENT_CONNECTED = 1,
4843 OR_CONN_EVENT_FAILED = 2,
4844 OR_CONN_EVENT_CLOSED = 3,
4845 OR_CONN_EVENT_NEW = 4,
4846 } or_conn_status_event_t;
4848 /** Used to indicate the type of a buildtime event */
4849 typedef enum buildtimeout_set_event_t {
4850 BUILDTIMEOUT_SET_EVENT_COMPUTED = 0,
4851 BUILDTIMEOUT_SET_EVENT_RESET = 1,
4852 BUILDTIMEOUT_SET_EVENT_SUSPENDED = 2,
4853 BUILDTIMEOUT_SET_EVENT_DISCARD = 3,
4854 BUILDTIMEOUT_SET_EVENT_RESUME = 4
4855 } buildtimeout_set_event_t;
4857 /** Execute the statement <b>stmt</b>, which may log events concerning the
4858 * connection <b>conn</b>. To prevent infinite loops, disable log messages
4859 * being sent to controllers if <b>conn</b> is a control connection.
4861 * Stmt must not contain any return or goto statements.
4863 #define CONN_LOG_PROTECT(conn, stmt) \
4864 STMT_BEGIN \
4865 int _log_conn_is_control; \
4866 tor_assert(conn); \
4867 _log_conn_is_control = (conn->type == CONN_TYPE_CONTROL); \
4868 if (_log_conn_is_control) \
4869 disable_control_logging(); \
4870 STMT_BEGIN stmt; STMT_END; \
4871 if (_log_conn_is_control) \
4872 enable_control_logging(); \
4873 STMT_END
4875 /** Enum describing various stages of bootstrapping, for use with controller
4876 * bootstrap status events. The values range from 0 to 100. */
4877 typedef enum {
4878 BOOTSTRAP_STATUS_UNDEF=-1,
4879 BOOTSTRAP_STATUS_STARTING=0,
4880 BOOTSTRAP_STATUS_CONN_DIR=5,
4881 BOOTSTRAP_STATUS_HANDSHAKE=-2,
4882 BOOTSTRAP_STATUS_HANDSHAKE_DIR=10,
4883 BOOTSTRAP_STATUS_ONEHOP_CREATE=15,
4884 BOOTSTRAP_STATUS_REQUESTING_STATUS=20,
4885 BOOTSTRAP_STATUS_LOADING_STATUS=25,
4886 BOOTSTRAP_STATUS_LOADING_KEYS=40,
4887 BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS=45,
4888 BOOTSTRAP_STATUS_LOADING_DESCRIPTORS=50,
4889 BOOTSTRAP_STATUS_CONN_OR=80,
4890 BOOTSTRAP_STATUS_HANDSHAKE_OR=85,
4891 BOOTSTRAP_STATUS_CIRCUIT_CREATE=90,
4892 BOOTSTRAP_STATUS_DONE=100
4893 } bootstrap_status_t;
4895 /********************************* directory.c ***************************/
4897 /** A pair of digests created by dir_split_resource_info_fingerprint_pairs() */
4898 typedef struct {
4899 char first[DIGEST_LEN];
4900 char second[DIGEST_LEN];
4901 } fp_pair_t;
4903 /********************************* dirserv.c ***************************/
4905 /** An enum to describe what format we're generating a routerstatus line in.
4907 typedef enum {
4908 /** For use in a v2 opinion */
4909 NS_V2,
4910 /** For use in a consensus networkstatus document (ns flavor) */
4911 NS_V3_CONSENSUS,
4912 /** For use in a vote networkstatus document */
4913 NS_V3_VOTE,
4914 /** For passing to the controlport in response to a GETINFO request */
4915 NS_CONTROL_PORT,
4916 /** For use in a consensus networkstatus document (microdesc flavor) */
4917 NS_V3_CONSENSUS_MICRODESC
4918 } routerstatus_format_type_t;
4920 #ifdef DIRSERV_PRIVATE
4921 typedef struct measured_bw_line_t {
4922 char node_id[DIGEST_LEN];
4923 char node_hex[MAX_HEX_NICKNAME_LEN+1];
4924 long int bw_kb;
4925 } measured_bw_line_t;
4927 #endif
4929 /********************************* dirvote.c ************************/
4931 /** Describes the schedule by which votes should be generated. */
4932 typedef struct vote_timing_t {
4933 /** Length in seconds between one consensus becoming valid and the next
4934 * becoming valid. */
4935 int vote_interval;
4936 /** For how many intervals is a consensus valid? */
4937 int n_intervals_valid;
4938 /** Time in seconds allowed to propagate votes */
4939 int vote_delay;
4940 /** Time in seconds allowed to propagate signatures */
4941 int dist_delay;
4942 } vote_timing_t;
4944 /********************************* geoip.c **************************/
4946 /** Indicates an action that we might be noting geoip statistics on.
4947 * Note that if we're noticing CONNECT, we're a bridge, and if we're noticing
4948 * the others, we're not.
4950 typedef enum {
4951 /** We've noticed a connection as a bridge relay or entry guard. */
4952 GEOIP_CLIENT_CONNECT = 0,
4953 /** We've served a networkstatus consensus as a directory server. */
4954 GEOIP_CLIENT_NETWORKSTATUS = 1,
4955 } geoip_client_action_t;
4956 /** Indicates either a positive reply or a reason for rejectng a network
4957 * status request that will be included in geoip statistics. */
4958 typedef enum {
4959 /** Request is answered successfully. */
4960 GEOIP_SUCCESS = 0,
4961 /** V3 network status is not signed by a sufficient number of requested
4962 * authorities. */
4963 GEOIP_REJECT_NOT_ENOUGH_SIGS = 1,
4964 /** Requested network status object is unavailable. */
4965 GEOIP_REJECT_UNAVAILABLE = 2,
4966 /** Requested network status not found. */
4967 GEOIP_REJECT_NOT_FOUND = 3,
4968 /** Network status has not been modified since If-Modified-Since time. */
4969 GEOIP_REJECT_NOT_MODIFIED = 4,
4970 /** Directory is busy. */
4971 GEOIP_REJECT_BUSY = 5,
4972 } geoip_ns_response_t;
4973 #define GEOIP_NS_RESPONSE_NUM 6
4975 /** Directory requests that we are measuring can be either direct or
4976 * tunneled. */
4977 typedef enum {
4978 DIRREQ_DIRECT = 0,
4979 DIRREQ_TUNNELED = 1,
4980 } dirreq_type_t;
4982 /** Possible states for either direct or tunneled directory requests that
4983 * are relevant for determining network status download times. */
4984 typedef enum {
4985 /** Found that the client requests a network status; applies to both
4986 * direct and tunneled requests; initial state of a request that we are
4987 * measuring. */
4988 DIRREQ_IS_FOR_NETWORK_STATUS = 0,
4989 /** Finished writing a network status to the directory connection;
4990 * applies to both direct and tunneled requests; completes a direct
4991 * request. */
4992 DIRREQ_FLUSHING_DIR_CONN_FINISHED = 1,
4993 /** END cell sent to circuit that initiated a tunneled request. */
4994 DIRREQ_END_CELL_SENT = 2,
4995 /** Flushed last cell from queue of the circuit that initiated a
4996 * tunneled request to the outbuf of the OR connection. */
4997 DIRREQ_CIRC_QUEUE_FLUSHED = 3,
4998 /** Flushed last byte from buffer of the channel belonging to the
4999 * circuit that initiated a tunneled request; completes a tunneled
5000 * request. */
5001 DIRREQ_CHANNEL_BUFFER_FLUSHED = 4
5002 } dirreq_state_t;
5004 #define WRITE_STATS_INTERVAL (24*60*60)
5006 /********************************* microdesc.c *************************/
5008 typedef struct microdesc_cache_t microdesc_cache_t;
5010 /********************************* networkstatus.c *********************/
5012 /** Possible statuses of a version of Tor, given opinions from the directory
5013 * servers. */
5014 typedef enum version_status_t {
5015 VS_RECOMMENDED=0, /**< This version is listed as recommended. */
5016 VS_OLD=1, /**< This version is older than any recommended version. */
5017 VS_NEW=2, /**< This version is newer than any recommended version. */
5018 VS_NEW_IN_SERIES=3, /**< This version is newer than any recommended version
5019 * in its series, but later recommended versions exist.
5021 VS_UNRECOMMENDED=4, /**< This version is not recommended (general case). */
5022 VS_EMPTY=5, /**< The version list was empty; no agreed-on versions. */
5023 VS_UNKNOWN, /**< We have no idea. */
5024 } version_status_t;
5026 /********************************* policies.c ************************/
5028 /** Outcome of applying an address policy to an address. */
5029 typedef enum {
5030 /** The address was accepted */
5031 ADDR_POLICY_ACCEPTED=0,
5032 /** The address was rejected */
5033 ADDR_POLICY_REJECTED=-1,
5034 /** Part of the address was unknown, but as far as we can tell, it was
5035 * accepted. */
5036 ADDR_POLICY_PROBABLY_ACCEPTED=1,
5037 /** Part of the address was unknown, but as far as we can tell, it was
5038 * rejected. */
5039 ADDR_POLICY_PROBABLY_REJECTED=2,
5040 } addr_policy_result_t;
5042 /********************************* rephist.c ***************************/
5044 /** Possible public/private key operations in Tor: used to keep track of where
5045 * we're spending our time. */
5046 typedef enum {
5047 SIGN_DIR, SIGN_RTR,
5048 VERIFY_DIR, VERIFY_RTR,
5049 ENC_ONIONSKIN, DEC_ONIONSKIN,
5050 TLS_HANDSHAKE_C, TLS_HANDSHAKE_S,
5051 REND_CLIENT, REND_MID, REND_SERVER,
5052 } pk_op_t;
5054 /********************************* rendcommon.c ***************************/
5056 /** Hidden-service side configuration of client authorization. */
5057 typedef struct rend_authorized_client_t {
5058 char *client_name;
5059 uint8_t descriptor_cookie[REND_DESC_COOKIE_LEN];
5060 crypto_pk_t *client_key;
5061 } rend_authorized_client_t;
5063 /** ASCII-encoded v2 hidden service descriptor. */
5064 typedef struct rend_encoded_v2_service_descriptor_t {
5065 char desc_id[DIGEST_LEN]; /**< Descriptor ID. */
5066 char *desc_str; /**< Descriptor string. */
5067 } rend_encoded_v2_service_descriptor_t;
5069 /** The maximum number of non-circuit-build-timeout failures a hidden
5070 * service client will tolerate while trying to build a circuit to an
5071 * introduction point. See also rend_intro_point_t.unreachable_count. */
5072 #define MAX_INTRO_POINT_REACHABILITY_FAILURES 5
5074 /** The minimum and maximum number of distinct INTRODUCE2 cells which a
5075 * hidden service's introduction point will receive before it begins to
5076 * expire. */
5077 #define INTRO_POINT_MIN_LIFETIME_INTRODUCTIONS 16384
5078 /* Double the minimum value so the interval is [min, min * 2]. */
5079 #define INTRO_POINT_MAX_LIFETIME_INTRODUCTIONS \
5080 (INTRO_POINT_MIN_LIFETIME_INTRODUCTIONS * 2)
5082 /** The minimum number of seconds that an introduction point will last
5083 * before expiring due to old age. (If it receives
5084 * INTRO_POINT_LIFETIME_INTRODUCTIONS INTRODUCE2 cells, it may expire
5085 * sooner.)
5087 * XXX Should this be configurable? */
5088 #define INTRO_POINT_LIFETIME_MIN_SECONDS (18*60*60)
5089 /** The maximum number of seconds that an introduction point will last
5090 * before expiring due to old age.
5092 * XXX Should this be configurable? */
5093 #define INTRO_POINT_LIFETIME_MAX_SECONDS (24*60*60)
5095 /** The maximum number of circuit creation retry we do to an intro point
5096 * before giving up. We try to reuse intro point that fails during their
5097 * lifetime so this is a hard limit on the amount of time we do that. */
5098 #define MAX_INTRO_POINT_CIRCUIT_RETRIES 3
5100 /** Introduction point information. Used both in rend_service_t (on
5101 * the service side) and in rend_service_descriptor_t (on both the
5102 * client and service side). */
5103 typedef struct rend_intro_point_t {
5104 extend_info_t *extend_info; /**< Extend info for connecting to this
5105 * introduction point via a multi-hop path. */
5106 crypto_pk_t *intro_key; /**< Introduction key that replaces the service
5107 * key, if this descriptor is V2. */
5109 /** (Client side only) Flag indicating that a timeout has occurred
5110 * after sending an INTRODUCE cell to this intro point. After a
5111 * timeout, an intro point should not be tried again during the same
5112 * hidden service connection attempt, but it may be tried again
5113 * during a future connection attempt. */
5114 unsigned int timed_out : 1;
5116 /** (Client side only) The number of times we have failed to build a
5117 * circuit to this intro point for some reason other than our
5118 * circuit-build timeout. See also MAX_INTRO_POINT_REACHABILITY_FAILURES. */
5119 unsigned int unreachable_count : 3;
5121 /** (Service side only) Flag indicating that this intro point was
5122 * included in the last HS descriptor we generated. */
5123 unsigned int listed_in_last_desc : 1;
5125 /** (Service side only) A replay cache recording the RSA-encrypted parts
5126 * of INTRODUCE2 cells this intro point's circuit has received. This is
5127 * used to prevent replay attacks. */
5128 replaycache_t *accepted_intro_rsa_parts;
5130 /** (Service side only) Count of INTRODUCE2 cells accepted from this
5131 * intro point.
5133 int accepted_introduce2_count;
5135 /** (Service side only) Number of maximum INTRODUCE2 cells that this IP
5136 * will accept. This is a random value between
5137 * INTRO_POINT_MIN_LIFETIME_INTRODUCTIONS and
5138 * INTRO_POINT_MAX_LIFETIME_INTRODUCTIONS. */
5139 int max_introductions;
5141 /** (Service side only) The time at which this intro point was first
5142 * published, or -1 if this intro point has not yet been
5143 * published. */
5144 time_t time_published;
5146 /** (Service side only) The time at which this intro point should
5147 * (start to) expire, or -1 if we haven't decided when this intro
5148 * point should expire. */
5149 time_t time_to_expire;
5151 /** (Service side only) The amount of circuit creation we've made to this
5152 * intro point. This is incremented every time we do a circuit relaunch on
5153 * this object which is triggered when the circuit dies but the node is
5154 * still in the consensus. After MAX_INTRO_POINT_CIRCUIT_RETRIES, we give
5155 * up on it. */
5156 unsigned int circuit_retries;
5158 /** (Service side only) Set if this intro point has an established circuit
5159 * and unset if it doesn't. */
5160 unsigned int circuit_established:1;
5161 } rend_intro_point_t;
5163 #define REND_PROTOCOL_VERSION_BITMASK_WIDTH 16
5165 /** Information used to connect to a hidden service. Used on both the
5166 * service side and the client side. */
5167 typedef struct rend_service_descriptor_t {
5168 crypto_pk_t *pk; /**< This service's public key. */
5169 int version; /**< Version of the descriptor format: 0 or 2. */
5170 time_t timestamp; /**< Time when the descriptor was generated. */
5171 /** Bitmask: which introduce/rendezvous protocols are supported?
5172 * (We allow bits '0', '1', '2' and '3' to be set.) */
5173 unsigned protocols : REND_PROTOCOL_VERSION_BITMASK_WIDTH;
5174 /** List of the service's introduction points. Elements are removed if
5175 * introduction attempts fail. */
5176 smartlist_t *intro_nodes;
5177 /** Has descriptor been uploaded to all hidden service directories? */
5178 int all_uploads_performed;
5179 /** List of hidden service directories to which an upload request for
5180 * this descriptor could be sent. Smartlist exists only when at least one
5181 * of the previous upload requests failed (otherwise it's not important
5182 * to know which uploads succeeded and which not). */
5183 smartlist_t *successful_uploads;
5184 } rend_service_descriptor_t;
5186 /********************************* routerlist.c ***************************/
5188 /** Represents information about a single trusted or fallback directory
5189 * server. */
5190 typedef struct dir_server_t {
5191 char *description;
5192 char *nickname;
5193 char *address; /**< Hostname. */
5194 /* XX/teor - why do we duplicate the address and port fields here and in
5195 * fake_status? Surely we could just use fake_status (#17867). */
5196 tor_addr_t ipv6_addr; /**< IPv6 address if present; AF_UNSPEC if not */
5197 uint32_t addr; /**< IPv4 address. */
5198 uint16_t dir_port; /**< Directory port. */
5199 uint16_t or_port; /**< OR port: Used for tunneling connections. */
5200 uint16_t ipv6_orport; /**< OR port corresponding to ipv6_addr. */
5201 double weight; /** Weight used when selecting this node at random */
5202 char digest[DIGEST_LEN]; /**< Digest of identity key. */
5203 char v3_identity_digest[DIGEST_LEN]; /**< Digest of v3 (authority only,
5204 * high-security) identity key. */
5206 unsigned int is_running:1; /**< True iff we think this server is running. */
5207 unsigned int is_authority:1; /**< True iff this is a directory authority
5208 * of some kind. */
5210 /** True iff this server has accepted the most recent server descriptor
5211 * we tried to upload to it. */
5212 unsigned int has_accepted_serverdesc:1;
5214 /** What kind of authority is this? (Bitfield.) */
5215 dirinfo_type_t type;
5217 time_t addr_current_at; /**< When was the document that we derived the
5218 * address information from published? */
5220 routerstatus_t fake_status; /**< Used when we need to pass this trusted
5221 * dir_server_t to directory_initiate_command_*
5222 * as a routerstatus_t. Not updated by the
5223 * router-status management code!
5225 } dir_server_t;
5227 #define RELAY_REQUIRED_MIN_BANDWIDTH (75*1024)
5228 #define BRIDGE_REQUIRED_MIN_BANDWIDTH (50*1024)
5230 #define ROUTER_MAX_DECLARED_BANDWIDTH INT32_MAX
5232 /* Flags for pick_directory_server() and pick_trusteddirserver(). */
5233 /** Flag to indicate that we should not automatically be willing to use
5234 * ourself to answer a directory request.
5235 * Passed to router_pick_directory_server (et al).*/
5236 #define PDS_ALLOW_SELF (1<<0)
5237 /** Flag to indicate that if no servers seem to be up, we should mark all
5238 * directory servers as up and try again.
5239 * Passed to router_pick_directory_server (et al).*/
5240 #define PDS_RETRY_IF_NO_SERVERS (1<<1)
5241 /** Flag to indicate that we should not exclude directory servers that
5242 * our ReachableAddress settings would exclude. This usually means that
5243 * we're going to connect to the server over Tor, and so we don't need to
5244 * worry about our firewall telling us we can't.
5245 * Passed to router_pick_directory_server (et al).*/
5246 #define PDS_IGNORE_FASCISTFIREWALL (1<<2)
5247 /** Flag to indicate that we should not use any directory authority to which
5248 * we have an existing directory connection for downloading server descriptors
5249 * or extrainfo documents.
5251 * Passed to router_pick_directory_server (et al)
5253 #define PDS_NO_EXISTING_SERVERDESC_FETCH (1<<3)
5254 /** Flag to indicate that we should not use any directory authority to which
5255 * we have an existing directory connection for downloading microdescs.
5257 * Passed to router_pick_directory_server (et al)
5259 #define PDS_NO_EXISTING_MICRODESC_FETCH (1<<4)
5261 /** This node is to be chosen as a directory guard, so don't choose any
5262 * node that's currently a guard. */
5263 #define PDS_FOR_GUARD (1<<5)
5265 /** Possible ways to weight routers when choosing one randomly. See
5266 * routerlist_sl_choose_by_bandwidth() for more information.*/
5267 typedef enum bandwidth_weight_rule_t {
5268 NO_WEIGHTING, WEIGHT_FOR_EXIT, WEIGHT_FOR_MID, WEIGHT_FOR_GUARD,
5269 WEIGHT_FOR_DIR
5270 } bandwidth_weight_rule_t;
5272 /** Flags to be passed to control router_choose_random_node() to indicate what
5273 * kind of nodes to pick according to what algorithm. */
5274 typedef enum {
5275 CRN_NEED_UPTIME = 1<<0,
5276 CRN_NEED_CAPACITY = 1<<1,
5277 CRN_NEED_GUARD = 1<<2,
5278 CRN_ALLOW_INVALID = 1<<3,
5279 /* XXXX not used, apparently. */
5280 CRN_WEIGHT_AS_EXIT = 1<<5,
5281 CRN_NEED_DESC = 1<<6,
5282 /* On clients, only provide nodes that satisfy ClientPreferIPv6OR */
5283 CRN_PREF_ADDR = 1<<7,
5284 /* On clients, only provide nodes that we can connect to directly, based on
5285 * our firewall rules */
5286 CRN_DIRECT_CONN = 1<<8
5287 } router_crn_flags_t;
5289 /** Return value for router_add_to_routerlist() and dirserv_add_descriptor() */
5290 typedef enum was_router_added_t {
5291 /* Router was added successfully. */
5292 ROUTER_ADDED_SUCCESSFULLY = 1,
5293 /* Router descriptor was added with warnings to submitter. */
5294 ROUTER_ADDED_NOTIFY_GENERATOR = 0,
5295 /* Extrainfo document was rejected because no corresponding router
5296 * descriptor was found OR router descriptor was rejected because
5297 * it was incompatible with its extrainfo document. */
5298 ROUTER_BAD_EI = -1,
5299 /* Router descriptor was rejected because it is already known. */
5300 ROUTER_IS_ALREADY_KNOWN = -2,
5301 /* General purpose router was rejected, because it was not listed
5302 * in consensus. */
5303 ROUTER_NOT_IN_CONSENSUS = -3,
5304 /* Router was neither in directory consensus nor in any of
5305 * networkstatus documents. Caching it to access later.
5306 * (Applies to fetched descriptors only.) */
5307 ROUTER_NOT_IN_CONSENSUS_OR_NETWORKSTATUS = -4,
5308 /* Router was rejected by directory authority. */
5309 ROUTER_AUTHDIR_REJECTS = -5,
5310 /* Bridge descriptor was rejected because such bridge was not one
5311 * of the bridges we have listed in our configuration. */
5312 ROUTER_WAS_NOT_WANTED = -6,
5313 /* Router descriptor was rejected because it was older than
5314 * OLD_ROUTER_DESC_MAX_AGE. */
5315 ROUTER_WAS_TOO_OLD = -7, /* note contrast with 'NOT_NEW' */
5316 /* DOCDOC */
5317 ROUTER_CERTS_EXPIRED = -8
5318 } was_router_added_t;
5320 /********************************* routerparse.c ************************/
5322 #define MAX_STATUS_TAG_LEN 32
5323 /** Structure to hold parsed Tor versions. This is a little messier
5324 * than we would like it to be, because we changed version schemes with 0.1.0.
5326 * See version-spec.txt for the whole business.
5328 typedef struct tor_version_t {
5329 int major;
5330 int minor;
5331 int micro;
5332 /** Release status. For version in the post-0.1 format, this is always
5333 * VER_RELEASE. */
5334 enum { VER_PRE=0, VER_RC=1, VER_RELEASE=2, } status;
5335 int patchlevel;
5336 char status_tag[MAX_STATUS_TAG_LEN];
5337 int svn_revision;
5339 int git_tag_len;
5340 char git_tag[DIGEST_LEN];
5341 } tor_version_t;
5343 #endif