Bug 6572: Use timestamp_created for liveness sanity checks.
[tor.git] / src / or / or.h
blob4e19140b4bb76c5e34bed96dc81b9371e890120b
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-2013, 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 __COVERITY__
18 /* If we're building for a static analysis, turn on all the off-by-default
19 * features. */
20 #ifndef INSTRUMENT_DOWNLOADS
21 #define INSTRUMENT_DOWNLOADS 1
22 #endif
23 #endif
25 #ifdef _WIN32
26 #ifndef _WIN32_WINNT
27 #define _WIN32_WINNT 0x0501
28 #endif
29 #define WIN32_LEAN_AND_MEAN
30 #endif
32 #ifdef HAVE_UNISTD_H
33 #include <unistd.h>
34 #endif
35 #ifdef HAVE_SIGNAL_H
36 #include <signal.h>
37 #endif
38 #ifdef HAVE_NETDB_H
39 #include <netdb.h>
40 #endif
41 #ifdef HAVE_SYS_PARAM_H
42 #include <sys/param.h> /* FreeBSD needs this to know what version it is */
43 #endif
44 #include "torint.h"
45 #ifdef HAVE_SYS_WAIT_H
46 #include <sys/wait.h>
47 #endif
48 #ifdef HAVE_SYS_FCNTL_H
49 #include <sys/fcntl.h>
50 #endif
51 #ifdef HAVE_FCNTL_H
52 #include <fcntl.h>
53 #endif
54 #ifdef HAVE_SYS_IOCTL_H
55 #include <sys/ioctl.h>
56 #endif
57 #ifdef HAVE_SYS_UN_H
58 #include <sys/un.h>
59 #endif
60 #ifdef HAVE_SYS_STAT_H
61 #include <sys/stat.h>
62 #endif
63 #ifdef HAVE_NETINET_IN_H
64 #include <netinet/in.h>
65 #endif
66 #ifdef HAVE_ARPA_INET_H
67 #include <arpa/inet.h>
68 #endif
69 #ifdef HAVE_ERRNO_H
70 #include <errno.h>
71 #endif
72 #ifdef HAVE_ASSERT_H
73 #include <assert.h>
74 #endif
75 #ifdef HAVE_TIME_H
76 #include <time.h>
77 #endif
79 #ifdef _WIN32
80 #include <io.h>
81 #include <process.h>
82 #include <direct.h>
83 #include <windows.h>
84 #endif
86 #ifdef USE_BUFFEREVENTS
87 #include <event2/bufferevent.h>
88 #include <event2/buffer.h>
89 #include <event2/util.h>
90 #endif
92 #include "crypto.h"
93 #include "tortls.h"
94 #include "../common/torlog.h"
95 #include "container.h"
96 #include "torgzip.h"
97 #include "address.h"
98 #include "compat_libevent.h"
99 #include "ht.h"
100 #include "replaycache.h"
101 #include "crypto_curve25519.h"
103 /* These signals are defined to help handle_control_signal work.
105 #ifndef SIGHUP
106 #define SIGHUP 1
107 #endif
108 #ifndef SIGINT
109 #define SIGINT 2
110 #endif
111 #ifndef SIGUSR1
112 #define SIGUSR1 10
113 #endif
114 #ifndef SIGUSR2
115 #define SIGUSR2 12
116 #endif
117 #ifndef SIGTERM
118 #define SIGTERM 15
119 #endif
120 /* Controller signals start at a high number so we don't
121 * conflict with system-defined signals. */
122 #define SIGNEWNYM 129
123 #define SIGCLEARDNSCACHE 130
125 #if (SIZEOF_CELL_T != 0)
126 /* On Irix, stdlib.h defines a cell_t type, so we need to make sure
127 * that our stuff always calls cell_t something different. */
128 #define cell_t tor_cell_t
129 #endif
131 #ifdef ENABLE_TOR2WEB_MODE
132 #define NON_ANONYMOUS_MODE_ENABLED 1
133 #endif
135 /** Length of longest allowable configured nickname. */
136 #define MAX_NICKNAME_LEN 19
137 /** Length of a router identity encoded as a hexadecimal digest, plus
138 * possible dollar sign. */
139 #define MAX_HEX_NICKNAME_LEN (HEX_DIGEST_LEN+1)
140 /** Maximum length of verbose router identifier: dollar sign, hex ID digest,
141 * equal sign or tilde, nickname. */
142 #define MAX_VERBOSE_NICKNAME_LEN (1+HEX_DIGEST_LEN+1+MAX_NICKNAME_LEN)
144 /** Maximum size, in bytes, for resized buffers. */
145 #define MAX_BUF_SIZE ((1<<24)-1) /* 16MB-1 */
146 /** Maximum size, in bytes, for any directory object that we've downloaded. */
147 #define MAX_DIR_DL_SIZE MAX_BUF_SIZE
149 /** For HTTP parsing: Maximum number of bytes we'll accept in the headers
150 * of an HTTP request or response. */
151 #define MAX_HEADERS_SIZE 50000
152 /** Maximum size, in bytes, for any directory object that we're accepting
153 * as an upload. */
154 #define MAX_DIR_UL_SIZE MAX_BUF_SIZE
156 /** Maximum size, in bytes, of a single router descriptor uploaded to us
157 * as a directory authority. Caches and clients fetch whatever descriptors
158 * the authorities tell them to fetch, and don't care about size. */
159 #define MAX_DESCRIPTOR_UPLOAD_SIZE 20000
161 /** Maximum size of a single extrainfo document, as above. */
162 #define MAX_EXTRAINFO_UPLOAD_SIZE 50000
164 /** How long do we keep DNS cache entries before purging them (regardless of
165 * their TTL)? */
166 #define MAX_DNS_ENTRY_AGE (30*60)
167 /** How long do we cache/tell clients to cache DNS records when no TTL is
168 * known? */
169 #define DEFAULT_DNS_TTL (30*60)
170 /** How long can a TTL be before we stop believing it? */
171 #define MAX_DNS_TTL (3*60*60)
172 /** How small can a TTL be before we stop believing it? Provides rudimentary
173 * pinning. */
174 #define MIN_DNS_TTL 60
176 /** How often do we rotate onion keys? */
177 #define MIN_ONION_KEY_LIFETIME (7*24*60*60)
178 /** How often do we rotate TLS contexts? */
179 #define MAX_SSL_KEY_LIFETIME_INTERNAL (2*60*60)
181 /** How old do we allow a router to get before removing it
182 * from the router list? In seconds. */
183 #define ROUTER_MAX_AGE (60*60*48)
184 /** How old can a router get before we (as a server) will no longer
185 * consider it live? In seconds. */
186 #define ROUTER_MAX_AGE_TO_PUBLISH (60*60*24)
187 /** How old do we let a saved descriptor get before force-removing it? */
188 #define OLD_ROUTER_DESC_MAX_AGE (60*60*24*5)
190 /** Possible rules for generating circuit IDs on an OR connection. */
191 typedef enum {
192 CIRC_ID_TYPE_LOWER=0, /**< Pick from 0..1<<15-1. */
193 CIRC_ID_TYPE_HIGHER=1, /**< Pick from 1<<15..1<<16-1. */
194 /** The other side of a connection is an OP: never create circuits to it,
195 * and let it use any circuit ID it wants. */
196 CIRC_ID_TYPE_NEITHER=2
197 } circ_id_type_t;
199 #define CONN_TYPE_MIN_ 3
200 /** Type for sockets listening for OR connections. */
201 #define CONN_TYPE_OR_LISTENER 3
202 /** A bidirectional TLS connection transmitting a sequence of cells.
203 * May be from an OR to an OR, or from an OP to an OR. */
204 #define CONN_TYPE_OR 4
205 /** A TCP connection from an onion router to a stream's destination. */
206 #define CONN_TYPE_EXIT 5
207 /** Type for sockets listening for SOCKS connections. */
208 #define CONN_TYPE_AP_LISTENER 6
209 /** A SOCKS proxy connection from the user application to the onion
210 * proxy. */
211 #define CONN_TYPE_AP 7
212 /** Type for sockets listening for HTTP connections to the directory server. */
213 #define CONN_TYPE_DIR_LISTENER 8
214 /** Type for HTTP connections to the directory server. */
215 #define CONN_TYPE_DIR 9
216 /** Connection from the main process to a CPU worker process. */
217 #define CONN_TYPE_CPUWORKER 10
218 /** Type for listening for connections from user interface process. */
219 #define CONN_TYPE_CONTROL_LISTENER 11
220 /** Type for connections from user interface process. */
221 #define CONN_TYPE_CONTROL 12
222 /** Type for sockets listening for transparent connections redirected by pf or
223 * netfilter. */
224 #define CONN_TYPE_AP_TRANS_LISTENER 13
225 /** Type for sockets listening for transparent connections redirected by
226 * natd. */
227 #define CONN_TYPE_AP_NATD_LISTENER 14
228 /** Type for sockets listening for DNS requests. */
229 #define CONN_TYPE_AP_DNS_LISTENER 15
230 #define CONN_TYPE_MAX_ 15
231 /* !!!! If CONN_TYPE_MAX_ is ever over 15, we must grow the type field in
232 * connection_t. */
234 /* Proxy client types */
235 #define PROXY_NONE 0
236 #define PROXY_CONNECT 1
237 #define PROXY_SOCKS4 2
238 #define PROXY_SOCKS5 3
239 /* !!!! If there is ever a PROXY_* type over 2, we must grow the proxy_type
240 * field in or_connection_t */
241 /* pluggable transports proxy type */
242 #define PROXY_PLUGGABLE 4
244 /* Proxy client handshake states */
245 /* We use a proxy but we haven't even connected to it yet. */
246 #define PROXY_INFANT 1
247 /* We use an HTTP proxy and we've sent the CONNECT command. */
248 #define PROXY_HTTPS_WANT_CONNECT_OK 2
249 /* We use a SOCKS4 proxy and we've sent the CONNECT command. */
250 #define PROXY_SOCKS4_WANT_CONNECT_OK 3
251 /* We use a SOCKS5 proxy and we try to negotiate without
252 any authentication . */
253 #define PROXY_SOCKS5_WANT_AUTH_METHOD_NONE 4
254 /* We use a SOCKS5 proxy and we try to negotiate with
255 Username/Password authentication . */
256 #define PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929 5
257 /* We use a SOCKS5 proxy and we just sent our credentials. */
258 #define PROXY_SOCKS5_WANT_AUTH_RFC1929_OK 6
259 /* We use a SOCKS5 proxy and we just sent our CONNECT command. */
260 #define PROXY_SOCKS5_WANT_CONNECT_OK 7
261 /* We use a proxy and we CONNECTed successfully!. */
262 #define PROXY_CONNECTED 8
264 /** True iff <b>x</b> is an edge connection. */
265 #define CONN_IS_EDGE(x) \
266 ((x)->type == CONN_TYPE_EXIT || (x)->type == CONN_TYPE_AP)
268 /** State for any listener connection. */
269 #define LISTENER_STATE_READY 0
271 #define CPUWORKER_STATE_MIN_ 1
272 /** State for a connection to a cpuworker process that's idle. */
273 #define CPUWORKER_STATE_IDLE 1
274 /** State for a connection to a cpuworker process that's processing a
275 * handshake. */
276 #define CPUWORKER_STATE_BUSY_ONION 2
277 #define CPUWORKER_STATE_MAX_ 2
279 #define CPUWORKER_TASK_ONION CPUWORKER_STATE_BUSY_ONION
280 #define CPUWORKER_TASK_SHUTDOWN 255
282 #define OR_CONN_STATE_MIN_ 1
283 /** State for a connection to an OR: waiting for connect() to finish. */
284 #define OR_CONN_STATE_CONNECTING 1
285 /** State for a connection to an OR: waiting for proxy handshake to complete */
286 #define OR_CONN_STATE_PROXY_HANDSHAKING 2
287 /** State for an OR connection client: SSL is handshaking, not done
288 * yet. */
289 #define OR_CONN_STATE_TLS_HANDSHAKING 3
290 /** State for a connection to an OR: We're doing a second SSL handshake for
291 * renegotiation purposes. (V2 handshake only.) */
292 #define OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING 4
293 /** State for a connection at an OR: We're waiting for the client to
294 * renegotiate (to indicate a v2 handshake) or send a versions cell (to
295 * indicate a v3 handshake) */
296 #define OR_CONN_STATE_TLS_SERVER_RENEGOTIATING 5
297 /** State for an OR connection: We're done with our SSL handshake, we've done
298 * renegotiation, but we haven't yet negotiated link protocol versions and
299 * sent a netinfo cell. */
300 #define OR_CONN_STATE_OR_HANDSHAKING_V2 6
301 /** State for an OR connection: We're done with our SSL handshake, but we
302 * haven't yet negotiated link protocol versions, done a V3 handshake, and
303 * sent a netinfo cell. */
304 #define OR_CONN_STATE_OR_HANDSHAKING_V3 7
305 /** State for an OR connection: Ready to send/receive cells. */
306 #define OR_CONN_STATE_OPEN 8
307 #define OR_CONN_STATE_MAX_ 8
309 #define EXIT_CONN_STATE_MIN_ 1
310 /** State for an exit connection: waiting for response from DNS farm. */
311 #define EXIT_CONN_STATE_RESOLVING 1
312 /** State for an exit connection: waiting for connect() to finish. */
313 #define EXIT_CONN_STATE_CONNECTING 2
314 /** State for an exit connection: open and ready to transmit data. */
315 #define EXIT_CONN_STATE_OPEN 3
316 /** State for an exit connection: waiting to be removed. */
317 #define EXIT_CONN_STATE_RESOLVEFAILED 4
318 #define EXIT_CONN_STATE_MAX_ 4
320 /* The AP state values must be disjoint from the EXIT state values. */
321 #define AP_CONN_STATE_MIN_ 5
322 /** State for a SOCKS connection: waiting for SOCKS request. */
323 #define AP_CONN_STATE_SOCKS_WAIT 5
324 /** State for a SOCKS connection: got a y.onion URL; waiting to receive
325 * rendezvous descriptor. */
326 #define AP_CONN_STATE_RENDDESC_WAIT 6
327 /** The controller will attach this connection to a circuit; it isn't our
328 * job to do so. */
329 #define AP_CONN_STATE_CONTROLLER_WAIT 7
330 /** State for a SOCKS connection: waiting for a completed circuit. */
331 #define AP_CONN_STATE_CIRCUIT_WAIT 8
332 /** State for a SOCKS connection: sent BEGIN, waiting for CONNECTED. */
333 #define AP_CONN_STATE_CONNECT_WAIT 9
334 /** State for a SOCKS connection: sent RESOLVE, waiting for RESOLVED. */
335 #define AP_CONN_STATE_RESOLVE_WAIT 10
336 /** State for a SOCKS connection: ready to send and receive. */
337 #define AP_CONN_STATE_OPEN 11
338 /** State for a transparent natd connection: waiting for original
339 * destination. */
340 #define AP_CONN_STATE_NATD_WAIT 12
341 #define AP_CONN_STATE_MAX_ 12
343 /** True iff the AP_CONN_STATE_* value <b>s</b> means that the corresponding
344 * edge connection is not attached to any circuit. */
345 #define AP_CONN_STATE_IS_UNATTACHED(s) \
346 ((s) <= AP_CONN_STATE_CIRCUIT_WAIT || (s) == AP_CONN_STATE_NATD_WAIT)
348 #define DIR_CONN_STATE_MIN_ 1
349 /** State for connection to directory server: waiting for connect(). */
350 #define DIR_CONN_STATE_CONNECTING 1
351 /** State for connection to directory server: sending HTTP request. */
352 #define DIR_CONN_STATE_CLIENT_SENDING 2
353 /** State for connection to directory server: reading HTTP response. */
354 #define DIR_CONN_STATE_CLIENT_READING 3
355 /** State for connection to directory server: happy and finished. */
356 #define DIR_CONN_STATE_CLIENT_FINISHED 4
357 /** State for connection at directory server: waiting for HTTP request. */
358 #define DIR_CONN_STATE_SERVER_COMMAND_WAIT 5
359 /** State for connection at directory server: sending HTTP response. */
360 #define DIR_CONN_STATE_SERVER_WRITING 6
361 #define DIR_CONN_STATE_MAX_ 6
363 /** True iff the purpose of <b>conn</b> means that it's a server-side
364 * directory connection. */
365 #define DIR_CONN_IS_SERVER(conn) ((conn)->purpose == DIR_PURPOSE_SERVER)
367 #define CONTROL_CONN_STATE_MIN_ 1
368 /** State for a control connection: Authenticated and accepting v1 commands. */
369 #define CONTROL_CONN_STATE_OPEN 1
370 /** State for a control connection: Waiting for authentication; speaking
371 * protocol v1. */
372 #define CONTROL_CONN_STATE_NEEDAUTH 2
373 #define CONTROL_CONN_STATE_MAX_ 2
375 #define DIR_PURPOSE_MIN_ 3
376 /** A connection to a directory server: download a rendezvous
377 * descriptor. */
378 #define DIR_PURPOSE_FETCH_RENDDESC 3
379 /** A connection to a directory server: set after a rendezvous
380 * descriptor is downloaded. */
381 #define DIR_PURPOSE_HAS_FETCHED_RENDDESC 4
382 /** A connection to a directory server: download one or more v2
383 * network-status objects */
384 #define DIR_PURPOSE_FETCH_V2_NETWORKSTATUS 5
385 /** A connection to a directory server: download one or more server
386 * descriptors. */
387 #define DIR_PURPOSE_FETCH_SERVERDESC 6
388 /** A connection to a directory server: download one or more extra-info
389 * documents. */
390 #define DIR_PURPOSE_FETCH_EXTRAINFO 7
391 /** A connection to a directory server: upload a server descriptor. */
392 #define DIR_PURPOSE_UPLOAD_DIR 8
393 /** A connection to a directory server: upload a rendezvous
394 * descriptor. */
395 #define DIR_PURPOSE_UPLOAD_RENDDESC 9
396 /** A connection to a directory server: upload a v3 networkstatus vote. */
397 #define DIR_PURPOSE_UPLOAD_VOTE 10
398 /** A connection to a directory server: upload a v3 consensus signature */
399 #define DIR_PURPOSE_UPLOAD_SIGNATURES 11
400 /** A connection to a directory server: download one or more v3 networkstatus
401 * votes. */
402 #define DIR_PURPOSE_FETCH_STATUS_VOTE 12
403 /** A connection to a directory server: download a v3 detached signatures
404 * object for a consensus. */
405 #define DIR_PURPOSE_FETCH_DETACHED_SIGNATURES 13
406 /** A connection to a directory server: download a v3 networkstatus
407 * consensus. */
408 #define DIR_PURPOSE_FETCH_CONSENSUS 14
409 /** A connection to a directory server: download one or more directory
410 * authority certificates. */
411 #define DIR_PURPOSE_FETCH_CERTIFICATE 15
413 /** Purpose for connection at a directory server. */
414 #define DIR_PURPOSE_SERVER 16
415 /** A connection to a hidden service directory server: upload a v2 rendezvous
416 * descriptor. */
417 #define DIR_PURPOSE_UPLOAD_RENDDESC_V2 17
418 /** A connection to a hidden service directory server: download a v2 rendezvous
419 * descriptor. */
420 #define DIR_PURPOSE_FETCH_RENDDESC_V2 18
421 /** A connection to a directory server: download a microdescriptor. */
422 #define DIR_PURPOSE_FETCH_MICRODESC 19
423 #define DIR_PURPOSE_MAX_ 19
425 /** True iff <b>p</b> is a purpose corresponding to uploading data to a
426 * directory server. */
427 #define DIR_PURPOSE_IS_UPLOAD(p) \
428 ((p)==DIR_PURPOSE_UPLOAD_DIR || \
429 (p)==DIR_PURPOSE_UPLOAD_RENDDESC || \
430 (p)==DIR_PURPOSE_UPLOAD_VOTE || \
431 (p)==DIR_PURPOSE_UPLOAD_SIGNATURES)
433 #define EXIT_PURPOSE_MIN_ 1
434 /** This exit stream wants to do an ordinary connect. */
435 #define EXIT_PURPOSE_CONNECT 1
436 /** This exit stream wants to do a resolve (either normal or reverse). */
437 #define EXIT_PURPOSE_RESOLVE 2
438 #define EXIT_PURPOSE_MAX_ 2
440 /* !!!! If any connection purpose is ever over 31, we must grow the type
441 * field in connection_t. */
443 /** Circuit state: I'm the origin, still haven't done all my handshakes. */
444 #define CIRCUIT_STATE_BUILDING 0
445 /** Circuit state: Waiting to process the onionskin. */
446 #define CIRCUIT_STATE_ONIONSKIN_PENDING 1
447 /** Circuit state: I'd like to deliver a create, but my n_chan is still
448 * connecting. */
449 #define CIRCUIT_STATE_CHAN_WAIT 2
450 /** Circuit state: onionskin(s) processed, ready to send/receive cells. */
451 #define CIRCUIT_STATE_OPEN 3
453 #define CIRCUIT_PURPOSE_MIN_ 1
455 /* these circuits were initiated elsewhere */
456 #define CIRCUIT_PURPOSE_OR_MIN_ 1
457 /** OR-side circuit purpose: normal circuit, at OR. */
458 #define CIRCUIT_PURPOSE_OR 1
459 /** OR-side circuit purpose: At OR, from Bob, waiting for intro from Alices. */
460 #define CIRCUIT_PURPOSE_INTRO_POINT 2
461 /** OR-side circuit purpose: At OR, from Alice, waiting for Bob. */
462 #define CIRCUIT_PURPOSE_REND_POINT_WAITING 3
463 /** OR-side circuit purpose: At OR, both circuits have this purpose. */
464 #define CIRCUIT_PURPOSE_REND_ESTABLISHED 4
465 #define CIRCUIT_PURPOSE_OR_MAX_ 4
467 /* these circuits originate at this node */
469 /* here's how circ client-side purposes work:
470 * normal circuits are C_GENERAL.
471 * circuits that are c_introducing are either on their way to
472 * becoming open, or they are open and waiting for a
473 * suitable rendcirc before they send the intro.
474 * circuits that are c_introduce_ack_wait have sent the intro,
475 * but haven't gotten a response yet.
476 * circuits that are c_establish_rend are either on their way
477 * to becoming open, or they are open and have sent the
478 * establish_rendezvous cell but haven't received an ack.
479 * circuits that are c_rend_ready are open and have received a
480 * rend ack, but haven't heard from bob yet. if they have a
481 * buildstate->pending_final_cpath then they're expecting a
482 * cell from bob, else they're not.
483 * circuits that are c_rend_ready_intro_acked are open, and
484 * some intro circ has sent its intro and received an ack.
485 * circuits that are c_rend_joined are open, have heard from
486 * bob, and are talking to him.
488 /** Client-side circuit purpose: Normal circuit, with cpath. */
489 #define CIRCUIT_PURPOSE_C_GENERAL 5
490 /** Client-side circuit purpose: at Alice, connecting to intro point. */
491 #define CIRCUIT_PURPOSE_C_INTRODUCING 6
492 /** Client-side circuit purpose: at Alice, sent INTRODUCE1 to intro point,
493 * waiting for ACK/NAK. */
494 #define CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT 7
495 /** Client-side circuit purpose: at Alice, introduced and acked, closing. */
496 #define CIRCUIT_PURPOSE_C_INTRODUCE_ACKED 8
497 /** Client-side circuit purpose: at Alice, waiting for ack. */
498 #define CIRCUIT_PURPOSE_C_ESTABLISH_REND 9
499 /** Client-side circuit purpose: at Alice, waiting for Bob. */
500 #define CIRCUIT_PURPOSE_C_REND_READY 10
501 /** Client-side circuit purpose: at Alice, waiting for Bob, INTRODUCE
502 * has been acknowledged. */
503 #define CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED 11
504 /** Client-side circuit purpose: at Alice, rendezvous established. */
505 #define CIRCUIT_PURPOSE_C_REND_JOINED 12
506 /** This circuit is used for build time measurement only */
507 #define CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT 13
508 #define CIRCUIT_PURPOSE_C_MAX_ 13
509 /** Hidden-service-side circuit purpose: at Bob, waiting for introductions. */
510 #define CIRCUIT_PURPOSE_S_ESTABLISH_INTRO 14
511 /** Hidden-service-side circuit purpose: at Bob, successfully established
512 * intro. */
513 #define CIRCUIT_PURPOSE_S_INTRO 15
514 /** Hidden-service-side circuit purpose: at Bob, connecting to rend point. */
515 #define CIRCUIT_PURPOSE_S_CONNECT_REND 16
516 /** Hidden-service-side circuit purpose: at Bob, rendezvous established. */
517 #define CIRCUIT_PURPOSE_S_REND_JOINED 17
518 /** A testing circuit; not meant to be used for actual traffic. */
519 #define CIRCUIT_PURPOSE_TESTING 18
520 /** A controller made this circuit and Tor should not use it. */
521 #define CIRCUIT_PURPOSE_CONTROLLER 19
522 /** This circuit is used for path bias probing only */
523 #define CIRCUIT_PURPOSE_PATH_BIAS_TESTING 20
524 #define CIRCUIT_PURPOSE_MAX_ 20
525 /** A catch-all for unrecognized purposes. Currently we don't expect
526 * to make or see any circuits with this purpose. */
527 #define CIRCUIT_PURPOSE_UNKNOWN 255
529 /** True iff the circuit purpose <b>p</b> is for a circuit that
530 * originated at this node. */
531 #define CIRCUIT_PURPOSE_IS_ORIGIN(p) ((p)>CIRCUIT_PURPOSE_OR_MAX_)
532 /** True iff the circuit purpose <b>p</b> is for a circuit that originated
533 * here to serve as a client. (Hidden services don't count here.) */
534 #define CIRCUIT_PURPOSE_IS_CLIENT(p) \
535 ((p)> CIRCUIT_PURPOSE_OR_MAX_ && \
536 (p)<=CIRCUIT_PURPOSE_C_MAX_)
537 /** True iff the circuit_t <b>c</b> is actually an origin_circuit_t. */
538 #define CIRCUIT_IS_ORIGIN(c) (CIRCUIT_PURPOSE_IS_ORIGIN((c)->purpose))
539 /** True iff the circuit purpose <b>p</b> is for an established rendezvous
540 * circuit. */
541 #define CIRCUIT_PURPOSE_IS_ESTABLISHED_REND(p) \
542 ((p) == CIRCUIT_PURPOSE_C_REND_JOINED || \
543 (p) == CIRCUIT_PURPOSE_S_REND_JOINED)
545 /** How many circuits do we want simultaneously in-progress to handle
546 * a given stream? */
547 #define MIN_CIRCUITS_HANDLING_STREAM 2
549 /* These RELAY_COMMAND constants define values for relay cell commands, and
550 * must match those defined in tor-spec.txt. */
551 #define RELAY_COMMAND_BEGIN 1
552 #define RELAY_COMMAND_DATA 2
553 #define RELAY_COMMAND_END 3
554 #define RELAY_COMMAND_CONNECTED 4
555 #define RELAY_COMMAND_SENDME 5
556 #define RELAY_COMMAND_EXTEND 6
557 #define RELAY_COMMAND_EXTENDED 7
558 #define RELAY_COMMAND_TRUNCATE 8
559 #define RELAY_COMMAND_TRUNCATED 9
560 #define RELAY_COMMAND_DROP 10
561 #define RELAY_COMMAND_RESOLVE 11
562 #define RELAY_COMMAND_RESOLVED 12
563 #define RELAY_COMMAND_BEGIN_DIR 13
564 #define RELAY_COMMAND_EXTEND2 14
565 #define RELAY_COMMAND_EXTENDED2 15
567 #define RELAY_COMMAND_ESTABLISH_INTRO 32
568 #define RELAY_COMMAND_ESTABLISH_RENDEZVOUS 33
569 #define RELAY_COMMAND_INTRODUCE1 34
570 #define RELAY_COMMAND_INTRODUCE2 35
571 #define RELAY_COMMAND_RENDEZVOUS1 36
572 #define RELAY_COMMAND_RENDEZVOUS2 37
573 #define RELAY_COMMAND_INTRO_ESTABLISHED 38
574 #define RELAY_COMMAND_RENDEZVOUS_ESTABLISHED 39
575 #define RELAY_COMMAND_INTRODUCE_ACK 40
577 /* Reasons why an OR connection is closed. */
578 #define END_OR_CONN_REASON_DONE 1
579 #define END_OR_CONN_REASON_REFUSED 2 /* connection refused */
580 #define END_OR_CONN_REASON_OR_IDENTITY 3
581 #define END_OR_CONN_REASON_CONNRESET 4 /* connection reset by peer */
582 #define END_OR_CONN_REASON_TIMEOUT 5
583 #define END_OR_CONN_REASON_NO_ROUTE 6 /* no route to host/net */
584 #define END_OR_CONN_REASON_IO_ERROR 7 /* read/write error */
585 #define END_OR_CONN_REASON_RESOURCE_LIMIT 8 /* sockets, buffers, etc */
586 #define END_OR_CONN_REASON_MISC 9
588 /* Reasons why we (or a remote OR) might close a stream. See tor-spec.txt for
589 * documentation of these. The values must match. */
590 #define END_STREAM_REASON_MISC 1
591 #define END_STREAM_REASON_RESOLVEFAILED 2
592 #define END_STREAM_REASON_CONNECTREFUSED 3
593 #define END_STREAM_REASON_EXITPOLICY 4
594 #define END_STREAM_REASON_DESTROY 5
595 #define END_STREAM_REASON_DONE 6
596 #define END_STREAM_REASON_TIMEOUT 7
597 #define END_STREAM_REASON_NOROUTE 8
598 #define END_STREAM_REASON_HIBERNATING 9
599 #define END_STREAM_REASON_INTERNAL 10
600 #define END_STREAM_REASON_RESOURCELIMIT 11
601 #define END_STREAM_REASON_CONNRESET 12
602 #define END_STREAM_REASON_TORPROTOCOL 13
603 #define END_STREAM_REASON_NOTDIRECTORY 14
604 #define END_STREAM_REASON_ENTRYPOLICY 15
606 /* These high-numbered end reasons are not part of the official spec,
607 * and are not intended to be put in relay end cells. They are here
608 * to be more informative when sending back socks replies to the
609 * application. */
610 /* XXXX 256 is no longer used; feel free to reuse it. */
611 /** We were unable to attach the connection to any circuit at all. */
612 /* XXXX the ways we use this one don't make a lot of sense. */
613 #define END_STREAM_REASON_CANT_ATTACH 257
614 /** We can't connect to any directories at all, so we killed our streams
615 * before they can time out. */
616 #define END_STREAM_REASON_NET_UNREACHABLE 258
617 /** This is a SOCKS connection, and the client used (or misused) the SOCKS
618 * protocol in a way we couldn't handle. */
619 #define END_STREAM_REASON_SOCKSPROTOCOL 259
620 /** This is a transparent proxy connection, but we can't extract the original
621 * target address:port. */
622 #define END_STREAM_REASON_CANT_FETCH_ORIG_DEST 260
623 /** This is a connection on the NATD port, and the destination IP:Port was
624 * either ill-formed or out-of-range. */
625 #define END_STREAM_REASON_INVALID_NATD_DEST 261
626 /** The target address is in a private network (like 127.0.0.1 or 10.0.0.1);
627 * you don't want to do that over a randomly chosen exit */
628 #define END_STREAM_REASON_PRIVATE_ADDR 262
630 /** Bitwise-and this value with endreason to mask out all flags. */
631 #define END_STREAM_REASON_MASK 511
633 /** Bitwise-or this with the argument to control_event_stream_status
634 * to indicate that the reason came from an END cell. */
635 #define END_STREAM_REASON_FLAG_REMOTE 512
636 /** Bitwise-or this with the argument to control_event_stream_status
637 * to indicate that we already sent a CLOSED stream event. */
638 #define END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED 1024
639 /** Bitwise-or this with endreason to indicate that we already sent
640 * a socks reply, and no further reply needs to be sent from
641 * connection_mark_unattached_ap(). */
642 #define END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED 2048
644 /** Reason for remapping an AP connection's address: we have a cached
645 * answer. */
646 #define REMAP_STREAM_SOURCE_CACHE 1
647 /** Reason for remapping an AP connection's address: the exit node told us an
648 * answer. */
649 #define REMAP_STREAM_SOURCE_EXIT 2
651 /* 'type' values to use in RESOLVED cells. Specified in tor-spec.txt. */
652 #define RESOLVED_TYPE_HOSTNAME 0
653 #define RESOLVED_TYPE_IPV4 4
654 #define RESOLVED_TYPE_IPV6 6
655 #define RESOLVED_TYPE_ERROR_TRANSIENT 0xF0
656 #define RESOLVED_TYPE_ERROR 0xF1
658 /* Negative reasons are internal: we never send them in a DESTROY or TRUNCATE
659 * call; they only go to the controller for tracking */
660 /** Our post-timeout circuit time measurement period expired.
661 * We must give up now */
662 #define END_CIRC_REASON_MEASUREMENT_EXPIRED -3
664 /** We couldn't build a path for this circuit. */
665 #define END_CIRC_REASON_NOPATH -2
666 /** Catch-all "other" reason for closing origin circuits. */
667 #define END_CIRC_AT_ORIGIN -1
669 /* Reasons why we (or a remote OR) might close a circuit. See tor-spec.txt for
670 * documentation of these. */
671 #define END_CIRC_REASON_MIN_ 0
672 #define END_CIRC_REASON_NONE 0
673 #define END_CIRC_REASON_TORPROTOCOL 1
674 #define END_CIRC_REASON_INTERNAL 2
675 #define END_CIRC_REASON_REQUESTED 3
676 #define END_CIRC_REASON_HIBERNATING 4
677 #define END_CIRC_REASON_RESOURCELIMIT 5
678 #define END_CIRC_REASON_CONNECTFAILED 6
679 #define END_CIRC_REASON_OR_IDENTITY 7
680 #define END_CIRC_REASON_CHANNEL_CLOSED 8
681 #define END_CIRC_REASON_FINISHED 9
682 #define END_CIRC_REASON_TIMEOUT 10
683 #define END_CIRC_REASON_DESTROYED 11
684 #define END_CIRC_REASON_NOSUCHSERVICE 12
685 #define END_CIRC_REASON_MAX_ 12
687 /** Bitwise-OR this with the argument to circuit_mark_for_close() or
688 * control_event_circuit_status() to indicate that the reason was
689 * passed through from a destroy or truncate cell. */
690 #define END_CIRC_REASON_FLAG_REMOTE 512
692 /** Length of 'y' portion of 'y.onion' URL. */
693 #define REND_SERVICE_ID_LEN_BASE32 16
695 /** Length of 'y.onion' including '.onion' URL. */
696 #define REND_SERVICE_ADDRESS_LEN (16+1+5)
698 /** Length of a binary-encoded rendezvous service ID. */
699 #define REND_SERVICE_ID_LEN 10
701 /** Time period for which a v2 descriptor will be valid. */
702 #define REND_TIME_PERIOD_V2_DESC_VALIDITY (24*60*60)
704 /** Time period within which two sets of v2 descriptors will be uploaded in
705 * parallel. */
706 #define REND_TIME_PERIOD_OVERLAPPING_V2_DESCS (60*60)
708 /** Number of non-consecutive replicas (i.e. distributed somewhere
709 * in the ring) for a descriptor. */
710 #define REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS 2
712 /** Number of consecutive replicas for a descriptor. */
713 #define REND_NUMBER_OF_CONSECUTIVE_REPLICAS 3
715 /** Length of v2 descriptor ID (32 base32 chars = 160 bits). */
716 #define REND_DESC_ID_V2_LEN_BASE32 32
718 /** Length of the base32-encoded secret ID part of versioned hidden service
719 * descriptors. */
720 #define REND_SECRET_ID_PART_LEN_BASE32 32
722 /** Length of the base32-encoded hash of an introduction point's
723 * identity key. */
724 #define REND_INTRO_POINT_ID_LEN_BASE32 32
726 /** Length of the descriptor cookie that is used for client authorization
727 * to hidden services. */
728 #define REND_DESC_COOKIE_LEN 16
730 /** Length of the base64-encoded descriptor cookie that is used for
731 * exchanging client authorization between hidden service and client. */
732 #define REND_DESC_COOKIE_LEN_BASE64 22
734 /** Length of client identifier in encrypted introduction points for hidden
735 * service authorization type 'basic'. */
736 #define REND_BASIC_AUTH_CLIENT_ID_LEN 4
738 /** Multiple of the number of clients to which the real number of clients
739 * is padded with fake clients for hidden service authorization type
740 * 'basic'. */
741 #define REND_BASIC_AUTH_CLIENT_MULTIPLE 16
743 /** Length of client entry consisting of client identifier and encrypted
744 * session key for hidden service authorization type 'basic'. */
745 #define REND_BASIC_AUTH_CLIENT_ENTRY_LEN (REND_BASIC_AUTH_CLIENT_ID_LEN \
746 + CIPHER_KEY_LEN)
748 /** Maximum size of v2 hidden service descriptors. */
749 #define REND_DESC_MAX_SIZE (20 * 1024)
751 /** Legal characters for use in authorized client names for a hidden
752 * service. */
753 #define REND_LEGAL_CLIENTNAME_CHARACTERS \
754 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-_"
756 /** Maximum length of authorized client names for a hidden service. */
757 #define REND_CLIENTNAME_MAX_LEN 16
759 /** Length of the rendezvous cookie that is used to connect circuits at the
760 * rendezvous point. */
761 #define REND_COOKIE_LEN DIGEST_LEN
763 /** Client authorization type that a hidden service performs. */
764 typedef enum rend_auth_type_t {
765 REND_NO_AUTH = 0,
766 REND_BASIC_AUTH = 1,
767 REND_STEALTH_AUTH = 2,
768 } rend_auth_type_t;
770 /** Client-side configuration of authorization for a hidden service. */
771 typedef struct rend_service_authorization_t {
772 char descriptor_cookie[REND_DESC_COOKIE_LEN];
773 char onion_address[REND_SERVICE_ADDRESS_LEN+1];
774 rend_auth_type_t auth_type;
775 } rend_service_authorization_t;
777 /** Client- and server-side data that is used for hidden service connection
778 * establishment. Not all fields contain data depending on where this struct
779 * is used. */
780 typedef struct rend_data_t {
781 /** Onion address (without the .onion part) that a client requests. */
782 char onion_address[REND_SERVICE_ID_LEN_BASE32+1];
784 /** (Optional) descriptor cookie that is used by a client. */
785 char descriptor_cookie[REND_DESC_COOKIE_LEN];
787 /** Authorization type for accessing a service used by a client. */
788 rend_auth_type_t auth_type;
790 /** Hash of the hidden service's PK used by a service. */
791 char rend_pk_digest[DIGEST_LEN];
793 /** Rendezvous cookie used by both, client and service. */
794 char rend_cookie[REND_COOKIE_LEN];
795 } rend_data_t;
797 /** Time interval for tracking replays of DH public keys received in
798 * INTRODUCE2 cells. Used only to avoid launching multiple
799 * simultaneous attempts to connect to the same rendezvous point. */
800 #define REND_REPLAY_TIME_INTERVAL (5 * 60)
802 /** Used to indicate which way a cell is going on a circuit. */
803 typedef enum {
804 CELL_DIRECTION_IN=1, /**< The cell is moving towards the origin. */
805 CELL_DIRECTION_OUT=2, /**< The cell is moving away from the origin. */
806 } cell_direction_t;
808 /** Initial value for both sides of a circuit transmission window when the
809 * circuit is initialized. Measured in cells. */
810 #define CIRCWINDOW_START 1000
811 #define CIRCWINDOW_START_MIN 100
812 #define CIRCWINDOW_START_MAX 1000
813 /** Amount to increment a circuit window when we get a circuit SENDME. */
814 #define CIRCWINDOW_INCREMENT 100
815 /** Initial value on both sides of a stream transmission window when the
816 * stream is initialized. Measured in cells. */
817 #define STREAMWINDOW_START 500
818 /** Amount to increment a stream window when we get a stream SENDME. */
819 #define STREAMWINDOW_INCREMENT 50
821 /* Cell commands. These values are defined in tor-spec.txt. */
822 #define CELL_PADDING 0
823 #define CELL_CREATE 1
824 #define CELL_CREATED 2
825 #define CELL_RELAY 3
826 #define CELL_DESTROY 4
827 #define CELL_CREATE_FAST 5
828 #define CELL_CREATED_FAST 6
829 #define CELL_VERSIONS 7
830 #define CELL_NETINFO 8
831 #define CELL_RELAY_EARLY 9
832 #define CELL_CREATE2 10
833 #define CELL_CREATED2 11
835 #define CELL_VPADDING 128
836 #define CELL_CERTS 129
837 #define CELL_AUTH_CHALLENGE 130
838 #define CELL_AUTHENTICATE 131
839 #define CELL_AUTHORIZE 132
841 /** How long to test reachability before complaining to the user. */
842 #define TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT (20*60)
844 /** Legal characters in a nickname. */
845 #define LEGAL_NICKNAME_CHARACTERS \
846 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
848 /** Name to use in client TLS certificates if no nickname is given. Once
849 * Tor 0.1.2.x is obsolete, we can remove this. */
850 #define DEFAULT_CLIENT_NICKNAME "client"
852 /** Name chosen by routers that don't configure nicknames */
853 #define UNNAMED_ROUTER_NICKNAME "Unnamed"
855 /** Number of bytes in a SOCKS4 header. */
856 #define SOCKS4_NETWORK_LEN 8
859 * Relay payload:
860 * Relay command [1 byte]
861 * Recognized [2 bytes]
862 * Stream ID [2 bytes]
863 * Partial SHA-1 [4 bytes]
864 * Length [2 bytes]
865 * Relay payload [498 bytes]
868 /** Number of bytes in a cell, minus cell header. */
869 #define CELL_PAYLOAD_SIZE 509
870 /** Number of bytes in a cell transmitted over the network, in the longest
871 * form */
872 #define CELL_MAX_NETWORK_SIZE 514
874 /** Maximum length of a header on a variable-length cell. */
875 #define VAR_CELL_MAX_HEADER_SIZE 7
877 static int get_cell_network_size(int wide_circ_ids);
878 static INLINE int get_cell_network_size(int wide_circ_ids)
880 return wide_circ_ids ? CELL_MAX_NETWORK_SIZE : CELL_MAX_NETWORK_SIZE - 2;
882 static int get_var_cell_header_size(int wide_circ_ids);
883 static INLINE int get_var_cell_header_size(int wide_circ_ids)
885 return wide_circ_ids ? VAR_CELL_MAX_HEADER_SIZE :
886 VAR_CELL_MAX_HEADER_SIZE - 2;
888 static int get_circ_id_size(int wide_circ_ids);
889 static INLINE int get_circ_id_size(int wide_circ_ids)
891 return wide_circ_ids ? 4 : 2;
894 /** Number of bytes in a relay cell's header (not including general cell
895 * header). */
896 #define RELAY_HEADER_SIZE (1+2+2+4+2)
897 /** Largest number of bytes that can fit in a relay cell payload. */
898 #define RELAY_PAYLOAD_SIZE (CELL_PAYLOAD_SIZE-RELAY_HEADER_SIZE)
900 /** Identifies a circuit on an or_connection */
901 typedef uint32_t circid_t;
902 /** Identifies a stream on a circuit */
903 typedef uint16_t streamid_t;
905 /* channel_t typedef; struct channel_s is in channel.h */
907 typedef struct channel_s channel_t;
909 /* channel_listener_t typedef; struct channel_listener_s is in channel.h */
911 typedef struct channel_listener_s channel_listener_t;
913 /* channel states for channel_t */
915 typedef enum {
917 * Closed state - channel is inactive
919 * Permitted transitions from:
920 * - CHANNEL_STATE_CLOSING
921 * Permitted transitions to:
922 * - CHANNEL_STATE_OPENING
924 CHANNEL_STATE_CLOSED = 0,
926 * Opening state - channel is trying to connect
928 * Permitted transitions from:
929 * - CHANNEL_STATE_CLOSED
930 * Permitted transitions to:
931 * - CHANNEL_STATE_CLOSING
932 * - CHANNEL_STATE_ERROR
933 * - CHANNEL_STATE_OPEN
935 CHANNEL_STATE_OPENING,
937 * Open state - channel is active and ready for use
939 * Permitted transitions from:
940 * - CHANNEL_STATE_MAINT
941 * - CHANNEL_STATE_OPENING
942 * Permitted transitions to:
943 * - CHANNEL_STATE_CLOSING
944 * - CHANNEL_STATE_ERROR
945 * - CHANNEL_STATE_MAINT
947 CHANNEL_STATE_OPEN,
949 * Maintenance state - channel is temporarily offline for subclass specific
950 * maintenance activities such as TLS renegotiation.
952 * Permitted transitions from:
953 * - CHANNEL_STATE_OPEN
954 * Permitted transitions to:
955 * - CHANNEL_STATE_CLOSING
956 * - CHANNEL_STATE_ERROR
957 * - CHANNEL_STATE_OPEN
959 CHANNEL_STATE_MAINT,
961 * Closing state - channel is shutting down
963 * Permitted transitions from:
964 * - CHANNEL_STATE_MAINT
965 * - CHANNEL_STATE_OPEN
966 * Permitted transitions to:
967 * - CHANNEL_STATE_CLOSED,
968 * - CHANNEL_STATE_ERROR
970 CHANNEL_STATE_CLOSING,
972 * Error state - channel has experienced a permanent error
974 * Permitted transitions from:
975 * - CHANNEL_STATE_CLOSING
976 * - CHANNEL_STATE_MAINT
977 * - CHANNEL_STATE_OPENING
978 * - CHANNEL_STATE_OPEN
979 * Permitted transitions to:
980 * - None
982 CHANNEL_STATE_ERROR,
984 * Placeholder for maximum state value
986 CHANNEL_STATE_LAST
987 } channel_state_t;
989 /* channel listener states for channel_listener_t */
991 typedef enum {
993 * Closed state - channel listener is inactive
995 * Permitted transitions from:
996 * - CHANNEL_LISTENER_STATE_CLOSING
997 * Permitted transitions to:
998 * - CHANNEL_LISTENER_STATE_LISTENING
1000 CHANNEL_LISTENER_STATE_CLOSED = 0,
1002 * Listening state - channel listener is listening for incoming
1003 * connections
1005 * Permitted transitions from:
1006 * - CHANNEL_LISTENER_STATE_CLOSED
1007 * Permitted transitions to:
1008 * - CHANNEL_LISTENER_STATE_CLOSING
1009 * - CHANNEL_LISTENER_STATE_ERROR
1011 CHANNEL_LISTENER_STATE_LISTENING,
1013 * Closing state - channel listener is shutting down
1015 * Permitted transitions from:
1016 * - CHANNEL_LISTENER_STATE_LISTENING
1017 * Permitted transitions to:
1018 * - CHANNEL_LISTENER_STATE_CLOSED,
1019 * - CHANNEL_LISTENER_STATE_ERROR
1021 CHANNEL_LISTENER_STATE_CLOSING,
1023 * Error state - channel listener has experienced a permanent error
1025 * Permitted transitions from:
1026 * - CHANNEL_STATE_CLOSING
1027 * - CHANNEL_STATE_LISTENING
1028 * Permitted transitions to:
1029 * - None
1031 CHANNEL_LISTENER_STATE_ERROR,
1033 * Placeholder for maximum state value
1035 CHANNEL_LISTENER_STATE_LAST
1036 } channel_listener_state_t;
1038 /* TLS channel stuff */
1040 typedef struct channel_tls_s channel_tls_t;
1042 /* circuitmux_t typedef; struct circuitmux_s is in circuitmux.h */
1044 typedef struct circuitmux_s circuitmux_t;
1046 /** Parsed onion routing cell. All communication between nodes
1047 * is via cells. */
1048 typedef struct cell_t {
1049 circid_t circ_id; /**< Circuit which received the cell. */
1050 uint8_t command; /**< Type of the cell: one of CELL_PADDING, CELL_CREATE,
1051 * CELL_DESTROY, etc */
1052 uint8_t payload[CELL_PAYLOAD_SIZE]; /**< Cell body. */
1053 } cell_t;
1055 /** Parsed variable-length onion routing cell. */
1056 typedef struct var_cell_t {
1057 /** Type of the cell: CELL_VERSIONS, etc. */
1058 uint8_t command;
1059 /** Circuit thich received the cell */
1060 circid_t circ_id;
1061 /** Number of bytes actually stored in <b>payload</b> */
1062 uint16_t payload_len;
1063 /** Payload of this cell */
1064 uint8_t payload[FLEXIBLE_ARRAY_MEMBER];
1065 } var_cell_t;
1067 /** A cell as packed for writing to the network. */
1068 typedef struct packed_cell_t {
1069 struct packed_cell_t *next; /**< Next cell queued on this circuit. */
1070 char body[CELL_MAX_NETWORK_SIZE]; /**< Cell as packed for network. */
1071 } packed_cell_t;
1073 /** Number of cells added to a circuit queue including their insertion
1074 * time on 10 millisecond detail; used for buffer statistics. */
1075 typedef struct insertion_time_elem_t {
1076 struct insertion_time_elem_t *next; /**< Next element in queue. */
1077 uint32_t insertion_time; /**< When were cells inserted (in 10 ms steps
1078 * starting at 0:00 of the current day)? */
1079 unsigned counter; /**< How many cells were inserted? */
1080 } insertion_time_elem_t;
1082 /** Queue of insertion times. */
1083 typedef struct insertion_time_queue_t {
1084 struct insertion_time_elem_t *first; /**< First element in queue. */
1085 struct insertion_time_elem_t *last; /**< Last element in queue. */
1086 } insertion_time_queue_t;
1088 /** A queue of cells on a circuit, waiting to be added to the
1089 * or_connection_t's outbuf. */
1090 typedef struct cell_queue_t {
1091 packed_cell_t *head; /**< The first cell, or NULL if the queue is empty. */
1092 packed_cell_t *tail; /**< The last cell, or NULL if the queue is empty. */
1093 int n; /**< The number of cells in the queue. */
1094 insertion_time_queue_t *insertion_times; /**< Insertion times of cells. */
1095 } cell_queue_t;
1097 /** Beginning of a RELAY cell payload. */
1098 typedef struct {
1099 uint8_t command; /**< The end-to-end relay command. */
1100 uint16_t recognized; /**< Used to tell whether cell is for us. */
1101 streamid_t stream_id; /**< Which stream is this cell associated with? */
1102 char integrity[4]; /**< Used to tell whether cell is corrupted. */
1103 uint16_t length; /**< How long is the payload body? */
1104 } relay_header_t;
1106 typedef struct buf_t buf_t;
1107 typedef struct socks_request_t socks_request_t;
1108 #ifdef USE_BUFFEREVENTS
1109 #define generic_buffer_t struct evbuffer
1110 #else
1111 #define generic_buffer_t buf_t
1112 #endif
1114 /* Values for connection_t.magic: used to make sure that downcasts (casts from
1115 * connection_t to foo_connection_t) are safe. */
1116 #define BASE_CONNECTION_MAGIC 0x7C3C304Eu
1117 #define OR_CONNECTION_MAGIC 0x7D31FF03u
1118 #define EDGE_CONNECTION_MAGIC 0xF0374013u
1119 #define ENTRY_CONNECTION_MAGIC 0xbb4a5703
1120 #define DIR_CONNECTION_MAGIC 0x9988ffeeu
1121 #define CONTROL_CONNECTION_MAGIC 0x8abc765du
1122 #define LISTENER_CONNECTION_MAGIC 0x1a1ac741u
1124 /** Description of a connection to another host or process, and associated
1125 * data.
1127 * A connection is named based on what it's connected to -- an "OR
1128 * connection" has a Tor node on the other end, an "exit
1129 * connection" has a website or other server on the other end, and an
1130 * "AP connection" has an application proxy (and thus a user) on the
1131 * other end.
1133 * Every connection has a type and a state. Connections never change
1134 * their type, but can go through many state changes in their lifetime.
1136 * Every connection has two associated input and output buffers.
1137 * Listeners don't use them. For non-listener connections, incoming
1138 * data is appended to conn->inbuf, and outgoing data is taken from
1139 * conn->outbuf. Connections differ primarily in the functions called
1140 * to fill and drain these buffers.
1142 typedef struct connection_t {
1143 uint32_t magic; /**< For memory debugging: must equal one of
1144 * *_CONNECTION_MAGIC. */
1146 uint8_t state; /**< Current state of this connection. */
1147 unsigned int type:4; /**< What kind of connection is this? */
1148 unsigned int purpose:5; /**< Only used for DIR and EXIT types currently. */
1150 /* The next fields are all one-bit booleans. Some are only applicable to
1151 * connection subtypes, but we hold them here anyway, to save space.
1153 unsigned int read_blocked_on_bw:1; /**< Boolean: should we start reading
1154 * again once the bandwidth throttler allows it? */
1155 unsigned int write_blocked_on_bw:1; /**< Boolean: should we start writing
1156 * again once the bandwidth throttler allows
1157 * writes? */
1158 unsigned int hold_open_until_flushed:1; /**< Despite this connection's being
1159 * marked for close, do we flush it
1160 * before closing it? */
1161 unsigned int inbuf_reached_eof:1; /**< Boolean: did read() return 0 on this
1162 * conn? */
1163 /** Set to 1 when we're inside connection_flushed_some to keep us from
1164 * calling connection_handle_write() recursively. */
1165 unsigned int in_flushed_some:1;
1167 /* For linked connections:
1169 unsigned int linked:1; /**< True if there is, or has been, a linked_conn. */
1170 /** True iff we'd like to be notified about read events from the
1171 * linked conn. */
1172 unsigned int reading_from_linked_conn:1;
1173 /** True iff we're willing to write to the linked conn. */
1174 unsigned int writing_to_linked_conn:1;
1175 /** True iff we're currently able to read on the linked conn, and our
1176 * read_event should be made active with libevent. */
1177 unsigned int active_on_link:1;
1178 /** True iff we've called connection_close_immediate() on this linked
1179 * connection. */
1180 unsigned int linked_conn_is_closed:1;
1182 /** CONNECT/SOCKS proxy client handshake state (for outgoing connections). */
1183 unsigned int proxy_state:4;
1185 /** Our socket; set to TOR_INVALID_SOCKET if this connection is closed,
1186 * or has no socket. */
1187 tor_socket_t s;
1188 int conn_array_index; /**< Index into the global connection array. */
1190 struct event *read_event; /**< Libevent event structure. */
1191 struct event *write_event; /**< Libevent event structure. */
1192 buf_t *inbuf; /**< Buffer holding data read over this connection. */
1193 buf_t *outbuf; /**< Buffer holding data to write over this connection. */
1194 size_t outbuf_flushlen; /**< How much data should we try to flush from the
1195 * outbuf? */
1196 time_t timestamp_lastread; /**< When was the last time libevent said we could
1197 * read? */
1198 time_t timestamp_lastwritten; /**< When was the last time libevent said we
1199 * could write? */
1201 #ifdef USE_BUFFEREVENTS
1202 struct bufferevent *bufev; /**< A Libevent buffered IO structure. */
1203 #endif
1205 time_t timestamp_created; /**< When was this connection_t created? */
1207 /* XXXX_IP6 make this IPv6-capable */
1208 int socket_family; /**< Address family of this connection's socket. Usually
1209 * AF_INET, but it can also be AF_UNIX, or in the future
1210 * AF_INET6 */
1211 tor_addr_t addr; /**< IP of the other side of the connection; used to
1212 * identify routers, along with port. */
1213 uint16_t port; /**< If non-zero, port on the other end
1214 * of the connection. */
1215 uint16_t marked_for_close; /**< Should we close this conn on the next
1216 * iteration of the main loop? (If true, holds
1217 * the line number where this connection was
1218 * marked.) */
1219 const char *marked_for_close_file; /**< For debugging: in which file were
1220 * we marked for close? */
1221 char *address; /**< FQDN (or IP) of the guy on the other end.
1222 * strdup into this, because free_connection() frees it. */
1223 /** Another connection that's connected to this one in lieu of a socket. */
1224 struct connection_t *linked_conn;
1226 /** Unique identifier for this connection on this Tor instance. */
1227 uint64_t global_identifier;
1228 } connection_t;
1230 /** Subtype of connection_t; used for a listener socket. */
1231 typedef struct listener_connection_t {
1232 connection_t base_;
1234 /** If the connection is a CONN_TYPE_AP_DNS_LISTENER, this field points
1235 * to the evdns_server_port it uses to listen to and answer connections. */
1236 struct evdns_server_port *dns_server_port;
1238 /** @name Isolation parameters
1240 * For an AP listener, these fields describe how to isolate streams that
1241 * arrive on the listener.
1243 * @{
1245 /** The session group for this listener. */
1246 int session_group;
1247 /** One or more ISO_ flags to describe how to isolate streams. */
1248 uint8_t isolation_flags;
1249 /**@}*/
1251 /** For a SOCKS listeners, these fields describe whether we should
1252 * allow IPv4 and IPv6 addresses from our exit nodes, respectively.
1254 * @{
1256 unsigned int socks_ipv4_traffic : 1;
1257 unsigned int socks_ipv6_traffic : 1;
1258 /** @} */
1259 /** For a socks listener: should we tell the exit that we prefer IPv6
1260 * addresses? */
1261 unsigned int socks_prefer_ipv6 : 1;
1263 /** For a socks listener: should we cache IPv4/IPv6 DNS information that
1264 * exit nodes tell us?
1266 * @{ */
1267 unsigned int cache_ipv4_answers : 1;
1268 unsigned int cache_ipv6_answers : 1;
1269 /** @} */
1270 /** For a socks listeners: if we find an answer in our client-side DNS cache,
1271 * should we use it?
1273 * @{ */
1274 unsigned int use_cached_ipv4_answers : 1;
1275 unsigned int use_cached_ipv6_answers : 1;
1276 /** @} */
1277 /** For socks listeners: When we can automap an address to IPv4 or IPv6,
1278 * do we prefer IPv6? */
1279 unsigned int prefer_ipv6_virtaddr : 1;
1281 } listener_connection_t;
1283 /** Minimum length of the random part of an AUTH_CHALLENGE cell. */
1284 #define OR_AUTH_CHALLENGE_LEN 32
1287 * @name Certificate types for CERTS cells.
1289 * These values are defined by the protocol, and affect how an X509
1290 * certificate in a CERTS cell is interpreted and used.
1292 * @{ */
1293 /** A certificate that authenticates a TLS link key. The subject key
1294 * must match the key used in the TLS handshake; it must be signed by
1295 * the identity key. */
1296 #define OR_CERT_TYPE_TLS_LINK 1
1297 /** A self-signed identity certificate. The subject key must be a
1298 * 1024-bit RSA key. */
1299 #define OR_CERT_TYPE_ID_1024 2
1300 /** A certificate that authenticates a key used in an AUTHENTICATE cell
1301 * in the v3 handshake. The subject key must be a 1024-bit RSA key; it
1302 * must be signed by the identity key */
1303 #define OR_CERT_TYPE_AUTH_1024 3
1304 /**@}*/
1306 /** The one currently supported type of AUTHENTICATE cell. It contains
1307 * a bunch of structures signed with an RSA1024 key. The signed
1308 * structures include a HMAC using negotiated TLS secrets, and a digest
1309 * of all cells sent or received before the AUTHENTICATE cell (including
1310 * the random server-generated AUTH_CHALLENGE cell).
1312 #define AUTHTYPE_RSA_SHA256_TLSSECRET 1
1314 /** The length of the part of the AUTHENTICATE cell body that the client and
1315 * server can generate independently (when using RSA_SHA256_TLSSECRET). It
1316 * contains everything except the client's timestamp, the client's randomly
1317 * generated nonce, and the signature. */
1318 #define V3_AUTH_FIXED_PART_LEN (8+(32*6))
1319 /** The length of the part of the AUTHENTICATE cell body that the client
1320 * signs. */
1321 #define V3_AUTH_BODY_LEN (V3_AUTH_FIXED_PART_LEN + 8 + 16)
1323 /** Stores flags and information related to the portion of a v2/v3 Tor OR
1324 * connection handshake that happens after the TLS handshake is finished.
1326 typedef struct or_handshake_state_t {
1327 /** When was the VERSIONS cell sent on this connection? Used to get
1328 * an estimate of the skew in the returning NETINFO reply. */
1329 time_t sent_versions_at;
1330 /** True iff we originated this connection */
1331 unsigned int started_here : 1;
1332 /** True iff we have received and processed a VERSIONS cell. */
1333 unsigned int received_versions : 1;
1334 /** True iff we have received and processed an AUTH_CHALLENGE cell */
1335 unsigned int received_auth_challenge : 1;
1336 /** True iff we have received and processed a CERTS cell. */
1337 unsigned int received_certs_cell : 1;
1338 /** True iff we have received and processed an AUTHENTICATE cell */
1339 unsigned int received_authenticate : 1;
1341 /* True iff we've received valid authentication to some identity. */
1342 unsigned int authenticated : 1;
1344 /** True iff we should feed outgoing cells into digest_sent and
1345 * digest_received respectively.
1347 * From the server's side of the v3 handshake, we want to capture everything
1348 * from the VERSIONS cell through and including the AUTH_CHALLENGE cell.
1349 * From the client's, we want to capture everything from the VERSIONS cell
1350 * through but *not* including the AUTHENTICATE cell.
1352 * @{ */
1353 unsigned int digest_sent_data : 1;
1354 unsigned int digest_received_data : 1;
1355 /**@}*/
1357 /** Identity digest that we have received and authenticated for our peer
1358 * on this connection. */
1359 uint8_t authenticated_peer_id[DIGEST_LEN];
1361 /** Digests of the cells that we have sent or received as part of a V3
1362 * handshake. Used for making and checking AUTHENTICATE cells.
1364 * @{
1366 crypto_digest_t *digest_sent;
1367 crypto_digest_t *digest_received;
1368 /** @} */
1370 /** Certificates that a connection initiator sent us in a CERTS cell; we're
1371 * holding on to them until we get an AUTHENTICATE cell.
1373 * @{
1375 /** The cert for the key that's supposed to sign the AUTHENTICATE cell */
1376 tor_cert_t *auth_cert;
1377 /** A self-signed identity certificate */
1378 tor_cert_t *id_cert;
1379 /**@}*/
1380 } or_handshake_state_t;
1382 /** Subtype of connection_t for an "OR connection" -- that is, one that speaks
1383 * cells over TLS. */
1384 typedef struct or_connection_t {
1385 connection_t base_;
1387 /** Hash of the public RSA key for the other side's identity key, or zeroes
1388 * if the other side hasn't shown us a valid identity key. */
1389 char identity_digest[DIGEST_LEN];
1390 char *nickname; /**< Nickname of OR on other side (if any). */
1392 tor_tls_t *tls; /**< TLS connection state. */
1393 int tls_error; /**< Last tor_tls error code. */
1394 /** When we last used this conn for any client traffic. If not
1395 * recent, we can rate limit it further. */
1397 /* Channel using this connection */
1398 channel_tls_t *chan;
1400 tor_addr_t real_addr; /**< The actual address that this connection came from
1401 * or went to. The <b>addr</b> field is prone to
1402 * getting overridden by the address from the router
1403 * descriptor matching <b>identity_digest</b>. */
1405 /** Should this connection be used for extending circuits to the server
1406 * matching the <b>identity_digest</b> field? Set to true if we're pretty
1407 * sure we aren't getting MITMed, either because we're connected to an
1408 * address listed in a server descriptor, or because an authenticated
1409 * NETINFO cell listed the address we're connected to as recognized. */
1410 unsigned int is_canonical:1;
1412 /** True iff we have decided that the other end of this connection
1413 * is a client. Connections with this flag set should never be used
1414 * to satisfy an EXTEND request. */
1415 unsigned int is_connection_with_client:1;
1416 /** True iff this is an outgoing connection. */
1417 unsigned int is_outgoing:1;
1418 unsigned int proxy_type:2; /**< One of PROXY_NONE...PROXY_SOCKS5 */
1419 unsigned int wide_circ_ids:1;
1420 uint16_t link_proto; /**< What protocol version are we using? 0 for
1421 * "none negotiated yet." */
1423 or_handshake_state_t *handshake_state; /**< If we are setting this connection
1424 * up, state information to do so. */
1426 time_t timestamp_lastempty; /**< When was the outbuf last completely empty?*/
1427 time_t timestamp_last_added_nonpadding; /** When did we last add a
1428 * non-padding cell to the outbuf? */
1430 /* bandwidth* and *_bucket only used by ORs in OPEN state: */
1431 int bandwidthrate; /**< Bytes/s added to the bucket. (OPEN ORs only.) */
1432 int bandwidthburst; /**< Max bucket size for this conn. (OPEN ORs only.) */
1433 #ifndef USE_BUFFEREVENTS
1434 int read_bucket; /**< When this hits 0, stop receiving. Every second we
1435 * add 'bandwidthrate' to this, capping it at
1436 * bandwidthburst. (OPEN ORs only) */
1437 int write_bucket; /**< When this hits 0, stop writing. Like read_bucket. */
1438 #else
1439 /** A rate-limiting configuration object to determine how this connection
1440 * set its read- and write- limits. */
1441 /* XXXX we could share this among all connections. */
1442 struct ev_token_bucket_cfg *bucket_cfg;
1443 #endif
1445 struct or_connection_t *next_with_same_id; /**< Next connection with same
1446 * identity digest as this one. */
1447 } or_connection_t;
1449 /** Subtype of connection_t for an "edge connection" -- that is, an entry (ap)
1450 * connection, or an exit. */
1451 typedef struct edge_connection_t {
1452 connection_t base_;
1454 struct edge_connection_t *next_stream; /**< Points to the next stream at this
1455 * edge, if any */
1456 int package_window; /**< How many more relay cells can I send into the
1457 * circuit? */
1458 int deliver_window; /**< How many more relay cells can end at me? */
1460 struct circuit_t *on_circuit; /**< The circuit (if any) that this edge
1461 * connection is using. */
1463 /** A pointer to which node in the circ this conn exits at. Set for AP
1464 * connections and for hidden service exit connections. */
1465 struct crypt_path_t *cpath_layer;
1466 /** What rendezvous service are we querying for (if an AP) or providing (if
1467 * an exit)? */
1468 rend_data_t *rend_data;
1470 uint32_t address_ttl; /**< TTL for address-to-addr mapping on exit
1471 * connection. Exit connections only. */
1472 uint32_t begincell_flags; /** Flags sent or received in the BEGIN cell
1473 * for this connection */
1475 streamid_t stream_id; /**< The stream ID used for this edge connection on its
1476 * circuit */
1478 /** The reason why this connection is closing; passed to the controller. */
1479 uint16_t end_reason;
1481 /** Bytes read since last call to control_event_stream_bandwidth_used() */
1482 uint32_t n_read;
1484 /** Bytes written since last call to control_event_stream_bandwidth_used() */
1485 uint32_t n_written;
1487 /** True iff this connection is for a DNS request only. */
1488 unsigned int is_dns_request:1;
1489 /** True iff this connection is for a PTR DNS request. (exit only) */
1490 unsigned int is_reverse_dns_lookup:1;
1492 unsigned int edge_has_sent_end:1; /**< For debugging; only used on edge
1493 * connections. Set once we've set the stream end,
1494 * and check in connection_about_to_close_connection().
1496 /** True iff we've blocked reading until the circuit has fewer queued
1497 * cells. */
1498 unsigned int edge_blocked_on_circ:1;
1500 /** Unique ID for directory requests; this used to be in connection_t, but
1501 * that's going away and being used on channels instead. We still tag
1502 * edge connections with dirreq_id from circuits, so it's copied here. */
1503 uint64_t dirreq_id;
1504 } edge_connection_t;
1506 /** Subtype of edge_connection_t for an "entry connection" -- that is, a SOCKS
1507 * connection, a DNS request, a TransPort connection or a NATD connection */
1508 typedef struct entry_connection_t {
1509 edge_connection_t edge_;
1511 /** Nickname of planned exit node -- used with .exit support. */
1512 char *chosen_exit_name;
1514 socks_request_t *socks_request; /**< SOCKS structure describing request (AP
1515 * only.) */
1517 /* === Isolation related, AP only. === */
1518 /** AP only: based on which factors do we isolate this stream? */
1519 uint8_t isolation_flags;
1520 /** AP only: what session group is this stream in? */
1521 int session_group;
1522 /** AP only: The newnym epoch in which we created this connection. */
1523 unsigned nym_epoch;
1524 /** AP only: The original requested address before we rewrote it. */
1525 char *original_dest_address;
1526 /* Other fields to isolate on already exist. The ClientAddr is addr. The
1527 ClientProtocol is a combination of type and socks_request->
1528 socks_version. SocksAuth is socks_request->username/password.
1529 DestAddr is in socks_request->address. */
1531 /** Number of times we've reassigned this application connection to
1532 * a new circuit. We keep track because the timeout is longer if we've
1533 * already retried several times. */
1534 uint8_t num_socks_retries;
1536 /** For AP connections only: buffer for data that we have sent
1537 * optimistically, which we might need to re-send if we have to
1538 * retry this connection. */
1539 generic_buffer_t *pending_optimistic_data;
1540 /* For AP connections only: buffer for data that we previously sent
1541 * optimistically which we are currently re-sending as we retry this
1542 * connection. */
1543 generic_buffer_t *sending_optimistic_data;
1545 /** If this is a DNSPort connection, this field holds the pending DNS
1546 * request that we're going to try to answer. */
1547 struct evdns_server_request *dns_server_request;
1549 #define NUM_CIRCUITS_LAUNCHED_THRESHOLD 10
1550 /** Number of times we've launched a circuit to handle this stream. If
1551 * it gets too high, that could indicate an inconsistency between our
1552 * "launch a circuit to handle this stream" logic and our "attach our
1553 * stream to one of the available circuits" logic. */
1554 unsigned int num_circuits_launched:4;
1556 /** True iff this stream must attach to a one-hop circuit (e.g. for
1557 * begin_dir). */
1558 unsigned int want_onehop:1;
1559 /** True iff this stream should use a BEGIN_DIR relay command to establish
1560 * itself rather than BEGIN (either via onehop or via a whole circuit). */
1561 unsigned int use_begindir:1;
1563 /** For AP connections only. If 1, and we fail to reach the chosen exit,
1564 * stop requiring it. */
1565 unsigned int chosen_exit_optional:1;
1566 /** For AP connections only. If non-zero, this exit node was picked as
1567 * a result of the TrackHostExit, and the value decrements every time
1568 * we fail to complete a circuit to our chosen exit -- if it reaches
1569 * zero, abandon the associated mapaddress. */
1570 unsigned int chosen_exit_retries:3;
1572 /** True iff this is an AP connection that came from a transparent or
1573 * NATd connection */
1574 unsigned int is_transparent_ap:1;
1576 /** For AP connections only: Set if this connection's target exit node
1577 * allows optimistic data (that is, data sent on this stream before
1578 * the exit has sent a CONNECTED cell) and we have chosen to use it.
1580 unsigned int may_use_optimistic_data : 1;
1582 /** Should we permit IPv4 and IPv6 traffic to use this connection?
1584 * @{ */
1585 unsigned int ipv4_traffic_ok : 1;
1586 unsigned int ipv6_traffic_ok : 1;
1587 /** @} */
1588 /** Should we say we prefer IPv6 traffic? */
1589 unsigned int prefer_ipv6_traffic : 1;
1591 /** For a socks listener: should we cache IPv4/IPv6 DNS information that
1592 * exit nodes tell us?
1594 * @{ */
1595 unsigned int cache_ipv4_answers : 1;
1596 unsigned int cache_ipv6_answers : 1;
1597 /** @} */
1598 /** For a socks listeners: if we find an answer in our client-side DNS cache,
1599 * should we use it?
1601 * @{ */
1602 unsigned int use_cached_ipv4_answers : 1;
1603 unsigned int use_cached_ipv6_answers : 1;
1604 /** @} */
1605 /** For socks listeners: When we can automap an address to IPv4 or IPv6,
1606 * do we prefer IPv6? */
1607 unsigned int prefer_ipv6_virtaddr : 1;
1609 } entry_connection_t;
1611 typedef enum {
1612 DIR_SPOOL_NONE=0, DIR_SPOOL_SERVER_BY_DIGEST, DIR_SPOOL_SERVER_BY_FP,
1613 DIR_SPOOL_EXTRA_BY_DIGEST, DIR_SPOOL_EXTRA_BY_FP,
1614 DIR_SPOOL_CACHED_DIR, DIR_SPOOL_NETWORKSTATUS,
1615 DIR_SPOOL_MICRODESC, /* NOTE: if we add another entry, add another bit. */
1616 } dir_spool_source_t;
1618 /** Subtype of connection_t for an "directory connection" -- that is, an HTTP
1619 * connection to retrieve or serve directory material. */
1620 typedef struct dir_connection_t {
1621 connection_t base_;
1623 /** Which 'resource' did we ask the directory for? This is typically the part
1624 * of the URL string that defines, relative to the directory conn purpose,
1625 * what thing we want. For example, in router descriptor downloads by
1626 * descriptor digest, it contains "d/", then one ore more +-separated
1627 * fingerprints.
1629 char *requested_resource;
1630 unsigned int dirconn_direct:1; /**< Is this dirconn direct, or via Tor? */
1632 /* Used only for server sides of some dir connections, to implement
1633 * "spooling" of directory material to the outbuf. Otherwise, we'd have
1634 * to append everything to the outbuf in one enormous chunk. */
1635 /** What exactly are we spooling right now? */
1636 ENUM_BF(dir_spool_source_t) dir_spool_src : 3;
1638 /** If we're fetching descriptors, what router purpose shall we assign
1639 * to them? */
1640 uint8_t router_purpose;
1641 /** List of fingerprints for networkstatuses or descriptors to be spooled. */
1642 smartlist_t *fingerprint_stack;
1643 /** A cached_dir_t object that we're currently spooling out */
1644 struct cached_dir_t *cached_dir;
1645 /** The current offset into cached_dir. */
1646 off_t cached_dir_offset;
1647 /** The zlib object doing on-the-fly compression for spooled data. */
1648 tor_zlib_state_t *zlib_state;
1650 /** What rendezvous service are we querying for? */
1651 rend_data_t *rend_data;
1653 char identity_digest[DIGEST_LEN]; /**< Hash of the public RSA key for
1654 * the directory server's signing key. */
1656 /** Unique ID for directory requests; this used to be in connection_t, but
1657 * that's going away and being used on channels instead. The dirserver still
1658 * needs this for the incoming side, so it's moved here. */
1659 uint64_t dirreq_id;
1660 } dir_connection_t;
1662 /** Subtype of connection_t for an connection to a controller. */
1663 typedef struct control_connection_t {
1664 connection_t base_;
1666 uint32_t event_mask; /**< Bitfield: which events does this controller
1667 * care about? */
1669 /** True if we have sent a protocolinfo reply on this connection. */
1670 unsigned int have_sent_protocolinfo:1;
1671 /** True if we have received a takeownership command on this
1672 * connection. */
1673 unsigned int is_owning_control_connection:1;
1675 /** If we have sent an AUTHCHALLENGE reply on this connection and
1676 * have not received a successful AUTHENTICATE command, points to
1677 * the value which the client must send to authenticate itself;
1678 * otherwise, NULL. */
1679 char *safecookie_client_hash;
1681 /** Amount of space allocated in incoming_cmd. */
1682 uint32_t incoming_cmd_len;
1683 /** Number of bytes currently stored in incoming_cmd. */
1684 uint32_t incoming_cmd_cur_len;
1685 /** A control command that we're reading from the inbuf, but which has not
1686 * yet arrived completely. */
1687 char *incoming_cmd;
1688 } control_connection_t;
1690 /** Cast a connection_t subtype pointer to a connection_t **/
1691 #define TO_CONN(c) (&(((c)->base_)))
1692 /** Helper macro: Given a pointer to to.base_, of type from*, return &to. */
1693 #define DOWNCAST(to, ptr) ((to*)SUBTYPE_P(ptr, to, base_))
1695 /** Cast a entry_connection_t subtype pointer to a edge_connection_t **/
1696 #define ENTRY_TO_EDGE_CONN(c) (&(((c))->edge_))
1697 /** Cast a entry_connection_t subtype pointer to a connection_t **/
1698 #define ENTRY_TO_CONN(c) (TO_CONN(ENTRY_TO_EDGE_CONN(c)))
1700 /** Convert a connection_t* to an or_connection_t*; assert if the cast is
1701 * invalid. */
1702 static or_connection_t *TO_OR_CONN(connection_t *);
1703 /** Convert a connection_t* to a dir_connection_t*; assert if the cast is
1704 * invalid. */
1705 static dir_connection_t *TO_DIR_CONN(connection_t *);
1706 /** Convert a connection_t* to an edge_connection_t*; assert if the cast is
1707 * invalid. */
1708 static edge_connection_t *TO_EDGE_CONN(connection_t *);
1709 /** Convert a connection_t* to an entry_connection_t*; assert if the cast is
1710 * invalid. */
1711 static entry_connection_t *TO_ENTRY_CONN(connection_t *);
1712 /** Convert a edge_connection_t* to an entry_connection_t*; assert if the cast
1713 * is invalid. */
1714 static entry_connection_t *EDGE_TO_ENTRY_CONN(edge_connection_t *);
1715 /** Convert a connection_t* to an control_connection_t*; assert if the cast is
1716 * invalid. */
1717 static control_connection_t *TO_CONTROL_CONN(connection_t *);
1718 /** Convert a connection_t* to an listener_connection_t*; assert if the cast is
1719 * invalid. */
1720 static listener_connection_t *TO_LISTENER_CONN(connection_t *);
1722 static INLINE or_connection_t *TO_OR_CONN(connection_t *c)
1724 tor_assert(c->magic == OR_CONNECTION_MAGIC);
1725 return DOWNCAST(or_connection_t, c);
1727 static INLINE dir_connection_t *TO_DIR_CONN(connection_t *c)
1729 tor_assert(c->magic == DIR_CONNECTION_MAGIC);
1730 return DOWNCAST(dir_connection_t, c);
1732 static INLINE edge_connection_t *TO_EDGE_CONN(connection_t *c)
1734 tor_assert(c->magic == EDGE_CONNECTION_MAGIC ||
1735 c->magic == ENTRY_CONNECTION_MAGIC);
1736 return DOWNCAST(edge_connection_t, c);
1738 static INLINE entry_connection_t *TO_ENTRY_CONN(connection_t *c)
1740 tor_assert(c->magic == ENTRY_CONNECTION_MAGIC);
1741 return (entry_connection_t*) SUBTYPE_P(c, entry_connection_t, edge_.base_);
1743 static INLINE entry_connection_t *EDGE_TO_ENTRY_CONN(edge_connection_t *c)
1745 tor_assert(c->base_.magic == ENTRY_CONNECTION_MAGIC);
1746 return (entry_connection_t*) SUBTYPE_P(c, entry_connection_t, edge_);
1748 static INLINE control_connection_t *TO_CONTROL_CONN(connection_t *c)
1750 tor_assert(c->magic == CONTROL_CONNECTION_MAGIC);
1751 return DOWNCAST(control_connection_t, c);
1753 static INLINE listener_connection_t *TO_LISTENER_CONN(connection_t *c)
1755 tor_assert(c->magic == LISTENER_CONNECTION_MAGIC);
1756 return DOWNCAST(listener_connection_t, c);
1759 /* Conditional macros to help write code that works whether bufferevents are
1760 disabled or not.
1762 We can't just write:
1763 if (conn->bufev) {
1764 do bufferevent stuff;
1765 } else {
1766 do other stuff;
1768 because the bufferevent stuff won't even compile unless we have a fairly
1769 new version of Libevent. Instead, we say:
1770 IF_HAS_BUFFEREVENT(conn, { do_bufferevent_stuff } );
1772 IF_HAS_BUFFEREVENT(conn, {
1773 do bufferevent stuff;
1774 }) ELSE_IF_NO_BUFFEREVENT {
1775 do non-bufferevent stuff;
1777 If we're compiling with bufferevent support, then the macros expand more or
1778 less to:
1779 if (conn->bufev) {
1780 do_bufferevent_stuff;
1781 } else {
1782 do non-bufferevent stuff;
1784 and if we aren't using bufferevents, they expand more or less to:
1785 { do non-bufferevent stuff; }
1787 #ifdef USE_BUFFEREVENTS
1788 #define HAS_BUFFEREVENT(c) (((c)->bufev) != NULL)
1789 #define IF_HAS_BUFFEREVENT(c, stmt) \
1790 if ((c)->bufev) do { \
1791 stmt ; \
1792 } while (0)
1793 #define ELSE_IF_NO_BUFFEREVENT ; else
1794 #define IF_HAS_NO_BUFFEREVENT(c) \
1795 if (NULL == (c)->bufev)
1796 #else
1797 #define HAS_BUFFEREVENT(c) (0)
1798 #define IF_HAS_BUFFEREVENT(c, stmt) (void)0
1799 #define ELSE_IF_NO_BUFFEREVENT ;
1800 #define IF_HAS_NO_BUFFEREVENT(c) \
1801 if (1)
1802 #endif
1804 /** What action type does an address policy indicate: accept or reject? */
1805 typedef enum {
1806 ADDR_POLICY_ACCEPT=1,
1807 ADDR_POLICY_REJECT=2,
1808 } addr_policy_action_t;
1810 /** A reference-counted address policy rule. */
1811 typedef struct addr_policy_t {
1812 int refcnt; /**< Reference count */
1813 /** What to do when the policy matches.*/
1814 ENUM_BF(addr_policy_action_t) policy_type:2;
1815 unsigned int is_private:1; /**< True iff this is the pseudo-address,
1816 * "private". */
1817 unsigned int is_canonical:1; /**< True iff this policy is the canonical
1818 * copy (stored in a hash table to avoid
1819 * duplication of common policies) */
1820 maskbits_t maskbits; /**< Accept/reject all addresses <b>a</b> such that the
1821 * first <b>maskbits</b> bits of <b>a</b> match
1822 * <b>addr</b>. */
1823 /** Base address to accept or reject.
1825 * Note that wildcards are treated
1826 * differntly depending on address family. An AF_UNSPEC address means
1827 * "All addresses, IPv4 or IPv6." An AF_INET address with maskbits==0 means
1828 * "All IPv4 addresses" and an AF_INET6 address with maskbits == 0 means
1829 * "All IPv6 addresses".
1831 tor_addr_t addr;
1832 uint16_t prt_min; /**< Lowest port number to accept/reject. */
1833 uint16_t prt_max; /**< Highest port number to accept/reject. */
1834 } addr_policy_t;
1836 /** A cached_dir_t represents a cacheable directory object, along with its
1837 * compressed form. */
1838 typedef struct cached_dir_t {
1839 char *dir; /**< Contents of this object, NUL-terminated. */
1840 char *dir_z; /**< Compressed contents of this object. */
1841 size_t dir_len; /**< Length of <b>dir</b> (not counting its NUL). */
1842 size_t dir_z_len; /**< Length of <b>dir_z</b>. */
1843 time_t published; /**< When was this object published. */
1844 digests_t digests; /**< Digests of this object (networkstatus only) */
1845 int refcnt; /**< Reference count for this cached_dir_t. */
1846 } cached_dir_t;
1848 /** Enum used to remember where a signed_descriptor_t is stored and how to
1849 * manage the memory for signed_descriptor_body. */
1850 typedef enum {
1851 /** The descriptor isn't stored on disk at all: the copy in memory is
1852 * canonical; the saved_offset field is meaningless. */
1853 SAVED_NOWHERE=0,
1854 /** The descriptor is stored in the cached_routers file: the
1855 * signed_descriptor_body is meaningless; the signed_descriptor_len and
1856 * saved_offset are used to index into the mmaped cache file. */
1857 SAVED_IN_CACHE,
1858 /** The descriptor is stored in the cached_routers.new file: the
1859 * signed_descriptor_body and saved_offset fields are both set. */
1860 /* FFFF (We could also mmap the file and grow the mmap as needed, or
1861 * lazy-load the descriptor text by using seek and read. We don't, for
1862 * now.)
1864 SAVED_IN_JOURNAL
1865 } saved_location_t;
1867 /** Enumeration: what kind of download schedule are we using for a given
1868 * object? */
1869 typedef enum {
1870 DL_SCHED_GENERIC = 0,
1871 DL_SCHED_CONSENSUS = 1,
1872 DL_SCHED_BRIDGE = 2,
1873 } download_schedule_t;
1875 /** Information about our plans for retrying downloads for a downloadable
1876 * object. */
1877 typedef struct download_status_t {
1878 time_t next_attempt_at; /**< When should we try downloading this descriptor
1879 * again? */
1880 uint8_t n_download_failures; /**< Number of failures trying to download the
1881 * most recent descriptor. */
1882 ENUM_BF(download_schedule_t) schedule : 8;
1883 } download_status_t;
1885 /** If n_download_failures is this high, the download can never happen. */
1886 #define IMPOSSIBLE_TO_DOWNLOAD 255
1888 /** The max size we expect router descriptor annotations we create to
1889 * be. We'll accept larger ones if we see them on disk, but we won't
1890 * create any that are larger than this. */
1891 #define ROUTER_ANNOTATION_BUF_LEN 256
1893 /** Information need to cache an onion router's descriptor. */
1894 typedef struct signed_descriptor_t {
1895 /** Pointer to the raw server descriptor, preceded by annotations. Not
1896 * necessarily NUL-terminated. If saved_location is SAVED_IN_CACHE, this
1897 * pointer is null. */
1898 char *signed_descriptor_body;
1899 /** Length of the annotations preceding the server descriptor. */
1900 size_t annotations_len;
1901 /** Length of the server descriptor. */
1902 size_t signed_descriptor_len;
1903 /** Digest of the server descriptor, computed as specified in
1904 * dir-spec.txt. */
1905 char signed_descriptor_digest[DIGEST_LEN];
1906 /** Identity digest of the router. */
1907 char identity_digest[DIGEST_LEN];
1908 /** Declared publication time of the descriptor. */
1909 time_t published_on;
1910 /** For routerdescs only: digest of the corresponding extrainfo. */
1911 char extra_info_digest[DIGEST_LEN];
1912 /** For routerdescs only: Status of downloading the corresponding
1913 * extrainfo. */
1914 download_status_t ei_dl_status;
1915 /** Where is the descriptor saved? */
1916 saved_location_t saved_location;
1917 /** If saved_location is SAVED_IN_CACHE or SAVED_IN_JOURNAL, the offset of
1918 * this descriptor in the corresponding file. */
1919 off_t saved_offset;
1920 /** What position is this descriptor within routerlist->routers or
1921 * routerlist->old_routers? -1 for none. */
1922 int routerlist_index;
1923 /** The valid-until time of the most recent consensus that listed this
1924 * descriptor, or a bit after the publication time of the most recent v2
1925 * networkstatus that listed it. 0 for "never listed in a consensus or
1926 * status, so far as we know." */
1927 time_t last_listed_as_valid_until;
1928 /* If true, we do not ever try to save this object in the cache. */
1929 unsigned int do_not_cache : 1;
1930 /* If true, this item is meant to represent an extrainfo. */
1931 unsigned int is_extrainfo : 1;
1932 /* If true, we got an extrainfo for this item, and the digest was right,
1933 * but it was incompatible. */
1934 unsigned int extrainfo_is_bogus : 1;
1935 /* If true, we are willing to transmit this item unencrypted. */
1936 unsigned int send_unencrypted : 1;
1937 } signed_descriptor_t;
1939 /** A signed integer representing a country code. */
1940 typedef int16_t country_t;
1942 /** Information about another onion router in the network. */
1943 typedef struct {
1944 signed_descriptor_t cache_info;
1945 char *address; /**< Location of OR: either a hostname or an IP address. */
1946 char *nickname; /**< Human-readable OR name. */
1948 uint32_t addr; /**< IPv4 address of OR, in host order. */
1949 uint16_t or_port; /**< Port for TLS connections. */
1950 uint16_t dir_port; /**< Port for HTTP directory connections. */
1952 /** A router's IPv6 address, if it has one. */
1953 /* XXXXX187 Actually these should probably be part of a list of addresses,
1954 * not just a special case. Use abstractions to access these; don't do it
1955 * directly. */
1956 tor_addr_t ipv6_addr;
1957 uint16_t ipv6_orport;
1959 crypto_pk_t *onion_pkey; /**< Public RSA key for onions. */
1960 crypto_pk_t *identity_pkey; /**< Public RSA key for signing. */
1961 /** Public curve25519 key for onions */
1962 curve25519_public_key_t *onion_curve25519_pkey;
1964 char *platform; /**< What software/operating system is this OR using? */
1966 /* link info */
1967 uint32_t bandwidthrate; /**< How many bytes does this OR add to its token
1968 * bucket per second? */
1969 uint32_t bandwidthburst; /**< How large is this OR's token bucket? */
1970 /** How many bytes/s is this router known to handle? */
1971 uint32_t bandwidthcapacity;
1972 smartlist_t *exit_policy; /**< What streams will this OR permit
1973 * to exit on IPv4? NULL for 'reject *:*'. */
1974 /** What streams will this OR permit to exit on IPv6?
1975 * NULL for 'reject *:*' */
1976 struct short_policy_t *ipv6_exit_policy;
1977 long uptime; /**< How many seconds the router claims to have been up */
1978 smartlist_t *declared_family; /**< Nicknames of router which this router
1979 * claims are its family. */
1980 char *contact_info; /**< Declared contact info for this router. */
1981 unsigned int is_hibernating:1; /**< Whether the router claims to be
1982 * hibernating */
1983 unsigned int caches_extra_info:1; /**< Whether the router says it caches and
1984 * serves extrainfo documents. */
1985 unsigned int allow_single_hop_exits:1; /**< Whether the router says
1986 * it allows single hop exits. */
1988 unsigned int wants_to_be_hs_dir:1; /**< True iff this router claims to be
1989 * a hidden service directory. */
1990 unsigned int policy_is_reject_star:1; /**< True iff the exit policy for this
1991 * router rejects everything. */
1992 /** True if, after we have added this router, we should re-launch
1993 * tests for it. */
1994 unsigned int needs_retest_if_added:1;
1996 /** Tor can use this router for general positions in circuits; we got it
1997 * from a directory server as usual, or we're an authority and a server
1998 * uploaded it. */
1999 #define ROUTER_PURPOSE_GENERAL 0
2000 /** Tor should avoid using this router for circuit-building: we got it
2001 * from a crontroller. If the controller wants to use it, it'll have to
2002 * ask for it by identity. */
2003 #define ROUTER_PURPOSE_CONTROLLER 1
2004 /** Tor should use this router only for bridge positions in circuits: we got
2005 * it via a directory request from the bridge itself, or a bridge
2006 * authority. x*/
2007 #define ROUTER_PURPOSE_BRIDGE 2
2008 /** Tor should not use this router; it was marked in cached-descriptors with
2009 * a purpose we didn't recognize. */
2010 #define ROUTER_PURPOSE_UNKNOWN 255
2012 /* In what way did we find out about this router? One of ROUTER_PURPOSE_*.
2013 * Routers of different purposes are kept segregated and used for different
2014 * things; see notes on ROUTER_PURPOSE_* macros above.
2016 uint8_t purpose;
2017 } routerinfo_t;
2019 /** Information needed to keep and cache a signed extra-info document. */
2020 typedef struct extrainfo_t {
2021 signed_descriptor_t cache_info;
2022 /** The router's nickname. */
2023 char nickname[MAX_NICKNAME_LEN+1];
2024 /** True iff we found the right key for this extra-info, verified the
2025 * signature, and found it to be bad. */
2026 unsigned int bad_sig : 1;
2027 /** If present, we didn't have the right key to verify this extra-info,
2028 * so this is a copy of the signature in the document. */
2029 char *pending_sig;
2030 /** Length of pending_sig. */
2031 size_t pending_sig_len;
2032 } extrainfo_t;
2034 /** Contents of a single router entry in a network status object.
2036 typedef struct routerstatus_t {
2037 time_t published_on; /**< When was this router published? */
2038 char nickname[MAX_NICKNAME_LEN+1]; /**< The nickname this router says it
2039 * has. */
2040 char identity_digest[DIGEST_LEN]; /**< Digest of the router's identity
2041 * key. */
2042 /** Digest of the router's most recent descriptor or microdescriptor.
2043 * If it's a descriptor, we only use the first DIGEST_LEN bytes. */
2044 char descriptor_digest[DIGEST256_LEN];
2045 uint32_t addr; /**< IPv4 address for this router. */
2046 uint16_t or_port; /**< OR port for this router. */
2047 uint16_t dir_port; /**< Directory port for this router. */
2048 tor_addr_t ipv6_addr; /**< IPv6 address for this router. */
2049 uint16_t ipv6_orport; /**<IPV6 OR port for this router. */
2050 unsigned int is_authority:1; /**< True iff this router is an authority. */
2051 unsigned int is_exit:1; /**< True iff this router is a good exit. */
2052 unsigned int is_stable:1; /**< True iff this router stays up a long time. */
2053 unsigned int is_fast:1; /**< True iff this router has good bandwidth. */
2054 /** True iff this router is called 'running' in the consensus. We give it
2055 * this funny name so that we don't accidentally use this bit as a view of
2056 * whether we think the router is *currently* running. If that's what you
2057 * want to know, look at is_running in node_t. */
2058 unsigned int is_flagged_running:1;
2059 unsigned int is_named:1; /**< True iff "nickname" belongs to this router. */
2060 unsigned int is_unnamed:1; /**< True iff "nickname" belongs to another
2061 * router. */
2062 unsigned int is_valid:1; /**< True iff this router isn't invalid. */
2063 unsigned int is_v2_dir:1; /**< True iff this router can serve directory
2064 * information with v2 of the directory
2065 * protocol. (All directory caches cache v1
2066 * directories.) */
2067 unsigned int is_possible_guard:1; /**< True iff this router would be a good
2068 * choice as an entry guard. */
2069 unsigned int is_bad_exit:1; /**< True iff this node is a bad choice for
2070 * an exit node. */
2071 unsigned int is_bad_directory:1; /**< Do we think this directory is junky,
2072 * underpowered, or otherwise useless? */
2073 unsigned int is_hs_dir:1; /**< True iff this router is a v2-or-later hidden
2074 * service directory. */
2075 /** True iff we know version info for this router. (i.e., a "v" entry was
2076 * included.) We'll replace all these with a big tor_version_t or a char[]
2077 * if the number of traits we care about ever becomes incredibly big. */
2078 unsigned int version_known:1;
2080 /** True iff this router is a version that, if it caches directory info,
2081 * we can get microdescriptors from. */
2082 unsigned int version_supports_microdesc_cache:1;
2083 /** True iff this router is a version that allows DATA cells to arrive on
2084 * a stream before it has sent a CONNECTED cell. */
2085 unsigned int version_supports_optimistic_data:1;
2086 /** True iff this router has a version that allows it to accept EXTEND2
2087 * cells */
2088 unsigned int version_supports_extend2_cells:1;
2090 unsigned int has_bandwidth:1; /**< The vote/consensus had bw info */
2091 unsigned int has_exitsummary:1; /**< The vote/consensus had exit summaries */
2092 unsigned int bw_is_unmeasured:1; /**< This is a consensus entry, with
2093 * the Unmeasured flag set. */
2095 uint32_t bandwidth; /**< Bandwidth (capacity) of the router as reported in
2096 * the vote/consensus, in kilobytes/sec. */
2097 char *exitsummary; /**< exit policy summary -
2098 * XXX weasel: this probably should not stay a string. */
2100 /* ---- The fields below aren't derived from the networkstatus; they
2101 * hold local information only. */
2103 /** True if we, as a directory mirror, want to download the corresponding
2104 * routerinfo from the authority who gave us this routerstatus. (That is,
2105 * if we don't have the routerinfo, and if we haven't already tried to get it
2106 * from this authority.) Applies in v2 networkstatus document only.
2108 unsigned int need_to_mirror:1;
2109 time_t last_dir_503_at; /**< When did this router last tell us that it
2110 * was too busy to serve directory info? */
2111 download_status_t dl_status;
2113 } routerstatus_t;
2115 /** A single entry in a parsed policy summary, describing a range of ports. */
2116 typedef struct short_policy_entry_t {
2117 uint16_t min_port, max_port;
2118 } short_policy_entry_t;
2120 /** A short_poliy_t is the parsed version of a policy summary. */
2121 typedef struct short_policy_t {
2122 /** True if the members of 'entries' are port ranges to accept; false if
2123 * they are port ranges to reject */
2124 unsigned int is_accept : 1;
2125 /** The actual number of values in 'entries'. */
2126 unsigned int n_entries : 31;
2127 /** An array of 0 or more short_policy_entry_t values, each describing a
2128 * range of ports that this policy accepts or rejects (depending on the
2129 * value of is_accept).
2131 short_policy_entry_t entries[FLEXIBLE_ARRAY_MEMBER];
2132 } short_policy_t;
2134 /** A microdescriptor is the smallest amount of information needed to build a
2135 * circuit through a router. They are generated by the directory authorities,
2136 * using information from the uploaded routerinfo documents. They are not
2137 * self-signed, but are rather authenticated by having their hash in a signed
2138 * networkstatus document. */
2139 typedef struct microdesc_t {
2140 /** Hashtable node, used to look up the microdesc by its digest. */
2141 HT_ENTRY(microdesc_t) node;
2143 /* Cache information */
2145 /** When was this microdescriptor last listed in a consensus document?
2146 * Once a microdesc has been unlisted long enough, we can drop it.
2148 time_t last_listed;
2149 /** Where is this microdescriptor currently stored? */
2150 ENUM_BF(saved_location_t) saved_location : 3;
2151 /** If true, do not attempt to cache this microdescriptor on disk. */
2152 unsigned int no_save : 1;
2153 /** If true, this microdesc has an entry in the microdesc_map */
2154 unsigned int held_in_map : 1;
2155 /** Reference count: how many node_ts have a reference to this microdesc? */
2156 unsigned int held_by_nodes;
2158 /** If saved_location == SAVED_IN_CACHE, this field holds the offset of the
2159 * microdescriptor in the cache. */
2160 off_t off;
2162 /* The string containing the microdesc. */
2164 /** A pointer to the encoded body of the microdescriptor. If the
2165 * saved_location is SAVED_IN_CACHE, then the body is a pointer into an
2166 * mmap'd region. Otherwise, it is a malloc'd string. The string might not
2167 * be NUL-terminated; take the length from <b>bodylen</b>. */
2168 char *body;
2169 /** The length of the microdescriptor in <b>body</b>. */
2170 size_t bodylen;
2171 /** A SHA256-digest of the microdescriptor. */
2172 char digest[DIGEST256_LEN];
2174 /* Fields in the microdescriptor. */
2176 /** As routerinfo_t.onion_pkey */
2177 crypto_pk_t *onion_pkey;
2178 /** As routerinfo_t.onion_curve25519_pkey */
2179 curve25519_public_key_t *onion_curve25519_pkey;
2180 /** As routerinfo_t.ipv6_add */
2181 tor_addr_t ipv6_addr;
2182 /** As routerinfo_t.ipv6_orport */
2183 uint16_t ipv6_orport;
2184 /** As routerinfo_t.family */
2185 smartlist_t *family;
2186 /** IPv4 exit policy summary */
2187 short_policy_t *exit_policy;
2188 /** IPv6 exit policy summary */
2189 short_policy_t *ipv6_exit_policy;
2191 } microdesc_t;
2193 /** A node_t represents a Tor router.
2195 * Specifically, a node_t is a Tor router as we are using it: a router that
2196 * we are considering for circuits, connections, and so on. A node_t is a
2197 * thin wrapper around the routerstatus, routerinfo, and microdesc for a
2198 * single wrapper, and provides a consistent interface for all of them.
2200 * Also, a node_t has mutable state. While a routerinfo, a routerstatus,
2201 * and a microdesc have[*] only the information read from a router
2202 * descriptor, a consensus entry, and a microdescriptor (respectively)...
2203 * a node_t has flags based on *our own current opinion* of the node.
2205 * [*] Actually, there is some leftover information in each that is mutable.
2206 * We should try to excise that.
2208 typedef struct node_t {
2209 /* Indexing information */
2211 /** Used to look up the node_t by its identity digest. */
2212 HT_ENTRY(node_t) ht_ent;
2213 /** Position of the node within the list of nodes */
2214 int nodelist_idx;
2216 /** The identity digest of this node_t. No more than one node_t per
2217 * identity may exist at a time. */
2218 char identity[DIGEST_LEN];
2220 microdesc_t *md;
2221 routerinfo_t *ri;
2222 routerstatus_t *rs;
2224 /* local info: copied from routerstatus, then possibly frobbed based
2225 * on experience. Authorities set this stuff directly. Note that
2226 * these reflect knowledge of the primary (IPv4) OR port only. */
2228 unsigned int is_running:1; /**< As far as we know, is this OR currently
2229 * running? */
2230 unsigned int is_valid:1; /**< Has a trusted dirserver validated this OR?
2231 * (For Authdir: Have we validated this OR?) */
2232 unsigned int is_fast:1; /** Do we think this is a fast OR? */
2233 unsigned int is_stable:1; /** Do we think this is a stable OR? */
2234 unsigned int is_possible_guard:1; /**< Do we think this is an OK guard? */
2235 unsigned int is_exit:1; /**< Do we think this is an OK exit? */
2236 unsigned int is_bad_exit:1; /**< Do we think this exit is censored, borked,
2237 * or otherwise nasty? */
2238 unsigned int is_bad_directory:1; /**< Do we think this directory is junky,
2239 * underpowered, or otherwise useless? */
2240 unsigned int is_hs_dir:1; /**< True iff this router is a hidden service
2241 * directory according to the authorities. */
2243 /* Local info: warning state. */
2245 unsigned int name_lookup_warned:1; /**< Have we warned the user for referring
2246 * to this (unnamed) router by nickname?
2249 /** Local info: we treat this node as if it rejects everything */
2250 unsigned int rejects_all:1;
2252 /** Local info: this node is in our list of guards */
2253 unsigned int using_as_guard:1;
2255 /* Local info: derived. */
2257 /** True if the IPv6 OR port is preferred over the IPv4 OR port. */
2258 unsigned int ipv6_preferred:1;
2260 /** According to the geoip db what country is this router in? */
2261 /* XXXprop186 what is this suppose to mean with multiple OR ports? */
2262 country_t country;
2264 /* The below items are used only by authdirservers for
2265 * reachability testing. */
2267 /** When was the last time we could reach this OR? */
2268 time_t last_reachable; /* IPv4. */
2269 time_t last_reachable6; /* IPv6. */
2271 } node_t;
2273 /** How many times will we try to download a router's descriptor before giving
2274 * up? */
2275 #define MAX_ROUTERDESC_DOWNLOAD_FAILURES 8
2277 /** How many times will we try to download a microdescriptor before giving
2278 * up? */
2279 #define MAX_MICRODESC_DOWNLOAD_FAILURES 8
2281 /** Contents of a v2 (non-consensus, non-vote) network status object. */
2282 typedef struct networkstatus_v2_t {
2283 /** When did we receive the network-status document? */
2284 time_t received_on;
2286 /** What was the digest of the document? */
2287 char networkstatus_digest[DIGEST_LEN];
2289 /* These fields come from the actual network-status document.*/
2290 time_t published_on; /**< Declared publication date. */
2292 char *source_address; /**< Canonical directory server hostname. */
2293 uint32_t source_addr; /**< Canonical directory server IP. */
2294 uint16_t source_dirport; /**< Canonical directory server dirport. */
2296 unsigned int binds_names:1; /**< True iff this directory server binds
2297 * names. */
2298 unsigned int recommends_versions:1; /**< True iff this directory server
2299 * recommends client and server software
2300 * versions. */
2301 unsigned int lists_bad_exits:1; /**< True iff this directory server marks
2302 * malfunctioning exits as bad. */
2303 /** True iff this directory server marks malfunctioning directories as
2304 * bad. */
2305 unsigned int lists_bad_directories:1;
2307 char identity_digest[DIGEST_LEN]; /**< Digest of signing key. */
2308 char *contact; /**< How to contact directory admin? (may be NULL). */
2309 crypto_pk_t *signing_key; /**< Key used to sign this directory. */
2310 char *client_versions; /**< comma-separated list of recommended client
2311 * versions. */
2312 char *server_versions; /**< comma-separated list of recommended server
2313 * versions. */
2315 smartlist_t *entries; /**< List of routerstatus_t*. This list is kept
2316 * sorted by identity_digest. */
2317 } networkstatus_v2_t;
2319 /** Linked list of microdesc hash lines for a single router in a directory
2320 * vote.
2322 typedef struct vote_microdesc_hash_t {
2323 /** Next element in the list, or NULL. */
2324 struct vote_microdesc_hash_t *next;
2325 /** The raw contents of the microdesc hash line, excluding the "m". */
2326 char *microdesc_hash_line;
2327 } vote_microdesc_hash_t;
2329 /** The claim about a single router, made in a vote. */
2330 typedef struct vote_routerstatus_t {
2331 routerstatus_t status; /**< Underlying 'status' object for this router.
2332 * Flags are redundant. */
2333 /** How many known-flags are allowed in a vote? This is the width of
2334 * the flags field of vote_routerstatus_t */
2335 #define MAX_KNOWN_FLAGS_IN_VOTE 64
2336 uint64_t flags; /**< Bit-field for all recognized flags; index into
2337 * networkstatus_t.known_flags. */
2338 char *version; /**< The version that the authority says this router is
2339 * running. */
2340 unsigned int has_measured_bw:1; /**< The vote had a measured bw */
2341 uint32_t measured_bw; /**< Measured bandwidth (capacity) of the router */
2342 /** The hash or hashes that the authority claims this microdesc has. */
2343 vote_microdesc_hash_t *microdesc;
2344 } vote_routerstatus_t;
2346 /** A signature of some document by an authority. */
2347 typedef struct document_signature_t {
2348 /** Declared SHA-1 digest of this voter's identity key */
2349 char identity_digest[DIGEST_LEN];
2350 /** Declared SHA-1 digest of signing key used by this voter. */
2351 char signing_key_digest[DIGEST_LEN];
2352 /** Algorithm used to compute the digest of the document. */
2353 digest_algorithm_t alg;
2354 /** Signature of the signed thing. */
2355 char *signature;
2356 /** Length of <b>signature</b> */
2357 int signature_len;
2358 unsigned int bad_signature : 1; /**< Set to true if we've tried to verify
2359 * the sig, and we know it's bad. */
2360 unsigned int good_signature : 1; /**< Set to true if we've verified the sig
2361 * as good. */
2362 } document_signature_t;
2364 /** Information about a single voter in a vote or a consensus. */
2365 typedef struct networkstatus_voter_info_t {
2366 /** Declared SHA-1 digest of this voter's identity key */
2367 char identity_digest[DIGEST_LEN];
2368 char *nickname; /**< Nickname of this voter */
2369 /** Digest of this voter's "legacy" identity key, if any. In vote only; for
2370 * consensuses, we treat legacy keys as additional signers. */
2371 char legacy_id_digest[DIGEST_LEN];
2372 char *address; /**< Address of this voter, in string format. */
2373 uint32_t addr; /**< Address of this voter, in IPv4, in host order. */
2374 uint16_t dir_port; /**< Directory port of this voter */
2375 uint16_t or_port; /**< OR port of this voter */
2376 char *contact; /**< Contact information for this voter. */
2377 char vote_digest[DIGEST_LEN]; /**< Digest of this voter's vote, as signed. */
2379 /* Nothing from here on is signed. */
2380 /** The signature of the document and the signature's status. */
2381 smartlist_t *sigs;
2382 } networkstatus_voter_info_t;
2384 /** Enumerates the possible seriousness values of a networkstatus document. */
2385 typedef enum {
2386 NS_TYPE_VOTE,
2387 NS_TYPE_CONSENSUS,
2388 NS_TYPE_OPINION,
2389 } networkstatus_type_t;
2391 /** Enumerates recognized flavors of a consensus networkstatus document. All
2392 * flavors of a consensus are generated from the same set of votes, but they
2393 * present different types information to different versions of Tor. */
2394 typedef enum {
2395 FLAV_NS = 0,
2396 FLAV_MICRODESC = 1,
2397 } consensus_flavor_t;
2399 /** How many different consensus flavors are there? */
2400 #define N_CONSENSUS_FLAVORS ((int)(FLAV_MICRODESC)+1)
2402 /** A common structure to hold a v3 network status vote, or a v3 network
2403 * status consensus. */
2404 typedef struct networkstatus_t {
2405 ENUM_BF(networkstatus_type_t) type : 8; /**< Vote, consensus, or opinion? */
2406 ENUM_BF(consensus_flavor_t) flavor : 8; /**< If a consensus, what kind? */
2407 unsigned int has_measured_bws : 1;/**< True iff this networkstatus contains
2408 * measured= bandwidth values. */
2410 time_t published; /**< Vote only: Time when vote was written. */
2411 time_t valid_after; /**< Time after which this vote or consensus applies. */
2412 time_t fresh_until; /**< Time before which this is the most recent vote or
2413 * consensus. */
2414 time_t valid_until; /**< Time after which this vote or consensus should not
2415 * be used. */
2417 /** Consensus only: what method was used to produce this consensus? */
2418 int consensus_method;
2419 /** Vote only: what methods is this voter willing to use? */
2420 smartlist_t *supported_methods;
2422 /** How long does this vote/consensus claim that authorities take to
2423 * distribute their votes to one another? */
2424 int vote_seconds;
2425 /** How long does this vote/consensus claim that authorities take to
2426 * distribute their consensus signatures to one another? */
2427 int dist_seconds;
2429 /** Comma-separated list of recommended client software, or NULL if this
2430 * voter has no opinion. */
2431 char *client_versions;
2432 char *server_versions;
2433 /** List of flags that this vote/consensus applies to routers. If a flag is
2434 * not listed here, the voter has no opinion on what its value should be. */
2435 smartlist_t *known_flags;
2437 /** List of key=value strings for the parameters in this vote or
2438 * consensus, sorted by key. */
2439 smartlist_t *net_params;
2441 /** List of key=value strings for the bw weight parameters in the
2442 * consensus. */
2443 smartlist_t *weight_params;
2445 /** List of networkstatus_voter_info_t. For a vote, only one element
2446 * is included. For a consensus, one element is included for every voter
2447 * whose vote contributed to the consensus. */
2448 smartlist_t *voters;
2450 struct authority_cert_t *cert; /**< Vote only: the voter's certificate. */
2452 /** Digests of this document, as signed. */
2453 digests_t digests;
2455 /** List of router statuses, sorted by identity digest. For a vote,
2456 * the elements are vote_routerstatus_t; for a consensus, the elements
2457 * are routerstatus_t. */
2458 smartlist_t *routerstatus_list;
2460 /** If present, a map from descriptor digest to elements of
2461 * routerstatus_list. */
2462 digestmap_t *desc_digest_map;
2463 } networkstatus_t;
2465 /** A set of signatures for a networkstatus consensus. Unless otherwise
2466 * noted, all fields are as for networkstatus_t. */
2467 typedef struct ns_detached_signatures_t {
2468 time_t valid_after;
2469 time_t fresh_until;
2470 time_t valid_until;
2471 strmap_t *digests; /**< Map from flavor name to digestset_t */
2472 strmap_t *signatures; /**< Map from flavor name to list of
2473 * document_signature_t */
2474 } ns_detached_signatures_t;
2476 /** Allowable types of desc_store_t. */
2477 typedef enum store_type_t {
2478 ROUTER_STORE = 0,
2479 EXTRAINFO_STORE = 1
2480 } store_type_t;
2482 /** A 'store' is a set of descriptors saved on disk, with accompanying
2483 * journal, mmaped as needed, rebuilt as needed. */
2484 typedef struct desc_store_t {
2485 /** Filename (within DataDir) for the store. We append .tmp to this
2486 * filename for a temporary file when rebuilding the store, and .new to this
2487 * filename for the journal. */
2488 const char *fname_base;
2489 /** Alternative (obsolete) value for fname_base: if the file named by
2490 * fname_base isn't present, we read from here instead, but we never write
2491 * here. */
2492 const char *fname_alt_base;
2493 /** Human-readable description of what this store contains. */
2494 const char *description;
2496 tor_mmap_t *mmap; /**< A mmap for the main file in the store. */
2498 store_type_t type; /**< What's stored in this store? */
2500 /** The size of the router log, in bytes. */
2501 size_t journal_len;
2502 /** The size of the router store, in bytes. */
2503 size_t store_len;
2504 /** Total bytes dropped since last rebuild: this is space currently
2505 * used in the cache and the journal that could be freed by a rebuild. */
2506 size_t bytes_dropped;
2507 } desc_store_t;
2509 /** Contents of a directory of onion routers. */
2510 typedef struct {
2511 /** Map from server identity digest to a member of routers. */
2512 struct digest_ri_map_t *identity_map;
2513 /** Map from server descriptor digest to a signed_descriptor_t from
2514 * routers or old_routers. */
2515 struct digest_sd_map_t *desc_digest_map;
2516 /** Map from extra-info digest to an extrainfo_t. Only exists for
2517 * routers in routers or old_routers. */
2518 struct digest_ei_map_t *extra_info_map;
2519 /** Map from extra-info digests to a signed_descriptor_t for a router
2520 * descriptor having that extra-info digest. Only exists for
2521 * routers in routers or old_routers. */
2522 struct digest_sd_map_t *desc_by_eid_map;
2523 /** List of routerinfo_t for all currently live routers we know. */
2524 smartlist_t *routers;
2525 /** List of signed_descriptor_t for older router descriptors we're
2526 * caching. */
2527 smartlist_t *old_routers;
2528 /** Store holding server descriptors. If present, any router whose
2529 * cache_info.saved_location == SAVED_IN_CACHE is stored in this file
2530 * starting at cache_info.saved_offset */
2531 desc_store_t desc_store;
2532 /** Store holding extra-info documents. */
2533 desc_store_t extrainfo_store;
2534 } routerlist_t;
2536 /** Information on router used when extending a circuit. We don't need a
2537 * full routerinfo_t to extend: we only need addr:port:keyid to build an OR
2538 * connection, and onion_key to create the onionskin. Note that for onehop
2539 * general-purpose tunnels, the onion_key is NULL. */
2540 typedef struct extend_info_t {
2541 char nickname[MAX_HEX_NICKNAME_LEN+1]; /**< This router's nickname for
2542 * display. */
2543 char identity_digest[DIGEST_LEN]; /**< Hash of this router's identity key. */
2544 uint16_t port; /**< OR port. */
2545 tor_addr_t addr; /**< IP address. */
2546 crypto_pk_t *onion_key; /**< Current onionskin key. */
2547 #ifdef CURVE25519_ENABLED
2548 curve25519_public_key_t curve25519_onion_key;
2549 #endif
2550 } extend_info_t;
2552 /** Certificate for v3 directory protocol: binds long-term authority identity
2553 * keys to medium-term authority signing keys. */
2554 typedef struct authority_cert_t {
2555 /** Information relating to caching this cert on disk and looking it up. */
2556 signed_descriptor_t cache_info;
2557 /** This authority's long-term authority identity key. */
2558 crypto_pk_t *identity_key;
2559 /** This authority's medium-term signing key. */
2560 crypto_pk_t *signing_key;
2561 /** The digest of <b>signing_key</b> */
2562 char signing_key_digest[DIGEST_LEN];
2563 /** The listed expiration time of this certificate. */
2564 time_t expires;
2565 /** This authority's IPv4 address, in host order. */
2566 uint32_t addr;
2567 /** This authority's directory port. */
2568 uint16_t dir_port;
2569 /** True iff this certificate was cross-certified by signing the identity
2570 * key with the signing key. */
2571 uint8_t is_cross_certified;
2572 } authority_cert_t;
2574 /** Bitfield enum type listing types of information that directory authorities
2575 * can be authoritative about, and that directory caches may or may not cache.
2577 * Note that the granularity here is based on authority granularity and on
2578 * cache capabilities. Thus, one particular bit may correspond in practice to
2579 * a few types of directory info, so long as every authority that pronounces
2580 * officially about one of the types prounounces officially about all of them,
2581 * and so long as every cache that caches one of them caches all of them.
2583 typedef enum {
2584 NO_DIRINFO = 0,
2585 /** Serves/signs v1 directory information: Big lists of routers, and short
2586 * routerstatus documents. */
2587 V1_DIRINFO = 1 << 0,
2588 /** Serves/signs v2 directory information: i.e. v2 networkstatus documents */
2589 V2_DIRINFO = 1 << 1,
2590 /** Serves/signs v3 directory information: votes, consensuses, certs */
2591 V3_DIRINFO = 1 << 2,
2592 /** Serves hidden service descriptors. */
2593 HIDSERV_DIRINFO = 1 << 3,
2594 /** Serves bridge descriptors. */
2595 BRIDGE_DIRINFO = 1 << 4,
2596 /** Serves extrainfo documents. */
2597 EXTRAINFO_DIRINFO=1 << 5,
2598 /** Serves microdescriptors. */
2599 MICRODESC_DIRINFO=1 << 6,
2600 } dirinfo_type_t;
2602 #define ALL_DIRINFO ((dirinfo_type_t)((1<<7)-1))
2604 #define CRYPT_PATH_MAGIC 0x70127012u
2606 struct fast_handshake_state_t;
2607 struct ntor_handshake_state_t;
2608 #define ONION_HANDSHAKE_TYPE_TAP 0x0000
2609 #define ONION_HANDSHAKE_TYPE_FAST 0x0001
2610 #define ONION_HANDSHAKE_TYPE_NTOR 0x0002
2611 #define MAX_ONION_HANDSHAKE_TYPE 0x0002
2612 typedef struct {
2613 uint16_t tag;
2614 union {
2615 struct fast_handshake_state_t *fast;
2616 crypto_dh_t *tap;
2617 struct ntor_handshake_state_t *ntor;
2618 } u;
2619 } onion_handshake_state_t;
2621 /** Holds accounting information for a single step in the layered encryption
2622 * performed by a circuit. Used only at the client edge of a circuit. */
2623 typedef struct crypt_path_t {
2624 uint32_t magic;
2626 /* crypto environments */
2627 /** Encryption key and counter for cells heading towards the OR at this
2628 * step. */
2629 crypto_cipher_t *f_crypto;
2630 /** Encryption key and counter for cells heading back from the OR at this
2631 * step. */
2632 crypto_cipher_t *b_crypto;
2634 /** Digest state for cells heading towards the OR at this step. */
2635 crypto_digest_t *f_digest; /* for integrity checking */
2636 /** Digest state for cells heading away from the OR at this step. */
2637 crypto_digest_t *b_digest;
2639 /** Current state of the handshake as performed with the OR at this
2640 * step. */
2641 onion_handshake_state_t handshake_state;
2642 /** Diffie-hellman handshake state for performing an introduction
2643 * operations */
2644 crypto_dh_t *rend_dh_handshake_state;
2646 /** Negotiated key material shared with the OR at this step. */
2647 char rend_circ_nonce[DIGEST_LEN];/* KH in tor-spec.txt */
2649 /** Information to extend to the OR at this step. */
2650 extend_info_t *extend_info;
2652 /** Is the circuit built to this step? Must be one of:
2653 * - CPATH_STATE_CLOSED (The circuit has not been extended to this step)
2654 * - CPATH_STATE_AWAITING_KEYS (We have sent an EXTEND/CREATE to this step
2655 * and not received an EXTENDED/CREATED)
2656 * - CPATH_STATE_OPEN (The circuit has been extended to this step) */
2657 uint8_t state;
2658 #define CPATH_STATE_CLOSED 0
2659 #define CPATH_STATE_AWAITING_KEYS 1
2660 #define CPATH_STATE_OPEN 2
2661 struct crypt_path_t *next; /**< Link to next crypt_path_t in the circuit.
2662 * (The list is circular, so the last node
2663 * links to the first.) */
2664 struct crypt_path_t *prev; /**< Link to previous crypt_path_t in the
2665 * circuit. */
2667 int package_window; /**< How many cells are we allowed to originate ending
2668 * at this step? */
2669 int deliver_window; /**< How many cells are we willing to deliver originating
2670 * at this step? */
2671 } crypt_path_t;
2673 /** A reference-counted pointer to a crypt_path_t, used only to share
2674 * the final rendezvous cpath to be used on a service-side rendezvous
2675 * circuit among multiple circuits built in parallel to the same
2676 * destination rendezvous point. */
2677 typedef struct {
2678 /** The reference count. */
2679 unsigned int refcount;
2680 /** The pointer. Set to NULL when the crypt_path_t is put into use
2681 * on an opened rendezvous circuit. */
2682 crypt_path_t *cpath;
2683 } crypt_path_reference_t;
2685 #define CPATH_KEY_MATERIAL_LEN (20*2+16*2)
2687 #define DH_KEY_LEN DH_BYTES
2689 /** Information used to build a circuit. */
2690 typedef struct {
2691 /** Intended length of the final circuit. */
2692 int desired_path_len;
2693 /** How to extend to the planned exit node. */
2694 extend_info_t *chosen_exit;
2695 /** Whether every node in the circ must have adequate uptime. */
2696 unsigned int need_uptime : 1;
2697 /** Whether every node in the circ must have adequate capacity. */
2698 unsigned int need_capacity : 1;
2699 /** Whether the last hop was picked with exiting in mind. */
2700 unsigned int is_internal : 1;
2701 /** Did we pick this as a one-hop tunnel (not safe for other streams)?
2702 * These are for encrypted dir conns that exit to this router, not
2703 * for arbitrary exits from the circuit. */
2704 unsigned int onehop_tunnel : 1;
2705 /** The crypt_path_t to append after rendezvous: used for rendezvous. */
2706 crypt_path_t *pending_final_cpath;
2707 /** A ref-counted reference to the crypt_path_t to append after
2708 * rendezvous; used on the service side. */
2709 crypt_path_reference_t *service_pending_final_cpath_ref;
2710 /** How many times has building a circuit for this task failed? */
2711 int failure_count;
2712 /** At what time should we give up on this task? */
2713 time_t expiry_time;
2714 } cpath_build_state_t;
2716 #define ORIGIN_CIRCUIT_MAGIC 0x35315243u
2717 #define OR_CIRCUIT_MAGIC 0x98ABC04Fu
2719 struct create_cell_t;
2722 * A circuit is a path over the onion routing
2723 * network. Applications can connect to one end of the circuit, and can
2724 * create exit connections at the other end of the circuit. AP and exit
2725 * connections have only one circuit associated with them (and thus these
2726 * connection types are closed when the circuit is closed), whereas
2727 * OR connections multiplex many circuits at once, and stay standing even
2728 * when there are no circuits running over them.
2730 * A circuit_t structure can fill one of two roles. First, a or_circuit_t
2731 * links two connections together: either an edge connection and an OR
2732 * connection, or two OR connections. (When joined to an OR connection, a
2733 * circuit_t affects only cells sent to a particular circID on that
2734 * connection. When joined to an edge connection, a circuit_t affects all
2735 * data.)
2737 * Second, an origin_circuit_t holds the cipher keys and state for sending data
2738 * along a given circuit. At the OP, it has a sequence of ciphers, each
2739 * of which is shared with a single OR along the circuit. Separate
2740 * ciphers are used for data going "forward" (away from the OP) and
2741 * "backward" (towards the OP). At the OR, a circuit has only two stream
2742 * ciphers: one for data going forward, and one for data going backward.
2744 typedef struct circuit_t {
2745 uint32_t magic; /**< For memory and type debugging: must equal
2746 * ORIGIN_CIRCUIT_MAGIC or OR_CIRCUIT_MAGIC. */
2748 /** The channel that is next in this circuit. */
2749 channel_t *n_chan;
2752 * The circuit_id used in the next (forward) hop of this circuit;
2753 * this is unique to n_chan, but this ordered pair is globally
2754 * unique:
2756 * (n_chan->global_identifier, n_circ_id)
2758 circid_t n_circ_id;
2761 * Circuit mux associated with n_chan to which this circuit is attached;
2762 * NULL if we have no n_chan.
2764 circuitmux_t *n_mux;
2766 /** Queue of cells waiting to be transmitted on n_chan */
2767 cell_queue_t n_chan_cells;
2770 * The hop to which we want to extend this circuit. Should be NULL if
2771 * the circuit has attached to a channel.
2773 extend_info_t *n_hop;
2775 /** True iff we are waiting for n_chan_cells to become less full before
2776 * allowing p_streams to add any more cells. (Origin circuit only.) */
2777 unsigned int streams_blocked_on_n_chan : 1;
2778 /** True iff we are waiting for p_chan_cells to become less full before
2779 * allowing n_streams to add any more cells. (OR circuit only.) */
2780 unsigned int streams_blocked_on_p_chan : 1;
2782 uint8_t state; /**< Current status of this circuit. */
2783 uint8_t purpose; /**< Why are we creating this circuit? */
2785 /** How many relay data cells can we package (read from edge streams)
2786 * on this circuit before we receive a circuit-level sendme cell asking
2787 * for more? */
2788 int package_window;
2789 /** How many relay data cells will we deliver (write to edge streams)
2790 * on this circuit? When deliver_window gets low, we send some
2791 * circuit-level sendme cells to indicate that we're willing to accept
2792 * more. */
2793 int deliver_window;
2795 /** For storage while n_chan is pending (state CIRCUIT_STATE_CHAN_WAIT). */
2796 struct create_cell_t *n_chan_create_cell;
2798 /** When did circuit construction actually begin (ie send the
2799 * CREATE cell or begin cannibalization).
2801 * Note: This timer will get reset if we decide to cannibalize
2802 * a circuit. It may also get reset during certain phases of hidden
2803 * service circuit use.
2805 * We keep this timestamp with a higher resolution than most so that the
2806 * circuit-build-time tracking code can get millisecond resolution.
2808 struct timeval timestamp_began;
2810 /** This timestamp marks when the init_circuit_base constructor ran. */
2811 struct timeval timestamp_created;
2813 /** When the circuit was first used, or 0 if the circuit is clean.
2815 * XXXX023 Note that some code will artifically adjust this value backward
2816 * in time in order to indicate that a circuit shouldn't be used for new
2817 * streams, but that it can stay alive as long as it has streams on it.
2818 * That's a kludge we should fix.
2820 * XXX023 The CBT code uses this field to record when HS-related
2821 * circuits entered certain states. This usage probably won't
2822 * interfere with this field's primary purpose, but we should
2823 * document it more thoroughly to make sure of that.
2825 time_t timestamp_dirty;
2827 uint16_t marked_for_close; /**< Should we close this circuit at the end of
2828 * the main loop? (If true, holds the line number
2829 * where this circuit was marked.) */
2830 const char *marked_for_close_file; /**< For debugging: in which file was this
2831 * circuit marked for close? */
2833 /** Unique ID for measuring tunneled network status requests. */
2834 uint64_t dirreq_id;
2836 struct circuit_t *next; /**< Next circuit in linked list of all circuits. */
2838 /** Next circuit in the doubly-linked ring of circuits waiting to add
2839 * cells to n_conn. NULL if we have no cells pending, or if we're not
2840 * linked to an OR connection. */
2841 struct circuit_t *next_active_on_n_chan;
2842 /** Previous circuit in the doubly-linked ring of circuits waiting to add
2843 * cells to n_conn. NULL if we have no cells pending, or if we're not
2844 * linked to an OR connection. */
2845 struct circuit_t *prev_active_on_n_chan;
2846 } circuit_t;
2848 /** Largest number of relay_early cells that we can send on a given
2849 * circuit. */
2850 #define MAX_RELAY_EARLY_CELLS_PER_CIRCUIT 8
2853 * Describes the circuit building process in simplified terms based
2854 * on the path bias accounting state for a circuit.
2856 * NOTE: These state values are enumerated in the order for which we
2857 * expect circuits to transition through them. If you add states,
2858 * you need to preserve this overall ordering. The various pathbias
2859 * state transition and accounting functions (pathbias_mark_* and
2860 * pathbias_count_*) contain ordinal comparisons to enforce proper
2861 * state transitions for corrections.
2863 * This state machine and the associated logic was created to prevent
2864 * miscounting due to unknown cases of circuit reuse. See also tickets
2865 * #6475 and #7802.
2867 typedef enum {
2868 /** This circuit is "new". It has not yet completed a first hop
2869 * or been counted by the path bias code. */
2870 PATH_STATE_NEW_CIRC = 0,
2871 /** This circuit has completed one/two hops, and has been counted by
2872 * the path bias logic. */
2873 PATH_STATE_BUILD_ATTEMPTED = 1,
2874 /** This circuit has been completely built */
2875 PATH_STATE_BUILD_SUCCEEDED = 2,
2876 /** Did we try to attach any SOCKS streams or hidserv introductions to
2877 * this circuit?
2879 * Note: If we ever implement end-to-end stream timing through test
2880 * stream probes (#5707), we must *not* set this for those probes
2881 * (or any other automatic streams) because the adversary could
2882 * just tag at a later point.
2884 PATH_STATE_USE_ATTEMPTED = 3,
2885 /** Did any SOCKS streams or hidserv introductions actually succeed on
2886 * this circuit?
2888 * If any streams detatch/fail from this circuit, the code transitions
2889 * the circuit back to PATH_STATE_USE_ATTEMPTED to ensure we probe. See
2890 * pathbias_mark_use_rollback() for that.
2892 PATH_STATE_USE_SUCCEEDED = 4,
2895 * This is a special state to indicate that we got a corrupted
2896 * relay cell on a circuit and we don't intend to probe it.
2898 PATH_STATE_USE_FAILED = 5,
2901 * This is a special state to indicate that we already counted
2902 * the circuit. Used to guard against potential state machine
2903 * violations.
2905 PATH_STATE_ALREADY_COUNTED = 6,
2906 } path_state_t;
2908 /** An origin_circuit_t holds data necessary to build and use a circuit.
2910 typedef struct origin_circuit_t {
2911 circuit_t base_;
2913 /** Linked list of AP streams (or EXIT streams if hidden service)
2914 * associated with this circuit. */
2915 edge_connection_t *p_streams;
2916 /** Build state for this circuit. It includes the intended path
2917 * length, the chosen exit router, rendezvous information, etc.
2919 cpath_build_state_t *build_state;
2920 /** The doubly-linked list of crypt_path_t entries, one per hop,
2921 * for this circuit. This includes ciphers for each hop,
2922 * integrity-checking digests for each hop, and package/delivery
2923 * windows for each hop.
2925 crypt_path_t *cpath;
2927 /** Holds all rendezvous data on either client or service side. */
2928 rend_data_t *rend_data;
2930 /** How many more relay_early cells can we send on this circuit, according
2931 * to the specification? */
2932 unsigned int remaining_relay_early_cells : 4;
2934 /** Set if this circuit is insanely old and we already informed the user */
2935 unsigned int is_ancient : 1;
2937 /** Set if this circuit has already been opened. Used to detect
2938 * cannibalized circuits. */
2939 unsigned int has_opened : 1;
2942 * Path bias state machine. Used to ensure integrity of our
2943 * circuit building and usage accounting. See path_state_t
2944 * for more details.
2946 ENUM_BF(path_state_t) path_state : 3;
2948 /* If this flag is set, we should not consider attaching any more
2949 * connections to this circuit. */
2950 unsigned int unusable_for_new_conns : 1;
2953 * Tristate variable to guard against pathbias miscounting
2954 * due to circuit purpose transitions changing the decision
2955 * of pathbias_should_count(). This variable is informational
2956 * only. The current results of pathbias_should_count() are
2957 * the official decision for pathbias accounting.
2959 uint8_t pathbias_shouldcount;
2960 #define PATHBIAS_SHOULDCOUNT_UNDECIDED 0
2961 #define PATHBIAS_SHOULDCOUNT_IGNORED 1
2962 #define PATHBIAS_SHOULDCOUNT_COUNTED 2
2964 /** For path probing. Store the temporary probe stream ID
2965 * for response comparison */
2966 streamid_t pathbias_probe_id;
2968 /** For path probing. Store the temporary probe address nonce
2969 * (in host byte order) for response comparison. */
2970 uint32_t pathbias_probe_nonce;
2972 /** Set iff this is a hidden-service circuit which has timed out
2973 * according to our current circuit-build timeout, but which has
2974 * been kept around because it might still succeed in connecting to
2975 * its destination, and which is not a fully-connected rendezvous
2976 * circuit.
2978 * (We clear this flag for client-side rendezvous circuits when they
2979 * are 'joined' to the other side's rendezvous circuit, so that
2980 * connection_ap_handshake_attach_circuit can put client streams on
2981 * the circuit. We also clear this flag for service-side rendezvous
2982 * circuits when they are 'joined' to a client's rend circ, but only
2983 * for symmetry with the client case. Client-side introduction
2984 * circuits are closed when we get a joined rend circ, and
2985 * service-side introduction circuits never have this flag set.) */
2986 unsigned int hs_circ_has_timed_out : 1;
2988 /** Set iff this circuit has been given a relaxed timeout because
2989 * no circuits have opened. Used to prevent spamming logs. */
2990 unsigned int relaxed_timeout : 1;
2992 /** Set iff this is a service-side rendezvous circuit for which a
2993 * new connection attempt has been launched. We consider launching
2994 * a new service-side rend circ to a client when the previous one
2995 * fails; now that we don't necessarily close a service-side rend
2996 * circ when we launch a new one to the same client, this flag keeps
2997 * us from launching two retries for the same failed rend circ. */
2998 unsigned int hs_service_side_rend_circ_has_been_relaunched : 1;
3000 /** What commands were sent over this circuit that decremented the
3001 * RELAY_EARLY counter? This is for debugging task 878. */
3002 uint8_t relay_early_commands[MAX_RELAY_EARLY_CELLS_PER_CIRCUIT];
3004 /** How many RELAY_EARLY cells have been sent over this circuit? This is
3005 * for debugging task 878, too. */
3006 int relay_early_cells_sent;
3008 /** The next stream_id that will be tried when we're attempting to
3009 * construct a new AP stream originating at this circuit. */
3010 streamid_t next_stream_id;
3012 /* The intro key replaces the hidden service's public key if purpose is
3013 * S_ESTABLISH_INTRO or S_INTRO, provided that no unversioned rendezvous
3014 * descriptor is used. */
3015 crypto_pk_t *intro_key;
3017 /** Quasi-global identifier for this circuit; used for control.c */
3018 /* XXXX NM This can get re-used after 2**32 circuits. */
3019 uint32_t global_identifier;
3021 /** True if we have associated one stream to this circuit, thereby setting
3022 * the isolation paramaters for this circuit. Note that this doesn't
3023 * necessarily mean that we've <em>attached</em> any streams to the circuit:
3024 * we may only have marked up this circuit during the launch process.
3026 unsigned int isolation_values_set : 1;
3027 /** True iff any stream has <em>ever</em> been attached to this circuit.
3029 * In a better world we could use timestamp_dirty for this, but
3030 * timestamp_dirty is far too overloaded at the moment.
3032 unsigned int isolation_any_streams_attached : 1;
3034 /** A bitfield of ISO_* flags for every isolation field such that this
3035 * circuit has had streams with more than one value for that field
3036 * attached to it. */
3037 uint8_t isolation_flags_mixed;
3039 /** @name Isolation parameters
3041 * If any streams have been associated with this circ (isolation_values_set
3042 * == 1), and all streams associated with the circuit have had the same
3043 * value for some field ((isolation_flags_mixed & ISO_FOO) == 0), then these
3044 * elements hold the value for that field.
3046 * Note again that "associated" is not the same as "attached": we
3047 * preliminarily associate streams with a circuit while the circuit is being
3048 * launched, so that we can tell whether we need to launch more circuits.
3050 * @{
3052 uint8_t client_proto_type;
3053 uint8_t client_proto_socksver;
3054 uint16_t dest_port;
3055 tor_addr_t client_addr;
3056 char *dest_address;
3057 int session_group;
3058 unsigned nym_epoch;
3059 size_t socks_username_len;
3060 uint8_t socks_password_len;
3061 /* Note that the next two values are NOT NUL-terminated; see
3062 socks_username_len and socks_password_len for their lengths. */
3063 char *socks_username;
3064 char *socks_password;
3065 /** Global identifier for the first stream attached here; used by
3066 * ISO_STREAM. */
3067 uint64_t associated_isolated_stream_global_id;
3068 /**@}*/
3069 /** A list of addr_policy_t for this circuit in particular. Used by
3070 * adjust_exit_policy_from_exitpolicy_failure.
3072 smartlist_t *prepend_policy;
3073 } origin_circuit_t;
3075 struct onion_queue_t;
3077 /** An or_circuit_t holds information needed to implement a circuit at an
3078 * OR. */
3079 typedef struct or_circuit_t {
3080 circuit_t base_;
3082 /** Next circuit in the doubly-linked ring of circuits waiting to add
3083 * cells to p_chan. NULL if we have no cells pending, or if we're not
3084 * linked to an OR connection. */
3085 struct circuit_t *next_active_on_p_chan;
3086 /** Previous circuit in the doubly-linked ring of circuits waiting to add
3087 * cells to p_chan. NULL if we have no cells pending, or if we're not
3088 * linked to an OR connection. */
3089 struct circuit_t *prev_active_on_p_chan;
3090 /** Pointer to an entry on the onion queue, if this circuit is waiting for a
3091 * chance to give an onionskin to a cpuworker. Used only in onion.c */
3092 struct onion_queue_t *onionqueue_entry;
3094 /** The circuit_id used in the previous (backward) hop of this circuit. */
3095 circid_t p_circ_id;
3096 /** Queue of cells waiting to be transmitted on p_conn. */
3097 cell_queue_t p_chan_cells;
3098 /** The channel that is previous in this circuit. */
3099 channel_t *p_chan;
3101 * Circuit mux associated with p_chan to which this circuit is attached;
3102 * NULL if we have no p_chan.
3104 circuitmux_t *p_mux;
3105 /** Linked list of Exit streams associated with this circuit. */
3106 edge_connection_t *n_streams;
3107 /** Linked list of Exit streams associated with this circuit that are
3108 * still being resolved. */
3109 edge_connection_t *resolving_streams;
3110 /** The cipher used by intermediate hops for cells heading toward the
3111 * OP. */
3112 crypto_cipher_t *p_crypto;
3113 /** The cipher used by intermediate hops for cells heading away from
3114 * the OP. */
3115 crypto_cipher_t *n_crypto;
3117 /** The integrity-checking digest used by intermediate hops, for
3118 * cells packaged here and heading towards the OP.
3120 crypto_digest_t *p_digest;
3121 /** The integrity-checking digest used by intermediate hops, for
3122 * cells packaged at the OP and arriving here.
3124 crypto_digest_t *n_digest;
3126 /** Points to spliced circuit if purpose is REND_ESTABLISHED, and circuit
3127 * is not marked for close. */
3128 struct or_circuit_t *rend_splice;
3130 #if REND_COOKIE_LEN >= DIGEST_LEN
3131 #define REND_TOKEN_LEN REND_COOKIE_LEN
3132 #else
3133 #define REND_TOKEN_LEN DIGEST_LEN
3134 #endif
3136 /** A hash of location-hidden service's PK if purpose is INTRO_POINT, or a
3137 * rendezvous cookie if purpose is REND_POINT_WAITING. Filled with zeroes
3138 * otherwise.
3139 * ???? move to a subtype or adjunct structure? Wastes 20 bytes. -NM
3141 char rend_token[REND_TOKEN_LEN];
3143 /* ???? move to a subtype or adjunct structure? Wastes 20 bytes -NM */
3144 /** Stores KH for the handshake. */
3145 char rend_circ_nonce[DIGEST_LEN];/* KH in tor-spec.txt */
3147 /** How many more relay_early cells can we send on this circuit, according
3148 * to the specification? */
3149 unsigned int remaining_relay_early_cells : 4;
3151 /** True iff this circuit was made with a CREATE_FAST cell. */
3152 unsigned int is_first_hop : 1;
3154 /** Number of cells that were removed from circuit queue; reset every
3155 * time when writing buffer stats to disk. */
3156 uint32_t processed_cells;
3158 /** Total time in milliseconds that cells spent in both app-ward and
3159 * exit-ward queues of this circuit; reset every time when writing
3160 * buffer stats to disk. */
3161 uint64_t total_cell_waiting_time;
3162 } or_circuit_t;
3164 /** Convert a circuit subtype to a circuit_t. */
3165 #define TO_CIRCUIT(x) (&((x)->base_))
3167 /** Convert a circuit_t* to a pointer to the enclosing or_circuit_t. Assert
3168 * if the cast is impossible. */
3169 static or_circuit_t *TO_OR_CIRCUIT(circuit_t *);
3170 /** Convert a circuit_t* to a pointer to the enclosing origin_circuit_t.
3171 * Assert if the cast is impossible. */
3172 static origin_circuit_t *TO_ORIGIN_CIRCUIT(circuit_t *);
3174 static INLINE or_circuit_t *TO_OR_CIRCUIT(circuit_t *x)
3176 tor_assert(x->magic == OR_CIRCUIT_MAGIC);
3177 return DOWNCAST(or_circuit_t, x);
3179 static INLINE origin_circuit_t *TO_ORIGIN_CIRCUIT(circuit_t *x)
3181 tor_assert(x->magic == ORIGIN_CIRCUIT_MAGIC);
3182 return DOWNCAST(origin_circuit_t, x);
3185 /** Bitfield type: things that we're willing to use invalid routers for. */
3186 typedef enum invalid_router_usage_t {
3187 ALLOW_INVALID_ENTRY =1,
3188 ALLOW_INVALID_EXIT =2,
3189 ALLOW_INVALID_MIDDLE =4,
3190 ALLOW_INVALID_RENDEZVOUS =8,
3191 ALLOW_INVALID_INTRODUCTION=16,
3192 } invalid_router_usage_t;
3194 /* limits for TCP send and recv buffer size used for constrained sockets */
3195 #define MIN_CONSTRAINED_TCP_BUFFER 2048
3196 #define MAX_CONSTRAINED_TCP_BUFFER 262144 /* 256k */
3198 /** @name Isolation flags
3200 Ways to isolate client streams
3204 /** Isolate based on destination port */
3205 #define ISO_DESTPORT (1u<<0)
3206 /** Isolate based on destination address */
3207 #define ISO_DESTADDR (1u<<1)
3208 /** Isolate based on SOCKS authentication */
3209 #define ISO_SOCKSAUTH (1u<<2)
3210 /** Isolate based on client protocol choice */
3211 #define ISO_CLIENTPROTO (1u<<3)
3212 /** Isolate based on client address */
3213 #define ISO_CLIENTADDR (1u<<4)
3214 /** Isolate based on session group (always on). */
3215 #define ISO_SESSIONGRP (1u<<5)
3216 /** Isolate based on newnym epoch (always on). */
3217 #define ISO_NYM_EPOCH (1u<<6)
3218 /** Isolate all streams (Internal only). */
3219 #define ISO_STREAM (1u<<7)
3220 /**@}*/
3222 /** Default isolation level for ports. */
3223 #define ISO_DEFAULT (ISO_CLIENTADDR|ISO_SOCKSAUTH|ISO_SESSIONGRP|ISO_NYM_EPOCH)
3225 /** Indicates that we haven't yet set a session group on a port_cfg_t. */
3226 #define SESSION_GROUP_UNSET -1
3227 /** Session group reserved for directory connections */
3228 #define SESSION_GROUP_DIRCONN -2
3229 /** Session group reserved for resolve requests launched by a controller */
3230 #define SESSION_GROUP_CONTROL_RESOLVE -3
3231 /** First automatically allocated session group number */
3232 #define SESSION_GROUP_FIRST_AUTO -4
3234 /** Configuration for a single port that we're listening on. */
3235 typedef struct port_cfg_t {
3236 tor_addr_t addr; /**< The actual IP to listen on, if !is_unix_addr. */
3237 int port; /**< The configured port, or CFG_AUTO_PORT to tell Tor to pick its
3238 * own port. */
3239 uint8_t type; /**< One of CONN_TYPE_*_LISTENER */
3240 unsigned is_unix_addr : 1; /**< True iff this is an AF_UNIX address. */
3242 /* Client port types (socks, dns, trans, natd) only: */
3243 uint8_t isolation_flags; /**< Zero or more isolation flags */
3244 int session_group; /**< A session group, or -1 if this port is not in a
3245 * session group. */
3247 /* Server port types (or, dir) only: */
3248 unsigned int no_advertise : 1;
3249 unsigned int no_listen : 1;
3250 unsigned int all_addrs : 1;
3251 unsigned int bind_ipv4_only : 1;
3252 unsigned int bind_ipv6_only : 1;
3254 /* Client port types only: */
3255 unsigned int ipv4_traffic : 1;
3256 unsigned int ipv6_traffic : 1;
3257 unsigned int prefer_ipv6 : 1;
3259 /** For a socks listener: should we cache IPv4/IPv6 DNS information that
3260 * exit nodes tell us?
3262 * @{ */
3263 unsigned int cache_ipv4_answers : 1;
3264 unsigned int cache_ipv6_answers : 1;
3265 /** @} */
3266 /** For a socks listeners: if we find an answer in our client-side DNS cache,
3267 * should we use it?
3269 * @{ */
3270 unsigned int use_cached_ipv4_answers : 1;
3271 unsigned int use_cached_ipv6_answers : 1;
3272 /** @} */
3273 /** For socks listeners: When we can automap an address to IPv4 or IPv6,
3274 * do we prefer IPv6? */
3275 unsigned int prefer_ipv6_virtaddr : 1;
3277 /* Unix sockets only: */
3278 /** Path for an AF_UNIX address */
3279 char unix_addr[FLEXIBLE_ARRAY_MEMBER];
3280 } port_cfg_t;
3282 /** Ordinary configuration line. */
3283 #define CONFIG_LINE_NORMAL 0
3284 /** Appends to previous configuration for the same option, even if we
3285 * would ordinary replace it. */
3286 #define CONFIG_LINE_APPEND 1
3287 /* Removes all previous configuration for an option. */
3288 #define CONFIG_LINE_CLEAR 2
3290 /** A linked list of lines in a config file. */
3291 typedef struct config_line_t {
3292 char *key;
3293 char *value;
3294 struct config_line_t *next;
3295 /** What special treatment (if any) does this line require? */
3296 unsigned int command:2;
3297 /** If true, subsequent assignments to this linelist should replace
3298 * it, not extend it. Set only on the first item in a linelist in an
3299 * or_options_t. */
3300 unsigned int fragile:1;
3301 } config_line_t;
3303 typedef struct routerset_t routerset_t;
3305 /** A magic value for the (Socks|OR|...)Port options below, telling Tor
3306 * to pick its own port. */
3307 #define CFG_AUTO_PORT 0xc4005e
3309 /** Configuration options for a Tor process. */
3310 typedef struct {
3311 uint32_t magic_;
3313 /** What should the tor process actually do? */
3314 enum {
3315 CMD_RUN_TOR=0, CMD_LIST_FINGERPRINT, CMD_HASH_PASSWORD,
3316 CMD_VERIFY_CONFIG, CMD_RUN_UNITTESTS
3317 } command;
3318 const char *command_arg; /**< Argument for command-line option. */
3320 config_line_t *Logs; /**< New-style list of configuration lines
3321 * for logs */
3322 int LogTimeGranularity; /**< Log resolution in milliseconds. */
3324 int LogMessageDomains; /**< Boolean: Should we log the domain(s) in which
3325 * each log message occurs? */
3327 char *DebugLogFile; /**< Where to send verbose log messages. */
3328 char *DataDirectory; /**< OR only: where to store long-term data. */
3329 char *Nickname; /**< OR only: nickname of this onion router. */
3330 char *Address; /**< OR only: configured address for this onion router. */
3331 char *PidFile; /**< Where to store PID of Tor process. */
3333 int DynamicDHGroups; /**< Dynamic generation of prime moduli for use in DH.*/
3335 routerset_t *ExitNodes; /**< Structure containing nicknames, digests,
3336 * country codes and IP address patterns of ORs to
3337 * consider as exits. */
3338 routerset_t *EntryNodes;/**< Structure containing nicknames, digests,
3339 * country codes and IP address patterns of ORs to
3340 * consider as entry points. */
3341 int StrictNodes; /**< Boolean: When none of our EntryNodes or ExitNodes
3342 * are up, or we need to access a node in ExcludeNodes,
3343 * do we just fail instead? */
3344 routerset_t *ExcludeNodes;/**< Structure containing nicknames, digests,
3345 * country codes and IP address patterns of ORs
3346 * not to use in circuits. But see StrictNodes
3347 * above. */
3348 routerset_t *ExcludeExitNodes;/**< Structure containing nicknames, digests,
3349 * country codes and IP address patterns of
3350 * ORs not to consider as exits. */
3352 /** Union of ExcludeNodes and ExcludeExitNodes */
3353 routerset_t *ExcludeExitNodesUnion_;
3355 int DisableAllSwap; /**< Boolean: Attempt to call mlockall() on our
3356 * process for all current and future memory. */
3358 /** List of "entry", "middle", "exit", "introduction", "rendezvous". */
3359 smartlist_t *AllowInvalidNodes;
3360 /** Bitmask; derived from AllowInvalidNodes. */
3361 invalid_router_usage_t AllowInvalid_;
3362 config_line_t *ExitPolicy; /**< Lists of exit policy components. */
3363 int ExitPolicyRejectPrivate; /**< Should we not exit to local addresses? */
3364 config_line_t *SocksPolicy; /**< Lists of socks policy components */
3365 config_line_t *DirPolicy; /**< Lists of dir policy components */
3366 /** Addresses to bind for listening for SOCKS connections. */
3367 config_line_t *SocksListenAddress;
3368 /** Addresses to bind for listening for transparent pf/netfilter
3369 * connections. */
3370 config_line_t *TransListenAddress;
3371 /** Addresses to bind for listening for transparent natd connections */
3372 config_line_t *NATDListenAddress;
3373 /** Addresses to bind for listening for SOCKS connections. */
3374 config_line_t *DNSListenAddress;
3375 /** Addresses to bind for listening for OR connections. */
3376 config_line_t *ORListenAddress;
3377 /** Addresses to bind for listening for directory connections. */
3378 config_line_t *DirListenAddress;
3379 /** Addresses to bind for listening for control connections. */
3380 config_line_t *ControlListenAddress;
3381 /** Local address to bind outbound sockets */
3382 config_line_t *OutboundBindAddress;
3383 /** IPv4 address derived from OutboundBindAddress. */
3384 tor_addr_t OutboundBindAddressIPv4_;
3385 /** IPv6 address derived from OutboundBindAddress. */
3386 tor_addr_t OutboundBindAddressIPv6_;
3387 /** Directory server only: which versions of
3388 * Tor should we tell users to run? */
3389 config_line_t *RecommendedVersions;
3390 config_line_t *RecommendedClientVersions;
3391 config_line_t *RecommendedServerVersions;
3392 /** Whether dirservers allow router descriptors with private IPs. */
3393 int DirAllowPrivateAddresses;
3394 /** Whether routers accept EXTEND cells to routers with private IPs. */
3395 int ExtendAllowPrivateAddresses;
3396 char *User; /**< Name of user to run Tor as. */
3397 char *Group; /**< Name of group to run Tor as. */
3398 config_line_t *ORPort_lines; /**< Ports to listen on for OR connections. */
3399 /** Ports to listen on for SOCKS connections. */
3400 config_line_t *SocksPort_lines;
3401 /** Ports to listen on for transparent pf/netfilter connections. */
3402 config_line_t *TransPort_lines;
3403 config_line_t *NATDPort_lines; /**< Ports to listen on for transparent natd
3404 * connections. */
3405 config_line_t *ControlPort_lines; /**< Ports to listen on for control
3406 * connections. */
3407 config_line_t *ControlSocket; /**< List of Unix Domain Sockets to listen on
3408 * for control connections. */
3410 int ControlSocketsGroupWritable; /**< Boolean: Are control sockets g+rw? */
3411 /** Ports to listen on for directory connections. */
3412 config_line_t *DirPort_lines;
3413 config_line_t *DNSPort_lines; /**< Ports to listen on for DNS requests. */
3415 /** @name port booleans
3417 * Derived booleans: True iff there is a non-listener port on an AF_INET or
3418 * AF_INET6 address of the given type configured in one of the _lines
3419 * options above.
3421 * @{
3423 unsigned int ORPort_set : 1;
3424 unsigned int SocksPort_set : 1;
3425 unsigned int TransPort_set : 1;
3426 unsigned int NATDPort_set : 1;
3427 unsigned int ControlPort_set : 1;
3428 unsigned int DirPort_set : 1;
3429 unsigned int DNSPort_set : 1;
3430 /**@}*/
3432 int AssumeReachable; /**< Whether to publish our descriptor regardless. */
3433 int AuthoritativeDir; /**< Boolean: is this an authoritative directory? */
3434 int V1AuthoritativeDir; /**< Boolean: is this an authoritative directory
3435 * for version 1 directories? */
3436 int V2AuthoritativeDir; /**< Boolean: is this an authoritative directory
3437 * for version 2 directories? */
3438 int V3AuthoritativeDir; /**< Boolean: is this an authoritative directory
3439 * for version 3 directories? */
3440 int HSAuthoritativeDir; /**< Boolean: does this an authoritative directory
3441 * handle hidden service requests? */
3442 int NamingAuthoritativeDir; /**< Boolean: is this an authoritative directory
3443 * that's willing to bind names? */
3444 int VersioningAuthoritativeDir; /**< Boolean: is this an authoritative
3445 * directory that's willing to recommend
3446 * versions? */
3447 int BridgeAuthoritativeDir; /**< Boolean: is this an authoritative directory
3448 * that aggregates bridge descriptors? */
3450 /** If set on a bridge authority, it will answer requests on its dirport
3451 * for bridge statuses -- but only if the requests use this password. */
3452 char *BridgePassword;
3453 /** If BridgePassword is set, this is a SHA256 digest of the basic http
3454 * authenticator for it. Used so we can do a time-independent comparison. */
3455 char *BridgePassword_AuthDigest_;
3457 int UseBridges; /**< Boolean: should we start all circuits with a bridge? */
3458 config_line_t *Bridges; /**< List of bootstrap bridge addresses. */
3460 config_line_t *ClientTransportPlugin; /**< List of client
3461 transport plugins. */
3463 config_line_t *ServerTransportPlugin; /**< List of client
3464 transport plugins. */
3466 /** List of TCP/IP addresses that transports should listen at. */
3467 config_line_t *ServerTransportListenAddr;
3469 int BridgeRelay; /**< Boolean: are we acting as a bridge relay? We make
3470 * this explicit so we can change how we behave in the
3471 * future. */
3473 /** Boolean: if we know the bridge's digest, should we get new
3474 * descriptors from the bridge authorities or from the bridge itself? */
3475 int UpdateBridgesFromAuthority;
3477 int AvoidDiskWrites; /**< Boolean: should we never cache things to disk?
3478 * Not used yet. */
3479 int ClientOnly; /**< Boolean: should we never evolve into a server role? */
3480 /** To what authority types do we publish our descriptor? Choices are
3481 * "v1", "v2", "v3", "bridge", or "". */
3482 smartlist_t *PublishServerDescriptor;
3483 /** A bitfield of authority types, derived from PublishServerDescriptor. */
3484 dirinfo_type_t PublishServerDescriptor_;
3485 /** Boolean: do we publish hidden service descriptors to the HS auths? */
3486 int PublishHidServDescriptors;
3487 int FetchServerDescriptors; /**< Do we fetch server descriptors as normal? */
3488 int FetchHidServDescriptors; /**< and hidden service descriptors? */
3489 int FetchV2Networkstatus; /**< Do we fetch v2 networkstatus documents when
3490 * we don't need to? */
3491 int HidServDirectoryV2; /**< Do we participate in the HS DHT? */
3493 int VoteOnHidServDirectoriesV2; /**< As a directory authority, vote on
3494 * assignment of the HSDir flag? */
3495 int MinUptimeHidServDirectoryV2; /**< As directory authority, accept hidden
3496 * service directories after what time? */
3498 int FetchUselessDescriptors; /**< Do we fetch non-running descriptors too? */
3499 int AllDirActionsPrivate; /**< Should every directory action be sent
3500 * through a Tor circuit? */
3502 /** Run in 'tor2web mode'? (I.e. only make client connections to hidden
3503 * services, and use a single hop for all hidden-service-related
3504 * circuits.) */
3505 int Tor2webMode;
3507 /** Close hidden service client circuits immediately when they reach
3508 * the normal circuit-build timeout, even if they have already sent
3509 * an INTRODUCE1 cell on its way to the service. */
3510 int CloseHSClientCircuitsImmediatelyOnTimeout;
3512 /** Close hidden-service-side rendezvous circuits immediately when
3513 * they reach the normal circuit-build timeout. */
3514 int CloseHSServiceRendCircuitsImmediatelyOnTimeout;
3516 int ConnLimit; /**< Demanded minimum number of simultaneous connections. */
3517 int ConnLimit_; /**< Maximum allowed number of simultaneous connections. */
3518 int RunAsDaemon; /**< If true, run in the background. (Unix only) */
3519 int FascistFirewall; /**< Whether to prefer ORs reachable on open ports. */
3520 smartlist_t *FirewallPorts; /**< Which ports our firewall allows
3521 * (strings). */
3522 config_line_t *ReachableAddresses; /**< IP:ports our firewall allows. */
3523 config_line_t *ReachableORAddresses; /**< IP:ports for OR conns. */
3524 config_line_t *ReachableDirAddresses; /**< IP:ports for Dir conns. */
3526 int ConstrainedSockets; /**< Shrink xmit and recv socket buffers. */
3527 uint64_t ConstrainedSockSize; /**< Size of constrained buffers. */
3529 /** Whether we should drop exit streams from Tors that we don't know are
3530 * relays. One of "0" (never refuse), "1" (always refuse), or "-1" (do
3531 * what the consensus says, defaulting to 'refuse' if the consensus says
3532 * nothing). */
3533 int RefuseUnknownExits;
3535 /** Application ports that require all nodes in circ to have sufficient
3536 * uptime. */
3537 smartlist_t *LongLivedPorts;
3538 /** Application ports that are likely to be unencrypted and
3539 * unauthenticated; we reject requests for them to prevent the
3540 * user from screwing up and leaking plaintext secrets to an
3541 * observer somewhere on the Internet. */
3542 smartlist_t *RejectPlaintextPorts;
3543 /** Related to RejectPlaintextPorts above, except this config option
3544 * controls whether we warn (in the log and via a controller status
3545 * event) every time a risky connection is attempted. */
3546 smartlist_t *WarnPlaintextPorts;
3547 /** Should we try to reuse the same exit node for a given host */
3548 smartlist_t *TrackHostExits;
3549 int TrackHostExitsExpire; /**< Number of seconds until we expire an
3550 * addressmap */
3551 config_line_t *AddressMap; /**< List of address map directives. */
3552 int AutomapHostsOnResolve; /**< If true, when we get a resolve request for a
3553 * hostname ending with one of the suffixes in
3554 * <b>AutomapHostsSuffixes</b>, map it to a
3555 * virtual address. */
3556 smartlist_t *AutomapHostsSuffixes; /**< List of suffixes for
3557 * <b>AutomapHostsOnResolve</b>. */
3558 int RendPostPeriod; /**< How often do we post each rendezvous service
3559 * descriptor? Remember to publish them independently. */
3560 int KeepalivePeriod; /**< How often do we send padding cells to keep
3561 * connections alive? */
3562 int SocksTimeout; /**< How long do we let a socks connection wait
3563 * unattached before we fail it? */
3564 int LearnCircuitBuildTimeout; /**< If non-zero, we attempt to learn a value
3565 * for CircuitBuildTimeout based on timeout
3566 * history */
3567 int CircuitBuildTimeout; /**< Cull non-open circuits that were born at
3568 * least this many seconds ago. Used until
3569 * adaptive algorithm learns a new value. */
3570 int CircuitIdleTimeout; /**< Cull open clean circuits that were born
3571 * at least this many seconds ago. */
3572 int CircuitStreamTimeout; /**< If non-zero, detach streams from circuits
3573 * and try a new circuit if the stream has been
3574 * waiting for this many seconds. If zero, use
3575 * our default internal timeout schedule. */
3576 int MaxOnionQueueDelay; /**<DOCDOC*/
3577 int NewCircuitPeriod; /**< How long do we use a circuit before building
3578 * a new one? */
3579 int MaxCircuitDirtiness; /**< Never use circs that were first used more than
3580 this interval ago. */
3581 uint64_t BandwidthRate; /**< How much bandwidth, on average, are we willing
3582 * to use in a second? */
3583 uint64_t BandwidthBurst; /**< How much bandwidth, at maximum, are we willing
3584 * to use in a second? */
3585 uint64_t MaxAdvertisedBandwidth; /**< How much bandwidth are we willing to
3586 * tell people we have? */
3587 uint64_t RelayBandwidthRate; /**< How much bandwidth, on average, are we
3588 * willing to use for all relayed conns? */
3589 uint64_t RelayBandwidthBurst; /**< How much bandwidth, at maximum, will we
3590 * use in a second for all relayed conns? */
3591 uint64_t PerConnBWRate; /**< Long-term bw on a single TLS conn, if set. */
3592 uint64_t PerConnBWBurst; /**< Allowed burst on a single TLS conn, if set. */
3593 int NumCPUs; /**< How many CPUs should we try to use? */
3594 //int RunTesting; /**< If true, create testing circuits to measure how well the
3595 // * other ORs are running. */
3596 config_line_t *RendConfigLines; /**< List of configuration lines
3597 * for rendezvous services. */
3598 config_line_t *HidServAuth; /**< List of configuration lines for client-side
3599 * authorizations for hidden services */
3600 char *ContactInfo; /**< Contact info to be published in the directory. */
3602 int HeartbeatPeriod; /**< Log heartbeat messages after this many seconds
3603 * have passed. */
3605 char *HTTPProxy; /**< hostname[:port] to use as http proxy, if any. */
3606 tor_addr_t HTTPProxyAddr; /**< Parsed IPv4 addr for http proxy, if any. */
3607 uint16_t HTTPProxyPort; /**< Parsed port for http proxy, if any. */
3608 char *HTTPProxyAuthenticator; /**< username:password string, if any. */
3610 char *HTTPSProxy; /**< hostname[:port] to use as https proxy, if any. */
3611 tor_addr_t HTTPSProxyAddr; /**< Parsed addr for https proxy, if any. */
3612 uint16_t HTTPSProxyPort; /**< Parsed port for https proxy, if any. */
3613 char *HTTPSProxyAuthenticator; /**< username:password string, if any. */
3615 char *Socks4Proxy; /**< hostname:port to use as a SOCKS4 proxy, if any. */
3616 tor_addr_t Socks4ProxyAddr; /**< Derived from Socks4Proxy. */
3617 uint16_t Socks4ProxyPort; /**< Derived from Socks4Proxy. */
3619 char *Socks5Proxy; /**< hostname:port to use as a SOCKS5 proxy, if any. */
3620 tor_addr_t Socks5ProxyAddr; /**< Derived from Sock5Proxy. */
3621 uint16_t Socks5ProxyPort; /**< Derived from Socks5Proxy. */
3622 char *Socks5ProxyUsername; /**< Username for SOCKS5 authentication, if any */
3623 char *Socks5ProxyPassword; /**< Password for SOCKS5 authentication, if any */
3625 /** List of configuration lines for replacement directory authorities.
3626 * If you just want to replace one class of authority at a time,
3627 * use the "Alternate*Authority" options below instead. */
3628 config_line_t *DirAuthorities;
3630 /** List of fallback directory servers */
3631 config_line_t *FallbackDir;
3633 /** Weight to apply to all directory authority rates if considering them
3634 * along with fallbackdirs */
3635 double DirAuthorityFallbackRate;
3637 /** If set, use these main (currently v3) directory authorities and
3638 * not the default ones. */
3639 config_line_t *AlternateDirAuthority;
3641 /** If set, use these bridge authorities and not the default one. */
3642 config_line_t *AlternateBridgeAuthority;
3644 /** If set, use these HS authorities and not the default ones. */
3645 config_line_t *AlternateHSAuthority;
3647 char *MyFamily; /**< Declared family for this OR. */
3648 config_line_t *NodeFamilies; /**< List of config lines for
3649 * node families */
3650 smartlist_t *NodeFamilySets; /**< List of parsed NodeFamilies values. */
3651 config_line_t *AuthDirBadDir; /**< Address policy for descriptors to
3652 * mark as bad dir mirrors. */
3653 config_line_t *AuthDirBadExit; /**< Address policy for descriptors to
3654 * mark as bad exits. */
3655 config_line_t *AuthDirReject; /**< Address policy for descriptors to
3656 * reject. */
3657 config_line_t *AuthDirInvalid; /**< Address policy for descriptors to
3658 * never mark as valid. */
3659 /** @name AuthDir...CC
3661 * Lists of country codes to mark as BadDir, BadExit, or Invalid, or to
3662 * reject entirely.
3664 * @{
3666 smartlist_t *AuthDirBadDirCCs;
3667 smartlist_t *AuthDirBadExitCCs;
3668 smartlist_t *AuthDirInvalidCCs;
3669 smartlist_t *AuthDirRejectCCs;
3670 /**@}*/
3672 int AuthDirListBadDirs; /**< True iff we should list bad dirs,
3673 * and vote for all other dir mirrors as good. */
3674 int AuthDirListBadExits; /**< True iff we should list bad exits,
3675 * and vote for all other exits as good. */
3676 int AuthDirRejectUnlisted; /**< Boolean: do we reject all routers that
3677 * aren't named in our fingerprint file? */
3678 int AuthDirMaxServersPerAddr; /**< Do not permit more than this
3679 * number of servers per IP address. */
3680 int AuthDirMaxServersPerAuthAddr; /**< Do not permit more than this
3681 * number of servers per IP address shared
3682 * with an authority. */
3683 int AuthDirHasIPv6Connectivity; /**< Boolean: are we on IPv6? */
3685 /** If non-zero, always vote the Fast flag for any relay advertising
3686 * this amount of capacity or more. */
3687 uint64_t AuthDirFastGuarantee;
3689 /** If non-zero, this advertised capacity or more is always sufficient
3690 * to satisfy the bandwidth requirement for the Guard flag. */
3691 uint64_t AuthDirGuardBWGuarantee;
3693 char *AccountingStart; /**< How long is the accounting interval, and when
3694 * does it start? */
3695 uint64_t AccountingMax; /**< How many bytes do we allow per accounting
3696 * interval before hibernation? 0 for "never
3697 * hibernate." */
3699 /** Base64-encoded hash of accepted passwords for the control system. */
3700 config_line_t *HashedControlPassword;
3701 /** As HashedControlPassword, but not saved. */
3702 config_line_t *HashedControlSessionPassword;
3704 int CookieAuthentication; /**< Boolean: do we enable cookie-based auth for
3705 * the control system? */
3706 char *CookieAuthFile; /**< Location of a cookie authentication file. */
3707 int CookieAuthFileGroupReadable; /**< Boolean: Is the CookieAuthFile g+r? */
3708 int LeaveStreamsUnattached; /**< Boolean: Does Tor attach new streams to
3709 * circuits itself (0), or does it expect a controller
3710 * to cope? (1) */
3711 int DisablePredictedCircuits; /**< Boolean: does Tor preemptively
3712 * make circuits in the background (0),
3713 * or not (1)? */
3715 /** Process specifier for a controller that ‘owns’ this Tor
3716 * instance. Tor will terminate if its owning controller does. */
3717 char *OwningControllerProcess;
3719 int ShutdownWaitLength; /**< When we get a SIGINT and we're a server, how
3720 * long do we wait before exiting? */
3721 char *SafeLogging; /**< Contains "relay", "1", "0" (meaning no scrubbing). */
3723 /* Derived from SafeLogging */
3724 enum {
3725 SAFELOG_SCRUB_ALL, SAFELOG_SCRUB_RELAY, SAFELOG_SCRUB_NONE
3726 } SafeLogging_;
3728 int SafeSocks; /**< Boolean: should we outright refuse application
3729 * connections that use socks4 or socks5-with-local-dns? */
3730 #define LOG_PROTOCOL_WARN (get_options()->ProtocolWarnings ? \
3731 LOG_WARN : LOG_INFO)
3732 int ProtocolWarnings; /**< Boolean: when other parties screw up the Tor
3733 * protocol, is it a warn or an info in our logs? */
3734 int TestSocks; /**< Boolean: when we get a socks connection, do we loudly
3735 * log whether it was DNS-leaking or not? */
3736 int HardwareAccel; /**< Boolean: Should we enable OpenSSL hardware
3737 * acceleration where available? */
3738 /** Token Bucket Refill resolution in milliseconds. */
3739 int TokenBucketRefillInterval;
3740 char *AccelName; /**< Optional hardware acceleration engine name. */
3741 char *AccelDir; /**< Optional hardware acceleration engine search dir. */
3742 int UseEntryGuards; /**< Boolean: Do we try to enter from a smallish number
3743 * of fixed nodes? */
3744 int NumEntryGuards; /**< How many entry guards do we try to establish? */
3745 int UseEntryGuardsAsDirGuards; /** Boolean: Do we try to get directory info
3746 * from a smallish number of fixed nodes? */
3747 int NumDirectoryGuards; /**< How many dir guards do we try to establish? */
3748 int RephistTrackTime; /**< How many seconds do we keep rephist info? */
3749 int FastFirstHopPK; /**< If Tor believes it is safe, should we save a third
3750 * of our PK time by sending CREATE_FAST cells? */
3751 /** Should we always fetch our dir info on the mirror schedule (which
3752 * means directly from the authorities) no matter our other config? */
3753 int FetchDirInfoEarly;
3755 /** Should we fetch our dir info at the start of the consensus period? */
3756 int FetchDirInfoExtraEarly;
3758 char *VirtualAddrNetworkIPv4; /**< Address and mask to hand out for virtual
3759 * MAPADDRESS requests for IPv4 addresses */
3760 char *VirtualAddrNetworkIPv6; /**< Address and mask to hand out for virtual
3761 * MAPADDRESS requests for IPv6 addresses */
3762 int ServerDNSSearchDomains; /**< Boolean: If set, we don't force exit
3763 * addresses to be FQDNs, but rather search for them in
3764 * the local domains. */
3765 int ServerDNSDetectHijacking; /**< Boolean: If true, check for DNS failure
3766 * hijacking. */
3767 int ServerDNSRandomizeCase; /**< Boolean: Use the 0x20-hack to prevent
3768 * DNS poisoning attacks. */
3769 char *ServerDNSResolvConfFile; /**< If provided, we configure our internal
3770 * resolver from the file here rather than from
3771 * /etc/resolv.conf (Unix) or the registry (Windows). */
3772 char *DirPortFrontPage; /**< This is a full path to a file with an html
3773 disclaimer. This allows a server administrator to show
3774 that they're running Tor and anyone visiting their server
3775 will know this without any specialized knowledge. */
3776 int DisableDebuggerAttachment; /**< Currently Linux only specific attempt to
3777 disable ptrace; needs BSD testing. */
3778 /** Boolean: if set, we start even if our resolv.conf file is missing
3779 * or broken. */
3780 int ServerDNSAllowBrokenConfig;
3781 /** Boolean: if set, then even connections to private addresses will get
3782 * rate-limited. */
3783 int CountPrivateBandwidth;
3784 smartlist_t *ServerDNSTestAddresses; /**< A list of addresses that definitely
3785 * should be resolvable. Used for
3786 * testing our DNS server. */
3787 int EnforceDistinctSubnets; /**< If true, don't allow multiple routers in the
3788 * same network zone in the same circuit. */
3789 int TunnelDirConns; /**< If true, use BEGIN_DIR rather than BEGIN when
3790 * possible. */
3791 int PreferTunneledDirConns; /**< If true, avoid dirservers that don't
3792 * support BEGIN_DIR, when possible. */
3793 int PortForwarding; /**< If true, use NAT-PMP or UPnP to automatically
3794 * forward the DirPort and ORPort on the NAT device */
3795 char *PortForwardingHelper; /** < Filename or full path of the port
3796 forwarding helper executable */
3797 int AllowNonRFC953Hostnames; /**< If true, we allow connections to hostnames
3798 * with weird characters. */
3799 /** If true, we try resolving hostnames with weird characters. */
3800 int ServerDNSAllowNonRFC953Hostnames;
3802 /** If true, we try to download extra-info documents (and we serve them,
3803 * if we are a cache). For authorities, this is always true. */
3804 int DownloadExtraInfo;
3806 /** If true, and we are acting as a relay, allow exit circuits even when
3807 * we are the first hop of a circuit. */
3808 int AllowSingleHopExits;
3809 /** If true, don't allow relays with AllowSingleHopExits=1 to be used in
3810 * circuits that we build. */
3811 int ExcludeSingleHopRelays;
3812 /** If true, and the controller tells us to use a one-hop circuit, and the
3813 * exit allows it, we use it. */
3814 int AllowSingleHopCircuits;
3816 /** If true, we convert "www.google.com.foo.exit" addresses on the
3817 * socks/trans/natd ports into "www.google.com" addresses that
3818 * exit from the node "foo". Disabled by default since attacking
3819 * websites and exit relays can use it to manipulate your path
3820 * selection. */
3821 int AllowDotExit;
3823 /** If true, we will warn if a user gives us only an IP address
3824 * instead of a hostname. */
3825 int WarnUnsafeSocks;
3827 /** If true, the user wants us to collect statistics on clients
3828 * requesting network statuses from us as directory. */
3829 int DirReqStatistics;
3831 /** If true, the user wants us to collect statistics on port usage. */
3832 int ExitPortStatistics;
3834 /** If true, the user wants us to collect connection statistics. */
3835 int ConnDirectionStatistics;
3837 /** If true, the user wants us to collect cell statistics. */
3838 int CellStatistics;
3840 /** If true, the user wants us to collect statistics as entry node. */
3841 int EntryStatistics;
3843 /** If true, include statistics file contents in extra-info documents. */
3844 int ExtraInfoStatistics;
3846 /** If true, do not believe anybody who tells us that a domain resolves
3847 * to an internal address, or that an internal address has a PTR mapping.
3848 * Helps avoid some cross-site attacks. */
3849 int ClientDNSRejectInternalAddresses;
3851 /** If true, do not accept any requests to connect to internal addresses
3852 * over randomly chosen exits. */
3853 int ClientRejectInternalAddresses;
3855 /** If true, clients may connect over IPv6. XXX we don't really
3856 enforce this -- clients _may_ set up outgoing IPv6 connections
3857 even when this option is not set. */
3858 int ClientUseIPv6;
3859 /** If true, prefer an IPv6 OR port over an IPv4 one. */
3860 int ClientPreferIPv6ORPort;
3862 /** The length of time that we think a consensus should be fresh. */
3863 int V3AuthVotingInterval;
3864 /** The length of time we think it will take to distribute votes. */
3865 int V3AuthVoteDelay;
3866 /** The length of time we think it will take to distribute signatures. */
3867 int V3AuthDistDelay;
3868 /** The number of intervals we think a consensus should be valid. */
3869 int V3AuthNIntervalsValid;
3871 /** Should advertise and sign consensuses with a legacy key, for key
3872 * migration purposes? */
3873 int V3AuthUseLegacyKey;
3875 /** Location of bandwidth measurement file */
3876 char *V3BandwidthsFile;
3878 /** Authority only: key=value pairs that we add to our networkstatus
3879 * consensus vote on the 'params' line. */
3880 char *ConsensusParams;
3882 /** Authority only: minimum number of measured bandwidths we must see
3883 * before we only beliee measured bandwidths to assign flags. */
3884 int MinMeasuredBWsForAuthToIgnoreAdvertised;
3886 /** The length of time that we think an initial consensus should be fresh.
3887 * Only altered on testing networks. */
3888 int TestingV3AuthInitialVotingInterval;
3890 /** The length of time we think it will take to distribute initial votes.
3891 * Only altered on testing networks. */
3892 int TestingV3AuthInitialVoteDelay;
3894 /** The length of time we think it will take to distribute initial
3895 * signatures. Only altered on testing networks.*/
3896 int TestingV3AuthInitialDistDelay;
3898 /** If an authority has been around for less than this amount of time, it
3899 * does not believe its reachability information is accurate. Only
3900 * altered on testing networks. */
3901 int TestingAuthDirTimeToLearnReachability;
3903 /** Clients don't download any descriptor this recent, since it will
3904 * probably not have propagated to enough caches. Only altered on testing
3905 * networks. */
3906 int TestingEstimatedDescriptorPropagationTime;
3908 /** If true, we take part in a testing network. Change the defaults of a
3909 * couple of other configuration options and allow to change the values
3910 * of certain configuration options. */
3911 int TestingTorNetwork;
3913 /** Minimum value for the Exit flag threshold on testing networks. */
3914 uint64_t TestingMinExitFlagThreshold;
3916 /** Minimum value for the Fast flag threshold on testing networks. */
3917 uint64_t TestingMinFastFlagThreshold;
3919 /** If true, and we have GeoIP data, and we're a bridge, keep a per-country
3920 * count of how many client addresses have contacted us so that we can help
3921 * the bridge authority guess which countries have blocked access to us. */
3922 int BridgeRecordUsageByCountry;
3924 /** Optionally, IPv4 and IPv6 GeoIP data. */
3925 char *GeoIPFile;
3926 char *GeoIPv6File;
3928 /** Autobool: if auto, then any attempt to Exclude{Exit,}Nodes a particular
3929 * country code will exclude all nodes in ?? and A1. If true, all nodes in
3930 * ?? and A1 are excluded. Has no effect if we don't know any GeoIP data. */
3931 int GeoIPExcludeUnknown;
3933 /** If true, SIGHUP should reload the torrc. Sometimes controllers want
3934 * to make this false. */
3935 int ReloadTorrcOnSIGHUP;
3937 /* The main parameter for picking circuits within a connection.
3939 * If this value is positive, when picking a cell to relay on a connection,
3940 * we always relay from the circuit whose weighted cell count is lowest.
3941 * Cells are weighted exponentially such that if one cell is sent
3942 * 'CircuitPriorityHalflife' seconds before another, it counts for half as
3943 * much.
3945 * If this value is zero, we're disabling the cell-EWMA algorithm.
3947 * If this value is negative, we're using the default approach
3948 * according to either Tor or a parameter set in the consensus.
3950 double CircuitPriorityHalflife;
3952 /** If true, do not enable IOCP on windows with bufferevents, even if
3953 * we think we could. */
3954 int DisableIOCP;
3955 /** For testing only: will go away eventually. */
3956 int UseFilteringSSLBufferevents;
3958 /** Set to true if the TestingTorNetwork configuration option is set.
3959 * This is used so that options_validate() has a chance to realize that
3960 * the defaults have changed. */
3961 int UsingTestNetworkDefaults_;
3963 /** If 1, we try to use microdescriptors to build circuits. If 0, we don't.
3964 * If -1, Tor decides. */
3965 int UseMicrodescriptors;
3967 /** File where we should write the ControlPort. */
3968 char *ControlPortWriteToFile;
3969 /** Should that file be group-readable? */
3970 int ControlPortFileGroupReadable;
3972 #define MAX_MAX_CLIENT_CIRCUITS_PENDING 1024
3973 /** Maximum number of non-open general-purpose origin circuits to allow at
3974 * once. */
3975 int MaxClientCircuitsPending;
3977 /** If 1, we always send optimistic data when it's supported. If 0, we
3978 * never use it. If -1, we do what the consensus says. */
3979 int OptimisticData;
3981 /** If 1, and we are using IOCP, we set the kernel socket SNDBUF and RCVBUF
3982 * to 0 to try to save kernel memory and avoid the dread "Out of buffers"
3983 * issue. */
3984 int UserspaceIOCPBuffers;
3986 /** If 1, we accept and launch no external network connections, except on
3987 * control ports. */
3988 int DisableNetwork;
3991 * Parameters for path-bias detection.
3992 * @{
3994 int PathBiasCircThreshold;
3995 double PathBiasNoticeRate;
3996 double PathBiasWarnRate;
3997 double PathBiasExtremeRate;
3998 int PathBiasDropGuards;
3999 int PathBiasScaleThreshold;
4000 /** @} */
4003 * Parameters for path-bias use detection
4004 * @{
4006 int PathBiasUseThreshold;
4007 double PathBiasNoticeUseRate;
4008 double PathBiasExtremeUseRate;
4009 int PathBiasScaleUseThreshold;
4010 /** @} */
4012 int IPv6Exit; /**< Do we support exiting to IPv6 addresses? */
4014 char *TLSECGroup; /**< One of "P256", "P224", or nil for auto */
4016 /** Autobool: should we use the ntor handshake if we can? */
4017 int UseNTorHandshake;
4019 /** Fraction: */
4020 double PathsNeededToBuildCircuits;
4022 /** Do we serve v2 directory info at all? This is a temporary option, since
4023 * we'd like to disable v2 directory serving entirely, but we need a way to
4024 * make it temporarily disableable, in order to do fast testing and be
4025 * able to turn it back on if it turns out to be non-workable.
4027 * XXXX025 Make this always-on, or always-off. Right now, it's only
4028 * enableable for authorities.
4030 int DisableV2DirectoryInfo_;
4032 /** What expiry time shall we place on our SSL certs? "0" means we
4033 * should guess a suitable value. */
4034 int SSLKeyLifetime;
4036 /** How long (seconds) do we keep a guard before picking a new one? */
4037 int GuardLifetime;
4038 } or_options_t;
4040 /** Persistent state for an onion router, as saved to disk. */
4041 typedef struct {
4042 uint32_t magic_;
4043 /** The time at which we next plan to write the state to the disk. Equal to
4044 * TIME_MAX if there are no savable changes, 0 if there are changes that
4045 * should be saved right away. */
4046 time_t next_write;
4048 /** When was the state last written to disk? */
4049 time_t LastWritten;
4051 /** Fields for accounting bandwidth use. */
4052 time_t AccountingIntervalStart;
4053 uint64_t AccountingBytesReadInInterval;
4054 uint64_t AccountingBytesWrittenInInterval;
4055 int AccountingSecondsActive;
4056 int AccountingSecondsToReachSoftLimit;
4057 time_t AccountingSoftLimitHitAt;
4058 uint64_t AccountingBytesAtSoftLimit;
4059 uint64_t AccountingExpectedUsage;
4061 /** A list of Entry Guard-related configuration lines. */
4062 config_line_t *EntryGuards;
4064 config_line_t *TransportProxies;
4066 /** These fields hold information on the history of bandwidth usage for
4067 * servers. The "Ends" fields hold the time when we last updated the
4068 * bandwidth usage. The "Interval" fields hold the granularity, in seconds,
4069 * of the entries of Values. The "Values" lists hold decimal string
4070 * representations of the number of bytes read or written in each
4071 * interval. The "Maxima" list holds decimal strings describing the highest
4072 * rate achieved during the interval.
4074 time_t BWHistoryReadEnds;
4075 int BWHistoryReadInterval;
4076 smartlist_t *BWHistoryReadValues;
4077 smartlist_t *BWHistoryReadMaxima;
4078 time_t BWHistoryWriteEnds;
4079 int BWHistoryWriteInterval;
4080 smartlist_t *BWHistoryWriteValues;
4081 smartlist_t *BWHistoryWriteMaxima;
4082 time_t BWHistoryDirReadEnds;
4083 int BWHistoryDirReadInterval;
4084 smartlist_t *BWHistoryDirReadValues;
4085 smartlist_t *BWHistoryDirReadMaxima;
4086 time_t BWHistoryDirWriteEnds;
4087 int BWHistoryDirWriteInterval;
4088 smartlist_t *BWHistoryDirWriteValues;
4089 smartlist_t *BWHistoryDirWriteMaxima;
4091 /** Build time histogram */
4092 config_line_t * BuildtimeHistogram;
4093 unsigned int TotalBuildTimes;
4094 unsigned int CircuitBuildAbandonedCount;
4096 /** What version of Tor wrote this state file? */
4097 char *TorVersion;
4099 /** Holds any unrecognized values we found in the state file, in the order
4100 * in which we found them. */
4101 config_line_t *ExtraLines;
4103 /** When did we last rotate our onion key? "0" for 'no idea'. */
4104 time_t LastRotatedOnionKey;
4105 } or_state_t;
4107 /** Change the next_write time of <b>state</b> to <b>when</b>, unless the
4108 * state is already scheduled to be written to disk earlier than <b>when</b>.
4110 static INLINE void or_state_mark_dirty(or_state_t *state, time_t when)
4112 if (state->next_write > when)
4113 state->next_write = when;
4116 #define MAX_SOCKS_REPLY_LEN 1024
4117 #define MAX_SOCKS_ADDR_LEN 256
4118 #define SOCKS_NO_AUTH 0x00
4119 #define SOCKS_USER_PASS 0x02
4121 /** Please open a TCP connection to this addr:port. */
4122 #define SOCKS_COMMAND_CONNECT 0x01
4123 /** Please turn this FQDN into an IP address, privately. */
4124 #define SOCKS_COMMAND_RESOLVE 0xF0
4125 /** Please turn this IP address into an FQDN, privately. */
4126 #define SOCKS_COMMAND_RESOLVE_PTR 0xF1
4128 #define SOCKS_COMMAND_IS_CONNECT(c) ((c)==SOCKS_COMMAND_CONNECT)
4129 #define SOCKS_COMMAND_IS_RESOLVE(c) ((c)==SOCKS_COMMAND_RESOLVE || \
4130 (c)==SOCKS_COMMAND_RESOLVE_PTR)
4132 /** State of a SOCKS request from a user to an OP. Also used to encode other
4133 * information for non-socks user request (such as those on TransPort and
4134 * DNSPort) */
4135 struct socks_request_t {
4136 /** Which version of SOCKS did the client use? One of "0, 4, 5" -- where
4137 * 0 means that no socks handshake ever took place, and this is just a
4138 * stub connection (e.g. see connection_ap_make_link()). */
4139 uint8_t socks_version;
4140 /** If using socks5 authentication, which authentication type did we
4141 * negotiate? currently we support 0 (no authentication) and 2
4142 * (username/password). */
4143 uint8_t auth_type;
4144 /** What is this stream's goal? One of the SOCKS_COMMAND_* values */
4145 uint8_t command;
4146 /** Which kind of listener created this stream? */
4147 uint8_t listener_type;
4148 size_t replylen; /**< Length of <b>reply</b>. */
4149 uint8_t reply[MAX_SOCKS_REPLY_LEN]; /**< Write an entry into this string if
4150 * we want to specify our own socks reply,
4151 * rather than using the default socks4 or
4152 * socks5 socks reply. We use this for the
4153 * two-stage socks5 handshake.
4155 char address[MAX_SOCKS_ADDR_LEN]; /**< What address did the client ask to
4156 connect to/resolve? */
4157 uint16_t port; /**< What port did the client ask to connect to? */
4158 unsigned int has_finished : 1; /**< Has the SOCKS handshake finished? Used to
4159 * make sure we send back a socks reply for
4160 * every connection. */
4161 unsigned int got_auth : 1; /**< Have we received any authentication data? */
4163 /** Number of bytes in username; 0 if username is NULL */
4164 size_t usernamelen;
4165 /** Number of bytes in password; 0 if password is NULL */
4166 uint8_t passwordlen;
4167 /** The negotiated username value if any (for socks5), or the entire
4168 * authentication string (for socks4). This value is NOT nul-terminated;
4169 * see usernamelen for its length. */
4170 char *username;
4171 /** The negotiated password value if any (for socks5). This value is NOT
4172 * nul-terminated; see passwordlen for its length. */
4173 char *password;
4176 /********************************* circuitbuild.c **********************/
4178 /** How many hops does a general-purpose circuit have by default? */
4179 #define DEFAULT_ROUTE_LEN 3
4181 /* Circuit Build Timeout "public" structures. */
4183 /** Precision multiplier for the Bw weights */
4184 #define BW_WEIGHT_SCALE 10000
4185 #define BW_MIN_WEIGHT_SCALE 1
4186 #define BW_MAX_WEIGHT_SCALE INT32_MAX
4188 /** Total size of the circuit timeout history to accumulate.
4189 * 1000 is approx 2.5 days worth of continual-use circuits. */
4190 #define CBT_NCIRCUITS_TO_OBSERVE 1000
4192 /** Width of the histogram bins in milliseconds */
4193 #define CBT_BIN_WIDTH ((build_time_t)50)
4195 /** Number of modes to use in the weighted-avg computation of Xm */
4196 #define CBT_DEFAULT_NUM_XM_MODES 3
4197 #define CBT_MIN_NUM_XM_MODES 1
4198 #define CBT_MAX_NUM_XM_MODES 20
4200 /** A build_time_t is milliseconds */
4201 typedef uint32_t build_time_t;
4204 * CBT_BUILD_ABANDONED is our flag value to represent a force-closed
4205 * circuit (Aka a 'right-censored' pareto value).
4207 #define CBT_BUILD_ABANDONED ((build_time_t)(INT32_MAX-1))
4208 #define CBT_BUILD_TIME_MAX ((build_time_t)(INT32_MAX))
4210 /** Save state every 10 circuits */
4211 #define CBT_SAVE_STATE_EVERY 10
4213 /* Circuit build times consensus parameters */
4216 * How long to wait before actually closing circuits that take too long to
4217 * build in terms of CDF quantile.
4219 #define CBT_DEFAULT_CLOSE_QUANTILE 95
4220 #define CBT_MIN_CLOSE_QUANTILE CBT_MIN_QUANTILE_CUTOFF
4221 #define CBT_MAX_CLOSE_QUANTILE CBT_MAX_QUANTILE_CUTOFF
4224 * How many circuits count as recent when considering if the
4225 * connection has gone gimpy or changed.
4227 #define CBT_DEFAULT_RECENT_CIRCUITS 20
4228 #define CBT_MIN_RECENT_CIRCUITS 3
4229 #define CBT_MAX_RECENT_CIRCUITS 1000
4232 * Maximum count of timeouts that finish the first hop in the past
4233 * RECENT_CIRCUITS before calculating a new timeout.
4235 * This tells us whether to abandon timeout history and set
4236 * the timeout back to whatever circuit_build_times_get_initial_timeout()
4237 * gives us.
4239 #define CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT (CBT_DEFAULT_RECENT_CIRCUITS*9/10)
4240 #define CBT_MIN_MAX_RECENT_TIMEOUT_COUNT 3
4241 #define CBT_MAX_MAX_RECENT_TIMEOUT_COUNT 10000
4243 /** Minimum circuits before estimating a timeout */
4244 #define CBT_DEFAULT_MIN_CIRCUITS_TO_OBSERVE 100
4245 #define CBT_MIN_MIN_CIRCUITS_TO_OBSERVE 1
4246 #define CBT_MAX_MIN_CIRCUITS_TO_OBSERVE 10000
4248 /** Cutoff percentile on the CDF for our timeout estimation. */
4249 #define CBT_DEFAULT_QUANTILE_CUTOFF 80
4250 #define CBT_MIN_QUANTILE_CUTOFF 10
4251 #define CBT_MAX_QUANTILE_CUTOFF 99
4252 double circuit_build_times_quantile_cutoff(void);
4254 /** How often in seconds should we build a test circuit */
4255 #define CBT_DEFAULT_TEST_FREQUENCY 60
4256 #define CBT_MIN_TEST_FREQUENCY 1
4257 #define CBT_MAX_TEST_FREQUENCY INT32_MAX
4259 /** Lowest allowable value for CircuitBuildTimeout in milliseconds */
4260 #define CBT_DEFAULT_TIMEOUT_MIN_VALUE (1500)
4261 #define CBT_MIN_TIMEOUT_MIN_VALUE 500
4262 #define CBT_MAX_TIMEOUT_MIN_VALUE INT32_MAX
4264 /** Initial circuit build timeout in milliseconds */
4265 #define CBT_DEFAULT_TIMEOUT_INITIAL_VALUE (60*1000)
4266 #define CBT_MIN_TIMEOUT_INITIAL_VALUE CBT_MIN_TIMEOUT_MIN_VALUE
4267 #define CBT_MAX_TIMEOUT_INITIAL_VALUE INT32_MAX
4268 int32_t circuit_build_times_initial_timeout(void);
4270 #if CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT < CBT_MIN_MAX_RECENT_TIMEOUT_COUNT
4271 #error "RECENT_CIRCUITS is set too low."
4272 #endif
4274 /** Information about the state of our local network connection */
4275 typedef struct {
4276 /** The timestamp we last completed a TLS handshake or received a cell */
4277 time_t network_last_live;
4278 /** If the network is not live, how many timeouts has this caused? */
4279 int nonlive_timeouts;
4280 /** Circular array of circuits that have made it to the first hop. Slot is
4281 * 1 if circuit timed out, 0 if circuit succeeded */
4282 int8_t *timeouts_after_firsthop;
4283 /** Number of elements allocated for the above array */
4284 int num_recent_circs;
4285 /** Index into circular array. */
4286 int after_firsthop_idx;
4287 } network_liveness_t;
4289 /** Structure for circuit build times history */
4290 typedef struct {
4291 /** The circular array of recorded build times in milliseconds */
4292 build_time_t circuit_build_times[CBT_NCIRCUITS_TO_OBSERVE];
4293 /** Current index in the circuit_build_times circular array */
4294 int build_times_idx;
4295 /** Total number of build times accumulated. Max CBT_NCIRCUITS_TO_OBSERVE */
4296 int total_build_times;
4297 /** Information about the state of our local network connection */
4298 network_liveness_t liveness;
4299 /** Last time we built a circuit. Used to decide to build new test circs */
4300 time_t last_circ_at;
4301 /** "Minimum" value of our pareto distribution (actually mode) */
4302 build_time_t Xm;
4303 /** alpha exponent for pareto dist. */
4304 double alpha;
4305 /** Have we computed a timeout? */
4306 int have_computed_timeout;
4307 /** The exact value for that timeout in milliseconds. Stored as a double
4308 * to maintain precision from calculations to and from quantile value. */
4309 double timeout_ms;
4310 /** How long we wait before actually closing the circuit. */
4311 double close_ms;
4312 } circuit_build_times_t;
4314 /********************************* config.c ***************************/
4316 /** An error from options_trial_assign() or options_init_from_string(). */
4317 typedef enum setopt_err_t {
4318 SETOPT_OK = 0,
4319 SETOPT_ERR_MISC = -1,
4320 SETOPT_ERR_PARSE = -2,
4321 SETOPT_ERR_TRANSITION = -3,
4322 SETOPT_ERR_SETTING = -4,
4323 } setopt_err_t;
4325 /********************************* connection_edge.c *************************/
4327 /** Enumerates possible origins of a client-side address mapping. */
4328 typedef enum {
4329 /** We're remapping this address because the controller told us to. */
4330 ADDRMAPSRC_CONTROLLER,
4331 /** We're remapping this address because of an AutomapHostsOnResolve
4332 * configuration. */
4333 ADDRMAPSRC_AUTOMAP,
4334 /** We're remapping this address because our configuration (via torrc, the
4335 * command line, or a SETCONF command) told us to. */
4336 ADDRMAPSRC_TORRC,
4337 /** We're remapping this address because we have TrackHostExit configured,
4338 * and we want to remember to use the same exit next time. */
4339 ADDRMAPSRC_TRACKEXIT,
4340 /** We're remapping this address because we got a DNS resolution from a
4341 * Tor server that told us what its value was. */
4342 ADDRMAPSRC_DNS,
4344 /** No remapping has occurred. This isn't a possible value for an
4345 * addrmap_entry_t; it's used as a null value when we need to answer "Why
4346 * did this remapping happen." */
4347 ADDRMAPSRC_NONE
4348 } addressmap_entry_source_t;
4350 /********************************* control.c ***************************/
4352 /** Used to indicate the type of a circuit event passed to the controller.
4353 * The various types are defined in control-spec.txt */
4354 typedef enum circuit_status_event_t {
4355 CIRC_EVENT_LAUNCHED = 0,
4356 CIRC_EVENT_BUILT = 1,
4357 CIRC_EVENT_EXTENDED = 2,
4358 CIRC_EVENT_FAILED = 3,
4359 CIRC_EVENT_CLOSED = 4,
4360 } circuit_status_event_t;
4362 /** Used to indicate the type of a CIRC_MINOR event passed to the controller.
4363 * The various types are defined in control-spec.txt . */
4364 typedef enum circuit_status_minor_event_t {
4365 CIRC_MINOR_EVENT_PURPOSE_CHANGED,
4366 CIRC_MINOR_EVENT_CANNIBALIZED,
4367 } circuit_status_minor_event_t;
4369 /** Used to indicate the type of a stream event passed to the controller.
4370 * The various types are defined in control-spec.txt */
4371 typedef enum stream_status_event_t {
4372 STREAM_EVENT_SENT_CONNECT = 0,
4373 STREAM_EVENT_SENT_RESOLVE = 1,
4374 STREAM_EVENT_SUCCEEDED = 2,
4375 STREAM_EVENT_FAILED = 3,
4376 STREAM_EVENT_CLOSED = 4,
4377 STREAM_EVENT_NEW = 5,
4378 STREAM_EVENT_NEW_RESOLVE = 6,
4379 STREAM_EVENT_FAILED_RETRIABLE = 7,
4380 STREAM_EVENT_REMAP = 8
4381 } stream_status_event_t;
4383 /** Used to indicate the type of an OR connection event passed to the
4384 * controller. The various types are defined in control-spec.txt */
4385 typedef enum or_conn_status_event_t {
4386 OR_CONN_EVENT_LAUNCHED = 0,
4387 OR_CONN_EVENT_CONNECTED = 1,
4388 OR_CONN_EVENT_FAILED = 2,
4389 OR_CONN_EVENT_CLOSED = 3,
4390 OR_CONN_EVENT_NEW = 4,
4391 } or_conn_status_event_t;
4393 /** Used to indicate the type of a buildtime event */
4394 typedef enum buildtimeout_set_event_t {
4395 BUILDTIMEOUT_SET_EVENT_COMPUTED = 0,
4396 BUILDTIMEOUT_SET_EVENT_RESET = 1,
4397 BUILDTIMEOUT_SET_EVENT_SUSPENDED = 2,
4398 BUILDTIMEOUT_SET_EVENT_DISCARD = 3,
4399 BUILDTIMEOUT_SET_EVENT_RESUME = 4
4400 } buildtimeout_set_event_t;
4402 /** Execute the statement <b>stmt</b>, which may log events concerning the
4403 * connection <b>conn</b>. To prevent infinite loops, disable log messages
4404 * being sent to controllers if <b>conn</b> is a control connection.
4406 * Stmt must not contain any return or goto statements.
4408 #define CONN_LOG_PROTECT(conn, stmt) \
4409 STMT_BEGIN \
4410 int _log_conn_is_control; \
4411 tor_assert(conn); \
4412 _log_conn_is_control = (conn->type == CONN_TYPE_CONTROL); \
4413 if (_log_conn_is_control) \
4414 disable_control_logging(); \
4415 STMT_BEGIN stmt; STMT_END; \
4416 if (_log_conn_is_control) \
4417 enable_control_logging(); \
4418 STMT_END
4420 /** Enum describing various stages of bootstrapping, for use with controller
4421 * bootstrap status events. The values range from 0 to 100. */
4422 typedef enum {
4423 BOOTSTRAP_STATUS_UNDEF=-1,
4424 BOOTSTRAP_STATUS_STARTING=0,
4425 BOOTSTRAP_STATUS_CONN_DIR=5,
4426 BOOTSTRAP_STATUS_HANDSHAKE=-2,
4427 BOOTSTRAP_STATUS_HANDSHAKE_DIR=10,
4428 BOOTSTRAP_STATUS_ONEHOP_CREATE=15,
4429 BOOTSTRAP_STATUS_REQUESTING_STATUS=20,
4430 BOOTSTRAP_STATUS_LOADING_STATUS=25,
4431 BOOTSTRAP_STATUS_LOADING_KEYS=40,
4432 BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS=45,
4433 BOOTSTRAP_STATUS_LOADING_DESCRIPTORS=50,
4434 BOOTSTRAP_STATUS_CONN_OR=80,
4435 BOOTSTRAP_STATUS_HANDSHAKE_OR=85,
4436 BOOTSTRAP_STATUS_CIRCUIT_CREATE=90,
4437 BOOTSTRAP_STATUS_DONE=100
4438 } bootstrap_status_t;
4440 /********************************* directory.c ***************************/
4442 /** A pair of digests created by dir_split_resource_info_fingerprint_pairs() */
4443 typedef struct {
4444 char first[DIGEST_LEN];
4445 char second[DIGEST_LEN];
4446 } fp_pair_t;
4448 /********************************* dirserv.c ***************************/
4450 /** An enum to describe what format we're generating a routerstatus line in.
4452 typedef enum {
4453 /** For use in a v2 opinion */
4454 NS_V2,
4455 /** For use in a consensus networkstatus document (ns flavor) */
4456 NS_V3_CONSENSUS,
4457 /** For use in a vote networkstatus document */
4458 NS_V3_VOTE,
4459 /** For passing to the controlport in response to a GETINFO request */
4460 NS_CONTROL_PORT,
4461 /** For use in a consensus networkstatus document (microdesc flavor) */
4462 NS_V3_CONSENSUS_MICRODESC
4463 } routerstatus_format_type_t;
4465 #ifdef DIRSERV_PRIVATE
4466 typedef struct measured_bw_line_t {
4467 char node_id[DIGEST_LEN];
4468 char node_hex[MAX_HEX_NICKNAME_LEN+1];
4469 long int bw;
4470 } measured_bw_line_t;
4472 #endif
4474 /********************************* dirvote.c ************************/
4476 /** Describes the schedule by which votes should be generated. */
4477 typedef struct vote_timing_t {
4478 /** Length in seconds between one consensus becoming valid and the next
4479 * becoming valid. */
4480 int vote_interval;
4481 /** For how many intervals is a consensus valid? */
4482 int n_intervals_valid;
4483 /** Time in seconds allowed to propagate votes */
4484 int vote_delay;
4485 /** Time in seconds allowed to propagate signatures */
4486 int dist_delay;
4487 } vote_timing_t;
4489 /********************************* geoip.c **************************/
4491 /** Indicates an action that we might be noting geoip statistics on.
4492 * Note that if we're noticing CONNECT, we're a bridge, and if we're noticing
4493 * the others, we're not.
4495 typedef enum {
4496 /** We've noticed a connection as a bridge relay or entry guard. */
4497 GEOIP_CLIENT_CONNECT = 0,
4498 /** We've served a networkstatus consensus as a directory server. */
4499 GEOIP_CLIENT_NETWORKSTATUS = 1,
4500 /** We've served a v2 networkstatus consensus as a directory server. */
4501 GEOIP_CLIENT_NETWORKSTATUS_V2 = 2,
4502 } geoip_client_action_t;
4503 /** Indicates either a positive reply or a reason for rejectng a network
4504 * status request that will be included in geoip statistics. */
4505 typedef enum {
4506 /** Request is answered successfully. */
4507 GEOIP_SUCCESS = 0,
4508 /** V3 network status is not signed by a sufficient number of requested
4509 * authorities. */
4510 GEOIP_REJECT_NOT_ENOUGH_SIGS = 1,
4511 /** Requested network status object is unavailable. */
4512 GEOIP_REJECT_UNAVAILABLE = 2,
4513 /** Requested network status not found. */
4514 GEOIP_REJECT_NOT_FOUND = 3,
4515 /** Network status has not been modified since If-Modified-Since time. */
4516 GEOIP_REJECT_NOT_MODIFIED = 4,
4517 /** Directory is busy. */
4518 GEOIP_REJECT_BUSY = 5,
4519 } geoip_ns_response_t;
4520 #define GEOIP_NS_RESPONSE_NUM 6
4522 /** Directory requests that we are measuring can be either direct or
4523 * tunneled. */
4524 typedef enum {
4525 DIRREQ_DIRECT = 0,
4526 DIRREQ_TUNNELED = 1,
4527 } dirreq_type_t;
4529 /** Possible states for either direct or tunneled directory requests that
4530 * are relevant for determining network status download times. */
4531 typedef enum {
4532 /** Found that the client requests a network status; applies to both
4533 * direct and tunneled requests; initial state of a request that we are
4534 * measuring. */
4535 DIRREQ_IS_FOR_NETWORK_STATUS = 0,
4536 /** Finished writing a network status to the directory connection;
4537 * applies to both direct and tunneled requests; completes a direct
4538 * request. */
4539 DIRREQ_FLUSHING_DIR_CONN_FINISHED = 1,
4540 /** END cell sent to circuit that initiated a tunneled request. */
4541 DIRREQ_END_CELL_SENT = 2,
4542 /** Flushed last cell from queue of the circuit that initiated a
4543 * tunneled request to the outbuf of the OR connection. */
4544 DIRREQ_CIRC_QUEUE_FLUSHED = 3,
4545 /** Flushed last byte from buffer of the channel belonging to the
4546 * circuit that initiated a tunneled request; completes a tunneled
4547 * request. */
4548 DIRREQ_CHANNEL_BUFFER_FLUSHED = 4
4549 } dirreq_state_t;
4551 #define WRITE_STATS_INTERVAL (24*60*60)
4553 /********************************* microdesc.c *************************/
4555 typedef struct microdesc_cache_t microdesc_cache_t;
4557 /********************************* networkstatus.c *********************/
4559 /** Location where we found a v2 networkstatus. */
4560 typedef enum {
4561 NS_FROM_CACHE, NS_FROM_DIR_BY_FP, NS_FROM_DIR_ALL, NS_GENERATED
4562 } v2_networkstatus_source_t;
4564 /** Possible statuses of a version of Tor, given opinions from the directory
4565 * servers. */
4566 typedef enum version_status_t {
4567 VS_RECOMMENDED=0, /**< This version is listed as recommended. */
4568 VS_OLD=1, /**< This version is older than any recommended version. */
4569 VS_NEW=2, /**< This version is newer than any recommended version. */
4570 VS_NEW_IN_SERIES=3, /**< This version is newer than any recommended version
4571 * in its series, but later recommended versions exist.
4573 VS_UNRECOMMENDED=4, /**< This version is not recommended (general case). */
4574 VS_EMPTY=5, /**< The version list was empty; no agreed-on versions. */
4575 VS_UNKNOWN, /**< We have no idea. */
4576 } version_status_t;
4578 /********************************* policies.c ************************/
4580 /** Outcome of applying an address policy to an address. */
4581 typedef enum {
4582 /** The address was accepted */
4583 ADDR_POLICY_ACCEPTED=0,
4584 /** The address was rejected */
4585 ADDR_POLICY_REJECTED=-1,
4586 /** Part of the address was unknown, but as far as we can tell, it was
4587 * accepted. */
4588 ADDR_POLICY_PROBABLY_ACCEPTED=1,
4589 /** Part of the address was unknown, but as far as we can tell, it was
4590 * rejected. */
4591 ADDR_POLICY_PROBABLY_REJECTED=2,
4592 } addr_policy_result_t;
4594 /********************************* rephist.c ***************************/
4596 /** Possible public/private key operations in Tor: used to keep track of where
4597 * we're spending our time. */
4598 typedef enum {
4599 SIGN_DIR, SIGN_RTR,
4600 VERIFY_DIR, VERIFY_RTR,
4601 ENC_ONIONSKIN, DEC_ONIONSKIN,
4602 TLS_HANDSHAKE_C, TLS_HANDSHAKE_S,
4603 REND_CLIENT, REND_MID, REND_SERVER,
4604 } pk_op_t;
4606 /********************************* rendcommon.c ***************************/
4608 /** Hidden-service side configuration of client authorization. */
4609 typedef struct rend_authorized_client_t {
4610 char *client_name;
4611 char descriptor_cookie[REND_DESC_COOKIE_LEN];
4612 crypto_pk_t *client_key;
4613 } rend_authorized_client_t;
4615 /** ASCII-encoded v2 hidden service descriptor. */
4616 typedef struct rend_encoded_v2_service_descriptor_t {
4617 char desc_id[DIGEST_LEN]; /**< Descriptor ID. */
4618 char *desc_str; /**< Descriptor string. */
4619 } rend_encoded_v2_service_descriptor_t;
4621 /** The maximum number of non-circuit-build-timeout failures a hidden
4622 * service client will tolerate while trying to build a circuit to an
4623 * introduction point. See also rend_intro_point_t.unreachable_count. */
4624 #define MAX_INTRO_POINT_REACHABILITY_FAILURES 5
4626 /** The maximum number of distinct INTRODUCE2 cells which a hidden
4627 * service's introduction point will receive before it begins to
4628 * expire.
4630 * XXX023 Is this number at all sane? */
4631 #define INTRO_POINT_LIFETIME_INTRODUCTIONS 16384
4633 /** The minimum number of seconds that an introduction point will last
4634 * before expiring due to old age. (If it receives
4635 * INTRO_POINT_LIFETIME_INTRODUCTIONS INTRODUCE2 cells, it may expire
4636 * sooner.)
4638 * XXX023 Should this be configurable? */
4639 #define INTRO_POINT_LIFETIME_MIN_SECONDS (18*60*60)
4640 /** The maximum number of seconds that an introduction point will last
4641 * before expiring due to old age.
4643 * XXX023 Should this be configurable? */
4644 #define INTRO_POINT_LIFETIME_MAX_SECONDS (24*60*60)
4646 /** Introduction point information. Used both in rend_service_t (on
4647 * the service side) and in rend_service_descriptor_t (on both the
4648 * client and service side). */
4649 typedef struct rend_intro_point_t {
4650 extend_info_t *extend_info; /**< Extend info of this introduction point. */
4651 crypto_pk_t *intro_key; /**< Introduction key that replaces the service
4652 * key, if this descriptor is V2. */
4654 /** (Client side only) Flag indicating that a timeout has occurred
4655 * after sending an INTRODUCE cell to this intro point. After a
4656 * timeout, an intro point should not be tried again during the same
4657 * hidden service connection attempt, but it may be tried again
4658 * during a future connection attempt. */
4659 unsigned int timed_out : 1;
4661 /** (Client side only) The number of times we have failed to build a
4662 * circuit to this intro point for some reason other than our
4663 * circuit-build timeout. See also MAX_INTRO_POINT_REACHABILITY_FAILURES. */
4664 unsigned int unreachable_count : 3;
4666 /** (Service side only) Flag indicating that this intro point was
4667 * included in the last HS descriptor we generated. */
4668 unsigned int listed_in_last_desc : 1;
4670 /** (Service side only) Flag indicating that
4671 * rend_service_note_removing_intro_point has been called for this
4672 * intro point. */
4673 unsigned int rend_service_note_removing_intro_point_called : 1;
4675 /** (Service side only) A replay cache recording the RSA-encrypted parts
4676 * of INTRODUCE2 cells this intro point's circuit has received. This is
4677 * used to prevent replay attacks. */
4678 replaycache_t *accepted_intro_rsa_parts;
4680 /** (Service side only) Count of INTRODUCE2 cells accepted from this
4681 * intro point.
4683 int accepted_introduce2_count;
4685 /** (Service side only) The time at which this intro point was first
4686 * published, or -1 if this intro point has not yet been
4687 * published. */
4688 time_t time_published;
4690 /** (Service side only) The time at which this intro point should
4691 * (start to) expire, or -1 if we haven't decided when this intro
4692 * point should expire. */
4693 time_t time_to_expire;
4695 /** (Service side only) The time at which we decided that this intro
4696 * point should start expiring, or -1 if this intro point is not yet
4697 * expiring.
4699 * This field also serves as a flag to indicate that we have decided
4700 * to expire this intro point, in case intro_point_should_expire_now
4701 * flaps (perhaps due to a clock jump; perhaps due to other
4702 * weirdness, or even a (present or future) bug). */
4703 time_t time_expiring;
4704 } rend_intro_point_t;
4706 #define REND_PROTOCOL_VERSION_BITMASK_WIDTH 16
4708 /** Information used to connect to a hidden service. Used on both the
4709 * service side and the client side. */
4710 typedef struct rend_service_descriptor_t {
4711 crypto_pk_t *pk; /**< This service's public key. */
4712 int version; /**< Version of the descriptor format: 0 or 2. */
4713 time_t timestamp; /**< Time when the descriptor was generated. */
4714 /** Bitmask: which rendezvous protocols are supported?
4715 * (We allow bits '0', '1', and '2' to be set.) */
4716 int protocols : REND_PROTOCOL_VERSION_BITMASK_WIDTH;
4717 /** List of the service's introduction points. Elements are removed if
4718 * introduction attempts fail. */
4719 smartlist_t *intro_nodes;
4720 /** Has descriptor been uploaded to all hidden service directories? */
4721 int all_uploads_performed;
4722 /** List of hidden service directories to which an upload request for
4723 * this descriptor could be sent. Smartlist exists only when at least one
4724 * of the previous upload requests failed (otherwise it's not important
4725 * to know which uploads succeeded and which not). */
4726 smartlist_t *successful_uploads;
4727 } rend_service_descriptor_t;
4729 /** A cached rendezvous descriptor. */
4730 typedef struct rend_cache_entry_t {
4731 size_t len; /**< Length of <b>desc</b> */
4732 time_t received; /**< When was the descriptor received? */
4733 char *desc; /**< Service descriptor */
4734 rend_service_descriptor_t *parsed; /**< Parsed value of 'desc' */
4735 } rend_cache_entry_t;
4737 /********************************* routerlist.c ***************************/
4739 /** Represents information about a single trusted or fallback directory
4740 * server. */
4741 typedef struct dir_server_t {
4742 char *description;
4743 char *nickname;
4744 char *address; /**< Hostname. */
4745 uint32_t addr; /**< IPv4 address. */
4746 uint16_t dir_port; /**< Directory port. */
4747 uint16_t or_port; /**< OR port: Used for tunneling connections. */
4748 double weight; /** Weight used when selecting this node at random */
4749 char digest[DIGEST_LEN]; /**< Digest of identity key. */
4750 char v3_identity_digest[DIGEST_LEN]; /**< Digest of v3 (authority only,
4751 * high-security) identity key. */
4753 unsigned int is_running:1; /**< True iff we think this server is running. */
4754 unsigned int is_authority:1; /**< True iff this is a directory authority
4755 * of some kind. */
4757 /** True iff this server has accepted the most recent server descriptor
4758 * we tried to upload to it. */
4759 unsigned int has_accepted_serverdesc:1;
4761 /** What kind of authority is this? (Bitfield.) */
4762 dirinfo_type_t type;
4764 download_status_t v2_ns_dl_status; /**< Status of downloading this server's
4765 * v2 network status. */
4766 time_t addr_current_at; /**< When was the document that we derived the
4767 * address information from published? */
4769 routerstatus_t fake_status; /**< Used when we need to pass this trusted
4770 * dir_server_t to directory_initiate_command_*
4771 * as a routerstatus_t. Not updated by the
4772 * router-status management code!
4774 } dir_server_t;
4776 #define ROUTER_REQUIRED_MIN_BANDWIDTH (20*1024)
4778 #define ROUTER_MAX_DECLARED_BANDWIDTH INT32_MAX
4780 /* Flags for pick_directory_server() and pick_trusteddirserver(). */
4781 /** Flag to indicate that we should not automatically be willing to use
4782 * ourself to answer a directory request.
4783 * Passed to router_pick_directory_server (et al).*/
4784 #define PDS_ALLOW_SELF (1<<0)
4785 /** Flag to indicate that if no servers seem to be up, we should mark all
4786 * directory servers as up and try again.
4787 * Passed to router_pick_directory_server (et al).*/
4788 #define PDS_RETRY_IF_NO_SERVERS (1<<1)
4789 /** Flag to indicate that we should not exclude directory servers that
4790 * our ReachableAddress settings would exclude. This usually means that
4791 * we're going to connect to the server over Tor, and so we don't need to
4792 * worry about our firewall telling us we can't.
4793 * Passed to router_pick_directory_server (et al).*/
4794 #define PDS_IGNORE_FASCISTFIREWALL (1<<2)
4795 /** Flag to indicate that we should not use any directory authority to which
4796 * we have an existing directory connection for downloading server descriptors
4797 * or extrainfo documents.
4799 * Passed to router_pick_directory_server (et al)
4801 * [XXXX NOTE: This option is only implemented for pick_trusteddirserver,
4802 * not pick_directory_server. If we make it work on pick_directory_server
4803 * too, we could conservatively make it only prevent multiple fetches to
4804 * the same authority, or we could aggressively make it prevent multiple
4805 * fetches to _any_ single directory server.]
4807 #define PDS_NO_EXISTING_SERVERDESC_FETCH (1<<3)
4808 #define PDS_NO_EXISTING_MICRODESC_FETCH (1<<4)
4810 /** This node is to be chosen as a directory guard, so don't choose any
4811 * node that's currently a guard. */
4812 #define PDS_FOR_GUARD (1<<5)
4814 #define PDS_PREFER_TUNNELED_DIR_CONNS_ (1<<16)
4816 /** Possible ways to weight routers when choosing one randomly. See
4817 * routerlist_sl_choose_by_bandwidth() for more information.*/
4818 typedef enum bandwidth_weight_rule_t {
4819 NO_WEIGHTING, WEIGHT_FOR_EXIT, WEIGHT_FOR_MID, WEIGHT_FOR_GUARD,
4820 WEIGHT_FOR_DIR
4821 } bandwidth_weight_rule_t;
4823 /** Flags to be passed to control router_choose_random_node() to indicate what
4824 * kind of nodes to pick according to what algorithm. */
4825 typedef enum {
4826 CRN_NEED_UPTIME = 1<<0,
4827 CRN_NEED_CAPACITY = 1<<1,
4828 CRN_NEED_GUARD = 1<<2,
4829 CRN_ALLOW_INVALID = 1<<3,
4830 /* XXXX not used, apparently. */
4831 CRN_WEIGHT_AS_EXIT = 1<<5,
4832 CRN_NEED_DESC = 1<<6
4833 } router_crn_flags_t;
4835 /** Return value for router_add_to_routerlist() and dirserv_add_descriptor() */
4836 typedef enum was_router_added_t {
4837 ROUTER_ADDED_SUCCESSFULLY = 1,
4838 ROUTER_ADDED_NOTIFY_GENERATOR = 0,
4839 ROUTER_BAD_EI = -1,
4840 ROUTER_WAS_NOT_NEW = -2,
4841 ROUTER_NOT_IN_CONSENSUS = -3,
4842 ROUTER_NOT_IN_CONSENSUS_OR_NETWORKSTATUS = -4,
4843 ROUTER_AUTHDIR_REJECTS = -5,
4844 ROUTER_WAS_NOT_WANTED = -6
4845 } was_router_added_t;
4847 /********************************* routerparse.c ************************/
4849 #define MAX_STATUS_TAG_LEN 32
4850 /** Structure to hold parsed Tor versions. This is a little messier
4851 * than we would like it to be, because we changed version schemes with 0.1.0.
4853 * See version-spec.txt for the whole business.
4855 typedef struct tor_version_t {
4856 int major;
4857 int minor;
4858 int micro;
4859 /** Release status. For version in the post-0.1 format, this is always
4860 * VER_RELEASE. */
4861 enum { VER_PRE=0, VER_RC=1, VER_RELEASE=2, } status;
4862 int patchlevel;
4863 char status_tag[MAX_STATUS_TAG_LEN];
4864 int svn_revision;
4866 int git_tag_len;
4867 char git_tag[DIGEST_LEN];
4868 } tor_version_t;
4870 #endif