<weasel> tortls.c: In function `tor_tls_client_is_using_v2_ciphers':
[tor.git] / src / or / or.h
blobb0ec610737ca36e75b209d016e8054a398b94ff5
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-2008, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
6 /* $Id$ */
8 /**
9 * \file or.h
10 * \brief Master header file for Tor-specific functionality.
11 **/
13 #ifndef __OR_H
14 #define __OR_H
15 #define OR_H_ID "$Id$"
17 #include "orconfig.h"
18 #ifdef MS_WINDOWS
19 #define WIN32_WINNT 0x400
20 #define _WIN32_WINNT 0x400
21 #define WIN32_LEAN_AND_MEAN
22 #endif
24 #ifdef HAVE_UNISTD_H
25 #include <unistd.h>
26 #endif
27 #ifdef HAVE_SIGNAL_H
28 #include <signal.h>
29 #endif
30 #ifdef HAVE_NETDB_H
31 #include <netdb.h>
32 #endif
33 #ifdef HAVE_SYS_PARAM_H
34 #include <sys/param.h> /* FreeBSD needs this to know what version it is */
35 #endif
36 #include "torint.h"
37 #ifdef HAVE_SYS_WAIT_H
38 #include <sys/wait.h>
39 #endif
40 #ifdef HAVE_SYS_FCNTL_H
41 #include <sys/fcntl.h>
42 #endif
43 #ifdef HAVE_FCNTL_H
44 #include <fcntl.h>
45 #endif
46 #ifdef HAVE_SYS_IOCTL_H
47 #include <sys/ioctl.h>
48 #endif
49 #ifdef HAVE_SYS_UN_H
50 #include <sys/un.h>
51 #endif
52 #ifdef HAVE_SYS_STAT_H
53 #include <sys/stat.h>
54 #endif
55 #ifdef HAVE_ARPA_INET_H
56 #include <arpa/inet.h>
57 #endif
58 #ifdef HAVE_ERRNO_H
59 #include <errno.h>
60 #endif
61 #ifdef HAVE_ASSERT_H
62 #include <assert.h>
63 #endif
64 #ifdef HAVE_TIME_H
65 #include <time.h>
66 #endif
68 #ifdef MS_WINDOWS
69 #include <io.h>
70 #include <process.h>
71 #include <direct.h>
72 #include <windows.h>
73 #define snprintf _snprintf
74 #endif
76 #include "crypto.h"
77 #include "tortls.h"
78 #include "log.h"
79 #include "compat.h"
80 #include "container.h"
81 #include "util.h"
82 #include "torgzip.h"
84 #include <event.h>
86 /* These signals are defined to help control_signal_act work.
88 #ifndef SIGHUP
89 #define SIGHUP 1
90 #endif
91 #ifndef SIGINT
92 #define SIGINT 2
93 #endif
94 #ifndef SIGUSR1
95 #define SIGUSR1 10
96 #endif
97 #ifndef SIGUSR2
98 #define SIGUSR2 12
99 #endif
100 #ifndef SIGTERM
101 #define SIGTERM 15
102 #endif
103 /* Controller signals start at a high number so we don't
104 * conflict with system-defined signals. */
105 #define SIGNEWNYM 129
106 #define SIGCLEARDNSCACHE 130
108 #if (SIZEOF_CELL_T != 0)
109 /* On Irix, stdlib.h defines a cell_t type, so we need to make sure
110 * that our stuff always calls cell_t something different. */
111 #define cell_t tor_cell_t
112 #endif
114 /** Length of longest allowable configured nickname. */
115 #define MAX_NICKNAME_LEN 19
116 /** Length of a router identity encoded as a hexadecimal digest, plus
117 * possible dollar sign. */
118 #define MAX_HEX_NICKNAME_LEN (HEX_DIGEST_LEN+1)
119 /** Maximum length of verbose router identifier: dollar sign, hex ID digest,
120 * equal sign or tilde, nickname. */
121 #define MAX_VERBOSE_NICKNAME_LEN (1+HEX_DIGEST_LEN+1+MAX_NICKNAME_LEN)
123 /** Maximum size, in bytes, for resized buffers. */
124 #define MAX_BUF_SIZE ((1<<24)-1) /* 16MB-1 */
125 /** Maximum size, in bytes, for any directory object that we've downloaded. */
126 #define MAX_DIR_DL_SIZE MAX_BUF_SIZE
128 /** For http parsing: Maximum number of bytes we'll accept in the headers
129 * of an HTTP request or response. */
130 #define MAX_HEADERS_SIZE 50000
131 /** Maximum size, in bytes, for any directory object that we're accepting
132 * as an upload. */
133 #define MAX_DIR_UL_SIZE 500000
135 /** Maximum size, in bytes, of a single router descriptor uploaded to us
136 * as a directory authority. Caches and clients fetch whatever descriptors
137 * the authorities tell them to fetch, and don't care about size. */
138 #define MAX_DESCRIPTOR_UPLOAD_SIZE 20000
140 /** Maximum size of a single extrainfo document, as above. */
141 #define MAX_EXTRAINFO_UPLOAD_SIZE 50000
143 /** How long do we keep DNS cache entries before purging them (regardless of
144 * their TTL)? */
145 #define MAX_DNS_ENTRY_AGE (30*60)
146 /** How long do we cache/tell clients to cache DNS records when no TTL is
147 * known? */
148 #define DEFAULT_DNS_TTL (30*60)
149 /** How long can a TTL be before we stop believing it? */
150 #define MAX_DNS_TTL (3*60*60)
151 /** How small can a TTL be before we stop believing it? Provides rudimentary
152 * pinning. */
153 #define MIN_DNS_TTL (60)
155 /** How often do we rotate onion keys? */
156 #define MIN_ONION_KEY_LIFETIME (7*24*60*60)
157 /** How often do we rotate TLS contexts? */
158 #define MAX_SSL_KEY_LIFETIME (2*60*60)
160 /** How old do we allow a router to get before removing it
161 * from the router list? In seconds. */
162 #define ROUTER_MAX_AGE (60*60*48)
163 /** How old can a router get before we (as a server) will no longer
164 * consider it live? In seconds. */
165 #define ROUTER_MAX_AGE_TO_PUBLISH (60*60*20)
166 /** How old do we let a saved descriptor get before force-removing it? */
167 #define OLD_ROUTER_DESC_MAX_AGE (60*60*24*5)
169 /** Possible rules for generating circuit IDs on an OR connection. */
170 typedef enum {
171 CIRC_ID_TYPE_LOWER=0, /**< Pick from 0..1<<15-1. */
172 CIRC_ID_TYPE_HIGHER=1, /**< Pick from 1<<15..1<<16-1. */
173 /** The other side of a connection is an OP: never create circuits to it,
174 * and let it use any circuit ID it wants. */
175 CIRC_ID_TYPE_NEITHER=2
176 } circ_id_type_t;
178 #define _CONN_TYPE_MIN 3
179 /** Type for sockets listening for OR connections. */
180 #define CONN_TYPE_OR_LISTENER 3
181 /** A bidirectional TLS connection transmitting a sequence of cells.
182 * May be from an OR to an OR, or from an OP to an OR. */
183 #define CONN_TYPE_OR 4
184 /** A TCP connection from an onion router to a stream's destination. */
185 #define CONN_TYPE_EXIT 5
186 /** Type for sockets listening for SOCKS connections. */
187 #define CONN_TYPE_AP_LISTENER 6
188 /** A SOCKS proxy connection from the user application to the onion
189 * proxy. */
190 #define CONN_TYPE_AP 7
191 /** Type for sockets listening for HTTP connections to the directory server. */
192 #define CONN_TYPE_DIR_LISTENER 8
193 /** Type for HTTP connections to the directory server. */
194 #define CONN_TYPE_DIR 9
195 /** Connection from the main process to a CPU worker process. */
196 #define CONN_TYPE_CPUWORKER 10
197 /** Type for listening for connections from user interface process. */
198 #define CONN_TYPE_CONTROL_LISTENER 11
199 /** Type for connections from user interface process. */
200 #define CONN_TYPE_CONTROL 12
201 /** Type for sockets listening for transparent connections redirected by pf or
202 * netfilter. */
203 #define CONN_TYPE_AP_TRANS_LISTENER 13
204 /** Type for sockets listening for transparent connections redirected by
205 * natd. */
206 #define CONN_TYPE_AP_NATD_LISTENER 14
207 /** Type for sockets listening for DNS requests. */
208 #define CONN_TYPE_AP_DNS_LISTENER 15
209 #define _CONN_TYPE_MAX 15
210 /* !!!! If _CONN_TYPE_MAX is ever over 15, we must grow the type field in
211 * connection_t. */
213 #define CONN_IS_EDGE(x) \
214 ((x)->type == CONN_TYPE_EXIT || (x)->type == CONN_TYPE_AP)
216 /** State for any listener connection. */
217 #define LISTENER_STATE_READY 0
219 #define _CPUWORKER_STATE_MIN 1
220 /** State for a connection to a cpuworker process that's idle. */
221 #define CPUWORKER_STATE_IDLE 1
222 /** State for a connection to a cpuworker process that's processing a
223 * handshake. */
224 #define CPUWORKER_STATE_BUSY_ONION 2
225 #define _CPUWORKER_STATE_MAX 2
227 #define CPUWORKER_TASK_ONION CPUWORKER_STATE_BUSY_ONION
229 #define _OR_CONN_STATE_MIN 1
230 /** State for a connection to an OR: waiting for connect() to finish. */
231 #define OR_CONN_STATE_CONNECTING 1
232 /** State for a connection to an OR: waiting for proxy command to flush. */
233 #define OR_CONN_STATE_PROXY_FLUSHING 2
234 /** State for a connection to an OR: waiting for proxy response. */
235 #define OR_CONN_STATE_PROXY_READING 3
236 /** State for a connection to an OR or client: SSL is handshaking, not done
237 * yet. */
238 #define OR_CONN_STATE_TLS_HANDSHAKING 4
239 /** State for a connection to an OR: We're doing a second SSL handshake for
240 * renegotiation purposes. */
241 #define OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING 5
242 /** State for a connection at an OR: We're waiting for the client to
243 * renegotiate. */
244 #define OR_CONN_STATE_TLS_SERVER_RENEGOTIATING 6
245 /** State for a connection to an OR: We're done with our SSL handshake, but we
246 * haven't yet negotiated link protocol versions and sent a netinfo cell.
248 #define OR_CONN_STATE_OR_HANDSHAKING 7
249 /** State for a connection to an OR: Ready to send/receive cells. */
250 #define OR_CONN_STATE_OPEN 8
251 #define _OR_CONN_STATE_MAX 8
253 #define _EXIT_CONN_STATE_MIN 1
254 /** State for an exit connection: waiting for response from dns farm. */
255 #define EXIT_CONN_STATE_RESOLVING 1
256 /** State for an exit connection: waiting for connect() to finish. */
257 #define EXIT_CONN_STATE_CONNECTING 2
258 /** State for an exit connection: open and ready to transmit data. */
259 #define EXIT_CONN_STATE_OPEN 3
260 /** State for an exit connection: waiting to be removed. */
261 #define EXIT_CONN_STATE_RESOLVEFAILED 4
262 #define _EXIT_CONN_STATE_MAX 4
264 /* The AP state values must be disjoint from the EXIT state values. */
265 #define _AP_CONN_STATE_MIN 5
266 /** State for a SOCKS connection: waiting for SOCKS request. */
267 #define AP_CONN_STATE_SOCKS_WAIT 5
268 /** State for a SOCKS connection: got a y.onion URL; waiting to receive
269 * rendezvous descriptor. */
270 #define AP_CONN_STATE_RENDDESC_WAIT 6
271 /** The controller will attach this connection to a circuit; it isn't our
272 * job to do so. */
273 #define AP_CONN_STATE_CONTROLLER_WAIT 7
274 /** State for a SOCKS connection: waiting for a completed circuit. */
275 #define AP_CONN_STATE_CIRCUIT_WAIT 8
276 /** State for a SOCKS connection: sent BEGIN, waiting for CONNECTED. */
277 #define AP_CONN_STATE_CONNECT_WAIT 9
278 /** State for a SOCKS connection: sent RESOLVE, waiting for RESOLVED. */
279 #define AP_CONN_STATE_RESOLVE_WAIT 10
280 /** State for a SOCKS connection: ready to send and receive. */
281 #define AP_CONN_STATE_OPEN 11
282 /** State for a transparent natd connection: waiting for original
283 * destination. */
284 #define AP_CONN_STATE_NATD_WAIT 12
285 #define _AP_CONN_STATE_MAX 12
287 /** True iff the AP_CONN_STATE_* value <b>s</b> means that the corresponding
288 * edge connection is not attached to any circuit. */
289 #define AP_CONN_STATE_IS_UNATTACHED(s) \
290 ((s) <= AP_CONN_STATE_CIRCUIT_WAIT || (s) == AP_CONN_STATE_NATD_WAIT)
292 #define _DIR_CONN_STATE_MIN 1
293 /** State for connection to directory server: waiting for connect(). */
294 #define DIR_CONN_STATE_CONNECTING 1
295 /** State for connection to directory server: sending HTTP request. */
296 #define DIR_CONN_STATE_CLIENT_SENDING 2
297 /** State for connection to directory server: reading HTTP response. */
298 #define DIR_CONN_STATE_CLIENT_READING 3
299 /** State for connection to directory server: happy and finished. */
300 #define DIR_CONN_STATE_CLIENT_FINISHED 4
301 /** State for connection at directory server: waiting for HTTP request. */
302 #define DIR_CONN_STATE_SERVER_COMMAND_WAIT 5
303 /** State for connection at directory server: sending HTTP response. */
304 #define DIR_CONN_STATE_SERVER_WRITING 6
305 #define _DIR_CONN_STATE_MAX 6
307 /** True iff the purpose of <b>conn</b> means that it's a server-side
308 * directory connection. */
309 #define DIR_CONN_IS_SERVER(conn) ((conn)->purpose == DIR_PURPOSE_SERVER)
311 #define _CONTROL_CONN_STATE_MIN 1
312 /** State for a control connection: Authenticated and accepting v1 commands. */
313 #define CONTROL_CONN_STATE_OPEN 1
314 /** State for a control connection: Waiting for authentication; speaking
315 * protocol v1. */
316 #define CONTROL_CONN_STATE_NEEDAUTH 2
317 #define _CONTROL_CONN_STATE_MAX 2
319 #define _DIR_PURPOSE_MIN 1
320 /** A connection to a directory server: download a directory. */
321 #define DIR_PURPOSE_FETCH_DIR 1
322 /** A connection to a directory server: download just the list
323 * of running routers. */
324 #define DIR_PURPOSE_FETCH_RUNNING_LIST 2
325 /** A connection to a directory server: download a rendezvous
326 * descriptor. */
327 #define DIR_PURPOSE_FETCH_RENDDESC 3
328 /** A connection to a directory server: set after a rendezvous
329 * descriptor is downloaded. */
330 #define DIR_PURPOSE_HAS_FETCHED_RENDDESC 4
331 /** A connection to a directory server: download one or more network-status
332 * objects */
333 #define DIR_PURPOSE_FETCH_NETWORKSTATUS 5
334 /** A connection to a directory server: download one or more server
335 * descriptors. */
336 #define DIR_PURPOSE_FETCH_SERVERDESC 6
337 /** A connection to a directory server: download one or more extra-info
338 * documents. */
339 #define DIR_PURPOSE_FETCH_EXTRAINFO 7
340 /** A connection to a directory server: upload a server descriptor. */
341 #define DIR_PURPOSE_UPLOAD_DIR 8
342 /** A connection to a directory server: upload a rendezvous
343 * descriptor. */
344 #define DIR_PURPOSE_UPLOAD_RENDDESC 9
345 /** A connection to a directory server: upload a v3 networkstatus vote. */
346 #define DIR_PURPOSE_UPLOAD_VOTE 10
347 /** A connection to a directory server: upload a v3 consensus signature */
348 #define DIR_PURPOSE_UPLOAD_SIGNATURES 11
349 /** A connection to a directory server: download one or more network-status
350 * objects */
351 #define DIR_PURPOSE_FETCH_STATUS_VOTE 12
352 /** A connection to a directory server: download one or more network-status
353 * objects */
354 #define DIR_PURPOSE_FETCH_DETACHED_SIGNATURES 13
355 /** A connection to a directory server: download one or more network-status
356 * objects */
357 #define DIR_PURPOSE_FETCH_CONSENSUS 14
358 /** A connection to a directory server: download one or more network-status
359 * objects */
360 #define DIR_PURPOSE_FETCH_CERTIFICATE 15
362 /** Purpose for connection at a directory server. */
363 #define DIR_PURPOSE_SERVER 16
364 /** A connection to a hidden service directory server: upload a v2 rendezvous
365 * descriptor. */
366 #define DIR_PURPOSE_UPLOAD_RENDDESC_V2 17
367 /** A connection to a hidden service directory server: download a v2 rendezvous
368 * descriptor. */
369 #define DIR_PURPOSE_FETCH_RENDDESC_V2 18
370 #define _DIR_PURPOSE_MAX 18
372 #define _EXIT_PURPOSE_MIN 1
373 /** This exit stream wants to do an ordinary connect. */
374 #define EXIT_PURPOSE_CONNECT 1
375 /** This exit stream wants to do a resolve (either normal or reverse). */
376 #define EXIT_PURPOSE_RESOLVE 2
377 #define _EXIT_PURPOSE_MAX 2
379 /* !!!! If any connection purpose is ever over over 31, we must grow the type
380 * field in connection_t. */
382 /** Circuit state: I'm the origin, still haven't done all my handshakes. */
383 #define CIRCUIT_STATE_BUILDING 0
384 /** Circuit state: Waiting to process the onionskin. */
385 #define CIRCUIT_STATE_ONIONSKIN_PENDING 1
386 /** Circuit state: I'd like to deliver a create, but my n_conn is still
387 * connecting. */
388 #define CIRCUIT_STATE_OR_WAIT 2
389 /** Circuit state: onionskin(s) processed, ready to send/receive cells. */
390 #define CIRCUIT_STATE_OPEN 3
392 #define _CIRCUIT_PURPOSE_MIN 1
394 /* these circuits were initiated elsewhere */
395 #define _CIRCUIT_PURPOSE_OR_MIN 1
396 /** OR-side circuit purpose: normal circuit, at OR. */
397 #define CIRCUIT_PURPOSE_OR 1
398 /** OR-side circuit purpose: At OR, from Bob, waiting for intro from Alices. */
399 #define CIRCUIT_PURPOSE_INTRO_POINT 2
400 /** OR-side circuit purpose: At OR, from Alice, waiting for Bob. */
401 #define CIRCUIT_PURPOSE_REND_POINT_WAITING 3
402 /** OR-side circuit purpose: At OR, both circuits have this purpose. */
403 #define CIRCUIT_PURPOSE_REND_ESTABLISHED 4
404 #define _CIRCUIT_PURPOSE_OR_MAX 4
406 /* these circuits originate at this node */
408 /* here's how circ client-side purposes work:
409 * normal circuits are C_GENERAL.
410 * circuits that are c_introducing are either on their way to
411 * becoming open, or they are open and waiting for a
412 * suitable rendcirc before they send the intro.
413 * circuits that are c_introduce_ack_wait have sent the intro,
414 * but haven't gotten a response yet.
415 * circuits that are c_establish_rend are either on their way
416 * to becoming open, or they are open and have sent the
417 * establish_rendezvous cell but haven't received an ack.
418 * circuits that are c_rend_ready are open and have received a
419 * rend ack, but haven't heard from bob yet. if they have a
420 * buildstate->pending_final_cpath then they're expecting a
421 * cell from bob, else they're not.
422 * circuits that are c_rend_ready_intro_acked are open, and
423 * some intro circ has sent its intro and received an ack.
424 * circuits that are c_rend_joined are open, have heard from
425 * bob, and are talking to him.
427 /** Client-side circuit purpose: Normal circuit, with cpath. */
428 #define CIRCUIT_PURPOSE_C_GENERAL 5
429 /** Client-side circuit purpose: at Alice, connecting to intro point. */
430 #define CIRCUIT_PURPOSE_C_INTRODUCING 6
431 /** Client-side circuit purpose: at Alice, sent INTRODUCE1 to intro point,
432 * waiting for ACK/NAK. */
433 #define CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT 7
434 /** Client-side circuit purpose: at Alice, introduced and acked, closing. */
435 #define CIRCUIT_PURPOSE_C_INTRODUCE_ACKED 8
436 /** Client-side circuit purpose: at Alice, waiting for ack. */
437 #define CIRCUIT_PURPOSE_C_ESTABLISH_REND 9
438 /** Client-side circuit purpose: at Alice, waiting for Bob. */
439 #define CIRCUIT_PURPOSE_C_REND_READY 10
440 /** Client-side circuit purpose: at Alice, waiting for Bob, INTRODUCE
441 * has been acknowledged. */
442 #define CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED 11
443 /** Client-side circuit purpose: at Alice, rendezvous established. */
444 #define CIRCUIT_PURPOSE_C_REND_JOINED 12
446 /** Hidden-service-side circuit purpose: at Bob, waiting for introductions. */
447 #define CIRCUIT_PURPOSE_S_ESTABLISH_INTRO 13
448 /** Hidden-service-side circuit purpose: at Bob, successfully established
449 * intro. */
450 #define CIRCUIT_PURPOSE_S_INTRO 14
451 /** Hidden-service-side circuit purpose: at Bob, connecting to rend point. */
452 #define CIRCUIT_PURPOSE_S_CONNECT_REND 15
453 /** Hidden-service-side circuit purpose: at Bob, rendezvous established. */
454 #define CIRCUIT_PURPOSE_S_REND_JOINED 16
455 /** A testing circuit; not meant to be used for actual traffic. */
456 #define CIRCUIT_PURPOSE_TESTING 17
457 /** A controller made this circuit and Tor should not use it. */
458 #define CIRCUIT_PURPOSE_CONTROLLER 18
459 #define _CIRCUIT_PURPOSE_MAX 18
460 /** A catch-all for unrecognized purposes. Currently we don't expect
461 * to make or see any circuits with this purpose. */
462 #define CIRCUIT_PURPOSE_UNKNOWN 255
464 /** True iff the circuit purpose <b>p</b> is for a circuit that
465 * originated at this node. */
466 #define CIRCUIT_PURPOSE_IS_ORIGIN(p) ((p)>_CIRCUIT_PURPOSE_OR_MAX)
467 #define CIRCUIT_IS_ORIGIN(c) (CIRCUIT_PURPOSE_IS_ORIGIN((c)->purpose))
469 /** How many circuits do we want simultaneously in-progress to handle
470 * a given stream? */
471 #define MIN_CIRCUITS_HANDLING_STREAM 2
473 #define RELAY_COMMAND_BEGIN 1
474 #define RELAY_COMMAND_DATA 2
475 #define RELAY_COMMAND_END 3
476 #define RELAY_COMMAND_CONNECTED 4
477 #define RELAY_COMMAND_SENDME 5
478 #define RELAY_COMMAND_EXTEND 6
479 #define RELAY_COMMAND_EXTENDED 7
480 #define RELAY_COMMAND_TRUNCATE 8
481 #define RELAY_COMMAND_TRUNCATED 9
482 #define RELAY_COMMAND_DROP 10
483 #define RELAY_COMMAND_RESOLVE 11
484 #define RELAY_COMMAND_RESOLVED 12
485 #define RELAY_COMMAND_BEGIN_DIR 13
487 #define RELAY_COMMAND_ESTABLISH_INTRO 32
488 #define RELAY_COMMAND_ESTABLISH_RENDEZVOUS 33
489 #define RELAY_COMMAND_INTRODUCE1 34
490 #define RELAY_COMMAND_INTRODUCE2 35
491 #define RELAY_COMMAND_RENDEZVOUS1 36
492 #define RELAY_COMMAND_RENDEZVOUS2 37
493 #define RELAY_COMMAND_INTRO_ESTABLISHED 38
494 #define RELAY_COMMAND_RENDEZVOUS_ESTABLISHED 39
495 #define RELAY_COMMAND_INTRODUCE_ACK 40
497 /* Reasons why an OR connection is closed */
498 #define END_OR_CONN_REASON_DONE 1
499 #define END_OR_CONN_REASON_TCP_REFUSED 2
500 #define END_OR_CONN_REASON_OR_IDENTITY 3
501 #define END_OR_CONN_REASON_TLS_CONNRESET 4 /* tls connection reset by peer */
502 #define END_OR_CONN_REASON_TLS_TIMEOUT 5
503 #define END_OR_CONN_REASON_TLS_NO_ROUTE 6 /* no route to host/net */
504 #define END_OR_CONN_REASON_TLS_IO_ERROR 7 /* tls read/write error */
505 #define END_OR_CONN_REASON_TLS_MISC 8
507 /* Reasons why we (or a remote OR) might close a stream. See tor-spec.txt for
508 * documentation of these. */
509 #define END_STREAM_REASON_MISC 1
510 #define END_STREAM_REASON_RESOLVEFAILED 2
511 #define END_STREAM_REASON_CONNECTREFUSED 3
512 #define END_STREAM_REASON_EXITPOLICY 4
513 #define END_STREAM_REASON_DESTROY 5
514 #define END_STREAM_REASON_DONE 6
515 #define END_STREAM_REASON_TIMEOUT 7
516 /* 8 is unallocated for historical reasons. */
517 #define END_STREAM_REASON_HIBERNATING 9
518 #define END_STREAM_REASON_INTERNAL 10
519 #define END_STREAM_REASON_RESOURCELIMIT 11
520 #define END_STREAM_REASON_CONNRESET 12
521 #define END_STREAM_REASON_TORPROTOCOL 13
522 #define END_STREAM_REASON_NOTDIRECTORY 14
523 #define END_STREAM_REASON_ENTRYPOLICY 15
525 /* These high-numbered end reasons are not part of the official spec,
526 * and are not intended to be put in relay end cells. They are here
527 * to be more informative when sending back socks replies to the
528 * application. */
529 /* XXXX 256 is no longer used; feel free to reuse it. */
530 /** We were unable to attach the connection to any circuit at all. */
531 /* XXXX the ways we use this one don't make a lot of sense. */
532 #define END_STREAM_REASON_CANT_ATTACH 257
533 /** We can't connect to any directories at all, so we killed our streams
534 * before they can time out. */
535 #define END_STREAM_REASON_NET_UNREACHABLE 258
536 /** This is a SOCKS connection, and the client used (or misused) the SOCKS
537 * protocol in a way we couldn't handle. */
538 #define END_STREAM_REASON_SOCKSPROTOCOL 259
539 /** This is a transparent proxy connection, but we can't extract the original
540 * target address:port. */
541 #define END_STREAM_REASON_CANT_FETCH_ORIG_DEST 260
542 /** This is a connection on the NATD port, and the destination IP:Port was
543 * either ill-formed or out-of-range. */
544 #define END_STREAM_REASON_INVALID_NATD_DEST 261
546 /** Bitwise-and this value with endreason to mask out all flags. */
547 #define END_STREAM_REASON_MASK 511
549 /** Bitwise-or this with the argument to control_event_stream_status
550 * to indicate that the reason came from an END cell. */
551 #define END_STREAM_REASON_FLAG_REMOTE 512
552 /** Bitwise-or this with the argument to control_event_stream_status
553 * to indicate that we already sent a CLOSED stream event. */
554 #define END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED 1024
555 /** Bitwise-or this with endreason to indicate that we already sent
556 * a socks reply, and no further reply needs to be sent from
557 * connection_mark_unattached_ap(). */
558 #define END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED 2048
560 /** Reason for remapping an AP connection's address: we have a cached
561 * answer. */
562 #define REMAP_STREAM_SOURCE_CACHE 1
563 /** Reason for remapping an AP connection's address: the exit node told us an
564 * answer. */
565 #define REMAP_STREAM_SOURCE_EXIT 2
567 /* 'type' values to use in RESOLVED cells. Specified in tor-spec.txt. */
568 #define RESOLVED_TYPE_HOSTNAME 0
569 #define RESOLVED_TYPE_IPV4 4
570 #define RESOLVED_TYPE_IPV6 6
571 #define RESOLVED_TYPE_ERROR_TRANSIENT 0xF0
572 #define RESOLVED_TYPE_ERROR 0xF1
574 /* Negative reasons are internal: we never send them in a DESTROY or TRUNCATE
575 * call; they only go to the controller for tracking */
576 /** We couldn't build a path for this circuit. */
577 #define END_CIRC_REASON_NOPATH -2
578 /** Catch-all "other" reason for closing origin circuits. */
579 #define END_CIRC_AT_ORIGIN -1
581 /* Reasons why we (or a remote OR) might close a circuit. See tor-spec.txt for
582 * documentation of these. */
583 #define _END_CIRC_REASON_MIN 0
584 #define END_CIRC_REASON_NONE 0
585 #define END_CIRC_REASON_TORPROTOCOL 1
586 #define END_CIRC_REASON_INTERNAL 2
587 #define END_CIRC_REASON_REQUESTED 3
588 #define END_CIRC_REASON_HIBERNATING 4
589 #define END_CIRC_REASON_RESOURCELIMIT 5
590 #define END_CIRC_REASON_CONNECTFAILED 6
591 #define END_CIRC_REASON_OR_IDENTITY 7
592 #define END_CIRC_REASON_OR_CONN_CLOSED 8
593 #define END_CIRC_REASON_FINISHED 9
594 #define END_CIRC_REASON_TIMEOUT 10
595 #define END_CIRC_REASON_DESTROYED 11
596 #define END_CIRC_REASON_NOSUCHSERVICE 12
597 #define _END_CIRC_REASON_MAX 12
599 /** Bitwise-OR this with the argument to circuit_mark_for_close() or
600 * control_event_circuit_status() to indicate that the reason was
601 * passed through from a destroy or truncate cell. */
602 #define END_CIRC_REASON_FLAG_REMOTE 512
604 /** Length of 'y' portion of 'y.onion' URL. */
605 #define REND_SERVICE_ID_LEN_BASE32 16
607 /** Length of a binary-encoded rendezvous service ID. */
608 #define REND_SERVICE_ID_LEN 10
610 /** Time period for which a v2 descriptor will be valid. */
611 #define REND_TIME_PERIOD_V2_DESC_VALIDITY (24*60*60)
613 /** Time period within which two sets of v2 descriptors will be uploaded in
614 * parallel. */
615 #define REND_TIME_PERIOD_OVERLAPPING_V2_DESCS (60*60)
617 /** Number of non-consecutive replicas (i.e. distributed somewhere
618 * in the ring) for a descriptor. */
619 #define REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS 2
621 /** Number of consecutive replicas for a descriptor. */
622 #define REND_NUMBER_OF_CONSECUTIVE_REPLICAS 3
624 /** Length of v2 descriptor ID (32 base32 chars = 160 bits). */
625 #define REND_DESC_ID_V2_LEN_BASE32 32
627 /** Length of the base32-encoded secret ID part of versioned hidden service
628 * descriptors. */
629 #define REND_SECRET_ID_PART_LEN_BASE32 32
631 /** Length of the base32-encoded hash of an introduction point's
632 * identity key. */
633 #define REND_INTRO_POINT_ID_LEN_BASE32 32
635 #define CELL_DIRECTION_IN 1
636 #define CELL_DIRECTION_OUT 2
638 /** Initial value for both sides of a circuit transmission window when the
639 * circuit is initialized. Measured in cells. */
640 #define CIRCWINDOW_START 1000
641 /** Amount to increment a circuit window when we get a circuit SENDME. */
642 #define CIRCWINDOW_INCREMENT 100
643 /** Initial value on both sides of a stream transmission window when the
644 * stream is initialized. Measured in cells. */
645 #define STREAMWINDOW_START 500
646 /** Amount to increment a stream window when we get a stream SENDME. */
647 #define STREAMWINDOW_INCREMENT 50
649 /* cell commands */
650 #define CELL_PADDING 0
651 #define CELL_CREATE 1
652 #define CELL_CREATED 2
653 #define CELL_RELAY 3
654 #define CELL_DESTROY 4
655 #define CELL_CREATE_FAST 5
656 #define CELL_CREATED_FAST 6
657 #define CELL_VERSIONS 7
658 #define CELL_NETINFO 8
659 #define CELL_RELAY_EARLY 9
661 #define CELL_COMMAND_IS_VAR_LENGTH(x) ((x) == CELL_VERSIONS)
663 /** How long to test reachability before complaining to the user. */
664 #define TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT (20*60)
666 /** Legal characters in a nickname. */
667 #define LEGAL_NICKNAME_CHARACTERS \
668 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
670 /** Name to use in client TLS certificates if no nickname is given. */
671 #define DEFAULT_CLIENT_NICKNAME "client"
673 /** Number of bytes in a SOCKS4 header. */
674 #define SOCKS4_NETWORK_LEN 8
676 /** Specified SOCKS5 status codes. */
677 typedef enum {
678 SOCKS5_SUCCEEDED = 0x00,
679 SOCKS5_GENERAL_ERROR = 0x01,
680 SOCKS5_NOT_ALLOWED = 0x02,
681 SOCKS5_NET_UNREACHABLE = 0x03,
682 SOCKS5_HOST_UNREACHABLE = 0x04,
683 SOCKS5_CONNECTION_REFUSED = 0x05,
684 SOCKS5_TTL_EXPIRED = 0x06,
685 SOCKS5_COMMAND_NOT_SUPPORTED = 0x07,
686 SOCKS5_ADDRESS_TYPE_NOT_SUPPORTED = 0x08,
687 } socks5_reply_status_t;
690 * Relay payload:
691 * Relay command [1 byte]
692 * Recognized [2 bytes]
693 * Stream ID [2 bytes]
694 * Partial SHA-1 [4 bytes]
695 * Length [2 bytes]
696 * Relay payload [498 bytes]
699 /** Number of bytes in a cell, minus cell header. */
700 #define CELL_PAYLOAD_SIZE 509
701 /** Number of bytes in a cell transmitted over the network. */
702 #define CELL_NETWORK_SIZE 512
704 #define VAR_CELL_HEADER_SIZE 5
706 /** Number of bytes in a relay cell's header (not including general cell
707 * header). */
708 #define RELAY_HEADER_SIZE (1+2+2+4+2)
709 /** Largest number of bytes that can fit in a relay cell payload. */
710 #define RELAY_PAYLOAD_SIZE (CELL_PAYLOAD_SIZE-RELAY_HEADER_SIZE)
712 /** Parsed onion routing cell. All communication between nodes
713 * is via cells. */
714 typedef struct cell_t {
715 uint16_t circ_id; /**< Circuit which received the cell. */
716 uint8_t command; /**< Type of the cell: one of CELL_PADDING, CELL_CREATE,
717 * CELL_DESTROY, etc */
718 char payload[CELL_PAYLOAD_SIZE]; /**< Cell body. */
719 } cell_t;
721 /** Parsed variable-length onion routing cell. */
722 typedef struct var_cell_t {
723 uint8_t command;
724 uint16_t circ_id;
725 uint16_t payload_len;
726 char payload[1];
727 } var_cell_t;
729 /** A cell as packed for writing to the network. */
730 typedef struct packed_cell_t {
731 struct packed_cell_t *next; /**< Next cell queued on this circuit. */
732 char body[CELL_NETWORK_SIZE]; /**< Cell as packed for network. */
733 } packed_cell_t;
735 /** A queue of cells on a circuit, waiting to be added to the
736 * or_connection_t's outbuf. */
737 typedef struct cell_queue_t {
738 packed_cell_t *head; /**< The first cell, or NULL if the queue is empty. */
739 packed_cell_t *tail; /**< The last cell, or NULL if the queue is empty. */
740 int n; /**< The number of cells in the queue. */
741 } cell_queue_t;
743 /** Beginning of a RELAY cell payload. */
744 typedef struct {
745 uint8_t command; /**< The end-to-end relay command. */
746 uint16_t recognized; /**< Used to tell whether cell is for us. */
747 uint16_t stream_id; /**< Which stream is this cell associated with? */
748 char integrity[4]; /**< Used to tell whether cell is corrupted. */
749 uint16_t length; /**< How long is the payload body? */
750 } relay_header_t;
752 typedef struct buf_t buf_t;
753 typedef struct socks_request_t socks_request_t;
755 /* Values for connection_t.magic: used to make sure that downcasts (casts from
756 * connection_t to foo_connection_t) are safe. */
757 #define BASE_CONNECTION_MAGIC 0x7C3C304Eu
758 #define OR_CONNECTION_MAGIC 0x7D31FF03u
759 #define EDGE_CONNECTION_MAGIC 0xF0374013u
760 #define DIR_CONNECTION_MAGIC 0x9988ffeeu
761 #define CONTROL_CONNECTION_MAGIC 0x8abc765du
763 /** Description of a connection to another host or process, and associated
764 * data.
766 * A connection is named based on what it's connected to -- an "OR
767 * connection" has a Tor node on the other end, an "exit
768 * connection" has a website or other server on the other end, and an
769 * "AP connection" has an application proxy (and thus a user) on the
770 * other end.
772 * Every connection has a type and a state. Connections never change
773 * their type, but can go through many state changes in their lifetime.
775 * Every connection has two associated input and output buffers.
776 * Listeners don't use them. For non-listener connections, incoming
777 * data is appended to conn->inbuf, and outgoing data is taken from
778 * conn->outbuf. Connections differ primarily in the functions called
779 * to fill and drain these buffers.
781 typedef struct connection_t {
782 uint32_t magic; /**< For memory debugging: must equal one of
783 * *_CONNECTION_MAGIC. */
785 uint8_t state; /**< Current state of this connection. */
786 unsigned int type:4; /**< What kind of connection is this? */
787 unsigned int purpose:5; /**< Only used for DIR and EXIT types currently. */
789 /* The next fields are all one-bit booleans. Some are only applicable to
790 * connection subtypes, but we hold them here anyway, to save space.
792 unsigned int read_blocked_on_bw:1; /**< Boolean: should we start reading
793 * again once the bandwidth throttler allows it? */
794 unsigned int write_blocked_on_bw:1; /**< Boolean: should we start writing
795 * again once the bandwidth throttler allows
796 * reads? */
797 unsigned int hold_open_until_flushed:1; /**< Despite this connection's being
798 * marked for close, do we flush it
799 * before closing it? */
800 unsigned int inbuf_reached_eof:1; /**< Boolean: did read() return 0 on this
801 * conn? */
802 unsigned int edge_has_sent_end:1; /**< For debugging; only used on edge
803 * connections. Set once we've set the stream end,
804 * and check in connection_about_to_close_connection().
806 /** Edge connections only: true if we've blocked reading until the
807 * circuit has fewer queued cells. */
808 unsigned int edge_blocked_on_circ:1;
809 /** Used for OR conns that shouldn't get any new circs attached to them. */
810 unsigned int or_is_obsolete:1;
811 /** For AP connections only. If 1, and we fail to reach the chosen exit,
812 * stop requiring it. */
813 unsigned int chosen_exit_optional:1;
814 /** For AP connections only. If non-zero, this exit node was picked as
815 * a result of the TrackHostExit, and the value decrements every time
816 * we fail to complete a circuit to our chosen exit -- if it reaches
817 * zero, abandon the associated mapaddress. */
818 unsigned int chosen_exit_retries:3;
819 /** Set to 1 when we're inside connection_flushed_some to keep us from
820 * calling connection_handle_write() recursively. */
821 unsigned int in_flushed_some:1;
823 /* For linked connections:
825 unsigned int linked:1; /**< True if there is, or has been, a linked_conn. */
826 /** True iff we'd like to be notified about read events from the
827 * linked conn. */
828 unsigned int reading_from_linked_conn:1;
829 /** True iff we're willing to write to the linked conn. */
830 unsigned int writing_to_linked_conn:1;
831 /** True iff we're currently able to read on the linked conn, and our
832 * read_event should be made active with libevent. */
833 unsigned int active_on_link:1;
834 /** True iff we've called connection_close_immediate() on this linked
835 * connection. */
836 unsigned int linked_conn_is_closed:1;
838 int s; /**< Our socket; -1 if this connection is closed, or has no
839 * socket. */
840 int conn_array_index; /**< Index into the global connection array. */
841 struct event *read_event; /**< Libevent event structure. */
842 struct event *write_event; /**< Libevent event structure. */
843 buf_t *inbuf; /**< Buffer holding data read over this connection. */
844 buf_t *outbuf; /**< Buffer holding data to write over this connection. */
845 size_t outbuf_flushlen; /**< How much data should we try to flush from the
846 * outbuf? */
847 time_t timestamp_lastread; /**< When was the last time libevent said we could
848 * read? */
849 time_t timestamp_lastwritten; /**< When was the last time libevent said we
850 * could write? */
851 time_t timestamp_created; /**< When was this connection_t created? */
853 /* XXXX_IP6 make this ipv6-capable */
854 int socket_family; /**< Address family of this connection's socket. Usually
855 * AF_INET, but it can also be AF_UNIX, or in the future
856 * AF_INET6 */
857 uint32_t addr; /**< IP of the other side of the connection; used to identify
858 * routers, along with port. */
859 uint16_t port; /**< If non-zero, port on the other end
860 * of the connection. */
861 uint16_t marked_for_close; /**< Should we close this conn on the next
862 * iteration of the main loop? (If true, holds
863 * the line number where this connection was
864 * marked.) */
865 const char *marked_for_close_file; /**< For debugging: in which file were
866 * we marked for close? */
867 char *address; /**< FQDN (or IP) of the guy on the other end.
868 * strdup into this, because free_connection frees it. */
869 /** Another connection that's connected to this one in lieu of a socket. */
870 struct connection_t *linked_conn;
872 /* XXXX021 move this into a subtype. */
873 struct evdns_server_port *dns_server_port;
875 } connection_t;
877 /** Stores flags and information related to the portion of a v2 Tor OR
878 * connection handshake that happens after the TLS handshake is finished.
880 typedef struct or_handshake_state_t {
881 /** When was the VERSIONS cell sent on this connection? Used to get
882 * an estimate of the skew in the returning NETINFO reply. */
883 time_t sent_versions_at;
884 /** True iff we originated this connection */
885 unsigned int started_here : 1;
886 /** True iff we have received and processed a VERSIONS cell. */
887 unsigned int received_versions : 1;
888 } or_handshake_state_t;
890 /** Subtype of connection_t for an "OR connection" -- that is, one that speaks
891 * cells over TLS. */
892 typedef struct or_connection_t {
893 connection_t _base;
895 /** Hash of the public RSA key for the other side's identity key, or zeroes
896 * if the other side hasn't shown us a valid identity key. */
897 char identity_digest[DIGEST_LEN];
898 char *nickname; /**< Nickname of OR on other side (if any). */
900 tor_tls_t *tls; /**< TLS connection state. */
901 int tls_error; /**< Last tor_tls error code. */
902 /** When we last used this conn for any client traffic. If not
903 * recent, we can rate limit it further. */
904 time_t client_used;
906 uint32_t real_addr; /**< The actual address that this connection came from
907 * or went to. The <b>addr</b> field is prone to
908 * getting overridden by the address from the router
909 * descriptor matching <b>identity_digest</b>. */
911 circ_id_type_t circ_id_type:2; /**< When we send CREATE cells along this
912 * connection, which half of the space should
913 * we use? */
914 /** Should this connection be used for extending circuits to the server
915 * matching the <b>identity_digest</b> field? Set to true if we're pretty
916 * sure we aren't getting MITMed, either because we're connected to an
917 * address listed in a server descriptor, or because an authenticated
918 * NETINFO cell listed the address we're connected to as recognized. */
919 unsigned int is_canonical:1;
920 uint8_t link_proto; /**< What protocol version are we using? 0 for
921 * "none negotiated yet." */
922 uint16_t next_circ_id; /**< Which circ_id do we try to use next on
923 * this connection? This is always in the
924 * range 0..1<<15-1. */
926 or_handshake_state_t *handshake_state; /**< If we are setting this connection
927 * up, state information to do so. */
928 time_t timestamp_lastempty; /**< When was the outbuf last completely empty?*/
929 time_t timestamp_last_added_nonpadding; /** When did we last add a
930 * non-padding cell to the outbuf? */
932 /* bandwidth* and read_bucket only used by ORs in OPEN state: */
933 int bandwidthrate; /**< Bytes/s added to the bucket. (OPEN ORs only.) */
934 int bandwidthburst; /**< Max bucket size for this conn. (OPEN ORs only.) */
935 int read_bucket; /**< When this hits 0, stop receiving. Every second we
936 * add 'bandwidthrate' to this, capping it at
937 * bandwidthburst. (OPEN ORs only) */
938 int n_circuits; /**< How many circuits use this connection as p_conn or
939 * n_conn ? */
941 /** Double-linked ring of circuits with queued cells waiting for room to
942 * free up on this connection's outbuf. Every time we pull cells from a
943 * circuit, we advance this pointer to the next circuit in the ring. */
944 struct circuit_t *active_circuits;
945 struct or_connection_t *next_with_same_id; /**< Next connection with same
946 * identity digest as this one. */
947 } or_connection_t;
949 /** Subtype of connection_t for an "edge connection" -- that is, a socks (ap)
950 * connection, or an exit. */
951 typedef struct edge_connection_t {
952 connection_t _base;
954 struct edge_connection_t *next_stream; /**< Points to the next stream at this
955 * edge, if any */
956 struct crypt_path_t *cpath_layer; /**< A pointer to which node in the circ
957 * this conn exits at. */
958 int package_window; /**< How many more relay cells can I send into the
959 * circuit? */
960 int deliver_window; /**< How many more relay cells can end at me? */
962 /** Nickname of planned exit node -- used with .exit support. */
963 char *chosen_exit_name;
965 socks_request_t *socks_request; /**< SOCKS structure describing request (AP
966 * only.) */
967 struct circuit_t *on_circuit; /**< The circuit (if any) that this edge
968 * connection is using. */
970 uint32_t address_ttl; /**< TTL for address-to-addr mapping on exit
971 * connection. Exit connections only. */
973 uint16_t stream_id; /**< The stream ID used for this edge connection on its
974 * circuit */
976 /** The reason why this connection is closing; passed to the controller. */
977 uint16_t end_reason;
979 /** Quasi-global identifier for this connection; used for control.c */
980 /* XXXX NM This can get re-used after 2**32 streams */
981 uint32_t global_identifier;
983 /** Bytes read since last call to control_event_stream_bandwidth_used() */
984 uint32_t n_read;
986 /** Bytes written since last call to control_event_stream_bandwidth_used() */
987 uint32_t n_written;
989 /** What rendezvous service are we querying for? (AP only) */
990 char rend_query[REND_SERVICE_ID_LEN_BASE32+1];
992 /** Number of times we've reassigned this application connection to
993 * a new circuit. We keep track because the timeout is longer if we've
994 * already retried several times. */
995 uint8_t num_socks_retries;
997 /** True iff this connection is for a dns request only. */
998 unsigned int is_dns_request : 1;
1000 /** True iff this stream must attach to a one-hop circuit (e.g. for
1001 * begin_dir). */
1002 int want_onehop:1;
1003 /** True iff this stream should use a BEGIN_DIR relay command to establish
1004 * itself rather than BEGIN (either via onehop or via a whole circuit). */
1005 int use_begindir:1;
1007 /** If this is a DNSPort connection, this field holds the pending DNS
1008 * request that we're going to try to answer. */
1009 struct evdns_server_request *dns_server_request;
1011 } edge_connection_t;
1013 /** Subtype of connection_t for an "directory connection" -- that is, an HTTP
1014 * connection to retrieve or serve directory material. */
1015 typedef struct dir_connection_t {
1016 connection_t _base;
1018 char *requested_resource; /**< Which 'resource' did we ask the directory
1019 * for? */
1020 unsigned int dirconn_direct:1; /**< Is this dirconn direct, or via Tor? */
1022 /* Used only for server sides of some dir connections, to implement
1023 * "spooling" of directory material to the outbuf. Otherwise, we'd have
1024 * to append everything to the outbuf in one enormous chunk. */
1025 /** What exactly are we spooling right now? */
1026 enum {
1027 DIR_SPOOL_NONE=0, DIR_SPOOL_SERVER_BY_DIGEST, DIR_SPOOL_SERVER_BY_FP,
1028 DIR_SPOOL_EXTRA_BY_DIGEST, DIR_SPOOL_EXTRA_BY_FP,
1029 DIR_SPOOL_CACHED_DIR, DIR_SPOOL_NETWORKSTATUS
1030 } dir_spool_src : 3;
1031 /** If we're fetching descriptors, what router purpose shall we assign
1032 * to them? */
1033 uint8_t router_purpose;
1034 /** List of fingerprints for networkstatuses or desriptors to be spooled. */
1035 smartlist_t *fingerprint_stack;
1036 /** A cached_dir_t object that we're currently spooling out */
1037 struct cached_dir_t *cached_dir;
1038 /** The current offset into cached_dir. */
1039 off_t cached_dir_offset;
1040 /** The zlib object doing on-the-fly compression for spooled data. */
1041 tor_zlib_state_t *zlib_state;
1043 /** What hidden service descriptor are we fetching, if any? */
1044 int rend_version;
1046 /** What rendezvous service are we querying for? */
1047 char rend_query[REND_SERVICE_ID_LEN_BASE32+1];
1049 char identity_digest[DIGEST_LEN]; /**< Hash of the public RSA key for
1050 * the directory server's signing key. */
1052 } dir_connection_t;
1054 /** Subtype of connection_t for an connection to a controller. */
1055 typedef struct control_connection_t {
1056 connection_t _base;
1058 uint32_t event_mask; /**< Bitfield: which events does this controller
1059 * care about? */
1060 unsigned int use_long_names:1; /**< True if we should use long nicknames
1061 * on this (v1) connection. Only settable
1062 * via v1 controllers. */
1063 /** For control connections only. If set, we send extended info with control
1064 * events as appropriate. */
1065 unsigned int use_extended_events:1;
1067 /** True if we have sent a protocolinfo reply on this connection. */
1068 unsigned int have_sent_protocolinfo:1;
1070 uint32_t incoming_cmd_len;
1071 uint32_t incoming_cmd_cur_len;
1072 char *incoming_cmd;
1073 /* Used only by control v0 connections */
1074 uint16_t incoming_cmd_type;
1075 } control_connection_t;
1077 /** Cast a connection_t subtype pointer to a connection_t **/
1078 #define TO_CONN(c) (&(((c)->_base)))
1079 /** Helper macro: Given a pointer to to._base, of type from*, return &to. */
1080 #define DOWNCAST(to, ptr) ((to*)SUBTYPE_P(ptr, to, _base))
1082 /** Convert a connection_t* to an or_connection_t*; assert if the cast is
1083 * invalid. */
1084 static or_connection_t *TO_OR_CONN(connection_t *);
1085 /** Convert a connection_t* to a dir_connection_t*; assert if the cast is
1086 * invalid. */
1087 static dir_connection_t *TO_DIR_CONN(connection_t *);
1088 /** Convert a connection_t* to an edge_connection_t*; assert if the cast is
1089 * invalid. */
1090 static edge_connection_t *TO_EDGE_CONN(connection_t *);
1091 /** Convert a connection_t* to an control_connection_t*; assert if the cast is
1092 * invalid. */
1093 static control_connection_t *TO_CONTROL_CONN(connection_t *);
1095 static INLINE or_connection_t *TO_OR_CONN(connection_t *c)
1097 tor_assert(c->magic == OR_CONNECTION_MAGIC);
1098 return DOWNCAST(or_connection_t, c);
1100 static INLINE dir_connection_t *TO_DIR_CONN(connection_t *c)
1102 tor_assert(c->magic == DIR_CONNECTION_MAGIC);
1103 return DOWNCAST(dir_connection_t, c);
1105 static INLINE edge_connection_t *TO_EDGE_CONN(connection_t *c)
1107 tor_assert(c->magic == EDGE_CONNECTION_MAGIC);
1108 return DOWNCAST(edge_connection_t, c);
1110 static INLINE control_connection_t *TO_CONTROL_CONN(connection_t *c)
1112 tor_assert(c->magic == CONTROL_CONNECTION_MAGIC);
1113 return DOWNCAST(control_connection_t, c);
1116 typedef enum {
1117 ADDR_POLICY_ACCEPT=1,
1118 ADDR_POLICY_REJECT=2,
1119 } addr_policy_action_t;
1121 /** A linked list of policy rules */
1122 typedef struct addr_policy_t {
1123 int refcnt; /**< Reference count */
1124 addr_policy_action_t policy_type:2;/**< What to do when the policy matches.*/
1125 unsigned int is_private:1; /**< True iff this is the pseudo-address,
1126 * "private". */
1127 unsigned int is_canonical:1; /**< True iff this policy is the canonical
1128 * copy (stored in a hash table to avoid
1129 * duplication of common policies) */
1130 maskbits_t maskbits; /**< Accept/reject all addresses <b>a</b> such that the
1131 * first <b>maskbits</b> bits of <b>a</b> match
1132 * <b>addr</b>. */
1133 /* XXXX_IP6 make this ipv6-capable */
1134 uint32_t addr; /**< Base address to accept or reject. */
1135 uint16_t prt_min; /**< Lowest port number to accept/reject. */
1136 uint16_t prt_max; /**< Highest port number to accept/reject. */
1137 } addr_policy_t;
1139 /** A cached_dir_t represents a cacheable directory object, along with its
1140 * compressed form. */
1141 typedef struct cached_dir_t {
1142 char *dir; /**< Contents of this object */
1143 char *dir_z; /**< Compressed contents of this object. */
1144 size_t dir_len; /**< Length of <b>dir</b> */
1145 size_t dir_z_len; /**< Length of <b>dir_z</b> */
1146 time_t published; /**< When was this object published */
1147 int refcnt; /**< Reference count for this cached_dir_t. */
1148 } cached_dir_t;
1150 /** Enum used to remember where a signed_descriptor_t is stored and how to
1151 * manage the memory for signed_descriptor_body. */
1152 typedef enum {
1153 /** The descriptor isn't stored on disk at all: the copy in memory is
1154 * canonical; the saved_offset field is meaningless. */
1155 SAVED_NOWHERE=0,
1156 /** The descriptor is stored in the cached_routers file: the
1157 * signed_descriptor_body is meaningless; the signed_descriptor_len and
1158 * saved_offset are used to index into the mmaped cache file. */
1159 SAVED_IN_CACHE,
1160 /** The descriptor is stored in the cached_routers.new file: the
1161 * signed_descriptor_body and saved_offset fields are both set. */
1162 /* FFFF (We could also mmap the file and grow the mmap as needed, or
1163 * lazy-load the descriptor text by using seek and read. We don't, for
1164 * now.)
1166 SAVED_IN_JOURNAL
1167 } saved_location_t;
1169 /** Enumeration: what kind of downlaod schedule are we using for a given
1170 * object? */
1171 typedef enum {
1172 DL_SCHED_GENERIC = 0,
1173 DL_SCHED_CONSENSUS = 1,
1174 } download_schedule_t;
1176 /** Information about our plans for retrying downloads for a downloadable
1177 * object. */
1178 typedef struct download_status_t {
1179 time_t next_attempt_at; /**< When should we try downloading this descriptor
1180 * again? */
1181 uint8_t n_download_failures; /**< Number of failures trying to download the
1182 * most recent descriptor. */
1183 download_schedule_t schedule : 8;
1184 } download_status_t;
1186 /** The max size we expect router descriptor annotations we create to
1187 * be. We'll accept larger ones if we see them on disk, but we won't
1188 * create any that are larger than this. */
1189 #define ROUTER_ANNOTATION_BUF_LEN 256
1191 /** Information need to cache an onion router's descriptor. */
1192 typedef struct signed_descriptor_t {
1193 /** Pointer to the raw server descriptor, preceded by annotations. Not
1194 * necessarily NUL-terminated. If saved_location is SAVED_IN_CACHE, this
1195 * pointer is null. */
1196 char *signed_descriptor_body;
1197 /** Length of the annotations preceeding the server descriptor. */
1198 size_t annotations_len;
1199 /** Length of the server descriptor. */
1200 size_t signed_descriptor_len;
1201 /** Digest of the server descriptor, computed as specified in
1202 * dir-spec.txt. */
1203 char signed_descriptor_digest[DIGEST_LEN];
1204 /** Identity digest of the router. */
1205 char identity_digest[DIGEST_LEN];
1206 /** Declared publication time of the descriptor. */
1207 time_t published_on;
1208 /** For routerdescs only: digest of the corresponding extrainfo. */
1209 char extra_info_digest[DIGEST_LEN];
1210 /** For routerdescs only: Status of downloading the corresponding
1211 * extrainfo. */
1212 download_status_t ei_dl_status;
1213 /** Where is the descriptor saved? */
1214 saved_location_t saved_location;
1215 /** If saved_location is SAVED_IN_CACHE or SAVED_IN_JOURNAL, the offset of
1216 * this descriptor in the corresponding file. */
1217 off_t saved_offset;
1218 /** What position is this descriptor within routerlist->routers or
1219 * routerlist->old_routers? -1 for none. */
1220 int routerlist_index;
1221 /** The valid-until time of the most recent consensus that listed this
1222 * descriptor. 0 for "never listed in a consensus, so far as we know." */
1223 time_t last_listed_as_valid_until;
1224 /* If true, we do not ever try to save this object in the cache. */
1225 unsigned int do_not_cache : 1;
1226 /* If true, this item is meant to represent an extrainfo. */
1227 unsigned int is_extrainfo : 1;
1228 /* If true, we got an extrainfo for this item, and the digest was right,
1229 * but it was incompatible. */
1230 unsigned int extrainfo_is_bogus : 1;
1231 /* If true, we are willing to transmit this item unencrypted. */
1232 unsigned int send_unencrypted : 1;
1233 } signed_descriptor_t;
1235 /** Information about another onion router in the network. */
1236 typedef struct {
1237 signed_descriptor_t cache_info;
1238 char *address; /**< Location of OR: either a hostname or an IP address. */
1239 char *nickname; /**< Human-readable OR name. */
1241 uint32_t addr; /**< IPv4 address of OR, in host order. */
1242 uint16_t or_port; /**< Port for TLS connections. */
1243 uint16_t dir_port; /**< Port for HTTP directory connections. */
1245 crypto_pk_env_t *onion_pkey; /**< Public RSA key for onions. */
1246 crypto_pk_env_t *identity_pkey; /**< Public RSA key for signing. */
1248 char *platform; /**< What software/operating system is this OR using? */
1250 /* link info */
1251 uint32_t bandwidthrate; /**< How many bytes does this OR add to its token
1252 * bucket per second? */
1253 uint32_t bandwidthburst; /**< How large is this OR's token bucket? */
1254 /** How many bytes/s is this router known to handle? */
1255 uint32_t bandwidthcapacity;
1256 smartlist_t *exit_policy; /**< What streams will this OR permit
1257 * to exit? NULL for 'reject *:*'. */
1258 long uptime; /**< How many seconds the router claims to have been up */
1259 smartlist_t *declared_family; /**< Nicknames of router which this router
1260 * claims are its family. */
1261 char *contact_info; /**< Declared contact info for this router. */
1262 unsigned int is_hibernating:1; /**< Whether the router claims to be
1263 * hibernating */
1264 unsigned int has_old_dnsworkers:1; /**< Whether the router is using
1265 * dnsworker code. */
1266 unsigned int caches_extra_info:1; /**< Whether the router caches and serves
1267 * extrainfo documents. */
1269 /* local info */
1270 unsigned int is_running:1; /**< As far as we know, is this OR currently
1271 * running? */
1272 unsigned int is_valid:1; /**< Has a trusted dirserver validated this OR?
1273 * (For Authdir: Have we validated this OR?)
1275 unsigned int is_named:1; /**< Do we believe the nickname that this OR gives
1276 * us? */
1277 unsigned int is_fast:1; /** Do we think this is a fast OR? */
1278 unsigned int is_stable:1; /** Do we think this is a stable OR? */
1279 unsigned int is_possible_guard:1; /**< Do we think this is an OK guard? */
1280 unsigned int is_exit:1; /**< Do we think this is an OK exit? */
1281 unsigned int is_bad_exit:1; /**< Do we think this exit is censored, borked,
1282 * or otherwise nasty? */
1283 unsigned int is_bad_directory:1; /**< Do we think this directory is junky,
1284 * underpowered, or otherwise useless? */
1285 unsigned int wants_to_be_hs_dir:1; /**< True iff this router claims to be
1286 * a hidden service directory. */
1287 unsigned int is_hs_dir:1; /**< True iff this router is a hidden service
1288 * directory according to the authorities. */
1290 /** Tor can use this router for general positions in circuits. */
1291 #define ROUTER_PURPOSE_GENERAL 0
1292 /** Tor should avoid using this router for circuit-building. */
1293 #define ROUTER_PURPOSE_CONTROLLER 1
1294 /** Tor should use this router only for bridge positions in circuits. */
1295 #define ROUTER_PURPOSE_BRIDGE 2
1296 /** Tor should not use this router; it was marked in cached-descriptors with
1297 * a purpose we didn't recognize. */
1298 #define ROUTER_PURPOSE_UNKNOWN 255
1300 uint8_t purpose; /** What positions in a circuit is this router good for? */
1302 /* The below items are used only by authdirservers for
1303 * reachability testing. */
1304 /** When was the last time we could reach this OR? */
1305 time_t last_reachable;
1306 /** When did we start testing reachability for this OR? */
1307 time_t testing_since;
1309 } routerinfo_t;
1311 /** Information needed to keep and cache a signed extra-info document. */
1312 typedef struct extrainfo_t {
1313 signed_descriptor_t cache_info;
1314 /** The router's nickname. */
1315 char nickname[MAX_NICKNAME_LEN+1];
1316 /** True iff we found the right key for this extra-info, verified the
1317 * signature, and found it to be bad. */
1318 unsigned int bad_sig : 1;
1319 /** If present, we didn't have the right key to verify this extra-info,
1320 * so this is a copy of the signature in the document. */
1321 char *pending_sig;
1322 /** Length of pending_sig. */
1323 size_t pending_sig_len;
1324 } extrainfo_t;
1326 /** Contents of a single router entry in a network status object.
1328 typedef struct routerstatus_t {
1329 time_t published_on; /**< When was this router published? */
1330 char nickname[MAX_NICKNAME_LEN+1]; /**< The nickname this router says it
1331 * has. */
1332 char identity_digest[DIGEST_LEN]; /**< Digest of the router's identity
1333 * key. */
1334 char descriptor_digest[DIGEST_LEN]; /**< Digest of the router's most recent
1335 * descriptor. */
1336 uint32_t addr; /**< IPv4 address for this router. */
1337 uint16_t or_port; /**< OR port for this router. */
1338 uint16_t dir_port; /**< Directory port for this router. */
1339 unsigned int is_authority:1; /**< True iff this router is an authority. */
1340 unsigned int is_exit:1; /**< True iff this router is a good exit. */
1341 unsigned int is_stable:1; /**< True iff this router stays up a long time. */
1342 unsigned int is_fast:1; /**< True iff this router has good bandwidth. */
1343 unsigned int is_running:1; /**< True iff this router is up. */
1344 unsigned int is_named:1; /**< True iff "nickname" belongs to this router. */
1345 unsigned int is_unnamed:1; /**< True iff "nickname" belongs to another
1346 * router. */
1347 unsigned int is_valid:1; /**< True iff this router isn't invalid. */
1348 unsigned int is_v2_dir:1; /**< True iff this router can serve directory
1349 * information with v2 of the directory
1350 * protocol. (All directory caches cache v1
1351 * directories.) */
1352 unsigned int is_possible_guard:1; /**< True iff this router would be a good
1353 * choice as an entry guard. */
1354 unsigned int is_bad_exit:1; /**< True iff this node is a bad choice for
1355 * an exit node. */
1356 unsigned int is_bad_directory:1; /**< Do we think this directory is junky,
1357 * underpowered, or otherwise useless? */
1358 unsigned int is_hs_dir:1; /** True iff this router is a v2-or-later hidden
1359 * service directory. */
1360 /** True iff we know version info for this router. (i.e., a "v" entry was
1361 * included.) We'll replace all these with a big tor_version_t or a char[]
1362 * if the number of traits we care about ever becomes incredibly big. */
1363 unsigned int version_known:1;
1364 /** True iff this router is a version that supports BEGIN_DIR cells. */
1365 unsigned int version_supports_begindir:1;
1366 /** True iff this router is a version that we can post extrainfo docs to. */
1367 unsigned int version_supports_extrainfo_upload:1;
1368 /** True iff this router is a version that, if it caches directory info,
1369 * we can get v3 downloads from. */
1370 unsigned int version_supports_v3_dir:1;
1372 /* ---- The fields below aren't derived from the networkstatus; they
1373 * hold local information only. */
1375 /** True if we, as a directory mirror, want to download the corresponding
1376 * routerinfo from the authority who gave us this routerstatus. (That is,
1377 * if we don't have the routerinfo, and if we haven't already tried to get it
1378 * from this authority.) Applies in v2 networkstatus document only.
1380 unsigned int need_to_mirror:1;
1381 unsigned int name_lookup_warned:1; /**< Have we warned the user for referring
1382 * to this (unnamed) router by nickname?
1384 time_t last_dir_503_at; /**< When did this router last tell us that it
1385 * was too busy to serve directory info? */
1386 download_status_t dl_status;
1388 } routerstatus_t;
1390 /** How many times will we try to download a router's descriptor before giving
1391 * up? */
1392 #define MAX_ROUTERDESC_DOWNLOAD_FAILURES 8
1394 /** Contents of a v2 (non-consensus, non-vote) network status object. */
1395 typedef struct networkstatus_v2_t {
1396 /** When did we receive the network-status document? */
1397 time_t received_on;
1399 /** What was the digest of the document? */
1400 char networkstatus_digest[DIGEST_LEN];
1402 unsigned int is_recent; /**< Is this recent enough to influence running
1403 * status? */
1405 /* These fields come from the actual network-status document.*/
1406 time_t published_on; /**< Declared publication date. */
1408 char *source_address; /**< Canonical directory server hostname. */
1409 uint32_t source_addr; /**< Canonical directory server IP. */
1410 uint16_t source_dirport; /**< Canonical directory server dirport. */
1412 unsigned int binds_names:1; /**< True iff this directory server binds
1413 * names. */
1414 unsigned int recommends_versions:1; /**< True iff this directory server
1415 * recommends client and server software
1416 * versions. */
1417 unsigned int lists_bad_exits:1; /**< True iff this directory server marks
1418 * malfunctioning exits as bad. */
1419 /** True iff this directory server marks malfunctioning directories as
1420 * bad. */
1421 unsigned int lists_bad_directories:1;
1423 char identity_digest[DIGEST_LEN]; /**< Digest of signing key. */
1424 char *contact; /**< How to contact directory admin? (may be NULL). */
1425 crypto_pk_env_t *signing_key; /**< Key used to sign this directory. */
1426 char *client_versions; /**< comma-separated list of recommended client
1427 * versions. */
1428 char *server_versions; /**< comma-separated list of recommended server
1429 * versions. */
1431 smartlist_t *entries; /**< List of routerstatus_t*. This list is kept
1432 * sorted by identity_digest. */
1433 } networkstatus_v2_t;
1435 /** The claim about a single router, make in a vote. */
1436 typedef struct vote_routerstatus_t {
1437 routerstatus_t status; /**< Underlying 'status' object for this router.
1438 * Flags are redundant. */
1439 uint64_t flags; /**< Bit-field for all recognized flags; index into
1440 * networkstatus_t.known_flags. */
1441 char *version; /**< The version that the authority says this router is
1442 * running. */
1443 } vote_routerstatus_t;
1445 /** Information about a single voter in a vote or a consensus. */
1446 typedef struct networkstatus_voter_info_t {
1447 char *nickname; /**< Nickname of this voter */
1448 char identity_digest[DIGEST_LEN]; /**< Digest of this voter's identity key */
1449 char *address; /**< Address of this voter, in string format. */
1450 uint32_t addr; /**< Address of this voter, in IPv4, in host order. */
1451 uint16_t dir_port; /**< Directory port of this voter */
1452 uint16_t or_port; /**< OR port of this voter */
1453 char *contact; /**< Contact information for this voter. */
1454 char vote_digest[DIGEST_LEN]; /**< Digest of this voter's vote, as signed. */
1456 /* Nothing from here on is signed. */
1457 char signing_key_digest[DIGEST_LEN]; /**< Declared digest of signing key
1458 * used by this voter. */
1459 char *signature; /**< Signature from this voter. */
1460 int signature_len; /**< Length of <b>signature</b> */
1461 unsigned int bad_signature : 1; /**< Set to true if we've verified the sig
1462 * as good. */
1463 unsigned int good_signature : 1; /**< Set to true if we've tried to verify
1464 * the sig, and we know it's bad. */
1465 } networkstatus_voter_info_t;
1467 /** A common structure to hold a v3 network status vote, or a v3 network
1468 * status consensus. */
1469 typedef struct networkstatus_t {
1470 int is_vote; /**< True if this is a vote; false if it is a consensus. */
1471 time_t published; /**< Vote only: Tiem when vote was written. */
1472 time_t valid_after; /**< Time after which this vote or consensus applies. */
1473 time_t fresh_until; /**< Time before which this is the most recent vote or
1474 * consensus. */
1475 time_t valid_until; /**< Time after which this vote or consensus should not
1476 * be used. */
1478 /** Consensus only: what method was used to produce this consensus? */
1479 int consensus_method;
1480 /** Vote only: what methods is this voter willing to use? */
1481 smartlist_t *supported_methods;
1483 /** How long does this vote/consensus claim that authorities take to
1484 * distribute their votes to one another? */
1485 int vote_seconds;
1486 /** How long does this vote/consensus claim that authorites take to
1487 * distribute their consensus signatures to one another? */
1488 int dist_seconds;
1490 /** Comma-separated list of recommended client software, or NULL if this
1491 * voter has no opinion. */
1492 char *client_versions;
1493 char *server_versions;
1494 /** List of flags that this vote/consensus applies to routers. If a flag is
1495 * not listed here, the voter has no opinion on what its value should be. */
1496 smartlist_t *known_flags;
1498 /** List of networkstatus_voter_info_t. For a vote, only one element
1499 * is included. For a consensus, one element is included for every voter
1500 * whose vote contributed to the consensus. */
1501 smartlist_t *voters;
1503 struct authority_cert_t *cert; /**< Vote only: the voter's certificate. */
1505 /** Digest of this document, as signed. */
1506 char networkstatus_digest[DIGEST_LEN];
1508 /** List of router statuses, sorted by identity digest. For a vote,
1509 * the elements are vote_routerstatus_t; for a consensus, the elements
1510 * are routerstatus_t. */
1511 smartlist_t *routerstatus_list;
1513 /** If present, a map from descriptor digest to elements of
1514 * routerstatus_list. */
1515 digestmap_t *desc_digest_map;
1516 } networkstatus_t;
1518 /** A set of signatures for a networkstatus consensus. All fields are as for
1519 * networkstatus_t. */
1520 typedef struct ns_detached_signatures_t {
1521 time_t valid_after;
1522 time_t fresh_until;
1523 time_t valid_until;
1524 char networkstatus_digest[DIGEST_LEN];
1525 smartlist_t *signatures; /* list of networkstatus_voter_info_t */
1526 } ns_detached_signatures_t;
1528 /** Allowable types of desc_store_t. */
1529 typedef enum store_type_t {
1530 ROUTER_STORE = 0,
1531 EXTRAINFO_STORE = 1
1532 } store_type_t;
1534 /** A 'store' is a set of descriptors saved on disk, with accompanying
1535 * journal, mmaped as needed, rebuilt as needed. */
1536 typedef struct desc_store_t {
1537 /** Filename (within DataDir) for the store. We append .tmp to this
1538 * filename for a temporary file when rebuilding the store, and .new to this
1539 * filename for the journal. */
1540 const char *fname_base;
1541 /** Alternative (obsolete) value for fname_base: if the file named by
1542 * fname_base isn't present, we read from here instead, but we never write
1543 * here. */
1544 const char *fname_alt_base;
1545 /** Human-readable description of what this store contains. */
1546 const char *description;
1548 tor_mmap_t *mmap; /**< A mmap for the main file in the store. */
1550 store_type_t type; /**< What's stored in this store? */
1552 /** The size of the router log, in bytes. */
1553 size_t journal_len;
1554 /** The size of the router store, in bytes. */
1555 size_t store_len;
1556 /** Total bytes dropped since last rebuild: this is space currently
1557 * used in the cache and the journal that could be freed by a rebuild. */
1558 size_t bytes_dropped;
1559 } desc_store_t;
1561 /** Contents of a directory of onion routers. */
1562 typedef struct {
1563 /** Map from server identity digest to a member of routers. */
1564 struct digest_ri_map_t *identity_map;
1565 /** Map from server descriptor digest to a signed_descriptor_t from
1566 * routers or old_routers. */
1567 struct digest_sd_map_t *desc_digest_map;
1568 /** Map from extra-info digest to an extrainfo_t. Only exists for
1569 * routers in routers or old_routers. */
1570 struct digest_ei_map_t *extra_info_map;
1571 /** Map from extra-info digests to a signed_descriptor_t for a router
1572 * descriptor having that extra-info digest. Only exists for
1573 * routers in routers or old_routers. */
1574 struct digest_sd_map_t *desc_by_eid_map;
1575 /** List of routerinfo_t for all currently live routers we know. */
1576 smartlist_t *routers;
1577 /** List of signed_descriptor_t for older router descriptors we're
1578 * caching. */
1579 smartlist_t *old_routers;
1580 /** Store holding server descriptors. If present, any router whose
1581 * cache_info.saved_location == SAVED_IN_CACHE is stored in this file
1582 * starting at cache_info.saved_offset */
1583 desc_store_t desc_store;
1584 /** Store holding extra-info documents. */
1585 desc_store_t extrainfo_store;
1586 } routerlist_t;
1588 /** Information on router used when extending a circuit. We don't need a
1589 * full routerinfo_t to extend: we only need addr:port:keyid to build an OR
1590 * connection, and onion_key to create the onionskin. Note that for onehop
1591 * general-purpose tunnels, the onion_key is NULL. */
1592 typedef struct extend_info_t {
1593 char nickname[MAX_HEX_NICKNAME_LEN+1]; /**< This router's nickname for
1594 * display. */
1595 char identity_digest[DIGEST_LEN]; /**< Hash of this router's identity key. */
1596 uint16_t port; /**< OR port. */
1597 uint32_t addr; /**< IP address in host order. */
1598 crypto_pk_env_t *onion_key; /**< Current onionskin key. */
1599 } extend_info_t;
1601 /** Certificate for v3 directory protocol: binds long-term authority identity
1602 * keys to medium-term authority signing keys. */
1603 typedef struct authority_cert_t {
1604 signed_descriptor_t cache_info;
1605 crypto_pk_env_t *identity_key;
1606 crypto_pk_env_t *signing_key;
1607 char signing_key_digest[DIGEST_LEN];
1608 time_t expires;
1609 uint32_t addr;
1610 uint16_t dir_port;
1611 } authority_cert_t;
1613 /** Bitfield enum type listing types of directory authority/directory
1614 * server. */
1615 typedef enum {
1616 NO_AUTHORITY = 0,
1617 V1_AUTHORITY = 1 << 0,
1618 V2_AUTHORITY = 1 << 1,
1619 V3_AUTHORITY = 1 << 2,
1620 HIDSERV_AUTHORITY = 1 << 3,
1621 BRIDGE_AUTHORITY = 1 << 4,
1622 EXTRAINFO_CACHE = 1 << 5, /* not precisely an authority type. */
1623 } authority_type_t;
1625 #define CRYPT_PATH_MAGIC 0x70127012u
1627 /** Holds accounting information for a single step in the layered encryption
1628 * performed by a circuit. Used only at the client edge of a circuit. */
1629 typedef struct crypt_path_t {
1630 uint32_t magic;
1632 /* crypto environments */
1633 /** Encryption key and counter for cells heading towards the OR at this
1634 * step. */
1635 crypto_cipher_env_t *f_crypto;
1636 /** Encryption key and counter for cells heading back from the OR at this
1637 * step. */
1638 crypto_cipher_env_t *b_crypto;
1640 /** Digest state for cells heading towards the OR at this step. */
1641 crypto_digest_env_t *f_digest; /* for integrity checking */
1642 /** Digest state for cells heading away from the OR at this step. */
1643 crypto_digest_env_t *b_digest;
1645 /** Current state of Diffie-Hellman key negotiation with the OR at this
1646 * step. */
1647 crypto_dh_env_t *dh_handshake_state;
1648 /** Current state of 'fast' (non-PK) key negotiation with the OR at this
1649 * step. Used to save CPU when TLS is already providing all the
1650 * authentication, secrecy, and integrity we need, and we're already
1651 * distinguishable from an OR.
1653 char fast_handshake_state[DIGEST_LEN];
1654 /** Negotiated key material shared with the OR at this step. */
1655 char handshake_digest[DIGEST_LEN];/* KH in tor-spec.txt */
1657 /** Information to extend to the OR at this step. */
1658 extend_info_t *extend_info;
1660 /** Is the circuit built to this step? Must be one of:
1661 * - CPATH_STATE_CLOSED (The circuit has not been extended to this step)
1662 * - CPATH_STATE_AWAITING_KEYS (We have sent an EXTEND/CREATE to this step
1663 * and not received an EXTENDED/CREATED)
1664 * - CPATH_STATE_OPEN (The circuit has been extended to this step) */
1665 uint8_t state;
1666 #define CPATH_STATE_CLOSED 0
1667 #define CPATH_STATE_AWAITING_KEYS 1
1668 #define CPATH_STATE_OPEN 2
1669 struct crypt_path_t *next; /**< Link to next crypt_path_t in the circuit.
1670 * (The list is circular, so the last node
1671 * links to the first.) */
1672 struct crypt_path_t *prev; /**< Link to previous crypt_path_t in the
1673 * circuit. */
1675 int package_window; /**< How many bytes are we allowed to originate ending
1676 * at this step? */
1677 int deliver_window; /**< How many bytes are we willing to deliver originating
1678 * at this step? */
1679 } crypt_path_t;
1681 #define CPATH_KEY_MATERIAL_LEN (20*2+16*2)
1683 #define DH_KEY_LEN DH_BYTES
1684 #define ONIONSKIN_CHALLENGE_LEN (PKCS1_OAEP_PADDING_OVERHEAD+\
1685 CIPHER_KEY_LEN+\
1686 DH_KEY_LEN)
1687 #define ONIONSKIN_REPLY_LEN (DH_KEY_LEN+DIGEST_LEN)
1688 #define REND_COOKIE_LEN DIGEST_LEN
1690 /** Information used to build a circuit. */
1691 typedef struct {
1692 /** Intended length of the final circuit. */
1693 int desired_path_len;
1694 /** How to extend to the planned exit node. */
1695 extend_info_t *chosen_exit;
1696 /** Whether every node in the circ must have adequate uptime. */
1697 int need_uptime;
1698 /** Whether every node in the circ must have adequate capacity. */
1699 int need_capacity;
1700 /** Whether the last hop was picked with exiting in mind. */
1701 int is_internal;
1702 /** Did we pick this as a one-hop tunnel (not safe for other conns)?
1703 * These are for encrypted connections that exit to this router, not
1704 * for arbitrary exits from the circuit. */
1705 int onehop_tunnel;
1706 /** The crypt_path_t to append after rendezvous: used for rendezvous. */
1707 crypt_path_t *pending_final_cpath;
1708 /** How many times has building a circuit for this task failed? */
1709 int failure_count;
1710 /** At what time should we give up on this task? */
1711 time_t expiry_time;
1712 } cpath_build_state_t;
1714 #define ORIGIN_CIRCUIT_MAGIC 0x35315243u
1715 #define OR_CIRCUIT_MAGIC 0x98ABC04Fu
1717 typedef uint16_t circid_t;
1720 * A circuit is a path over the onion routing
1721 * network. Applications can connect to one end of the circuit, and can
1722 * create exit connections at the other end of the circuit. AP and exit
1723 * connections have only one circuit associated with them (and thus these
1724 * connection types are closed when the circuit is closed), whereas
1725 * OR connections multiplex many circuits at once, and stay standing even
1726 * when there are no circuits running over them.
1728 * A circuit_t structure can fill one of two roles. First, a or_circuit_t
1729 * links two connections together: either an edge connection and an OR
1730 * connection, or two OR connections. (When joined to an OR connection, a
1731 * circuit_t affects only cells sent to a particular circID on that
1732 * connection. When joined to an edge connection, a circuit_t affects all
1733 * data.)
1735 * Second, an origin_circuit_t holds the cipher keys and state for sending data
1736 * along a given circuit. At the OP, it has a sequence of ciphers, each
1737 * of which is shared with a single OR along the circuit. Separate
1738 * ciphers are used for data going "forward" (away from the OP) and
1739 * "backward" (towards the OP). At the OR, a circuit has only two stream
1740 * ciphers: one for data going forward, and one for data going backward.
1742 typedef struct circuit_t {
1743 uint32_t magic; /**< For memory and type debugging: must equal
1744 * ORIGIN_CIRCUIT_MAGIC or OR_CIRCUIT_MAGIC. */
1746 /** Queue of cells waiting to be transmitted on n_conn. */
1747 cell_queue_t n_conn_cells;
1748 /** The OR connection that is next in this circuit. */
1749 or_connection_t *n_conn;
1750 /** The identity hash of n_conn. */
1751 char n_conn_id_digest[DIGEST_LEN];
1752 /** The circuit_id used in the next (forward) hop of this circuit. */
1753 uint16_t n_circ_id;
1754 /** The port for the OR that is next in this circuit. */
1755 uint16_t n_port;
1756 /** The IPv4 address of the OR that is next in this circuit. */
1757 uint32_t n_addr;
1759 /** True iff we are waiting for n_conn_cells to become less full before
1760 * allowing p_streams to add any more cells. (Origin circuit only.) */
1761 unsigned int streams_blocked_on_n_conn : 1;
1762 /** True iff we are waiting for p_conn_cells to become less full before
1763 * allowing n_streams to add any more cells. (OR circuit only.) */
1764 unsigned int streams_blocked_on_p_conn : 1;
1766 uint8_t state; /**< Current status of this circuit. */
1767 uint8_t purpose; /**< Why are we creating this circuit? */
1769 /** How many relay data cells can we package (read from edge streams)
1770 * on this circuit before we receive a circuit-level sendme cell asking
1771 * for more? */
1772 int package_window;
1773 /** How many relay data cells will we deliver (write to edge streams)
1774 * on this circuit? When deliver_window gets low, we send some
1775 * circuit-level sendme cells to indicate that we're willing to accept
1776 * more. */
1777 int deliver_window;
1779 /** For storage while n_conn is pending
1780 * (state CIRCUIT_STATE_OR_WAIT). When defined, it is always
1781 * length ONIONSKIN_CHALLENGE_LEN. */
1782 char *n_conn_onionskin;
1784 time_t timestamp_created; /**< When was this circuit created? */
1785 time_t timestamp_dirty; /**< When the circuit was first used, or 0 if the
1786 * circuit is clean. */
1788 uint16_t marked_for_close; /**< Should we close this circuit at the end of
1789 * the main loop? (If true, holds the line number
1790 * where this circuit was marked.) */
1791 const char *marked_for_close_file; /**< For debugging: in which file was this
1792 * circuit marked for close? */
1794 /** Next circuit in the doubly-linked ring of circuits waiting to add
1795 * cells to n_conn. NULL if we have no cells pending, or if we're not
1796 * linked to an OR connection. */
1797 struct circuit_t *next_active_on_n_conn;
1798 /** Previous circuit in the doubly-linked ring of circuits waiting to add
1799 * cells to n_conn. NULL if we have no cells pending, or if we're not
1800 * linked to an OR connection. */
1801 struct circuit_t *prev_active_on_n_conn;
1802 struct circuit_t *next; /**< Next circuit in linked list of all circuits. */
1803 } circuit_t;
1805 /** An origin_circuit_t holds data necessary to build and use a circuit.
1807 typedef struct origin_circuit_t {
1808 circuit_t _base;
1810 /** Linked list of AP streams (or EXIT streams if hidden service)
1811 * associated with this circuit. */
1812 edge_connection_t *p_streams;
1813 /** Build state for this circuit. It includes the intended path
1814 * length, the chosen exit router, rendezvous information, etc.
1816 cpath_build_state_t *build_state;
1817 /** The doubly-linked list of crypt_path_t entries, one per hop,
1818 * for this circuit. This includes ciphers for each hop,
1819 * integrity-checking digests for each hop, and package/delivery
1820 * windows for each hop.
1822 crypt_path_t *cpath;
1824 /** The rend_pk_digest field holds a hash of location-hidden service's
1825 * PK if purpose is S_ESTABLISH_INTRO or S_RENDEZVOUSING.
1827 char rend_pk_digest[DIGEST_LEN];
1829 /** Holds rendezvous cookie if purpose is C_ESTABLISH_REND. Filled with
1830 * zeroes otherwise.
1832 char rend_cookie[REND_COOKIE_LEN];
1835 * The rend_query field holds the y portion of y.onion (nul-terminated)
1836 * if purpose is C_INTRODUCING or C_ESTABLISH_REND, or is a C_GENERAL
1837 * for a hidden service, or is S_*.
1839 char rend_query[REND_SERVICE_ID_LEN_BASE32+1];
1841 /** Stores the rendezvous descriptor version if purpose is S_*. Used to
1842 * distinguish introduction and rendezvous points belonging to the same
1843 * rendezvous service ID, but different descriptor versions.
1845 uint8_t rend_desc_version;
1847 /* The intro key replaces the hidden service's public key if purpose is
1848 * S_ESTABLISH_INTRO or S_INTRO, provided that no unversioned rendezvous
1849 * descriptor is used. */
1850 crypto_pk_env_t *intro_key;
1852 /** The next stream_id that will be tried when we're attempting to
1853 * construct a new AP stream originating at this circuit. */
1854 uint16_t next_stream_id;
1856 /** Quasi-global identifier for this circuit; used for control.c */
1857 /* XXXX NM This can get re-used after 2**32 circuits. */
1858 uint32_t global_identifier;
1860 } origin_circuit_t;
1862 /** An or_circuit_t holds information needed to implement a circuit at an
1863 * OR. */
1864 typedef struct or_circuit_t {
1865 circuit_t _base;
1867 /** Next circuit in the doubly-linked ring of circuits waiting to add
1868 * cells to p_conn. NULL if we have no cells pending, or if we're not
1869 * linked to an OR connection. */
1870 struct circuit_t *next_active_on_p_conn;
1871 /** Previous circuit in the doubly-linked ring of circuits waiting to add
1872 * cells to p_conn. NULL if we have no cells pending, or if we're not
1873 * linked to an OR connection. */
1874 struct circuit_t *prev_active_on_p_conn;
1876 /** The circuit_id used in the previous (backward) hop of this circuit. */
1877 circid_t p_circ_id;
1878 /** Queue of cells waiting to be transmitted on p_conn. */
1879 cell_queue_t p_conn_cells;
1880 /** The OR connection that is previous in this circuit. */
1881 or_connection_t *p_conn;
1882 /** Linked list of Exit streams associated with this circuit. */
1883 edge_connection_t *n_streams;
1884 /** Linked list of Exit streams associated with this circuit that are
1885 * still being resolved. */
1886 edge_connection_t *resolving_streams;
1887 /** The cipher used by intermediate hops for cells heading toward the
1888 * OP. */
1889 crypto_cipher_env_t *p_crypto;
1890 /** The cipher used by intermediate hops for cells heading away from
1891 * the OP. */
1892 crypto_cipher_env_t *n_crypto;
1894 /** The integrity-checking digest used by intermediate hops, for
1895 * cells packaged here and heading towards the OP.
1897 crypto_digest_env_t *p_digest;
1898 /** The integrity-checking digest used by intermediate hops, for
1899 * cells packaged at the OP and arriving here.
1901 crypto_digest_env_t *n_digest;
1903 /** Points to spliced circuit if purpose is REND_ESTABLISHED, and circuit
1904 * is not marked for close. */
1905 struct or_circuit_t *rend_splice;
1907 #if REND_COOKIE_LEN >= DIGEST_LEN
1908 #define REND_TOKEN_LEN REND_COOKIE_LEN
1909 #else
1910 #define REND_TOKEN_LEN DIGEST_LEN
1911 #endif
1913 /** A hash of location-hidden service's PK if purpose is INTRO_POINT, or a
1914 * rendezvous cookie if purpose is REND_POINT_WAITING. Filled with zeroes
1915 * otherwise.
1916 * ???? move to a subtype or adjunct structure? Wastes 20 bytes. -NM
1918 char rend_token[REND_TOKEN_LEN];
1920 /* ???? move to a subtype or adjunct structure? Wastes 20 bytes -NM */
1921 char handshake_digest[DIGEST_LEN]; /**< Stores KH for the handshake. */
1923 /** True iff this circuit was made with a CREATE_FAST cell. */
1924 unsigned int is_first_hop : 1;
1925 } or_circuit_t;
1927 /** Convert a circuit subtype to a circuit_t.*/
1928 #define TO_CIRCUIT(x) (&((x)->_base))
1930 /** Convert a circuit_t* to a pointer to the enclosing or_circuit_t. Asserts
1931 * if the cast is impossible. */
1932 static or_circuit_t *TO_OR_CIRCUIT(circuit_t *);
1933 /** Convert a circuit_t* to a pointer to the enclosing origin_circuit_t.
1934 * Asserts if the cast is impossible. */
1935 static origin_circuit_t *TO_ORIGIN_CIRCUIT(circuit_t *);
1937 static INLINE or_circuit_t *TO_OR_CIRCUIT(circuit_t *x)
1939 tor_assert(x->magic == OR_CIRCUIT_MAGIC);
1940 return DOWNCAST(or_circuit_t, x);
1942 static INLINE origin_circuit_t *TO_ORIGIN_CIRCUIT(circuit_t *x)
1944 tor_assert(x->magic == ORIGIN_CIRCUIT_MAGIC);
1945 return DOWNCAST(origin_circuit_t, x);
1948 #define ALLOW_INVALID_ENTRY 1
1949 #define ALLOW_INVALID_EXIT 2
1950 #define ALLOW_INVALID_MIDDLE 4
1951 #define ALLOW_INVALID_RENDEZVOUS 8
1952 #define ALLOW_INVALID_INTRODUCTION 16
1954 /** An entry specifying a set of addresses and ports that should be remapped
1955 * to another address and port before exiting this exit node. */
1956 typedef struct exit_redirect_t {
1957 /* XXXX_IP6 make this whole mess ipv6-capable. (Does anybody use it? */
1959 uint32_t addr;
1960 uint16_t port_min;
1961 uint16_t port_max;
1962 maskbits_t maskbits;
1964 uint32_t addr_dest;
1965 uint16_t port_dest;
1966 unsigned int is_redirect:1;
1967 } exit_redirect_t;
1969 /* limits for TCP send and recv buffer size used for constrained sockets */
1970 #define MIN_CONSTRAINED_TCP_BUFFER 2048
1971 #define MAX_CONSTRAINED_TCP_BUFFER 262144 /* 256k */
1973 /** A linked list of lines in a config file. */
1974 typedef struct config_line_t {
1975 char *key;
1976 char *value;
1977 struct config_line_t *next;
1978 } config_line_t;
1980 /** Configuration options for a Tor process. */
1981 typedef struct {
1982 uint32_t _magic;
1984 /** What should the tor process actually do? */
1985 enum {
1986 CMD_RUN_TOR=0, CMD_LIST_FINGERPRINT, CMD_HASH_PASSWORD,
1987 CMD_VERIFY_CONFIG, CMD_RUN_UNITTESTS
1988 } command;
1989 const char *command_arg; /**< Argument for command-line option. */
1991 config_line_t *Logs; /**< New-style list of configuration lines
1992 * for logs */
1994 char *DebugLogFile; /**< Where to send verbose log messages. */
1995 char *DataDirectory; /**< OR only: where to store long-term data. */
1996 char *Nickname; /**< OR only: nickname of this onion router. */
1997 char *Address; /**< OR only: configured address for this onion router. */
1998 char *PidFile; /**< Where to store PID of Tor process. */
2000 char *ExitNodes; /**< Comma-separated list of nicknames of ORs to consider
2001 * as exits. */
2002 char *EntryNodes; /**< Comma-separated list of nicknames of ORs to consider
2003 * as entry points. */
2004 int StrictExitNodes; /**< Boolean: When none of our ExitNodes are up, do we
2005 * stop building circuits? */
2006 int StrictEntryNodes; /**< Boolean: When none of our EntryNodes are up, do we
2007 * stop building circuits? */
2008 char *ExcludeNodes; /**< Comma-separated list of nicknames of ORs not to
2009 * use in circuits. */
2011 char *RendNodes; /**< Comma-separated list of nicknames used as introduction
2012 * points. */
2013 char *RendExcludeNodes; /**< Comma-separated list of nicknames not to use
2014 * as introduction points. */
2016 /** List of "entry", "middle", "exit", "introduction", "rendezvous". */
2017 smartlist_t *AllowInvalidNodes;
2018 int _AllowInvalid; /**< Bitmask; derived from AllowInvalidNodes. */
2019 config_line_t *ExitPolicy; /**< Lists of exit policy components. */
2020 int ExitPolicyRejectPrivate; /**< Should we not exit to local addresses? */
2021 config_line_t *SocksPolicy; /**< Lists of socks policy components */
2022 config_line_t *DirPolicy; /**< Lists of dir policy components */
2023 /** Addresses to bind for listening for SOCKS connections. */
2024 config_line_t *SocksListenAddress;
2025 /** Addresses to bind for listening for transparent pf/nefilter
2026 * connections. */
2027 config_line_t *TransListenAddress;
2028 /** Addresses to bind for listening for transparent natd connections */
2029 config_line_t *NatdListenAddress;
2030 /** Addresses to bind for listening for SOCKS connections. */
2031 config_line_t *DNSListenAddress;
2032 /** Addresses to bind for listening for OR connections. */
2033 config_line_t *ORListenAddress;
2034 /** Addresses to bind for listening for directory connections. */
2035 config_line_t *DirListenAddress;
2036 /** Addresses to bind for listening for control connections. */
2037 config_line_t *ControlListenAddress;
2038 /** Local address to bind outbound sockets */
2039 char *OutboundBindAddress;
2040 /** Directory server only: which versions of
2041 * Tor should we tell users to run? */
2042 config_line_t *RecommendedVersions;
2043 config_line_t *RecommendedClientVersions;
2044 config_line_t *RecommendedServerVersions;
2045 /** Whether dirservers refuse router descriptors with private IPs. */
2046 int DirAllowPrivateAddresses;
2047 char *User; /**< Name of user to run Tor as. */
2048 char *Group; /**< Name of group to run Tor as. */
2049 int ORPort; /**< Port to listen on for OR connections. */
2050 int SocksPort; /**< Port to listen on for SOCKS connections. */
2051 /** Port to listen on for transparent pf/netfilter connections. */
2052 int TransPort;
2053 int NatdPort; /**< Port to listen on for transparent natd connections. */
2054 int ControlPort; /**< Port to listen on for control connections. */
2055 config_line_t *ControlSocket; /**< List of Unix Domain Sockets to listen on
2056 * for control connections. */
2057 int DirPort; /**< Port to listen on for directory connections. */
2058 int DNSPort; /**< Port to listen on for DNS requests. */
2059 int AssumeReachable; /**< Whether to publish our descriptor regardless. */
2060 int AuthoritativeDir; /**< Boolean: is this an authoritative directory? */
2061 int V1AuthoritativeDir; /**< Boolean: is this an authoritative directory
2062 * for version 1 directories? */
2063 int V2AuthoritativeDir; /**< Boolean: is this an authoritative directory
2064 * for version 2 directories? */
2065 int V3AuthoritativeDir; /**< Boolean: is this an authoritative directory
2066 * for version 3 directories? */
2067 int HSAuthoritativeDir; /**< Boolean: does this an authoritative directory
2068 * handle hidden service requests? */
2069 int HSAuthorityRecordStats; /**< Boolean: does this HS authoritative
2070 * directory record statistics? */
2071 int NamingAuthoritativeDir; /**< Boolean: is this an authoritative directory
2072 * that's willing to bind names? */
2073 int VersioningAuthoritativeDir; /**< Boolean: is this an authoritative
2074 * directory that's willing to recommend
2075 * versions? */
2076 int BridgeAuthoritativeDir; /**< Boolean: is this an authoritative directory
2077 * that aggregates bridge descriptors? */
2079 /** If set on a bridge authority, it will answer requests on its dirport
2080 * for bridge statuses -- but only if the requests use this password.
2081 * If set on a bridge user, request bridge statuses, and use this password
2082 * when doing so. */
2083 char *BridgePassword;
2085 int UseBridges; /**< Boolean: should we start all circuits with a bridge? */
2086 config_line_t *Bridges; /**< List of bootstrap bridge addresses. */
2088 int BridgeRelay; /**< Boolean: are we acting as a bridge relay? We make
2089 * this explicit so we can change how we behave in the
2090 * future. */
2092 /** Boolean: if we know the bridge's digest, should we get new
2093 * descriptors from the bridge authorities or from the bridge itself? */
2094 int UpdateBridgesFromAuthority;
2096 int AvoidDiskWrites; /**< Boolean: should we never cache things to disk?
2097 * Not used yet. */
2098 int ClientOnly; /**< Boolean: should we never evolve into a server role? */
2099 /** Boolean: should we never publish a descriptor? Deprecated. */
2100 int NoPublish;
2101 /** To what authority types do we publish our descriptor? Choices are
2102 * "v1", "v2", "v3", "bridge", or "". */
2103 smartlist_t *PublishServerDescriptor;
2104 /** An authority type, derived from PublishServerDescriptor. */
2105 authority_type_t _PublishServerDescriptor;
2106 /** Boolean: do we publish hidden service descriptors to the HS auths? */
2107 int PublishHidServDescriptors;
2108 int FetchServerDescriptors; /**< Do we fetch server descriptors as normal? */
2109 int FetchHidServDescriptors; /** and hidden service descriptors? */
2110 int HidServDirectoryV2; /**< Do we participate in the HS DHT? */
2112 int MinUptimeHidServDirectoryV2; /**< As directory authority, accept hidden
2113 * service directories after what time? */
2114 int FetchUselessDescriptors; /**< Do we fetch non-running descriptors too? */
2115 int AllDirActionsPrivate; /**< Should every directory action be sent
2116 * through a Tor circuit? */
2118 int ConnLimit; /**< Demanded minimum number of simultaneous connections. */
2119 int _ConnLimit; /**< Maximum allowed number of simultaneous connections. */
2120 int RunAsDaemon; /**< If true, run in the background. (Unix only) */
2121 int FascistFirewall; /**< Whether to prefer ORs reachable on open ports. */
2122 smartlist_t *FirewallPorts; /**< Which ports our firewall allows
2123 * (strings). */
2124 config_line_t *ReachableAddresses; /**< IP:ports our firewall allows. */
2125 config_line_t *ReachableORAddresses; /**< IP:ports for OR conns. */
2126 config_line_t *ReachableDirAddresses; /**< IP:ports for Dir conns. */
2128 int ConstrainedSockets; /**< Shrink xmit and recv socket buffers. */
2129 uint64_t ConstrainedSockSize; /**< Size of constrained buffers. */
2131 /** Application ports that require all nodes in circ to have sufficient
2132 * uptime. */
2133 smartlist_t *LongLivedPorts;
2134 /** Application ports that are likely to be unencrypted and
2135 * unauthenticated; we reject requests for them to prevent the
2136 * user from screwing up and leaking plaintext secrets to an
2137 * observer somewhere on the Internet. */
2138 smartlist_t *RejectPlaintextPorts;
2139 /** Related to RejectPlaintextPorts above, except this config option
2140 * controls whether we warn (in the log and via a controller status
2141 * event) every time a risky connection is attempted. */
2142 smartlist_t *WarnPlaintextPorts;
2143 /** Should we try to reuse the same exit node for a given host */
2144 smartlist_t *TrackHostExits;
2145 int TrackHostExitsExpire; /**< Number of seconds until we expire an
2146 * addressmap */
2147 config_line_t *AddressMap; /**< List of address map directives. */
2148 int AutomapHostsOnResolve; /**< If true, when we get a resolve request for a
2149 * hostname ending with one of the suffixes in
2150 * <b>AutomapHostsSuffixes</b>, map it to a
2151 * virtual address. */
2152 smartlist_t *AutomapHostsSuffixes; /**< List of suffixes for
2153 * <b>AutomapHostsOnResolve</b>. */
2154 int RendPostPeriod; /**< How often do we post each rendezvous service
2155 * descriptor? Remember to publish them independently. */
2156 int KeepalivePeriod; /**< How often do we send padding cells to keep
2157 * connections alive? */
2158 int SocksTimeout; /**< How long do we let a socks connection wait
2159 * unattached before we fail it? */
2160 int CircuitBuildTimeout; /**< Cull non-open circuits that were born
2161 * at least this many seconds ago. */
2162 int CircuitIdleTimeout; /**< Cull open clean circuits that were born
2163 * at least this many seconds ago. */
2164 int MaxOnionsPending; /**< How many circuit CREATE requests do we allow
2165 * to wait simultaneously before we start dropping
2166 * them? */
2167 int NewCircuitPeriod; /**< How long do we use a circuit before building
2168 * a new one? */
2169 int MaxCircuitDirtiness; /**< Never use circs that were first used more than
2170 this interval ago. */
2171 uint64_t BandwidthRate; /**< How much bandwidth, on average, are we willing
2172 * to use in a second? */
2173 uint64_t BandwidthBurst; /**< How much bandwidth, at maximum, are we willing
2174 * to use in a second? */
2175 uint64_t MaxAdvertisedBandwidth; /**< How much bandwidth are we willing to
2176 * tell people we have? */
2177 uint64_t RelayBandwidthRate; /**< How much bandwidth, on average, are we
2178 * willing to use for all relayed conns? */
2179 uint64_t RelayBandwidthBurst; /**< How much bandwidth, at maximum, will we
2180 * use in a second for all relayed conns? */
2181 int NumCpus; /**< How many CPUs should we try to use? */
2182 int RunTesting; /**< If true, create testing circuits to measure how well the
2183 * other ORs are running. */
2184 char *TestVia; /**< When reachability testing, use these as middle hop. */
2185 config_line_t *RendConfigLines; /**< List of configuration lines
2186 * for rendezvous services. */
2187 char *ContactInfo; /**< Contact info to be published in the directory. */
2189 char *HttpProxy; /**< hostname[:port] to use as http proxy, if any. */
2190 uint32_t HttpProxyAddr; /**< Parsed IPv4 addr for http proxy, if any. */
2191 uint16_t HttpProxyPort; /**< Parsed port for http proxy, if any. */
2192 char *HttpProxyAuthenticator; /**< username:password string, if any. */
2194 char *HttpsProxy; /**< hostname[:port] to use as https proxy, if any. */
2195 uint32_t HttpsProxyAddr; /**< Parsed IPv4 addr for https proxy, if any. */
2196 uint16_t HttpsProxyPort; /**< Parsed port for https proxy, if any. */
2197 char *HttpsProxyAuthenticator; /**< username:password string, if any. */
2199 /** List of configuration lines for replacement directory authorities.
2200 * If you just want to replace one class of authority at a time,
2201 * use the "Alternate*Authority" options below instead. */
2202 config_line_t *DirServers;
2204 /** If set, use these main (currently v3) directory authorities and
2205 * not the default ones. */
2206 config_line_t *AlternateDirAuthority;
2208 /** If set, use these bridge authorities and not the default one. */
2209 config_line_t *AlternateBridgeAuthority;
2211 /** If set, use these HS authorities and not the default ones. */
2212 config_line_t *AlternateHSAuthority;
2214 char *MyFamily; /**< Declared family for this OR. */
2215 config_line_t *NodeFamilies; /**< List of config lines for
2216 * node families */
2217 config_line_t *RedirectExit; /**< List of config lines for simple
2218 * addr/port redirection */
2219 smartlist_t *RedirectExitList; /**< List of exit_redirect_t */
2220 config_line_t *AuthDirBadDir; /**< Address policy for descriptors to
2221 * mark as bad dir mirrors. */
2222 config_line_t *AuthDirBadExit; /**< Address policy for descriptors to
2223 * mark as bad exits. */
2224 config_line_t *AuthDirReject; /**< Address policy for descriptors to
2225 * reject. */
2226 config_line_t *AuthDirInvalid; /**< Address policy for descriptors to
2227 * never mark as valid. */
2228 int AuthDirListBadDirs; /**< True iff we should list bad dirs,
2229 * and vote for all other dir mirrors as good. */
2230 int AuthDirListBadExits; /**< True iff we should list bad exits,
2231 * and vote for all other exits as good. */
2232 int AuthDirRejectUnlisted; /**< Boolean: do we reject all routers that
2233 * aren't named in our fingerprint file? */
2234 int AuthDirMaxServersPerAddr; /**< Do not permit more than this
2235 * number of servers per IP address. */
2236 int AuthDirMaxServersPerAuthAddr; /**< Do not permit more than this
2237 * number of servers per IP address shared
2238 * with an authority. */
2240 char *AccountingStart; /**< How long is the accounting interval, and when
2241 * does it start? */
2242 uint64_t AccountingMax; /**< How many bytes do we allow per accounting
2243 * interval before hibernation? 0 for "never
2244 * hibernate." */
2246 /** Base64-encoded hash of accepted passwords for the control system. */
2247 config_line_t *HashedControlPassword;
2248 /** As HashedControlPassword, but not saved. */
2249 config_line_t *HashedControlSessionPassword;
2251 int CookieAuthentication; /**< Boolean: do we enable cookie-based auth for
2252 * the control system? */
2253 char *CookieAuthFile; /**< Location of a cookie authentication file. */
2254 int CookieAuthFileGroupReadable; /**< Boolean: Is the CookieAuthFile g+r? */
2255 int LeaveStreamsUnattached; /**< Boolean: Does Tor attach new streams to
2256 * circuits itself (0), or does it expect a controller
2257 * to cope? (1) */
2258 int DisablePredictedCircuits; /**< Boolean: does Tor preemptively
2259 * make circuits in the background (0),
2260 * or not (1)? */
2261 int ShutdownWaitLength; /**< When we get a SIGINT and we're a server, how
2262 * long do we wait before exiting? */
2263 int SafeLogging; /**< Boolean: are we allowed to log sensitive strings
2264 * such as addresses (0), or do we scrub them first (1)? */
2265 int SafeSocks; /**< Boolean: should we outright refuse application
2266 * connections that use socks4 or socks5-with-local-dns? */
2267 #define LOG_PROTOCOL_WARN (get_options()->ProtocolWarnings ? \
2268 LOG_WARN : LOG_INFO)
2269 int ProtocolWarnings; /**< Boolean: when other parties screw up the Tor
2270 * protocol, is it a warn or an info in our logs? */
2271 int TestSocks; /**< Boolean: when we get a socks connection, do we loudly
2272 * log whether it was DNS-leaking or not? */
2273 int HardwareAccel; /**< Boolean: Should we enable OpenSSL hardware
2274 * acceleration where available? */
2275 int UseEntryGuards; /**< Boolean: Do we try to enter from a smallish number
2276 * of fixed nodes? */
2277 int NumEntryGuards; /**< How many entry guards do we try to establish? */
2278 int RephistTrackTime; /**< How many seconds do we keep rephist info? */
2279 int FastFirstHopPK; /**< If Tor believes it is safe, should we save a third
2280 * of our PK time by sending CREATE_FAST cells? */
2281 /** Should we always fetch our dir info on the mirror schedule (which
2282 * means directly from the authorities) no matter our other config? */
2283 int FetchDirInfoEarly;
2285 smartlist_t *reachable_addr_policy; /**< Parsed from ReachableAddresses */
2287 char *VirtualAddrNetwork; /**< Address and mask to hand out for virtual
2288 * MAPADDRESS requests. */
2289 int ServerDNSSearchDomains; /**< Boolean: If set, we don't force exit
2290 * addresses to be FQDNs, but rather search for them in
2291 * the local domains. */
2292 int ServerDNSDetectHijacking; /**< Boolean: If true, check for DNS failure
2293 * hijacking. */
2294 char *ServerDNSResolvConfFile; /**< If provided, we configure our internal
2295 * resolver from the file here rather than from
2296 * /etc/resolv.conf (Unix) or the registry (Windows). */
2297 /** Boolean: if set, we start even if our resolv.conf file is missing
2298 * or broken. */
2299 int ServerDNSAllowBrokenResolvConf;
2301 smartlist_t *ServerDNSTestAddresses; /**< A list of addresses that definitely
2302 * should be resolveable. Used for
2303 * testing our DNS server. */
2304 int EnforceDistinctSubnets; /**< If true, don't allow multiple routers in the
2305 * same network zone in the same circuit. */
2306 int TunnelDirConns; /**< If true, use BEGIN_DIR rather than BEGIN when
2307 * possible. */
2308 int PreferTunneledDirConns; /**< If true, avoid dirservers that don't
2309 * support BEGIN_DIR, when possible. */
2310 int AllowNonRFC953Hostnames; /**< If true, we allow connections to hostnames
2311 * with weird characters. */
2312 /** If true, we try resolving hostnames with weird characters. */
2313 int ServerDNSAllowNonRFC953Hostnames;
2315 /** If true, we try to download extra-info documents (and we serve them,
2316 * if we are a cache). For authorities, this is always true. */
2317 int DownloadExtraInfo;
2319 /** If true, do not believe anybody who tells us that a domain resolves
2320 * to an internal address, or that an internal address has a PTR mapping.
2321 * Helps avoid some cross-site attacks. */
2322 int ClientDNSRejectInternalAddresses;
2324 /** The length of time that we think a consensus should be fresh. */
2325 int V3AuthVotingInterval;
2326 /** The length of time we think it will take to distribute votes. */
2327 int V3AuthVoteDelay;
2328 /** The length of time we think it will take to distribute signatures. */
2329 int V3AuthDistDelay;
2330 /** The number of intervals we think a consensus should be valid. */
2331 int V3AuthNIntervalsValid;
2333 /** File to check for a consensus networkstatus, if we don't have one
2334 * cached. */
2335 char *FallbackNetworkstatusFile;
2337 /** If true, and we have GeoIP data, and we're a bridge, keep a per-country
2338 * count of how many client addresses have contacted us so that we can help
2339 * the bridge authority guess which countries have blocked access to us. */
2340 int BridgeRecordUsageByCountry;
2341 /** Optionally, a file with GeoIP data. */
2342 char *GeoIPFile;
2344 } or_options_t;
2346 /** Persistent state for an onion router, as saved to disk. */
2347 typedef struct {
2348 uint32_t _magic;
2349 /** The time at which we next plan to write the state to the disk. Equal to
2350 * TIME_MAX if there are no saveable changes, 0 if there are changes that
2351 * should be saved right away. */
2352 time_t next_write;
2354 /** When was the state last written to disk? */
2355 time_t LastWritten;
2357 /** Fields for accounting bandwidth use. */
2358 time_t AccountingIntervalStart;
2359 uint64_t AccountingBytesReadInInterval;
2360 uint64_t AccountingBytesWrittenInInterval;
2361 int AccountingSecondsActive;
2362 uint64_t AccountingExpectedUsage;
2364 /** A list of Entry Guard-related configuration lines. */
2365 config_line_t *EntryGuards;
2367 /** These fields hold information on the history of bandwidth usage for
2368 * servers. The "Ends" fields hold the time when we last updated the
2369 * bandwidth usage. The "Interval" fields hold the granularity, in seconds,
2370 * of the entries of Values. The "Values" lists hold decimal string
2371 * representations of the number of bytes read or written in each
2372 * interval. */
2373 time_t BWHistoryReadEnds;
2374 int BWHistoryReadInterval;
2375 smartlist_t *BWHistoryReadValues;
2376 time_t BWHistoryWriteEnds;
2377 int BWHistoryWriteInterval;
2378 smartlist_t *BWHistoryWriteValues;
2380 /** What version of Tor wrote this state file? */
2381 char *TorVersion;
2383 /** Holds any unrecognized values we found in the state file, in the order
2384 * in which we found them. */
2385 config_line_t *ExtraLines;
2387 /** When did we last rotate our onion key? "0" for 'no idea'. */
2388 time_t LastRotatedOnionKey;
2389 } or_state_t;
2391 /** Change the next_write time of <b>state</b> to <b>when</b>, unless the
2392 * state is already scheduled to be written to disk earlier than <b>when</b>.
2394 static INLINE void or_state_mark_dirty(or_state_t *state, time_t when)
2396 if (state->next_write > when)
2397 state->next_write = when;
2400 #define MAX_SOCKS_REPLY_LEN 1024
2401 #define MAX_SOCKS_ADDR_LEN 256
2403 /** Please open a TCP connection to this addr:port. */
2404 #define SOCKS_COMMAND_CONNECT 0x01
2405 /** Please turn this FQDN into an IP address, privately. */
2406 #define SOCKS_COMMAND_RESOLVE 0xF0
2407 /** Please turn this IP address into an FQDN, privately. */
2408 #define SOCKS_COMMAND_RESOLVE_PTR 0xF1
2410 #define SOCKS_COMMAND_IS_CONNECT(c) ((c)==SOCKS_COMMAND_CONNECT)
2411 #define SOCKS_COMMAND_IS_RESOLVE(c) ((c)==SOCKS_COMMAND_RESOLVE || \
2412 (c)==SOCKS_COMMAND_RESOLVE_PTR)
2414 /** State of a SOCKS request from a user to an OP. Also used to encode other
2415 * information for non-socks user request (such as those on TransPort and
2416 * DNSPort) */
2417 struct socks_request_t {
2418 /** Which version of SOCKS did the client use? One of "0, 4, 5" -- where
2419 * 0 means that no socks handshake ever took place, and this is just a
2420 * stub connection (e.g. see connection_ap_make_link()). */
2421 char socks_version;
2422 int command; /**< What is this stream's goal? One from the above list. */
2423 size_t replylen; /**< Length of <b>reply</b>. */
2424 char reply[MAX_SOCKS_REPLY_LEN]; /**< Write an entry into this string if
2425 * we want to specify our own socks reply,
2426 * rather than using the default socks4 or
2427 * socks5 socks reply. We use this for the
2428 * two-stage socks5 handshake.
2430 char address[MAX_SOCKS_ADDR_LEN]; /**< What address did the client ask to
2431 connect to/resolve? */
2432 uint16_t port; /**< What port did the client ask to connect to? */
2433 unsigned int has_finished : 1; /**< Has the SOCKS handshake finished? Used to
2434 * make sure we send back a socks reply for
2435 * every connection. */
2438 /* all the function prototypes go here */
2440 /********************************* buffers.c ***************************/
2442 buf_t *buf_new(void);
2443 buf_t *buf_new_with_capacity(size_t size);
2444 void buf_free(buf_t *buf);
2445 void buf_clear(buf_t *buf);
2446 void buf_shrink(buf_t *buf);
2447 void buf_shrink_freelists(int free_all);
2448 void buf_dump_freelist_sizes(int severity);
2450 size_t buf_datalen(const buf_t *buf);
2451 size_t buf_allocation(const buf_t *buf);
2452 size_t buf_slack(const buf_t *buf);
2453 const char *_buf_peek_raw_buffer(const buf_t *buf);
2455 int read_to_buf(int s, size_t at_most, buf_t *buf, int *reached_eof);
2456 int read_to_buf_tls(tor_tls_t *tls, size_t at_most, buf_t *buf);
2458 int flush_buf(int s, buf_t *buf, size_t sz, size_t *buf_flushlen);
2459 int flush_buf_tls(tor_tls_t *tls, buf_t *buf, size_t sz, size_t *buf_flushlen);
2461 int write_to_buf(const char *string, size_t string_len, buf_t *buf);
2462 int write_to_buf_zlib(buf_t *buf, tor_zlib_state_t *state,
2463 const char *data, size_t data_len, int done);
2464 int move_buf_to_buf(buf_t *buf_out, buf_t *buf_in, size_t *buf_flushlen);
2465 int fetch_from_buf(char *string, size_t string_len, buf_t *buf);
2466 int fetch_var_cell_from_buf(buf_t *buf, var_cell_t **out, int linkproto);
2467 int fetch_from_buf_http(buf_t *buf,
2468 char **headers_out, size_t max_headerlen,
2469 char **body_out, size_t *body_used, size_t max_bodylen,
2470 int force_complete);
2471 int fetch_from_buf_socks(buf_t *buf, socks_request_t *req,
2472 int log_sockstype, int safe_socks);
2473 int fetch_from_buf_line(buf_t *buf, char *data_out, size_t *data_len);
2475 int peek_buf_has_control0_command(buf_t *buf);
2477 void assert_buf_ok(buf_t *buf);
2479 #ifdef BUFFERS_PRIVATE
2480 int buf_find_string_offset(const buf_t *buf, const char *s, size_t n);
2481 #endif
2483 /********************************* circuitbuild.c **********************/
2485 char *circuit_list_path(origin_circuit_t *circ, int verbose);
2486 char *circuit_list_path_for_controller(origin_circuit_t *circ);
2487 void circuit_log_path(int severity, unsigned int domain,
2488 origin_circuit_t *circ);
2489 void circuit_rep_hist_note_result(origin_circuit_t *circ);
2490 origin_circuit_t *origin_circuit_init(uint8_t purpose, int flags);
2491 origin_circuit_t *circuit_establish_circuit(uint8_t purpose,
2492 extend_info_t *exit,
2493 int flags);
2494 int circuit_handle_first_hop(origin_circuit_t *circ);
2495 void circuit_n_conn_done(or_connection_t *or_conn, int status);
2496 int inform_testing_reachability(void);
2497 int circuit_send_next_onion_skin(origin_circuit_t *circ);
2498 void circuit_note_clock_jumped(int seconds_elapsed);
2499 int circuit_extend(cell_t *cell, circuit_t *circ);
2500 int circuit_init_cpath_crypto(crypt_path_t *cpath, const char *key_data,
2501 int reverse);
2502 int circuit_finish_handshake(origin_circuit_t *circ, uint8_t cell_type,
2503 const char *reply);
2504 int circuit_truncated(origin_circuit_t *circ, crypt_path_t *layer);
2505 int onionskin_answer(or_circuit_t *circ, uint8_t cell_type,
2506 const char *payload, const char *keys);
2507 int circuit_all_predicted_ports_handled(time_t now, int *need_uptime,
2508 int *need_capacity);
2510 int circuit_append_new_exit(origin_circuit_t *circ, extend_info_t *info);
2511 int circuit_extend_to_new_exit(origin_circuit_t *circ, extend_info_t *info);
2512 void onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop);
2513 extend_info_t *extend_info_alloc(const char *nickname, const char *digest,
2514 crypto_pk_env_t *onion_key,
2515 uint32_t addr, uint16_t port);
2516 extend_info_t *extend_info_from_router(routerinfo_t *r);
2517 extend_info_t *extend_info_dup(extend_info_t *info);
2518 void extend_info_free(extend_info_t *info);
2519 routerinfo_t *build_state_get_exit_router(cpath_build_state_t *state);
2520 const char *build_state_get_exit_nickname(cpath_build_state_t *state);
2522 void entry_guards_compute_status(void);
2523 int entry_guard_register_connect_status(const char *digest, int succeeded,
2524 time_t now);
2525 void entry_nodes_should_be_added(void);
2526 int entry_list_can_grow(or_options_t *options);
2527 routerinfo_t *choose_random_entry(cpath_build_state_t *state);
2528 int entry_guards_parse_state(or_state_t *state, int set, char **msg);
2529 void entry_guards_update_state(or_state_t *state);
2530 int getinfo_helper_entry_guards(control_connection_t *conn,
2531 const char *question, char **answer);
2533 void clear_bridge_list(void);
2534 int routerinfo_is_a_configured_bridge(routerinfo_t *ri);
2535 void bridge_add_from_config(uint32_t addr, uint16_t port, char *digest);
2536 void retry_bridge_descriptor_fetch_directly(char *digest);
2537 void fetch_bridge_descriptors(time_t now);
2538 void learned_bridge_descriptor(routerinfo_t *ri, int from_cache);
2539 int any_bridge_descriptors_known(void);
2540 int bridges_known_but_down(void);
2541 void bridges_retry_all(void);
2543 void entry_guards_free_all(void);
2545 /********************************* circuitlist.c ***********************/
2547 circuit_t * _circuit_get_global_list(void);
2548 const char *circuit_state_to_string(int state);
2549 void circuit_dump_by_conn(connection_t *conn, int severity);
2550 void circuit_set_p_circid_orconn(or_circuit_t *circ, uint16_t id,
2551 or_connection_t *conn);
2552 void circuit_set_n_circid_orconn(circuit_t *circ, uint16_t id,
2553 or_connection_t *conn);
2554 void circuit_set_state(circuit_t *circ, uint8_t state);
2555 void circuit_close_all_marked(void);
2556 origin_circuit_t *origin_circuit_new(void);
2557 or_circuit_t *or_circuit_new(uint16_t p_circ_id, or_connection_t *p_conn);
2558 circuit_t *circuit_get_by_circid_orconn(uint16_t circ_id,
2559 or_connection_t *conn);
2560 circuit_t *circuit_get_by_edge_conn(edge_connection_t *conn);
2561 void circuit_unlink_all_from_or_conn(or_connection_t *conn, int reason);
2562 origin_circuit_t *circuit_get_by_global_id(uint32_t id);
2563 origin_circuit_t *circuit_get_by_rend_query_and_purpose(const char *rend_query,
2564 uint8_t purpose);
2565 origin_circuit_t *circuit_get_next_by_pk_and_purpose(origin_circuit_t *start,
2566 const char *digest, uint8_t purpose);
2567 or_circuit_t *circuit_get_rendezvous(const char *cookie);
2568 or_circuit_t *circuit_get_intro_point(const char *digest);
2569 origin_circuit_t *circuit_find_to_cannibalize(uint8_t purpose,
2570 extend_info_t *info, int flags);
2571 void circuit_mark_all_unused_circs(void);
2572 void circuit_expire_all_dirty_circs(void);
2573 void _circuit_mark_for_close(circuit_t *circ, int reason,
2574 int line, const char *file);
2575 int circuit_get_cpath_len(origin_circuit_t *circ);
2576 crypt_path_t *circuit_get_cpath_hop(origin_circuit_t *circ, int hopnum);
2577 void circuit_get_all_pending_on_or_conn(smartlist_t *out,
2578 or_connection_t *or_conn);
2579 int circuit_count_pending_on_or_conn(or_connection_t *or_conn);
2581 #define circuit_mark_for_close(c, reason) \
2582 _circuit_mark_for_close((c), (reason), __LINE__, _SHORT_FILE_)
2584 void assert_cpath_layer_ok(const crypt_path_t *cp);
2585 void assert_circuit_ok(const circuit_t *c);
2586 void circuit_free_all(void);
2588 /********************************* circuituse.c ************************/
2590 void circuit_expire_building(time_t now);
2591 void circuit_remove_handled_ports(smartlist_t *needed_ports);
2592 int circuit_stream_is_being_handled(edge_connection_t *conn, uint16_t port,
2593 int min);
2594 void circuit_build_needed_circs(time_t now);
2595 void circuit_detach_stream(circuit_t *circ, edge_connection_t *conn);
2597 void reset_bandwidth_test(void);
2598 int circuit_enough_testing_circs(void);
2600 void circuit_has_opened(origin_circuit_t *circ);
2601 void circuit_build_failed(origin_circuit_t *circ);
2603 /** Flag to set when a circuit should have only a single hop. */
2604 #define CIRCLAUNCH_ONEHOP_TUNNEL (1<<0)
2605 /** Flag to set when a circuit needs to be built of high-uptime nodes */
2606 #define CIRCLAUNCH_NEED_UPTIME (1<<1)
2607 /** Flag to set when a circuit needs to be build of high-capcity nodes */
2608 #define CIRCLAUNCH_NEED_CAPACITY (1<<2)
2609 /** Flag to set when the last hop of a circuit doesn't need to be an
2610 * exit node. */
2611 #define CIRCLAUNCH_IS_INTERNAL (1<<3)
2612 origin_circuit_t *circuit_launch_by_nickname(uint8_t purpose,
2613 const char *exit_nickname,
2614 int flags);
2615 origin_circuit_t *circuit_launch_by_extend_info(uint8_t purpose,
2616 extend_info_t *info,
2617 int flags);
2618 origin_circuit_t *circuit_launch_by_router(uint8_t purpose,
2619 routerinfo_t *exit, int flags);
2620 void circuit_reset_failure_count(int timeout);
2621 int connection_ap_handshake_attach_chosen_circuit(edge_connection_t *conn,
2622 origin_circuit_t *circ,
2623 crypt_path_t *cpath);
2624 int connection_ap_handshake_attach_circuit(edge_connection_t *conn);
2626 /********************************* command.c ***************************/
2628 void command_process_cell(cell_t *cell, or_connection_t *conn);
2629 void command_process_var_cell(var_cell_t *cell, or_connection_t *conn);
2631 extern uint64_t stats_n_padding_cells_processed;
2632 extern uint64_t stats_n_create_cells_processed;
2633 extern uint64_t stats_n_created_cells_processed;
2634 extern uint64_t stats_n_relay_cells_processed;
2635 extern uint64_t stats_n_destroy_cells_processed;
2637 /********************************* config.c ***************************/
2639 or_options_t *get_options(void);
2640 int set_options(or_options_t *new_val, char **msg);
2641 void config_free_all(void);
2642 const char *safe_str(const char *address);
2643 const char *escaped_safe_str(const char *address);
2644 const char *get_version(void);
2646 int config_get_lines(const char *string, config_line_t **result);
2647 void config_free_lines(config_line_t *front);
2648 int options_trial_assign(config_line_t *list, int use_defaults,
2649 int clear_first, char **msg);
2650 int resolve_my_address(int warn_severity, or_options_t *options,
2651 uint32_t *addr, char **hostname_out);
2652 int is_local_IP(uint32_t ip) ATTR_PURE;
2653 void options_init(or_options_t *options);
2654 int options_init_from_torrc(int argc, char **argv);
2655 int option_is_recognized(const char *key);
2656 const char *option_get_canonical_name(const char *key);
2657 config_line_t *option_get_assignment(or_options_t *options,
2658 const char *key);
2659 int options_save_current(void);
2660 const char *get_torrc_fname(void);
2661 char *get_datadir_fname2_suffix(const char *sub1, const char *sub2,
2662 const char *suffix);
2663 /** Return a newly allocated string containing datadir/sub1. See
2664 * get_datadir_fname2_suffix. */
2665 #define get_datadir_fname(sub1) get_datadir_fname2_suffix((sub1), NULL, NULL)
2666 /** Return a newly allocated string containing datadir/sub1/sub2. See
2667 * get_datadir_fname2_suffix. */
2668 #define get_datadir_fname2(sub1,sub2) \
2669 get_datadir_fname2_suffix((sub1), (sub2), NULL)
2670 /** Return a newly allocated string containing datadir/sub1suffix. See
2671 * get_datadir_fname2_suffix. */
2672 #define get_datadir_fname_suffix(sub1, suffix) \
2673 get_datadir_fname2_suffix((sub1), NULL, (suffix))
2675 or_state_t *get_or_state(void);
2676 int or_state_save(time_t now);
2678 int getinfo_helper_config(control_connection_t *conn,
2679 const char *question, char **answer);
2681 #ifdef CONFIG_PRIVATE
2682 /* Used only by config.c and test.c */
2683 or_options_t *options_new(void);
2684 #endif
2686 /********************************* connection.c ***************************/
2688 const char *conn_type_to_string(int type);
2689 const char *conn_state_to_string(int type, int state);
2691 connection_t *connection_new(int type, int socket_family);
2692 void connection_link_connections(connection_t *conn_a, connection_t *conn_b);
2693 void connection_unregister_events(connection_t *conn);
2694 void connection_free(connection_t *conn);
2695 void connection_free_all(void);
2696 void connection_about_to_close_connection(connection_t *conn);
2697 void connection_close_immediate(connection_t *conn);
2698 void _connection_mark_for_close(connection_t *conn,int line, const char *file);
2700 #define connection_mark_for_close(c) \
2701 _connection_mark_for_close((c), __LINE__, _SHORT_FILE_)
2703 void connection_expire_held_open(void);
2705 int connection_connect(connection_t *conn, const char *address, uint32_t addr,
2706 uint16_t port);
2707 int retry_all_listeners(smartlist_t *replaced_conns,
2708 smartlist_t *new_conns);
2710 int connection_bucket_write_limit(connection_t *conn, time_t now);
2711 int global_write_bucket_low(connection_t *conn, size_t attempt, int priority);
2712 void connection_bucket_init(void);
2713 void connection_bucket_refill(int seconds_elapsed, time_t now);
2715 int connection_handle_read(connection_t *conn);
2717 int connection_fetch_from_buf(char *string, size_t len, connection_t *conn);
2719 int connection_wants_to_flush(connection_t *conn);
2720 int connection_outbuf_too_full(connection_t *conn);
2721 int connection_handle_write(connection_t *conn, int force);
2722 void _connection_write_to_buf_impl(const char *string, size_t len,
2723 connection_t *conn, int zlib);
2724 static void connection_write_to_buf(const char *string, size_t len,
2725 connection_t *conn);
2726 static void connection_write_to_buf_zlib(const char *string, size_t len,
2727 dir_connection_t *conn, int done);
2728 static INLINE void
2729 connection_write_to_buf(const char *string, size_t len, connection_t *conn)
2731 _connection_write_to_buf_impl(string, len, conn, 0);
2733 static INLINE void
2734 connection_write_to_buf_zlib(const char *string, size_t len,
2735 dir_connection_t *conn, int done)
2737 _connection_write_to_buf_impl(string, len, TO_CONN(conn), done ? -1 : 1);
2740 or_connection_t *connection_or_exact_get_by_addr_port(uint32_t addr,
2741 uint16_t port);
2742 edge_connection_t *connection_get_by_global_id(uint32_t id);
2744 connection_t *connection_get_by_type(int type);
2745 connection_t *connection_get_by_type_purpose(int type, int purpose);
2746 connection_t *connection_get_by_type_addr_port_purpose(int type, uint32_t addr,
2747 uint16_t port, int purpose);
2748 connection_t *connection_get_by_type_state(int type, int state);
2749 connection_t *connection_get_by_type_state_rendquery(int type, int state,
2750 const char *rendquery,
2751 int rendversion);
2753 #define connection_speaks_cells(conn) ((conn)->type == CONN_TYPE_OR)
2754 int connection_is_listener(connection_t *conn);
2755 int connection_state_is_open(connection_t *conn);
2756 int connection_state_is_connecting(connection_t *conn);
2758 char *alloc_http_authenticator(const char *authenticator);
2760 void assert_connection_ok(connection_t *conn, time_t now);
2761 int connection_or_nonopen_was_started_here(or_connection_t *conn);
2762 void connection_dump_buffer_mem_stats(int severity);
2763 void remove_file_if_very_old(const char *fname, time_t now);
2765 /********************************* connection_edge.c *************************/
2767 #define connection_mark_unattached_ap(conn, endreason) \
2768 _connection_mark_unattached_ap((conn), (endreason), __LINE__, _SHORT_FILE_)
2770 void _connection_mark_unattached_ap(edge_connection_t *conn, int endreason,
2771 int line, const char *file);
2772 int connection_edge_reached_eof(edge_connection_t *conn);
2773 int connection_edge_process_inbuf(edge_connection_t *conn,
2774 int package_partial);
2775 int connection_edge_destroy(uint16_t circ_id, edge_connection_t *conn);
2776 int connection_edge_end(edge_connection_t *conn, char reason);
2777 int connection_edge_end_errno(edge_connection_t *conn);
2778 int connection_edge_finished_flushing(edge_connection_t *conn);
2779 int connection_edge_finished_connecting(edge_connection_t *conn);
2781 int connection_ap_handshake_send_begin(edge_connection_t *ap_conn);
2782 int connection_ap_handshake_send_resolve(edge_connection_t *ap_conn);
2784 edge_connection_t *connection_ap_make_link(char *address, uint16_t port,
2785 const char *digest,
2786 int use_begindir, int want_onehop);
2787 void connection_ap_handshake_socks_reply(edge_connection_t *conn, char *reply,
2788 size_t replylen,
2789 int endreason);
2790 void connection_ap_handshake_socks_resolved(edge_connection_t *conn,
2791 int answer_type,
2792 size_t answer_len,
2793 const char *answer,
2794 int ttl,
2795 time_t expires);
2797 int connection_exit_begin_conn(cell_t *cell, circuit_t *circ);
2798 int connection_exit_begin_resolve(cell_t *cell, or_circuit_t *circ);
2799 void connection_exit_connect(edge_connection_t *conn);
2800 int connection_edge_is_rendezvous_stream(edge_connection_t *conn);
2801 int connection_ap_can_use_exit(edge_connection_t *conn, routerinfo_t *exit);
2802 void connection_ap_expire_beginning(void);
2803 void connection_ap_attach_pending(void);
2804 void circuit_discard_optional_exit_enclaves(extend_info_t *info);
2805 int connection_ap_detach_retriable(edge_connection_t *conn,
2806 origin_circuit_t *circ,
2807 int reason);
2808 int connection_ap_process_transparent(edge_connection_t *conn);
2810 int address_is_invalid_destination(const char *address, int client);
2812 void addressmap_init(void);
2813 void addressmap_clean(time_t now);
2814 void addressmap_clear_configured(void);
2815 void addressmap_clear_transient(void);
2816 void addressmap_free_all(void);
2817 int addressmap_rewrite(char *address, size_t maxlen, time_t *expires_out);
2818 int addressmap_have_mapping(const char *address);
2819 typedef enum {
2820 ADDRMAPSRC_CONTROLLER, ADDRMAPSRC_TORRC, ADDRMAPSRC_TRACKEXIT,
2821 ADDRMAPSRC_DNS,
2822 } addressmap_entry_source_t;
2823 void addressmap_register(const char *address, char *new_address,
2824 time_t expires, addressmap_entry_source_t source);
2825 int parse_virtual_addr_network(const char *val, int validate_only,
2826 char **msg);
2827 int client_dns_incr_failures(const char *address);
2828 void client_dns_clear_failures(const char *address);
2829 void client_dns_set_addressmap(const char *address, uint32_t val,
2830 const char *exitname, int ttl);
2831 const char *addressmap_register_virtual_address(int type, char *new_address);
2832 void addressmap_get_mappings(smartlist_t *sl, time_t min_expires,
2833 time_t max_expires, int want_expiry);
2834 int connection_ap_handshake_rewrite_and_attach(edge_connection_t *conn,
2835 origin_circuit_t *circ,
2836 crypt_path_t *cpath);
2837 int hostname_is_noconnect_address(const char *address);
2839 void set_exit_redirects(smartlist_t *lst);
2840 typedef enum hostname_type_t {
2841 NORMAL_HOSTNAME, ONION_HOSTNAME, EXIT_HOSTNAME, BAD_HOSTNAME
2842 } hostname_type_t;
2843 hostname_type_t parse_extended_hostname(char *address);
2845 /********************************* connection_or.c ***************************/
2847 void connection_or_remove_from_identity_map(or_connection_t *conn);
2848 void connection_or_clear_identity_map(void);
2849 or_connection_t *connection_or_get_by_identity_digest(const char *digest);
2851 int connection_or_reached_eof(or_connection_t *conn);
2852 int connection_or_process_inbuf(or_connection_t *conn);
2853 int connection_or_flushed_some(or_connection_t *conn);
2854 int connection_or_finished_flushing(or_connection_t *conn);
2855 int connection_or_finished_connecting(or_connection_t *conn);
2857 or_connection_t *connection_or_connect(uint32_t addr, uint16_t port,
2858 const char *id_digest);
2860 int connection_tls_start_handshake(or_connection_t *conn, int receiving);
2861 int connection_tls_continue_handshake(or_connection_t *conn);
2863 void or_handshake_state_free(or_handshake_state_t *state);
2864 int connection_or_set_state_open(or_connection_t *conn);
2865 void connection_or_write_cell_to_buf(const cell_t *cell,
2866 or_connection_t *conn);
2867 void connection_or_write_var_cell_to_buf(const var_cell_t *cell,
2868 or_connection_t *conn);
2869 int connection_or_send_destroy(uint16_t circ_id, or_connection_t *conn,
2870 int reason);
2871 int connection_or_send_netinfo(or_connection_t *conn);
2872 int connection_or_send_cert(or_connection_t *conn);
2873 int connection_or_send_link_auth(or_connection_t *conn);
2874 int connection_or_compute_link_auth_hmac(or_connection_t *conn,
2875 char *hmac_out);
2876 int is_or_protocol_version_known(uint16_t version);
2878 void cell_pack(packed_cell_t *dest, const cell_t *src);
2879 void var_cell_pack_header(const var_cell_t *cell, char *hdr_out);
2880 var_cell_t *var_cell_new(uint16_t payload_len);
2881 void var_cell_free(var_cell_t *cell);
2883 /********************************* control.c ***************************/
2885 typedef enum circuit_status_event_t {
2886 CIRC_EVENT_LAUNCHED = 0,
2887 CIRC_EVENT_BUILT = 1,
2888 CIRC_EVENT_EXTENDED = 2,
2889 CIRC_EVENT_FAILED = 3,
2890 CIRC_EVENT_CLOSED = 4,
2891 } circuit_status_event_t;
2893 typedef enum stream_status_event_t {
2894 STREAM_EVENT_SENT_CONNECT = 0,
2895 STREAM_EVENT_SENT_RESOLVE = 1,
2896 STREAM_EVENT_SUCCEEDED = 2,
2897 STREAM_EVENT_FAILED = 3,
2898 STREAM_EVENT_CLOSED = 4,
2899 STREAM_EVENT_NEW = 5,
2900 STREAM_EVENT_NEW_RESOLVE = 6,
2901 STREAM_EVENT_FAILED_RETRIABLE = 7,
2902 STREAM_EVENT_REMAP = 8
2903 } stream_status_event_t;
2905 typedef enum or_conn_status_event_t {
2906 OR_CONN_EVENT_LAUNCHED = 0,
2907 OR_CONN_EVENT_CONNECTED = 1,
2908 OR_CONN_EVENT_FAILED = 2,
2909 OR_CONN_EVENT_CLOSED = 3,
2910 OR_CONN_EVENT_NEW = 4,
2911 } or_conn_status_event_t;
2913 void control_update_global_event_mask(void);
2914 void control_adjust_event_log_severity(void);
2916 /** Execute the statement <b>stmt</b>, which may log events concerning the
2917 * connection <b>conn</b>. To prevent infinite loops, disable log messages
2918 * being sent to controllers if <b>conn</b> is a control connection.
2920 * Stmt must not contain any return or goto statements.
2922 #define CONN_LOG_PROTECT(conn, stmt) \
2923 STMT_BEGIN \
2924 int _log_conn_is_control = (conn && conn->type == CONN_TYPE_CONTROL); \
2925 if (_log_conn_is_control) \
2926 disable_control_logging(); \
2927 STMT_BEGIN stmt; STMT_END; \
2928 if (_log_conn_is_control) \
2929 enable_control_logging(); \
2930 STMT_END
2932 /** Log information about the connection <b>conn</b>, protecting it as with
2933 * CONN_LOG_PROTECT. Example:
2935 * LOG_FN_CONN(conn, (LOG_DEBUG, "Socket %d wants to write", conn->s));
2937 #define LOG_FN_CONN(conn, args) \
2938 CONN_LOG_PROTECT(conn, log_fn args)
2940 int connection_control_finished_flushing(control_connection_t *conn);
2941 int connection_control_reached_eof(control_connection_t *conn);
2942 int connection_control_process_inbuf(control_connection_t *conn);
2944 #define EVENT_AUTHDIR_NEWDESCS 0x000D
2945 #define EVENT_NS 0x000F
2946 int control_event_is_interesting(int event);
2948 int control_event_circuit_status(origin_circuit_t *circ,
2949 circuit_status_event_t e, int reason);
2950 int control_event_stream_status(edge_connection_t *conn,
2951 stream_status_event_t e,
2952 int reason);
2953 int control_tls_error_to_reason(int e);
2954 int control_event_or_conn_status(or_connection_t *conn,
2955 or_conn_status_event_t e, int reason);
2956 int control_event_bandwidth_used(uint32_t n_read, uint32_t n_written);
2957 int control_event_stream_bandwidth_used(void);
2958 void control_event_logmsg(int severity, unsigned int domain, const char *msg);
2959 int control_event_descriptors_changed(smartlist_t *routers);
2960 int control_event_address_mapped(const char *from, const char *to,
2961 time_t expires, const char *error);
2962 int control_event_or_authdir_new_descriptor(const char *action,
2963 const char *desc,
2964 size_t desclen,
2965 const char *msg);
2966 int control_event_my_descriptor_changed(void);
2967 int control_event_networkstatus_changed(smartlist_t *statuses);
2968 int control_event_networkstatus_changed_single(routerstatus_t *rs);
2969 int control_event_general_status(int severity, const char *format, ...)
2970 CHECK_PRINTF(2,3);
2971 int control_event_client_status(int severity, const char *format, ...)
2972 CHECK_PRINTF(2,3);
2973 int control_event_server_status(int severity, const char *format, ...)
2974 CHECK_PRINTF(2,3);
2975 int control_event_guard(const char *nickname, const char *digest,
2976 const char *status);
2978 int init_cookie_authentication(int enabled);
2979 smartlist_t *decode_hashed_passwords(config_line_t *passwords);
2980 void disable_control_logging(void);
2981 void enable_control_logging(void);
2983 #ifdef CONTROL_PRIVATE
2984 /* Used only by control.c and test.c */
2985 size_t write_escaped_data(const char *data, size_t len, char **out);
2986 size_t read_escaped_data(const char *data, size_t len, char **out);
2987 #endif
2989 /********************************* cpuworker.c *****************************/
2991 void cpu_init(void);
2992 void cpuworkers_rotate(void);
2993 int connection_cpu_finished_flushing(connection_t *conn);
2994 int connection_cpu_reached_eof(connection_t *conn);
2995 int connection_cpu_process_inbuf(connection_t *conn);
2996 int assign_onionskin_to_cpuworker(connection_t *cpuworker,
2997 or_circuit_t *circ,
2998 char *onionskin);
3000 /********************************* directory.c ***************************/
3002 int directories_have_accepted_server_descriptor(void);
3003 char *authority_type_to_string(authority_type_t auth);
3004 void directory_post_to_dirservers(uint8_t dir_purpose, uint8_t router_purpose,
3005 authority_type_t type, const char *payload,
3006 size_t payload_len, size_t extrainfo_len);
3007 void directory_get_from_dirserver(uint8_t dir_purpose, uint8_t router_purpose,
3008 const char *resource,
3009 int retry_if_no_servers);
3010 void directory_get_from_all_authorities(uint8_t dir_purpose,
3011 uint8_t router_purpose,
3012 const char *resource);
3013 void directory_initiate_command_routerstatus(routerstatus_t *status,
3014 uint8_t dir_purpose,
3015 uint8_t router_purpose,
3016 int anonymized_connection,
3017 const char *resource,
3018 const char *payload,
3019 size_t payload_len,
3020 time_t if_modified_since);
3022 int parse_http_response(const char *headers, int *code, time_t *date,
3023 compress_method_t *compression, char **response);
3025 int connection_dir_is_encrypted(dir_connection_t *conn);
3026 int connection_dir_reached_eof(dir_connection_t *conn);
3027 int connection_dir_process_inbuf(dir_connection_t *conn);
3028 int connection_dir_finished_flushing(dir_connection_t *conn);
3029 int connection_dir_finished_connecting(dir_connection_t *conn);
3030 void connection_dir_request_failed(dir_connection_t *conn);
3031 void directory_initiate_command(const char *address, uint32_t addr,
3032 uint16_t or_port, uint16_t dir_port,
3033 int supports_begindir, const char *digest,
3034 uint8_t dir_purpose, uint8_t router_purpose,
3035 int anonymized_connection,
3036 const char *resource,
3037 const char *payload, size_t payload_len,
3038 time_t if_modified_since);
3040 int dir_split_resource_into_fingerprints(const char *resource,
3041 smartlist_t *fp_out, int *compresseed_out,
3042 int decode_hex, int sort_uniq);
3043 char *directory_dump_request_log(void);
3044 int router_supports_extrainfo(const char *identity_digest, int is_authority);
3046 time_t download_status_increment_failure(download_status_t *dls,
3047 int status_code, const char *item,
3048 int server, time_t now);
3049 #define download_status_failed(dls, sc) \
3050 download_status_increment_failure((dls), (sc), NULL, \
3051 get_options()->DirPort, time(NULL))
3053 void download_status_reset(download_status_t *dls);
3054 static int download_status_is_ready(download_status_t *dls, time_t now,
3055 int max_failures);
3056 /** Return true iff, as of <b>now</b>, the resource tracked by <b>dls</b> is
3057 * ready to get its download reattempted. */
3058 static INLINE int
3059 download_status_is_ready(download_status_t *dls, time_t now,
3060 int max_failures)
3062 return (dls->n_download_failures <= max_failures
3063 && dls->next_attempt_at <= now);
3066 /********************************* dirserv.c ***************************/
3067 /** Maximum allowable length of a version line in a networkstatus. */
3068 #define MAX_V_LINE_LEN 128
3069 /** Length of "r Authority BadDirectory BadExit Exit Fast Guard HSDir Named
3070 * Running Stable Unnamed V2Dir Valid\n". */
3071 #define MAX_FLAG_LINE_LEN 96
3072 /** Amount of space to allocate for each entry: r, s, and v lines. */
3073 #define RS_ENTRY_LEN \
3074 ( /* first line */ \
3075 MAX_NICKNAME_LEN+BASE64_DIGEST_LEN*2+ISO_TIME_LEN+INET_NTOA_BUF_LEN+ \
3076 5*2 /* ports */ + 10 /* punctuation */ + \
3077 /* second line */ \
3078 MAX_FLAG_LINE_LEN + \
3079 /* v line. */ \
3080 MAX_V_LINE_LEN \
3082 #define UNNAMED_ROUTER_NICKNAME "Unnamed"
3084 int connection_dirserv_flushed_some(dir_connection_t *conn);
3086 int dirserv_add_own_fingerprint(const char *nickname, crypto_pk_env_t *pk);
3087 int dirserv_load_fingerprint_file(void);
3088 void dirserv_free_fingerprint_list(void);
3089 const char *dirserv_get_nickname_by_digest(const char *digest);
3090 int dirserv_add_multiple_descriptors(const char *desc, uint8_t purpose,
3091 const char *source,
3092 const char **msg);
3093 int dirserv_add_descriptor(routerinfo_t *ri, const char **msg);
3094 int getinfo_helper_dirserv_unregistered(control_connection_t *conn,
3095 const char *question, char **answer);
3096 void dirserv_free_descriptors(void);
3097 void dirserv_set_router_is_running(routerinfo_t *router, time_t now);
3098 int list_server_status_v1(smartlist_t *routers, char **router_status_out,
3099 int for_controller);
3100 int dirserv_dump_directory_to_string(char **dir_out,
3101 crypto_pk_env_t *private_key);
3103 int directory_fetches_from_authorities(or_options_t *options);
3104 int directory_fetches_dir_info_early(or_options_t *options);
3105 int directory_fetches_dir_info_later(or_options_t *options);
3106 int directory_caches_v2_dir_info(or_options_t *options);
3107 #define directory_caches_v1_dir_info(o) directory_caches_v2_dir_info(o)
3108 int directory_caches_dir_info(or_options_t *options);
3109 int directory_permits_begindir_requests(or_options_t *options);
3110 int directory_permits_controller_requests(or_options_t *options);
3111 int directory_too_idle_to_fetch_descriptors(or_options_t *options, time_t now);
3113 void directory_set_dirty(void);
3114 cached_dir_t *dirserv_get_directory(void);
3115 cached_dir_t *dirserv_get_runningrouters(void);
3116 cached_dir_t *dirserv_get_consensus(void);
3117 void dirserv_set_cached_directory(const char *directory, time_t when,
3118 int is_running_routers);
3119 void dirserv_set_cached_networkstatus_v2(const char *directory,
3120 const char *identity,
3121 time_t published);
3122 void dirserv_set_cached_networkstatus_v3(const char *consensus,
3123 time_t published);
3124 void dirserv_clear_old_networkstatuses(time_t cutoff);
3125 void dirserv_clear_old_v1_info(time_t now);
3126 void dirserv_get_networkstatus_v2(smartlist_t *result, const char *key);
3127 void dirserv_get_networkstatus_v2_fingerprints(smartlist_t *result,
3128 const char *key);
3129 int dirserv_get_routerdesc_fingerprints(smartlist_t *fps_out, const char *key,
3130 const char **msg,
3131 int for_unencrypted_conn);
3132 int dirserv_get_routerdescs(smartlist_t *descs_out, const char *key,
3133 const char **msg);
3134 void dirserv_orconn_tls_done(const char *address,
3135 uint16_t or_port,
3136 const char *digest_rcvd,
3137 int as_advertised);
3138 void dirserv_test_reachability(time_t now, int try_all);
3139 int authdir_wants_to_reject_router(routerinfo_t *ri, const char **msg,
3140 int complain);
3141 int dirserv_would_reject_router(routerstatus_t *rs);
3142 int dirserv_remove_old_statuses(smartlist_t *fps, time_t cutoff);
3143 int dirserv_have_any_serverdesc(smartlist_t *fps, int spool_src);
3144 size_t dirserv_estimate_data_size(smartlist_t *fps, int is_serverdescs,
3145 int compressed);
3146 int routerstatus_format_entry(char *buf, size_t buf_len,
3147 routerstatus_t *rs, const char *platform,
3148 int first_line_only);
3149 void dirserv_free_all(void);
3150 void cached_dir_decref(cached_dir_t *d);
3151 cached_dir_t *new_cached_dir(char *s, time_t published);
3153 /********************************* dirvote.c ************************/
3155 /** Lowest allowable value for VoteSeconds. */
3156 #define MIN_VOTE_SECONDS 20
3157 /** Lowest allowable value for DistSeconds. */
3158 #define MIN_DIST_SECONDS 20
3159 /** Smallest allowable voting interval. */
3160 #define MIN_VOTE_INTERVAL 300
3162 /** If there is no consensus, what interval do we default to? */
3163 #define DEFAULT_VOTING_INTERVAL_WHEN_NO_CONSENSUS (30*60)
3165 void dirvote_free_all(void);
3167 /* vote manipulation */
3168 char *networkstatus_compute_consensus(smartlist_t *votes,
3169 int total_authorities,
3170 crypto_pk_env_t *identity_key,
3171 crypto_pk_env_t *signing_key);
3172 int networkstatus_add_detached_signatures(networkstatus_t *target,
3173 ns_detached_signatures_t *sigs,
3174 const char **msg_out);
3175 char *networkstatus_get_detached_signatures(networkstatus_t *consensus);
3176 void ns_detached_signatures_free(ns_detached_signatures_t *s);
3178 /* cert manipulation */
3179 authority_cert_t *authority_cert_dup(authority_cert_t *cert);
3181 /** Describes the schedule by which votes should be generated. */
3182 typedef struct vote_timing_t {
3183 int vote_interval;
3184 int n_intervals_valid;
3185 int vote_delay;
3186 int dist_delay;
3187 } vote_timing_t;
3188 /* vote scheduling */
3189 void dirvote_get_preferred_voting_intervals(vote_timing_t *timing_out);
3190 time_t dirvote_get_start_of_next_interval(time_t now, int interval);
3191 void dirvote_recalculate_timing(or_options_t *options, time_t now);
3192 void dirvote_act(or_options_t *options, time_t now);
3194 /* invoked on timers and by outside triggers. */
3195 struct pending_vote_t * dirvote_add_vote(const char *vote_body,
3196 const char **msg_out,
3197 int *status_out);
3198 int dirvote_add_signatures(const char *detached_signatures_body,
3199 const char *source,
3200 const char **msg_out);
3202 /* Item access */
3203 const char *dirvote_get_pending_consensus(void);
3204 const char *dirvote_get_pending_detached_signatures(void);
3205 #define DGV_BY_ID 1
3206 #define DGV_INCLUDE_PENDING 2
3207 #define DGV_INCLUDE_PREVIOUS 4
3208 const cached_dir_t *dirvote_get_vote(const char *fp, int flags);
3209 void set_routerstatus_from_routerinfo(routerstatus_t *rs,
3210 routerinfo_t *ri, time_t now,
3211 int naming, int exits_can_be_guards,
3212 int listbadexits, int listbaddirs);
3213 void router_clear_status_flags(routerinfo_t *ri);
3214 networkstatus_t *
3215 dirserv_generate_networkstatus_vote_obj(crypto_pk_env_t *private_key,
3216 authority_cert_t *cert);
3218 #ifdef DIRVOTE_PRIVATE
3219 char *
3220 format_networkstatus_vote(crypto_pk_env_t *private_key,
3221 networkstatus_t *v3_ns);
3222 #endif
3224 /********************************* dns.c ***************************/
3226 int dns_init(void);
3227 void dns_free_all(void);
3228 uint32_t dns_clip_ttl(uint32_t ttl);
3229 int dns_reset(void);
3230 void connection_dns_remove(edge_connection_t *conn);
3231 void assert_connection_edge_not_dns_pending(edge_connection_t *conn);
3232 void assert_all_pending_dns_resolves_ok(void);
3233 void dns_cancel_pending_resolve(const char *question);
3234 int dns_resolve(edge_connection_t *exitconn);
3235 void dns_launch_correctness_checks(void);
3236 int dns_seems_to_be_broken(void);
3237 void dns_reset_correctness_checks(void);
3239 /********************************* dnsserv.c ************************/
3241 void dnsserv_configure_listener(connection_t *conn);
3242 void dnsserv_close_listener(connection_t *conn);
3243 void dnsserv_resolved(edge_connection_t *conn,
3244 int answer_type,
3245 size_t answer_len,
3246 const char *answer,
3247 int ttl);
3248 void dnsserv_reject_request(edge_connection_t *conn);
3249 int dnsserv_launch_request(const char *name, int is_reverse);
3251 /********************************* geoip.c **************************/
3253 #ifdef GEOIP_PRIVATE
3254 int geoip_parse_entry(const char *line);
3255 #endif
3256 int geoip_load_file(const char *filename);
3257 int geoip_get_country_by_ip(uint32_t ipaddr);
3258 int geoip_get_n_countries(void);
3259 const char *geoip_get_country_name(int num);
3260 int geoip_is_loaded(void);
3261 void geoip_note_client_seen(uint32_t addr, time_t now);
3262 void geoip_remove_old_clients(time_t cutoff);
3263 time_t geoip_get_history_start(void);
3264 char *geoip_get_client_history(time_t now);
3265 int getinfo_helper_geoip(control_connection_t *control_conn,
3266 const char *question, char **answer);
3267 void geoip_free_all(void);
3269 /********************************* hibernate.c **********************/
3271 int accounting_parse_options(or_options_t *options, int validate_only);
3272 int accounting_is_enabled(or_options_t *options);
3273 void configure_accounting(time_t now);
3274 void accounting_run_housekeeping(time_t now);
3275 void accounting_add_bytes(size_t n_read, size_t n_written, int seconds);
3276 int accounting_record_bandwidth_usage(time_t now, or_state_t *state);
3277 void hibernate_begin_shutdown(void);
3278 int we_are_hibernating(void);
3279 void consider_hibernation(time_t now);
3280 int getinfo_helper_accounting(control_connection_t *conn,
3281 const char *question, char **answer);
3282 void accounting_set_bandwidth_usage_from_state(or_state_t *state);
3284 /********************************* main.c ***************************/
3286 extern int has_completed_circuit;
3288 int connection_add(connection_t *conn);
3289 int connection_remove(connection_t *conn);
3290 int connection_in_array(connection_t *conn);
3291 void add_connection_to_closeable_list(connection_t *conn);
3292 int connection_is_on_closeable_list(connection_t *conn);
3294 smartlist_t *get_connection_array(void);
3296 void connection_watch_events(connection_t *conn, short events);
3297 int connection_is_reading(connection_t *conn);
3298 void connection_stop_reading(connection_t *conn);
3299 void connection_start_reading(connection_t *conn);
3301 int connection_is_writing(connection_t *conn);
3302 void connection_stop_writing(connection_t *conn);
3303 void connection_start_writing(connection_t *conn);
3305 void connection_stop_reading_from_linked_conn(connection_t *conn);
3307 void directory_all_unreachable(time_t now);
3308 void directory_info_has_arrived(time_t now, int from_cache);
3310 void ip_address_changed(int at_interface);
3311 void dns_servers_relaunch_checks(void);
3313 void control_signal_act(int the_signal);
3314 void handle_signals(int is_parent);
3315 void tor_cleanup(void);
3316 void tor_free_all(int postfork);
3318 int tor_main(int argc, char *argv[]);
3320 #ifdef MAIN_PRIVATE
3321 int do_main_loop(void);
3322 int do_list_fingerprint(void);
3323 void do_hash_password(void);
3324 int tor_init(int argc, char **argv);
3325 #endif
3327 /********************************* networkstatus.c *********************/
3329 /** How old do we allow a v2 network-status to get before removing it
3330 * completely? */
3331 #define MAX_NETWORKSTATUS_AGE (10*24*60*60)
3333 typedef enum {
3334 NS_FROM_CACHE, NS_FROM_DIR_BY_FP, NS_FROM_DIR_ALL, NS_GENERATED
3335 } networkstatus_source_t;
3337 typedef enum version_status_t {
3338 VS_RECOMMENDED=0, /**< This version is listed as recommended. */
3339 VS_OLD=1, /**< This version is older than any recommended version. */
3340 VS_NEW=2, /**< This version is newer than any recommended version. */
3341 VS_NEW_IN_SERIES=3, /**< This version is newer than any recommended version
3342 * in its series, but later recommended versions exist.
3344 VS_UNRECOMMENDED=4, /**< This version is not recommended (general case). */
3345 VS_EMPTY=5, /**< The version list was empty; no agreed-on versions. */
3346 VS_UNKNOWN, /**< We have no idea. */
3347 } version_status_t;
3349 void networkstatus_reset_warnings(void);
3350 void networkstatus_reset_download_failures(void);
3351 int router_reload_v2_networkstatus(void);
3352 int router_reload_consensus_networkstatus(void);
3353 void routerstatus_free(routerstatus_t *rs);
3354 void networkstatus_v2_free(networkstatus_v2_t *ns);
3355 void networkstatus_vote_free(networkstatus_t *ns);
3356 networkstatus_voter_info_t *networkstatus_get_voter_by_id(
3357 networkstatus_t *vote,
3358 const char *identity);
3359 int networkstatus_check_consensus_signature(networkstatus_t *consensus,
3360 int warn);
3361 int networkstatus_check_voter_signature(networkstatus_t *consensus,
3362 networkstatus_voter_info_t *voter,
3363 authority_cert_t *cert);
3364 char *networkstatus_get_cache_filename(const char *identity_digest);
3365 int router_set_networkstatus_v2(const char *s, time_t arrived_at,
3366 networkstatus_source_t source,
3367 smartlist_t *requested_fingerprints);
3368 void networkstatus_v2_list_clean(time_t now);
3369 routerstatus_t *networkstatus_v2_find_entry(networkstatus_v2_t *ns,
3370 const char *digest);
3371 routerstatus_t *networkstatus_vote_find_entry(networkstatus_t *ns,
3372 const char *digest);
3373 int networkstatus_vote_find_entry_idx(networkstatus_t *ns,
3374 const char *digest, int *found_out);
3375 const smartlist_t *networkstatus_get_v2_list(void);
3376 download_status_t *router_get_dl_status_by_descriptor_digest(const char *d);
3377 routerstatus_t *router_get_consensus_status_by_id(const char *digest);
3378 routerstatus_t *router_get_consensus_status_by_descriptor_digest(
3379 const char *digest);
3380 routerstatus_t *router_get_consensus_status_by_nickname(const char *nickname,
3381 int warn_if_unnamed);
3382 const char *networkstatus_get_router_digest_by_nickname(const char *nickname);
3383 int networkstatus_nickname_is_unnamed(const char *nickname);
3384 void networkstatus_consensus_download_failed(int status_code);
3385 void update_consensus_networkstatus_fetch_time(time_t now);
3386 int should_delay_dir_fetches(or_options_t *options);
3387 void update_networkstatus_downloads(time_t now);
3388 void update_certificate_downloads(time_t now);
3389 networkstatus_v2_t *networkstatus_v2_get_by_digest(const char *digest);
3390 networkstatus_t *networkstatus_get_latest_consensus(void);
3391 networkstatus_t *networkstatus_get_live_consensus(time_t now);
3392 networkstatus_t *networkstatus_get_reasonably_live_consensus(time_t now);
3393 #define NSSET_FROM_CACHE 1
3394 #define NSSET_WAS_WAITING_FOR_CERTS 2
3395 #define NSSET_DONT_DOWNLOAD_CERTS 4
3396 int networkstatus_set_current_consensus(const char *consensus, unsigned flags);
3397 void networkstatus_note_certs_arrived(void);
3398 void routers_update_all_from_networkstatus(time_t now, int dir_version);
3399 void routerstatus_list_update_from_consensus_networkstatus(time_t now);
3400 void routers_update_status_from_consensus_networkstatus(smartlist_t *routers,
3401 int reset_failures);
3402 void signed_descs_update_status_from_consensus_networkstatus(
3403 smartlist_t *descs);
3405 char *networkstatus_getinfo_helper_single(routerstatus_t *rs);
3406 char *networkstatus_getinfo_by_purpose(const char *purpose_string, time_t now);
3407 void networkstatus_dump_bridge_status_to_file(time_t now);
3408 int getinfo_helper_networkstatus(control_connection_t *conn,
3409 const char *question, char **answer);
3410 void networkstatus_free_all(void);
3412 /********************************* ntmain.c ***************************/
3413 #ifdef MS_WINDOWS
3414 #define NT_SERVICE
3415 #endif
3417 #ifdef NT_SERVICE
3418 int nt_service_parse_options(int argc, char **argv, int *should_exit);
3419 int nt_service_is_stopping(void);
3420 void nt_service_set_state(DWORD state);
3421 #else
3422 #define nt_service_is_stopping() (0)
3423 #endif
3425 /********************************* onion.c ***************************/
3427 int onion_pending_add(or_circuit_t *circ, char *onionskin);
3428 or_circuit_t *onion_next_task(char **onionskin_out);
3429 void onion_pending_remove(or_circuit_t *circ);
3431 int onion_skin_create(crypto_pk_env_t *router_key,
3432 crypto_dh_env_t **handshake_state_out,
3433 char *onion_skin_out);
3435 int onion_skin_server_handshake(const char *onion_skin,
3436 crypto_pk_env_t *private_key,
3437 crypto_pk_env_t *prev_private_key,
3438 char *handshake_reply_out,
3439 char *key_out,
3440 size_t key_out_len);
3442 int onion_skin_client_handshake(crypto_dh_env_t *handshake_state,
3443 const char *handshake_reply,
3444 char *key_out,
3445 size_t key_out_len);
3447 int fast_server_handshake(const char *key_in,
3448 char *handshake_reply_out,
3449 char *key_out,
3450 size_t key_out_len);
3452 int fast_client_handshake(const char *handshake_state,
3453 const char *handshake_reply_out,
3454 char *key_out,
3455 size_t key_out_len);
3457 void clear_pending_onions(void);
3459 /********************************* policies.c ************************/
3461 /* (length of "accept 255.255.255.255/255.255.255.255:65535-65535\n" plus a
3462 * nul.)
3464 #define POLICY_BUF_LEN 52
3466 typedef enum {
3467 ADDR_POLICY_ACCEPTED=0,
3468 ADDR_POLICY_REJECTED=-1,
3469 ADDR_POLICY_PROBABLY_ACCEPTED=1,
3470 ADDR_POLICY_PROBABLY_REJECTED=2
3471 } addr_policy_result_t;
3473 int firewall_is_fascist_or(void);
3474 int fascist_firewall_allows_address_or(uint32_t addr, uint16_t port);
3475 int fascist_firewall_allows_address_dir(uint32_t addr, uint16_t port);
3476 int dir_policy_permits_address(uint32_t addr);
3477 int socks_policy_permits_address(uint32_t addr);
3478 int authdir_policy_permits_address(uint32_t addr, uint16_t port);
3479 int authdir_policy_valid_address(uint32_t addr, uint16_t port);
3480 int authdir_policy_baddir_address(uint32_t addr, uint16_t port);
3481 int authdir_policy_badexit_address(uint32_t addr, uint16_t port);
3483 int validate_addr_policies(or_options_t *options, char **msg);
3484 void policy_expand_private(smartlist_t **policy);
3485 int policies_parse_from_options(or_options_t *options);
3487 addr_policy_t *addr_policy_get_canonical_entry(addr_policy_t *ent);
3488 int cmp_addr_policies(smartlist_t *a, smartlist_t *b);
3489 addr_policy_result_t compare_addr_to_addr_policy(uint32_t addr,
3490 uint16_t port, smartlist_t *policy);
3491 int policies_parse_exit_policy(config_line_t *cfg, smartlist_t **dest,
3492 int rejectprivate, const char *local_address);
3493 void policies_set_router_exitpolicy_to_reject_all(routerinfo_t *exitrouter);
3494 int exit_policy_is_general_exit(smartlist_t *policy);
3495 int policy_is_reject_star(smartlist_t *policy);
3496 int getinfo_helper_policies(control_connection_t *conn,
3497 const char *question, char **answer);
3498 int policy_write_item(char *buf, size_t buflen, addr_policy_t *item);
3500 void addr_policy_list_free(smartlist_t *p);
3501 void addr_policy_free(addr_policy_t *p);
3502 void policies_free_all(void);
3504 /********************************* relay.c ***************************/
3506 extern uint64_t stats_n_relay_cells_relayed;
3507 extern uint64_t stats_n_relay_cells_delivered;
3509 int circuit_receive_relay_cell(cell_t *cell, circuit_t *circ,
3510 int cell_direction);
3512 void relay_header_pack(char *dest, const relay_header_t *src);
3513 void relay_header_unpack(relay_header_t *dest, const char *src);
3514 int relay_send_command_from_edge(uint16_t stream_id, circuit_t *circ,
3515 uint8_t relay_command, const char *payload,
3516 size_t payload_len, crypt_path_t *cpath_layer);
3517 int connection_edge_send_command(edge_connection_t *fromconn,
3518 uint8_t relay_command, const char *payload,
3519 size_t payload_len);
3520 int connection_edge_package_raw_inbuf(edge_connection_t *conn,
3521 int package_partial);
3522 void connection_edge_consider_sending_sendme(edge_connection_t *conn);
3523 socks5_reply_status_t connection_edge_end_reason_socks5_response(int reason);
3524 int errno_to_end_reason(int e);
3526 extern uint64_t stats_n_data_cells_packaged;
3527 extern uint64_t stats_n_data_bytes_packaged;
3528 extern uint64_t stats_n_data_cells_received;
3529 extern uint64_t stats_n_data_bytes_received;
3531 void init_cell_pool(void);
3532 void free_cell_pool(void);
3533 void clean_cell_pool(void);
3534 void dump_cell_pool_usage(int severity);
3536 void cell_queue_clear(cell_queue_t *queue);
3537 void cell_queue_append(cell_queue_t *queue, packed_cell_t *cell);
3538 void cell_queue_append_packed_copy(cell_queue_t *queue, const cell_t *cell);
3540 void append_cell_to_circuit_queue(circuit_t *circ, or_connection_t *orconn,
3541 cell_t *cell, int direction);
3542 void connection_or_unlink_all_active_circs(or_connection_t *conn);
3543 int connection_or_flush_from_first_active_circuit(or_connection_t *conn,
3544 int max);
3545 void assert_active_circuits_ok(or_connection_t *orconn);
3546 void make_circuit_inactive_on_conn(circuit_t *circ, or_connection_t *conn);
3547 void make_circuit_active_on_conn(circuit_t *circ, or_connection_t *conn);
3549 /********************************* rephist.c ***************************/
3551 void rep_hist_init(void);
3552 void rep_hist_note_connect_failed(const char* nickname, time_t when);
3553 void rep_hist_note_connect_succeeded(const char* nickname, time_t when);
3554 void rep_hist_note_disconnect(const char* nickname, time_t when);
3555 void rep_hist_note_connection_died(const char* nickname, time_t when);
3556 void rep_hist_note_extend_succeeded(const char *from_name,
3557 const char *to_name);
3558 void rep_hist_note_extend_failed(const char *from_name, const char *to_name);
3559 void rep_hist_dump_stats(time_t now, int severity);
3560 void rep_hist_note_bytes_read(size_t num_bytes, time_t when);
3561 void rep_hist_note_bytes_written(size_t num_bytes, time_t when);
3562 int rep_hist_bandwidth_assess(void);
3563 char *rep_hist_get_bandwidth_lines(int for_extrainfo);
3564 void rep_hist_update_state(or_state_t *state);
3565 int rep_hist_load_state(or_state_t *state, char **err);
3566 void rep_history_clean(time_t before);
3568 void rep_hist_note_router_reachable(const char *id, time_t when);
3569 void rep_hist_note_router_unreachable(const char *id, time_t when);
3570 int rep_hist_record_mtbf_data(void);
3571 int rep_hist_load_mtbf_data(time_t now);
3573 time_t rep_hist_downrate_old_runs(time_t now);
3574 double rep_hist_get_stability(const char *id, time_t when);
3575 double rep_hist_get_weighted_fractional_uptime(const char *id, time_t when);
3576 long rep_hist_get_weighted_time_known(const char *id, time_t when);
3577 int rep_hist_have_measured_enough_stability(void);
3579 void rep_hist_note_used_port(uint16_t port, time_t now);
3580 smartlist_t *rep_hist_get_predicted_ports(time_t now);
3581 void rep_hist_note_used_resolve(time_t now);
3582 void rep_hist_note_used_internal(time_t now, int need_uptime,
3583 int need_capacity);
3584 int rep_hist_get_predicted_internal(time_t now, int *need_uptime,
3585 int *need_capacity);
3587 int any_predicted_circuits(time_t now);
3588 int rep_hist_circbuilding_dormant(time_t now);
3590 /** Possible public/private key operations in Tor: used to keep track of where
3591 * we're spending our time. */
3592 typedef enum {
3593 SIGN_DIR, SIGN_RTR,
3594 VERIFY_DIR, VERIFY_RTR,
3595 ENC_ONIONSKIN, DEC_ONIONSKIN,
3596 TLS_HANDSHAKE_C, TLS_HANDSHAKE_S,
3597 REND_CLIENT, REND_MID, REND_SERVER,
3598 } pk_op_t;
3599 void note_crypto_pk_op(pk_op_t operation);
3600 void dump_pk_ops(int severity);
3602 void rep_hist_free_all(void);
3604 /* for hidden service usage statistics */
3605 void hs_usage_note_publish_total(const char *service_id, time_t now);
3606 void hs_usage_note_publish_novel(const char *service_id, time_t now);
3607 void hs_usage_note_fetch_total(const char *service_id, time_t now);
3608 void hs_usage_note_fetch_successful(const char *service_id, time_t now);
3609 void hs_usage_write_statistics_to_file(time_t now);
3610 void hs_usage_free_all(void);
3612 /********************************* rendclient.c ***************************/
3614 void rend_client_introcirc_has_opened(origin_circuit_t *circ);
3615 void rend_client_rendcirc_has_opened(origin_circuit_t *circ);
3616 int rend_client_introduction_acked(origin_circuit_t *circ, const char *request,
3617 size_t request_len);
3618 void rend_client_refetch_renddesc(const char *query);
3619 void rend_client_refetch_v2_renddesc(const char *query);
3620 int rend_client_remove_intro_point(extend_info_t *failed_intro,
3621 const char *query);
3622 int rend_client_rendezvous_acked(origin_circuit_t *circ, const char *request,
3623 size_t request_len);
3624 int rend_client_receive_rendezvous(origin_circuit_t *circ, const char *request,
3625 size_t request_len);
3626 void rend_client_desc_here(const char *query);
3628 extend_info_t *rend_client_get_random_intro(const char *query);
3630 int rend_client_send_introduction(origin_circuit_t *introcirc,
3631 origin_circuit_t *rendcirc);
3633 /********************************* rendcommon.c ***************************/
3635 /** ASCII-encoded v2 hidden service descriptor. */
3636 typedef struct rend_encoded_v2_service_descriptor_t {
3637 char desc_id[DIGEST_LEN]; /**< Descriptor ID. */
3638 char *desc_str; /**< Descriptor string. */
3639 } rend_encoded_v2_service_descriptor_t;
3641 /** Introduction point information. */
3642 typedef struct rend_intro_point_t {
3643 extend_info_t *extend_info; /**< Extend info of this introduction point. */
3644 crypto_pk_env_t *intro_key; /**< Introduction key that replaces the service
3645 * key, if this descriptor is V2. */
3646 } rend_intro_point_t;
3648 /** Information used to connect to a hidden service. */
3649 typedef struct rend_service_descriptor_t {
3650 crypto_pk_env_t *pk; /**< This service's public key. */
3651 int version; /**< Version of the descriptor format: 0 or 2. */
3652 time_t timestamp; /**< Time when the descriptor was generated. */
3653 uint16_t protocols; /**< Bitmask: which rendezvous protocols are supported?
3654 * (We allow bits '0', '1', and '2' to be set.) */
3655 /** List of the service's introduction points. Elements are removed if
3656 * introduction attempts fail. */
3657 smartlist_t *intro_nodes;
3658 } rend_service_descriptor_t;
3660 int rend_cmp_service_ids(const char *one, const char *two);
3662 void rend_process_relay_cell(circuit_t *circ, int command, size_t length,
3663 const char *payload);
3665 void rend_service_descriptor_free(rend_service_descriptor_t *desc);
3666 int rend_encode_service_descriptor(rend_service_descriptor_t *desc,
3667 crypto_pk_env_t *key,
3668 char **str_out,
3669 size_t *len_out);
3670 rend_service_descriptor_t *rend_parse_service_descriptor(const char *str,
3671 size_t len);
3672 int rend_get_service_id(crypto_pk_env_t *pk, char *out);
3673 void rend_encoded_v2_service_descriptor_free(
3674 rend_encoded_v2_service_descriptor_t *desc);
3675 void rend_intro_point_free(rend_intro_point_t *intro);
3677 /** A cached rendezvous descriptor. */
3678 typedef struct rend_cache_entry_t {
3679 size_t len; /**< Length of <b>desc</b> */
3680 time_t received; /**< When was the descriptor received? */
3681 char *desc; /**< Service descriptor */
3682 rend_service_descriptor_t *parsed; /**< Parsed value of 'desc' */
3683 } rend_cache_entry_t;
3685 void rend_cache_init(void);
3686 void rend_cache_clean(void);
3687 void rend_cache_clean_v2_descs_as_dir(void);
3688 void rend_cache_free_all(void);
3689 int rend_valid_service_id(const char *query);
3690 int rend_cache_lookup_desc(const char *query, int version, const char **desc,
3691 size_t *desc_len);
3692 int rend_cache_lookup_entry(const char *query, int version,
3693 rend_cache_entry_t **entry_out);
3694 int rend_cache_lookup_v2_desc_as_dir(const char *query, const char **desc);
3695 int rend_cache_store(const char *desc, size_t desc_len, int published);
3696 int rend_cache_store_v2_desc_as_client(const char *desc,
3697 const char *descriptor_cookie);
3698 int rend_cache_store_v2_desc_as_dir(const char *desc);
3699 int rend_cache_size(void);
3700 int rend_encode_v2_descriptors(smartlist_t *descs_out,
3701 rend_service_descriptor_t *desc, time_t now,
3702 const char *descriptor_cookie, uint8_t period);
3703 int rend_compute_v2_desc_id(char *desc_id_out, const char *service_id,
3704 const char *descriptor_cookie,
3705 time_t now, uint8_t replica);
3706 int rend_id_is_in_interval(const char *a, const char *b, const char *c);
3707 void rend_get_descriptor_id_bytes(char *descriptor_id_out,
3708 const char *service_id,
3709 const char *secret_id_part);
3711 /********************************* rendservice.c ***************************/
3713 int num_rend_services(void);
3714 int rend_config_services(or_options_t *options, int validate_only);
3715 int rend_service_load_keys(void);
3716 void rend_services_init(void);
3717 void rend_services_introduce(void);
3718 void rend_consider_services_upload(time_t now);
3720 void rend_service_intro_has_opened(origin_circuit_t *circuit);
3721 int rend_service_intro_established(origin_circuit_t *circuit,
3722 const char *request,
3723 size_t request_len);
3724 void rend_service_rendezvous_has_opened(origin_circuit_t *circuit);
3725 int rend_service_introduce(origin_circuit_t *circuit, const char *request,
3726 size_t request_len);
3727 void rend_service_relaunch_rendezvous(origin_circuit_t *oldcirc);
3728 int rend_service_set_connection_addr_port(edge_connection_t *conn,
3729 origin_circuit_t *circ);
3730 void rend_service_dump_stats(int severity);
3731 void rend_service_free_all(void);
3733 /********************************* rendmid.c *******************************/
3734 int rend_mid_establish_intro(or_circuit_t *circ, const char *request,
3735 size_t request_len);
3736 int rend_mid_introduce(or_circuit_t *circ, const char *request,
3737 size_t request_len);
3738 int rend_mid_establish_rendezvous(or_circuit_t *circ, const char *request,
3739 size_t request_len);
3740 int rend_mid_rendezvous(or_circuit_t *circ, const char *request,
3741 size_t request_len);
3743 /********************************* router.c ***************************/
3745 crypto_pk_env_t *get_onion_key(void);
3746 time_t get_onion_key_set_at(void);
3747 void set_identity_key(crypto_pk_env_t *k);
3748 crypto_pk_env_t *get_identity_key(void);
3749 int identity_key_is_set(void);
3750 authority_cert_t *get_my_v3_authority_cert(void);
3751 crypto_pk_env_t *get_my_v3_authority_signing_key(void);
3752 void dup_onion_keys(crypto_pk_env_t **key, crypto_pk_env_t **last);
3753 void rotate_onion_key(void);
3754 crypto_pk_env_t *init_key_from_file(const char *fname, int generate,
3755 int severity);
3756 void v3_authority_check_key_expiry(void);
3758 int init_keys(void);
3760 int check_whether_orport_reachable(void);
3761 int check_whether_dirport_reachable(void);
3762 void consider_testing_reachability(int test_or, int test_dir);
3763 void router_orport_found_reachable(void);
3764 void router_dirport_found_reachable(void);
3765 void router_perform_bandwidth_test(int num_circs, time_t now);
3767 int authdir_mode(or_options_t *options);
3768 int authdir_mode_v1(or_options_t *options);
3769 int authdir_mode_v2(or_options_t *options);
3770 int authdir_mode_v3(or_options_t *options);
3771 int authdir_mode_any_main(or_options_t *options);
3772 int authdir_mode_any_nonhidserv(or_options_t *options);
3773 int authdir_mode_handles_descs(or_options_t *options, int purpose);
3774 int authdir_mode_publishes_statuses(or_options_t *options);
3775 int authdir_mode_tests_reachability(or_options_t *options);
3776 int authdir_mode_bridge(or_options_t *options);
3778 int clique_mode(or_options_t *options);
3779 int server_mode(or_options_t *options);
3780 int advertised_server_mode(void);
3781 int proxy_mode(or_options_t *options);
3782 void consider_publishable_server(int force);
3784 int router_is_clique_mode(routerinfo_t *router);
3785 void router_upload_dir_desc_to_dirservers(int force);
3786 void mark_my_descriptor_dirty_if_older_than(time_t when);
3787 void mark_my_descriptor_dirty(void);
3788 void check_descriptor_bandwidth_changed(time_t now);
3789 void check_descriptor_ipaddress_changed(time_t now);
3790 void router_new_address_suggestion(const char *suggestion,
3791 const dir_connection_t *d_conn);
3792 int router_compare_to_my_exit_policy(edge_connection_t *conn);
3793 routerinfo_t *router_get_my_routerinfo(void);
3794 extrainfo_t *router_get_my_extrainfo(void);
3795 const char *router_get_my_descriptor(void);
3796 int router_digest_is_me(const char *digest);
3797 int router_is_me(routerinfo_t *router);
3798 int router_fingerprint_is_me(const char *fp);
3799 int router_pick_published_address(or_options_t *options, uint32_t *addr);
3800 int router_rebuild_descriptor(int force);
3801 int router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
3802 crypto_pk_env_t *ident_key);
3803 int extrainfo_dump_to_string(char *s, size_t maxlen, extrainfo_t *extrainfo,
3804 crypto_pk_env_t *ident_key);
3805 int is_legal_nickname(const char *s);
3806 int is_legal_nickname_or_hexdigest(const char *s);
3807 int is_legal_hexdigest(const char *s);
3808 void router_get_verbose_nickname(char *buf, routerinfo_t *router);
3809 void router_reset_warnings(void);
3810 void router_reset_reachability(void);
3811 void router_free_all(void);
3813 const char *router_purpose_to_string(uint8_t p);
3814 uint8_t router_purpose_from_string(const char *s);
3816 #ifdef ROUTER_PRIVATE
3817 /* Used only by router.c and test.c */
3818 void get_platform_str(char *platform, size_t len);
3819 #endif
3821 /********************************* routerlist.c ***************************/
3823 /** Represents information about a single trusted directory server. */
3824 typedef struct trusted_dir_server_t {
3825 char *description;
3826 char *nickname;
3827 char *address; /**< Hostname. */
3828 uint32_t addr; /**< IPv4 address. */
3829 uint16_t dir_port; /**< Directory port. */
3830 uint16_t or_port; /**< OR port: Used for tunneling connections. */
3831 char digest[DIGEST_LEN]; /**< Digest of identity key. */
3832 char v3_identity_digest[DIGEST_LEN]; /**< Digest of v3 (authority only,
3833 * high-security) identity key. */
3835 unsigned int is_running:1; /**< True iff we think this server is running. */
3837 /** True iff this server has accepted the most recent server descriptor
3838 * we tried to upload to it. */
3839 unsigned int has_accepted_serverdesc:1;
3841 /** What kind of authority is this? (Bitfield.) */
3842 authority_type_t type;
3844 download_status_t v2_ns_dl_status; /**< Status of downloading this server's
3845 * v2 network status. */
3846 time_t addr_current_at; /**< When was the document that we derived the
3847 * address information from published? */
3849 routerstatus_t fake_status; /**< Used when we need to pass this trusted
3850 * dir_server_t to directory_initiate_command_*
3851 * as a routerstatus_t. Not updated by the
3852 * router-status management code!
3854 } trusted_dir_server_t;
3856 #define ROUTER_REQUIRED_MIN_BANDWIDTH 10000
3858 #define ROUTER_MAX_DECLARED_BANDWIDTH INT32_MAX
3860 int get_n_authorities(authority_type_t type);
3861 int trusted_dirs_reload_certs(void);
3862 int trusted_dirs_load_certs_from_string(const char *contents, int from_store,
3863 int flush);
3864 void trusted_dirs_flush_certs_to_disk(void);
3865 authority_cert_t *authority_cert_get_newest_by_id(const char *id_digest);
3866 authority_cert_t *authority_cert_get_by_sk_digest(const char *sk_digest);
3867 authority_cert_t *authority_cert_get_by_digests(const char *id_digest,
3868 const char *sk_digest);
3869 void authority_cert_get_all(smartlist_t *certs_out);
3870 void authority_cert_dl_failed(const char *id_digest, int status);
3871 void authority_certs_fetch_missing(networkstatus_t *status, time_t now);
3872 int router_reload_router_list(void);
3873 smartlist_t *router_get_trusted_dir_servers(void);
3875 /* Flags for pick_directory_server and pick_trusteddirserver. */
3876 #define PDS_ALLOW_SELF (1<<0)
3877 #define PDS_RETRY_IF_NO_SERVERS (1<<1)
3878 #define PDS_IGNORE_FASCISTFIREWALL (1<<2)
3879 #define _PDS_PREFER_TUNNELED_DIR_CONNS (1<<16)
3880 routerstatus_t *router_pick_directory_server(authority_type_t type, int flags);
3881 trusted_dir_server_t *router_get_trusteddirserver_by_digest(const char *d);
3882 trusted_dir_server_t *trusteddirserver_get_by_v3_auth_digest(const char *d);
3883 routerstatus_t *router_pick_trusteddirserver(authority_type_t type, int flags);
3884 void router_reset_status_download_failures(void);
3885 void routerlist_add_family(smartlist_t *sl, routerinfo_t *router);
3886 int routers_in_same_family(routerinfo_t *r1, routerinfo_t *r2);
3887 void add_nickname_list_to_smartlist(smartlist_t *sl, const char *list,
3888 int must_be_running);
3889 int router_nickname_is_in_list(routerinfo_t *router, const char *list);
3890 routerinfo_t *routerlist_find_my_routerinfo(void);
3891 routerinfo_t *router_find_exact_exit_enclave(const char *address,
3892 uint16_t port);
3893 int router_is_unreliable(routerinfo_t *router, int need_uptime,
3894 int need_capacity, int need_guard);
3895 uint32_t router_get_advertised_bandwidth(routerinfo_t *router);
3897 typedef enum {
3898 NO_WEIGHTING, WEIGHT_FOR_EXIT, WEIGHT_FOR_GUARD
3899 } bandwidth_weight_rule_t;
3900 routerinfo_t *routerlist_sl_choose_by_bandwidth(smartlist_t *sl,
3901 bandwidth_weight_rule_t rule);
3902 routerstatus_t *routerstatus_sl_choose_by_bandwidth(smartlist_t *sl);
3903 routerinfo_t *router_choose_random_node(const char *preferred,
3904 const char *excluded,
3905 smartlist_t *excludedsmartlist,
3906 int need_uptime, int need_capacity,
3907 int need_guard,
3908 int allow_invalid, int strict,
3909 int weight_for_exit);
3910 routerinfo_t *router_get_by_nickname(const char *nickname,
3911 int warn_if_unnamed);
3912 int router_digest_version_as_new_as(const char *digest, const char *cutoff);
3913 int router_digest_is_trusted_dir_type(const char *digest,
3914 authority_type_t type);
3915 #define router_digest_is_trusted_dir(d) \
3916 router_digest_is_trusted_dir_type((d), NO_AUTHORITY)
3918 int router_addr_is_trusted_dir(uint32_t addr);
3919 int hexdigest_to_digest(const char *hexdigest, char *digest);
3920 routerinfo_t *router_get_by_hexdigest(const char *hexdigest);
3921 routerinfo_t *router_get_by_digest(const char *digest);
3922 signed_descriptor_t *router_get_by_descriptor_digest(const char *digest);
3923 signed_descriptor_t *router_get_by_extrainfo_digest(const char *digest);
3924 signed_descriptor_t *extrainfo_get_by_descriptor_digest(const char *digest);
3925 const char *signed_descriptor_get_body(signed_descriptor_t *desc);
3926 const char *signed_descriptor_get_annotations(signed_descriptor_t *desc);
3927 routerlist_t *router_get_routerlist(void);
3928 void routerinfo_free(routerinfo_t *router);
3929 void extrainfo_free(extrainfo_t *extrainfo);
3930 void routerlist_free(routerlist_t *rl);
3931 void dump_routerlist_mem_usage(int severity);
3932 void routerlist_remove(routerlist_t *rl, routerinfo_t *ri, int make_old);
3933 void routerlist_free_all(void);
3934 void routerlist_reset_warnings(void);
3935 void router_set_status(const char *digest, int up);
3936 int router_add_to_routerlist(routerinfo_t *router, const char **msg,
3937 int from_cache, int from_fetch);
3938 int router_add_extrainfo_to_routerlist(extrainfo_t *ei, const char **msg,
3939 int from_cache, int from_fetch);
3940 void routerlist_remove_old_routers(void);
3941 int router_load_single_router(const char *s, uint8_t purpose, int cache,
3942 const char **msg);
3943 void router_load_routers_from_string(const char *s, const char *eos,
3944 saved_location_t saved_location,
3945 smartlist_t *requested_fingerprints,
3946 int descriptor_digests,
3947 const char *prepend_annotations);
3948 void router_load_extrainfo_from_string(const char *s, const char *eos,
3949 saved_location_t saved_location,
3950 smartlist_t *requested_fingerprints,
3951 int descriptor_digests);
3952 void routerlist_retry_directory_downloads(time_t now);
3953 int router_exit_policy_all_routers_reject(uint32_t addr, uint16_t port,
3954 int need_uptime);
3955 int router_exit_policy_rejects_all(routerinfo_t *router);
3956 trusted_dir_server_t *add_trusted_dir_server(const char *nickname,
3957 const char *address,
3958 uint16_t dir_port, uint16_t or_port,
3959 const char *digest, const char *v3_auth_digest,
3960 authority_type_t type);
3961 void authority_cert_free(authority_cert_t *cert);
3962 void clear_trusted_dir_servers(void);
3963 int any_trusted_dir_is_v1_authority(void);
3964 void update_router_descriptor_downloads(time_t now);
3965 void update_extrainfo_downloads(time_t now);
3966 int router_have_minimum_dir_info(void);
3967 void router_dir_info_changed(void);
3968 const char *get_dir_info_status_string(void);
3969 void router_reset_descriptor_download_failures(void);
3970 int router_differences_are_cosmetic(routerinfo_t *r1, routerinfo_t *r2);
3971 int routerinfo_incompatible_with_extrainfo(routerinfo_t *ri, extrainfo_t *ei,
3972 signed_descriptor_t *sd,
3973 const char **msg);
3974 void routerlist_assert_ok(routerlist_t *rl);
3975 const char *esc_router_info(routerinfo_t *router);
3976 void routers_sort_by_identity(smartlist_t *routers);
3978 int hid_serv_get_responsible_directories(smartlist_t *responsible_dirs,
3979 const char *id);
3980 int hid_serv_acting_as_directory(void);
3981 int hid_serv_responsible_for_desc_id(const char *id);
3983 /********************************* routerparse.c ************************/
3985 #define MAX_STATUS_TAG_LEN 32
3986 /** Structure to hold parsed Tor versions. This is a little messier
3987 * than we would like it to be, because we changed version schemes with 0.1.0.
3989 * See version-spec.txt for the whole business.
3991 typedef struct tor_version_t {
3992 int major;
3993 int minor;
3994 int micro;
3995 /** Release status. For version in the post-0.1 format, this is always
3996 * VER_RELEASE. */
3997 enum { VER_PRE=0, VER_RC=1, VER_RELEASE=2, } status;
3998 int patchlevel;
3999 char status_tag[MAX_STATUS_TAG_LEN];
4000 int svn_revision;
4001 } tor_version_t;
4003 int router_get_router_hash(const char *s, char *digest);
4004 int router_get_dir_hash(const char *s, char *digest);
4005 int router_get_runningrouters_hash(const char *s, char *digest);
4006 int router_get_networkstatus_v2_hash(const char *s, char *digest);
4007 int router_get_networkstatus_v3_hash(const char *s, char *digest);
4008 int router_get_extrainfo_hash(const char *s, char *digest);
4009 int router_append_dirobj_signature(char *buf, size_t buf_len,
4010 const char *digest,
4011 crypto_pk_env_t *private_key);
4012 int router_parse_list_from_string(const char **s, const char *eos,
4013 smartlist_t *dest,
4014 saved_location_t saved_location,
4015 int is_extrainfo,
4016 int allow_annotations,
4017 const char *prepend_annotations);
4018 int router_parse_routerlist_from_directory(const char *s,
4019 routerlist_t **dest,
4020 crypto_pk_env_t *pkey,
4021 int check_version,
4022 int write_to_cache);
4023 int router_parse_runningrouters(const char *str);
4024 int router_parse_directory(const char *str);
4025 routerinfo_t *router_parse_entry_from_string(const char *s, const char *end,
4026 int cache_copy,
4027 int allow_annotations,
4028 const char *prepend_annotations);
4029 extrainfo_t *extrainfo_parse_entry_from_string(const char *s, const char *end,
4030 int cache_copy, struct digest_ri_map_t *routermap);
4031 addr_policy_t *router_parse_addr_policy_item_from_string(const char *s,
4032 int assume_action);
4033 version_status_t tor_version_is_obsolete(const char *myversion,
4034 const char *versionlist);
4035 int tor_version_parse(const char *s, tor_version_t *out);
4036 int tor_version_as_new_as(const char *platform, const char *cutoff);
4037 int tor_version_compare(tor_version_t *a, tor_version_t *b);
4038 void sort_version_list(smartlist_t *lst, int remove_duplicates);
4039 void assert_addr_policy_ok(smartlist_t *t);
4040 void dump_distinct_digest_count(int severity);
4042 networkstatus_v2_t *networkstatus_v2_parse_from_string(const char *s);
4043 networkstatus_t *networkstatus_parse_vote_from_string(const char *s,
4044 const char **eos_out,
4045 int is_vote);
4046 ns_detached_signatures_t *networkstatus_parse_detached_signatures(
4047 const char *s, const char *eos);
4049 authority_cert_t *authority_cert_parse_from_string(const char *s,
4050 const char **end_of_string);
4051 int rend_parse_v2_service_descriptor(rend_service_descriptor_t **parsed_out,
4052 char *desc_id_out,
4053 char **intro_points_encrypted_out,
4054 size_t *intro_points_encrypted_size_out,
4055 size_t *encoded_size_out,
4056 const char **next_out, const char *desc);
4057 int rend_decrypt_introduction_points(rend_service_descriptor_t *parsed,
4058 const char *descriptor_cookie,
4059 const char *intro_content,
4060 size_t intro_size);
4062 #endif