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