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