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