Remove the unused rend_cache_entry_t->received field.
[tor.git] / src / or / or.h
blobf821d0b4057e8b874af91935c135a854dfc5a164
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-2015, 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 #if defined(__clang_analyzer__) || defined(__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_FCNTL_H
46 #include <sys/fcntl.h>
47 #endif
48 #ifdef HAVE_FCNTL_H
49 #include <fcntl.h>
50 #endif
51 #ifdef HAVE_SYS_IOCTL_H
52 #include <sys/ioctl.h>
53 #endif
54 #ifdef HAVE_SYS_UN_H
55 #include <sys/un.h>
56 #endif
57 #ifdef HAVE_SYS_STAT_H
58 #include <sys/stat.h>
59 #endif
60 #ifdef HAVE_NETINET_IN_H
61 #include <netinet/in.h>
62 #endif
63 #ifdef HAVE_ARPA_INET_H
64 #include <arpa/inet.h>
65 #endif
66 #ifdef HAVE_ERRNO_H
67 #include <errno.h>
68 #endif
69 #ifdef HAVE_ASSERT_H
70 #include <assert.h>
71 #endif
72 #ifdef HAVE_TIME_H
73 #include <time.h>
74 #endif
76 #ifdef _WIN32
77 #include <io.h>
78 #include <process.h>
79 #include <direct.h>
80 #include <windows.h>
81 #endif
83 #ifdef USE_BUFFEREVENTS
84 #include <event2/bufferevent.h>
85 #include <event2/buffer.h>
86 #include <event2/util.h>
87 #endif
89 #include "crypto.h"
90 #include "tortls.h"
91 #include "../common/torlog.h"
92 #include "container.h"
93 #include "torgzip.h"
94 #include "address.h"
95 #include "compat_libevent.h"
96 #include "ht.h"
97 #include "replaycache.h"
98 #include "crypto_curve25519.h"
99 #include "tor_queue.h"
101 /* These signals are defined to help handle_control_signal work.
103 #ifndef SIGHUP
104 #define SIGHUP 1
105 #endif
106 #ifndef SIGINT
107 #define SIGINT 2
108 #endif
109 #ifndef SIGUSR1
110 #define SIGUSR1 10
111 #endif
112 #ifndef SIGUSR2
113 #define SIGUSR2 12
114 #endif
115 #ifndef SIGTERM
116 #define SIGTERM 15
117 #endif
118 /* Controller signals start at a high number so we don't
119 * conflict with system-defined signals. */
120 #define SIGNEWNYM 129
121 #define SIGCLEARDNSCACHE 130
122 #define SIGHEARTBEAT 131
124 #if (SIZEOF_CELL_T != 0)
125 /* On Irix, stdlib.h defines a cell_t type, so we need to make sure
126 * that our stuff always calls cell_t something different. */
127 #define cell_t tor_cell_t
128 #endif
130 #ifdef ENABLE_TOR2WEB_MODE
131 #define NON_ANONYMOUS_MODE_ENABLED 1
132 #endif
134 /** Length of longest allowable configured nickname. */
135 #define MAX_NICKNAME_LEN 19
136 /** Length of a router identity encoded as a hexadecimal digest, plus
137 * possible dollar sign. */
138 #define MAX_HEX_NICKNAME_LEN (HEX_DIGEST_LEN+1)
139 /** Maximum length of verbose router identifier: dollar sign, hex ID digest,
140 * equal sign or tilde, nickname. */
141 #define MAX_VERBOSE_NICKNAME_LEN (1+HEX_DIGEST_LEN+1+MAX_NICKNAME_LEN)
143 /** Maximum size, in bytes, for resized buffers. */
144 #define MAX_BUF_SIZE ((1<<24)-1) /* 16MB-1 */
145 /** Maximum size, in bytes, for any directory object that we've downloaded. */
146 #define MAX_DIR_DL_SIZE MAX_BUF_SIZE
148 /** For HTTP parsing: Maximum number of bytes we'll accept in the headers
149 * of an HTTP request or response. */
150 #define MAX_HEADERS_SIZE 50000
151 /** Maximum size, in bytes, for any directory object that we're accepting
152 * as an upload. */
153 #define MAX_DIR_UL_SIZE MAX_BUF_SIZE
155 /** Maximum size, in bytes, of a single router descriptor uploaded to us
156 * as a directory authority. Caches and clients fetch whatever descriptors
157 * the authorities tell them to fetch, and don't care about size. */
158 #define MAX_DESCRIPTOR_UPLOAD_SIZE 20000
160 /** Maximum size of a single extrainfo document, as above. */
161 #define MAX_EXTRAINFO_UPLOAD_SIZE 50000
163 /** How long do we keep DNS cache entries before purging them (regardless of
164 * their TTL)? */
165 #define MAX_DNS_ENTRY_AGE (30*60)
166 /** How long do we cache/tell clients to cache DNS records when no TTL is
167 * known? */
168 #define DEFAULT_DNS_TTL (30*60)
169 /** How long can a TTL be before we stop believing it? */
170 #define MAX_DNS_TTL (3*60*60)
171 /** How small can a TTL be before we stop believing it? Provides rudimentary
172 * pinning. */
173 #define MIN_DNS_TTL 60
175 /** How often do we rotate onion keys? */
176 #define MIN_ONION_KEY_LIFETIME (7*24*60*60)
177 /** How often do we rotate TLS contexts? */
178 #define MAX_SSL_KEY_LIFETIME_INTERNAL (2*60*60)
180 /** How old do we allow a router to get before removing it
181 * from the router list? In seconds. */
182 #define ROUTER_MAX_AGE (60*60*48)
183 /** How old can a router get before we (as a server) will no longer
184 * consider it live? In seconds. */
185 #define ROUTER_MAX_AGE_TO_PUBLISH (60*60*24)
186 /** How old do we let a saved descriptor get before force-removing it? */
187 #define OLD_ROUTER_DESC_MAX_AGE (60*60*24*5)
189 /** Possible rules for generating circuit IDs on an OR connection. */
190 typedef enum {
191 CIRC_ID_TYPE_LOWER=0, /**< Pick from 0..1<<15-1. */
192 CIRC_ID_TYPE_HIGHER=1, /**< Pick from 1<<15..1<<16-1. */
193 /** The other side of a connection is an OP: never create circuits to it,
194 * and let it use any circuit ID it wants. */
195 CIRC_ID_TYPE_NEITHER=2
196 } circ_id_type_t;
197 #define circ_id_type_bitfield_t ENUM_BF(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
231 /** Type for connections from the Extended ORPort. */
232 #define CONN_TYPE_EXT_OR 16
233 /** Type for sockets listening for Extended ORPort connections. */
234 #define CONN_TYPE_EXT_OR_LISTENER 17
236 #define CONN_TYPE_MAX_ 17
237 /* !!!! If _CONN_TYPE_MAX is ever over 31, we must grow the type field in
238 * connection_t. */
240 /* Proxy client types */
241 #define PROXY_NONE 0
242 #define PROXY_CONNECT 1
243 #define PROXY_SOCKS4 2
244 #define PROXY_SOCKS5 3
245 /* !!!! If there is ever a PROXY_* type over 3, we must grow the proxy_type
246 * field in or_connection_t */
248 /* Pluggable transport proxy type. Don't use this in or_connection_t,
249 * instead use the actual underlying proxy type (see above). */
250 #define PROXY_PLUGGABLE 4
252 /* Proxy client handshake states */
253 /* We use a proxy but we haven't even connected to it yet. */
254 #define PROXY_INFANT 1
255 /* We use an HTTP proxy and we've sent the CONNECT command. */
256 #define PROXY_HTTPS_WANT_CONNECT_OK 2
257 /* We use a SOCKS4 proxy and we've sent the CONNECT command. */
258 #define PROXY_SOCKS4_WANT_CONNECT_OK 3
259 /* We use a SOCKS5 proxy and we try to negotiate without
260 any authentication . */
261 #define PROXY_SOCKS5_WANT_AUTH_METHOD_NONE 4
262 /* We use a SOCKS5 proxy and we try to negotiate with
263 Username/Password authentication . */
264 #define PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929 5
265 /* We use a SOCKS5 proxy and we just sent our credentials. */
266 #define PROXY_SOCKS5_WANT_AUTH_RFC1929_OK 6
267 /* We use a SOCKS5 proxy and we just sent our CONNECT command. */
268 #define PROXY_SOCKS5_WANT_CONNECT_OK 7
269 /* We use a proxy and we CONNECTed successfully!. */
270 #define PROXY_CONNECTED 8
272 /** True iff <b>x</b> is an edge connection. */
273 #define CONN_IS_EDGE(x) \
274 ((x)->type == CONN_TYPE_EXIT || (x)->type == CONN_TYPE_AP)
276 /** State for any listener connection. */
277 #define LISTENER_STATE_READY 0
279 #define CPUWORKER_STATE_MIN_ 1
280 /** State for a connection to a cpuworker process that's idle. */
281 #define CPUWORKER_STATE_IDLE 1
282 /** State for a connection to a cpuworker process that's processing a
283 * handshake. */
284 #define CPUWORKER_STATE_BUSY_ONION 2
285 #define CPUWORKER_STATE_MAX_ 2
287 #define CPUWORKER_TASK_ONION CPUWORKER_STATE_BUSY_ONION
288 #define CPUWORKER_TASK_SHUTDOWN 255
290 #define OR_CONN_STATE_MIN_ 1
291 /** State for a connection to an OR: waiting for connect() to finish. */
292 #define OR_CONN_STATE_CONNECTING 1
293 /** State for a connection to an OR: waiting for proxy handshake to complete */
294 #define OR_CONN_STATE_PROXY_HANDSHAKING 2
295 /** State for an OR connection client: SSL is handshaking, not done
296 * yet. */
297 #define OR_CONN_STATE_TLS_HANDSHAKING 3
298 /** State for a connection to an OR: We're doing a second SSL handshake for
299 * renegotiation purposes. (V2 handshake only.) */
300 #define OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING 4
301 /** State for a connection at an OR: We're waiting for the client to
302 * renegotiate (to indicate a v2 handshake) or send a versions cell (to
303 * indicate a v3 handshake) */
304 #define OR_CONN_STATE_TLS_SERVER_RENEGOTIATING 5
305 /** State for an OR connection: We're done with our SSL handshake, we've done
306 * renegotiation, but we haven't yet negotiated link protocol versions and
307 * sent a netinfo cell. */
308 #define OR_CONN_STATE_OR_HANDSHAKING_V2 6
309 /** State for an OR connection: We're done with our SSL handshake, but we
310 * haven't yet negotiated link protocol versions, done a V3 handshake, and
311 * sent a netinfo cell. */
312 #define OR_CONN_STATE_OR_HANDSHAKING_V3 7
313 /** State for an OR connection: Ready to send/receive cells. */
314 #define OR_CONN_STATE_OPEN 8
315 #define OR_CONN_STATE_MAX_ 8
317 /** States of the Extended ORPort protocol. Be careful before changing
318 * the numbers: they matter. */
319 #define EXT_OR_CONN_STATE_MIN_ 1
320 /** Extended ORPort authentication is waiting for the authentication
321 * type selected by the client. */
322 #define EXT_OR_CONN_STATE_AUTH_WAIT_AUTH_TYPE 1
323 /** Extended ORPort authentication is waiting for the client nonce. */
324 #define EXT_OR_CONN_STATE_AUTH_WAIT_CLIENT_NONCE 2
325 /** Extended ORPort authentication is waiting for the client hash. */
326 #define EXT_OR_CONN_STATE_AUTH_WAIT_CLIENT_HASH 3
327 #define EXT_OR_CONN_STATE_AUTH_MAX 3
328 /** Authentication finished and the Extended ORPort is now accepting
329 * traffic. */
330 #define EXT_OR_CONN_STATE_OPEN 4
331 /** Extended ORPort is flushing its last messages and preparing to
332 * start accepting OR connections. */
333 #define EXT_OR_CONN_STATE_FLUSHING 5
334 #define EXT_OR_CONN_STATE_MAX_ 5
336 #define EXIT_CONN_STATE_MIN_ 1
337 /** State for an exit connection: waiting for response from DNS farm. */
338 #define EXIT_CONN_STATE_RESOLVING 1
339 /** State for an exit connection: waiting for connect() to finish. */
340 #define EXIT_CONN_STATE_CONNECTING 2
341 /** State for an exit connection: open and ready to transmit data. */
342 #define EXIT_CONN_STATE_OPEN 3
343 /** State for an exit connection: waiting to be removed. */
344 #define EXIT_CONN_STATE_RESOLVEFAILED 4
345 #define EXIT_CONN_STATE_MAX_ 4
347 /* The AP state values must be disjoint from the EXIT state values. */
348 #define AP_CONN_STATE_MIN_ 5
349 /** State for a SOCKS connection: waiting for SOCKS request. */
350 #define AP_CONN_STATE_SOCKS_WAIT 5
351 /** State for a SOCKS connection: got a y.onion URL; waiting to receive
352 * rendezvous descriptor. */
353 #define AP_CONN_STATE_RENDDESC_WAIT 6
354 /** The controller will attach this connection to a circuit; it isn't our
355 * job to do so. */
356 #define AP_CONN_STATE_CONTROLLER_WAIT 7
357 /** State for a SOCKS connection: waiting for a completed circuit. */
358 #define AP_CONN_STATE_CIRCUIT_WAIT 8
359 /** State for a SOCKS connection: sent BEGIN, waiting for CONNECTED. */
360 #define AP_CONN_STATE_CONNECT_WAIT 9
361 /** State for a SOCKS connection: sent RESOLVE, waiting for RESOLVED. */
362 #define AP_CONN_STATE_RESOLVE_WAIT 10
363 /** State for a SOCKS connection: ready to send and receive. */
364 #define AP_CONN_STATE_OPEN 11
365 /** State for a transparent natd connection: waiting for original
366 * destination. */
367 #define AP_CONN_STATE_NATD_WAIT 12
368 #define AP_CONN_STATE_MAX_ 12
370 /** True iff the AP_CONN_STATE_* value <b>s</b> means that the corresponding
371 * edge connection is not attached to any circuit. */
372 #define AP_CONN_STATE_IS_UNATTACHED(s) \
373 ((s) <= AP_CONN_STATE_CIRCUIT_WAIT || (s) == AP_CONN_STATE_NATD_WAIT)
375 #define DIR_CONN_STATE_MIN_ 1
376 /** State for connection to directory server: waiting for connect(). */
377 #define DIR_CONN_STATE_CONNECTING 1
378 /** State for connection to directory server: sending HTTP request. */
379 #define DIR_CONN_STATE_CLIENT_SENDING 2
380 /** State for connection to directory server: reading HTTP response. */
381 #define DIR_CONN_STATE_CLIENT_READING 3
382 /** State for connection to directory server: happy and finished. */
383 #define DIR_CONN_STATE_CLIENT_FINISHED 4
384 /** State for connection at directory server: waiting for HTTP request. */
385 #define DIR_CONN_STATE_SERVER_COMMAND_WAIT 5
386 /** State for connection at directory server: sending HTTP response. */
387 #define DIR_CONN_STATE_SERVER_WRITING 6
388 #define DIR_CONN_STATE_MAX_ 6
390 /** True iff the purpose of <b>conn</b> means that it's a server-side
391 * directory connection. */
392 #define DIR_CONN_IS_SERVER(conn) ((conn)->purpose == DIR_PURPOSE_SERVER)
394 #define CONTROL_CONN_STATE_MIN_ 1
395 /** State for a control connection: Authenticated and accepting v1 commands. */
396 #define CONTROL_CONN_STATE_OPEN 1
397 /** State for a control connection: Waiting for authentication; speaking
398 * protocol v1. */
399 #define CONTROL_CONN_STATE_NEEDAUTH 2
400 #define CONTROL_CONN_STATE_MAX_ 2
402 #define DIR_PURPOSE_MIN_ 4
403 /** A connection to a directory server: set after a v2 rendezvous
404 * descriptor is downloaded. */
405 #define DIR_PURPOSE_HAS_FETCHED_RENDDESC_V2 4
406 /** A connection to a directory server: download one or more server
407 * descriptors. */
408 #define DIR_PURPOSE_FETCH_SERVERDESC 6
409 /** A connection to a directory server: download one or more extra-info
410 * documents. */
411 #define DIR_PURPOSE_FETCH_EXTRAINFO 7
412 /** A connection to a directory server: upload a server descriptor. */
413 #define DIR_PURPOSE_UPLOAD_DIR 8
414 /** A connection to a directory server: upload a v3 networkstatus vote. */
415 #define DIR_PURPOSE_UPLOAD_VOTE 10
416 /** A connection to a directory server: upload a v3 consensus signature */
417 #define DIR_PURPOSE_UPLOAD_SIGNATURES 11
418 /** A connection to a directory server: download one or more v3 networkstatus
419 * votes. */
420 #define DIR_PURPOSE_FETCH_STATUS_VOTE 12
421 /** A connection to a directory server: download a v3 detached signatures
422 * object for a consensus. */
423 #define DIR_PURPOSE_FETCH_DETACHED_SIGNATURES 13
424 /** A connection to a directory server: download a v3 networkstatus
425 * consensus. */
426 #define DIR_PURPOSE_FETCH_CONSENSUS 14
427 /** A connection to a directory server: download one or more directory
428 * authority certificates. */
429 #define DIR_PURPOSE_FETCH_CERTIFICATE 15
431 /** Purpose for connection at a directory server. */
432 #define DIR_PURPOSE_SERVER 16
433 /** A connection to a hidden service directory server: upload a v2 rendezvous
434 * descriptor. */
435 #define DIR_PURPOSE_UPLOAD_RENDDESC_V2 17
436 /** A connection to a hidden service directory server: download a v2 rendezvous
437 * descriptor. */
438 #define DIR_PURPOSE_FETCH_RENDDESC_V2 18
439 /** A connection to a directory server: download a microdescriptor. */
440 #define DIR_PURPOSE_FETCH_MICRODESC 19
441 #define DIR_PURPOSE_MAX_ 19
443 /** True iff <b>p</b> is a purpose corresponding to uploading data to a
444 * directory server. */
445 #define DIR_PURPOSE_IS_UPLOAD(p) \
446 ((p)==DIR_PURPOSE_UPLOAD_DIR || \
447 (p)==DIR_PURPOSE_UPLOAD_VOTE || \
448 (p)==DIR_PURPOSE_UPLOAD_SIGNATURES)
450 #define EXIT_PURPOSE_MIN_ 1
451 /** This exit stream wants to do an ordinary connect. */
452 #define EXIT_PURPOSE_CONNECT 1
453 /** This exit stream wants to do a resolve (either normal or reverse). */
454 #define EXIT_PURPOSE_RESOLVE 2
455 #define EXIT_PURPOSE_MAX_ 2
457 /* !!!! If any connection purpose is ever over 31, we must grow the type
458 * field in connection_t. */
460 /** Circuit state: I'm the origin, still haven't done all my handshakes. */
461 #define CIRCUIT_STATE_BUILDING 0
462 /** Circuit state: Waiting to process the onionskin. */
463 #define CIRCUIT_STATE_ONIONSKIN_PENDING 1
464 /** Circuit state: I'd like to deliver a create, but my n_chan is still
465 * connecting. */
466 #define CIRCUIT_STATE_CHAN_WAIT 2
467 /** Circuit state: onionskin(s) processed, ready to send/receive cells. */
468 #define CIRCUIT_STATE_OPEN 3
470 #define CIRCUIT_PURPOSE_MIN_ 1
472 /* these circuits were initiated elsewhere */
473 #define CIRCUIT_PURPOSE_OR_MIN_ 1
474 /** OR-side circuit purpose: normal circuit, at OR. */
475 #define CIRCUIT_PURPOSE_OR 1
476 /** OR-side circuit purpose: At OR, from Bob, waiting for intro from Alices. */
477 #define CIRCUIT_PURPOSE_INTRO_POINT 2
478 /** OR-side circuit purpose: At OR, from Alice, waiting for Bob. */
479 #define CIRCUIT_PURPOSE_REND_POINT_WAITING 3
480 /** OR-side circuit purpose: At OR, both circuits have this purpose. */
481 #define CIRCUIT_PURPOSE_REND_ESTABLISHED 4
482 #define CIRCUIT_PURPOSE_OR_MAX_ 4
484 /* these circuits originate at this node */
486 /* here's how circ client-side purposes work:
487 * normal circuits are C_GENERAL.
488 * circuits that are c_introducing are either on their way to
489 * becoming open, or they are open and waiting for a
490 * suitable rendcirc before they send the intro.
491 * circuits that are c_introduce_ack_wait have sent the intro,
492 * but haven't gotten a response yet.
493 * circuits that are c_establish_rend are either on their way
494 * to becoming open, or they are open and have sent the
495 * establish_rendezvous cell but haven't received an ack.
496 * circuits that are c_rend_ready are open and have received a
497 * rend ack, but haven't heard from bob yet. if they have a
498 * buildstate->pending_final_cpath then they're expecting a
499 * cell from bob, else they're not.
500 * circuits that are c_rend_ready_intro_acked are open, and
501 * some intro circ has sent its intro and received an ack.
502 * circuits that are c_rend_joined are open, have heard from
503 * bob, and are talking to him.
505 /** Client-side circuit purpose: Normal circuit, with cpath. */
506 #define CIRCUIT_PURPOSE_C_GENERAL 5
507 /** Client-side circuit purpose: at Alice, connecting to intro point. */
508 #define CIRCUIT_PURPOSE_C_INTRODUCING 6
509 /** Client-side circuit purpose: at Alice, sent INTRODUCE1 to intro point,
510 * waiting for ACK/NAK. */
511 #define CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT 7
512 /** Client-side circuit purpose: at Alice, introduced and acked, closing. */
513 #define CIRCUIT_PURPOSE_C_INTRODUCE_ACKED 8
514 /** Client-side circuit purpose: at Alice, waiting for ack. */
515 #define CIRCUIT_PURPOSE_C_ESTABLISH_REND 9
516 /** Client-side circuit purpose: at Alice, waiting for Bob. */
517 #define CIRCUIT_PURPOSE_C_REND_READY 10
518 /** Client-side circuit purpose: at Alice, waiting for Bob, INTRODUCE
519 * has been acknowledged. */
520 #define CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED 11
521 /** Client-side circuit purpose: at Alice, rendezvous established. */
522 #define CIRCUIT_PURPOSE_C_REND_JOINED 12
523 /** This circuit is used for build time measurement only */
524 #define CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT 13
525 #define CIRCUIT_PURPOSE_C_MAX_ 13
526 /** Hidden-service-side circuit purpose: at Bob, waiting for introductions. */
527 #define CIRCUIT_PURPOSE_S_ESTABLISH_INTRO 14
528 /** Hidden-service-side circuit purpose: at Bob, successfully established
529 * intro. */
530 #define CIRCUIT_PURPOSE_S_INTRO 15
531 /** Hidden-service-side circuit purpose: at Bob, connecting to rend point. */
532 #define CIRCUIT_PURPOSE_S_CONNECT_REND 16
533 /** Hidden-service-side circuit purpose: at Bob, rendezvous established. */
534 #define CIRCUIT_PURPOSE_S_REND_JOINED 17
535 /** A testing circuit; not meant to be used for actual traffic. */
536 #define CIRCUIT_PURPOSE_TESTING 18
537 /** A controller made this circuit and Tor should not use it. */
538 #define CIRCUIT_PURPOSE_CONTROLLER 19
539 /** This circuit is used for path bias probing only */
540 #define CIRCUIT_PURPOSE_PATH_BIAS_TESTING 20
541 #define CIRCUIT_PURPOSE_MAX_ 20
542 /** A catch-all for unrecognized purposes. Currently we don't expect
543 * to make or see any circuits with this purpose. */
544 #define CIRCUIT_PURPOSE_UNKNOWN 255
546 /** True iff the circuit purpose <b>p</b> is for a circuit that
547 * originated at this node. */
548 #define CIRCUIT_PURPOSE_IS_ORIGIN(p) ((p)>CIRCUIT_PURPOSE_OR_MAX_)
549 /** True iff the circuit purpose <b>p</b> is for a circuit that originated
550 * here to serve as a client. (Hidden services don't count here.) */
551 #define CIRCUIT_PURPOSE_IS_CLIENT(p) \
552 ((p)> CIRCUIT_PURPOSE_OR_MAX_ && \
553 (p)<=CIRCUIT_PURPOSE_C_MAX_)
554 /** True iff the circuit_t <b>c</b> is actually an origin_circuit_t. */
555 #define CIRCUIT_IS_ORIGIN(c) (CIRCUIT_PURPOSE_IS_ORIGIN((c)->purpose))
556 /** True iff the circuit purpose <b>p</b> is for an established rendezvous
557 * circuit. */
558 #define CIRCUIT_PURPOSE_IS_ESTABLISHED_REND(p) \
559 ((p) == CIRCUIT_PURPOSE_C_REND_JOINED || \
560 (p) == CIRCUIT_PURPOSE_S_REND_JOINED)
561 /** True iff the circuit_t c is actually an or_circuit_t */
562 #define CIRCUIT_IS_ORCIRC(c) (((circuit_t *)(c))->magic == OR_CIRCUIT_MAGIC)
564 /** How many circuits do we want simultaneously in-progress to handle
565 * a given stream? */
566 #define MIN_CIRCUITS_HANDLING_STREAM 2
568 /* These RELAY_COMMAND constants define values for relay cell commands, and
569 * must match those defined in tor-spec.txt. */
570 #define RELAY_COMMAND_BEGIN 1
571 #define RELAY_COMMAND_DATA 2
572 #define RELAY_COMMAND_END 3
573 #define RELAY_COMMAND_CONNECTED 4
574 #define RELAY_COMMAND_SENDME 5
575 #define RELAY_COMMAND_EXTEND 6
576 #define RELAY_COMMAND_EXTENDED 7
577 #define RELAY_COMMAND_TRUNCATE 8
578 #define RELAY_COMMAND_TRUNCATED 9
579 #define RELAY_COMMAND_DROP 10
580 #define RELAY_COMMAND_RESOLVE 11
581 #define RELAY_COMMAND_RESOLVED 12
582 #define RELAY_COMMAND_BEGIN_DIR 13
583 #define RELAY_COMMAND_EXTEND2 14
584 #define RELAY_COMMAND_EXTENDED2 15
586 #define RELAY_COMMAND_ESTABLISH_INTRO 32
587 #define RELAY_COMMAND_ESTABLISH_RENDEZVOUS 33
588 #define RELAY_COMMAND_INTRODUCE1 34
589 #define RELAY_COMMAND_INTRODUCE2 35
590 #define RELAY_COMMAND_RENDEZVOUS1 36
591 #define RELAY_COMMAND_RENDEZVOUS2 37
592 #define RELAY_COMMAND_INTRO_ESTABLISHED 38
593 #define RELAY_COMMAND_RENDEZVOUS_ESTABLISHED 39
594 #define RELAY_COMMAND_INTRODUCE_ACK 40
596 /* Reasons why an OR connection is closed. */
597 #define END_OR_CONN_REASON_DONE 1
598 #define END_OR_CONN_REASON_REFUSED 2 /* connection refused */
599 #define END_OR_CONN_REASON_OR_IDENTITY 3
600 #define END_OR_CONN_REASON_CONNRESET 4 /* connection reset by peer */
601 #define END_OR_CONN_REASON_TIMEOUT 5
602 #define END_OR_CONN_REASON_NO_ROUTE 6 /* no route to host/net */
603 #define END_OR_CONN_REASON_IO_ERROR 7 /* read/write error */
604 #define END_OR_CONN_REASON_RESOURCE_LIMIT 8 /* sockets, buffers, etc */
605 #define END_OR_CONN_REASON_PT_MISSING 9 /* PT failed or not available */
606 #define END_OR_CONN_REASON_MISC 10
608 /* Reasons why we (or a remote OR) might close a stream. See tor-spec.txt for
609 * documentation of these. The values must match. */
610 #define END_STREAM_REASON_MISC 1
611 #define END_STREAM_REASON_RESOLVEFAILED 2
612 #define END_STREAM_REASON_CONNECTREFUSED 3
613 #define END_STREAM_REASON_EXITPOLICY 4
614 #define END_STREAM_REASON_DESTROY 5
615 #define END_STREAM_REASON_DONE 6
616 #define END_STREAM_REASON_TIMEOUT 7
617 #define END_STREAM_REASON_NOROUTE 8
618 #define END_STREAM_REASON_HIBERNATING 9
619 #define END_STREAM_REASON_INTERNAL 10
620 #define END_STREAM_REASON_RESOURCELIMIT 11
621 #define END_STREAM_REASON_CONNRESET 12
622 #define END_STREAM_REASON_TORPROTOCOL 13
623 #define END_STREAM_REASON_NOTDIRECTORY 14
624 #define END_STREAM_REASON_ENTRYPOLICY 15
626 /* These high-numbered end reasons are not part of the official spec,
627 * and are not intended to be put in relay end cells. They are here
628 * to be more informative when sending back socks replies to the
629 * application. */
630 /* XXXX 256 is no longer used; feel free to reuse it. */
631 /** We were unable to attach the connection to any circuit at all. */
632 /* XXXX the ways we use this one don't make a lot of sense. */
633 #define END_STREAM_REASON_CANT_ATTACH 257
634 /** We can't connect to any directories at all, so we killed our streams
635 * before they can time out. */
636 #define END_STREAM_REASON_NET_UNREACHABLE 258
637 /** This is a SOCKS connection, and the client used (or misused) the SOCKS
638 * protocol in a way we couldn't handle. */
639 #define END_STREAM_REASON_SOCKSPROTOCOL 259
640 /** This is a transparent proxy connection, but we can't extract the original
641 * target address:port. */
642 #define END_STREAM_REASON_CANT_FETCH_ORIG_DEST 260
643 /** This is a connection on the NATD port, and the destination IP:Port was
644 * either ill-formed or out-of-range. */
645 #define END_STREAM_REASON_INVALID_NATD_DEST 261
646 /** The target address is in a private network (like 127.0.0.1 or 10.0.0.1);
647 * you don't want to do that over a randomly chosen exit */
648 #define END_STREAM_REASON_PRIVATE_ADDR 262
650 /** Bitwise-and this value with endreason to mask out all flags. */
651 #define END_STREAM_REASON_MASK 511
653 /** Bitwise-or this with the argument to control_event_stream_status
654 * to indicate that the reason came from an END cell. */
655 #define END_STREAM_REASON_FLAG_REMOTE 512
656 /** Bitwise-or this with the argument to control_event_stream_status
657 * to indicate that we already sent a CLOSED stream event. */
658 #define END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED 1024
659 /** Bitwise-or this with endreason to indicate that we already sent
660 * a socks reply, and no further reply needs to be sent from
661 * connection_mark_unattached_ap(). */
662 #define END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED 2048
664 /** Reason for remapping an AP connection's address: we have a cached
665 * answer. */
666 #define REMAP_STREAM_SOURCE_CACHE 1
667 /** Reason for remapping an AP connection's address: the exit node told us an
668 * answer. */
669 #define REMAP_STREAM_SOURCE_EXIT 2
671 /* 'type' values to use in RESOLVED cells. Specified in tor-spec.txt. */
672 #define RESOLVED_TYPE_HOSTNAME 0
673 #define RESOLVED_TYPE_IPV4 4
674 #define RESOLVED_TYPE_IPV6 6
675 #define RESOLVED_TYPE_ERROR_TRANSIENT 0xF0
676 #define RESOLVED_TYPE_ERROR 0xF1
678 /* Negative reasons are internal: we never send them in a DESTROY or TRUNCATE
679 * call; they only go to the controller for tracking */
681 /* Closing introduction point that were opened in parallel. */
682 #define END_CIRC_REASON_IP_NOW_REDUNDANT -4
684 /** Our post-timeout circuit time measurement period expired.
685 * We must give up now */
686 #define END_CIRC_REASON_MEASUREMENT_EXPIRED -3
688 /** We couldn't build a path for this circuit. */
689 #define END_CIRC_REASON_NOPATH -2
690 /** Catch-all "other" reason for closing origin circuits. */
691 #define END_CIRC_AT_ORIGIN -1
693 /* Reasons why we (or a remote OR) might close a circuit. See tor-spec.txt for
694 * documentation of these. */
695 #define END_CIRC_REASON_MIN_ 0
696 #define END_CIRC_REASON_NONE 0
697 #define END_CIRC_REASON_TORPROTOCOL 1
698 #define END_CIRC_REASON_INTERNAL 2
699 #define END_CIRC_REASON_REQUESTED 3
700 #define END_CIRC_REASON_HIBERNATING 4
701 #define END_CIRC_REASON_RESOURCELIMIT 5
702 #define END_CIRC_REASON_CONNECTFAILED 6
703 #define END_CIRC_REASON_OR_IDENTITY 7
704 #define END_CIRC_REASON_CHANNEL_CLOSED 8
705 #define END_CIRC_REASON_FINISHED 9
706 #define END_CIRC_REASON_TIMEOUT 10
707 #define END_CIRC_REASON_DESTROYED 11
708 #define END_CIRC_REASON_NOSUCHSERVICE 12
709 #define END_CIRC_REASON_MAX_ 12
711 /** Bitwise-OR this with the argument to circuit_mark_for_close() or
712 * control_event_circuit_status() to indicate that the reason was
713 * passed through from a destroy or truncate cell. */
714 #define END_CIRC_REASON_FLAG_REMOTE 512
716 /** Length of 'y' portion of 'y.onion' URL. */
717 #define REND_SERVICE_ID_LEN_BASE32 16
719 /** Length of 'y.onion' including '.onion' URL. */
720 #define REND_SERVICE_ADDRESS_LEN (16+1+5)
722 /** Length of a binary-encoded rendezvous service ID. */
723 #define REND_SERVICE_ID_LEN 10
725 /** Time period for which a v2 descriptor will be valid. */
726 #define REND_TIME_PERIOD_V2_DESC_VALIDITY (24*60*60)
728 /** Time period within which two sets of v2 descriptors will be uploaded in
729 * parallel. */
730 #define REND_TIME_PERIOD_OVERLAPPING_V2_DESCS (60*60)
732 /** Number of non-consecutive replicas (i.e. distributed somewhere
733 * in the ring) for a descriptor. */
734 #define REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS 2
736 /** Number of consecutive replicas for a descriptor. */
737 #define REND_NUMBER_OF_CONSECUTIVE_REPLICAS 3
739 /** Length of v2 descriptor ID (32 base32 chars = 160 bits). */
740 #define REND_DESC_ID_V2_LEN_BASE32 32
742 /** Length of the base32-encoded secret ID part of versioned hidden service
743 * descriptors. */
744 #define REND_SECRET_ID_PART_LEN_BASE32 32
746 /** Length of the base32-encoded hash of an introduction point's
747 * identity key. */
748 #define REND_INTRO_POINT_ID_LEN_BASE32 32
750 /** Length of the descriptor cookie that is used for client authorization
751 * to hidden services. */
752 #define REND_DESC_COOKIE_LEN 16
754 /** Length of the base64-encoded descriptor cookie that is used for
755 * exchanging client authorization between hidden service and client. */
756 #define REND_DESC_COOKIE_LEN_BASE64 22
758 /** Length of client identifier in encrypted introduction points for hidden
759 * service authorization type 'basic'. */
760 #define REND_BASIC_AUTH_CLIENT_ID_LEN 4
762 /** Multiple of the number of clients to which the real number of clients
763 * is padded with fake clients for hidden service authorization type
764 * 'basic'. */
765 #define REND_BASIC_AUTH_CLIENT_MULTIPLE 16
767 /** Length of client entry consisting of client identifier and encrypted
768 * session key for hidden service authorization type 'basic'. */
769 #define REND_BASIC_AUTH_CLIENT_ENTRY_LEN (REND_BASIC_AUTH_CLIENT_ID_LEN \
770 + CIPHER_KEY_LEN)
772 /** Maximum size of v2 hidden service descriptors. */
773 #define REND_DESC_MAX_SIZE (20 * 1024)
775 /** Legal characters for use in authorized client names for a hidden
776 * service. */
777 #define REND_LEGAL_CLIENTNAME_CHARACTERS \
778 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-_"
780 /** Maximum length of authorized client names for a hidden service. */
781 #define REND_CLIENTNAME_MAX_LEN 16
783 /** Length of the rendezvous cookie that is used to connect circuits at the
784 * rendezvous point. */
785 #define REND_COOKIE_LEN DIGEST_LEN
787 /** Client authorization type that a hidden service performs. */
788 typedef enum rend_auth_type_t {
789 REND_NO_AUTH = 0,
790 REND_BASIC_AUTH = 1,
791 REND_STEALTH_AUTH = 2,
792 } rend_auth_type_t;
794 /** Client-side configuration of authorization for a hidden service. */
795 typedef struct rend_service_authorization_t {
796 char descriptor_cookie[REND_DESC_COOKIE_LEN];
797 char onion_address[REND_SERVICE_ADDRESS_LEN+1];
798 rend_auth_type_t auth_type;
799 } rend_service_authorization_t;
801 /** Client- and server-side data that is used for hidden service connection
802 * establishment. Not all fields contain data depending on where this struct
803 * is used. */
804 typedef struct rend_data_t {
805 /** Onion address (without the .onion part) that a client requests. */
806 char onion_address[REND_SERVICE_ID_LEN_BASE32+1];
808 /** (Optional) descriptor cookie that is used by a client. */
809 char descriptor_cookie[REND_DESC_COOKIE_LEN];
811 /** Authorization type for accessing a service used by a client. */
812 rend_auth_type_t auth_type;
814 /** Hash of the hidden service's PK used by a service. */
815 char rend_pk_digest[DIGEST_LEN];
817 /** Rendezvous cookie used by both, client and service. */
818 char rend_cookie[REND_COOKIE_LEN];
819 } rend_data_t;
821 /** Time interval for tracking replays of DH public keys received in
822 * INTRODUCE2 cells. Used only to avoid launching multiple
823 * simultaneous attempts to connect to the same rendezvous point. */
824 #define REND_REPLAY_TIME_INTERVAL (5 * 60)
826 /** Used to indicate which way a cell is going on a circuit. */
827 typedef enum {
828 CELL_DIRECTION_IN=1, /**< The cell is moving towards the origin. */
829 CELL_DIRECTION_OUT=2, /**< The cell is moving away from the origin. */
830 } cell_direction_t;
832 /** Initial value for both sides of a circuit transmission window when the
833 * circuit is initialized. Measured in cells. */
834 #define CIRCWINDOW_START 1000
835 #define CIRCWINDOW_START_MIN 100
836 #define CIRCWINDOW_START_MAX 1000
837 /** Amount to increment a circuit window when we get a circuit SENDME. */
838 #define CIRCWINDOW_INCREMENT 100
839 /** Initial value on both sides of a stream transmission window when the
840 * stream is initialized. Measured in cells. */
841 #define STREAMWINDOW_START 500
842 /** Amount to increment a stream window when we get a stream SENDME. */
843 #define STREAMWINDOW_INCREMENT 50
845 /** Maximum number of queued cells on a circuit for which we are the
846 * midpoint before we give up and kill it. This must be >= circwindow
847 * to avoid killing innocent circuits, and >= circwindow*2 to give
848 * leaky-pipe a chance of working someday. The ORCIRC_MAX_MIDDLE_KILL_THRESH
849 * ratio controls the margin of error between emitting a warning and
850 * killing the circuit.
852 #define ORCIRC_MAX_MIDDLE_CELLS (CIRCWINDOW_START_MAX*2)
853 /** Ratio of hard (circuit kill) to soft (warning) thresholds for the
854 * ORCIRC_MAX_MIDDLE_CELLS tests.
856 #define ORCIRC_MAX_MIDDLE_KILL_THRESH (1.1f)
858 /* Cell commands. These values are defined in tor-spec.txt. */
859 #define CELL_PADDING 0
860 #define CELL_CREATE 1
861 #define CELL_CREATED 2
862 #define CELL_RELAY 3
863 #define CELL_DESTROY 4
864 #define CELL_CREATE_FAST 5
865 #define CELL_CREATED_FAST 6
866 #define CELL_VERSIONS 7
867 #define CELL_NETINFO 8
868 #define CELL_RELAY_EARLY 9
869 #define CELL_CREATE2 10
870 #define CELL_CREATED2 11
872 #define CELL_VPADDING 128
873 #define CELL_CERTS 129
874 #define CELL_AUTH_CHALLENGE 130
875 #define CELL_AUTHENTICATE 131
876 #define CELL_AUTHORIZE 132
877 #define CELL_COMMAND_MAX_ 132
879 /** How long to test reachability before complaining to the user. */
880 #define TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT (20*60)
882 /** Legal characters in a nickname. */
883 #define LEGAL_NICKNAME_CHARACTERS \
884 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
886 /** Name to use in client TLS certificates if no nickname is given. Once
887 * Tor 0.1.2.x is obsolete, we can remove this. */
888 #define DEFAULT_CLIENT_NICKNAME "client"
890 /** Name chosen by routers that don't configure nicknames */
891 #define UNNAMED_ROUTER_NICKNAME "Unnamed"
893 /** Number of bytes in a SOCKS4 header. */
894 #define SOCKS4_NETWORK_LEN 8
897 * Relay payload:
898 * Relay command [1 byte]
899 * Recognized [2 bytes]
900 * Stream ID [2 bytes]
901 * Partial SHA-1 [4 bytes]
902 * Length [2 bytes]
903 * Relay payload [498 bytes]
906 /** Number of bytes in a cell, minus cell header. */
907 #define CELL_PAYLOAD_SIZE 509
908 /** Number of bytes in a cell transmitted over the network, in the longest
909 * form */
910 #define CELL_MAX_NETWORK_SIZE 514
912 /** Maximum length of a header on a variable-length cell. */
913 #define VAR_CELL_MAX_HEADER_SIZE 7
915 static int get_cell_network_size(int wide_circ_ids);
916 static INLINE int get_cell_network_size(int wide_circ_ids)
918 return wide_circ_ids ? CELL_MAX_NETWORK_SIZE : CELL_MAX_NETWORK_SIZE - 2;
920 static int get_var_cell_header_size(int wide_circ_ids);
921 static INLINE int get_var_cell_header_size(int wide_circ_ids)
923 return wide_circ_ids ? VAR_CELL_MAX_HEADER_SIZE :
924 VAR_CELL_MAX_HEADER_SIZE - 2;
926 static int get_circ_id_size(int wide_circ_ids);
927 static INLINE int get_circ_id_size(int wide_circ_ids)
929 return wide_circ_ids ? 4 : 2;
932 /** Number of bytes in a relay cell's header (not including general cell
933 * header). */
934 #define RELAY_HEADER_SIZE (1+2+2+4+2)
935 /** Largest number of bytes that can fit in a relay cell payload. */
936 #define RELAY_PAYLOAD_SIZE (CELL_PAYLOAD_SIZE-RELAY_HEADER_SIZE)
938 /** Identifies a circuit on an or_connection */
939 typedef uint32_t circid_t;
940 /** Identifies a stream on a circuit */
941 typedef uint16_t streamid_t;
943 /* channel_t typedef; struct channel_s is in channel.h */
945 typedef struct channel_s channel_t;
947 /* channel_listener_t typedef; struct channel_listener_s is in channel.h */
949 typedef struct channel_listener_s channel_listener_t;
951 /* channel states for channel_t */
953 typedef enum {
955 * Closed state - channel is inactive
957 * Permitted transitions from:
958 * - CHANNEL_STATE_CLOSING
959 * Permitted transitions to:
960 * - CHANNEL_STATE_OPENING
962 CHANNEL_STATE_CLOSED = 0,
964 * Opening state - channel is trying to connect
966 * Permitted transitions from:
967 * - CHANNEL_STATE_CLOSED
968 * Permitted transitions to:
969 * - CHANNEL_STATE_CLOSING
970 * - CHANNEL_STATE_ERROR
971 * - CHANNEL_STATE_OPEN
973 CHANNEL_STATE_OPENING,
975 * Open state - channel is active and ready for use
977 * Permitted transitions from:
978 * - CHANNEL_STATE_MAINT
979 * - CHANNEL_STATE_OPENING
980 * Permitted transitions to:
981 * - CHANNEL_STATE_CLOSING
982 * - CHANNEL_STATE_ERROR
983 * - CHANNEL_STATE_MAINT
985 CHANNEL_STATE_OPEN,
987 * Maintenance state - channel is temporarily offline for subclass specific
988 * maintenance activities such as TLS renegotiation.
990 * Permitted transitions from:
991 * - CHANNEL_STATE_OPEN
992 * Permitted transitions to:
993 * - CHANNEL_STATE_CLOSING
994 * - CHANNEL_STATE_ERROR
995 * - CHANNEL_STATE_OPEN
997 CHANNEL_STATE_MAINT,
999 * Closing state - channel is shutting down
1001 * Permitted transitions from:
1002 * - CHANNEL_STATE_MAINT
1003 * - CHANNEL_STATE_OPEN
1004 * Permitted transitions to:
1005 * - CHANNEL_STATE_CLOSED,
1006 * - CHANNEL_STATE_ERROR
1008 CHANNEL_STATE_CLOSING,
1010 * Error state - channel has experienced a permanent error
1012 * Permitted transitions from:
1013 * - CHANNEL_STATE_CLOSING
1014 * - CHANNEL_STATE_MAINT
1015 * - CHANNEL_STATE_OPENING
1016 * - CHANNEL_STATE_OPEN
1017 * Permitted transitions to:
1018 * - None
1020 CHANNEL_STATE_ERROR,
1022 * Placeholder for maximum state value
1024 CHANNEL_STATE_LAST
1025 } channel_state_t;
1027 /* channel listener states for channel_listener_t */
1029 typedef enum {
1031 * Closed state - channel listener is inactive
1033 * Permitted transitions from:
1034 * - CHANNEL_LISTENER_STATE_CLOSING
1035 * Permitted transitions to:
1036 * - CHANNEL_LISTENER_STATE_LISTENING
1038 CHANNEL_LISTENER_STATE_CLOSED = 0,
1040 * Listening state - channel listener is listening for incoming
1041 * connections
1043 * Permitted transitions from:
1044 * - CHANNEL_LISTENER_STATE_CLOSED
1045 * Permitted transitions to:
1046 * - CHANNEL_LISTENER_STATE_CLOSING
1047 * - CHANNEL_LISTENER_STATE_ERROR
1049 CHANNEL_LISTENER_STATE_LISTENING,
1051 * Closing state - channel listener is shutting down
1053 * Permitted transitions from:
1054 * - CHANNEL_LISTENER_STATE_LISTENING
1055 * Permitted transitions to:
1056 * - CHANNEL_LISTENER_STATE_CLOSED,
1057 * - CHANNEL_LISTENER_STATE_ERROR
1059 CHANNEL_LISTENER_STATE_CLOSING,
1061 * Error state - channel listener has experienced a permanent error
1063 * Permitted transitions from:
1064 * - CHANNEL_STATE_CLOSING
1065 * - CHANNEL_STATE_LISTENING
1066 * Permitted transitions to:
1067 * - None
1069 CHANNEL_LISTENER_STATE_ERROR,
1071 * Placeholder for maximum state value
1073 CHANNEL_LISTENER_STATE_LAST
1074 } channel_listener_state_t;
1076 /* TLS channel stuff */
1078 typedef struct channel_tls_s channel_tls_t;
1080 /* circuitmux_t typedef; struct circuitmux_s is in circuitmux.h */
1082 typedef struct circuitmux_s circuitmux_t;
1084 /** Parsed onion routing cell. All communication between nodes
1085 * is via cells. */
1086 typedef struct cell_t {
1087 circid_t circ_id; /**< Circuit which received the cell. */
1088 uint8_t command; /**< Type of the cell: one of CELL_PADDING, CELL_CREATE,
1089 * CELL_DESTROY, etc */
1090 uint8_t payload[CELL_PAYLOAD_SIZE]; /**< Cell body. */
1091 } cell_t;
1093 /** Parsed variable-length onion routing cell. */
1094 typedef struct var_cell_t {
1095 /** Type of the cell: CELL_VERSIONS, etc. */
1096 uint8_t command;
1097 /** Circuit thich received the cell */
1098 circid_t circ_id;
1099 /** Number of bytes actually stored in <b>payload</b> */
1100 uint16_t payload_len;
1101 /** Payload of this cell */
1102 uint8_t payload[FLEXIBLE_ARRAY_MEMBER];
1103 } var_cell_t;
1105 /** A parsed Extended ORPort message. */
1106 typedef struct ext_or_cmd_t {
1107 uint16_t cmd; /** Command type */
1108 uint16_t len; /** Body length */
1109 char body[FLEXIBLE_ARRAY_MEMBER]; /** Message body */
1110 } ext_or_cmd_t;
1112 /** A cell as packed for writing to the network. */
1113 typedef struct packed_cell_t {
1114 /** Next cell queued on this circuit. */
1115 TOR_SIMPLEQ_ENTRY(packed_cell_t) next;
1116 char body[CELL_MAX_NETWORK_SIZE]; /**< Cell as packed for network. */
1117 uint32_t inserted_time; /**< Time (in milliseconds since epoch, with high
1118 * bits truncated) when this cell was inserted. */
1119 } packed_cell_t;
1121 /** A queue of cells on a circuit, waiting to be added to the
1122 * or_connection_t's outbuf. */
1123 typedef struct cell_queue_t {
1124 /** Linked list of packed_cell_t*/
1125 TOR_SIMPLEQ_HEAD(cell_simpleq, packed_cell_t) head;
1126 int n; /**< The number of cells in the queue. */
1127 } cell_queue_t;
1129 /** Beginning of a RELAY cell payload. */
1130 typedef struct {
1131 uint8_t command; /**< The end-to-end relay command. */
1132 uint16_t recognized; /**< Used to tell whether cell is for us. */
1133 streamid_t stream_id; /**< Which stream is this cell associated with? */
1134 char integrity[4]; /**< Used to tell whether cell is corrupted. */
1135 uint16_t length; /**< How long is the payload body? */
1136 } relay_header_t;
1138 typedef struct buf_t buf_t;
1139 typedef struct socks_request_t socks_request_t;
1140 #ifdef USE_BUFFEREVENTS
1141 #define generic_buffer_t struct evbuffer
1142 #else
1143 #define generic_buffer_t buf_t
1144 #endif
1146 typedef struct entry_port_cfg_t {
1147 /* Client port types (socks, dns, trans, natd) only: */
1148 uint8_t isolation_flags; /**< Zero or more isolation flags */
1149 int session_group; /**< A session group, or -1 if this port is not in a
1150 * session group. */
1152 /* Socks only: */
1153 /** When both no-auth and user/pass are advertised by a SOCKS client, select
1154 * no-auth. */
1155 unsigned int socks_prefer_no_auth : 1;
1157 /* Client port types only: */
1158 unsigned int ipv4_traffic : 1;
1159 unsigned int ipv6_traffic : 1;
1160 unsigned int prefer_ipv6 : 1;
1162 /** For a socks listener: should we cache IPv4/IPv6 DNS information that
1163 * exit nodes tell us?
1165 * @{ */
1166 unsigned int cache_ipv4_answers : 1;
1167 unsigned int cache_ipv6_answers : 1;
1168 /** @} */
1169 /** For a socks listeners: if we find an answer in our client-side DNS cache,
1170 * should we use it?
1172 * @{ */
1173 unsigned int use_cached_ipv4_answers : 1;
1174 unsigned int use_cached_ipv6_answers : 1;
1175 /** @} */
1176 /** For socks listeners: When we can automap an address to IPv4 or IPv6,
1177 * do we prefer IPv6? */
1178 unsigned int prefer_ipv6_virtaddr : 1;
1180 } entry_port_cfg_t;
1182 typedef struct server_port_cfg_t {
1183 /* Server port types (or, dir) only: */
1184 unsigned int no_advertise : 1;
1185 unsigned int no_listen : 1;
1186 unsigned int all_addrs : 1;
1187 unsigned int bind_ipv4_only : 1;
1188 unsigned int bind_ipv6_only : 1;
1189 } server_port_cfg_t;
1191 /* Values for connection_t.magic: used to make sure that downcasts (casts from
1192 * connection_t to foo_connection_t) are safe. */
1193 #define BASE_CONNECTION_MAGIC 0x7C3C304Eu
1194 #define OR_CONNECTION_MAGIC 0x7D31FF03u
1195 #define EDGE_CONNECTION_MAGIC 0xF0374013u
1196 #define ENTRY_CONNECTION_MAGIC 0xbb4a5703
1197 #define DIR_CONNECTION_MAGIC 0x9988ffeeu
1198 #define CONTROL_CONNECTION_MAGIC 0x8abc765du
1199 #define LISTENER_CONNECTION_MAGIC 0x1a1ac741u
1201 /** Description of a connection to another host or process, and associated
1202 * data.
1204 * A connection is named based on what it's connected to -- an "OR
1205 * connection" has a Tor node on the other end, an "exit
1206 * connection" has a website or other server on the other end, and an
1207 * "AP connection" has an application proxy (and thus a user) on the
1208 * other end.
1210 * Every connection has a type and a state. Connections never change
1211 * their type, but can go through many state changes in their lifetime.
1213 * Every connection has two associated input and output buffers.
1214 * Listeners don't use them. For non-listener connections, incoming
1215 * data is appended to conn->inbuf, and outgoing data is taken from
1216 * conn->outbuf. Connections differ primarily in the functions called
1217 * to fill and drain these buffers.
1219 typedef struct connection_t {
1220 uint32_t magic; /**< For memory debugging: must equal one of
1221 * *_CONNECTION_MAGIC. */
1223 uint8_t state; /**< Current state of this connection. */
1224 unsigned int type:5; /**< What kind of connection is this? */
1225 unsigned int purpose:5; /**< Only used for DIR and EXIT types currently. */
1227 /* The next fields are all one-bit booleans. Some are only applicable to
1228 * connection subtypes, but we hold them here anyway, to save space.
1230 unsigned int read_blocked_on_bw:1; /**< Boolean: should we start reading
1231 * again once the bandwidth throttler allows it? */
1232 unsigned int write_blocked_on_bw:1; /**< Boolean: should we start writing
1233 * again once the bandwidth throttler allows
1234 * writes? */
1235 unsigned int hold_open_until_flushed:1; /**< Despite this connection's being
1236 * marked for close, do we flush it
1237 * before closing it? */
1238 unsigned int inbuf_reached_eof:1; /**< Boolean: did read() return 0 on this
1239 * conn? */
1240 /** Set to 1 when we're inside connection_flushed_some to keep us from
1241 * calling connection_handle_write() recursively. */
1242 unsigned int in_flushed_some:1;
1243 /** True if connection_handle_write is currently running on this connection.
1245 unsigned int in_connection_handle_write:1;
1247 /* For linked connections:
1249 unsigned int linked:1; /**< True if there is, or has been, a linked_conn. */
1250 /** True iff we'd like to be notified about read events from the
1251 * linked conn. */
1252 unsigned int reading_from_linked_conn:1;
1253 /** True iff we're willing to write to the linked conn. */
1254 unsigned int writing_to_linked_conn:1;
1255 /** True iff we're currently able to read on the linked conn, and our
1256 * read_event should be made active with libevent. */
1257 unsigned int active_on_link:1;
1258 /** True iff we've called connection_close_immediate() on this linked
1259 * connection. */
1260 unsigned int linked_conn_is_closed:1;
1262 /** CONNECT/SOCKS proxy client handshake state (for outgoing connections). */
1263 unsigned int proxy_state:4;
1265 /** Our socket; set to TOR_INVALID_SOCKET if this connection is closed,
1266 * or has no socket. */
1267 tor_socket_t s;
1268 int conn_array_index; /**< Index into the global connection array. */
1270 struct event *read_event; /**< Libevent event structure. */
1271 struct event *write_event; /**< Libevent event structure. */
1272 buf_t *inbuf; /**< Buffer holding data read over this connection. */
1273 buf_t *outbuf; /**< Buffer holding data to write over this connection. */
1274 size_t outbuf_flushlen; /**< How much data should we try to flush from the
1275 * outbuf? */
1276 time_t timestamp_lastread; /**< When was the last time libevent said we could
1277 * read? */
1278 time_t timestamp_lastwritten; /**< When was the last time libevent said we
1279 * could write? */
1281 #ifdef USE_BUFFEREVENTS
1282 struct bufferevent *bufev; /**< A Libevent buffered IO structure. */
1283 #endif
1285 time_t timestamp_created; /**< When was this connection_t created? */
1287 /* XXXX_IP6 make this IPv6-capable */
1288 int socket_family; /**< Address family of this connection's socket. Usually
1289 * AF_INET, but it can also be AF_UNIX, or in the future
1290 * AF_INET6 */
1291 tor_addr_t addr; /**< IP of the other side of the connection; used to
1292 * identify routers, along with port. */
1293 uint16_t port; /**< If non-zero, port on the other end
1294 * of the connection. */
1295 uint16_t marked_for_close; /**< Should we close this conn on the next
1296 * iteration of the main loop? (If true, holds
1297 * the line number where this connection was
1298 * marked.) */
1299 const char *marked_for_close_file; /**< For debugging: in which file were
1300 * we marked for close? */
1301 char *address; /**< FQDN (or IP) of the guy on the other end.
1302 * strdup into this, because free_connection() frees it. */
1303 /** Another connection that's connected to this one in lieu of a socket. */
1304 struct connection_t *linked_conn;
1306 /** Unique identifier for this connection on this Tor instance. */
1307 uint64_t global_identifier;
1309 /** Bytes read since last call to control_event_conn_bandwidth_used().
1310 * Only used if we're configured to emit CONN_BW events. */
1311 uint32_t n_read_conn_bw;
1313 /** Bytes written since last call to control_event_conn_bandwidth_used().
1314 * Only used if we're configured to emit CONN_BW events. */
1315 uint32_t n_written_conn_bw;
1316 } connection_t;
1318 /** Subtype of connection_t; used for a listener socket. */
1319 typedef struct listener_connection_t {
1320 connection_t base_;
1322 /** If the connection is a CONN_TYPE_AP_DNS_LISTENER, this field points
1323 * to the evdns_server_port it uses to listen to and answer connections. */
1324 struct evdns_server_port *dns_server_port;
1326 entry_port_cfg_t entry_cfg;
1328 } listener_connection_t;
1330 /** Minimum length of the random part of an AUTH_CHALLENGE cell. */
1331 #define OR_AUTH_CHALLENGE_LEN 32
1334 * @name Certificate types for CERTS cells.
1336 * These values are defined by the protocol, and affect how an X509
1337 * certificate in a CERTS cell is interpreted and used.
1339 * @{ */
1340 /** A certificate that authenticates a TLS link key. The subject key
1341 * must match the key used in the TLS handshake; it must be signed by
1342 * the identity key. */
1343 #define OR_CERT_TYPE_TLS_LINK 1
1344 /** A self-signed identity certificate. The subject key must be a
1345 * 1024-bit RSA key. */
1346 #define OR_CERT_TYPE_ID_1024 2
1347 /** A certificate that authenticates a key used in an AUTHENTICATE cell
1348 * in the v3 handshake. The subject key must be a 1024-bit RSA key; it
1349 * must be signed by the identity key */
1350 #define OR_CERT_TYPE_AUTH_1024 3
1351 /**@}*/
1353 /** The one currently supported type of AUTHENTICATE cell. It contains
1354 * a bunch of structures signed with an RSA1024 key. The signed
1355 * structures include a HMAC using negotiated TLS secrets, and a digest
1356 * of all cells sent or received before the AUTHENTICATE cell (including
1357 * the random server-generated AUTH_CHALLENGE cell).
1359 #define AUTHTYPE_RSA_SHA256_TLSSECRET 1
1361 /** The length of the part of the AUTHENTICATE cell body that the client and
1362 * server can generate independently (when using RSA_SHA256_TLSSECRET). It
1363 * contains everything except the client's timestamp, the client's randomly
1364 * generated nonce, and the signature. */
1365 #define V3_AUTH_FIXED_PART_LEN (8+(32*6))
1366 /** The length of the part of the AUTHENTICATE cell body that the client
1367 * signs. */
1368 #define V3_AUTH_BODY_LEN (V3_AUTH_FIXED_PART_LEN + 8 + 16)
1370 /** Stores flags and information related to the portion of a v2/v3 Tor OR
1371 * connection handshake that happens after the TLS handshake is finished.
1373 typedef struct or_handshake_state_t {
1374 /** When was the VERSIONS cell sent on this connection? Used to get
1375 * an estimate of the skew in the returning NETINFO reply. */
1376 time_t sent_versions_at;
1377 /** True iff we originated this connection */
1378 unsigned int started_here : 1;
1379 /** True iff we have received and processed a VERSIONS cell. */
1380 unsigned int received_versions : 1;
1381 /** True iff we have received and processed an AUTH_CHALLENGE cell */
1382 unsigned int received_auth_challenge : 1;
1383 /** True iff we have received and processed a CERTS cell. */
1384 unsigned int received_certs_cell : 1;
1385 /** True iff we have received and processed an AUTHENTICATE cell */
1386 unsigned int received_authenticate : 1;
1388 /* True iff we've received valid authentication to some identity. */
1389 unsigned int authenticated : 1;
1391 /* True iff we have sent a netinfo cell */
1392 unsigned int sent_netinfo : 1;
1394 /** True iff we should feed outgoing cells into digest_sent and
1395 * digest_received respectively.
1397 * From the server's side of the v3 handshake, we want to capture everything
1398 * from the VERSIONS cell through and including the AUTH_CHALLENGE cell.
1399 * From the client's, we want to capture everything from the VERSIONS cell
1400 * through but *not* including the AUTHENTICATE cell.
1402 * @{ */
1403 unsigned int digest_sent_data : 1;
1404 unsigned int digest_received_data : 1;
1405 /**@}*/
1407 /** Identity digest that we have received and authenticated for our peer
1408 * on this connection. */
1409 uint8_t authenticated_peer_id[DIGEST_LEN];
1411 /** Digests of the cells that we have sent or received as part of a V3
1412 * handshake. Used for making and checking AUTHENTICATE cells.
1414 * @{
1416 crypto_digest_t *digest_sent;
1417 crypto_digest_t *digest_received;
1418 /** @} */
1420 /** Certificates that a connection initiator sent us in a CERTS cell; we're
1421 * holding on to them until we get an AUTHENTICATE cell.
1423 * @{
1425 /** The cert for the key that's supposed to sign the AUTHENTICATE cell */
1426 tor_cert_t *auth_cert;
1427 /** A self-signed identity certificate */
1428 tor_cert_t *id_cert;
1429 /**@}*/
1430 } or_handshake_state_t;
1432 /** Length of Extended ORPort connection identifier. */
1433 #define EXT_OR_CONN_ID_LEN DIGEST_LEN /* 20 */
1435 * OR_CONN_HIGHWATER and OR_CONN_LOWWATER moved from connection_or.c so
1436 * channeltls.c can see them too.
1439 /** When adding cells to an OR connection's outbuf, keep adding until the
1440 * outbuf is at least this long, or we run out of cells. */
1441 #define OR_CONN_HIGHWATER (32*1024)
1443 /** Add cells to an OR connection's outbuf whenever the outbuf's data length
1444 * drops below this size. */
1445 #define OR_CONN_LOWWATER (16*1024)
1447 /** Subtype of connection_t for an "OR connection" -- that is, one that speaks
1448 * cells over TLS. */
1449 typedef struct or_connection_t {
1450 connection_t base_;
1452 /** Hash of the public RSA key for the other side's identity key, or zeroes
1453 * if the other side hasn't shown us a valid identity key. */
1454 char identity_digest[DIGEST_LEN];
1456 /** Extended ORPort connection identifier. */
1457 char *ext_or_conn_id;
1458 /** This is the ClientHash value we expect to receive from the
1459 * client during the Extended ORPort authentication protocol. We
1460 * compute it upon receiving the ClientNoce from the client, and we
1461 * compare it with the acual ClientHash value sent by the
1462 * client. */
1463 char *ext_or_auth_correct_client_hash;
1464 /** String carrying the name of the pluggable transport
1465 * (e.g. "obfs2") that is obfuscating this connection. If no
1466 * pluggable transports are used, it's NULL. */
1467 char *ext_or_transport;
1469 char *nickname; /**< Nickname of OR on other side (if any). */
1471 tor_tls_t *tls; /**< TLS connection state. */
1472 int tls_error; /**< Last tor_tls error code. */
1473 /** When we last used this conn for any client traffic. If not
1474 * recent, we can rate limit it further. */
1476 /* Channel using this connection */
1477 channel_tls_t *chan;
1479 tor_addr_t real_addr; /**< The actual address that this connection came from
1480 * or went to. The <b>addr</b> field is prone to
1481 * getting overridden by the address from the router
1482 * descriptor matching <b>identity_digest</b>. */
1484 /** Should this connection be used for extending circuits to the server
1485 * matching the <b>identity_digest</b> field? Set to true if we're pretty
1486 * sure we aren't getting MITMed, either because we're connected to an
1487 * address listed in a server descriptor, or because an authenticated
1488 * NETINFO cell listed the address we're connected to as recognized. */
1489 unsigned int is_canonical:1;
1491 /** True iff we have decided that the other end of this connection
1492 * is a client. Connections with this flag set should never be used
1493 * to satisfy an EXTEND request. */
1494 unsigned int is_connection_with_client:1;
1495 /** True iff this is an outgoing connection. */
1496 unsigned int is_outgoing:1;
1497 unsigned int proxy_type:2; /**< One of PROXY_NONE...PROXY_SOCKS5 */
1498 unsigned int wide_circ_ids:1;
1499 /** True iff this connection has had its bootstrap failure logged with
1500 * control_event_bootstrap_problem. */
1501 unsigned int have_noted_bootstrap_problem:1;
1503 uint16_t link_proto; /**< What protocol version are we using? 0 for
1504 * "none negotiated yet." */
1505 uint16_t idle_timeout; /**< How long can this connection sit with no
1506 * circuits on it before we close it? Based on
1507 * IDLE_CIRCUIT_TIMEOUT_{NON,}CANONICAL and
1508 * on is_canonical, randomized. */
1509 or_handshake_state_t *handshake_state; /**< If we are setting this connection
1510 * up, state information to do so. */
1512 time_t timestamp_lastempty; /**< When was the outbuf last completely empty?*/
1514 /* bandwidth* and *_bucket only used by ORs in OPEN state: */
1515 int bandwidthrate; /**< Bytes/s added to the bucket. (OPEN ORs only.) */
1516 int bandwidthburst; /**< Max bucket size for this conn. (OPEN ORs only.) */
1517 #ifndef USE_BUFFEREVENTS
1518 int read_bucket; /**< When this hits 0, stop receiving. Every second we
1519 * add 'bandwidthrate' to this, capping it at
1520 * bandwidthburst. (OPEN ORs only) */
1521 int write_bucket; /**< When this hits 0, stop writing. Like read_bucket. */
1522 #else
1523 /** A rate-limiting configuration object to determine how this connection
1524 * set its read- and write- limits. */
1525 /* XXXX we could share this among all connections. */
1526 struct ev_token_bucket_cfg *bucket_cfg;
1527 #endif
1529 struct or_connection_t *next_with_same_id; /**< Next connection with same
1530 * identity digest as this one. */
1531 /** Last emptied read token bucket in msec since midnight; only used if
1532 * TB_EMPTY events are enabled. */
1533 uint32_t read_emptied_time;
1534 /** Last emptied write token bucket in msec since midnight; only used if
1535 * TB_EMPTY events are enabled. */
1536 uint32_t write_emptied_time;
1539 * Count the number of bytes flushed out on this orconn, and the number of
1540 * bytes TLS actually sent - used for overhead estimation for scheduling.
1542 uint64_t bytes_xmitted, bytes_xmitted_by_tls;
1543 } or_connection_t;
1545 /** Subtype of connection_t for an "edge connection" -- that is, an entry (ap)
1546 * connection, or an exit. */
1547 typedef struct edge_connection_t {
1548 connection_t base_;
1550 struct edge_connection_t *next_stream; /**< Points to the next stream at this
1551 * edge, if any */
1552 int package_window; /**< How many more relay cells can I send into the
1553 * circuit? */
1554 int deliver_window; /**< How many more relay cells can end at me? */
1556 struct circuit_t *on_circuit; /**< The circuit (if any) that this edge
1557 * connection is using. */
1559 /** A pointer to which node in the circ this conn exits at. Set for AP
1560 * connections and for hidden service exit connections. */
1561 struct crypt_path_t *cpath_layer;
1562 /** What rendezvous service are we querying for (if an AP) or providing (if
1563 * an exit)? */
1564 rend_data_t *rend_data;
1566 uint32_t address_ttl; /**< TTL for address-to-addr mapping on exit
1567 * connection. Exit connections only. */
1568 uint32_t begincell_flags; /** Flags sent or received in the BEGIN cell
1569 * for this connection */
1571 streamid_t stream_id; /**< The stream ID used for this edge connection on its
1572 * circuit */
1574 /** The reason why this connection is closing; passed to the controller. */
1575 uint16_t end_reason;
1577 /** Bytes read since last call to control_event_stream_bandwidth_used() */
1578 uint32_t n_read;
1580 /** Bytes written since last call to control_event_stream_bandwidth_used() */
1581 uint32_t n_written;
1583 /** True iff this connection is for a DNS request only. */
1584 unsigned int is_dns_request:1;
1585 /** True iff this connection is for a PTR DNS request. (exit only) */
1586 unsigned int is_reverse_dns_lookup:1;
1588 unsigned int edge_has_sent_end:1; /**< For debugging; only used on edge
1589 * connections. Set once we've set the stream end,
1590 * and check in connection_about_to_close_connection().
1592 /** True iff we've blocked reading until the circuit has fewer queued
1593 * cells. */
1594 unsigned int edge_blocked_on_circ:1;
1596 /** Unique ID for directory requests; this used to be in connection_t, but
1597 * that's going away and being used on channels instead. We still tag
1598 * edge connections with dirreq_id from circuits, so it's copied here. */
1599 uint64_t dirreq_id;
1600 } edge_connection_t;
1602 /** Subtype of edge_connection_t for an "entry connection" -- that is, a SOCKS
1603 * connection, a DNS request, a TransPort connection or a NATD connection */
1604 typedef struct entry_connection_t {
1605 edge_connection_t edge_;
1607 /** Nickname of planned exit node -- used with .exit support. */
1608 char *chosen_exit_name;
1610 socks_request_t *socks_request; /**< SOCKS structure describing request (AP
1611 * only.) */
1613 /* === Isolation related, AP only. === */
1614 entry_port_cfg_t entry_cfg;
1615 /** AP only: The newnym epoch in which we created this connection. */
1616 unsigned nym_epoch;
1618 /** AP only: The original requested address before we rewrote it. */
1619 char *original_dest_address;
1620 /* Other fields to isolate on already exist. The ClientAddr is addr. The
1621 ClientProtocol is a combination of type and socks_request->
1622 socks_version. SocksAuth is socks_request->username/password.
1623 DestAddr is in socks_request->address. */
1625 /** Number of times we've reassigned this application connection to
1626 * a new circuit. We keep track because the timeout is longer if we've
1627 * already retried several times. */
1628 uint8_t num_socks_retries;
1630 /** For AP connections only: buffer for data that we have sent
1631 * optimistically, which we might need to re-send if we have to
1632 * retry this connection. */
1633 generic_buffer_t *pending_optimistic_data;
1634 /* For AP connections only: buffer for data that we previously sent
1635 * optimistically which we are currently re-sending as we retry this
1636 * connection. */
1637 generic_buffer_t *sending_optimistic_data;
1639 /** If this is a DNSPort connection, this field holds the pending DNS
1640 * request that we're going to try to answer. */
1641 struct evdns_server_request *dns_server_request;
1643 #define NUM_CIRCUITS_LAUNCHED_THRESHOLD 10
1644 /** Number of times we've launched a circuit to handle this stream. If
1645 * it gets too high, that could indicate an inconsistency between our
1646 * "launch a circuit to handle this stream" logic and our "attach our
1647 * stream to one of the available circuits" logic. */
1648 unsigned int num_circuits_launched:4;
1650 /** True iff this stream must attach to a one-hop circuit (e.g. for
1651 * begin_dir). */
1652 unsigned int want_onehop:1;
1653 /** True iff this stream should use a BEGIN_DIR relay command to establish
1654 * itself rather than BEGIN (either via onehop or via a whole circuit). */
1655 unsigned int use_begindir:1;
1657 /** For AP connections only. If 1, and we fail to reach the chosen exit,
1658 * stop requiring it. */
1659 unsigned int chosen_exit_optional:1;
1660 /** For AP connections only. If non-zero, this exit node was picked as
1661 * a result of the TrackHostExit, and the value decrements every time
1662 * we fail to complete a circuit to our chosen exit -- if it reaches
1663 * zero, abandon the associated mapaddress. */
1664 unsigned int chosen_exit_retries:3;
1666 /** True iff this is an AP connection that came from a transparent or
1667 * NATd connection */
1668 unsigned int is_transparent_ap:1;
1670 /** For AP connections only: Set if this connection's target exit node
1671 * allows optimistic data (that is, data sent on this stream before
1672 * the exit has sent a CONNECTED cell) and we have chosen to use it.
1674 unsigned int may_use_optimistic_data : 1;
1676 /** Are we a socks SocksSocket listener? */
1677 unsigned int is_socks_socket:1;
1678 } entry_connection_t;
1680 typedef enum {
1681 DIR_SPOOL_NONE=0, DIR_SPOOL_SERVER_BY_DIGEST, DIR_SPOOL_SERVER_BY_FP,
1682 DIR_SPOOL_EXTRA_BY_DIGEST, DIR_SPOOL_EXTRA_BY_FP,
1683 DIR_SPOOL_CACHED_DIR, DIR_SPOOL_NETWORKSTATUS,
1684 DIR_SPOOL_MICRODESC, /* NOTE: if we add another entry, add another bit. */
1685 } dir_spool_source_t;
1686 #define dir_spool_source_bitfield_t ENUM_BF(dir_spool_source_t)
1688 /** Subtype of connection_t for an "directory connection" -- that is, an HTTP
1689 * connection to retrieve or serve directory material. */
1690 typedef struct dir_connection_t {
1691 connection_t base_;
1693 /** Which 'resource' did we ask the directory for? This is typically the part
1694 * of the URL string that defines, relative to the directory conn purpose,
1695 * what thing we want. For example, in router descriptor downloads by
1696 * descriptor digest, it contains "d/", then one ore more +-separated
1697 * fingerprints.
1699 char *requested_resource;
1700 unsigned int dirconn_direct:1; /**< Is this dirconn direct, or via Tor? */
1702 /* Used only for server sides of some dir connections, to implement
1703 * "spooling" of directory material to the outbuf. Otherwise, we'd have
1704 * to append everything to the outbuf in one enormous chunk. */
1705 /** What exactly are we spooling right now? */
1706 dir_spool_source_bitfield_t dir_spool_src : 3;
1708 /** If we're fetching descriptors, what router purpose shall we assign
1709 * to them? */
1710 uint8_t router_purpose;
1711 /** List of fingerprints for networkstatuses or descriptors to be spooled. */
1712 smartlist_t *fingerprint_stack;
1713 /** A cached_dir_t object that we're currently spooling out */
1714 struct cached_dir_t *cached_dir;
1715 /** The current offset into cached_dir. */
1716 off_t cached_dir_offset;
1717 /** The zlib object doing on-the-fly compression for spooled data. */
1718 tor_zlib_state_t *zlib_state;
1720 /** What rendezvous service are we querying for? */
1721 rend_data_t *rend_data;
1723 char identity_digest[DIGEST_LEN]; /**< Hash of the public RSA key for
1724 * the directory server's signing key. */
1726 /** Unique ID for directory requests; this used to be in connection_t, but
1727 * that's going away and being used on channels instead. The dirserver still
1728 * needs this for the incoming side, so it's moved here. */
1729 uint64_t dirreq_id;
1730 } dir_connection_t;
1732 /** Subtype of connection_t for an connection to a controller. */
1733 typedef struct control_connection_t {
1734 connection_t base_;
1736 uint64_t event_mask; /**< Bitfield: which events does this controller
1737 * care about?
1738 * EVENT_MAX_ is >31, so we need a 64 bit mask */
1740 /** True if we have sent a protocolinfo reply on this connection. */
1741 unsigned int have_sent_protocolinfo:1;
1742 /** True if we have received a takeownership command on this
1743 * connection. */
1744 unsigned int is_owning_control_connection:1;
1746 /** If we have sent an AUTHCHALLENGE reply on this connection and
1747 * have not received a successful AUTHENTICATE command, points to
1748 * the value which the client must send to authenticate itself;
1749 * otherwise, NULL. */
1750 char *safecookie_client_hash;
1752 /** Amount of space allocated in incoming_cmd. */
1753 uint32_t incoming_cmd_len;
1754 /** Number of bytes currently stored in incoming_cmd. */
1755 uint32_t incoming_cmd_cur_len;
1756 /** A control command that we're reading from the inbuf, but which has not
1757 * yet arrived completely. */
1758 char *incoming_cmd;
1759 } control_connection_t;
1761 /** Cast a connection_t subtype pointer to a connection_t **/
1762 #define TO_CONN(c) (&(((c)->base_)))
1763 /** Helper macro: Given a pointer to to.base_, of type from*, return &to. */
1764 #define DOWNCAST(to, ptr) ((to*)SUBTYPE_P(ptr, to, base_))
1766 /** Cast a entry_connection_t subtype pointer to a edge_connection_t **/
1767 #define ENTRY_TO_EDGE_CONN(c) (&(((c))->edge_))
1768 /** Cast a entry_connection_t subtype pointer to a connection_t **/
1769 #define ENTRY_TO_CONN(c) (TO_CONN(ENTRY_TO_EDGE_CONN(c)))
1771 /** Convert a connection_t* to an or_connection_t*; assert if the cast is
1772 * invalid. */
1773 static or_connection_t *TO_OR_CONN(connection_t *);
1774 /** Convert a connection_t* to a dir_connection_t*; assert if the cast is
1775 * invalid. */
1776 static dir_connection_t *TO_DIR_CONN(connection_t *);
1777 /** Convert a connection_t* to an edge_connection_t*; assert if the cast is
1778 * invalid. */
1779 static edge_connection_t *TO_EDGE_CONN(connection_t *);
1780 /** Convert a connection_t* to an entry_connection_t*; assert if the cast is
1781 * invalid. */
1782 static entry_connection_t *TO_ENTRY_CONN(connection_t *);
1783 /** Convert a edge_connection_t* to an entry_connection_t*; assert if the cast
1784 * is invalid. */
1785 static entry_connection_t *EDGE_TO_ENTRY_CONN(edge_connection_t *);
1786 /** Convert a connection_t* to an control_connection_t*; assert if the cast is
1787 * invalid. */
1788 static control_connection_t *TO_CONTROL_CONN(connection_t *);
1789 /** Convert a connection_t* to an listener_connection_t*; assert if the cast is
1790 * invalid. */
1791 static listener_connection_t *TO_LISTENER_CONN(connection_t *);
1793 static INLINE or_connection_t *TO_OR_CONN(connection_t *c)
1795 tor_assert(c->magic == OR_CONNECTION_MAGIC);
1796 return DOWNCAST(or_connection_t, c);
1798 static INLINE dir_connection_t *TO_DIR_CONN(connection_t *c)
1800 tor_assert(c->magic == DIR_CONNECTION_MAGIC);
1801 return DOWNCAST(dir_connection_t, c);
1803 static INLINE edge_connection_t *TO_EDGE_CONN(connection_t *c)
1805 tor_assert(c->magic == EDGE_CONNECTION_MAGIC ||
1806 c->magic == ENTRY_CONNECTION_MAGIC);
1807 return DOWNCAST(edge_connection_t, c);
1809 static INLINE entry_connection_t *TO_ENTRY_CONN(connection_t *c)
1811 tor_assert(c->magic == ENTRY_CONNECTION_MAGIC);
1812 return (entry_connection_t*) SUBTYPE_P(c, entry_connection_t, edge_.base_);
1814 static INLINE entry_connection_t *EDGE_TO_ENTRY_CONN(edge_connection_t *c)
1816 tor_assert(c->base_.magic == ENTRY_CONNECTION_MAGIC);
1817 return (entry_connection_t*) SUBTYPE_P(c, entry_connection_t, edge_);
1819 static INLINE control_connection_t *TO_CONTROL_CONN(connection_t *c)
1821 tor_assert(c->magic == CONTROL_CONNECTION_MAGIC);
1822 return DOWNCAST(control_connection_t, c);
1824 static INLINE listener_connection_t *TO_LISTENER_CONN(connection_t *c)
1826 tor_assert(c->magic == LISTENER_CONNECTION_MAGIC);
1827 return DOWNCAST(listener_connection_t, c);
1830 /* Conditional macros to help write code that works whether bufferevents are
1831 disabled or not.
1833 We can't just write:
1834 if (conn->bufev) {
1835 do bufferevent stuff;
1836 } else {
1837 do other stuff;
1839 because the bufferevent stuff won't even compile unless we have a fairly
1840 new version of Libevent. Instead, we say:
1841 IF_HAS_BUFFEREVENT(conn, { do_bufferevent_stuff } );
1843 IF_HAS_BUFFEREVENT(conn, {
1844 do bufferevent stuff;
1845 }) ELSE_IF_NO_BUFFEREVENT {
1846 do non-bufferevent stuff;
1848 If we're compiling with bufferevent support, then the macros expand more or
1849 less to:
1850 if (conn->bufev) {
1851 do_bufferevent_stuff;
1852 } else {
1853 do non-bufferevent stuff;
1855 and if we aren't using bufferevents, they expand more or less to:
1856 { do non-bufferevent stuff; }
1858 #ifdef USE_BUFFEREVENTS
1859 #define HAS_BUFFEREVENT(c) (((c)->bufev) != NULL)
1860 #define IF_HAS_BUFFEREVENT(c, stmt) \
1861 if ((c)->bufev) do { \
1862 stmt ; \
1863 } while (0)
1864 #define ELSE_IF_NO_BUFFEREVENT ; else
1865 #define IF_HAS_NO_BUFFEREVENT(c) \
1866 if (NULL == (c)->bufev)
1867 #else
1868 #define HAS_BUFFEREVENT(c) (0)
1869 #define IF_HAS_BUFFEREVENT(c, stmt) (void)0
1870 #define ELSE_IF_NO_BUFFEREVENT ;
1871 #define IF_HAS_NO_BUFFEREVENT(c) \
1872 if (1)
1873 #endif
1875 /** What action type does an address policy indicate: accept or reject? */
1876 typedef enum {
1877 ADDR_POLICY_ACCEPT=1,
1878 ADDR_POLICY_REJECT=2,
1879 } addr_policy_action_t;
1880 #define addr_policy_action_bitfield_t ENUM_BF(addr_policy_action_t)
1882 /** A reference-counted address policy rule. */
1883 typedef struct addr_policy_t {
1884 int refcnt; /**< Reference count */
1885 /** What to do when the policy matches.*/
1886 addr_policy_action_bitfield_t policy_type:2;
1887 unsigned int is_private:1; /**< True iff this is the pseudo-address,
1888 * "private". */
1889 unsigned int is_canonical:1; /**< True iff this policy is the canonical
1890 * copy (stored in a hash table to avoid
1891 * duplication of common policies) */
1892 maskbits_t maskbits; /**< Accept/reject all addresses <b>a</b> such that the
1893 * first <b>maskbits</b> bits of <b>a</b> match
1894 * <b>addr</b>. */
1895 /** Base address to accept or reject.
1897 * Note that wildcards are treated
1898 * differntly depending on address family. An AF_UNSPEC address means
1899 * "All addresses, IPv4 or IPv6." An AF_INET address with maskbits==0 means
1900 * "All IPv4 addresses" and an AF_INET6 address with maskbits == 0 means
1901 * "All IPv6 addresses".
1903 tor_addr_t addr;
1904 uint16_t prt_min; /**< Lowest port number to accept/reject. */
1905 uint16_t prt_max; /**< Highest port number to accept/reject. */
1906 } addr_policy_t;
1908 /** A cached_dir_t represents a cacheable directory object, along with its
1909 * compressed form. */
1910 typedef struct cached_dir_t {
1911 char *dir; /**< Contents of this object, NUL-terminated. */
1912 char *dir_z; /**< Compressed contents of this object. */
1913 size_t dir_len; /**< Length of <b>dir</b> (not counting its NUL). */
1914 size_t dir_z_len; /**< Length of <b>dir_z</b>. */
1915 time_t published; /**< When was this object published. */
1916 digests_t digests; /**< Digests of this object (networkstatus only) */
1917 int refcnt; /**< Reference count for this cached_dir_t. */
1918 } cached_dir_t;
1920 /** Enum used to remember where a signed_descriptor_t is stored and how to
1921 * manage the memory for signed_descriptor_body. */
1922 typedef enum {
1923 /** The descriptor isn't stored on disk at all: the copy in memory is
1924 * canonical; the saved_offset field is meaningless. */
1925 SAVED_NOWHERE=0,
1926 /** The descriptor is stored in the cached_routers file: the
1927 * signed_descriptor_body is meaningless; the signed_descriptor_len and
1928 * saved_offset are used to index into the mmaped cache file. */
1929 SAVED_IN_CACHE,
1930 /** The descriptor is stored in the cached_routers.new file: the
1931 * signed_descriptor_body and saved_offset fields are both set. */
1932 /* FFFF (We could also mmap the file and grow the mmap as needed, or
1933 * lazy-load the descriptor text by using seek and read. We don't, for
1934 * now.)
1936 SAVED_IN_JOURNAL
1937 } saved_location_t;
1938 #define saved_location_bitfield_t ENUM_BF(saved_location_t)
1940 /** Enumeration: what kind of download schedule are we using for a given
1941 * object? */
1942 typedef enum {
1943 DL_SCHED_GENERIC = 0,
1944 DL_SCHED_CONSENSUS = 1,
1945 DL_SCHED_BRIDGE = 2,
1946 } download_schedule_t;
1947 #define download_schedule_bitfield_t ENUM_BF(download_schedule_t)
1949 /** Information about our plans for retrying downloads for a downloadable
1950 * object. */
1951 typedef struct download_status_t {
1952 time_t next_attempt_at; /**< When should we try downloading this descriptor
1953 * again? */
1954 uint8_t n_download_failures; /**< Number of failures trying to download the
1955 * most recent descriptor. */
1956 download_schedule_bitfield_t schedule : 8;
1958 } download_status_t;
1960 /** If n_download_failures is this high, the download can never happen. */
1961 #define IMPOSSIBLE_TO_DOWNLOAD 255
1963 /** The max size we expect router descriptor annotations we create to
1964 * be. We'll accept larger ones if we see them on disk, but we won't
1965 * create any that are larger than this. */
1966 #define ROUTER_ANNOTATION_BUF_LEN 256
1968 /** Information need to cache an onion router's descriptor. */
1969 typedef struct signed_descriptor_t {
1970 /** Pointer to the raw server descriptor, preceded by annotations. Not
1971 * necessarily NUL-terminated. If saved_location is SAVED_IN_CACHE, this
1972 * pointer is null. */
1973 char *signed_descriptor_body;
1974 /** Length of the annotations preceding the server descriptor. */
1975 size_t annotations_len;
1976 /** Length of the server descriptor. */
1977 size_t signed_descriptor_len;
1978 /** Digest of the server descriptor, computed as specified in
1979 * dir-spec.txt. */
1980 char signed_descriptor_digest[DIGEST_LEN];
1981 /** Identity digest of the router. */
1982 char identity_digest[DIGEST_LEN];
1983 /** Declared publication time of the descriptor. */
1984 time_t published_on;
1985 /** For routerdescs only: digest of the corresponding extrainfo. */
1986 char extra_info_digest[DIGEST_LEN];
1987 /** For routerdescs only: Status of downloading the corresponding
1988 * extrainfo. */
1989 download_status_t ei_dl_status;
1990 /** Where is the descriptor saved? */
1991 saved_location_t saved_location;
1992 /** If saved_location is SAVED_IN_CACHE or SAVED_IN_JOURNAL, the offset of
1993 * this descriptor in the corresponding file. */
1994 off_t saved_offset;
1995 /** What position is this descriptor within routerlist->routers or
1996 * routerlist->old_routers? -1 for none. */
1997 int routerlist_index;
1998 /** The valid-until time of the most recent consensus that listed this
1999 * descriptor. 0 for "never listed in a consensus, so far as we know." */
2000 time_t last_listed_as_valid_until;
2001 /* If true, we do not ever try to save this object in the cache. */
2002 unsigned int do_not_cache : 1;
2003 /* If true, this item is meant to represent an extrainfo. */
2004 unsigned int is_extrainfo : 1;
2005 /* If true, we got an extrainfo for this item, and the digest was right,
2006 * but it was incompatible. */
2007 unsigned int extrainfo_is_bogus : 1;
2008 /* If true, we are willing to transmit this item unencrypted. */
2009 unsigned int send_unencrypted : 1;
2010 } signed_descriptor_t;
2012 /** A signed integer representing a country code. */
2013 typedef int16_t country_t;
2015 /** Information about another onion router in the network. */
2016 typedef struct {
2017 signed_descriptor_t cache_info;
2018 char *nickname; /**< Human-readable OR name. */
2020 uint32_t addr; /**< IPv4 address of OR, in host order. */
2021 uint16_t or_port; /**< Port for TLS connections. */
2022 uint16_t dir_port; /**< Port for HTTP directory connections. */
2024 /** A router's IPv6 address, if it has one. */
2025 /* XXXXX187 Actually these should probably be part of a list of addresses,
2026 * not just a special case. Use abstractions to access these; don't do it
2027 * directly. */
2028 tor_addr_t ipv6_addr;
2029 uint16_t ipv6_orport;
2031 crypto_pk_t *onion_pkey; /**< Public RSA key for onions. */
2032 crypto_pk_t *identity_pkey; /**< Public RSA key for signing. */
2033 /** Public curve25519 key for onions */
2034 curve25519_public_key_t *onion_curve25519_pkey;
2036 char *platform; /**< What software/operating system is this OR using? */
2038 /* link info */
2039 uint32_t bandwidthrate; /**< How many bytes does this OR add to its token
2040 * bucket per second? */
2041 uint32_t bandwidthburst; /**< How large is this OR's token bucket? */
2042 /** How many bytes/s is this router known to handle? */
2043 uint32_t bandwidthcapacity;
2044 smartlist_t *exit_policy; /**< What streams will this OR permit
2045 * to exit on IPv4? NULL for 'reject *:*'. */
2046 /** What streams will this OR permit to exit on IPv6?
2047 * NULL for 'reject *:*' */
2048 struct short_policy_t *ipv6_exit_policy;
2049 long uptime; /**< How many seconds the router claims to have been up */
2050 smartlist_t *declared_family; /**< Nicknames of router which this router
2051 * claims are its family. */
2052 char *contact_info; /**< Declared contact info for this router. */
2053 unsigned int is_hibernating:1; /**< Whether the router claims to be
2054 * hibernating */
2055 unsigned int caches_extra_info:1; /**< Whether the router says it caches and
2056 * serves extrainfo documents. */
2057 unsigned int allow_single_hop_exits:1; /**< Whether the router says
2058 * it allows single hop exits. */
2060 unsigned int wants_to_be_hs_dir:1; /**< True iff this router claims to be
2061 * a hidden service directory. */
2062 unsigned int policy_is_reject_star:1; /**< True iff the exit policy for this
2063 * router rejects everything. */
2064 /** True if, after we have added this router, we should re-launch
2065 * tests for it. */
2066 unsigned int needs_retest_if_added:1;
2068 /** Tor can use this router for general positions in circuits; we got it
2069 * from a directory server as usual, or we're an authority and a server
2070 * uploaded it. */
2071 #define ROUTER_PURPOSE_GENERAL 0
2072 /** Tor should avoid using this router for circuit-building: we got it
2073 * from a crontroller. If the controller wants to use it, it'll have to
2074 * ask for it by identity. */
2075 #define ROUTER_PURPOSE_CONTROLLER 1
2076 /** Tor should use this router only for bridge positions in circuits: we got
2077 * it via a directory request from the bridge itself, or a bridge
2078 * authority. x*/
2079 #define ROUTER_PURPOSE_BRIDGE 2
2080 /** Tor should not use this router; it was marked in cached-descriptors with
2081 * a purpose we didn't recognize. */
2082 #define ROUTER_PURPOSE_UNKNOWN 255
2084 /* In what way did we find out about this router? One of ROUTER_PURPOSE_*.
2085 * Routers of different purposes are kept segregated and used for different
2086 * things; see notes on ROUTER_PURPOSE_* macros above.
2088 uint8_t purpose;
2089 } routerinfo_t;
2091 /** Information needed to keep and cache a signed extra-info document. */
2092 typedef struct extrainfo_t {
2093 signed_descriptor_t cache_info;
2094 /** The router's nickname. */
2095 char nickname[MAX_NICKNAME_LEN+1];
2096 /** True iff we found the right key for this extra-info, verified the
2097 * signature, and found it to be bad. */
2098 unsigned int bad_sig : 1;
2099 /** If present, we didn't have the right key to verify this extra-info,
2100 * so this is a copy of the signature in the document. */
2101 char *pending_sig;
2102 /** Length of pending_sig. */
2103 size_t pending_sig_len;
2104 } extrainfo_t;
2106 /** Contents of a single router entry in a network status object.
2108 typedef struct routerstatus_t {
2109 time_t published_on; /**< When was this router published? */
2110 char nickname[MAX_NICKNAME_LEN+1]; /**< The nickname this router says it
2111 * has. */
2112 char identity_digest[DIGEST_LEN]; /**< Digest of the router's identity
2113 * key. */
2114 /** Digest of the router's most recent descriptor or microdescriptor.
2115 * If it's a descriptor, we only use the first DIGEST_LEN bytes. */
2116 char descriptor_digest[DIGEST256_LEN];
2117 uint32_t addr; /**< IPv4 address for this router. */
2118 uint16_t or_port; /**< OR port for this router. */
2119 uint16_t dir_port; /**< Directory port for this router. */
2120 tor_addr_t ipv6_addr; /**< IPv6 address for this router. */
2121 uint16_t ipv6_orport; /**<IPV6 OR port for this router. */
2122 unsigned int is_authority:1; /**< True iff this router is an authority. */
2123 unsigned int is_exit:1; /**< True iff this router is a good exit. */
2124 unsigned int is_stable:1; /**< True iff this router stays up a long time. */
2125 unsigned int is_fast:1; /**< True iff this router has good bandwidth. */
2126 /** True iff this router is called 'running' in the consensus. We give it
2127 * this funny name so that we don't accidentally use this bit as a view of
2128 * whether we think the router is *currently* running. If that's what you
2129 * want to know, look at is_running in node_t. */
2130 unsigned int is_flagged_running:1;
2131 unsigned int is_named:1; /**< True iff "nickname" belongs to this router. */
2132 unsigned int is_unnamed:1; /**< True iff "nickname" belongs to another
2133 * router. */
2134 unsigned int is_valid:1; /**< True iff this router isn't invalid. */
2135 unsigned int is_possible_guard:1; /**< True iff this router would be a good
2136 * choice as an entry guard. */
2137 unsigned int is_bad_exit:1; /**< True iff this node is a bad choice for
2138 * an exit node. */
2139 unsigned int is_hs_dir:1; /**< True iff this router is a v2-or-later hidden
2140 * service directory. */
2141 /** True iff we know version info for this router. (i.e., a "v" entry was
2142 * included.) We'll replace all these with a big tor_version_t or a char[]
2143 * if the number of traits we care about ever becomes incredibly big. */
2144 unsigned int version_known:1;
2146 /** True iff this router is a version that, if it caches directory info,
2147 * we can get microdescriptors from. */
2148 unsigned int version_supports_microdesc_cache:1;
2149 /** True iff this router has a version that allows it to accept EXTEND2
2150 * cells */
2151 unsigned int version_supports_extend2_cells:1;
2153 unsigned int has_bandwidth:1; /**< The vote/consensus had bw info */
2154 unsigned int has_exitsummary:1; /**< The vote/consensus had exit summaries */
2155 unsigned int bw_is_unmeasured:1; /**< This is a consensus entry, with
2156 * the Unmeasured flag set. */
2158 uint32_t bandwidth_kb; /**< Bandwidth (capacity) of the router as reported in
2159 * the vote/consensus, in kilobytes/sec. */
2160 char *exitsummary; /**< exit policy summary -
2161 * XXX weasel: this probably should not stay a string. */
2163 /* ---- The fields below aren't derived from the networkstatus; they
2164 * hold local information only. */
2166 time_t last_dir_503_at; /**< When did this router last tell us that it
2167 * was too busy to serve directory info? */
2168 download_status_t dl_status;
2170 } routerstatus_t;
2172 /** A single entry in a parsed policy summary, describing a range of ports. */
2173 typedef struct short_policy_entry_t {
2174 uint16_t min_port, max_port;
2175 } short_policy_entry_t;
2177 /** A short_poliy_t is the parsed version of a policy summary. */
2178 typedef struct short_policy_t {
2179 /** True if the members of 'entries' are port ranges to accept; false if
2180 * they are port ranges to reject */
2181 unsigned int is_accept : 1;
2182 /** The actual number of values in 'entries'. */
2183 unsigned int n_entries : 31;
2184 /** An array of 0 or more short_policy_entry_t values, each describing a
2185 * range of ports that this policy accepts or rejects (depending on the
2186 * value of is_accept).
2188 short_policy_entry_t entries[FLEXIBLE_ARRAY_MEMBER];
2189 } short_policy_t;
2191 /** A microdescriptor is the smallest amount of information needed to build a
2192 * circuit through a router. They are generated by the directory authorities,
2193 * using information from the uploaded routerinfo documents. They are not
2194 * self-signed, but are rather authenticated by having their hash in a signed
2195 * networkstatus document. */
2196 typedef struct microdesc_t {
2197 /** Hashtable node, used to look up the microdesc by its digest. */
2198 HT_ENTRY(microdesc_t) node;
2200 /* Cache information */
2202 /** When was this microdescriptor last listed in a consensus document?
2203 * Once a microdesc has been unlisted long enough, we can drop it.
2205 time_t last_listed;
2206 /** Where is this microdescriptor currently stored? */
2207 saved_location_bitfield_t saved_location : 3;
2208 /** If true, do not attempt to cache this microdescriptor on disk. */
2209 unsigned int no_save : 1;
2210 /** If true, this microdesc has an entry in the microdesc_map */
2211 unsigned int held_in_map : 1;
2212 /** Reference count: how many node_ts have a reference to this microdesc? */
2213 unsigned int held_by_nodes;
2215 /** If saved_location == SAVED_IN_CACHE, this field holds the offset of the
2216 * microdescriptor in the cache. */
2217 off_t off;
2219 /* The string containing the microdesc. */
2221 /** A pointer to the encoded body of the microdescriptor. If the
2222 * saved_location is SAVED_IN_CACHE, then the body is a pointer into an
2223 * mmap'd region. Otherwise, it is a malloc'd string. The string might not
2224 * be NUL-terminated; take the length from <b>bodylen</b>. */
2225 char *body;
2226 /** The length of the microdescriptor in <b>body</b>. */
2227 size_t bodylen;
2228 /** A SHA256-digest of the microdescriptor. */
2229 char digest[DIGEST256_LEN];
2231 /* Fields in the microdescriptor. */
2233 /** As routerinfo_t.onion_pkey */
2234 crypto_pk_t *onion_pkey;
2235 /** As routerinfo_t.onion_curve25519_pkey */
2236 curve25519_public_key_t *onion_curve25519_pkey;
2237 /** As routerinfo_t.ipv6_add */
2238 tor_addr_t ipv6_addr;
2239 /** As routerinfo_t.ipv6_orport */
2240 uint16_t ipv6_orport;
2241 /** As routerinfo_t.family */
2242 smartlist_t *family;
2243 /** IPv4 exit policy summary */
2244 short_policy_t *exit_policy;
2245 /** IPv6 exit policy summary */
2246 short_policy_t *ipv6_exit_policy;
2248 } microdesc_t;
2250 /** A node_t represents a Tor router.
2252 * Specifically, a node_t is a Tor router as we are using it: a router that
2253 * we are considering for circuits, connections, and so on. A node_t is a
2254 * thin wrapper around the routerstatus, routerinfo, and microdesc for a
2255 * single wrapper, and provides a consistent interface for all of them.
2257 * Also, a node_t has mutable state. While a routerinfo, a routerstatus,
2258 * and a microdesc have[*] only the information read from a router
2259 * descriptor, a consensus entry, and a microdescriptor (respectively)...
2260 * a node_t has flags based on *our own current opinion* of the node.
2262 * [*] Actually, there is some leftover information in each that is mutable.
2263 * We should try to excise that.
2265 typedef struct node_t {
2266 /* Indexing information */
2268 /** Used to look up the node_t by its identity digest. */
2269 HT_ENTRY(node_t) ht_ent;
2270 /** Position of the node within the list of nodes */
2271 int nodelist_idx;
2273 /** The identity digest of this node_t. No more than one node_t per
2274 * identity may exist at a time. */
2275 char identity[DIGEST_LEN];
2277 microdesc_t *md;
2278 routerinfo_t *ri;
2279 routerstatus_t *rs;
2281 /* local info: copied from routerstatus, then possibly frobbed based
2282 * on experience. Authorities set this stuff directly. Note that
2283 * these reflect knowledge of the primary (IPv4) OR port only. */
2285 unsigned int is_running:1; /**< As far as we know, is this OR currently
2286 * running? */
2287 unsigned int is_valid:1; /**< Has a trusted dirserver validated this OR?
2288 * (For Authdir: Have we validated this OR?) */
2289 unsigned int is_fast:1; /** Do we think this is a fast OR? */
2290 unsigned int is_stable:1; /** Do we think this is a stable OR? */
2291 unsigned int is_possible_guard:1; /**< Do we think this is an OK guard? */
2292 unsigned int is_exit:1; /**< Do we think this is an OK exit? */
2293 unsigned int is_bad_exit:1; /**< Do we think this exit is censored, borked,
2294 * or otherwise nasty? */
2295 unsigned int is_hs_dir:1; /**< True iff this router is a hidden service
2296 * directory according to the authorities. */
2298 /* Local info: warning state. */
2300 unsigned int name_lookup_warned:1; /**< Have we warned the user for referring
2301 * to this (unnamed) router by nickname?
2304 /** Local info: we treat this node as if it rejects everything */
2305 unsigned int rejects_all:1;
2307 /** Local info: this node is in our list of guards */
2308 unsigned int using_as_guard:1;
2310 /* Local info: derived. */
2312 /** True if the IPv6 OR port is preferred over the IPv4 OR port. */
2313 unsigned int ipv6_preferred:1;
2315 /** According to the geoip db what country is this router in? */
2316 /* XXXprop186 what is this suppose to mean with multiple OR ports? */
2317 country_t country;
2319 /* The below items are used only by authdirservers for
2320 * reachability testing. */
2322 /** When was the last time we could reach this OR? */
2323 time_t last_reachable; /* IPv4. */
2324 time_t last_reachable6; /* IPv6. */
2326 } node_t;
2328 /** Linked list of microdesc hash lines for a single router in a directory
2329 * vote.
2331 typedef struct vote_microdesc_hash_t {
2332 /** Next element in the list, or NULL. */
2333 struct vote_microdesc_hash_t *next;
2334 /** The raw contents of the microdesc hash line, from the "m" through the
2335 * newline. */
2336 char *microdesc_hash_line;
2337 } vote_microdesc_hash_t;
2339 /** The claim about a single router, made in a vote. */
2340 typedef struct vote_routerstatus_t {
2341 routerstatus_t status; /**< Underlying 'status' object for this router.
2342 * Flags are redundant. */
2343 /** How many known-flags are allowed in a vote? This is the width of
2344 * the flags field of vote_routerstatus_t */
2345 #define MAX_KNOWN_FLAGS_IN_VOTE 64
2346 uint64_t flags; /**< Bit-field for all recognized flags; index into
2347 * networkstatus_t.known_flags. */
2348 char *version; /**< The version that the authority says this router is
2349 * running. */
2350 unsigned int has_measured_bw:1; /**< The vote had a measured bw */
2351 uint32_t measured_bw_kb; /**< Measured bandwidth (capacity) of the router */
2352 /** The hash or hashes that the authority claims this microdesc has. */
2353 vote_microdesc_hash_t *microdesc;
2354 } vote_routerstatus_t;
2356 /** A signature of some document by an authority. */
2357 typedef struct document_signature_t {
2358 /** Declared SHA-1 digest of this voter's identity key */
2359 char identity_digest[DIGEST_LEN];
2360 /** Declared SHA-1 digest of signing key used by this voter. */
2361 char signing_key_digest[DIGEST_LEN];
2362 /** Algorithm used to compute the digest of the document. */
2363 digest_algorithm_t alg;
2364 /** Signature of the signed thing. */
2365 char *signature;
2366 /** Length of <b>signature</b> */
2367 int signature_len;
2368 unsigned int bad_signature : 1; /**< Set to true if we've tried to verify
2369 * the sig, and we know it's bad. */
2370 unsigned int good_signature : 1; /**< Set to true if we've verified the sig
2371 * as good. */
2372 } document_signature_t;
2374 /** Information about a single voter in a vote or a consensus. */
2375 typedef struct networkstatus_voter_info_t {
2376 /** Declared SHA-1 digest of this voter's identity key */
2377 char identity_digest[DIGEST_LEN];
2378 char *nickname; /**< Nickname of this voter */
2379 /** Digest of this voter's "legacy" identity key, if any. In vote only; for
2380 * consensuses, we treat legacy keys as additional signers. */
2381 char legacy_id_digest[DIGEST_LEN];
2382 char *address; /**< Address of this voter, in string format. */
2383 uint32_t addr; /**< Address of this voter, in IPv4, in host order. */
2384 uint16_t dir_port; /**< Directory port of this voter */
2385 uint16_t or_port; /**< OR port of this voter */
2386 char *contact; /**< Contact information for this voter. */
2387 char vote_digest[DIGEST_LEN]; /**< Digest of this voter's vote, as signed. */
2389 /* Nothing from here on is signed. */
2390 /** The signature of the document and the signature's status. */
2391 smartlist_t *sigs;
2392 } networkstatus_voter_info_t;
2394 /** Enumerates the possible seriousness values of a networkstatus document. */
2395 typedef enum {
2396 NS_TYPE_VOTE,
2397 NS_TYPE_CONSENSUS,
2398 NS_TYPE_OPINION,
2399 } networkstatus_type_t;
2401 /** Enumerates recognized flavors of a consensus networkstatus document. All
2402 * flavors of a consensus are generated from the same set of votes, but they
2403 * present different types information to different versions of Tor. */
2404 typedef enum {
2405 FLAV_NS = 0,
2406 FLAV_MICRODESC = 1,
2407 } consensus_flavor_t;
2409 /** How many different consensus flavors are there? */
2410 #define N_CONSENSUS_FLAVORS ((int)(FLAV_MICRODESC)+1)
2412 /** A common structure to hold a v3 network status vote, or a v3 network
2413 * status consensus. */
2414 typedef struct networkstatus_t {
2415 networkstatus_type_t type; /**< Vote, consensus, or opinion? */
2416 consensus_flavor_t flavor; /**< If a consensus, what kind? */
2417 unsigned int has_measured_bws : 1;/**< True iff this networkstatus contains
2418 * measured= bandwidth values. */
2420 time_t published; /**< Vote only: Time when vote was written. */
2421 time_t valid_after; /**< Time after which this vote or consensus applies. */
2422 time_t fresh_until; /**< Time before which this is the most recent vote or
2423 * consensus. */
2424 time_t valid_until; /**< Time after which this vote or consensus should not
2425 * be used. */
2427 /** Consensus only: what method was used to produce this consensus? */
2428 int consensus_method;
2429 /** Vote only: what methods is this voter willing to use? */
2430 smartlist_t *supported_methods;
2432 /** How long does this vote/consensus claim that authorities take to
2433 * distribute their votes to one another? */
2434 int vote_seconds;
2435 /** How long does this vote/consensus claim that authorities take to
2436 * distribute their consensus signatures to one another? */
2437 int dist_seconds;
2439 /** Comma-separated list of recommended client software, or NULL if this
2440 * voter has no opinion. */
2441 char *client_versions;
2442 char *server_versions;
2443 /** List of flags that this vote/consensus applies to routers. If a flag is
2444 * not listed here, the voter has no opinion on what its value should be. */
2445 smartlist_t *known_flags;
2447 /** List of key=value strings for the parameters in this vote or
2448 * consensus, sorted by key. */
2449 smartlist_t *net_params;
2451 /** List of key=value strings for the bw weight parameters in the
2452 * consensus. */
2453 smartlist_t *weight_params;
2455 /** List of networkstatus_voter_info_t. For a vote, only one element
2456 * is included. For a consensus, one element is included for every voter
2457 * whose vote contributed to the consensus. */
2458 smartlist_t *voters;
2460 struct authority_cert_t *cert; /**< Vote only: the voter's certificate. */
2462 /** Digests of this document, as signed. */
2463 digests_t digests;
2465 /** List of router statuses, sorted by identity digest. For a vote,
2466 * the elements are vote_routerstatus_t; for a consensus, the elements
2467 * are routerstatus_t. */
2468 smartlist_t *routerstatus_list;
2470 /** If present, a map from descriptor digest to elements of
2471 * routerstatus_list. */
2472 digestmap_t *desc_digest_map;
2473 } networkstatus_t;
2475 /** A set of signatures for a networkstatus consensus. Unless otherwise
2476 * noted, all fields are as for networkstatus_t. */
2477 typedef struct ns_detached_signatures_t {
2478 time_t valid_after;
2479 time_t fresh_until;
2480 time_t valid_until;
2481 strmap_t *digests; /**< Map from flavor name to digestset_t */
2482 strmap_t *signatures; /**< Map from flavor name to list of
2483 * document_signature_t */
2484 } ns_detached_signatures_t;
2486 /** Allowable types of desc_store_t. */
2487 typedef enum store_type_t {
2488 ROUTER_STORE = 0,
2489 EXTRAINFO_STORE = 1
2490 } store_type_t;
2492 /** A 'store' is a set of descriptors saved on disk, with accompanying
2493 * journal, mmaped as needed, rebuilt as needed. */
2494 typedef struct desc_store_t {
2495 /** Filename (within DataDir) for the store. We append .tmp to this
2496 * filename for a temporary file when rebuilding the store, and .new to this
2497 * filename for the journal. */
2498 const char *fname_base;
2499 /** Human-readable description of what this store contains. */
2500 const char *description;
2502 tor_mmap_t *mmap; /**< A mmap for the main file in the store. */
2504 store_type_t type; /**< What's stored in this store? */
2506 /** The size of the router log, in bytes. */
2507 size_t journal_len;
2508 /** The size of the router store, in bytes. */
2509 size_t store_len;
2510 /** Total bytes dropped since last rebuild: this is space currently
2511 * used in the cache and the journal that could be freed by a rebuild. */
2512 size_t bytes_dropped;
2513 } desc_store_t;
2515 /** Contents of a directory of onion routers. */
2516 typedef struct {
2517 /** Map from server identity digest to a member of routers. */
2518 struct digest_ri_map_t *identity_map;
2519 /** Map from server descriptor digest to a signed_descriptor_t from
2520 * routers or old_routers. */
2521 struct digest_sd_map_t *desc_digest_map;
2522 /** Map from extra-info digest to an extrainfo_t. Only exists for
2523 * routers in routers or old_routers. */
2524 struct digest_ei_map_t *extra_info_map;
2525 /** Map from extra-info digests to a signed_descriptor_t for a router
2526 * descriptor having that extra-info digest. Only exists for
2527 * routers in routers or old_routers. */
2528 struct digest_sd_map_t *desc_by_eid_map;
2529 /** List of routerinfo_t for all currently live routers we know. */
2530 smartlist_t *routers;
2531 /** List of signed_descriptor_t for older router descriptors we're
2532 * caching. */
2533 smartlist_t *old_routers;
2534 /** Store holding server descriptors. If present, any router whose
2535 * cache_info.saved_location == SAVED_IN_CACHE is stored in this file
2536 * starting at cache_info.saved_offset */
2537 desc_store_t desc_store;
2538 /** Store holding extra-info documents. */
2539 desc_store_t extrainfo_store;
2540 } routerlist_t;
2542 /** Information on router used when extending a circuit. We don't need a
2543 * full routerinfo_t to extend: we only need addr:port:keyid to build an OR
2544 * connection, and onion_key to create the onionskin. Note that for onehop
2545 * general-purpose tunnels, the onion_key is NULL. */
2546 typedef struct extend_info_t {
2547 char nickname[MAX_HEX_NICKNAME_LEN+1]; /**< This router's nickname for
2548 * display. */
2549 char identity_digest[DIGEST_LEN]; /**< Hash of this router's identity key. */
2550 uint16_t port; /**< OR port. */
2551 tor_addr_t addr; /**< IP address. */
2552 crypto_pk_t *onion_key; /**< Current onionskin key. */
2553 curve25519_public_key_t curve25519_onion_key;
2554 } extend_info_t;
2556 /** Certificate for v3 directory protocol: binds long-term authority identity
2557 * keys to medium-term authority signing keys. */
2558 typedef struct authority_cert_t {
2559 /** Information relating to caching this cert on disk and looking it up. */
2560 signed_descriptor_t cache_info;
2561 /** This authority's long-term authority identity key. */
2562 crypto_pk_t *identity_key;
2563 /** This authority's medium-term signing key. */
2564 crypto_pk_t *signing_key;
2565 /** The digest of <b>signing_key</b> */
2566 char signing_key_digest[DIGEST_LEN];
2567 /** The listed expiration time of this certificate. */
2568 time_t expires;
2569 /** This authority's IPv4 address, in host order. */
2570 uint32_t addr;
2571 /** This authority's directory port. */
2572 uint16_t dir_port;
2573 } authority_cert_t;
2575 /** Bitfield enum type listing types of information that directory authorities
2576 * can be authoritative about, and that directory caches may or may not cache.
2578 * Note that the granularity here is based on authority granularity and on
2579 * cache capabilities. Thus, one particular bit may correspond in practice to
2580 * a few types of directory info, so long as every authority that pronounces
2581 * officially about one of the types prounounces officially about all of them,
2582 * and so long as every cache that caches one of them caches all of them.
2584 typedef enum {
2585 NO_DIRINFO = 0,
2586 /** Serves/signs v3 directory information: votes, consensuses, certs */
2587 V3_DIRINFO = 1 << 2,
2588 /** Serves bridge descriptors. */
2589 BRIDGE_DIRINFO = 1 << 4,
2590 /** Serves extrainfo documents. */
2591 EXTRAINFO_DIRINFO=1 << 5,
2592 /** Serves microdescriptors. */
2593 MICRODESC_DIRINFO=1 << 6,
2594 } dirinfo_type_t;
2596 #define ALL_DIRINFO ((dirinfo_type_t)((1<<7)-1))
2598 #define CRYPT_PATH_MAGIC 0x70127012u
2600 struct fast_handshake_state_t;
2601 struct ntor_handshake_state_t;
2602 #define ONION_HANDSHAKE_TYPE_TAP 0x0000
2603 #define ONION_HANDSHAKE_TYPE_FAST 0x0001
2604 #define ONION_HANDSHAKE_TYPE_NTOR 0x0002
2605 #define MAX_ONION_HANDSHAKE_TYPE 0x0002
2606 typedef struct {
2607 uint16_t tag;
2608 union {
2609 struct fast_handshake_state_t *fast;
2610 crypto_dh_t *tap;
2611 struct ntor_handshake_state_t *ntor;
2612 } u;
2613 } onion_handshake_state_t;
2615 /** Holds accounting information for a single step in the layered encryption
2616 * performed by a circuit. Used only at the client edge of a circuit. */
2617 typedef struct crypt_path_t {
2618 uint32_t magic;
2620 /* crypto environments */
2621 /** Encryption key and counter for cells heading towards the OR at this
2622 * step. */
2623 crypto_cipher_t *f_crypto;
2624 /** Encryption key and counter for cells heading back from the OR at this
2625 * step. */
2626 crypto_cipher_t *b_crypto;
2628 /** Digest state for cells heading towards the OR at this step. */
2629 crypto_digest_t *f_digest; /* for integrity checking */
2630 /** Digest state for cells heading away from the OR at this step. */
2631 crypto_digest_t *b_digest;
2633 /** Current state of the handshake as performed with the OR at this
2634 * step. */
2635 onion_handshake_state_t handshake_state;
2636 /** Diffie-hellman handshake state for performing an introduction
2637 * operations */
2638 crypto_dh_t *rend_dh_handshake_state;
2640 /** Negotiated key material shared with the OR at this step. */
2641 char rend_circ_nonce[DIGEST_LEN];/* KH in tor-spec.txt */
2643 /** Information to extend to the OR at this step. */
2644 extend_info_t *extend_info;
2646 /** Is the circuit built to this step? Must be one of:
2647 * - CPATH_STATE_CLOSED (The circuit has not been extended to this step)
2648 * - CPATH_STATE_AWAITING_KEYS (We have sent an EXTEND/CREATE to this step
2649 * and not received an EXTENDED/CREATED)
2650 * - CPATH_STATE_OPEN (The circuit has been extended to this step) */
2651 uint8_t state;
2652 #define CPATH_STATE_CLOSED 0
2653 #define CPATH_STATE_AWAITING_KEYS 1
2654 #define CPATH_STATE_OPEN 2
2655 struct crypt_path_t *next; /**< Link to next crypt_path_t in the circuit.
2656 * (The list is circular, so the last node
2657 * links to the first.) */
2658 struct crypt_path_t *prev; /**< Link to previous crypt_path_t in the
2659 * circuit. */
2661 int package_window; /**< How many cells are we allowed to originate ending
2662 * at this step? */
2663 int deliver_window; /**< How many cells are we willing to deliver originating
2664 * at this step? */
2665 } crypt_path_t;
2667 /** A reference-counted pointer to a crypt_path_t, used only to share
2668 * the final rendezvous cpath to be used on a service-side rendezvous
2669 * circuit among multiple circuits built in parallel to the same
2670 * destination rendezvous point. */
2671 typedef struct {
2672 /** The reference count. */
2673 unsigned int refcount;
2674 /** The pointer. Set to NULL when the crypt_path_t is put into use
2675 * on an opened rendezvous circuit. */
2676 crypt_path_t *cpath;
2677 } crypt_path_reference_t;
2679 #define CPATH_KEY_MATERIAL_LEN (20*2+16*2)
2681 #define DH_KEY_LEN DH_BYTES
2683 /** Information used to build a circuit. */
2684 typedef struct {
2685 /** Intended length of the final circuit. */
2686 int desired_path_len;
2687 /** How to extend to the planned exit node. */
2688 extend_info_t *chosen_exit;
2689 /** Whether every node in the circ must have adequate uptime. */
2690 unsigned int need_uptime : 1;
2691 /** Whether every node in the circ must have adequate capacity. */
2692 unsigned int need_capacity : 1;
2693 /** Whether the last hop was picked with exiting in mind. */
2694 unsigned int is_internal : 1;
2695 /** Did we pick this as a one-hop tunnel (not safe for other streams)?
2696 * These are for encrypted dir conns that exit to this router, not
2697 * for arbitrary exits from the circuit. */
2698 unsigned int onehop_tunnel : 1;
2699 /** The crypt_path_t to append after rendezvous: used for rendezvous. */
2700 crypt_path_t *pending_final_cpath;
2701 /** A ref-counted reference to the crypt_path_t to append after
2702 * rendezvous; used on the service side. */
2703 crypt_path_reference_t *service_pending_final_cpath_ref;
2704 /** How many times has building a circuit for this task failed? */
2705 int failure_count;
2706 /** At what time should we give up on this task? */
2707 time_t expiry_time;
2708 } cpath_build_state_t;
2710 #define ORIGIN_CIRCUIT_MAGIC 0x35315243u
2711 #define OR_CIRCUIT_MAGIC 0x98ABC04Fu
2713 struct create_cell_t;
2715 /** Entry in the cell stats list of a circuit; used only if CELL_STATS
2716 * events are enabled. */
2717 typedef struct testing_cell_stats_entry_t {
2718 uint8_t command; /**< cell command number. */
2719 /** Waiting time in centiseconds if this event is for a removed cell,
2720 * or 0 if this event is for adding a cell to the queue. 22 bits can
2721 * store more than 11 hours, enough to assume that a circuit with this
2722 * delay would long have been closed. */
2723 unsigned int waiting_time:22;
2724 unsigned int removed:1; /**< 0 for added to, 1 for removed from queue. */
2725 unsigned int exitward:1; /**< 0 for app-ward, 1 for exit-ward. */
2726 } testing_cell_stats_entry_t;
2729 * A circuit is a path over the onion routing
2730 * network. Applications can connect to one end of the circuit, and can
2731 * create exit connections at the other end of the circuit. AP and exit
2732 * connections have only one circuit associated with them (and thus these
2733 * connection types are closed when the circuit is closed), whereas
2734 * OR connections multiplex many circuits at once, and stay standing even
2735 * when there are no circuits running over them.
2737 * A circuit_t structure can fill one of two roles. First, a or_circuit_t
2738 * links two connections together: either an edge connection and an OR
2739 * connection, or two OR connections. (When joined to an OR connection, a
2740 * circuit_t affects only cells sent to a particular circID on that
2741 * connection. When joined to an edge connection, a circuit_t affects all
2742 * data.)
2744 * Second, an origin_circuit_t holds the cipher keys and state for sending data
2745 * along a given circuit. At the OP, it has a sequence of ciphers, each
2746 * of which is shared with a single OR along the circuit. Separate
2747 * ciphers are used for data going "forward" (away from the OP) and
2748 * "backward" (towards the OP). At the OR, a circuit has only two stream
2749 * ciphers: one for data going forward, and one for data going backward.
2751 typedef struct circuit_t {
2752 uint32_t magic; /**< For memory and type debugging: must equal
2753 * ORIGIN_CIRCUIT_MAGIC or OR_CIRCUIT_MAGIC. */
2755 /** The channel that is next in this circuit. */
2756 channel_t *n_chan;
2759 * The circuit_id used in the next (forward) hop of this circuit;
2760 * this is unique to n_chan, but this ordered pair is globally
2761 * unique:
2763 * (n_chan->global_identifier, n_circ_id)
2765 circid_t n_circ_id;
2768 * Circuit mux associated with n_chan to which this circuit is attached;
2769 * NULL if we have no n_chan.
2771 circuitmux_t *n_mux;
2773 /** Queue of cells waiting to be transmitted on n_chan */
2774 cell_queue_t n_chan_cells;
2777 * The hop to which we want to extend this circuit. Should be NULL if
2778 * the circuit has attached to a channel.
2780 extend_info_t *n_hop;
2782 /** True iff we are waiting for n_chan_cells to become less full before
2783 * allowing p_streams to add any more cells. (Origin circuit only.) */
2784 unsigned int streams_blocked_on_n_chan : 1;
2785 /** True iff we are waiting for p_chan_cells to become less full before
2786 * allowing n_streams to add any more cells. (OR circuit only.) */
2787 unsigned int streams_blocked_on_p_chan : 1;
2789 /** True iff we have queued a delete backwards on this circuit, but not put
2790 * it on the output buffer. */
2791 unsigned int p_delete_pending : 1;
2792 /** True iff we have queued a delete forwards on this circuit, but not put
2793 * it on the output buffer. */
2794 unsigned int n_delete_pending : 1;
2796 /** True iff this circuit has received a DESTROY cell in either direction */
2797 unsigned int received_destroy : 1;
2799 uint8_t state; /**< Current status of this circuit. */
2800 uint8_t purpose; /**< Why are we creating this circuit? */
2802 /** How many relay data cells can we package (read from edge streams)
2803 * on this circuit before we receive a circuit-level sendme cell asking
2804 * for more? */
2805 int package_window;
2806 /** How many relay data cells will we deliver (write to edge streams)
2807 * on this circuit? When deliver_window gets low, we send some
2808 * circuit-level sendme cells to indicate that we're willing to accept
2809 * more. */
2810 int deliver_window;
2812 /** Temporary field used during circuits_handle_oom. */
2813 uint32_t age_tmp;
2815 /** For storage while n_chan is pending (state CIRCUIT_STATE_CHAN_WAIT). */
2816 struct create_cell_t *n_chan_create_cell;
2818 /** When did circuit construction actually begin (ie send the
2819 * CREATE cell or begin cannibalization).
2821 * Note: This timer will get reset if we decide to cannibalize
2822 * a circuit. It may also get reset during certain phases of hidden
2823 * service circuit use.
2825 * We keep this timestamp with a higher resolution than most so that the
2826 * circuit-build-time tracking code can get millisecond resolution.
2828 struct timeval timestamp_began;
2830 /** This timestamp marks when the init_circuit_base constructor ran. */
2831 struct timeval timestamp_created;
2833 /** When the circuit was first used, or 0 if the circuit is clean.
2835 * XXXX023 Note that some code will artifically adjust this value backward
2836 * in time in order to indicate that a circuit shouldn't be used for new
2837 * streams, but that it can stay alive as long as it has streams on it.
2838 * That's a kludge we should fix.
2840 * XXX023 The CBT code uses this field to record when HS-related
2841 * circuits entered certain states. This usage probably won't
2842 * interfere with this field's primary purpose, but we should
2843 * document it more thoroughly to make sure of that.
2845 time_t timestamp_dirty;
2847 uint16_t marked_for_close; /**< Should we close this circuit at the end of
2848 * the main loop? (If true, holds the line number
2849 * where this circuit was marked.) */
2850 const char *marked_for_close_file; /**< For debugging: in which file was this
2851 * circuit marked for close? */
2853 /** Unique ID for measuring tunneled network status requests. */
2854 uint64_t dirreq_id;
2856 /** Index in smartlist of all circuits (global_circuitlist). */
2857 int global_circuitlist_idx;
2859 /** Next circuit in the doubly-linked ring of circuits waiting to add
2860 * cells to n_conn. NULL if we have no cells pending, or if we're not
2861 * linked to an OR connection. */
2862 struct circuit_t *next_active_on_n_chan;
2863 /** Previous circuit in the doubly-linked ring of circuits waiting to add
2864 * cells to n_conn. NULL if we have no cells pending, or if we're not
2865 * linked to an OR connection. */
2866 struct circuit_t *prev_active_on_n_chan;
2868 /** Various statistics about cells being added to or removed from this
2869 * circuit's queues; used only if CELL_STATS events are enabled and
2870 * cleared after being sent to control port. */
2871 smartlist_t *testing_cell_stats;
2872 } circuit_t;
2874 /** Largest number of relay_early cells that we can send on a given
2875 * circuit. */
2876 #define MAX_RELAY_EARLY_CELLS_PER_CIRCUIT 8
2879 * Describes the circuit building process in simplified terms based
2880 * on the path bias accounting state for a circuit.
2882 * NOTE: These state values are enumerated in the order for which we
2883 * expect circuits to transition through them. If you add states,
2884 * you need to preserve this overall ordering. The various pathbias
2885 * state transition and accounting functions (pathbias_mark_* and
2886 * pathbias_count_*) contain ordinal comparisons to enforce proper
2887 * state transitions for corrections.
2889 * This state machine and the associated logic was created to prevent
2890 * miscounting due to unknown cases of circuit reuse. See also tickets
2891 * #6475 and #7802.
2893 typedef enum {
2894 /** This circuit is "new". It has not yet completed a first hop
2895 * or been counted by the path bias code. */
2896 PATH_STATE_NEW_CIRC = 0,
2897 /** This circuit has completed one/two hops, and has been counted by
2898 * the path bias logic. */
2899 PATH_STATE_BUILD_ATTEMPTED = 1,
2900 /** This circuit has been completely built */
2901 PATH_STATE_BUILD_SUCCEEDED = 2,
2902 /** Did we try to attach any SOCKS streams or hidserv introductions to
2903 * this circuit?
2905 * Note: If we ever implement end-to-end stream timing through test
2906 * stream probes (#5707), we must *not* set this for those probes
2907 * (or any other automatic streams) because the adversary could
2908 * just tag at a later point.
2910 PATH_STATE_USE_ATTEMPTED = 3,
2911 /** Did any SOCKS streams or hidserv introductions actually succeed on
2912 * this circuit?
2914 * If any streams detatch/fail from this circuit, the code transitions
2915 * the circuit back to PATH_STATE_USE_ATTEMPTED to ensure we probe. See
2916 * pathbias_mark_use_rollback() for that.
2918 PATH_STATE_USE_SUCCEEDED = 4,
2921 * This is a special state to indicate that we got a corrupted
2922 * relay cell on a circuit and we don't intend to probe it.
2924 PATH_STATE_USE_FAILED = 5,
2927 * This is a special state to indicate that we already counted
2928 * the circuit. Used to guard against potential state machine
2929 * violations.
2931 PATH_STATE_ALREADY_COUNTED = 6,
2932 } path_state_t;
2933 #define path_state_bitfield_t ENUM_BF(path_state_t)
2935 /** An origin_circuit_t holds data necessary to build and use a circuit.
2937 typedef struct origin_circuit_t {
2938 circuit_t base_;
2940 /** Linked list of AP streams (or EXIT streams if hidden service)
2941 * associated with this circuit. */
2942 edge_connection_t *p_streams;
2944 /** Bytes read from any attached stream since last call to
2945 * control_event_circ_bandwidth_used(). Only used if we're configured
2946 * to emit CIRC_BW events. */
2947 uint32_t n_read_circ_bw;
2949 /** Bytes written to any attached stream since last call to
2950 * control_event_circ_bandwidth_used(). Only used if we're configured
2951 * to emit CIRC_BW events. */
2952 uint32_t n_written_circ_bw;
2954 /** Build state for this circuit. It includes the intended path
2955 * length, the chosen exit router, rendezvous information, etc.
2957 cpath_build_state_t *build_state;
2958 /** The doubly-linked list of crypt_path_t entries, one per hop,
2959 * for this circuit. This includes ciphers for each hop,
2960 * integrity-checking digests for each hop, and package/delivery
2961 * windows for each hop.
2963 crypt_path_t *cpath;
2965 /** Holds all rendezvous data on either client or service side. */
2966 rend_data_t *rend_data;
2968 /** How many more relay_early cells can we send on this circuit, according
2969 * to the specification? */
2970 unsigned int remaining_relay_early_cells : 4;
2972 /** Set if this circuit is insanely old and we already informed the user */
2973 unsigned int is_ancient : 1;
2975 /** Set if this circuit has already been opened. Used to detect
2976 * cannibalized circuits. */
2977 unsigned int has_opened : 1;
2980 * Path bias state machine. Used to ensure integrity of our
2981 * circuit building and usage accounting. See path_state_t
2982 * for more details.
2984 path_state_bitfield_t path_state : 3;
2986 /* If this flag is set, we should not consider attaching any more
2987 * connections to this circuit. */
2988 unsigned int unusable_for_new_conns : 1;
2991 * Tristate variable to guard against pathbias miscounting
2992 * due to circuit purpose transitions changing the decision
2993 * of pathbias_should_count(). This variable is informational
2994 * only. The current results of pathbias_should_count() are
2995 * the official decision for pathbias accounting.
2997 uint8_t pathbias_shouldcount;
2998 #define PATHBIAS_SHOULDCOUNT_UNDECIDED 0
2999 #define PATHBIAS_SHOULDCOUNT_IGNORED 1
3000 #define PATHBIAS_SHOULDCOUNT_COUNTED 2
3002 /** For path probing. Store the temporary probe stream ID
3003 * for response comparison */
3004 streamid_t pathbias_probe_id;
3006 /** For path probing. Store the temporary probe address nonce
3007 * (in host byte order) for response comparison. */
3008 uint32_t pathbias_probe_nonce;
3010 /** Set iff this is a hidden-service circuit which has timed out
3011 * according to our current circuit-build timeout, but which has
3012 * been kept around because it might still succeed in connecting to
3013 * its destination, and which is not a fully-connected rendezvous
3014 * circuit.
3016 * (We clear this flag for client-side rendezvous circuits when they
3017 * are 'joined' to the other side's rendezvous circuit, so that
3018 * connection_ap_handshake_attach_circuit can put client streams on
3019 * the circuit. We also clear this flag for service-side rendezvous
3020 * circuits when they are 'joined' to a client's rend circ, but only
3021 * for symmetry with the client case. Client-side introduction
3022 * circuits are closed when we get a joined rend circ, and
3023 * service-side introduction circuits never have this flag set.) */
3024 unsigned int hs_circ_has_timed_out : 1;
3026 /** Set iff this circuit has been given a relaxed timeout because
3027 * no circuits have opened. Used to prevent spamming logs. */
3028 unsigned int relaxed_timeout : 1;
3030 /** Set iff this is a service-side rendezvous circuit for which a
3031 * new connection attempt has been launched. We consider launching
3032 * a new service-side rend circ to a client when the previous one
3033 * fails; now that we don't necessarily close a service-side rend
3034 * circ when we launch a new one to the same client, this flag keeps
3035 * us from launching two retries for the same failed rend circ. */
3036 unsigned int hs_service_side_rend_circ_has_been_relaunched : 1;
3038 /** What commands were sent over this circuit that decremented the
3039 * RELAY_EARLY counter? This is for debugging task 878. */
3040 uint8_t relay_early_commands[MAX_RELAY_EARLY_CELLS_PER_CIRCUIT];
3042 /** How many RELAY_EARLY cells have been sent over this circuit? This is
3043 * for debugging task 878, too. */
3044 int relay_early_cells_sent;
3046 /** The next stream_id that will be tried when we're attempting to
3047 * construct a new AP stream originating at this circuit. */
3048 streamid_t next_stream_id;
3050 /* The intro key replaces the hidden service's public key if purpose is
3051 * S_ESTABLISH_INTRO or S_INTRO, provided that no unversioned rendezvous
3052 * descriptor is used. */
3053 crypto_pk_t *intro_key;
3055 /** Quasi-global identifier for this circuit; used for control.c */
3056 /* XXXX NM This can get re-used after 2**32 circuits. */
3057 uint32_t global_identifier;
3059 /** True if we have associated one stream to this circuit, thereby setting
3060 * the isolation paramaters for this circuit. Note that this doesn't
3061 * necessarily mean that we've <em>attached</em> any streams to the circuit:
3062 * we may only have marked up this circuit during the launch process.
3064 unsigned int isolation_values_set : 1;
3065 /** True iff any stream has <em>ever</em> been attached to this circuit.
3067 * In a better world we could use timestamp_dirty for this, but
3068 * timestamp_dirty is far too overloaded at the moment.
3070 unsigned int isolation_any_streams_attached : 1;
3072 /** A bitfield of ISO_* flags for every isolation field such that this
3073 * circuit has had streams with more than one value for that field
3074 * attached to it. */
3075 uint8_t isolation_flags_mixed;
3077 /** @name Isolation parameters
3079 * If any streams have been associated with this circ (isolation_values_set
3080 * == 1), and all streams associated with the circuit have had the same
3081 * value for some field ((isolation_flags_mixed & ISO_FOO) == 0), then these
3082 * elements hold the value for that field.
3084 * Note again that "associated" is not the same as "attached": we
3085 * preliminarily associate streams with a circuit while the circuit is being
3086 * launched, so that we can tell whether we need to launch more circuits.
3088 * @{
3090 uint8_t client_proto_type;
3091 uint8_t client_proto_socksver;
3092 uint16_t dest_port;
3093 tor_addr_t client_addr;
3094 char *dest_address;
3095 int session_group;
3096 unsigned nym_epoch;
3097 size_t socks_username_len;
3098 uint8_t socks_password_len;
3099 /* Note that the next two values are NOT NUL-terminated; see
3100 socks_username_len and socks_password_len for their lengths. */
3101 char *socks_username;
3102 char *socks_password;
3103 /** Global identifier for the first stream attached here; used by
3104 * ISO_STREAM. */
3105 uint64_t associated_isolated_stream_global_id;
3106 /**@}*/
3107 /** A list of addr_policy_t for this circuit in particular. Used by
3108 * adjust_exit_policy_from_exitpolicy_failure.
3110 smartlist_t *prepend_policy;
3111 } origin_circuit_t;
3113 struct onion_queue_t;
3115 /** An or_circuit_t holds information needed to implement a circuit at an
3116 * OR. */
3117 typedef struct or_circuit_t {
3118 circuit_t base_;
3120 /** Next circuit in the doubly-linked ring of circuits waiting to add
3121 * cells to p_chan. NULL if we have no cells pending, or if we're not
3122 * linked to an OR connection. */
3123 struct circuit_t *next_active_on_p_chan;
3124 /** Previous circuit in the doubly-linked ring of circuits waiting to add
3125 * cells to p_chan. NULL if we have no cells pending, or if we're not
3126 * linked to an OR connection. */
3127 struct circuit_t *prev_active_on_p_chan;
3128 /** Pointer to an entry on the onion queue, if this circuit is waiting for a
3129 * chance to give an onionskin to a cpuworker. Used only in onion.c */
3130 struct onion_queue_t *onionqueue_entry;
3132 /** The circuit_id used in the previous (backward) hop of this circuit. */
3133 circid_t p_circ_id;
3134 /** Queue of cells waiting to be transmitted on p_conn. */
3135 cell_queue_t p_chan_cells;
3136 /** The channel that is previous in this circuit. */
3137 channel_t *p_chan;
3139 * Circuit mux associated with p_chan to which this circuit is attached;
3140 * NULL if we have no p_chan.
3142 circuitmux_t *p_mux;
3143 /** Linked list of Exit streams associated with this circuit. */
3144 edge_connection_t *n_streams;
3145 /** Linked list of Exit streams associated with this circuit that are
3146 * still being resolved. */
3147 edge_connection_t *resolving_streams;
3148 /** The cipher used by intermediate hops for cells heading toward the
3149 * OP. */
3150 crypto_cipher_t *p_crypto;
3151 /** The cipher used by intermediate hops for cells heading away from
3152 * the OP. */
3153 crypto_cipher_t *n_crypto;
3155 /** The integrity-checking digest used by intermediate hops, for
3156 * cells packaged here and heading towards the OP.
3158 crypto_digest_t *p_digest;
3159 /** The integrity-checking digest used by intermediate hops, for
3160 * cells packaged at the OP and arriving here.
3162 crypto_digest_t *n_digest;
3164 /** Points to spliced circuit if purpose is REND_ESTABLISHED, and circuit
3165 * is not marked for close. */
3166 struct or_circuit_t *rend_splice;
3168 struct or_circuit_rendinfo_s *rendinfo;
3170 /** Stores KH for the handshake. */
3171 char rend_circ_nonce[DIGEST_LEN];/* KH in tor-spec.txt */
3173 /** How many more relay_early cells can we send on this circuit, according
3174 * to the specification? */
3175 unsigned int remaining_relay_early_cells : 4;
3177 /** True iff this circuit was made with a CREATE_FAST cell. */
3178 unsigned int is_first_hop : 1;
3180 /** If set, this circuit carries HS traffic. Consider it in any HS
3181 * statistics. */
3182 unsigned int circuit_carries_hs_traffic_stats : 1;
3184 /** Number of cells that were removed from circuit queue; reset every
3185 * time when writing buffer stats to disk. */
3186 uint32_t processed_cells;
3188 /** Total time in milliseconds that cells spent in both app-ward and
3189 * exit-ward queues of this circuit; reset every time when writing
3190 * buffer stats to disk. */
3191 uint64_t total_cell_waiting_time;
3193 /** Maximum cell queue size for a middle relay; this is stored per circuit
3194 * so append_cell_to_circuit_queue() can adjust it if it changes. If set
3195 * to zero, it is initialized to the default value.
3197 uint32_t max_middle_cells;
3198 } or_circuit_t;
3200 typedef struct or_circuit_rendinfo_s {
3202 #if REND_COOKIE_LEN != DIGEST_LEN
3203 #error "The REND_TOKEN_LEN macro assumes REND_COOKIE_LEN == DIGEST_LEN"
3204 #endif
3205 #define REND_TOKEN_LEN DIGEST_LEN
3207 /** A hash of location-hidden service's PK if purpose is INTRO_POINT, or a
3208 * rendezvous cookie if purpose is REND_POINT_WAITING. Filled with zeroes
3209 * otherwise.
3211 char rend_token[REND_TOKEN_LEN];
3213 /** True if this is a rendezvous point circuit; false if this is an
3214 * introduction point. */
3215 unsigned is_rend_circ;
3217 } or_circuit_rendinfo_t;
3219 /** Convert a circuit subtype to a circuit_t. */
3220 #define TO_CIRCUIT(x) (&((x)->base_))
3222 /** Convert a circuit_t* to a pointer to the enclosing or_circuit_t. Assert
3223 * if the cast is impossible. */
3224 static or_circuit_t *TO_OR_CIRCUIT(circuit_t *);
3225 static const or_circuit_t *CONST_TO_OR_CIRCUIT(const circuit_t *);
3226 /** Convert a circuit_t* to a pointer to the enclosing origin_circuit_t.
3227 * Assert if the cast is impossible. */
3228 static origin_circuit_t *TO_ORIGIN_CIRCUIT(circuit_t *);
3229 static const origin_circuit_t *CONST_TO_ORIGIN_CIRCUIT(const circuit_t *);
3231 /** Return 1 iff <b>node</b> has Exit flag and no BadExit flag.
3232 * Otherwise, return 0.
3234 static INLINE int node_is_good_exit(const node_t *node)
3236 return node->is_exit && ! node->is_bad_exit;
3239 static INLINE or_circuit_t *TO_OR_CIRCUIT(circuit_t *x)
3241 tor_assert(x->magic == OR_CIRCUIT_MAGIC);
3242 return DOWNCAST(or_circuit_t, x);
3244 static INLINE const or_circuit_t *CONST_TO_OR_CIRCUIT(const circuit_t *x)
3246 tor_assert(x->magic == OR_CIRCUIT_MAGIC);
3247 return DOWNCAST(or_circuit_t, x);
3249 static INLINE origin_circuit_t *TO_ORIGIN_CIRCUIT(circuit_t *x)
3251 tor_assert(x->magic == ORIGIN_CIRCUIT_MAGIC);
3252 return DOWNCAST(origin_circuit_t, x);
3254 static INLINE const origin_circuit_t *CONST_TO_ORIGIN_CIRCUIT(
3255 const circuit_t *x)
3257 tor_assert(x->magic == ORIGIN_CIRCUIT_MAGIC);
3258 return DOWNCAST(origin_circuit_t, x);
3261 /** Bitfield type: things that we're willing to use invalid routers for. */
3262 typedef enum invalid_router_usage_t {
3263 ALLOW_INVALID_ENTRY =1,
3264 ALLOW_INVALID_EXIT =2,
3265 ALLOW_INVALID_MIDDLE =4,
3266 ALLOW_INVALID_RENDEZVOUS =8,
3267 ALLOW_INVALID_INTRODUCTION=16,
3268 } invalid_router_usage_t;
3270 /* limits for TCP send and recv buffer size used for constrained sockets */
3271 #define MIN_CONSTRAINED_TCP_BUFFER 2048
3272 #define MAX_CONSTRAINED_TCP_BUFFER 262144 /* 256k */
3274 /** @name Isolation flags
3276 Ways to isolate client streams
3280 /** Isolate based on destination port */
3281 #define ISO_DESTPORT (1u<<0)
3282 /** Isolate based on destination address */
3283 #define ISO_DESTADDR (1u<<1)
3284 /** Isolate based on SOCKS authentication */
3285 #define ISO_SOCKSAUTH (1u<<2)
3286 /** Isolate based on client protocol choice */
3287 #define ISO_CLIENTPROTO (1u<<3)
3288 /** Isolate based on client address */
3289 #define ISO_CLIENTADDR (1u<<4)
3290 /** Isolate based on session group (always on). */
3291 #define ISO_SESSIONGRP (1u<<5)
3292 /** Isolate based on newnym epoch (always on). */
3293 #define ISO_NYM_EPOCH (1u<<6)
3294 /** Isolate all streams (Internal only). */
3295 #define ISO_STREAM (1u<<7)
3296 /**@}*/
3298 /** Default isolation level for ports. */
3299 #define ISO_DEFAULT (ISO_CLIENTADDR|ISO_SOCKSAUTH|ISO_SESSIONGRP|ISO_NYM_EPOCH)
3301 /** Indicates that we haven't yet set a session group on a port_cfg_t. */
3302 #define SESSION_GROUP_UNSET -1
3303 /** Session group reserved for directory connections */
3304 #define SESSION_GROUP_DIRCONN -2
3305 /** Session group reserved for resolve requests launched by a controller */
3306 #define SESSION_GROUP_CONTROL_RESOLVE -3
3307 /** First automatically allocated session group number */
3308 #define SESSION_GROUP_FIRST_AUTO -4
3310 /** Configuration for a single port that we're listening on. */
3311 typedef struct port_cfg_t {
3312 tor_addr_t addr; /**< The actual IP to listen on, if !is_unix_addr. */
3313 int port; /**< The configured port, or CFG_AUTO_PORT to tell Tor to pick its
3314 * own port. */
3315 uint8_t type; /**< One of CONN_TYPE_*_LISTENER */
3316 unsigned is_unix_addr : 1; /**< True iff this is an AF_UNIX address. */
3318 entry_port_cfg_t entry_cfg;
3320 server_port_cfg_t server_cfg;
3322 /* Unix sockets only: */
3323 /** Path for an AF_UNIX address */
3324 char unix_addr[FLEXIBLE_ARRAY_MEMBER];
3325 } port_cfg_t;
3327 /** Ordinary configuration line. */
3328 #define CONFIG_LINE_NORMAL 0
3329 /** Appends to previous configuration for the same option, even if we
3330 * would ordinary replace it. */
3331 #define CONFIG_LINE_APPEND 1
3332 /* Removes all previous configuration for an option. */
3333 #define CONFIG_LINE_CLEAR 2
3335 /** A linked list of lines in a config file. */
3336 typedef struct config_line_t {
3337 char *key;
3338 char *value;
3339 struct config_line_t *next;
3340 /** What special treatment (if any) does this line require? */
3341 unsigned int command:2;
3342 /** If true, subsequent assignments to this linelist should replace
3343 * it, not extend it. Set only on the first item in a linelist in an
3344 * or_options_t. */
3345 unsigned int fragile:1;
3346 } config_line_t;
3348 typedef struct routerset_t routerset_t;
3350 /** A magic value for the (Socks|OR|...)Port options below, telling Tor
3351 * to pick its own port. */
3352 #define CFG_AUTO_PORT 0xc4005e
3354 /** Configuration options for a Tor process. */
3355 typedef struct {
3356 uint32_t magic_;
3358 /** What should the tor process actually do? */
3359 enum {
3360 CMD_RUN_TOR=0, CMD_LIST_FINGERPRINT, CMD_HASH_PASSWORD,
3361 CMD_VERIFY_CONFIG, CMD_RUN_UNITTESTS, CMD_DUMP_CONFIG
3362 } command;
3363 char *command_arg; /**< Argument for command-line option. */
3365 config_line_t *Logs; /**< New-style list of configuration lines
3366 * for logs */
3367 int LogTimeGranularity; /**< Log resolution in milliseconds. */
3369 int LogMessageDomains; /**< Boolean: Should we log the domain(s) in which
3370 * each log message occurs? */
3371 int TruncateLogFile; /**< Boolean: Should we truncate the log file
3372 before we start writing? */
3374 char *DebugLogFile; /**< Where to send verbose log messages. */
3375 char *DataDirectory; /**< OR only: where to store long-term data. */
3376 char *Nickname; /**< OR only: nickname of this onion router. */
3377 char *Address; /**< OR only: configured address for this onion router. */
3378 char *PidFile; /**< Where to store PID of Tor process. */
3380 int DynamicDHGroups; /**< Dynamic generation of prime moduli for use in DH.*/
3382 routerset_t *ExitNodes; /**< Structure containing nicknames, digests,
3383 * country codes and IP address patterns of ORs to
3384 * consider as exits. */
3385 routerset_t *EntryNodes;/**< Structure containing nicknames, digests,
3386 * country codes and IP address patterns of ORs to
3387 * consider as entry points. */
3388 int StrictNodes; /**< Boolean: When none of our EntryNodes or ExitNodes
3389 * are up, or we need to access a node in ExcludeNodes,
3390 * do we just fail instead? */
3391 routerset_t *ExcludeNodes;/**< Structure containing nicknames, digests,
3392 * country codes and IP address patterns of ORs
3393 * not to use in circuits. But see StrictNodes
3394 * above. */
3395 routerset_t *ExcludeExitNodes;/**< Structure containing nicknames, digests,
3396 * country codes and IP address patterns of
3397 * ORs not to consider as exits. */
3399 /** Union of ExcludeNodes and ExcludeExitNodes */
3400 routerset_t *ExcludeExitNodesUnion_;
3402 int DisableAllSwap; /**< Boolean: Attempt to call mlockall() on our
3403 * process for all current and future memory. */
3405 /** List of "entry", "middle", "exit", "introduction", "rendezvous". */
3406 smartlist_t *AllowInvalidNodes;
3407 /** Bitmask; derived from AllowInvalidNodes. */
3408 invalid_router_usage_t AllowInvalid_;
3409 config_line_t *ExitPolicy; /**< Lists of exit policy components. */
3410 int ExitPolicyRejectPrivate; /**< Should we not exit to local addresses? */
3411 config_line_t *SocksPolicy; /**< Lists of socks policy components */
3412 config_line_t *DirPolicy; /**< Lists of dir policy components */
3413 /** Addresses to bind for listening for SOCKS connections. */
3414 config_line_t *SocksListenAddress;
3415 /** Addresses to bind for listening for transparent pf/netfilter
3416 * connections. */
3417 config_line_t *TransListenAddress;
3418 /** Addresses to bind for listening for transparent natd connections */
3419 config_line_t *NATDListenAddress;
3420 /** Addresses to bind for listening for SOCKS connections. */
3421 config_line_t *DNSListenAddress;
3422 /** Addresses to bind for listening for OR connections. */
3423 config_line_t *ORListenAddress;
3424 /** Addresses to bind for listening for directory connections. */
3425 config_line_t *DirListenAddress;
3426 /** Addresses to bind for listening for control connections. */
3427 config_line_t *ControlListenAddress;
3428 /** Local address to bind outbound sockets */
3429 config_line_t *OutboundBindAddress;
3430 /** IPv4 address derived from OutboundBindAddress. */
3431 tor_addr_t OutboundBindAddressIPv4_;
3432 /** IPv6 address derived from OutboundBindAddress. */
3433 tor_addr_t OutboundBindAddressIPv6_;
3434 /** Directory server only: which versions of
3435 * Tor should we tell users to run? */
3436 config_line_t *RecommendedVersions;
3437 config_line_t *RecommendedClientVersions;
3438 config_line_t *RecommendedServerVersions;
3439 /** Whether dirservers allow router descriptors with private IPs. */
3440 int DirAllowPrivateAddresses;
3441 /** Whether routers accept EXTEND cells to routers with private IPs. */
3442 int ExtendAllowPrivateAddresses;
3443 char *User; /**< Name of user to run Tor as. */
3444 char *Group; /**< Name of group to run Tor as. */
3445 config_line_t *ORPort_lines; /**< Ports to listen on for OR connections. */
3446 /** Ports to listen on for extended OR connections. */
3447 config_line_t *ExtORPort_lines;
3448 /** Ports to listen on for SOCKS connections. */
3449 config_line_t *SocksPort_lines;
3450 /** Ports to listen on for transparent pf/netfilter connections. */
3451 config_line_t *TransPort_lines;
3452 const char *TransProxyType; /**< What kind of transparent proxy
3453 * implementation are we using? */
3454 /** Parsed value of TransProxyType. */
3455 enum {
3456 TPT_DEFAULT,
3457 TPT_PF_DIVERT,
3458 TPT_IPFW,
3459 TPT_TPROXY,
3460 } TransProxyType_parsed;
3461 config_line_t *NATDPort_lines; /**< Ports to listen on for transparent natd
3462 * connections. */
3463 config_line_t *ControlPort_lines; /**< Ports to listen on for control
3464 * connections. */
3465 config_line_t *ControlSocket; /**< List of Unix Domain Sockets to listen on
3466 * for control connections. */
3468 int ControlSocketsGroupWritable; /**< Boolean: Are control sockets g+rw? */
3469 config_line_t *SocksSocket; /**< List of Unix Domain Sockets to listen on
3470 * for SOCKS connections. */
3472 int SocksSocketsGroupWritable; /**< Boolean: Are SOCKS sockets g+rw? */
3473 /** Ports to listen on for directory connections. */
3474 config_line_t *DirPort_lines;
3475 config_line_t *DNSPort_lines; /**< Ports to listen on for DNS requests. */
3477 /* MaxMemInQueues value as input by the user. We clean this up to be
3478 * MaxMemInQueues. */
3479 uint64_t MaxMemInQueues_raw;
3480 uint64_t MaxMemInQueues;/**< If we have more memory than this allocated
3481 * for queues and buffers, run the OOM handler */
3482 /** Above this value, consider ourselves low on RAM. */
3483 uint64_t MaxMemInQueues_low_threshold;
3485 /** @name port booleans
3487 * Derived booleans: True iff there is a non-listener port on an AF_INET or
3488 * AF_INET6 address of the given type configured in one of the _lines
3489 * options above.
3491 * @{
3493 unsigned int ORPort_set : 1;
3494 unsigned int SocksPort_set : 1;
3495 unsigned int SocksSocket_set : 1;
3496 unsigned int TransPort_set : 1;
3497 unsigned int NATDPort_set : 1;
3498 unsigned int ControlPort_set : 1;
3499 unsigned int DirPort_set : 1;
3500 unsigned int DNSPort_set : 1;
3501 unsigned int ExtORPort_set : 1;
3502 /**@}*/
3504 int AssumeReachable; /**< Whether to publish our descriptor regardless. */
3505 int AuthoritativeDir; /**< Boolean: is this an authoritative directory? */
3506 int V3AuthoritativeDir; /**< Boolean: is this an authoritative directory
3507 * for version 3 directories? */
3508 int VersioningAuthoritativeDir; /**< Boolean: is this an authoritative
3509 * directory that's willing to recommend
3510 * versions? */
3511 int BridgeAuthoritativeDir; /**< Boolean: is this an authoritative directory
3512 * that aggregates bridge descriptors? */
3514 /** If set on a bridge authority, it will answer requests on its dirport
3515 * for bridge statuses -- but only if the requests use this password. */
3516 char *BridgePassword;
3517 /** If BridgePassword is set, this is a SHA256 digest of the basic http
3518 * authenticator for it. Used so we can do a time-independent comparison. */
3519 char *BridgePassword_AuthDigest_;
3521 int UseBridges; /**< Boolean: should we start all circuits with a bridge? */
3522 config_line_t *Bridges; /**< List of bootstrap bridge addresses. */
3524 config_line_t *ClientTransportPlugin; /**< List of client
3525 transport plugins. */
3527 config_line_t *ServerTransportPlugin; /**< List of client
3528 transport plugins. */
3530 /** List of TCP/IP addresses that transports should listen at. */
3531 config_line_t *ServerTransportListenAddr;
3533 /** List of options that must be passed to pluggable transports. */
3534 config_line_t *ServerTransportOptions;
3536 int BridgeRelay; /**< Boolean: are we acting as a bridge relay? We make
3537 * this explicit so we can change how we behave in the
3538 * future. */
3540 /** Boolean: if we know the bridge's digest, should we get new
3541 * descriptors from the bridge authorities or from the bridge itself? */
3542 int UpdateBridgesFromAuthority;
3544 int AvoidDiskWrites; /**< Boolean: should we never cache things to disk?
3545 * Not used yet. */
3546 int ClientOnly; /**< Boolean: should we never evolve into a server role? */
3547 /** To what authority types do we publish our descriptor? Choices are
3548 * "v1", "v2", "v3", "bridge", or "". */
3549 smartlist_t *PublishServerDescriptor;
3550 /** A bitfield of authority types, derived from PublishServerDescriptor. */
3551 dirinfo_type_t PublishServerDescriptor_;
3552 /** Boolean: do we publish hidden service descriptors to the HS auths? */
3553 int PublishHidServDescriptors;
3554 int FetchServerDescriptors; /**< Do we fetch server descriptors as normal? */
3555 int FetchHidServDescriptors; /**< and hidden service descriptors? */
3556 int HidServDirectoryV2; /**< Do we participate in the HS DHT? */
3558 int VoteOnHidServDirectoriesV2; /**< As a directory authority, vote on
3559 * assignment of the HSDir flag? */
3560 int MinUptimeHidServDirectoryV2; /**< As directory authority, accept hidden
3561 * service directories after what time? */
3563 int FetchUselessDescriptors; /**< Do we fetch non-running descriptors too? */
3564 int AllDirActionsPrivate; /**< Should every directory action be sent
3565 * through a Tor circuit? */
3567 /** Run in 'tor2web mode'? (I.e. only make client connections to hidden
3568 * services, and use a single hop for all hidden-service-related
3569 * circuits.) */
3570 int Tor2webMode;
3572 /** Close hidden service client circuits immediately when they reach
3573 * the normal circuit-build timeout, even if they have already sent
3574 * an INTRODUCE1 cell on its way to the service. */
3575 int CloseHSClientCircuitsImmediatelyOnTimeout;
3577 /** Close hidden-service-side rendezvous circuits immediately when
3578 * they reach the normal circuit-build timeout. */
3579 int CloseHSServiceRendCircuitsImmediatelyOnTimeout;
3581 int ConnLimit; /**< Demanded minimum number of simultaneous connections. */
3582 int ConnLimit_; /**< Maximum allowed number of simultaneous connections. */
3583 int RunAsDaemon; /**< If true, run in the background. (Unix only) */
3584 int FascistFirewall; /**< Whether to prefer ORs reachable on open ports. */
3585 smartlist_t *FirewallPorts; /**< Which ports our firewall allows
3586 * (strings). */
3587 config_line_t *ReachableAddresses; /**< IP:ports our firewall allows. */
3588 config_line_t *ReachableORAddresses; /**< IP:ports for OR conns. */
3589 config_line_t *ReachableDirAddresses; /**< IP:ports for Dir conns. */
3591 int ConstrainedSockets; /**< Shrink xmit and recv socket buffers. */
3592 uint64_t ConstrainedSockSize; /**< Size of constrained buffers. */
3594 /** Whether we should drop exit streams from Tors that we don't know are
3595 * relays. One of "0" (never refuse), "1" (always refuse), or "-1" (do
3596 * what the consensus says, defaulting to 'refuse' if the consensus says
3597 * nothing). */
3598 int RefuseUnknownExits;
3600 /** Application ports that require all nodes in circ to have sufficient
3601 * uptime. */
3602 smartlist_t *LongLivedPorts;
3603 /** Application ports that are likely to be unencrypted and
3604 * unauthenticated; we reject requests for them to prevent the
3605 * user from screwing up and leaking plaintext secrets to an
3606 * observer somewhere on the Internet. */
3607 smartlist_t *RejectPlaintextPorts;
3608 /** Related to RejectPlaintextPorts above, except this config option
3609 * controls whether we warn (in the log and via a controller status
3610 * event) every time a risky connection is attempted. */
3611 smartlist_t *WarnPlaintextPorts;
3612 /** Should we try to reuse the same exit node for a given host */
3613 smartlist_t *TrackHostExits;
3614 int TrackHostExitsExpire; /**< Number of seconds until we expire an
3615 * addressmap */
3616 config_line_t *AddressMap; /**< List of address map directives. */
3617 int AutomapHostsOnResolve; /**< If true, when we get a resolve request for a
3618 * hostname ending with one of the suffixes in
3619 * <b>AutomapHostsSuffixes</b>, map it to a
3620 * virtual address. */
3621 /** List of suffixes for <b>AutomapHostsOnResolve</b>. The special value
3622 * "." means "match everything." */
3623 smartlist_t *AutomapHostsSuffixes;
3624 int RendPostPeriod; /**< How often do we post each rendezvous service
3625 * descriptor? Remember to publish them independently. */
3626 int KeepalivePeriod; /**< How often do we send padding cells to keep
3627 * connections alive? */
3628 int SocksTimeout; /**< How long do we let a socks connection wait
3629 * unattached before we fail it? */
3630 int LearnCircuitBuildTimeout; /**< If non-zero, we attempt to learn a value
3631 * for CircuitBuildTimeout based on timeout
3632 * history */
3633 int CircuitBuildTimeout; /**< Cull non-open circuits that were born at
3634 * least this many seconds ago. Used until
3635 * adaptive algorithm learns a new value. */
3636 int CircuitIdleTimeout; /**< Cull open clean circuits that were born
3637 * at least this many seconds ago. */
3638 int CircuitStreamTimeout; /**< If non-zero, detach streams from circuits
3639 * and try a new circuit if the stream has been
3640 * waiting for this many seconds. If zero, use
3641 * our default internal timeout schedule. */
3642 int MaxOnionQueueDelay; /**<DOCDOC*/
3643 int NewCircuitPeriod; /**< How long do we use a circuit before building
3644 * a new one? */
3645 int MaxCircuitDirtiness; /**< Never use circs that were first used more than
3646 this interval ago. */
3647 int PredictedPortsRelevanceTime; /** How long after we've requested a
3648 * connection for a given port, do we want
3649 * to continue to pick exits that support
3650 * that port? */
3651 uint64_t BandwidthRate; /**< How much bandwidth, on average, are we willing
3652 * to use in a second? */
3653 uint64_t BandwidthBurst; /**< How much bandwidth, at maximum, are we willing
3654 * to use in a second? */
3655 uint64_t MaxAdvertisedBandwidth; /**< How much bandwidth are we willing to
3656 * tell people we have? */
3657 uint64_t RelayBandwidthRate; /**< How much bandwidth, on average, are we
3658 * willing to use for all relayed conns? */
3659 uint64_t RelayBandwidthBurst; /**< How much bandwidth, at maximum, will we
3660 * use in a second for all relayed conns? */
3661 uint64_t PerConnBWRate; /**< Long-term bw on a single TLS conn, if set. */
3662 uint64_t PerConnBWBurst; /**< Allowed burst on a single TLS conn, if set. */
3663 int NumCPUs; /**< How many CPUs should we try to use? */
3664 //int RunTesting; /**< If true, create testing circuits to measure how well the
3665 // * other ORs are running. */
3666 config_line_t *RendConfigLines; /**< List of configuration lines
3667 * for rendezvous services. */
3668 config_line_t *HidServAuth; /**< List of configuration lines for client-side
3669 * authorizations for hidden services */
3670 char *ContactInfo; /**< Contact info to be published in the directory. */
3672 int HeartbeatPeriod; /**< Log heartbeat messages after this many seconds
3673 * have passed. */
3675 char *HTTPProxy; /**< hostname[:port] to use as http proxy, if any. */
3676 tor_addr_t HTTPProxyAddr; /**< Parsed IPv4 addr for http proxy, if any. */
3677 uint16_t HTTPProxyPort; /**< Parsed port for http proxy, if any. */
3678 char *HTTPProxyAuthenticator; /**< username:password string, if any. */
3680 char *HTTPSProxy; /**< hostname[:port] to use as https proxy, if any. */
3681 tor_addr_t HTTPSProxyAddr; /**< Parsed addr for https proxy, if any. */
3682 uint16_t HTTPSProxyPort; /**< Parsed port for https proxy, if any. */
3683 char *HTTPSProxyAuthenticator; /**< username:password string, if any. */
3685 char *Socks4Proxy; /**< hostname:port to use as a SOCKS4 proxy, if any. */
3686 tor_addr_t Socks4ProxyAddr; /**< Derived from Socks4Proxy. */
3687 uint16_t Socks4ProxyPort; /**< Derived from Socks4Proxy. */
3689 char *Socks5Proxy; /**< hostname:port to use as a SOCKS5 proxy, if any. */
3690 tor_addr_t Socks5ProxyAddr; /**< Derived from Sock5Proxy. */
3691 uint16_t Socks5ProxyPort; /**< Derived from Socks5Proxy. */
3692 char *Socks5ProxyUsername; /**< Username for SOCKS5 authentication, if any */
3693 char *Socks5ProxyPassword; /**< Password for SOCKS5 authentication, if any */
3695 /** List of configuration lines for replacement directory authorities.
3696 * If you just want to replace one class of authority at a time,
3697 * use the "Alternate*Authority" options below instead. */
3698 config_line_t *DirAuthorities;
3700 /** List of fallback directory servers */
3701 config_line_t *FallbackDir;
3703 /** Weight to apply to all directory authority rates if considering them
3704 * along with fallbackdirs */
3705 double DirAuthorityFallbackRate;
3707 /** If set, use these main (currently v3) directory authorities and
3708 * not the default ones. */
3709 config_line_t *AlternateDirAuthority;
3711 /** If set, use these bridge authorities and not the default one. */
3712 config_line_t *AlternateBridgeAuthority;
3714 char *MyFamily; /**< Declared family for this OR. */
3715 config_line_t *NodeFamilies; /**< List of config lines for
3716 * node families */
3717 smartlist_t *NodeFamilySets; /**< List of parsed NodeFamilies values. */
3718 config_line_t *AuthDirBadExit; /**< Address policy for descriptors to
3719 * mark as bad exits. */
3720 config_line_t *AuthDirReject; /**< Address policy for descriptors to
3721 * reject. */
3722 config_line_t *AuthDirInvalid; /**< Address policy for descriptors to
3723 * never mark as valid. */
3724 /** @name AuthDir...CC
3726 * Lists of country codes to mark as BadExit, or Invalid, or to
3727 * reject entirely.
3729 * @{
3731 smartlist_t *AuthDirBadExitCCs;
3732 smartlist_t *AuthDirInvalidCCs;
3733 smartlist_t *AuthDirRejectCCs;
3734 /**@}*/
3736 int AuthDirListBadExits; /**< True iff we should list bad exits,
3737 * and vote for all other exits as good. */
3738 int AuthDirMaxServersPerAddr; /**< Do not permit more than this
3739 * number of servers per IP address. */
3740 int AuthDirMaxServersPerAuthAddr; /**< Do not permit more than this
3741 * number of servers per IP address shared
3742 * with an authority. */
3743 int AuthDirHasIPv6Connectivity; /**< Boolean: are we on IPv6? */
3745 /** If non-zero, always vote the Fast flag for any relay advertising
3746 * this amount of capacity or more. */
3747 uint64_t AuthDirFastGuarantee;
3749 /** If non-zero, this advertised capacity or more is always sufficient
3750 * to satisfy the bandwidth requirement for the Guard flag. */
3751 uint64_t AuthDirGuardBWGuarantee;
3753 char *AccountingStart; /**< How long is the accounting interval, and when
3754 * does it start? */
3755 uint64_t AccountingMax; /**< How many bytes do we allow per accounting
3756 * interval before hibernation? 0 for "never
3757 * hibernate." */
3758 /** How do we determine when our AccountingMax has been reached?
3759 * "max" for when in or out reaches AccountingMax
3760 * "sum for when in plus out reaches AccountingMax */
3761 char *AccountingRule_option;
3762 enum { ACCT_MAX, ACCT_SUM } AccountingRule;
3764 /** Base64-encoded hash of accepted passwords for the control system. */
3765 config_line_t *HashedControlPassword;
3766 /** As HashedControlPassword, but not saved. */
3767 config_line_t *HashedControlSessionPassword;
3769 int CookieAuthentication; /**< Boolean: do we enable cookie-based auth for
3770 * the control system? */
3771 char *CookieAuthFile; /**< Filesystem location of a ControlPort
3772 * authentication cookie. */
3773 char *ExtORPortCookieAuthFile; /**< Filesystem location of Extended
3774 * ORPort authentication cookie. */
3775 int CookieAuthFileGroupReadable; /**< Boolean: Is the CookieAuthFile g+r? */
3776 int ExtORPortCookieAuthFileGroupReadable; /**< Boolean: Is the
3777 * ExtORPortCookieAuthFile g+r? */
3778 int LeaveStreamsUnattached; /**< Boolean: Does Tor attach new streams to
3779 * circuits itself (0), or does it expect a controller
3780 * to cope? (1) */
3781 int DisablePredictedCircuits; /**< Boolean: does Tor preemptively
3782 * make circuits in the background (0),
3783 * or not (1)? */
3785 /** Process specifier for a controller that ‘owns’ this Tor
3786 * instance. Tor will terminate if its owning controller does. */
3787 char *OwningControllerProcess;
3789 int ShutdownWaitLength; /**< When we get a SIGINT and we're a server, how
3790 * long do we wait before exiting? */
3791 char *SafeLogging; /**< Contains "relay", "1", "0" (meaning no scrubbing). */
3793 /* Derived from SafeLogging */
3794 enum {
3795 SAFELOG_SCRUB_ALL, SAFELOG_SCRUB_RELAY, SAFELOG_SCRUB_NONE
3796 } SafeLogging_;
3798 int Sandbox; /**< Boolean: should sandboxing be enabled? */
3799 int SafeSocks; /**< Boolean: should we outright refuse application
3800 * connections that use socks4 or socks5-with-local-dns? */
3801 #define LOG_PROTOCOL_WARN (get_options()->ProtocolWarnings ? \
3802 LOG_WARN : LOG_INFO)
3803 int ProtocolWarnings; /**< Boolean: when other parties screw up the Tor
3804 * protocol, is it a warn or an info in our logs? */
3805 int TestSocks; /**< Boolean: when we get a socks connection, do we loudly
3806 * log whether it was DNS-leaking or not? */
3807 int HardwareAccel; /**< Boolean: Should we enable OpenSSL hardware
3808 * acceleration where available? */
3809 /** Token Bucket Refill resolution in milliseconds. */
3810 int TokenBucketRefillInterval;
3811 char *AccelName; /**< Optional hardware acceleration engine name. */
3812 char *AccelDir; /**< Optional hardware acceleration engine search dir. */
3813 int UseEntryGuards; /**< Boolean: Do we try to enter from a smallish number
3814 * of fixed nodes? */
3815 int NumEntryGuards; /**< How many entry guards do we try to establish? */
3816 int UseEntryGuardsAsDirGuards; /** Boolean: Do we try to get directory info
3817 * from a smallish number of fixed nodes? */
3818 int NumDirectoryGuards; /**< How many dir guards do we try to establish?
3819 * If 0, use value from NumEntryGuards. */
3820 int RephistTrackTime; /**< How many seconds do we keep rephist info? */
3821 int FastFirstHopPK; /**< If Tor believes it is safe, should we save a third
3822 * of our PK time by sending CREATE_FAST cells? */
3823 /** Should we always fetch our dir info on the mirror schedule (which
3824 * means directly from the authorities) no matter our other config? */
3825 int FetchDirInfoEarly;
3827 /** Should we fetch our dir info at the start of the consensus period? */
3828 int FetchDirInfoExtraEarly;
3830 char *VirtualAddrNetworkIPv4; /**< Address and mask to hand out for virtual
3831 * MAPADDRESS requests for IPv4 addresses */
3832 char *VirtualAddrNetworkIPv6; /**< Address and mask to hand out for virtual
3833 * MAPADDRESS requests for IPv6 addresses */
3834 int ServerDNSSearchDomains; /**< Boolean: If set, we don't force exit
3835 * addresses to be FQDNs, but rather search for them in
3836 * the local domains. */
3837 int ServerDNSDetectHijacking; /**< Boolean: If true, check for DNS failure
3838 * hijacking. */
3839 int ServerDNSRandomizeCase; /**< Boolean: Use the 0x20-hack to prevent
3840 * DNS poisoning attacks. */
3841 char *ServerDNSResolvConfFile; /**< If provided, we configure our internal
3842 * resolver from the file here rather than from
3843 * /etc/resolv.conf (Unix) or the registry (Windows). */
3844 char *DirPortFrontPage; /**< This is a full path to a file with an html
3845 disclaimer. This allows a server administrator to show
3846 that they're running Tor and anyone visiting their server
3847 will know this without any specialized knowledge. */
3848 int DisableDebuggerAttachment; /**< Currently Linux only specific attempt to
3849 disable ptrace; needs BSD testing. */
3850 /** Boolean: if set, we start even if our resolv.conf file is missing
3851 * or broken. */
3852 int ServerDNSAllowBrokenConfig;
3853 /** Boolean: if set, then even connections to private addresses will get
3854 * rate-limited. */
3855 int CountPrivateBandwidth;
3856 smartlist_t *ServerDNSTestAddresses; /**< A list of addresses that definitely
3857 * should be resolvable. Used for
3858 * testing our DNS server. */
3859 int EnforceDistinctSubnets; /**< If true, don't allow multiple routers in the
3860 * same network zone in the same circuit. */
3861 int PortForwarding; /**< If true, use NAT-PMP or UPnP to automatically
3862 * forward the DirPort and ORPort on the NAT device */
3863 char *PortForwardingHelper; /** < Filename or full path of the port
3864 forwarding helper executable */
3865 int AllowNonRFC953Hostnames; /**< If true, we allow connections to hostnames
3866 * with weird characters. */
3867 /** If true, we try resolving hostnames with weird characters. */
3868 int ServerDNSAllowNonRFC953Hostnames;
3870 /** If true, we try to download extra-info documents (and we serve them,
3871 * if we are a cache). For authorities, this is always true. */
3872 int DownloadExtraInfo;
3874 /** If true, and we are acting as a relay, allow exit circuits even when
3875 * we are the first hop of a circuit. */
3876 int AllowSingleHopExits;
3877 /** If true, don't allow relays with AllowSingleHopExits=1 to be used in
3878 * circuits that we build. */
3879 int ExcludeSingleHopRelays;
3880 /** If true, and the controller tells us to use a one-hop circuit, and the
3881 * exit allows it, we use it. */
3882 int AllowSingleHopCircuits;
3884 /** If true, we convert "www.google.com.foo.exit" addresses on the
3885 * socks/trans/natd ports into "www.google.com" addresses that
3886 * exit from the node "foo". Disabled by default since attacking
3887 * websites and exit relays can use it to manipulate your path
3888 * selection. */
3889 int AllowDotExit;
3891 /** If true, we will warn if a user gives us only an IP address
3892 * instead of a hostname. */
3893 int WarnUnsafeSocks;
3895 /** If true, we're configured to collect statistics on clients
3896 * requesting network statuses from us as directory. */
3897 int DirReqStatistics_option;
3898 /** Internal variable to remember whether we're actually acting on
3899 * DirReqStatistics_option -- yes if it's set and we're a server, else no. */
3900 int DirReqStatistics;
3902 /** If true, the user wants us to collect statistics on port usage. */
3903 int ExitPortStatistics;
3905 /** If true, the user wants us to collect connection statistics. */
3906 int ConnDirectionStatistics;
3908 /** If true, the user wants us to collect cell statistics. */
3909 int CellStatistics;
3911 /** If true, the user wants us to collect statistics as entry node. */
3912 int EntryStatistics;
3914 /** If true, the user wants us to collect statistics as hidden service
3915 * directory, introduction point, or rendezvous point. */
3916 int HiddenServiceStatistics;
3918 /** If true, include statistics file contents in extra-info documents. */
3919 int ExtraInfoStatistics;
3921 /** If true, do not believe anybody who tells us that a domain resolves
3922 * to an internal address, or that an internal address has a PTR mapping.
3923 * Helps avoid some cross-site attacks. */
3924 int ClientDNSRejectInternalAddresses;
3926 /** If true, do not accept any requests to connect to internal addresses
3927 * over randomly chosen exits. */
3928 int ClientRejectInternalAddresses;
3930 /** If true, clients may connect over IPv6. XXX we don't really
3931 enforce this -- clients _may_ set up outgoing IPv6 connections
3932 even when this option is not set. */
3933 int ClientUseIPv6;
3934 /** If true, prefer an IPv6 OR port over an IPv4 one. */
3935 int ClientPreferIPv6ORPort;
3937 /** The length of time that we think a consensus should be fresh. */
3938 int V3AuthVotingInterval;
3939 /** The length of time we think it will take to distribute votes. */
3940 int V3AuthVoteDelay;
3941 /** The length of time we think it will take to distribute signatures. */
3942 int V3AuthDistDelay;
3943 /** The number of intervals we think a consensus should be valid. */
3944 int V3AuthNIntervalsValid;
3946 /** Should advertise and sign consensuses with a legacy key, for key
3947 * migration purposes? */
3948 int V3AuthUseLegacyKey;
3950 /** Location of bandwidth measurement file */
3951 char *V3BandwidthsFile;
3953 /** Authority only: key=value pairs that we add to our networkstatus
3954 * consensus vote on the 'params' line. */
3955 char *ConsensusParams;
3957 /** Authority only: minimum number of measured bandwidths we must see
3958 * before we only beliee measured bandwidths to assign flags. */
3959 int MinMeasuredBWsForAuthToIgnoreAdvertised;
3961 /** The length of time that we think an initial consensus should be fresh.
3962 * Only altered on testing networks. */
3963 int TestingV3AuthInitialVotingInterval;
3965 /** The length of time we think it will take to distribute initial votes.
3966 * Only altered on testing networks. */
3967 int TestingV3AuthInitialVoteDelay;
3969 /** The length of time we think it will take to distribute initial
3970 * signatures. Only altered on testing networks.*/
3971 int TestingV3AuthInitialDistDelay;
3973 /** Offset in seconds added to the starting time for consensus
3974 voting. Only altered on testing networks. */
3975 int TestingV3AuthVotingStartOffset;
3977 /** If an authority has been around for less than this amount of time, it
3978 * does not believe its reachability information is accurate. Only
3979 * altered on testing networks. */
3980 int TestingAuthDirTimeToLearnReachability;
3982 /** Clients don't download any descriptor this recent, since it will
3983 * probably not have propagated to enough caches. Only altered on testing
3984 * networks. */
3985 int TestingEstimatedDescriptorPropagationTime;
3987 /** Schedule for when servers should download things in general. Only
3988 * altered on testing networks. */
3989 smartlist_t *TestingServerDownloadSchedule;
3991 /** Schedule for when clients should download things in general. Only
3992 * altered on testing networks. */
3993 smartlist_t *TestingClientDownloadSchedule;
3995 /** Schedule for when servers should download consensuses. Only altered
3996 * on testing networks. */
3997 smartlist_t *TestingServerConsensusDownloadSchedule;
3999 /** Schedule for when clients should download consensuses. Only altered
4000 * on testing networks. */
4001 smartlist_t *TestingClientConsensusDownloadSchedule;
4003 /** Schedule for when clients should download bridge descriptors. Only
4004 * altered on testing networks. */
4005 smartlist_t *TestingBridgeDownloadSchedule;
4007 /** When directory clients have only a few descriptors to request, they
4008 * batch them until they have more, or until this amount of time has
4009 * passed. Only altered on testing networks. */
4010 int TestingClientMaxIntervalWithoutRequest;
4012 /** How long do we let a directory connection stall before expiring
4013 * it? Only altered on testing networks. */
4014 int TestingDirConnectionMaxStall;
4016 /** How many times will we try to fetch a consensus before we give
4017 * up? Only altered on testing networks. */
4018 int TestingConsensusMaxDownloadTries;
4020 /** How many times will we try to download a router's descriptor before
4021 * giving up? Only altered on testing networks. */
4022 int TestingDescriptorMaxDownloadTries;
4024 /** How many times will we try to download a microdescriptor before
4025 * giving up? Only altered on testing networks. */
4026 int TestingMicrodescMaxDownloadTries;
4028 /** How many times will we try to fetch a certificate before giving
4029 * up? Only altered on testing networks. */
4030 int TestingCertMaxDownloadTries;
4032 /** If true, we take part in a testing network. Change the defaults of a
4033 * couple of other configuration options and allow to change the values
4034 * of certain configuration options. */
4035 int TestingTorNetwork;
4037 /** Minimum value for the Exit flag threshold on testing networks. */
4038 uint64_t TestingMinExitFlagThreshold;
4040 /** Minimum value for the Fast flag threshold on testing networks. */
4041 uint64_t TestingMinFastFlagThreshold;
4043 /** Relays in a testing network which should be voted Exit
4044 * regardless of exit policy. */
4045 routerset_t *TestingDirAuthVoteExit;
4047 /** Relays in a testing network which should be voted Guard
4048 * regardless of uptime and bandwidth. */
4049 routerset_t *TestingDirAuthVoteGuard;
4051 /** Relays in a testing network which should be voted HSDir
4052 * regardless of uptime and ORPort connectivity.
4053 * Respects VoteOnHidServDirectoriesV2. */
4054 routerset_t *TestingDirAuthVoteHSDir;
4056 /** Enable CONN_BW events. Only altered on testing networks. */
4057 int TestingEnableConnBwEvent;
4059 /** Enable CELL_STATS events. Only altered on testing networks. */
4060 int TestingEnableCellStatsEvent;
4062 /** Enable TB_EMPTY events. Only altered on testing networks. */
4063 int TestingEnableTbEmptyEvent;
4065 /** If true, and we have GeoIP data, and we're a bridge, keep a per-country
4066 * count of how many client addresses have contacted us so that we can help
4067 * the bridge authority guess which countries have blocked access to us. */
4068 int BridgeRecordUsageByCountry;
4070 /** Optionally, IPv4 and IPv6 GeoIP data. */
4071 char *GeoIPFile;
4072 char *GeoIPv6File;
4074 /** Autobool: if auto, then any attempt to Exclude{Exit,}Nodes a particular
4075 * country code will exclude all nodes in ?? and A1. If true, all nodes in
4076 * ?? and A1 are excluded. Has no effect if we don't know any GeoIP data. */
4077 int GeoIPExcludeUnknown;
4079 /** If true, SIGHUP should reload the torrc. Sometimes controllers want
4080 * to make this false. */
4081 int ReloadTorrcOnSIGHUP;
4083 /* The main parameter for picking circuits within a connection.
4085 * If this value is positive, when picking a cell to relay on a connection,
4086 * we always relay from the circuit whose weighted cell count is lowest.
4087 * Cells are weighted exponentially such that if one cell is sent
4088 * 'CircuitPriorityHalflife' seconds before another, it counts for half as
4089 * much.
4091 * If this value is zero, we're disabling the cell-EWMA algorithm.
4093 * If this value is negative, we're using the default approach
4094 * according to either Tor or a parameter set in the consensus.
4096 double CircuitPriorityHalflife;
4098 /** If true, do not enable IOCP on windows with bufferevents, even if
4099 * we think we could. */
4100 int DisableIOCP;
4101 /** For testing only: will go away eventually. */
4102 int UseFilteringSSLBufferevents;
4104 /** Set to true if the TestingTorNetwork configuration option is set.
4105 * This is used so that options_validate() has a chance to realize that
4106 * the defaults have changed. */
4107 int UsingTestNetworkDefaults_;
4109 /** If 1, we try to use microdescriptors to build circuits. If 0, we don't.
4110 * If -1, Tor decides. */
4111 int UseMicrodescriptors;
4113 /** File where we should write the ControlPort. */
4114 char *ControlPortWriteToFile;
4115 /** Should that file be group-readable? */
4116 int ControlPortFileGroupReadable;
4118 #define MAX_MAX_CLIENT_CIRCUITS_PENDING 1024
4119 /** Maximum number of non-open general-purpose origin circuits to allow at
4120 * once. */
4121 int MaxClientCircuitsPending;
4123 /** If 1, we always send optimistic data when it's supported. If 0, we
4124 * never use it. If -1, we do what the consensus says. */
4125 int OptimisticData;
4127 /** If 1, and we are using IOCP, we set the kernel socket SNDBUF and RCVBUF
4128 * to 0 to try to save kernel memory and avoid the dread "Out of buffers"
4129 * issue. */
4130 int UserspaceIOCPBuffers;
4132 /** If 1, we accept and launch no external network connections, except on
4133 * control ports. */
4134 int DisableNetwork;
4137 * Parameters for path-bias detection.
4138 * @{
4139 * These options override the default behavior of Tor's (**currently
4140 * experimental**) path bias detection algorithm. To try to find broken or
4141 * misbehaving guard nodes, Tor looks for nodes where more than a certain
4142 * fraction of circuits through that guard fail to get built.
4144 * The PathBiasCircThreshold option controls how many circuits we need to
4145 * build through a guard before we make these checks. The
4146 * PathBiasNoticeRate, PathBiasWarnRate and PathBiasExtremeRate options
4147 * control what fraction of circuits must succeed through a guard so we
4148 * won't write log messages. If less than PathBiasExtremeRate circuits
4149 * succeed *and* PathBiasDropGuards is set to 1, we disable use of that
4150 * guard.
4152 * When we have seen more than PathBiasScaleThreshold circuits through a
4153 * guard, we scale our observations by 0.5 (governed by the consensus) so
4154 * that new observations don't get swamped by old ones.
4156 * By default, or if a negative value is provided for one of these options,
4157 * Tor uses reasonable defaults from the networkstatus consensus document.
4158 * If no defaults are available there, these options default to 150, .70,
4159 * .50, .30, 0, and 300 respectively.
4161 int PathBiasCircThreshold;
4162 double PathBiasNoticeRate;
4163 double PathBiasWarnRate;
4164 double PathBiasExtremeRate;
4165 int PathBiasDropGuards;
4166 int PathBiasScaleThreshold;
4167 /** @} */
4170 * Parameters for path-bias use detection
4171 * @{
4172 * Similar to the above options, these options override the default behavior
4173 * of Tor's (**currently experimental**) path use bias detection algorithm.
4175 * Where as the path bias parameters govern thresholds for successfully
4176 * building circuits, these four path use bias parameters govern thresholds
4177 * only for circuit usage. Circuits which receive no stream usage are not
4178 * counted by this detection algorithm. A used circuit is considered
4179 * successful if it is capable of carrying streams or otherwise receiving
4180 * well-formed responses to RELAY cells.
4182 * By default, or if a negative value is provided for one of these options,
4183 * Tor uses reasonable defaults from the networkstatus consensus document.
4184 * If no defaults are available there, these options default to 20, .80,
4185 * .60, and 100, respectively.
4187 int PathBiasUseThreshold;
4188 double PathBiasNoticeUseRate;
4189 double PathBiasExtremeUseRate;
4190 int PathBiasScaleUseThreshold;
4191 /** @} */
4193 int IPv6Exit; /**< Do we support exiting to IPv6 addresses? */
4195 char *TLSECGroup; /**< One of "P256", "P224", or nil for auto */
4197 /** Autobool: should we use the ntor handshake if we can? */
4198 int UseNTorHandshake;
4200 /** Fraction: */
4201 double PathsNeededToBuildCircuits;
4203 /** What expiry time shall we place on our SSL certs? "0" means we
4204 * should guess a suitable value. */
4205 int SSLKeyLifetime;
4207 /** How long (seconds) do we keep a guard before picking a new one? */
4208 int GuardLifetime;
4210 /** Low-water mark for global scheduler - start sending when estimated
4211 * queued size falls below this threshold.
4213 uint64_t SchedulerLowWaterMark__;
4214 /** High-water mark for global scheduler - stop sending when estimated
4215 * queued size exceeds this threshold.
4217 uint64_t SchedulerHighWaterMark__;
4218 /** Flush size for global scheduler - flush this many cells at a time
4219 * when sending.
4221 int SchedulerMaxFlushCells__;
4223 /** Is this an exit node? This is a tristate, where "1" means "yes, and use
4224 * the default exit policy if none is given" and "0" means "no; exit policy
4225 * is 'reject *'" and "auto" (-1) means "same as 1, but warn the user."
4227 * XXXX Eventually, the default will be 0. */
4228 int ExitRelay;
4230 } or_options_t;
4232 /** Persistent state for an onion router, as saved to disk. */
4233 typedef struct {
4234 uint32_t magic_;
4235 /** The time at which we next plan to write the state to the disk. Equal to
4236 * TIME_MAX if there are no savable changes, 0 if there are changes that
4237 * should be saved right away. */
4238 time_t next_write;
4240 /** When was the state last written to disk? */
4241 time_t LastWritten;
4243 /** Fields for accounting bandwidth use. */
4244 time_t AccountingIntervalStart;
4245 uint64_t AccountingBytesReadInInterval;
4246 uint64_t AccountingBytesWrittenInInterval;
4247 int AccountingSecondsActive;
4248 int AccountingSecondsToReachSoftLimit;
4249 time_t AccountingSoftLimitHitAt;
4250 uint64_t AccountingBytesAtSoftLimit;
4251 uint64_t AccountingExpectedUsage;
4253 /** A list of Entry Guard-related configuration lines. */
4254 config_line_t *EntryGuards;
4256 config_line_t *TransportProxies;
4258 /** These fields hold information on the history of bandwidth usage for
4259 * servers. The "Ends" fields hold the time when we last updated the
4260 * bandwidth usage. The "Interval" fields hold the granularity, in seconds,
4261 * of the entries of Values. The "Values" lists hold decimal string
4262 * representations of the number of bytes read or written in each
4263 * interval. The "Maxima" list holds decimal strings describing the highest
4264 * rate achieved during the interval.
4266 time_t BWHistoryReadEnds;
4267 int BWHistoryReadInterval;
4268 smartlist_t *BWHistoryReadValues;
4269 smartlist_t *BWHistoryReadMaxima;
4270 time_t BWHistoryWriteEnds;
4271 int BWHistoryWriteInterval;
4272 smartlist_t *BWHistoryWriteValues;
4273 smartlist_t *BWHistoryWriteMaxima;
4274 time_t BWHistoryDirReadEnds;
4275 int BWHistoryDirReadInterval;
4276 smartlist_t *BWHistoryDirReadValues;
4277 smartlist_t *BWHistoryDirReadMaxima;
4278 time_t BWHistoryDirWriteEnds;
4279 int BWHistoryDirWriteInterval;
4280 smartlist_t *BWHistoryDirWriteValues;
4281 smartlist_t *BWHistoryDirWriteMaxima;
4283 /** Build time histogram */
4284 config_line_t * BuildtimeHistogram;
4285 unsigned int TotalBuildTimes;
4286 unsigned int CircuitBuildAbandonedCount;
4288 /** What version of Tor wrote this state file? */
4289 char *TorVersion;
4291 /** Holds any unrecognized values we found in the state file, in the order
4292 * in which we found them. */
4293 config_line_t *ExtraLines;
4295 /** When did we last rotate our onion key? "0" for 'no idea'. */
4296 time_t LastRotatedOnionKey;
4297 } or_state_t;
4299 /** Change the next_write time of <b>state</b> to <b>when</b>, unless the
4300 * state is already scheduled to be written to disk earlier than <b>when</b>.
4302 static INLINE void or_state_mark_dirty(or_state_t *state, time_t when)
4304 if (state->next_write > when)
4305 state->next_write = when;
4308 #define MAX_SOCKS_REPLY_LEN 1024
4309 #define MAX_SOCKS_ADDR_LEN 256
4310 #define SOCKS_NO_AUTH 0x00
4311 #define SOCKS_USER_PASS 0x02
4313 /** Please open a TCP connection to this addr:port. */
4314 #define SOCKS_COMMAND_CONNECT 0x01
4315 /** Please turn this FQDN into an IP address, privately. */
4316 #define SOCKS_COMMAND_RESOLVE 0xF0
4317 /** Please turn this IP address into an FQDN, privately. */
4318 #define SOCKS_COMMAND_RESOLVE_PTR 0xF1
4320 /* || 0 is for -Wparentheses-equality (-Wall?) appeasement under clang */
4321 #define SOCKS_COMMAND_IS_CONNECT(c) (((c)==SOCKS_COMMAND_CONNECT) || 0)
4322 #define SOCKS_COMMAND_IS_RESOLVE(c) ((c)==SOCKS_COMMAND_RESOLVE || \
4323 (c)==SOCKS_COMMAND_RESOLVE_PTR)
4325 /** State of a SOCKS request from a user to an OP. Also used to encode other
4326 * information for non-socks user request (such as those on TransPort and
4327 * DNSPort) */
4328 struct socks_request_t {
4329 /** Which version of SOCKS did the client use? One of "0, 4, 5" -- where
4330 * 0 means that no socks handshake ever took place, and this is just a
4331 * stub connection (e.g. see connection_ap_make_link()). */
4332 uint8_t socks_version;
4333 /** If using socks5 authentication, which authentication type did we
4334 * negotiate? currently we support 0 (no authentication) and 2
4335 * (username/password). */
4336 uint8_t auth_type;
4337 /** What is this stream's goal? One of the SOCKS_COMMAND_* values */
4338 uint8_t command;
4339 /** Which kind of listener created this stream? */
4340 uint8_t listener_type;
4341 size_t replylen; /**< Length of <b>reply</b>. */
4342 uint8_t reply[MAX_SOCKS_REPLY_LEN]; /**< Write an entry into this string if
4343 * we want to specify our own socks reply,
4344 * rather than using the default socks4 or
4345 * socks5 socks reply. We use this for the
4346 * two-stage socks5 handshake.
4348 char address[MAX_SOCKS_ADDR_LEN]; /**< What address did the client ask to
4349 connect to/resolve? */
4350 uint16_t port; /**< What port did the client ask to connect to? */
4351 unsigned int has_finished : 1; /**< Has the SOCKS handshake finished? Used to
4352 * make sure we send back a socks reply for
4353 * every connection. */
4354 unsigned int got_auth : 1; /**< Have we received any authentication data? */
4355 /** If this is set, we will choose "no authentication" instead of
4356 * "username/password" authentication if both are offered. Used as input to
4357 * parse_socks. */
4358 unsigned int socks_prefer_no_auth : 1;
4360 /** Number of bytes in username; 0 if username is NULL */
4361 size_t usernamelen;
4362 /** Number of bytes in password; 0 if password is NULL */
4363 uint8_t passwordlen;
4364 /** The negotiated username value if any (for socks5), or the entire
4365 * authentication string (for socks4). This value is NOT nul-terminated;
4366 * see usernamelen for its length. */
4367 char *username;
4368 /** The negotiated password value if any (for socks5). This value is NOT
4369 * nul-terminated; see passwordlen for its length. */
4370 char *password;
4373 /********************************* circuitbuild.c **********************/
4375 /** How many hops does a general-purpose circuit have by default? */
4376 #define DEFAULT_ROUTE_LEN 3
4378 /* Circuit Build Timeout "public" structures. */
4380 /** Precision multiplier for the Bw weights */
4381 #define BW_WEIGHT_SCALE 10000
4382 #define BW_MIN_WEIGHT_SCALE 1
4383 #define BW_MAX_WEIGHT_SCALE INT32_MAX
4385 /** Total size of the circuit timeout history to accumulate.
4386 * 1000 is approx 2.5 days worth of continual-use circuits. */
4387 #define CBT_NCIRCUITS_TO_OBSERVE 1000
4389 /** Width of the histogram bins in milliseconds */
4390 #define CBT_BIN_WIDTH ((build_time_t)50)
4392 /** Number of modes to use in the weighted-avg computation of Xm */
4393 #define CBT_DEFAULT_NUM_XM_MODES 3
4394 #define CBT_MIN_NUM_XM_MODES 1
4395 #define CBT_MAX_NUM_XM_MODES 20
4397 /** A build_time_t is milliseconds */
4398 typedef uint32_t build_time_t;
4401 * CBT_BUILD_ABANDONED is our flag value to represent a force-closed
4402 * circuit (Aka a 'right-censored' pareto value).
4404 #define CBT_BUILD_ABANDONED ((build_time_t)(INT32_MAX-1))
4405 #define CBT_BUILD_TIME_MAX ((build_time_t)(INT32_MAX))
4407 /** Save state every 10 circuits */
4408 #define CBT_SAVE_STATE_EVERY 10
4410 /* Circuit build times consensus parameters */
4413 * How long to wait before actually closing circuits that take too long to
4414 * build in terms of CDF quantile.
4416 #define CBT_DEFAULT_CLOSE_QUANTILE 95
4417 #define CBT_MIN_CLOSE_QUANTILE CBT_MIN_QUANTILE_CUTOFF
4418 #define CBT_MAX_CLOSE_QUANTILE CBT_MAX_QUANTILE_CUTOFF
4421 * How many circuits count as recent when considering if the
4422 * connection has gone gimpy or changed.
4424 #define CBT_DEFAULT_RECENT_CIRCUITS 20
4425 #define CBT_MIN_RECENT_CIRCUITS 3
4426 #define CBT_MAX_RECENT_CIRCUITS 1000
4429 * Maximum count of timeouts that finish the first hop in the past
4430 * RECENT_CIRCUITS before calculating a new timeout.
4432 * This tells us whether to abandon timeout history and set
4433 * the timeout back to whatever circuit_build_times_get_initial_timeout()
4434 * gives us.
4436 #define CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT (CBT_DEFAULT_RECENT_CIRCUITS*9/10)
4437 #define CBT_MIN_MAX_RECENT_TIMEOUT_COUNT 3
4438 #define CBT_MAX_MAX_RECENT_TIMEOUT_COUNT 10000
4440 /** Minimum circuits before estimating a timeout */
4441 #define CBT_DEFAULT_MIN_CIRCUITS_TO_OBSERVE 100
4442 #define CBT_MIN_MIN_CIRCUITS_TO_OBSERVE 1
4443 #define CBT_MAX_MIN_CIRCUITS_TO_OBSERVE 10000
4445 /** Cutoff percentile on the CDF for our timeout estimation. */
4446 #define CBT_DEFAULT_QUANTILE_CUTOFF 80
4447 #define CBT_MIN_QUANTILE_CUTOFF 10
4448 #define CBT_MAX_QUANTILE_CUTOFF 99
4449 double circuit_build_times_quantile_cutoff(void);
4451 /** How often in seconds should we build a test circuit */
4452 #define CBT_DEFAULT_TEST_FREQUENCY 60
4453 #define CBT_MIN_TEST_FREQUENCY 1
4454 #define CBT_MAX_TEST_FREQUENCY INT32_MAX
4456 /** Lowest allowable value for CircuitBuildTimeout in milliseconds */
4457 #define CBT_DEFAULT_TIMEOUT_MIN_VALUE (1500)
4458 #define CBT_MIN_TIMEOUT_MIN_VALUE 500
4459 #define CBT_MAX_TIMEOUT_MIN_VALUE INT32_MAX
4461 /** Initial circuit build timeout in milliseconds */
4462 #define CBT_DEFAULT_TIMEOUT_INITIAL_VALUE (60*1000)
4463 #define CBT_MIN_TIMEOUT_INITIAL_VALUE CBT_MIN_TIMEOUT_MIN_VALUE
4464 #define CBT_MAX_TIMEOUT_INITIAL_VALUE INT32_MAX
4465 int32_t circuit_build_times_initial_timeout(void);
4467 #if CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT < CBT_MIN_MAX_RECENT_TIMEOUT_COUNT
4468 #error "RECENT_CIRCUITS is set too low."
4469 #endif
4471 /** Information about the state of our local network connection */
4472 typedef struct {
4473 /** The timestamp we last completed a TLS handshake or received a cell */
4474 time_t network_last_live;
4475 /** If the network is not live, how many timeouts has this caused? */
4476 int nonlive_timeouts;
4477 /** Circular array of circuits that have made it to the first hop. Slot is
4478 * 1 if circuit timed out, 0 if circuit succeeded */
4479 int8_t *timeouts_after_firsthop;
4480 /** Number of elements allocated for the above array */
4481 int num_recent_circs;
4482 /** Index into circular array. */
4483 int after_firsthop_idx;
4484 } network_liveness_t;
4486 typedef struct circuit_build_times_s circuit_build_times_t;
4488 /********************************* config.c ***************************/
4490 /** An error from options_trial_assign() or options_init_from_string(). */
4491 typedef enum setopt_err_t {
4492 SETOPT_OK = 0,
4493 SETOPT_ERR_MISC = -1,
4494 SETOPT_ERR_PARSE = -2,
4495 SETOPT_ERR_TRANSITION = -3,
4496 SETOPT_ERR_SETTING = -4,
4497 } setopt_err_t;
4499 /********************************* connection_edge.c *************************/
4501 /** Enumerates possible origins of a client-side address mapping. */
4502 typedef enum {
4503 /** We're remapping this address because the controller told us to. */
4504 ADDRMAPSRC_CONTROLLER,
4505 /** We're remapping this address because of an AutomapHostsOnResolve
4506 * configuration. */
4507 ADDRMAPSRC_AUTOMAP,
4508 /** We're remapping this address because our configuration (via torrc, the
4509 * command line, or a SETCONF command) told us to. */
4510 ADDRMAPSRC_TORRC,
4511 /** We're remapping this address because we have TrackHostExit configured,
4512 * and we want to remember to use the same exit next time. */
4513 ADDRMAPSRC_TRACKEXIT,
4514 /** We're remapping this address because we got a DNS resolution from a
4515 * Tor server that told us what its value was. */
4516 ADDRMAPSRC_DNS,
4518 /** No remapping has occurred. This isn't a possible value for an
4519 * addrmap_entry_t; it's used as a null value when we need to answer "Why
4520 * did this remapping happen." */
4521 ADDRMAPSRC_NONE
4522 } addressmap_entry_source_t;
4523 #define addressmap_entry_source_bitfield_t ENUM_BF(addressmap_entry_source_t)
4525 /********************************* control.c ***************************/
4527 /** Used to indicate the type of a circuit event passed to the controller.
4528 * The various types are defined in control-spec.txt */
4529 typedef enum circuit_status_event_t {
4530 CIRC_EVENT_LAUNCHED = 0,
4531 CIRC_EVENT_BUILT = 1,
4532 CIRC_EVENT_EXTENDED = 2,
4533 CIRC_EVENT_FAILED = 3,
4534 CIRC_EVENT_CLOSED = 4,
4535 } circuit_status_event_t;
4537 /** Used to indicate the type of a CIRC_MINOR event passed to the controller.
4538 * The various types are defined in control-spec.txt . */
4539 typedef enum circuit_status_minor_event_t {
4540 CIRC_MINOR_EVENT_PURPOSE_CHANGED,
4541 CIRC_MINOR_EVENT_CANNIBALIZED,
4542 } circuit_status_minor_event_t;
4544 /** Used to indicate the type of a stream event passed to the controller.
4545 * The various types are defined in control-spec.txt */
4546 typedef enum stream_status_event_t {
4547 STREAM_EVENT_SENT_CONNECT = 0,
4548 STREAM_EVENT_SENT_RESOLVE = 1,
4549 STREAM_EVENT_SUCCEEDED = 2,
4550 STREAM_EVENT_FAILED = 3,
4551 STREAM_EVENT_CLOSED = 4,
4552 STREAM_EVENT_NEW = 5,
4553 STREAM_EVENT_NEW_RESOLVE = 6,
4554 STREAM_EVENT_FAILED_RETRIABLE = 7,
4555 STREAM_EVENT_REMAP = 8
4556 } stream_status_event_t;
4558 /** Used to indicate the type of an OR connection event passed to the
4559 * controller. The various types are defined in control-spec.txt */
4560 typedef enum or_conn_status_event_t {
4561 OR_CONN_EVENT_LAUNCHED = 0,
4562 OR_CONN_EVENT_CONNECTED = 1,
4563 OR_CONN_EVENT_FAILED = 2,
4564 OR_CONN_EVENT_CLOSED = 3,
4565 OR_CONN_EVENT_NEW = 4,
4566 } or_conn_status_event_t;
4568 /** Used to indicate the type of a buildtime event */
4569 typedef enum buildtimeout_set_event_t {
4570 BUILDTIMEOUT_SET_EVENT_COMPUTED = 0,
4571 BUILDTIMEOUT_SET_EVENT_RESET = 1,
4572 BUILDTIMEOUT_SET_EVENT_SUSPENDED = 2,
4573 BUILDTIMEOUT_SET_EVENT_DISCARD = 3,
4574 BUILDTIMEOUT_SET_EVENT_RESUME = 4
4575 } buildtimeout_set_event_t;
4577 /** Execute the statement <b>stmt</b>, which may log events concerning the
4578 * connection <b>conn</b>. To prevent infinite loops, disable log messages
4579 * being sent to controllers if <b>conn</b> is a control connection.
4581 * Stmt must not contain any return or goto statements.
4583 #define CONN_LOG_PROTECT(conn, stmt) \
4584 STMT_BEGIN \
4585 int _log_conn_is_control; \
4586 tor_assert(conn); \
4587 _log_conn_is_control = (conn->type == CONN_TYPE_CONTROL); \
4588 if (_log_conn_is_control) \
4589 disable_control_logging(); \
4590 STMT_BEGIN stmt; STMT_END; \
4591 if (_log_conn_is_control) \
4592 enable_control_logging(); \
4593 STMT_END
4595 /** Enum describing various stages of bootstrapping, for use with controller
4596 * bootstrap status events. The values range from 0 to 100. */
4597 typedef enum {
4598 BOOTSTRAP_STATUS_UNDEF=-1,
4599 BOOTSTRAP_STATUS_STARTING=0,
4600 BOOTSTRAP_STATUS_CONN_DIR=5,
4601 BOOTSTRAP_STATUS_HANDSHAKE=-2,
4602 BOOTSTRAP_STATUS_HANDSHAKE_DIR=10,
4603 BOOTSTRAP_STATUS_ONEHOP_CREATE=15,
4604 BOOTSTRAP_STATUS_REQUESTING_STATUS=20,
4605 BOOTSTRAP_STATUS_LOADING_STATUS=25,
4606 BOOTSTRAP_STATUS_LOADING_KEYS=40,
4607 BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS=45,
4608 BOOTSTRAP_STATUS_LOADING_DESCRIPTORS=50,
4609 BOOTSTRAP_STATUS_CONN_OR=80,
4610 BOOTSTRAP_STATUS_HANDSHAKE_OR=85,
4611 BOOTSTRAP_STATUS_CIRCUIT_CREATE=90,
4612 BOOTSTRAP_STATUS_DONE=100
4613 } bootstrap_status_t;
4615 /********************************* directory.c ***************************/
4617 /** A pair of digests created by dir_split_resource_info_fingerprint_pairs() */
4618 typedef struct {
4619 char first[DIGEST_LEN];
4620 char second[DIGEST_LEN];
4621 } fp_pair_t;
4623 /********************************* dirserv.c ***************************/
4625 /** An enum to describe what format we're generating a routerstatus line in.
4627 typedef enum {
4628 /** For use in a v2 opinion */
4629 NS_V2,
4630 /** For use in a consensus networkstatus document (ns flavor) */
4631 NS_V3_CONSENSUS,
4632 /** For use in a vote networkstatus document */
4633 NS_V3_VOTE,
4634 /** For passing to the controlport in response to a GETINFO request */
4635 NS_CONTROL_PORT,
4636 /** For use in a consensus networkstatus document (microdesc flavor) */
4637 NS_V3_CONSENSUS_MICRODESC
4638 } routerstatus_format_type_t;
4640 #ifdef DIRSERV_PRIVATE
4641 typedef struct measured_bw_line_t {
4642 char node_id[DIGEST_LEN];
4643 char node_hex[MAX_HEX_NICKNAME_LEN+1];
4644 long int bw_kb;
4645 } measured_bw_line_t;
4647 #endif
4649 /********************************* dirvote.c ************************/
4651 /** Describes the schedule by which votes should be generated. */
4652 typedef struct vote_timing_t {
4653 /** Length in seconds between one consensus becoming valid and the next
4654 * becoming valid. */
4655 int vote_interval;
4656 /** For how many intervals is a consensus valid? */
4657 int n_intervals_valid;
4658 /** Time in seconds allowed to propagate votes */
4659 int vote_delay;
4660 /** Time in seconds allowed to propagate signatures */
4661 int dist_delay;
4662 } vote_timing_t;
4664 /********************************* geoip.c **************************/
4666 /** Indicates an action that we might be noting geoip statistics on.
4667 * Note that if we're noticing CONNECT, we're a bridge, and if we're noticing
4668 * the others, we're not.
4670 typedef enum {
4671 /** We've noticed a connection as a bridge relay or entry guard. */
4672 GEOIP_CLIENT_CONNECT = 0,
4673 /** We've served a networkstatus consensus as a directory server. */
4674 GEOIP_CLIENT_NETWORKSTATUS = 1,
4675 } geoip_client_action_t;
4676 /** Indicates either a positive reply or a reason for rejectng a network
4677 * status request that will be included in geoip statistics. */
4678 typedef enum {
4679 /** Request is answered successfully. */
4680 GEOIP_SUCCESS = 0,
4681 /** V3 network status is not signed by a sufficient number of requested
4682 * authorities. */
4683 GEOIP_REJECT_NOT_ENOUGH_SIGS = 1,
4684 /** Requested network status object is unavailable. */
4685 GEOIP_REJECT_UNAVAILABLE = 2,
4686 /** Requested network status not found. */
4687 GEOIP_REJECT_NOT_FOUND = 3,
4688 /** Network status has not been modified since If-Modified-Since time. */
4689 GEOIP_REJECT_NOT_MODIFIED = 4,
4690 /** Directory is busy. */
4691 GEOIP_REJECT_BUSY = 5,
4692 } geoip_ns_response_t;
4693 #define GEOIP_NS_RESPONSE_NUM 6
4695 /** Directory requests that we are measuring can be either direct or
4696 * tunneled. */
4697 typedef enum {
4698 DIRREQ_DIRECT = 0,
4699 DIRREQ_TUNNELED = 1,
4700 } dirreq_type_t;
4702 /** Possible states for either direct or tunneled directory requests that
4703 * are relevant for determining network status download times. */
4704 typedef enum {
4705 /** Found that the client requests a network status; applies to both
4706 * direct and tunneled requests; initial state of a request that we are
4707 * measuring. */
4708 DIRREQ_IS_FOR_NETWORK_STATUS = 0,
4709 /** Finished writing a network status to the directory connection;
4710 * applies to both direct and tunneled requests; completes a direct
4711 * request. */
4712 DIRREQ_FLUSHING_DIR_CONN_FINISHED = 1,
4713 /** END cell sent to circuit that initiated a tunneled request. */
4714 DIRREQ_END_CELL_SENT = 2,
4715 /** Flushed last cell from queue of the circuit that initiated a
4716 * tunneled request to the outbuf of the OR connection. */
4717 DIRREQ_CIRC_QUEUE_FLUSHED = 3,
4718 /** Flushed last byte from buffer of the channel belonging to the
4719 * circuit that initiated a tunneled request; completes a tunneled
4720 * request. */
4721 DIRREQ_CHANNEL_BUFFER_FLUSHED = 4
4722 } dirreq_state_t;
4724 #define WRITE_STATS_INTERVAL (24*60*60)
4726 /********************************* microdesc.c *************************/
4728 typedef struct microdesc_cache_t microdesc_cache_t;
4730 /********************************* networkstatus.c *********************/
4732 /** Possible statuses of a version of Tor, given opinions from the directory
4733 * servers. */
4734 typedef enum version_status_t {
4735 VS_RECOMMENDED=0, /**< This version is listed as recommended. */
4736 VS_OLD=1, /**< This version is older than any recommended version. */
4737 VS_NEW=2, /**< This version is newer than any recommended version. */
4738 VS_NEW_IN_SERIES=3, /**< This version is newer than any recommended version
4739 * in its series, but later recommended versions exist.
4741 VS_UNRECOMMENDED=4, /**< This version is not recommended (general case). */
4742 VS_EMPTY=5, /**< The version list was empty; no agreed-on versions. */
4743 VS_UNKNOWN, /**< We have no idea. */
4744 } version_status_t;
4746 /********************************* policies.c ************************/
4748 /** Outcome of applying an address policy to an address. */
4749 typedef enum {
4750 /** The address was accepted */
4751 ADDR_POLICY_ACCEPTED=0,
4752 /** The address was rejected */
4753 ADDR_POLICY_REJECTED=-1,
4754 /** Part of the address was unknown, but as far as we can tell, it was
4755 * accepted. */
4756 ADDR_POLICY_PROBABLY_ACCEPTED=1,
4757 /** Part of the address was unknown, but as far as we can tell, it was
4758 * rejected. */
4759 ADDR_POLICY_PROBABLY_REJECTED=2,
4760 } addr_policy_result_t;
4762 /********************************* rephist.c ***************************/
4764 /** Possible public/private key operations in Tor: used to keep track of where
4765 * we're spending our time. */
4766 typedef enum {
4767 SIGN_DIR, SIGN_RTR,
4768 VERIFY_DIR, VERIFY_RTR,
4769 ENC_ONIONSKIN, DEC_ONIONSKIN,
4770 TLS_HANDSHAKE_C, TLS_HANDSHAKE_S,
4771 REND_CLIENT, REND_MID, REND_SERVER,
4772 } pk_op_t;
4774 /********************************* rendcommon.c ***************************/
4776 /** Hidden-service side configuration of client authorization. */
4777 typedef struct rend_authorized_client_t {
4778 char *client_name;
4779 char descriptor_cookie[REND_DESC_COOKIE_LEN];
4780 crypto_pk_t *client_key;
4781 } rend_authorized_client_t;
4783 /** ASCII-encoded v2 hidden service descriptor. */
4784 typedef struct rend_encoded_v2_service_descriptor_t {
4785 char desc_id[DIGEST_LEN]; /**< Descriptor ID. */
4786 char *desc_str; /**< Descriptor string. */
4787 } rend_encoded_v2_service_descriptor_t;
4789 /** The maximum number of non-circuit-build-timeout failures a hidden
4790 * service client will tolerate while trying to build a circuit to an
4791 * introduction point. See also rend_intro_point_t.unreachable_count. */
4792 #define MAX_INTRO_POINT_REACHABILITY_FAILURES 5
4794 /** The maximum number of distinct INTRODUCE2 cells which a hidden
4795 * service's introduction point will receive before it begins to
4796 * expire.
4798 * XXX023 Is this number at all sane? */
4799 #define INTRO_POINT_LIFETIME_INTRODUCTIONS 16384
4801 /** The minimum number of seconds that an introduction point will last
4802 * before expiring due to old age. (If it receives
4803 * INTRO_POINT_LIFETIME_INTRODUCTIONS INTRODUCE2 cells, it may expire
4804 * sooner.)
4806 * XXX023 Should this be configurable? */
4807 #define INTRO_POINT_LIFETIME_MIN_SECONDS (18*60*60)
4808 /** The maximum number of seconds that an introduction point will last
4809 * before expiring due to old age.
4811 * XXX023 Should this be configurable? */
4812 #define INTRO_POINT_LIFETIME_MAX_SECONDS (24*60*60)
4814 /** Introduction point information. Used both in rend_service_t (on
4815 * the service side) and in rend_service_descriptor_t (on both the
4816 * client and service side). */
4817 typedef struct rend_intro_point_t {
4818 extend_info_t *extend_info; /**< Extend info of this introduction point. */
4819 crypto_pk_t *intro_key; /**< Introduction key that replaces the service
4820 * key, if this descriptor is V2. */
4822 /** (Client side only) Flag indicating that a timeout has occurred
4823 * after sending an INTRODUCE cell to this intro point. After a
4824 * timeout, an intro point should not be tried again during the same
4825 * hidden service connection attempt, but it may be tried again
4826 * during a future connection attempt. */
4827 unsigned int timed_out : 1;
4829 /** (Client side only) The number of times we have failed to build a
4830 * circuit to this intro point for some reason other than our
4831 * circuit-build timeout. See also MAX_INTRO_POINT_REACHABILITY_FAILURES. */
4832 unsigned int unreachable_count : 3;
4834 /** (Service side only) Flag indicating that this intro point was
4835 * included in the last HS descriptor we generated. */
4836 unsigned int listed_in_last_desc : 1;
4838 /** (Service side only) Flag indicating that
4839 * rend_service_note_removing_intro_point has been called for this
4840 * intro point. */
4841 unsigned int rend_service_note_removing_intro_point_called : 1;
4843 /** (Service side only) A replay cache recording the RSA-encrypted parts
4844 * of INTRODUCE2 cells this intro point's circuit has received. This is
4845 * used to prevent replay attacks. */
4846 replaycache_t *accepted_intro_rsa_parts;
4848 /** (Service side only) Count of INTRODUCE2 cells accepted from this
4849 * intro point.
4851 int accepted_introduce2_count;
4853 /** (Service side only) The time at which this intro point was first
4854 * published, or -1 if this intro point has not yet been
4855 * published. */
4856 time_t time_published;
4858 /** (Service side only) The time at which this intro point should
4859 * (start to) expire, or -1 if we haven't decided when this intro
4860 * point should expire. */
4861 time_t time_to_expire;
4863 /** (Service side only) The time at which we decided that this intro
4864 * point should start expiring, or -1 if this intro point is not yet
4865 * expiring.
4867 * This field also serves as a flag to indicate that we have decided
4868 * to expire this intro point, in case intro_point_should_expire_now
4869 * flaps (perhaps due to a clock jump; perhaps due to other
4870 * weirdness, or even a (present or future) bug). */
4871 time_t time_expiring;
4872 } rend_intro_point_t;
4874 #define REND_PROTOCOL_VERSION_BITMASK_WIDTH 16
4876 /** Information used to connect to a hidden service. Used on both the
4877 * service side and the client side. */
4878 typedef struct rend_service_descriptor_t {
4879 crypto_pk_t *pk; /**< This service's public key. */
4880 int version; /**< Version of the descriptor format: 0 or 2. */
4881 time_t timestamp; /**< Time when the descriptor was generated. */
4882 /** Bitmask: which introduce/rendezvous protocols are supported?
4883 * (We allow bits '0', '1', '2' and '3' to be set.) */
4884 unsigned protocols : REND_PROTOCOL_VERSION_BITMASK_WIDTH;
4885 /** List of the service's introduction points. Elements are removed if
4886 * introduction attempts fail. */
4887 smartlist_t *intro_nodes;
4888 /** Has descriptor been uploaded to all hidden service directories? */
4889 int all_uploads_performed;
4890 /** List of hidden service directories to which an upload request for
4891 * this descriptor could be sent. Smartlist exists only when at least one
4892 * of the previous upload requests failed (otherwise it's not important
4893 * to know which uploads succeeded and which not). */
4894 smartlist_t *successful_uploads;
4895 } rend_service_descriptor_t;
4897 /** A cached rendezvous descriptor. */
4898 typedef struct rend_cache_entry_t {
4899 size_t len; /**< Length of <b>desc</b> */
4900 time_t last_served; /**< When did we last write this one to somebody?
4901 * (HSDir only) */
4902 char *desc; /**< Service descriptor */
4903 rend_service_descriptor_t *parsed; /**< Parsed value of 'desc' */
4904 } rend_cache_entry_t;
4906 /********************************* routerlist.c ***************************/
4908 /** Represents information about a single trusted or fallback directory
4909 * server. */
4910 typedef struct dir_server_t {
4911 char *description;
4912 char *nickname;
4913 char *address; /**< Hostname. */
4914 uint32_t addr; /**< IPv4 address. */
4915 uint16_t dir_port; /**< Directory port. */
4916 uint16_t or_port; /**< OR port: Used for tunneling connections. */
4917 double weight; /** Weight used when selecting this node at random */
4918 char digest[DIGEST_LEN]; /**< Digest of identity key. */
4919 char v3_identity_digest[DIGEST_LEN]; /**< Digest of v3 (authority only,
4920 * high-security) identity key. */
4922 unsigned int is_running:1; /**< True iff we think this server is running. */
4923 unsigned int is_authority:1; /**< True iff this is a directory authority
4924 * of some kind. */
4926 /** True iff this server has accepted the most recent server descriptor
4927 * we tried to upload to it. */
4928 unsigned int has_accepted_serverdesc:1;
4930 /** What kind of authority is this? (Bitfield.) */
4931 dirinfo_type_t type;
4933 time_t addr_current_at; /**< When was the document that we derived the
4934 * address information from published? */
4936 routerstatus_t fake_status; /**< Used when we need to pass this trusted
4937 * dir_server_t to directory_initiate_command_*
4938 * as a routerstatus_t. Not updated by the
4939 * router-status management code!
4941 } dir_server_t;
4943 #define ROUTER_REQUIRED_MIN_BANDWIDTH (20*1024)
4945 #define ROUTER_MAX_DECLARED_BANDWIDTH INT32_MAX
4947 /* Flags for pick_directory_server() and pick_trusteddirserver(). */
4948 /** Flag to indicate that we should not automatically be willing to use
4949 * ourself to answer a directory request.
4950 * Passed to router_pick_directory_server (et al).*/
4951 #define PDS_ALLOW_SELF (1<<0)
4952 /** Flag to indicate that if no servers seem to be up, we should mark all
4953 * directory servers as up and try again.
4954 * Passed to router_pick_directory_server (et al).*/
4955 #define PDS_RETRY_IF_NO_SERVERS (1<<1)
4956 /** Flag to indicate that we should not exclude directory servers that
4957 * our ReachableAddress settings would exclude. This usually means that
4958 * we're going to connect to the server over Tor, and so we don't need to
4959 * worry about our firewall telling us we can't.
4960 * Passed to router_pick_directory_server (et al).*/
4961 #define PDS_IGNORE_FASCISTFIREWALL (1<<2)
4962 /** Flag to indicate that we should not use any directory authority to which
4963 * we have an existing directory connection for downloading server descriptors
4964 * or extrainfo documents.
4966 * Passed to router_pick_directory_server (et al)
4968 * [XXXX NOTE: This option is only implemented for pick_trusteddirserver,
4969 * not pick_directory_server. If we make it work on pick_directory_server
4970 * too, we could conservatively make it only prevent multiple fetches to
4971 * the same authority, or we could aggressively make it prevent multiple
4972 * fetches to _any_ single directory server.]
4974 #define PDS_NO_EXISTING_SERVERDESC_FETCH (1<<3)
4975 #define PDS_NO_EXISTING_MICRODESC_FETCH (1<<4)
4977 /** This node is to be chosen as a directory guard, so don't choose any
4978 * node that's currently a guard. */
4979 #define PDS_FOR_GUARD (1<<5)
4981 /** Possible ways to weight routers when choosing one randomly. See
4982 * routerlist_sl_choose_by_bandwidth() for more information.*/
4983 typedef enum bandwidth_weight_rule_t {
4984 NO_WEIGHTING, WEIGHT_FOR_EXIT, WEIGHT_FOR_MID, WEIGHT_FOR_GUARD,
4985 WEIGHT_FOR_DIR
4986 } bandwidth_weight_rule_t;
4988 /** Flags to be passed to control router_choose_random_node() to indicate what
4989 * kind of nodes to pick according to what algorithm. */
4990 typedef enum {
4991 CRN_NEED_UPTIME = 1<<0,
4992 CRN_NEED_CAPACITY = 1<<1,
4993 CRN_NEED_GUARD = 1<<2,
4994 CRN_ALLOW_INVALID = 1<<3,
4995 /* XXXX not used, apparently. */
4996 CRN_WEIGHT_AS_EXIT = 1<<5,
4997 CRN_NEED_DESC = 1<<6
4998 } router_crn_flags_t;
5000 /** Return value for router_add_to_routerlist() and dirserv_add_descriptor() */
5001 typedef enum was_router_added_t {
5002 /* Router was added successfully. */
5003 ROUTER_ADDED_SUCCESSFULLY = 1,
5004 /* Router descriptor was added with warnings to submitter. */
5005 ROUTER_ADDED_NOTIFY_GENERATOR = 0,
5006 /* Extrainfo document was rejected because no corresponding router
5007 * descriptor was found OR router descriptor was rejected because
5008 * it was incompatible with its extrainfo document. */
5009 ROUTER_BAD_EI = -1,
5010 /* Router descriptor was rejected because it is already known. */
5011 ROUTER_IS_ALREADY_KNOWN = -2,
5012 /* General purpose router was rejected, because it was not listed
5013 * in consensus. */
5014 ROUTER_NOT_IN_CONSENSUS = -3,
5015 /* Router was neither in directory consensus nor in any of
5016 * networkstatus documents. Caching it to access later.
5017 * (Applies to fetched descriptors only.) */
5018 ROUTER_NOT_IN_CONSENSUS_OR_NETWORKSTATUS = -4,
5019 /* Router was rejected by directory authority. */
5020 ROUTER_AUTHDIR_REJECTS = -5,
5021 /* Bridge descriptor was rejected because such bridge was not one
5022 * of the bridges we have listed in our configuration. */
5023 ROUTER_WAS_NOT_WANTED = -6,
5024 /* Router descriptor was rejected because it was older than
5025 * OLD_ROUTER_DESC_MAX_AGE. */
5026 ROUTER_WAS_TOO_OLD = -7, /* note contrast with 'NOT_NEW' */
5027 } was_router_added_t;
5029 /********************************* routerparse.c ************************/
5031 #define MAX_STATUS_TAG_LEN 32
5032 /** Structure to hold parsed Tor versions. This is a little messier
5033 * than we would like it to be, because we changed version schemes with 0.1.0.
5035 * See version-spec.txt for the whole business.
5037 typedef struct tor_version_t {
5038 int major;
5039 int minor;
5040 int micro;
5041 /** Release status. For version in the post-0.1 format, this is always
5042 * VER_RELEASE. */
5043 enum { VER_PRE=0, VER_RC=1, VER_RELEASE=2, } status;
5044 int patchlevel;
5045 char status_tag[MAX_STATUS_TAG_LEN];
5046 int svn_revision;
5048 int git_tag_len;
5049 char git_tag[DIGEST_LEN];
5050 } tor_version_t;
5052 #endif