Fix an assert error introduced in 0.1.2.5-alpha: if a single TLS
[tor.git] / src / or / or.h
blobb4d2d8c51d6977af7192f42882e8ae3adcff7b92
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
5 /* $Id$ */
7 /**
8 * \file or.h
9 * \brief Master header file for Tor-specific functionality.
10 **/
12 #ifndef __OR_H
13 #define __OR_H
14 #define OR_H_ID "$Id$"
16 #include "orconfig.h"
17 #ifdef MS_WINDOWS
18 #define WIN32_WINNT 0x400
19 #define _WIN32_WINNT 0x400
20 #define WIN32_LEAN_AND_MEAN
21 #endif
23 #include <stdio.h>
24 #include <stdlib.h>
25 #ifdef HAVE_UNISTD_H
26 #include <unistd.h>
27 #endif
28 #ifdef HAVE_STRING_H
29 #include <string.h>
30 #endif
31 #ifdef HAVE_SIGNAL_H
32 #include <signal.h>
33 #endif
34 #ifdef HAVE_NETDB_H
35 #include <netdb.h>
36 #endif
37 #ifdef HAVE_CTYPE_H
38 #include <ctype.h>
39 #endif
40 #ifdef HAVE_SYS_PARAM_H
41 #include <sys/param.h> /* FreeBSD needs this to know what version it is */
42 #endif
43 #include "../common/torint.h"
44 #ifdef HAVE_SYS_WAIT_H
45 #include <sys/wait.h>
46 #endif
47 #ifdef HAVE_SYS_FCNTL_H
48 #include <sys/fcntl.h>
49 #endif
50 #ifdef HAVE_FCNTL_H
51 #include <fcntl.h>
52 #endif
53 #ifdef HAVE_SYS_IOCTL_H
54 #include <sys/ioctl.h>
55 #endif
56 #ifdef HAVE_SYS_SOCKET_H
57 #include <sys/socket.h>
58 #endif
59 #ifdef HAVE_SYS_TIME_H
60 #include <sys/time.h>
61 #endif
62 #ifdef HAVE_SYS_STAT_H
63 #include <sys/stat.h>
64 #endif
65 #ifdef HAVE_NETINET_IN_H
66 #include <netinet/in.h>
67 #endif
68 #ifdef HAVE_ARPA_INET_H
69 #include <arpa/inet.h>
70 #endif
71 #ifdef HAVE_ERRNO_H
72 #include <errno.h>
73 #endif
74 #ifdef HAVE_ASSERT_H
75 #include <assert.h>
76 #endif
77 #ifdef HAVE_TIME_H
78 #include <time.h>
79 #endif
81 /** Upper bound on maximum simultaneous connections; can be lowered by
82 * config file. */
83 #if defined(CYGWIN) || defined(__CYGWIN__)
84 /* http://archives.seul.org/or/talk/Aug-2006/msg00210.html */
85 #define MAXCONNECTIONS 3200
86 #else
87 /* very high by default. "nobody should need more than this..." */
88 #define MAXCONNECTIONS 15000
89 #endif
91 #ifdef MS_WINDOWS
92 /* No, we don't need to redefine FD_SETSIZE before including winsock:
93 * we use libevent now, and libevent handles the select() stuff. Yes,
94 * some documents imply that we need to redefine anyway if we're using
95 * select() anywhere in our application or in anything it links to: these
96 * documents are either the holy texts of a cargo cult of network
97 * programmers, or more likely a simplification of what's going on for
98 * people who haven't read winsock[2].c for themselves.
100 #if (_MSC_VER <= 1300)
101 #include <winsock.h>
102 #else
103 #include <winsock2.h>
104 #include <ws2tcpip.h>
105 #endif
106 #endif
108 #ifdef MS_WINDOWS
109 #include <io.h>
110 #include <process.h>
111 #include <direct.h>
112 #include <windows.h>
113 #define snprintf _snprintf
114 #endif
116 #ifdef HAVE_EVENT_H
117 #include <event.h>
118 #else
119 #error "Tor requires libevent to build."
120 #endif
122 #include "../common/crypto.h"
123 #include "../common/tortls.h"
124 #include "../common/log.h"
125 #include "../common/compat.h"
126 #include "../common/container.h"
127 #include "../common/util.h"
128 #include "../common/torgzip.h"
130 /* These signals are defined to help control_signal_act work.
132 #ifndef SIGHUP
133 #define SIGHUP 1
134 #endif
135 #ifndef SIGINT
136 #define SIGINT 2
137 #endif
138 #ifndef SIGUSR1
139 #define SIGUSR1 10
140 #endif
141 #ifndef SIGUSR2
142 #define SIGUSR2 12
143 #endif
144 #ifndef SIGTERM
145 #define SIGTERM 15
146 #endif
147 /* Controller signals start at a high number so we don't
148 * conflict with system-defined signals. */
149 #define SIGNEWNYM 129
150 #define SIGCLEARDNSCACHE 130
152 #if (SIZEOF_CELL_T != 0)
153 /* On Irix, stdlib.h defines a cell_t type, so we need to make sure
154 * that our stuff always calls cell_t something different. */
155 #define cell_t tor_cell_t
156 #endif
158 #define MAX_NICKNAME_LEN 19
159 /* Hex digest plus dollar sign. */
160 #define MAX_HEX_NICKNAME_LEN (HEX_DIGEST_LEN+1)
161 /* $Hexdigest=nickname */
162 #define MAX_VERBOSE_NICKNAME_LEN (1+HEX_DIGEST_LEN+1+MAX_NICKNAME_LEN)
164 /** Maximum size, in bytes, for resized buffers. */
165 #define MAX_BUF_SIZE ((1<<24)-1)
166 #define MAX_DIR_SIZE MAX_BUF_SIZE
168 /* For http parsing */
169 #define MAX_HEADERS_SIZE 50000
170 #define MAX_BODY_SIZE 500000
172 /** How long do we keep DNS cache entries before purging them (regardless of
173 * their TTL)? */
174 #define MAX_DNS_ENTRY_AGE (30*60)
175 #define DEFAULT_DNS_TTL (30*60)
176 /** How long can a TTL be before we stop believing it? */
177 #define MAX_DNS_TTL (3*60*60)
178 /** How small can a TTL be before we stop believing it? */
179 #define MIN_DNS_TTL (60)
181 /** How often do we rotate onion keys? */
182 #define MIN_ONION_KEY_LIFETIME (7*24*60*60)
183 /** How often do we rotate TLS contexts? */
184 #define MAX_SSL_KEY_LIFETIME (2*60*60)
186 /** How old do we allow a router to get before removing it
187 * from the router list? In seconds. */
188 #define ROUTER_MAX_AGE (60*60*48)
189 /** How old can a router get before we (as a server) will no longer
190 * consider it live? In seconds. */
191 #define ROUTER_MAX_AGE_TO_PUBLISH (60*60*20)
192 /** How old do we let a saved descriptor get before force-removing it? */
193 #define OLD_ROUTER_DESC_MAX_AGE (60*60*24*5)
194 /** How old do we let a networkstatus get before ignoring it? */
195 #define NETWORKSTATUS_MAX_AGE (60*60*24)
197 typedef enum {
198 CIRC_ID_TYPE_LOWER=0,
199 CIRC_ID_TYPE_HIGHER=1
200 } circ_id_type_t;
202 #define _CONN_TYPE_MIN 3
203 /** Type for sockets listening for OR connections. */
204 #define CONN_TYPE_OR_LISTENER 3
205 /** A bidirectional TLS connection transmitting a sequence of cells.
206 * May be from an OR to an OR, or from an OP to an OR. */
207 #define CONN_TYPE_OR 4
208 /** A TCP connection from an onion router to a stream's destination. */
209 #define CONN_TYPE_EXIT 5
210 /** Type for sockets listening for SOCKS connections. */
211 #define CONN_TYPE_AP_LISTENER 6
212 /** A SOCKS proxy connection from the user application to the onion
213 * proxy. */
214 #define CONN_TYPE_AP 7
215 /** Type for sockets listening for HTTP connections to the directory server. */
216 #define CONN_TYPE_DIR_LISTENER 8
217 /** Type for HTTP connections to the directory server. */
218 #define CONN_TYPE_DIR 9
219 /** Connection from the main process to a DNS worker process. */
220 #define CONN_TYPE_DNSWORKER 10
221 /** Connection from the main process to a CPU worker process. */
222 #define CONN_TYPE_CPUWORKER 11
223 /** Type for listening for connections from user interface process. */
224 #define CONN_TYPE_CONTROL_LISTENER 12
225 /** Type for connections from user interface process. */
226 #define CONN_TYPE_CONTROL 13
227 /** Type for sockets listening for transparent connections redirected by pf or
228 * netfilter. */
229 #define CONN_TYPE_AP_TRANS_LISTENER 14
230 /** Type for sockets listening for transparent connections redirected by
231 * natd. */
232 #define CONN_TYPE_AP_NATD_LISTENER 15
233 #define _CONN_TYPE_MAX 15
235 #define CONN_IS_EDGE(x) \
236 ((x)->type == CONN_TYPE_EXIT || (x)->type == CONN_TYPE_AP)
238 /** State for any listener connection. */
239 #define LISTENER_STATE_READY 0
241 #define _DNSWORKER_STATE_MIN 1
242 /** State for a connection to a dnsworker process that's idle. */
243 #define DNSWORKER_STATE_IDLE 1
244 /** State for a connection to a dnsworker process that's resolving a
245 * hostname. */
246 #define DNSWORKER_STATE_BUSY 2
247 #define _DNSWORKER_STATE_MAX 2
249 #define _CPUWORKER_STATE_MIN 1
250 /** State for a connection to a cpuworker process that's idle. */
251 #define CPUWORKER_STATE_IDLE 1
252 /** State for a connection to a cpuworker process that's processing a
253 * handshake. */
254 #define CPUWORKER_STATE_BUSY_ONION 2
255 #define _CPUWORKER_STATE_MAX 2
257 #define CPUWORKER_TASK_ONION CPUWORKER_STATE_BUSY_ONION
259 #define _OR_CONN_STATE_MIN 1
260 /** State for a connection to an OR: waiting for connect() to finish. */
261 #define OR_CONN_STATE_CONNECTING 1
262 /** State for a connection to an OR: waiting for proxy command to flush. */
263 #define OR_CONN_STATE_PROXY_FLUSHING 2
264 /** State for a connection to an OR: waiting for proxy response. */
265 #define OR_CONN_STATE_PROXY_READING 3
266 /** State for a connection to an OR: SSL is handshaking, not done yet. */
267 #define OR_CONN_STATE_HANDSHAKING 4
268 /** State for a connection to an OR: Ready to send/receive cells. */
269 #define OR_CONN_STATE_OPEN 5
270 #define _OR_CONN_STATE_MAX 5
272 #define _EXIT_CONN_STATE_MIN 1
273 /** State for an exit connection: waiting for response from dns farm. */
274 #define EXIT_CONN_STATE_RESOLVING 1
275 /** State for an exit connection: waiting for connect() to finish. */
276 #define EXIT_CONN_STATE_CONNECTING 2
277 /** State for an exit connection: open and ready to transmit data. */
278 #define EXIT_CONN_STATE_OPEN 3
279 /** State for an exit connection: waiting to be removed. */
280 #define EXIT_CONN_STATE_RESOLVEFAILED 4
281 #define _EXIT_CONN_STATE_MAX 4
283 /* the AP state values must be disjoint from the EXIT state values */
284 #define _AP_CONN_STATE_MIN 5
285 /** State for a SOCKS connection: waiting for SOCKS request. */
286 #define AP_CONN_STATE_SOCKS_WAIT 5
287 /** State for a SOCKS connection: got a y.onion URL; waiting to receive
288 * rendezvous descriptor. */
289 #define AP_CONN_STATE_RENDDESC_WAIT 6
290 /** The controller will attach this connection to a circuit; it isn't our
291 * job to do so. */
292 #define AP_CONN_STATE_CONTROLLER_WAIT 7
293 /** State for a SOCKS connection: waiting for a completed circuit. */
294 #define AP_CONN_STATE_CIRCUIT_WAIT 8
295 /** State for a SOCKS connection: sent BEGIN, waiting for CONNECTED. */
296 #define AP_CONN_STATE_CONNECT_WAIT 9
297 /** State for a SOCKS connection: send RESOLVE, waiting for RESOLVED. */
298 #define AP_CONN_STATE_RESOLVE_WAIT 10
299 /** State for a SOCKS connection: ready to send and receive. */
300 #define AP_CONN_STATE_OPEN 11
301 /** State for a transparent natd connection: waiting for original
302 * destination. */
303 #define AP_CONN_STATE_NATD_WAIT 12
304 #define _AP_CONN_STATE_MAX 12
306 #define _DIR_CONN_STATE_MIN 1
307 /** State for connection to directory server: waiting for connect(). */
308 #define DIR_CONN_STATE_CONNECTING 1
309 /** State for connection to directory server: sending HTTP request. */
310 #define DIR_CONN_STATE_CLIENT_SENDING 2
311 /** State for connection to directory server: reading HTTP response. */
312 #define DIR_CONN_STATE_CLIENT_READING 3
313 /** State for connection to directory server: happy and finished. */
314 #define DIR_CONN_STATE_CLIENT_FINISHED 4
315 /** State for connection at directory server: waiting for HTTP request. */
316 #define DIR_CONN_STATE_SERVER_COMMAND_WAIT 5
317 /** State for connection at directory server: sending HTTP response. */
318 #define DIR_CONN_STATE_SERVER_WRITING 6
319 #define _DIR_CONN_STATE_MAX 6
321 #define DIR_CONN_IS_SERVER(conn) ((conn)->purpose == DIR_PURPOSE_SERVER)
323 #define _CONTROL_CONN_STATE_MIN 1
324 #define CONTROL_CONN_STATE_OPEN_V0 1
325 #define CONTROL_CONN_STATE_OPEN_V1 2
326 #define CONTROL_CONN_STATE_NEEDAUTH_V0 3
327 #define CONTROL_CONN_STATE_NEEDAUTH_V1 4
328 #define _CONTROL_CONN_STATE_MAX 4
330 #define _DIR_PURPOSE_MIN 1
331 /** A connection to a directory server: download a directory. */
332 #define DIR_PURPOSE_FETCH_DIR 1
333 /** A connection to a directory server: download just the list
334 * of running routers. */
335 #define DIR_PURPOSE_FETCH_RUNNING_LIST 2
336 /** A connection to a directory server: download a rendezvous
337 * descriptor. */
338 #define DIR_PURPOSE_FETCH_RENDDESC 3
339 /** A connection to a directory server: set after a rendezvous
340 * descriptor is downloaded. */
341 #define DIR_PURPOSE_HAS_FETCHED_RENDDESC 4
342 /** A connection to a directory server: download one or more network-status
343 * objects */
344 #define DIR_PURPOSE_FETCH_NETWORKSTATUS 5
345 /** A connection to a directory server: download one or more server
346 * descriptors. */
347 #define DIR_PURPOSE_FETCH_SERVERDESC 6
348 /** A connection to a directory server: upload a server descriptor. */
349 #define DIR_PURPOSE_UPLOAD_DIR 7
350 /** A connection to a directory server: upload a rendezvous
351 * descriptor. */
352 #define DIR_PURPOSE_UPLOAD_RENDDESC 8
353 /** Purpose for connection at a directory server. */
354 #define DIR_PURPOSE_SERVER 9
355 #define _DIR_PURPOSE_MAX 9
357 #define _EXIT_PURPOSE_MIN 1
358 /** This exit stream wants to do an ordinary connect. */
359 #define EXIT_PURPOSE_CONNECT 1
360 /** This exit stream wants to do a resolve (either normal or reverse). */
361 #define EXIT_PURPOSE_RESOLVE 2
362 #define _EXIT_PURPOSE_MAX 2
364 /** Circuit state: I'm the origin, still haven't done all my handshakes. */
365 #define CIRCUIT_STATE_BUILDING 0
366 /** Circuit state: Waiting to process the onionskin. */
367 #define CIRCUIT_STATE_ONIONSKIN_PENDING 1
368 /** Circuit state: I'd like to deliver a create, but my n_conn is still
369 * connecting. */
370 #define CIRCUIT_STATE_OR_WAIT 2
371 /** Circuit state: onionskin(s) processed, ready to send/receive cells. */
372 #define CIRCUIT_STATE_OPEN 3
374 #define _CIRCUIT_PURPOSE_MIN 1
376 /* these circuits were initiated elsewhere */
377 #define _CIRCUIT_PURPOSE_OR_MIN 1
378 /** OR-side circuit purpose: normal circuit, at OR. */
379 #define CIRCUIT_PURPOSE_OR 1
380 /** OR-side circuit purpose: At OR, from Bob, waiting for intro from Alices. */
381 #define CIRCUIT_PURPOSE_INTRO_POINT 2
382 /** OR-side circuit purpose: At OR, from Alice, waiting for Bob. */
383 #define CIRCUIT_PURPOSE_REND_POINT_WAITING 3
384 /** OR-side circuit purpose: At OR, both circuits have this purpose. */
385 #define CIRCUIT_PURPOSE_REND_ESTABLISHED 4
386 #define _CIRCUIT_PURPOSE_OR_MAX 4
388 /* these circuits originate at this node */
390 /* here's how circ client-side purposes work:
391 * normal circuits are C_GENERAL.
392 * circuits that are c_introducing are either on their way to
393 * becoming open, or they are open and waiting for a
394 * suitable rendcirc before they send the intro.
395 * circuits that are c_introduce_ack_wait have sent the intro,
396 * but haven't gotten a response yet.
397 * circuits that are c_establish_rend are either on their way
398 * to becoming open, or they are open and have sent the
399 * establish_rendezvous cell but haven't received an ack.
400 * circuits that are c_rend_ready are open and have received a
401 * rend ack, but haven't heard from bob yet. if they have a
402 * buildstate->pending_final_cpath then they're expecting a
403 * cell from bob, else they're not.
404 * circuits that are c_rend_ready_intro_acked are open, and
405 * some intro circ has sent its intro and received an ack.
406 * circuits that are c_rend_joined are open, have heard from
407 * bob, and are talking to him.
409 /** Client-side circuit purpose: Normal circuit, with cpath. */
410 #define CIRCUIT_PURPOSE_C_GENERAL 5
411 /** Client-side circuit purpose: at Alice, connecting to intro point. */
412 #define CIRCUIT_PURPOSE_C_INTRODUCING 6
413 /** Client-side circuit purpose: at Alice, sent INTRODUCE1 to intro point,
414 * waiting for ACK/NAK. */
415 #define CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT 7
416 /** Client-side circuit purpose: at Alice, introduced and acked, closing. */
417 #define CIRCUIT_PURPOSE_C_INTRODUCE_ACKED 8
418 /** Client-side circuit purpose: at Alice, waiting for ack. */
419 #define CIRCUIT_PURPOSE_C_ESTABLISH_REND 9
420 /** Client-side circuit purpose: at Alice, waiting for Bob. */
421 #define CIRCUIT_PURPOSE_C_REND_READY 10
422 /** Client-side circuit purpose: at Alice, waiting for Bob, INTRODUCE
423 * has been acknowledged. */
424 #define CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED 11
425 /** Client-side circuit purpose: at Alice, rendezvous established. */
426 #define CIRCUIT_PURPOSE_C_REND_JOINED 12
428 /** Hidden-service-side circuit purpose: at Bob, waiting for introductions. */
429 #define CIRCUIT_PURPOSE_S_ESTABLISH_INTRO 13
430 /** Hidden-service-side circuit purpose: at Bob, successfully established
431 * intro. */
432 #define CIRCUIT_PURPOSE_S_INTRO 14
433 /** Hidden-service-side circuit purpose: at Bob, connecting to rend point. */
434 #define CIRCUIT_PURPOSE_S_CONNECT_REND 15
435 /** Hidden-service-side circuit purpose: at Bob, rendezvous established. */
436 #define CIRCUIT_PURPOSE_S_REND_JOINED 16
437 /** A testing circuit; not meant to be used for actual traffic. */
438 #define CIRCUIT_PURPOSE_TESTING 17
439 /** A controller made this circuit and Tor should not use it. */
440 #define CIRCUIT_PURPOSE_CONTROLLER 18
441 #define _CIRCUIT_PURPOSE_MAX 18
443 /** True iff the circuit purpose <b>p</b> is for a circuit that
444 * originated at this node. */
445 #define CIRCUIT_PURPOSE_IS_ORIGIN(p) ((p)>_CIRCUIT_PURPOSE_OR_MAX)
446 #define CIRCUIT_IS_ORIGIN(c) (CIRCUIT_PURPOSE_IS_ORIGIN((c)->purpose))
448 /** How many circuits do we want simultaneously in-progress to handle
449 * a given stream? */
450 #define MIN_CIRCUITS_HANDLING_STREAM 2
452 #define RELAY_COMMAND_BEGIN 1
453 #define RELAY_COMMAND_DATA 2
454 #define RELAY_COMMAND_END 3
455 #define RELAY_COMMAND_CONNECTED 4
456 #define RELAY_COMMAND_SENDME 5
457 #define RELAY_COMMAND_EXTEND 6
458 #define RELAY_COMMAND_EXTENDED 7
459 #define RELAY_COMMAND_TRUNCATE 8
460 #define RELAY_COMMAND_TRUNCATED 9
461 #define RELAY_COMMAND_DROP 10
462 #define RELAY_COMMAND_RESOLVE 11
463 #define RELAY_COMMAND_RESOLVED 12
464 #define RELAY_COMMAND_BEGIN_DIR 13
466 #define RELAY_COMMAND_ESTABLISH_INTRO 32
467 #define RELAY_COMMAND_ESTABLISH_RENDEZVOUS 33
468 #define RELAY_COMMAND_INTRODUCE1 34
469 #define RELAY_COMMAND_INTRODUCE2 35
470 #define RELAY_COMMAND_RENDEZVOUS1 36
471 #define RELAY_COMMAND_RENDEZVOUS2 37
472 #define RELAY_COMMAND_INTRO_ESTABLISHED 38
473 #define RELAY_COMMAND_RENDEZVOUS_ESTABLISHED 39
474 #define RELAY_COMMAND_INTRODUCE_ACK 40
476 /* Reasons why we (or a remote OR) might close a stream. See tor-spec.txt for
477 * documentation of these. */
478 #define END_STREAM_REASON_MISC 1
479 #define END_STREAM_REASON_RESOLVEFAILED 2
480 #define END_STREAM_REASON_CONNECTREFUSED 3
481 #define END_STREAM_REASON_EXITPOLICY 4
482 #define END_STREAM_REASON_DESTROY 5
483 #define END_STREAM_REASON_DONE 6
484 #define END_STREAM_REASON_TIMEOUT 7
485 /* 8 is unallocated. */
486 #define END_STREAM_REASON_HIBERNATING 9
487 #define END_STREAM_REASON_INTERNAL 10
488 #define END_STREAM_REASON_RESOURCELIMIT 11
489 #define END_STREAM_REASON_CONNRESET 12
490 #define END_STREAM_REASON_TORPROTOCOL 13
491 #define END_STREAM_REASON_NOTDIRECTORY 14
493 /* These high-numbered end reasons are not part of the official spec,
494 * and are not intended to be put in relay end cells. They are here
495 * to be more informative when sending back socks replies to the
496 * application. */
497 #define END_STREAM_REASON_ALREADY_SOCKS_REPLIED 256
498 #define END_STREAM_REASON_CANT_ATTACH 257
499 #define END_STREAM_REASON_NET_UNREACHABLE 258
500 #define END_STREAM_REASON_SOCKSPROTOCOL 259
501 #define END_STREAM_REASON_CANT_FETCH_ORIG_DEST 260
502 #define END_STREAM_REASON_INVALID_NATD_DEST 261
504 /* OR this with the argument to control_event_stream_status to indicate that
505 * the reason came from an END cell. */
506 #define END_STREAM_REASON_FLAG_REMOTE 512
508 #define RESOLVED_TYPE_HOSTNAME 0
509 #define RESOLVED_TYPE_IPV4 4
510 #define RESOLVED_TYPE_IPV6 6
511 #define RESOLVED_TYPE_ERROR_TRANSIENT 0xF0
512 #define RESOLVED_TYPE_ERROR 0xF1
514 /* DOCDOC We should document the meaning of these. */
515 /* Negative reasons are internal */
516 #define END_CIRC_REASON_NOPATH -2
517 #define END_CIRC_AT_ORIGIN -1
519 /* Reasons why we (or a remote OR) might close a circuit. See tor-spec.txt for
520 * documentation of these. */
521 #define _END_CIRC_REASON_MIN 0
522 #define END_CIRC_REASON_NONE 0
523 #define END_CIRC_REASON_TORPROTOCOL 1
524 #define END_CIRC_REASON_INTERNAL 2
525 #define END_CIRC_REASON_REQUESTED 3
526 #define END_CIRC_REASON_HIBERNATING 4
527 #define END_CIRC_REASON_RESOURCELIMIT 5
528 #define END_CIRC_REASON_CONNECTFAILED 6
529 #define END_CIRC_REASON_OR_IDENTITY 7
530 #define END_CIRC_REASON_OR_CONN_CLOSED 8
531 #define END_CIRC_REASON_FINISHED 9
532 #define END_CIRC_REASON_TIMEOUT 10
533 #define END_CIRC_REASON_DESTROYED 11
534 #define END_CIRC_REASON_NOSUCHSERVICE 12
535 #define _END_CIRC_REASON_MAX 12
537 /* OR this with the argument to circuit_mark_for_close, or
538 * control_event_circuit_status to indicate that the reason came from a
539 * destroy or truncate cell. */
540 #define END_CIRC_REASON_FLAG_REMOTE 512
542 /** Length of 'y' portion of 'y.onion' URL. */
543 #define REND_SERVICE_ID_LEN 16
545 #define CELL_DIRECTION_IN 1
546 #define CELL_DIRECTION_OUT 2
548 #ifdef TOR_PERF
549 #define CIRCWINDOW_START 10000
550 #define CIRCWINDOW_INCREMENT 1000
551 #define STREAMWINDOW_START 5000
552 #define STREAMWINDOW_INCREMENT 500
553 #else
554 #define CIRCWINDOW_START 1000
555 #define CIRCWINDOW_INCREMENT 100
556 #define STREAMWINDOW_START 500
557 #define STREAMWINDOW_INCREMENT 50
558 #endif
560 /* cell commands */
561 #define CELL_PADDING 0
562 #define CELL_CREATE 1
563 #define CELL_CREATED 2
564 #define CELL_RELAY 3
565 #define CELL_DESTROY 4
566 #define CELL_CREATE_FAST 5
567 #define CELL_CREATED_FAST 6
569 /** How long to test reachability before complaining to the user. */
570 #define TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT (20*60)
572 /* legal characters in a nickname */
573 #define LEGAL_NICKNAME_CHARACTERS \
574 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
576 /** Name to use in client TLS certificates if no nickname is given.*/
577 #define DEFAULT_CLIENT_NICKNAME "client"
579 #define SOCKS4_NETWORK_LEN 8
581 typedef enum {
582 SOCKS5_SUCCEEDED = 0x00,
583 SOCKS5_GENERAL_ERROR = 0x01,
584 SOCKS5_NOT_ALLOWED = 0x02,
585 SOCKS5_NET_UNREACHABLE = 0x03,
586 SOCKS5_HOST_UNREACHABLE = 0x04,
587 SOCKS5_CONNECTION_REFUSED = 0x05,
588 SOCKS5_TTL_EXPIRED = 0x06,
589 SOCKS5_COMMAND_NOT_SUPPORTED = 0x07,
590 SOCKS5_ADDRESS_TYPE_NOT_SUPPORTED = 0x08,
591 } socks5_reply_status_t;
594 * Relay payload:
595 * Relay command [1 byte]
596 * Recognized [2 bytes]
597 * Stream ID [2 bytes]
598 * Partial SHA-1 [4 bytes]
599 * Length [2 bytes]
600 * Relay payload [498 bytes]
603 #define CELL_PAYLOAD_SIZE 509
604 #define CELL_NETWORK_SIZE 512
606 #define RELAY_HEADER_SIZE (1+2+2+4+2)
607 #define RELAY_PAYLOAD_SIZE (CELL_PAYLOAD_SIZE-RELAY_HEADER_SIZE)
609 /** Parsed onion routing cell. All communication between nodes
610 * is via cells. */
611 typedef struct {
612 uint16_t circ_id; /**< Circuit which received the cell. */
613 uint8_t command; /**< Type of the cell: one of PADDING, CREATE, RELAY,
614 * or DESTROY. */
615 char payload[CELL_PAYLOAD_SIZE]; /**< Cell body. */
616 } cell_t;
618 /** Beginning of a RELAY cell payload. */
619 typedef struct {
620 uint8_t command; /**< The end-to-end relay command. */
621 uint16_t recognized; /**< Used to tell whether cell is for us. */
622 uint16_t stream_id; /**< Which stream is this cell associated with? */
623 char integrity[4]; /**< Used to tell whether cell is corrupted. */
624 uint16_t length; /**< How long is the payload body? */
625 } relay_header_t;
627 typedef struct buf_t buf_t;
628 typedef struct socks_request_t socks_request_t;
630 #define BASE_CONNECTION_MAGIC 0x7C3C304Eu
631 #define OR_CONNECTION_MAGIC 0x7D31FF03u
632 #define EDGE_CONNECTION_MAGIC 0xF0374013u
633 #define DIR_CONNECTION_MAGIC 0x9988ffeeu
634 #define CONTROL_CONNECTION_MAGIC 0x8abc765du
636 /** Description of a connection to another host or process, and associated
637 * data.
639 * A connection is named based on what it's connected to -- an "OR
640 * connection" has a Tor node on the other end, an "exit
641 * connection" has a website or other server on the other end, and an
642 * "AP connection" has an application proxy (and thus a user) on the
643 * other end.
645 * Every connection has a type and a state. Connections never change
646 * their type, but can go through many state changes in their lifetime.
648 * Every connection has two associated input and output buffers.
649 * Listeners don't use them. For non-listener connections, incoming
650 * data is appended to conn->inbuf, and outgoing data is taken from
651 * conn->outbuf. Connections differ primarily in the functions called
652 * to fill and drain these buffers.
654 typedef struct connection_t {
655 uint32_t magic; /**< For memory debugging: must equal one of
656 * *_CONNECTION_MAGIC. */
658 uint8_t type; /**< What kind of connection is this? */
659 uint8_t state; /**< Current state of this connection. */
660 uint8_t purpose; /**< Only used for DIR and EXIT types currently. */
662 /* The next fields are all one-bit booleans. Some are only applicable
663 * to connection subtypes, but we hold them here anyway, to save space.
664 * (Currently, they all fit into a single byte.) */
665 unsigned wants_to_read:1; /**< Boolean: should we start reading again once
666 * the bandwidth throttler allows it? */
667 unsigned wants_to_write:1; /**< Boolean: should we start writing again once
668 * the bandwidth throttler allows reads? */
669 unsigned hold_open_until_flushed:1; /**< Despite this connection's being
670 * marked for close, do we flush it
671 * before closing it? */
672 unsigned int inbuf_reached_eof:1; /**< Boolean: did read() return 0 on this
673 * conn? */
674 unsigned edge_has_sent_end:1; /**< For debugging; only used on edge
675 * connections. Set once we've set the stream end,
676 * and check in connection_about_to_close_connection().
678 /** Used for OR conns that shouldn't get any new circs attached to them. */
679 unsigned int or_is_obsolete:1;
680 /** For AP connections only. If 1, and we fail to reach the chosen exit,
681 * stop requiring it. */
682 unsigned int chosen_exit_optional:1;
684 int s; /**< Our socket; -1 if this connection is closed. */
685 int conn_array_index; /**< Index into the global connection array. */
686 struct event *read_event; /**< Libevent event structure. */
687 struct event *write_event; /**< Libevent event structure. */
688 buf_t *inbuf; /**< Buffer holding data read over this connection. */
689 buf_t *outbuf; /**< Buffer holding data to write over this connection. */
690 size_t outbuf_flushlen; /**< How much data should we try to flush from the
691 * outbuf? */
692 time_t timestamp_lastread; /**< When was the last time libevent said we could
693 * read? */
694 time_t timestamp_lastwritten; /**< When was the last time libevent said we
695 * could write? */
696 time_t timestamp_created; /**< When was this connection_t created? */
698 uint32_t addr; /**< IP of the other side of the connection; used to identify
699 * routers, along with port. */
700 uint16_t port; /**< If non-zero, port on the other end
701 * of the connection. */
702 uint16_t marked_for_close; /**< Should we close this conn on the next
703 * iteration of the main loop? (If true, holds
704 * the line number where this connection was
705 * marked.) */
706 const char *marked_for_close_file; /**< For debugging: in which file were
707 * we marked for close? */
708 char *address; /**< FQDN (or IP) of the guy on the other end.
709 * strdup into this, because free_connection frees it. */
711 } connection_t;
713 /** Subtype of connection_t for an "OR connection" -- that is, one that speaks
714 * cells over TLS. */
715 typedef struct or_connection_t {
716 connection_t _base;
718 char identity_digest[DIGEST_LEN]; /**< Hash of the public RSA key for
719 * the other side's signing key. */
720 char *nickname; /**< Nickname of OR on other side (if any). */
722 tor_tls_t *tls; /**< TLS connection state */
724 time_t timestamp_lastempty; /**< When was the outbuf last completely empty?*/
726 /* bandwidth* and read_bucket only used by ORs in OPEN state: */
727 int bandwidthrate; /**< Bytes/s added to the bucket. (OPEN ORs only.) */
728 int bandwidthburst; /**< Max bucket size for this conn. (OPEN ORs only.) */
729 int read_bucket; /**< When this hits 0, stop receiving. Every second we
730 * add 'bandwidthrate' to this, capping it at
731 * bandwidthburst. (OPEN ORs only) */
732 circ_id_type_t circ_id_type; /**< When we send CREATE cells along this
733 * connection, which half of the space should
734 * we use? */
735 int n_circuits; /**< How many circuits use this connection as p_conn or
736 * n_conn ? */
737 struct or_connection_t *next_with_same_id; /**< Next connection with same
738 * identity digest as this one. */
739 uint16_t next_circ_id; /**< Which circ_id do we try to use next on
740 * this connection? This is always in the
741 * range 0..1<<15-1. */
742 } or_connection_t;
744 /** Subtype of connection_t for an "edge connection" -- that is, a socks (ap)
745 * connection, or an exit. */
746 typedef struct edge_connection_t {
747 connection_t _base;
749 struct edge_connection_t *next_stream; /**< Points to the next stream at this
750 * edge, if any */
751 struct crypt_path_t *cpath_layer; /**< A pointer to which node in the circ
752 * this conn exits at. */
753 int package_window; /**< How many more relay cells can I send into the
754 * circuit? */
755 int deliver_window; /**< How many more relay cells can end at me? */
757 /** Nickname of planned exit node -- used with .exit support. */
758 char *chosen_exit_name;
760 socks_request_t *socks_request; /**< SOCKS structure describing request (AP
761 * only.) */
762 struct circuit_t *on_circuit; /**< The circuit (if any) that this edge
763 * connection is using. */
765 uint32_t address_ttl; /**< TTL for address-to-addr mapping on exit
766 * connection. Exit connections only. */
768 uint16_t stream_id; /**< The stream ID used for this edge connection on its
769 * circuit */
771 /** The reason why this connection is closing; passed to the controller. */
772 uint16_t end_reason;
774 /** Quasi-global identifier for this connection; used for control.c */
775 /* XXXX NM This can get re-used after 2**32 streams */
776 uint32_t global_identifier;
778 char rend_query[REND_SERVICE_ID_LEN+1]; /**< What rendezvous service are we
779 * querying for? (AP only) */
781 /** Number of times we've reassigned this application connection to
782 * a new circuit. We keep track because the timeout is longer if we've
783 * already retried several times. */
784 uint8_t num_socks_retries;
786 } edge_connection_t;
788 /** Subtype of connection_t for an "directory connection" -- that is, an HTTP
789 * connection to retrieve or serve directory material. */
790 typedef struct dir_connection_t {
791 connection_t _base;
793 char *requested_resource; /**< Which 'resource' did we ask the directory
794 * for? */
795 unsigned int dirconn_direct:1; /**< Is this dirconn direct, or via Tor? */
797 /* Used only for server sides of some dir connections, to implement
798 * "spooling" of directory material to the outbuf. Otherwise, we'd have
799 * to append everything to the outbuf in one enormous chunk. */
800 enum {
801 DIR_SPOOL_NONE=0, DIR_SPOOL_SERVER_BY_DIGEST, DIR_SPOOL_SERVER_BY_FP,
802 DIR_SPOOL_CACHED_DIR, DIR_SPOOL_NETWORKSTATUS
803 } dir_spool_src;
804 smartlist_t *fingerprint_stack;
805 struct cached_dir_t *cached_dir;
806 off_t cached_dir_offset;
807 tor_zlib_state_t *zlib_state;
809 char rend_query[REND_SERVICE_ID_LEN+1]; /**< What rendezvous service are we
810 * querying for? */
812 char identity_digest[DIGEST_LEN]; /**< Hash of the public RSA key for
813 * the directory server's signing key. */
814 } dir_connection_t;
816 /** Subtype of connection_t for an connection to a controller. */
817 typedef struct control_connection_t {
818 connection_t _base;
820 uint32_t event_mask; /**< Bitfield: which events does this controller
821 * care about? */
822 unsigned int use_long_names:1; /**< True if we should use long nicknames
823 * on this (v1) connection. Only settable
824 * via v1 controllers. */
825 /** For control connections only. If set, we send extended info with control
826 * events as appropriate. */
827 unsigned int use_extended_events:1;
829 uint32_t incoming_cmd_len;
830 uint32_t incoming_cmd_cur_len;
831 char *incoming_cmd;
832 /* Used only by control v0 connections */
833 uint16_t incoming_cmd_type;
834 } control_connection_t;
836 /** Cast a connection_t subtype pointer to a connection_t **/
837 #define TO_CONN(c) &(((c)->_base))
838 /** Helper macro: Given a pointer to to._base, of type from*, return &to. */
839 #define DOWNCAST(to, ptr) \
840 (to*) (((char*)(ptr)) - STRUCT_OFFSET(to, _base))
842 /** Convert a connection_t* to an or_connection_t*; assert if the cast is
843 * invalid. */
844 static or_connection_t *TO_OR_CONN(connection_t *);
845 /** Convert a connection_t* to a dir_connection_t*; assert if the cast is
846 * invalid. */
847 static dir_connection_t *TO_DIR_CONN(connection_t *);
848 /** Convert a connection_t* to an edge_connection_t*; assert if the cast is
849 * invalid. */
850 static edge_connection_t *TO_EDGE_CONN(connection_t *);
851 /** Convert a connection_t* to an control_connection_t*; assert if the cast is
852 * invalid. */
853 static control_connection_t *TO_CONTROL_CONN(connection_t *);
855 static INLINE or_connection_t *TO_OR_CONN(connection_t *c)
857 tor_assert(c->magic == OR_CONNECTION_MAGIC);
858 return DOWNCAST(or_connection_t, c);
860 static INLINE dir_connection_t *TO_DIR_CONN(connection_t *c)
862 tor_assert(c->magic == DIR_CONNECTION_MAGIC);
863 return DOWNCAST(dir_connection_t, c);
865 static INLINE edge_connection_t *TO_EDGE_CONN(connection_t *c)
867 tor_assert(c->magic == EDGE_CONNECTION_MAGIC);
868 return DOWNCAST(edge_connection_t, c);
870 static INLINE control_connection_t *TO_CONTROL_CONN(connection_t *c)
872 tor_assert(c->magic == CONTROL_CONNECTION_MAGIC);
873 return DOWNCAST(control_connection_t, c);
876 typedef enum {
877 ADDR_POLICY_ACCEPT=1,
878 ADDR_POLICY_REJECT=2,
879 } addr_policy_action_t;
881 /** A linked list of policy rules */
882 typedef struct addr_policy_t {
883 addr_policy_action_t policy_type; /**< What to do when the policy matches.*/
884 char *string; /**< String representation of this rule. */
885 uint32_t addr; /**< Base address to accept or reject. */
886 uint32_t msk; /**< Accept/reject all addresses <b>a</b> such that
887 * a &amp; msk == <b>addr</b> &amp; msk . */
888 uint16_t prt_min; /**< Lowest port number to accept/reject. */
889 uint16_t prt_max; /**< Highest port number to accept/reject. */
891 struct addr_policy_t *next; /**< Next rule in list. */
892 } addr_policy_t;
894 /** A cached_dir_t represents a cacheable directory object, along with its
895 * compressed form. */
896 typedef struct cached_dir_t {
897 char *dir; /**< Contents of this object */
898 char *dir_z; /**< Compressed contents of this object. */
899 size_t dir_len; /**< Length of <b>dir</b> */
900 size_t dir_z_len; /**< Length of <b>dir_z</b> */
901 time_t published; /**< When was this object published */
902 int refcnt; /**< Reference count for this cached_dir_t. */
903 } cached_dir_t;
905 typedef enum {
906 SAVED_NOWHERE=0, SAVED_IN_CACHE, SAVED_IN_JOURNAL
907 } saved_location_t;
909 /** Information need to cache an onion router's descriptor. */
910 typedef struct signed_descriptor_t {
911 char *signed_descriptor_body;
912 size_t signed_descriptor_len;
913 char signed_descriptor_digest[DIGEST_LEN];
914 char identity_digest[DIGEST_LEN];
915 time_t published_on;
916 saved_location_t saved_location;
917 off_t saved_offset;
918 } signed_descriptor_t;
920 /** Information about another onion router in the network. */
921 typedef struct {
922 signed_descriptor_t cache_info;
923 char *address; /**< Location of OR: either a hostname or an IP address. */
924 char *nickname; /**< Human-readable OR name. */
926 uint32_t addr; /**< IPv4 address of OR, in host order. */
927 uint16_t or_port; /**< Port for TLS connections. */
928 uint16_t dir_port; /**< Port for HTTP directory connections. */
930 crypto_pk_env_t *onion_pkey; /**< Public RSA key for onions. */
931 crypto_pk_env_t *identity_pkey; /**< Public RSA key for signing. */
933 char *platform; /**< What software/operating system is this OR using? */
935 /* link info */
936 uint32_t bandwidthrate; /**< How many bytes does this OR add to its token
937 * bucket per second? */
938 uint32_t bandwidthburst; /**< How large is this OR's token bucket? */
939 /** How many bytes/s is this router known to handle? */
940 uint32_t bandwidthcapacity;
941 addr_policy_t *exit_policy; /**< What streams will this OR permit
942 * to exit? */
943 long uptime; /**< How many seconds the router claims to have been up */
944 smartlist_t *declared_family; /**< Nicknames of router which this router
945 * claims are its family. */
946 char *contact_info; /**< Declared contact info for this router. */
947 unsigned int is_hibernating:1; /**< Whether the router claims to be
948 * hibernating */
949 unsigned int has_old_dnsworkers:1; /**< Whether the router is using
950 * dnsworker code. */
952 /* local info */
953 unsigned int is_running:1; /**< As far as we know, is this OR currently
954 * running? */
955 unsigned int is_valid:1; /**< Has a trusted dirserver validated this OR?
956 * (For Authdir: Have we validated this OR?)
958 unsigned int is_named:1; /**< Do we believe the nickname that this OR gives
959 * us? */
960 unsigned int is_fast:1; /** Do we think this is a fast OR? */
961 unsigned int is_stable:1; /** Do we think this is a stable OR? */
962 unsigned int is_possible_guard:1; /**< Do we think this is an OK guard? */
963 unsigned int is_exit:1; /**< Do we think this is an OK exit? */
964 unsigned int is_bad_exit:1; /**< Do we think this exit is censored, borked,
965 * or otherwise nasty? */
967 /** Tor can use this desc for circuit-building. */
968 #define ROUTER_PURPOSE_GENERAL 0
969 /** Tor should avoid using this desc for circuit-building. */
970 #define ROUTER_PURPOSE_CONTROLLER 1
971 uint8_t purpose; /** Should Tor use this desc for circuit-building? */
973 /* The below items are used only by authdirservers for
974 * reachability testing. */
975 /** When was the last time we could reach this OR? */
976 time_t last_reachable;
977 /** When did we start testing reachability for this OR? */
978 time_t testing_since;
979 /** How many times has a descriptor been posted and we believed
980 * this router to be unreachable? We only actually warn on the third. */
981 int num_unreachable_notifications;
983 /** What position is this descriptor within routerlist->routers? -1 for
984 * none. */
985 int routerlist_index;
986 } routerinfo_t;
988 /** Contents of a single router entry in a network status object.
990 typedef struct routerstatus_t {
991 time_t published_on; /**< When was this router published? */
992 char nickname[MAX_NICKNAME_LEN+1]; /**< The nickname this router says it
993 * has. */
994 char identity_digest[DIGEST_LEN]; /**< Digest of the router's identity
995 * key. */
996 char descriptor_digest[DIGEST_LEN]; /**< Digest of the router's most recent
997 * descriptor. */
998 uint32_t addr; /**< IPv4 address for this router. */
999 uint16_t or_port; /**< OR port for this router. */
1000 uint16_t dir_port; /**< Directory port for this router. */
1001 unsigned int is_exit:1; /**< True iff this router is a good exit. */
1002 unsigned int is_stable:1; /**< True iff this router stays up a long time. */
1003 unsigned int is_fast:1; /**< True iff this router has good bandwidth. */
1004 unsigned int is_running:1; /**< True iff this router is up. */
1005 unsigned int is_named:1; /**< True iff "nickname" belongs to this router. */
1006 unsigned int is_valid:1; /**< True iff this router is validated. */
1007 unsigned int is_v2_dir:1; /**< True iff this router can serve directory
1008 * information with v2 of the directory
1009 * protocol. (All directory caches cache v1
1010 * directories.) */
1011 unsigned int is_possible_guard:1; /**< True iff this router would be a good
1012 * choice as an entry guard. */
1013 unsigned int is_bad_exit:1; /**< True iff this node is a bad choice for
1014 * an exit node. */
1015 unsigned int is_bad_directory:1; /**< Do we think this directory is junky,
1016 * underpowered, or otherwise useless? */
1018 /** True iff we know version info for this router. (i.e., a "v" entry was
1019 * included.) We'll replace all these with a big tor_version_t or a char[]
1020 * if the number of traits we care about ever becomes incredibly big. */
1021 unsigned int version_known:1;
1022 /** True iff this router is a version that supports BEGIN_DIR cells. */
1023 unsigned int version_supports_begindir:1;
1025 /** True if we, as a directory mirror, want to download the corresponding
1026 * routerinfo from the authority who gave us this routerstatus. (That is,
1027 * if we don't have the routerinfo, and if we haven't already tried to get it
1028 * from this authority.)
1030 unsigned int need_to_mirror:1;
1031 } routerstatus_t;
1033 /** Our "local" or combined view of the info from all networkstatus objects
1034 * about a single router. */
1035 typedef struct local_routerstatus_t {
1036 /** What do we believe to be the case about this router? In this field,
1037 * descriptor_digest represents the descriptor we would most like to use for
1038 * this router. */
1039 routerstatus_t status;
1040 time_t next_attempt_at; /**< When should we try downloading this descriptor
1041 * again? */
1042 time_t last_dir_503_at; /**< When did this router last tell us that it
1043 * was too busy to serve directory info? */
1044 uint8_t n_download_failures; /**< Number of failures trying to download the
1045 * most recent descriptor. */
1046 unsigned int name_lookup_warned:1; /**< Have we warned the user for referring
1047 * to this (unnamed) router by nickname?
1049 } local_routerstatus_t;
1051 /** How many times will we try to download a router's descriptor before giving
1052 * up? */
1053 #define MAX_ROUTERDESC_DOWNLOAD_FAILURES 8
1055 /** Contents of a (v2 or later) network status object. */
1056 typedef struct networkstatus_t {
1057 /** When did we receive the network-status document? */
1058 time_t received_on;
1060 /** What was the digest of the document? */
1061 char networkstatus_digest[DIGEST_LEN];
1063 unsigned int is_recent; /**< Is this recent enough to influence running
1064 * status? */
1066 /* These fields come from the actual network-status document.*/
1067 time_t published_on; /**< Declared publication date. */
1069 char *source_address; /**< Canonical directory server hostname. */
1070 uint32_t source_addr; /**< Canonical directory server IP. */
1071 uint16_t source_dirport; /**< Canonical directory server dirport. */
1073 char identity_digest[DIGEST_LEN]; /**< Digest of signing key. */
1074 char *contact; /**< How to contact directory admin? (may be NULL). */
1075 crypto_pk_env_t *signing_key; /**< Key used to sign this directory. */
1076 char *client_versions; /**< comma-separated list of recommended client
1077 * versions. */
1078 char *server_versions; /**< comma-separated list of recommended server
1079 * versions. */
1081 unsigned int binds_names:1; /**< True iff this directory server binds
1082 * names. */
1083 unsigned int recommends_versions:1; /**< True iff this directory server
1084 * recommends client and server software
1085 * versions. */
1086 unsigned int lists_bad_exits:1; /**< True iff this directory server marks
1087 * malfunctioning exits as bad. */
1088 /** True iff this directory server marks malfunctioning directories as
1089 * bad. */
1090 unsigned int lists_bad_directories:1;
1091 smartlist_t *entries; /**< List of routerstatus_t*. This list is kept
1092 * sorted by identity_digest. */
1093 } networkstatus_t;
1095 /** Contents of a directory of onion routers. */
1096 typedef struct {
1097 /** Map from server identity digest to a member of routers. */
1098 digestmap_t *identity_map;
1099 /** Map from server descriptor digest to a signed_descriptor_t from
1100 * routers or old_routers. */
1101 digestmap_t *desc_digest_map;
1102 /** List of routerinfo_t for all currently live routers we know. */
1103 smartlist_t *routers;
1104 /** List of signed_descriptor_t for older router descriptors we're
1105 * caching. */
1106 smartlist_t *old_routers;
1107 /** Mmaped file holding server descriptors. If present, any router whose
1108 * cache_info.saved_location == SAVED_IN_CACHE is stored in this file
1109 * starting at cache_info.saved_offset */
1110 tor_mmap_t *mmap_descriptors;
1111 } routerlist_t;
1113 /** Information on router used when extending a circuit. (We don't need a
1114 * full routerinfo_t to extend: we only need addr:port:keyid to build an OR
1115 * connection, and onion_key to create the onionskin.) */
1116 typedef struct extend_info_t {
1117 char nickname[MAX_HEX_NICKNAME_LEN+1]; /**< This router's nickname for
1118 * display. */
1119 char identity_digest[DIGEST_LEN]; /**< Hash of this router's identity key. */
1120 uint32_t addr; /**< IP address in host order. */
1121 uint16_t port; /**< OR port. */
1122 crypto_pk_env_t *onion_key; /**< Current onionskin key. */
1123 } extend_info_t;
1125 #define CRYPT_PATH_MAGIC 0x70127012u
1127 /** Holds accounting information for a single step in the layered encryption
1128 * performed by a circuit. Used only at the client edge of a circuit. */
1129 typedef struct crypt_path_t {
1130 uint32_t magic;
1132 /* crypto environments */
1133 /** Encryption key and counter for cells heading towards the OR at this
1134 * step. */
1135 crypto_cipher_env_t *f_crypto;
1136 /** Encryption key and counter for cells heading back from the OR at this
1137 * step. */
1138 crypto_cipher_env_t *b_crypto;
1140 /** Digest state for cells heading towards the OR at this step. */
1141 crypto_digest_env_t *f_digest; /* for integrity checking */
1142 /** Digest state for cells heading away from the OR at this step. */
1143 crypto_digest_env_t *b_digest;
1145 /** Current state of Diffie-Hellman key negotiation with the OR at this
1146 * step. */
1147 crypto_dh_env_t *dh_handshake_state;
1148 /** Current state of 'fast' (non-PK) key negotiation with the OR at this
1149 * step. Used to save CPU when TLS is already providing all the
1150 * authentication, secrecy, and integrity we need, and we're already
1151 * distinguishable from an OR.
1153 char fast_handshake_state[DIGEST_LEN];
1154 /** Negotiated key material shared with the OR at this step. */
1155 char handshake_digest[DIGEST_LEN];/* KH in tor-spec.txt */
1157 /** Information to extend to the OR at this step. */
1158 extend_info_t *extend_info;
1160 /** Is the circuit built to this step? Must be one of:
1161 * - CPATH_STATE_CLOSED (The circuit has not been extended to this step)
1162 * - CPATH_STATE_AWAITING_KEYS (We have sent an EXTEND/CREATE to this step
1163 * and not received an EXTENDED/CREATED)
1164 * - CPATH_STATE_OPEN (The circuit has been extended to this step) */
1165 uint8_t state;
1166 #define CPATH_STATE_CLOSED 0
1167 #define CPATH_STATE_AWAITING_KEYS 1
1168 #define CPATH_STATE_OPEN 2
1169 struct crypt_path_t *next; /**< Link to next crypt_path_t in the circuit.
1170 * (The list is circular, so the last node
1171 * links to the first.) */
1172 struct crypt_path_t *prev; /**< Link to previous crypt_path_t in the
1173 * circuit. */
1175 int package_window; /**< How many bytes are we allowed to originate ending
1176 * at this step? */
1177 int deliver_window; /**< How many bytes are we willing to deliver originating
1178 * at this step? */
1179 } crypt_path_t;
1181 #define CPATH_KEY_MATERIAL_LEN (20*2+16*2)
1183 #define DH_KEY_LEN DH_BYTES
1184 #define ONIONSKIN_CHALLENGE_LEN (PKCS1_OAEP_PADDING_OVERHEAD+\
1185 CIPHER_KEY_LEN+\
1186 DH_KEY_LEN)
1187 #define ONIONSKIN_REPLY_LEN (DH_KEY_LEN+DIGEST_LEN)
1188 #define REND_COOKIE_LEN DIGEST_LEN
1190 /** Information used to build a circuit. */
1191 typedef struct {
1192 /** Intended length of the final circuit. */
1193 int desired_path_len;
1194 /** How to extend to the planned exit node. */
1195 extend_info_t *chosen_exit;
1196 /** Whether every node in the circ must have adequate uptime. */
1197 int need_uptime;
1198 /** Whether every node in the circ must have adequate capacity. */
1199 int need_capacity;
1200 /** Whether the last hop was picked with exiting in mind. */
1201 int is_internal;
1202 /** Did we pick this as a one-hop tunnel (not safe for other conns)?
1203 * These are for encrypted connections that exit to this router, not
1204 * for arbitrary exits from the circuit. */
1205 int onehop_tunnel;
1206 /** The crypt_path_t to append after rendezvous: used for rendezvous. */
1207 crypt_path_t *pending_final_cpath;
1208 /** How many times has building a circuit for this task failed? */
1209 int failure_count;
1210 /** At what time should we give up on this task? */
1211 time_t expiry_time;
1212 } cpath_build_state_t;
1214 #define ORIGIN_CIRCUIT_MAGIC 0x35315243u
1215 #define OR_CIRCUIT_MAGIC 0x98ABC04Fu
1217 typedef uint16_t circid_t;
1220 * A circuit is a path over the onion routing
1221 * network. Applications can connect to one end of the circuit, and can
1222 * create exit connections at the other end of the circuit. AP and exit
1223 * connections have only one circuit associated with them (and thus these
1224 * connection types are closed when the circuit is closed), whereas
1225 * OR connections multiplex many circuits at once, and stay standing even
1226 * when there are no circuits running over them.
1228 * A circuit_t structure can fill one of two roles. First, a or_circuit_t
1229 * links two connections together: either an edge connection and an OR
1230 * connection, or two OR connections. (When joined to an OR connection, a
1231 * circuit_t affects only cells sent to a particular circID on that
1232 * connection. When joined to an edge connection, a circuit_t affects all
1233 * data.)
1235 * Second, an origin_circuit_t holds the cipher keys and state for sending data
1236 * along a given circuit. At the OP, it has a sequence of ciphers, each
1237 * of which is shared with a single OR along the circuit. Separate
1238 * ciphers are used for data going "forward" (away from the OP) and
1239 * "backward" (towards the OP). At the OR, a circuit has only two stream
1240 * ciphers: one for data going forward, and one for data going backward.
1242 typedef struct circuit_t {
1243 uint32_t magic; /**< For memory and type debugging: must equal
1244 * ORIGIN_CIRCUIT_MAGIC or OR_CIRCUIT_MAGIC. */
1246 /** The OR connection that is next in this circuit. */
1247 or_connection_t *n_conn;
1248 /** The identity hash of n_conn. */
1249 char n_conn_id_digest[DIGEST_LEN];
1250 /** The circuit_id used in the next (forward) hop of this circuit. */
1251 uint16_t n_circ_id;
1252 /** The port for the OR that is next in this circuit. */
1253 uint16_t n_port;
1254 /** The IPv4 address of the OR that is next in this circuit. */
1255 uint32_t n_addr;
1256 /** How many relay data cells can we package (read from edge streams)
1257 * on this circuit before we receive a circuit-level sendme cell asking
1258 * for more? */
1259 int package_window;
1260 /** How many relay data cells will we deliver (write to edge streams)
1261 * on this circuit? When deliver_window gets low, we send some
1262 * circuit-level sendme cells to indicate that we're willing to accept
1263 * more. */
1264 int deliver_window;
1266 /** For storage while passing to cpuworker (state
1267 * CIRCUIT_STATE_ONIONSKIN_PENDING), or while n_conn is pending
1268 * (state CIRCUIT_STATE_OR_WAIT). When defined, it is always
1269 * length ONIONSKIN_CHALLENGE_LEN. */
1270 char *onionskin;
1272 time_t timestamp_created; /**< When was this circuit created? */
1273 time_t timestamp_dirty; /**< When the circuit was first used, or 0 if the
1274 * circuit is clean. */
1276 uint8_t state; /**< Current status of this circuit. */
1277 uint8_t purpose; /**< Why are we creating this circuit? */
1279 uint16_t marked_for_close; /**< Should we close this circuit at the end of
1280 * the main loop? (If true, holds the line number
1281 * where this circuit was marked.) */
1282 const char *marked_for_close_file; /**< For debugging: in which file was this
1283 * circuit marked for close? */
1285 struct circuit_t *next; /**< Next circuit in linked list. */
1286 } circuit_t;
1288 /** An origin_circuit_t holds data necessary to build and use a circuit.
1290 typedef struct origin_circuit_t {
1291 circuit_t _base;
1293 /** Linked list of AP streams (or EXIT streams if hidden service)
1294 * associated with this circuit. */
1295 edge_connection_t *p_streams;
1296 /** Build state for this circuit. It includes the intended path
1297 * length, the chosen exit router, rendezvous information, etc.
1299 cpath_build_state_t *build_state;
1300 /** The doubly-linked list of crypt_path_t entries, one per hop,
1301 * for this circuit. This includes ciphers for each hop,
1302 * integrity-checking digests for each hop, and package/delivery
1303 * windows for each hop.
1305 crypt_path_t *cpath;
1307 /** The rend_pk_digest field holds a hash of location-hidden service's
1308 * PK if purpose is S_ESTABLISH_INTRO or S_RENDEZVOUSING.
1310 char rend_pk_digest[DIGEST_LEN];
1312 /** Holds rendezvous cookie if purpose is C_ESTABLISH_REND. Filled with
1313 * zeroes otherwise.
1315 char rend_cookie[REND_COOKIE_LEN];
1318 * The rend_query field holds the y portion of y.onion (nul-terminated)
1319 * if purpose is C_INTRODUCING or C_ESTABLISH_REND, or is a C_GENERAL
1320 * for a hidden service, or is S_*.
1322 char rend_query[REND_SERVICE_ID_LEN+1];
1324 /** The next stream_id that will be tried when we're attempting to
1325 * construct a new AP stream originating at this circuit. */
1326 uint16_t next_stream_id;
1328 /** Quasi-global identifier for this circuit; used for control.c */
1329 /* XXXX NM This can get re-used after 2**32 circuits. */
1330 uint32_t global_identifier;
1332 } origin_circuit_t;
1334 /** An or_circuit_t holds information needed to implement a circuit at an
1335 * OR. */
1336 typedef struct or_circuit_t {
1337 circuit_t _base;
1339 /** The circuit_id used in the previous (backward) hop of this circuit. */
1340 circid_t p_circ_id;
1341 /** The OR connection that is previous in this circuit. */
1342 or_connection_t *p_conn;
1343 /** Linked list of Exit streams associated with this circuit. */
1344 edge_connection_t *n_streams;
1345 /** Linked list of Exit streams associated with this circuit that are
1346 * still being resolved. */
1347 edge_connection_t *resolving_streams;
1348 /** The cipher used by intermediate hops for cells heading toward the
1349 * OP. */
1350 crypto_cipher_env_t *p_crypto;
1351 /** The cipher used by intermediate hops for cells heading away from
1352 * the OP. */
1353 crypto_cipher_env_t *n_crypto;
1355 /** The integrity-checking digest used by intermediate hops, for
1356 * cells packaged here and heading towards the OP.
1358 crypto_digest_env_t *p_digest;
1359 /** The integrity-checking digest used by intermediate hops, for
1360 * cells packaged at the OP and arriving here.
1362 crypto_digest_env_t *n_digest;
1364 /** Points to spliced circuit if purpose is REND_ESTABLISHED, and circuit
1365 * is not marked for close. */
1366 struct or_circuit_t *rend_splice;
1368 #if REND_COOKIE_LEN >= DIGEST_LEN
1369 #define REND_TOKEN_LEN REND_COOKIE_LEN
1370 #else
1371 #define REND_TOKEN_LEN DIGEST_LEN
1372 #endif
1374 /** A hash of location-hidden service's PK if purpose is INTRO_POINT, or a
1375 * rendezvous cookie if purpose is REND_POINT_WAITING. Filled with zeroes
1376 * otherwise.
1377 * ???? move to a subtype or adjunct structure? Wastes 20 bytes. -NM
1379 char rend_token[REND_TOKEN_LEN];
1381 /* ???? move to a subtype or adjunct structure? Wastes 20 bytes -NM */
1382 char handshake_digest[DIGEST_LEN]; /**< Stores KH for the handshake. */
1384 /** True iff this circuit was made with a CREATE_FAST cell. */
1385 unsigned int is_first_hop : 1;
1386 } or_circuit_t;
1388 /** Convert a circuit subtype to a circuit_t.*/
1389 #define TO_CIRCUIT(x) (&((x)->_base))
1391 /** Convert a circuit_t* to a pointer to the enclosing or_circuit_t. Asserts
1392 * if the cast is impossible. */
1393 static or_circuit_t *TO_OR_CIRCUIT(circuit_t *);
1394 /** Convert a circuit_t* to a pointer to the enclosing origin_circuit_t.
1395 * Asserts if the cast is impossible. */
1396 static origin_circuit_t *TO_ORIGIN_CIRCUIT(circuit_t *);
1398 static INLINE or_circuit_t *TO_OR_CIRCUIT(circuit_t *x)
1400 tor_assert(x->magic == OR_CIRCUIT_MAGIC);
1401 //return (or_circuit_t*) (((char*)x) - STRUCT_OFFSET(or_circuit_t, _base));
1402 return DOWNCAST(or_circuit_t, x);
1404 static INLINE origin_circuit_t *TO_ORIGIN_CIRCUIT(circuit_t *x)
1406 tor_assert(x->magic == ORIGIN_CIRCUIT_MAGIC);
1407 //return (origin_circuit_t*)
1408 // (((char*)x) - STRUCT_OFFSET(origin_circuit_t, _base));
1409 return DOWNCAST(origin_circuit_t, x);
1412 #define ALLOW_INVALID_ENTRY 1
1413 #define ALLOW_INVALID_EXIT 2
1414 #define ALLOW_INVALID_MIDDLE 4
1415 #define ALLOW_INVALID_RENDEZVOUS 8
1416 #define ALLOW_INVALID_INTRODUCTION 16
1418 /** An entry specifying a set of addresses and ports that should be remapped
1419 * to another address and port before exiting this exit node. */
1420 typedef struct exit_redirect_t {
1421 uint32_t addr;
1422 uint32_t mask;
1423 uint16_t port_min;
1424 uint16_t port_max;
1426 uint32_t addr_dest;
1427 uint16_t port_dest;
1428 unsigned is_redirect:1;
1429 } exit_redirect_t;
1431 /** A linked list of lines in a config file. */
1432 typedef struct config_line_t {
1433 char *key;
1434 char *value;
1435 struct config_line_t *next;
1436 } config_line_t;
1438 /** Configuration options for a Tor process. */
1439 typedef struct {
1440 uint32_t _magic;
1442 /** What should the tor process actually do? */
1443 enum {
1444 CMD_RUN_TOR=0, CMD_LIST_FINGERPRINT, CMD_HASH_PASSWORD,
1445 CMD_VERIFY_CONFIG, CMD_RUN_UNITTESTS
1446 } command;
1447 const char *command_arg; /**< Argument for command-line option. */
1449 config_line_t *Logs; /**< New-style list of configuration lines
1450 * for logs */
1452 char *DebugLogFile; /**< Where to send verbose log messages. */
1453 char *DataDirectory; /**< OR only: where to store long-term data. */
1454 char *Nickname; /**< OR only: nickname of this onion router. */
1455 char *Address; /**< OR only: configured address for this onion router. */
1456 char *PidFile; /**< Where to store PID of Tor process. */
1458 char *ExitNodes; /**< Comma-separated list of nicknames of ORs to consider
1459 * as exits. */
1460 char *EntryNodes; /**< Comma-separated list of nicknames of ORs to consider
1461 * as entry points. */
1462 int StrictExitNodes; /**< Boolean: When none of our ExitNodes are up, do we
1463 * stop building circuits? */
1464 int StrictEntryNodes; /**< Boolean: When none of our EntryNodes are up, do we
1465 * stop building circuits? */
1466 char *ExcludeNodes; /**< Comma-separated list of nicknames of ORs not to
1467 * use in circuits. */
1469 char *RendNodes; /**< Comma-separated list of nicknames used as introduction
1470 * points. */
1471 char *RendExcludeNodes; /**< Comma-separated list of nicknames not to use
1472 * as introduction points. */
1474 smartlist_t *AllowInvalidNodes; /**< List of "entry", "middle", "exit" */
1475 int _AllowInvalid; /**< Bitmask; derived from AllowInvalidNodes; */
1476 config_line_t *ExitPolicy; /**< Lists of exit policy components. */
1477 int ExitPolicyRejectPrivate; /**< Should we not exit to local addresses? */
1478 config_line_t *SocksPolicy; /**< Lists of socks policy components */
1479 config_line_t *DirPolicy; /**< Lists of dir policy components */
1480 /** Addresses to bind for listening for SOCKS connections. */
1481 config_line_t *SocksListenAddress;
1482 /** Addresses to bind for listening for transparent pf/nefilter
1483 * connections. */
1484 config_line_t *TransListenAddress;
1485 /** Addresses to bind for listening for transparent natd connections */
1486 config_line_t *NatdListenAddress;
1487 /** Addresses to bind for listening for OR connections. */
1488 config_line_t *ORListenAddress;
1489 /** Addresses to bind for listening for directory connections. */
1490 config_line_t *DirListenAddress;
1491 /** Addresses to bind for listening for control connections. */
1492 config_line_t *ControlListenAddress;
1493 /** Local address to bind outbound sockets */
1494 char *OutboundBindAddress;
1495 /** Directory server only: which versions of
1496 * Tor should we tell users to run? */
1497 config_line_t *RecommendedVersions;
1498 config_line_t *RecommendedClientVersions;
1499 config_line_t *RecommendedServerVersions;
1500 /** Whether dirservers refuse router descriptors with private IPs. */
1501 int DirAllowPrivateAddresses;
1502 char *User; /**< Name of user to run Tor as. */
1503 char *Group; /**< Name of group to run Tor as. */
1504 double PathlenCoinWeight; /**< Parameter used to configure average path
1505 * length (alpha in geometric distribution). */
1506 int ORPort; /**< Port to listen on for OR connections. */
1507 int SocksPort; /**< Port to listen on for SOCKS connections. */
1508 /** Port to listen on for transparent pf/netfilter connections. */
1509 int TransPort;
1510 int NatdPort; /**< Port to listen on for transparent natd connections. */
1511 int ControlPort; /**< Port to listen on for control connections. */
1512 int DirPort; /**< Port to listen on for directory connections. */
1513 int AssumeReachable; /**< Whether to publish our descriptor regardless. */
1514 int AuthoritativeDir; /**< Boolean: is this an authoritative directory? */
1515 int V1AuthoritativeDir; /**< Boolean: is this an authoritative directory
1516 * for version 1 directories? */
1517 int HSAuthoritativeDir; /**< Boolean: does this an authoritative directory
1518 * handle hidden service requests? */
1519 int NamingAuthoritativeDir; /**< Boolean: is this an authoritative directory
1520 * that's willing to bind names? */
1521 int VersioningAuthoritativeDir; /**< Boolean: is this an authoritative
1522 * directory that's willing to recommend
1523 * versions? */
1524 int AvoidDiskWrites; /**< Boolean: should we never cache things to disk?
1525 * Not used yet. */
1526 int ClientOnly; /**< Boolean: should we never evolve into a server role? */
1527 int NoPublish; /**< Boolean: should we never publish a descriptor? */
1528 int PublishServerDescriptor; /**< Do we publish our descriptor as normal? */
1529 int PublishHidServDescriptors; /**< and our hidden service descriptors? */
1530 int FetchServerDescriptors; /**< Do we fetch server descriptors as normal? */
1531 int FetchHidServDescriptors; /** and hidden service descriptors? */
1532 int FetchUselessDescriptors; /**< Do we fetch non-running descriptors too? */
1533 int AllDirActionsPrivate; /**< Should every directory action be sent
1534 * through a Tor circuit? */
1536 int ConnLimit; /**< Demanded minimum number of simultaneous connections. */
1537 int _ConnLimit; /**< Maximum allowed number of simultaneous connections. */
1538 int RunAsDaemon; /**< If true, run in the background. (Unix only) */
1539 int FascistFirewall; /**< Whether to prefer ORs reachable on open ports. */
1540 smartlist_t *FirewallPorts; /**< Which ports our firewall allows
1541 * (strings). */
1542 config_line_t *ReachableAddresses; /**< IP:ports our firewall allows. */
1543 config_line_t *ReachableORAddresses; /**< IP:ports for OR conns. */
1544 config_line_t *ReachableDirAddresses; /**< IP:ports for Dir conns. */
1546 /** Application ports that require all nodes in circ to have sufficient
1547 * uptime. */
1548 smartlist_t *LongLivedPorts;
1549 /** Should we try to reuse the same exit node for a given host */
1550 smartlist_t *TrackHostExits;
1551 int TrackHostExitsExpire; /**< Number of seconds until we expire an
1552 * addressmap */
1553 config_line_t *AddressMap; /**< List of address map directives. */
1554 int RendPostPeriod; /**< How often do we post each rendezvous service
1555 * descriptor? Remember to publish them independently. */
1556 int KeepalivePeriod; /**< How often do we send padding cells to keep
1557 * connections alive? */
1558 int SocksTimeout; /**< How long do we let a socks connection wait
1559 * unattached before we fail it? */
1560 int CircuitBuildTimeout; /**< Cull non-open circuits that were born
1561 * at least this many seconds ago. */
1562 int CircuitIdleTimeout; /**< Cull open clean circuits that were born
1563 * at least this many seconds ago. */
1564 int MaxOnionsPending; /**< How many circuit CREATE requests do we allow
1565 * to wait simultaneously before we start dropping
1566 * them? */
1567 int NewCircuitPeriod; /**< How long do we use a circuit before building
1568 * a new one? */
1569 int MaxCircuitDirtiness; /**< Never use circs that were first used more than
1570 this interval ago. */
1571 uint64_t BandwidthRate; /**< How much bandwidth, on average, are we willing
1572 * to use in a second? */
1573 uint64_t BandwidthBurst; /**< How much bandwidth, at maximum, are we willing
1574 * to use in a second? */
1575 uint64_t MaxAdvertisedBandwidth; /**< How much bandwidth are we willing to
1576 * tell people we have? */
1577 uint64_t RelayBandwidthRate; /**< How much bandwidth, on average, are we
1578 * willing to use for all relayed conns? */
1579 uint64_t RelayBandwidthBurst; /**< How much bandwidth, at maximum, will we
1580 * use in a second for all relayed conns? */
1581 int NumCpus; /**< How many CPUs should we try to use? */
1582 int RunTesting; /**< If true, create testing circuits to measure how well the
1583 * other ORs are running. */
1584 char *TestVia; /**< When reachability testing, use these as middle hop. */
1585 config_line_t *RendConfigLines; /**< List of configuration lines
1586 * for rendezvous services. */
1587 char *ContactInfo; /**< Contact info to be published in the directory */
1589 char *HttpProxy; /**< hostname[:port] to use as http proxy, if any */
1590 uint32_t HttpProxyAddr; /**< Parsed IPv4 addr for http proxy, if any */
1591 uint16_t HttpProxyPort; /**< Parsed port for http proxy, if any */
1592 char *HttpProxyAuthenticator; /**< username:password string, if any */
1594 char *HttpsProxy; /**< hostname[:port] to use as https proxy, if any */
1595 uint32_t HttpsProxyAddr; /**< Parsed IPv4 addr for https proxy, if any */
1596 uint16_t HttpsProxyPort; /**< Parsed port for https proxy, if any */
1597 char *HttpsProxyAuthenticator; /**< username:password string, if any */
1599 config_line_t *DirServers; /**< List of configuration lines
1600 * for directory servers. */
1601 char *MyFamily; /**< Declared family for this OR. */
1602 config_line_t *NodeFamilies; /**< List of config lines for
1603 * node families */
1604 config_line_t *RedirectExit; /**< List of config lines for simple
1605 * addr/port redirection */
1606 smartlist_t *RedirectExitList; /**< List of exit_redirect_t */
1607 config_line_t *AuthDirBadExit; /**< Address policy for descriptors to
1608 * mark as bad exits. */
1609 config_line_t *AuthDirReject; /**< Address policy for descriptors to
1610 * reject. */
1611 config_line_t *AuthDirInvalid; /**< Address policy for descriptors to
1612 * never mark as valid. */
1613 int AuthDirListBadExits; /**< True iff we should list bad exits,
1614 * and vote for all other exits as good. */
1615 int AuthDirRejectUnlisted; /**< Boolean: do we reject all routers that
1616 * aren't named in our fingerprint file? */
1617 char *AccountingStart; /**< How long is the accounting interval, and when
1618 * does it start? */
1619 uint64_t AccountingMax; /**< How many bytes do we allow per accounting
1620 * interval before hibernation? 0 for "never
1621 * hibernate." */
1623 char *HashedControlPassword; /**< Base64-encoded hash of a password for
1624 * the control system. */
1625 int CookieAuthentication; /**< Boolean: do we enable cookie-based auth for
1626 * the control system? */
1627 int LeaveStreamsUnattached; /**< Boolean: Does Tor attach new streams to
1628 * circuits itself (0), or does it expect a controller
1629 * to cope? (1) */
1630 int ShutdownWaitLength; /**< When we get a SIGINT and we're a server, how
1631 * long do we wait before exiting? */
1632 int SafeLogging; /**< Boolean: are we allowed to log sensitive strings
1633 * such as addresses (0), or do we scrub them first (1)? */
1634 int SafeSocks; /**< Boolean: should we outright refuse application
1635 * connections that use socks4 or socks5-with-local-dns? */
1636 #define LOG_PROTOCOL_WARN (get_options()->ProtocolWarnings ? \
1637 LOG_WARN : LOG_INFO)
1638 int ProtocolWarnings; /**< Boolean: when other parties screw up the Tor
1639 * protocol, is it a warn or an info in our logs? */
1640 int TestSocks; /**< Boolean: when we get a socks connection, do we loudly
1641 * log whether it was DNS-leaking or not? */
1642 int HardwareAccel; /**< Boolean: Should we enable OpenSSL hardware
1643 * acceleration where available? */
1644 int UseEntryGuards; /**< Boolean: Do we try to enter from a smallish number
1645 * of fixed nodes? */
1646 int NumEntryGuards; /**< How many entry guards do we try to establish? */
1647 int RephistTrackTime; /**< How many seconds do we keep rephist info? */
1648 int FastFirstHopPK; /**< If Tor believes it is safe, should we save a third
1649 * of our PK time by sending CREATE_FAST cells? */
1651 addr_policy_t *reachable_addr_policy; /**< Parsed from ReachableAddresses */
1653 char *VirtualAddrNetwork; /**< Address and mask to hand out for virtual
1654 * MAPADDRESS requests. */
1655 int ServerDNSSearchDomains; /**< Boolean: If set, we don't force exit
1656 * addresses to be FQDNs, but rather search for them in
1657 * the local domains. */
1658 int ServerDNSDetectHijacking; /**< Boolean: If true, check for DNS failure
1659 * hijacking. */
1660 char *ServerDNSResolvConfFile; /**< If provided, we configure our internal
1661 * resolver from the file here rather than from
1662 * /etc/resolv.conf (Unix) or the registry (Windows). */
1663 smartlist_t *ServerDNSTestAddresses; /**< A list of addresses that definitely
1664 * should be resolveable. Used for
1665 * testing our DNS server. */
1666 int EnforceDistinctSubnets; /**< If true, don't allow multiple routers in the
1667 * same network zone in the same circuit. */
1668 int TunnelDirConns; /**< If true, use BEGIN_DIR rather than BEGIN when
1669 * possible. */
1670 int PreferTunneledDirConns; /**< If true, avoid dirservers that don't
1671 * support BEGIN_DIR, when possible. */
1672 int AllowNonRFC953Hostnames; /**< If true, we allow connections to hostnames
1673 * with weird characters. */
1674 } or_options_t;
1676 /** Persistent state for an onion router, as saved to disk. */
1677 typedef struct {
1678 uint32_t _magic;
1679 /** The time at which we next plan to write the state to the disk. Equal to
1680 * TIME_MAX if there are no saveable changes, 0 if there are changes that
1681 * should be saved right away. */
1682 time_t next_write;
1684 /** When was the state last written to disk? */
1685 time_t LastWritten;
1687 /** Fields for accounting bandwidth use. */
1688 time_t AccountingIntervalStart;
1689 uint64_t AccountingBytesReadInInterval;
1690 uint64_t AccountingBytesWrittenInInterval;
1691 int AccountingSecondsActive;
1692 uint64_t AccountingExpectedUsage;
1694 /** A list of Entry Guard-related configuration lines. */
1695 config_line_t *EntryGuards;
1697 /** These fields hold information on the history of bandwidth usage for
1698 * servers. The "Ends" fields hold the time when we last updated the
1699 * bandwidth usage. The "Interval" fields hold the granularity, in seconds,
1700 * of the entries of Values. The "Values" lists hold decimal string
1701 * representations of the number of bytes read or written in each
1702 * interval. */
1703 time_t BWHistoryReadEnds;
1704 int BWHistoryReadInterval;
1705 smartlist_t *BWHistoryReadValues;
1706 time_t BWHistoryWriteEnds;
1707 int BWHistoryWriteInterval;
1708 smartlist_t *BWHistoryWriteValues;
1710 /** What version of Tor wrote this state file? */
1711 char *TorVersion;
1713 /** Holds any unrecognized values we found in the state file, in the order
1714 * in which we found them. */
1715 config_line_t *ExtraLines;
1717 /** When did we last rotate our onion key? "0" for 'no idea'. */
1718 time_t LastRotatedOnionKey;
1719 } or_state_t;
1721 /** Change the next_write time of <b>state</b> to <b>when</b>, unless the
1722 * state is already scheduled to be written to disk earlier than <b>when</b>.
1724 static INLINE void or_state_mark_dirty(or_state_t *state, time_t when)
1726 if (state->next_write > when)
1727 state->next_write = when;
1730 #define MAX_SOCKS_REPLY_LEN 1024
1731 #define MAX_SOCKS_ADDR_LEN 256
1733 /** Please open a TCP connection to this addr:port. */
1734 #define SOCKS_COMMAND_CONNECT 0x01
1735 /** Please turn this FQDN into an IP address, privately. */
1736 #define SOCKS_COMMAND_RESOLVE 0xF0
1737 /** Please turn this IP address into an FQDN, privately. */
1738 #define SOCKS_COMMAND_RESOLVE_PTR 0xF1
1739 /** Please open an encrypted direct TCP connection to the directory port
1740 * of the Tor server specified by address:port. (In this case address:port
1741 * specifies the ORPort of the server.) */
1742 #define SOCKS_COMMAND_CONNECT_DIR 0xF2
1744 #define SOCKS_COMMAND_IS_CONNECT(c) ((c)==SOCKS_COMMAND_CONNECT || \
1745 (c)==SOCKS_COMMAND_CONNECT_DIR)
1746 #define SOCKS_COMMAND_IS_RESOLVE(c) ((c)==SOCKS_COMMAND_RESOLVE || \
1747 (c)==SOCKS_COMMAND_RESOLVE_PTR)
1749 /** State of a SOCKS request from a user to an OP */
1750 struct socks_request_t {
1751 /** Which version of SOCKS did the client use? One of "0, 4, 5" -- where
1752 * 0 means that no socks handshake ever took place, and this is just a
1753 * stub connection (e.g. see connection_ap_make_bridge()). */
1754 char socks_version;
1755 int command; /**< What is this stream's goal? One from the above list. */
1756 size_t replylen; /**< Length of <b>reply</b>. */
1757 char reply[MAX_SOCKS_REPLY_LEN]; /**< Write an entry into this string if
1758 * we want to specify our own socks reply,
1759 * rather than using the default socks4 or
1760 * socks5 socks reply. We use this for the
1761 * two-stage socks5 handshake.
1763 int has_finished; /**< Has the SOCKS handshake finished? */
1764 char address[MAX_SOCKS_ADDR_LEN]; /**< What address did the client ask to
1765 connect to? */
1766 uint16_t port; /**< What port did the client ask to connect to? */
1769 /* all the function prototypes go here */
1771 /********************************* buffers.c ***************************/
1773 buf_t *buf_new(void);
1774 buf_t *buf_new_with_capacity(size_t size);
1775 void buf_free(buf_t *buf);
1776 void buf_clear(buf_t *buf);
1777 void buf_shrink(buf_t *buf);
1779 size_t buf_datalen(const buf_t *buf);
1780 size_t buf_capacity(const buf_t *buf);
1781 const char *_buf_peek_raw_buffer(const buf_t *buf);
1783 int read_to_buf(int s, size_t at_most, buf_t *buf, int *reached_eof);
1784 int read_to_buf_tls(tor_tls_t *tls, size_t at_most, buf_t *buf);
1786 int flush_buf(int s, buf_t *buf, size_t sz, size_t *buf_flushlen);
1787 int flush_buf_tls(tor_tls_t *tls, buf_t *buf, size_t sz, size_t *buf_flushlen);
1789 int write_to_buf(const char *string, size_t string_len, buf_t *buf);
1790 int write_to_buf_zlib(buf_t *buf, tor_zlib_state_t *state,
1791 const char *data, size_t data_len, int done);
1792 int fetch_from_buf(char *string, size_t string_len, buf_t *buf);
1793 int fetch_from_buf_http(buf_t *buf,
1794 char **headers_out, size_t max_headerlen,
1795 char **body_out, size_t *body_used, size_t max_bodylen,
1796 int force_complete);
1797 int fetch_from_buf_socks(buf_t *buf, socks_request_t *req,
1798 int log_sockstype, int safe_socks);
1799 int fetch_from_buf_control0(buf_t *buf, uint32_t *len_out, uint16_t *type_out,
1800 char **body_out, int check_for_v1);
1801 int fetch_from_buf_line(buf_t *buf, char *data_out, size_t *data_len);
1802 int fetch_from_buf_line_lf(buf_t *buf, char *data_out, size_t *data_len);
1804 void assert_buf_ok(buf_t *buf);
1806 /********************************* circuitbuild.c **********************/
1808 char *circuit_list_path(origin_circuit_t *circ, int verbose);
1809 char *circuit_list_path_for_controller(origin_circuit_t *circ);
1810 void circuit_log_path(int severity, unsigned int domain,
1811 origin_circuit_t *circ);
1812 void circuit_rep_hist_note_result(origin_circuit_t *circ);
1813 origin_circuit_t *origin_circuit_init(uint8_t purpose, int onehop_tunnel,
1814 int need_uptime,
1815 int need_capacity, int internal);
1816 origin_circuit_t *circuit_establish_circuit(uint8_t purpose,
1817 int onehop_tunnel, extend_info_t *exit,
1818 int need_uptime, int need_capacity,
1819 int internal);
1820 int circuit_handle_first_hop(origin_circuit_t *circ);
1821 void circuit_n_conn_done(or_connection_t *or_conn, int status);
1822 int inform_testing_reachability(void);
1823 int circuit_send_next_onion_skin(origin_circuit_t *circ);
1824 void circuit_note_clock_jumped(int seconds_elapsed);
1825 int circuit_extend(cell_t *cell, circuit_t *circ);
1826 int circuit_init_cpath_crypto(crypt_path_t *cpath, char *key_data,
1827 int reverse);
1828 int circuit_finish_handshake(origin_circuit_t *circ, uint8_t cell_type,
1829 char *reply);
1830 int circuit_truncated(origin_circuit_t *circ, crypt_path_t *layer);
1831 int onionskin_answer(or_circuit_t *circ, uint8_t cell_type, char *payload,
1832 char *keys);
1833 int circuit_all_predicted_ports_handled(time_t now, int *need_uptime,
1834 int *need_capacity);
1836 int circuit_append_new_exit(origin_circuit_t *circ, extend_info_t *info);
1837 int circuit_extend_to_new_exit(origin_circuit_t *circ, extend_info_t *info);
1838 void onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop);
1839 extend_info_t *extend_info_from_router(routerinfo_t *r);
1840 extend_info_t *extend_info_dup(extend_info_t *info);
1841 void extend_info_free(extend_info_t *info);
1842 routerinfo_t *build_state_get_exit_router(cpath_build_state_t *state);
1843 const char *build_state_get_exit_nickname(cpath_build_state_t *state);
1845 void entry_guards_compute_status(void);
1846 int entry_guard_register_connect_status(const char *digest, int succeeded,
1847 time_t now);
1848 void entry_nodes_should_be_added(void);
1849 void entry_guards_prepend_from_config(void);
1850 void entry_guards_update_state(or_state_t *state);
1851 int entry_guards_parse_state(or_state_t *state, int set, char **msg);
1852 int getinfo_helper_entry_guards(control_connection_t *conn,
1853 const char *question, char **answer);
1854 void entry_guards_free_all(void);
1856 /********************************* circuitlist.c ***********************/
1858 circuit_t * _circuit_get_global_list(void);
1859 const char *circuit_state_to_string(int state);
1860 void circuit_dump_by_conn(connection_t *conn, int severity);
1861 void circuit_set_p_circid_orconn(or_circuit_t *circ, uint16_t id,
1862 or_connection_t *conn);
1863 void circuit_set_n_circid_orconn(circuit_t *circ, uint16_t id,
1864 or_connection_t *conn);
1865 void circuit_set_state(circuit_t *circ, int state);
1866 void circuit_close_all_marked(void);
1867 origin_circuit_t *origin_circuit_new(void);
1868 or_circuit_t *or_circuit_new(uint16_t p_circ_id, or_connection_t *p_conn);
1869 circuit_t *circuit_get_by_circid_orconn(uint16_t circ_id,
1870 or_connection_t *conn);
1871 circuit_t *circuit_get_by_edge_conn(edge_connection_t *conn);
1872 void circuit_unlink_all_from_or_conn(or_connection_t *conn, int reason);
1873 origin_circuit_t *circuit_get_by_global_id(uint32_t id);
1874 origin_circuit_t *circuit_get_by_rend_query_and_purpose(const char *rend_query,
1875 uint8_t purpose);
1876 origin_circuit_t *circuit_get_next_by_pk_and_purpose(origin_circuit_t *start,
1877 const char *digest, uint8_t purpose);
1878 or_circuit_t *circuit_get_rendezvous(const char *cookie);
1879 or_circuit_t *circuit_get_intro_point(const char *digest);
1880 origin_circuit_t *circuit_find_to_cannibalize(uint8_t purpose,
1881 extend_info_t *info,
1882 int need_uptime,
1883 int need_capacity, int internal);
1884 void circuit_mark_all_unused_circs(void);
1885 void circuit_expire_all_dirty_circs(void);
1886 void _circuit_mark_for_close(circuit_t *circ, int reason,
1887 int line, const char *file);
1888 int circuit_get_cpath_len(origin_circuit_t *circ);
1890 #define circuit_mark_for_close(c, reason) \
1891 _circuit_mark_for_close((c), (reason), __LINE__, _SHORT_FILE_)
1893 void assert_cpath_layer_ok(const crypt_path_t *cp);
1894 void assert_circuit_ok(const circuit_t *c);
1895 void circuit_free_all(void);
1897 /********************************* circuituse.c ************************/
1899 void circuit_expire_building(time_t now);
1900 void circuit_remove_handled_ports(smartlist_t *needed_ports);
1901 int circuit_stream_is_being_handled(edge_connection_t *conn, uint16_t port,
1902 int min);
1903 void circuit_build_needed_circs(time_t now);
1904 void circuit_detach_stream(circuit_t *circ, edge_connection_t *conn);
1906 void reset_bandwidth_test(void);
1907 int circuit_enough_testing_circs(void);
1909 void circuit_has_opened(origin_circuit_t *circ);
1910 void circuit_build_failed(origin_circuit_t *circ);
1911 origin_circuit_t *circuit_launch_by_nickname(uint8_t purpose,
1912 int onehop_tunnel,
1913 const char *exit_nickname,
1914 int need_uptime, int need_capacity,
1915 int is_internal);
1916 origin_circuit_t *circuit_launch_by_extend_info(uint8_t purpose,
1917 int onehop_tunnel,
1918 extend_info_t *info,
1919 int need_uptime, int need_capacity,
1920 int is_internal);
1921 origin_circuit_t *circuit_launch_by_router(uint8_t purpose,
1922 int onehop_tunnel,
1923 routerinfo_t *exit,
1924 int need_uptime, int need_capacity,
1925 int is_internal);
1926 void circuit_reset_failure_count(int timeout);
1927 int connection_ap_handshake_attach_chosen_circuit(edge_connection_t *conn,
1928 origin_circuit_t *circ);
1929 int connection_ap_handshake_attach_circuit(edge_connection_t *conn);
1931 /********************************* command.c ***************************/
1933 void command_process_cell(cell_t *cell, or_connection_t *conn);
1935 extern uint64_t stats_n_padding_cells_processed;
1936 extern uint64_t stats_n_create_cells_processed;
1937 extern uint64_t stats_n_created_cells_processed;
1938 extern uint64_t stats_n_relay_cells_processed;
1939 extern uint64_t stats_n_destroy_cells_processed;
1941 /********************************* config.c ***************************/
1943 or_options_t *get_options(void);
1944 int set_options(or_options_t *new_val, char **msg);
1945 void config_free_all(void);
1946 const char *safe_str(const char *address);
1947 const char *escaped_safe_str(const char *address);
1949 int config_get_lines(char *string, config_line_t **result);
1950 void config_free_lines(config_line_t *front);
1951 int options_trial_assign(config_line_t *list, int use_defaults,
1952 int clear_first, char **msg);
1953 int resolve_my_address(int warn_severity, or_options_t *options,
1954 uint32_t *addr, char **hostname_out);
1955 int is_local_IP(uint32_t ip) ATTR_PURE;
1956 void options_init(or_options_t *options);
1957 int options_init_from_torrc(int argc, char **argv);
1958 int options_init_logs(or_options_t *options, int validate_only);
1959 int option_is_recognized(const char *key);
1960 const char *option_get_canonical_name(const char *key);
1961 config_line_t *option_get_assignment(or_options_t *options,
1962 const char *key);
1963 char *options_dump(or_options_t *options, int minimal);
1964 int options_save_current(void);
1965 const char *get_torrc_fname(void);
1967 or_state_t *get_or_state(void);
1968 int or_state_load(void);
1969 int or_state_save(time_t now);
1971 int getinfo_helper_config(control_connection_t *conn,
1972 const char *question, char **answer);
1974 /********************************* connection.c ***************************/
1976 const char *conn_type_to_string(int type);
1977 const char *conn_state_to_string(int type, int state);
1979 connection_t *connection_new(int type);
1980 void connection_unregister(connection_t *conn);
1981 void connection_free(connection_t *conn);
1982 void connection_free_all(void);
1983 void connection_about_to_close_connection(connection_t *conn);
1984 void connection_close_immediate(connection_t *conn);
1985 void _connection_mark_for_close(connection_t *conn,int line, const char *file);
1987 #define connection_mark_for_close(c) \
1988 _connection_mark_for_close((c), __LINE__, _SHORT_FILE_)
1990 void connection_expire_held_open(void);
1992 int connection_connect(connection_t *conn, char *address, uint32_t addr,
1993 uint16_t port);
1994 int retry_all_listeners(int force, smartlist_t *replaced_conns,
1995 smartlist_t *new_conns);
1997 int connection_bucket_write_limit(connection_t *conn);
1998 int global_write_bucket_low(size_t attempt, int priority);
1999 void connection_bucket_init(void);
2000 void connection_bucket_refill(int seconds_elapsed);
2002 int connection_handle_read(connection_t *conn);
2004 int connection_fetch_from_buf(char *string, size_t len, connection_t *conn);
2006 int connection_wants_to_flush(connection_t *conn);
2007 int connection_outbuf_too_full(connection_t *conn);
2008 int connection_handle_write(connection_t *conn, int force);
2009 void _connection_write_to_buf_impl(const char *string, size_t len,
2010 connection_t *conn, int zlib);
2011 static void connection_write_to_buf(const char *string, size_t len,
2012 connection_t *conn);
2013 static void connection_write_to_buf_zlib(const char *string, size_t len,
2014 dir_connection_t *conn, int done);
2015 static INLINE void
2016 connection_write_to_buf(const char *string, size_t len, connection_t *conn)
2018 _connection_write_to_buf_impl(string, len, conn, 0);
2020 static INLINE void
2021 connection_write_to_buf_zlib(const char *string, size_t len,
2022 dir_connection_t *conn, int done)
2024 _connection_write_to_buf_impl(string, len, TO_CONN(conn), done ? -1 : 1);
2027 or_connection_t *connection_or_exact_get_by_addr_port(uint32_t addr,
2028 uint16_t port);
2029 edge_connection_t *connection_get_by_global_id(uint32_t id);
2031 connection_t *connection_get_by_type(int type);
2032 connection_t *connection_get_by_type_purpose(int type, int purpose);
2033 connection_t *connection_get_by_type_addr_port_purpose(int type, uint32_t addr,
2034 uint16_t port, int purpose);
2035 connection_t *connection_get_by_type_state(int type, int state);
2036 connection_t *connection_get_by_type_state_lastwritten(int type, int state);
2037 connection_t *connection_get_by_type_state_rendquery(int type, int state,
2038 const char *rendquery);
2040 #define connection_speaks_cells(conn) ((conn)->type == CONN_TYPE_OR)
2041 int connection_is_listener(connection_t *conn);
2042 int connection_state_is_open(connection_t *conn);
2043 int connection_state_is_connecting(connection_t *conn);
2045 char *alloc_http_authenticator(const char *authenticator);
2047 void assert_connection_ok(connection_t *conn, time_t now);
2048 int connection_or_nonopen_was_started_here(or_connection_t *conn);
2050 /********************************* connection_edge.c *************************/
2052 #define connection_mark_unattached_ap(conn, endreason) \
2053 _connection_mark_unattached_ap((conn), (endreason), __LINE__, _SHORT_FILE_)
2055 void _connection_mark_unattached_ap(edge_connection_t *conn, int endreason,
2056 int line, const char *file);
2057 int connection_edge_reached_eof(edge_connection_t *conn);
2058 int connection_edge_process_inbuf(edge_connection_t *conn,
2059 int package_partial);
2060 int connection_edge_destroy(uint16_t circ_id, edge_connection_t *conn);
2061 int connection_edge_end(edge_connection_t *conn, char reason,
2062 crypt_path_t *cpath_layer);
2063 int connection_edge_end_errno(edge_connection_t *conn,
2064 crypt_path_t *cpath_layer);
2065 int connection_edge_finished_flushing(edge_connection_t *conn);
2066 int connection_edge_finished_connecting(edge_connection_t *conn);
2068 int connection_ap_handshake_send_begin(edge_connection_t *ap_conn,
2069 origin_circuit_t *circ);
2070 int connection_ap_handshake_send_resolve(edge_connection_t *ap_conn,
2071 origin_circuit_t *circ);
2073 int connection_ap_make_bridge(char *address, uint16_t port,
2074 const char *digest, int command);
2075 void connection_ap_handshake_socks_reply(edge_connection_t *conn, char *reply,
2076 size_t replylen,
2077 int endreason);
2078 void connection_ap_handshake_socks_resolved(edge_connection_t *conn,
2079 int answer_type,
2080 size_t answer_len,
2081 const char *answer,
2082 int ttl);
2084 int connection_exit_begin_conn(cell_t *cell, circuit_t *circ);
2085 int connection_exit_begin_resolve(cell_t *cell, or_circuit_t *circ);
2086 void connection_exit_connect(edge_connection_t *conn);
2087 int connection_edge_is_rendezvous_stream(edge_connection_t *conn);
2088 int connection_ap_can_use_exit(edge_connection_t *conn, routerinfo_t *exit);
2089 void connection_ap_expire_beginning(void);
2090 void connection_ap_attach_pending(void);
2091 void circuit_discard_optional_exit_enclaves(extend_info_t *info);
2092 int connection_ap_detach_retriable(edge_connection_t *conn,
2093 origin_circuit_t *circ,
2094 int reason);
2095 int connection_ap_process_transparent(edge_connection_t *conn);
2097 int address_is_invalid_destination(const char *address);
2099 void addressmap_init(void);
2100 void addressmap_clean(time_t now);
2101 void addressmap_clear_configured(void);
2102 void addressmap_clear_transient(void);
2103 void addressmap_free_all(void);
2104 void addressmap_rewrite(char *address, size_t maxlen);
2105 int addressmap_have_mapping(const char *address);
2106 void addressmap_register(const char *address, char *new_address,
2107 time_t expires);
2108 int parse_virtual_addr_network(const char *val, int validate_only,
2109 char **msg);
2110 int client_dns_incr_failures(const char *address);
2111 void client_dns_clear_failures(const char *address);
2112 void client_dns_set_addressmap(const char *address, uint32_t val,
2113 const char *exitname, int ttl);
2114 int address_is_in_virtual_range(const char *addr);
2115 const char *addressmap_register_virtual_address(int type, char *new_address);
2116 void addressmap_get_mappings(smartlist_t *sl, time_t min_expires,
2117 time_t max_expires);
2118 int connection_ap_handshake_rewrite_and_attach(edge_connection_t *conn,
2119 origin_circuit_t *circ);
2121 void set_exit_redirects(smartlist_t *lst);
2122 typedef enum hostname_type_t {
2123 NORMAL_HOSTNAME, ONION_HOSTNAME, EXIT_HOSTNAME, BAD_HOSTNAME
2124 } hostname_type_t;
2125 hostname_type_t parse_extended_hostname(char *address);
2127 /********************************* connection_or.c ***************************/
2129 void connection_or_remove_from_identity_map(or_connection_t *conn);
2130 void connection_or_clear_identity_map(void);
2131 or_connection_t *connection_or_get_by_identity_digest(const char *digest);
2133 int connection_or_reached_eof(or_connection_t *conn);
2134 int connection_or_process_inbuf(or_connection_t *conn);
2135 int connection_or_finished_flushing(or_connection_t *conn);
2136 int connection_or_finished_connecting(or_connection_t *conn);
2138 or_connection_t *connection_or_connect(uint32_t addr, uint16_t port,
2139 const char *id_digest);
2141 int connection_tls_start_handshake(or_connection_t *conn, int receiving);
2142 int connection_tls_continue_handshake(or_connection_t *conn);
2144 void connection_or_write_cell_to_buf(const cell_t *cell,
2145 or_connection_t *conn);
2146 int connection_or_send_destroy(uint16_t circ_id, or_connection_t *conn,
2147 int reason);
2149 /********************************* control.c ***************************/
2151 typedef enum circuit_status_event_t {
2152 CIRC_EVENT_LAUNCHED = 0,
2153 CIRC_EVENT_BUILT = 1,
2154 CIRC_EVENT_EXTENDED = 2,
2155 CIRC_EVENT_FAILED = 3,
2156 CIRC_EVENT_CLOSED = 4,
2157 } circuit_status_event_t;
2159 typedef enum stream_status_event_t {
2160 STREAM_EVENT_SENT_CONNECT = 0,
2161 STREAM_EVENT_SENT_RESOLVE = 1,
2162 STREAM_EVENT_SUCCEEDED = 2,
2163 STREAM_EVENT_FAILED = 3,
2164 STREAM_EVENT_CLOSED = 4,
2165 STREAM_EVENT_NEW = 5,
2166 STREAM_EVENT_NEW_RESOLVE = 6,
2167 STREAM_EVENT_FAILED_RETRIABLE = 7
2168 } stream_status_event_t;
2170 typedef enum or_conn_status_event_t {
2171 OR_CONN_EVENT_LAUNCHED = 0,
2172 OR_CONN_EVENT_CONNECTED = 1,
2173 OR_CONN_EVENT_FAILED = 2,
2174 OR_CONN_EVENT_CLOSED = 3,
2175 OR_CONN_EVENT_NEW = 4,
2176 } or_conn_status_event_t;
2178 void control_update_global_event_mask(void);
2179 void control_adjust_event_log_severity(void);
2181 /** Execute the statement <b>stmt</b>, which may log events concerning the
2182 * connection <b>conn</b>. To prevent infinite loops, disable log messages
2183 * being sent to controllers if <b>conn</b> is a control connection.
2185 * Stmt must not contain any return or goto statements.
2187 #define CONN_LOG_PROTECT(conn, stmt) \
2188 do { \
2189 int _log_conn_is_control = (conn && conn->type == CONN_TYPE_CONTROL); \
2190 if (_log_conn_is_control) \
2191 disable_control_logging(); \
2192 do {stmt;} while (0); \
2193 if (_log_conn_is_control) \
2194 enable_control_logging(); \
2195 } while (0)
2197 /** Log information about the connection <b>conn</b>, protecting it as with
2198 * CONN_LOG_PROTECT. Example:
2200 * LOG_FN_CONN(conn, (LOG_DEBUG, "Socket %d wants to write", conn->s));
2202 #define LOG_FN_CONN(conn, args) \
2203 CONN_LOG_PROTECT(conn, log_fn args)
2205 int connection_control_finished_flushing(control_connection_t *conn);
2206 int connection_control_reached_eof(control_connection_t *conn);
2207 int connection_control_process_inbuf(control_connection_t *conn);
2209 int control_event_circuit_status(origin_circuit_t *circ,
2210 circuit_status_event_t e, int reason);
2211 int control_event_stream_status(edge_connection_t *conn,
2212 stream_status_event_t e,
2213 int reason);
2214 int control_event_or_conn_status(or_connection_t *conn,
2215 or_conn_status_event_t e);
2216 int control_event_bandwidth_used(uint32_t n_read, uint32_t n_written);
2217 void control_event_logmsg(int severity, unsigned int domain, const char *msg);
2218 int control_event_descriptors_changed(smartlist_t *routers);
2219 int control_event_address_mapped(const char *from, const char *to,
2220 time_t expires);
2221 int control_event_or_authdir_new_descriptor(const char *action,
2222 const char *descriptor,
2223 const char *msg);
2224 int control_event_my_descriptor_changed(void);
2225 int control_event_networkstatus_changed(smartlist_t *statuses);
2226 int control_event_networkstatus_changed_single(local_routerstatus_t *rs);
2227 int control_event_general_status(int severity, const char *format, ...)
2228 CHECK_PRINTF(2,3);
2229 int control_event_client_status(int severity, const char *format, ...)
2230 CHECK_PRINTF(2,3);
2231 int control_event_server_status(int severity, const char *format, ...)
2232 CHECK_PRINTF(2,3);
2233 int control_event_guard(const char *nickname, const char *digest,
2234 const char *status);
2236 int init_cookie_authentication(int enabled);
2237 int decode_hashed_password(char *buf, const char *hashed);
2238 void disable_control_logging(void);
2239 void enable_control_logging(void);
2241 /********************************* cpuworker.c *****************************/
2243 void cpu_init(void);
2244 void cpuworkers_rotate(void);
2245 int connection_cpu_finished_flushing(connection_t *conn);
2246 int connection_cpu_reached_eof(connection_t *conn);
2247 int connection_cpu_process_inbuf(connection_t *conn);
2248 int assign_to_cpuworker(connection_t *cpuworker, uint8_t question_type,
2249 void *task);
2251 /********************************* directory.c ***************************/
2253 void directory_post_to_dirservers(uint8_t purpose, const char *payload,
2254 size_t payload_len);
2255 void directory_get_from_dirserver(uint8_t purpose, const char *resource,
2256 int retry_if_no_servers);
2257 void directory_initiate_command_router(routerinfo_t *router, uint8_t purpose,
2258 int private_connection,
2259 const char *resource,
2260 const char *payload,
2261 size_t payload_len);
2262 void directory_initiate_command_routerstatus(routerstatus_t *status,
2263 uint8_t purpose,
2264 int private_connection,
2265 const char *resource,
2266 const char *payload,
2267 size_t payload_len);
2269 int parse_http_response(const char *headers, int *code, time_t *date,
2270 compress_method_t *compression, char **response);
2272 int connection_dir_reached_eof(dir_connection_t *conn);
2273 int connection_dir_process_inbuf(dir_connection_t *conn);
2274 int connection_dir_finished_flushing(dir_connection_t *conn);
2275 int connection_dir_finished_connecting(dir_connection_t *conn);
2276 void connection_dir_request_failed(dir_connection_t *conn);
2277 int dir_split_resource_into_fingerprints(const char *resource,
2278 smartlist_t *fp_out, int *compresseed_out,
2279 int decode_hex, int sort_uniq);
2280 char *directory_dump_request_log(void);
2282 /********************************* dirserv.c ***************************/
2284 #define UNNAMED_ROUTER_NICKNAME "Unnamed"
2286 int connection_dirserv_flushed_some(dir_connection_t *conn);
2287 int dirserv_add_own_fingerprint(const char *nickname, crypto_pk_env_t *pk);
2288 int dirserv_load_fingerprint_file(void);
2289 void dirserv_free_fingerprint_list(void);
2290 const char *dirserv_get_nickname_by_digest(const char *digest);
2291 int dirserv_add_descriptor(const char *desc, const char **msg);
2292 int getinfo_helper_dirserv_unregistered(control_connection_t *conn,
2293 const char *question, char **answer);
2294 void dirserv_free_descriptors(void);
2295 int dirserv_thinks_router_is_blatantly_unreachable(routerinfo_t *router,
2296 time_t now);
2297 int list_server_status(smartlist_t *routers, char **router_status_out,
2298 int for_controller);
2299 int dirserv_dump_directory_to_string(char **dir_out,
2300 crypto_pk_env_t *private_key,
2301 int complete);
2302 void directory_set_dirty(void);
2303 cached_dir_t *dirserv_get_directory(void);
2304 size_t dirserv_get_runningrouters(const char **rr, int compress);
2305 void dirserv_set_cached_directory(const char *directory, time_t when,
2306 int is_running_routers);
2307 void dirserv_set_cached_networkstatus_v2(const char *directory,
2308 const char *identity,
2309 time_t published);
2310 void dirserv_get_networkstatus_v2(smartlist_t *result, const char *key);
2311 void dirserv_get_networkstatus_v2_fingerprints(smartlist_t *result,
2312 const char *key);
2313 int dirserv_get_routerdesc_fingerprints(smartlist_t *fps_out, const char *key,
2314 const char **msg);
2315 int dirserv_get_routerdescs(smartlist_t *descs_out, const char *key,
2316 const char **msg);
2317 void dirserv_orconn_tls_done(const char *address,
2318 uint16_t or_port,
2319 const char *digest_rcvd,
2320 const char *nickname,
2321 int as_advertised);
2322 void dirserv_test_reachability(int try_all);
2323 int authdir_wants_to_reject_router(routerinfo_t *ri, const char **msg,
2324 int complain);
2325 int dirserv_would_reject_router(routerstatus_t *rs);
2326 size_t dirserv_estimate_data_size(smartlist_t *fps, int is_serverdescs,
2327 int compressed);
2328 void dirserv_free_all(void);
2329 void cached_dir_decref(cached_dir_t *d);
2331 /********************************* dns.c ***************************/
2333 int dns_init(void);
2334 void dns_free_all(void);
2335 uint32_t dns_clip_ttl(uint32_t ttl);
2336 int connection_dns_finished_flushing(connection_t *conn);
2337 int connection_dns_reached_eof(connection_t *conn);
2338 int connection_dns_process_inbuf(connection_t *conn);
2339 void dns_reset(void);
2340 void connection_dns_remove(edge_connection_t *conn);
2341 void assert_connection_edge_not_dns_pending(edge_connection_t *conn);
2342 void assert_all_pending_dns_resolves_ok(void);
2343 void dns_cancel_pending_resolve(const char *question);
2344 int dns_resolve(edge_connection_t *exitconn, or_circuit_t *circ);
2345 void dns_launch_correctness_checks(void);
2346 int dns_seems_to_be_broken(void);
2347 void dns_reset_correctness_checks(void);
2349 /********************************* hibernate.c **********************/
2351 int accounting_parse_options(or_options_t *options, int validate_only);
2352 int accounting_is_enabled(or_options_t *options);
2353 void configure_accounting(time_t now);
2354 void accounting_run_housekeeping(time_t now);
2355 void accounting_add_bytes(size_t n_read, size_t n_written, int seconds);
2356 int accounting_record_bandwidth_usage(time_t now, or_state_t *state);
2357 void hibernate_begin_shutdown(void);
2358 int we_are_hibernating(void);
2359 void consider_hibernation(time_t now);
2360 int getinfo_helper_accounting(control_connection_t *conn,
2361 const char *question, char **answer);
2362 void accounting_set_bandwidth_usage_from_state(or_state_t *state);
2364 /********************************* main.c ***************************/
2366 extern int has_completed_circuit;
2368 int connection_add(connection_t *conn);
2369 int connection_remove(connection_t *conn);
2370 int connection_in_array(connection_t *conn);
2371 void add_connection_to_closeable_list(connection_t *conn);
2372 int connection_is_on_closeable_list(connection_t *conn);
2374 void get_connection_array(connection_t ***array, int *n);
2376 void connection_watch_events(connection_t *conn, short events);
2377 int connection_is_reading(connection_t *conn);
2378 void connection_stop_reading(connection_t *conn);
2379 void connection_start_reading(connection_t *conn);
2381 int connection_is_writing(connection_t *conn);
2382 void connection_stop_writing(connection_t *conn);
2383 void connection_start_writing(connection_t *conn);
2385 void directory_all_unreachable(time_t now);
2386 void directory_info_has_arrived(time_t now, int from_cache);
2388 void ip_address_changed(int at_interface);
2389 void dns_servers_relaunch_checks(void);
2391 void control_signal_act(int the_signal);
2392 void handle_signals(int is_parent);
2393 void tor_cleanup(void);
2394 void tor_free_all(int postfork);
2396 int tor_main(int argc, char *argv[]);
2398 /********************************* onion.c ***************************/
2400 int onion_pending_add(or_circuit_t *circ);
2401 or_circuit_t *onion_next_task(void);
2402 void onion_pending_remove(or_circuit_t *circ);
2404 int onion_skin_create(crypto_pk_env_t *router_key,
2405 crypto_dh_env_t **handshake_state_out,
2406 char *onion_skin_out);
2408 int onion_skin_server_handshake(const char *onion_skin,
2409 crypto_pk_env_t *private_key,
2410 crypto_pk_env_t *prev_private_key,
2411 char *handshake_reply_out,
2412 char *key_out,
2413 size_t key_out_len);
2415 int onion_skin_client_handshake(crypto_dh_env_t *handshake_state,
2416 const char *handshake_reply,
2417 char *key_out,
2418 size_t key_out_len);
2420 int fast_server_handshake(const char *key_in,
2421 char *handshake_reply_out,
2422 char *key_out,
2423 size_t key_out_len);
2425 int fast_client_handshake(const char *handshake_state,
2426 const char *handshake_reply_out,
2427 char *key_out,
2428 size_t key_out_len);
2430 void clear_pending_onions(void);
2432 /********************************* policies.c ************************/
2434 /* (length of "accept 255.255.255.255/255.255.255.255:65535-65535\n" plus a
2435 * nul.)
2437 #define POLICY_BUF_LEN 52
2439 typedef enum {
2440 ADDR_POLICY_ACCEPTED=0,
2441 ADDR_POLICY_REJECTED=-1,
2442 ADDR_POLICY_PROBABLY_ACCEPTED=1,
2443 ADDR_POLICY_PROBABLY_REJECTED=2
2444 } addr_policy_result_t;
2446 int firewall_is_fascist_or(void);
2447 int fascist_firewall_allows_address_or(uint32_t addr, uint16_t port);
2448 int fascist_firewall_allows_address_dir(uint32_t addr, uint16_t port);
2449 int dir_policy_permits_address(uint32_t addr);
2450 int socks_policy_permits_address(uint32_t addr);
2451 int authdir_policy_permits_address(uint32_t addr, uint16_t port);
2452 int authdir_policy_valid_address(uint32_t addr, uint16_t port);
2453 int authdir_policy_badexit_address(uint32_t addr, uint16_t port);
2455 int validate_addr_policies(or_options_t *options, char **msg);
2456 void policies_parse_from_options(or_options_t *options);
2458 int cmp_addr_policies(addr_policy_t *a, addr_policy_t *b);
2459 addr_policy_result_t compare_addr_to_addr_policy(uint32_t addr,
2460 uint16_t port, addr_policy_t *policy);
2461 int policies_parse_exit_policy(config_line_t *cfg,
2462 addr_policy_t **dest,
2463 int rejectprivate);
2464 int exit_policy_is_general_exit(addr_policy_t *policy);
2465 int policy_is_reject_star(addr_policy_t *policy);
2466 int getinfo_helper_policies(control_connection_t *conn,
2467 const char *question, char **answer);
2468 int policy_write_item(char *buf, size_t buflen, addr_policy_t *policy);
2470 void addr_policy_free(addr_policy_t *p);
2471 void policies_free_all(void);
2473 /********************************* relay.c ***************************/
2475 extern uint64_t stats_n_relay_cells_relayed;
2476 extern uint64_t stats_n_relay_cells_delivered;
2478 int circuit_receive_relay_cell(cell_t *cell, circuit_t *circ,
2479 int cell_direction);
2481 void relay_header_pack(char *dest, const relay_header_t *src);
2482 void relay_header_unpack(relay_header_t *dest, const char *src);
2483 int relay_send_command_from_edge(uint16_t stream_id, circuit_t *circ,
2484 int relay_command, const char *payload,
2485 size_t payload_len, crypt_path_t *cpath_layer);
2486 int connection_edge_send_command(edge_connection_t *fromconn, circuit_t *circ,
2487 int relay_command, const char *payload,
2488 size_t payload_len,
2489 crypt_path_t *cpath_layer);
2490 int connection_edge_package_raw_inbuf(edge_connection_t *conn,
2491 int package_partial);
2492 void connection_edge_consider_sending_sendme(edge_connection_t *conn);
2493 socks5_reply_status_t connection_edge_end_reason_socks5_response(int reason);
2494 int errno_to_end_reason(int e);
2496 extern uint64_t stats_n_data_cells_packaged;
2497 extern uint64_t stats_n_data_bytes_packaged;
2498 extern uint64_t stats_n_data_cells_received;
2499 extern uint64_t stats_n_data_bytes_received;
2501 /********************************* rephist.c ***************************/
2503 void rep_hist_init(void);
2504 void rep_hist_note_connect_failed(const char* nickname, time_t when);
2505 void rep_hist_note_connect_succeeded(const char* nickname, time_t when);
2506 void rep_hist_note_disconnect(const char* nickname, time_t when);
2507 void rep_hist_note_connection_died(const char* nickname, time_t when);
2508 void rep_hist_note_extend_succeeded(const char *from_name,
2509 const char *to_name);
2510 void rep_hist_note_extend_failed(const char *from_name, const char *to_name);
2511 void rep_hist_dump_stats(time_t now, int severity);
2512 void rep_hist_note_bytes_read(int num_bytes, time_t when);
2513 void rep_hist_note_bytes_written(int num_bytes, time_t when);
2514 int rep_hist_bandwidth_assess(void);
2515 char *rep_hist_get_bandwidth_lines(void);
2516 void rep_hist_update_state(or_state_t *state);
2517 int rep_hist_load_state(or_state_t *state, char **err);
2518 void rep_history_clean(time_t before);
2520 void rep_hist_note_used_port(uint16_t port, time_t now);
2521 smartlist_t *rep_hist_get_predicted_ports(time_t now);
2522 void rep_hist_note_used_resolve(time_t now);
2523 void rep_hist_note_used_internal(time_t now, int need_uptime,
2524 int need_capacity);
2525 int rep_hist_get_predicted_internal(time_t now, int *need_uptime,
2526 int *need_capacity);
2528 int any_predicted_circuits(time_t now);
2529 int rep_hist_circbuilding_dormant(time_t now);
2531 typedef enum {
2532 SIGN_DIR, SIGN_RTR,
2533 VERIFY_DIR, VERIFY_RTR,
2534 ENC_ONIONSKIN, DEC_ONIONSKIN,
2535 TLS_HANDSHAKE_C, TLS_HANDSHAKE_S,
2536 REND_CLIENT, REND_MID, REND_SERVER,
2537 } pk_op_t;
2538 void note_crypto_pk_op(pk_op_t operation);
2539 void dump_pk_ops(int severity);
2541 void rep_hist_free_all(void);
2543 /********************************* rendclient.c ***************************/
2545 void rend_client_introcirc_has_opened(origin_circuit_t *circ);
2546 void rend_client_rendcirc_has_opened(origin_circuit_t *circ);
2547 int rend_client_introduction_acked(origin_circuit_t *circ, const char *request,
2548 size_t request_len);
2549 void rend_client_refetch_renddesc(const char *query);
2550 int rend_client_remove_intro_point(extend_info_t *failed_intro,
2551 const char *query);
2552 int rend_client_rendezvous_acked(origin_circuit_t *circ, const char *request,
2553 size_t request_len);
2554 int rend_client_receive_rendezvous(origin_circuit_t *circ, const char *request,
2555 size_t request_len);
2556 void rend_client_desc_here(const char *query);
2558 extend_info_t *rend_client_get_random_intro(const char *query);
2560 int rend_client_send_introduction(origin_circuit_t *introcirc,
2561 origin_circuit_t *rendcirc);
2563 /********************************* rendcommon.c ***************************/
2565 /** Information used to connect to a hidden service. */
2566 typedef struct rend_service_descriptor_t {
2567 crypto_pk_env_t *pk; /**< This service's public key. */
2568 int version; /**< 0 or 1. */
2569 time_t timestamp; /**< Time when the descriptor was generated. */
2570 uint16_t protocols; /**< Bitmask: which rendezvous protocols are supported?
2571 * (We allow bits '0', '1', and '2' to be set.) */
2572 int n_intro_points; /**< Number of introduction points. */
2573 /** Array of n_intro_points elements for this service's introduction points'
2574 * nicknames. Elements are removed from this array if introduction attempts
2575 * fail. */
2576 char **intro_points;
2577 /** Array of n_intro_points elements for this service's introduction points'
2578 * extend_infos, or NULL if this descriptor is V0. Elements are removed
2579 * from this array if introduction attempts fail. If this array is present,
2580 * its elements correspond to the elements of intro_points. */
2581 extend_info_t **intro_point_extend_info;
2582 } rend_service_descriptor_t;
2584 int rend_cmp_service_ids(const char *one, const char *two);
2586 void rend_process_relay_cell(circuit_t *circ, int command, size_t length,
2587 const char *payload);
2589 void rend_service_descriptor_free(rend_service_descriptor_t *desc);
2590 int rend_encode_service_descriptor(rend_service_descriptor_t *desc,
2591 int version,
2592 crypto_pk_env_t *key,
2593 char **str_out,
2594 size_t *len_out);
2595 rend_service_descriptor_t *rend_parse_service_descriptor(const char *str,
2596 size_t len);
2597 int rend_get_service_id(crypto_pk_env_t *pk, char *out);
2599 /** A cached rendezvous descriptor. */
2600 typedef struct rend_cache_entry_t {
2601 size_t len; /** Length of <b>desc</b> */
2602 time_t received; /** When was the descriptor received? */
2603 char *desc; /** Service descriptor */
2604 rend_service_descriptor_t *parsed; /* Parsed value of 'desc' */
2605 } rend_cache_entry_t;
2607 void rend_cache_init(void);
2608 void rend_cache_clean(void);
2609 void rend_cache_free_all(void);
2610 int rend_valid_service_id(const char *query);
2611 int rend_cache_lookup_desc(const char *query, int version, const char **desc,
2612 size_t *desc_len);
2613 int rend_cache_lookup_entry(const char *query, int version,
2614 rend_cache_entry_t **entry_out);
2615 int rend_cache_store(const char *desc, size_t desc_len);
2617 /********************************* rendservice.c ***************************/
2619 int num_rend_services(void);
2620 int rend_config_services(or_options_t *options, int validate_only);
2621 int rend_service_load_keys(void);
2622 void rend_services_init(void);
2623 void rend_services_introduce(void);
2624 void rend_consider_services_upload(time_t now);
2626 void rend_service_intro_has_opened(origin_circuit_t *circuit);
2627 int rend_service_intro_established(origin_circuit_t *circuit,
2628 const char *request,
2629 size_t request_len);
2630 void rend_service_rendezvous_has_opened(origin_circuit_t *circuit);
2631 int rend_service_introduce(origin_circuit_t *circuit, const char *request,
2632 size_t request_len);
2633 void rend_service_relaunch_rendezvous(origin_circuit_t *oldcirc);
2634 int rend_service_set_connection_addr_port(edge_connection_t *conn,
2635 origin_circuit_t *circ);
2636 void rend_service_dump_stats(int severity);
2637 void rend_service_free_all(void);
2639 /********************************* rendmid.c *******************************/
2640 int rend_mid_establish_intro(or_circuit_t *circ, const char *request,
2641 size_t request_len);
2642 int rend_mid_introduce(or_circuit_t *circ, const char *request,
2643 size_t request_len);
2644 int rend_mid_establish_rendezvous(or_circuit_t *circ, const char *request,
2645 size_t request_len);
2646 int rend_mid_rendezvous(or_circuit_t *circ, const char *request,
2647 size_t request_len);
2649 /********************************* router.c ***************************/
2651 crypto_pk_env_t *get_onion_key(void);
2652 time_t get_onion_key_set_at(void);
2653 void set_identity_key(crypto_pk_env_t *k);
2654 crypto_pk_env_t *get_identity_key(void);
2655 int identity_key_is_set(void);
2656 void dup_onion_keys(crypto_pk_env_t **key, crypto_pk_env_t **last);
2657 void rotate_onion_key(void);
2658 crypto_pk_env_t *init_key_from_file(const char *fname);
2659 int init_keys(void);
2661 int check_whether_orport_reachable(void);
2662 int check_whether_dirport_reachable(void);
2663 void consider_testing_reachability(int test_or, int test_dir);
2664 void router_orport_found_reachable(void);
2665 void router_dirport_found_reachable(void);
2666 void router_perform_bandwidth_test(int num_circs, time_t now);
2668 int authdir_mode(or_options_t *options);
2669 int clique_mode(or_options_t *options);
2670 int server_mode(or_options_t *options);
2671 int advertised_server_mode(void);
2672 int proxy_mode(or_options_t *options);
2673 void consider_publishable_server(int force);
2675 int router_is_clique_mode(routerinfo_t *router);
2676 void router_upload_dir_desc_to_dirservers(int force);
2677 void mark_my_descriptor_dirty_if_older_than(time_t when);
2678 void mark_my_descriptor_dirty(void);
2679 void check_descriptor_bandwidth_changed(time_t now);
2680 void check_descriptor_ipaddress_changed(time_t now);
2681 void router_new_address_suggestion(const char *suggestion);
2682 int router_compare_to_my_exit_policy(edge_connection_t *conn);
2683 routerinfo_t *router_get_my_routerinfo(void);
2684 const char *router_get_my_descriptor(void);
2685 int router_digest_is_me(const char *digest);
2686 int router_is_me(routerinfo_t *router);
2687 int router_fingerprint_is_me(const char *fp);
2688 int router_pick_published_address(or_options_t *options, uint32_t *addr);
2689 int router_rebuild_descriptor(int force);
2690 int router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
2691 crypto_pk_env_t *ident_key);
2692 int is_legal_nickname(const char *s);
2693 int is_legal_nickname_or_hexdigest(const char *s);
2694 int is_legal_hexdigest(const char *s);
2695 void router_get_verbose_nickname(char *buf, routerinfo_t *router);
2696 void router_reset_warnings(void);
2697 void router_reset_reachability(void);
2698 void router_free_all(void);
2700 /********************************* routerlist.c ***************************/
2702 /** Represents information about a single trusted directory server. */
2703 typedef struct trusted_dir_server_t {
2704 char *description;
2705 char *nickname;
2706 char *address; /**< Hostname. */
2707 uint32_t addr; /**< IPv4 address. */
2708 uint16_t dir_port; /**< Directory port. */
2709 uint16_t or_port; /**< OR port: Used for tunneling connections. */
2710 char digest[DIGEST_LEN]; /**< Digest of identity key. */
2711 unsigned int is_running:1; /**< True iff we think this server is running. */
2712 /** True iff this server is an authority for the older ("v1") directory
2713 * protocol. */
2714 unsigned int is_v1_authority:1;
2715 /** True iff this server is an authority for the newer ("v2") directory
2716 * protocol. */
2717 unsigned int is_v2_authority:1;
2718 /** True iff this server is an authority for hidden services. */
2719 unsigned int is_hidserv_authority:1;
2720 /** True iff this server has accepted the most recent server descriptor
2721 * we tried to upload to it. */
2722 unsigned int has_accepted_serverdesc:1;
2724 int n_networkstatus_failures; /**< How many times have we asked for this
2725 * server's network-status unsuccessfully? */
2726 local_routerstatus_t fake_status; /**< Used when we need to pass this trusted
2727 * dir_server_t to directory_initiate_command_*
2728 * as a routerstatus_t. Not updated by the
2729 * router-status management code!
2731 } trusted_dir_server_t;
2733 int router_reload_router_list(void);
2734 int router_reload_networkstatus(void);
2735 smartlist_t *router_get_trusted_dir_servers(void);
2736 routerstatus_t *router_pick_directory_server(int requireother,
2737 int fascistfirewall,
2738 int for_v2_directory,
2739 int retry_if_no_servers);
2740 typedef enum {
2741 V1_AUTHORITY, V2_AUTHORITY, HIDSERV_AUTHORITY,
2742 } authority_type_t;
2743 routerstatus_t *router_pick_trusteddirserver(authority_type_t type,
2744 int requireother,
2745 int fascistfirewall,
2746 int retry_if_no_servers);
2747 trusted_dir_server_t *router_get_trusteddirserver_by_digest(
2748 const char *digest);
2749 void routerlist_add_family(smartlist_t *sl, routerinfo_t *router);
2750 void add_nickname_list_to_smartlist(smartlist_t *sl, const char *list,
2751 int must_be_running,
2752 int warn_if_down, int warn_if_unnamed);
2753 int router_nickname_is_in_list(routerinfo_t *router, const char *list);
2754 routerinfo_t *routerlist_find_my_routerinfo(void);
2755 routerinfo_t *router_find_exact_exit_enclave(const char *address,
2756 uint16_t port);
2758 #define ROUTER_REQUIRED_MIN_BANDWIDTH 10000
2759 int router_is_unreliable(routerinfo_t *router, int need_uptime,
2760 int need_capacity, int need_guard);
2761 uint32_t router_get_advertised_bandwidth(routerinfo_t *router);
2762 routerinfo_t *routerlist_sl_choose_by_bandwidth(smartlist_t *sl, int for_exit);
2764 routerinfo_t *router_choose_random_node(const char *preferred,
2765 const char *excluded,
2766 smartlist_t *excludedsmartlist,
2767 int need_uptime, int need_bandwidth,
2768 int need_guard,
2769 int allow_invalid, int strict,
2770 int weight_for_exit);
2771 routerinfo_t *router_get_by_nickname(const char *nickname,
2772 int warn_if_unnamed);
2773 routerinfo_t *router_get_by_hexdigest(const char *hexdigest);
2774 routerinfo_t *router_get_by_digest(const char *digest);
2775 signed_descriptor_t *router_get_by_descriptor_digest(const char *digest);
2776 const char *signed_descriptor_get_body(signed_descriptor_t *desc);
2777 int router_digest_version_as_new_as(const char *digest, const char *cutoff);
2778 int router_digest_is_trusted_dir(const char *digest);
2779 routerlist_t *router_get_routerlist(void);
2780 void routerlist_reset_warnings(void);
2781 void routerlist_free(routerlist_t *routerlist);
2782 void dump_routerlist_mem_usage(int severity);
2783 void routerlist_remove(routerlist_t *rl, routerinfo_t *ri, int idx,
2784 int make_old);
2785 void routerinfo_free(routerinfo_t *router);
2786 void routerstatus_free(routerstatus_t *routerstatus);
2787 void networkstatus_free(networkstatus_t *networkstatus);
2788 void routerlist_free_all(void);
2789 routerinfo_t *routerinfo_copy(const routerinfo_t *router);
2790 void router_set_status(const char *digest, int up);
2791 void routerlist_remove_old_routers(void);
2792 void networkstatus_list_clean(time_t now);
2793 int router_add_to_routerlist(routerinfo_t *router, const char **msg,
2794 int from_cache, int from_fetch);
2795 int router_load_single_router(const char *s, uint8_t purpose,
2796 const char **msg);
2797 void router_load_routers_from_string(const char *s,
2798 saved_location_t saved_location,
2799 smartlist_t *requested_fingerprints);
2800 typedef enum {
2801 NS_FROM_CACHE, NS_FROM_DIR_BY_FP, NS_FROM_DIR_ALL, NS_GENERATED
2802 } networkstatus_source_t;
2803 int router_set_networkstatus(const char *s, time_t arrived_at,
2804 networkstatus_source_t source,
2805 smartlist_t *requested_fingerprints);
2807 int router_exit_policy_all_routers_reject(uint32_t addr, uint16_t port,
2808 int need_uptime);
2809 int router_exit_policy_rejects_all(routerinfo_t *router);
2811 void add_trusted_dir_server(const char *nickname, const char *address,
2812 uint16_t dir_port, uint16_t or_port,
2813 const char *digest, int is_v1_authority,
2814 int is_v2_authority, int is_hidserv_authority);
2815 void clear_trusted_dir_servers(void);
2816 int any_trusted_dir_is_v1_authority(void);
2817 networkstatus_t *networkstatus_get_by_digest(const char *digest);
2818 local_routerstatus_t *router_get_combined_status_by_digest(const char *digest);
2819 void update_networkstatus_downloads(time_t now);
2820 void update_router_descriptor_downloads(time_t now);
2821 void routers_update_all_from_networkstatus(void);
2822 void routers_update_status_from_networkstatus(smartlist_t *routers,
2823 int reset_failures);
2824 smartlist_t *router_list_superseded(void);
2825 int router_have_minimum_dir_info(void);
2826 void networkstatus_list_update_recent(time_t now);
2827 void router_reset_descriptor_download_failures(void);
2828 void router_reset_status_download_failures(void);
2829 int router_differences_are_cosmetic(routerinfo_t *r1, routerinfo_t *r2);
2830 const char *esc_router_info(routerinfo_t *router);
2832 char *networkstatus_getinfo_helper_single(routerstatus_t *rs);
2833 int getinfo_helper_networkstatus(control_connection_t *conn,
2834 const char *question, char **answer);
2836 /********************************* routerparse.c ************************/
2838 #define MAX_STATUS_TAG_LEN 32
2839 /** Structure to hold parsed Tor versions. This is a little messier
2840 * than we would like it to be, because we changed version schemes with 0.1.0.
2842 * See version-spec.txt for the whole business.
2844 typedef struct tor_version_t {
2845 int major;
2846 int minor;
2847 int micro;
2848 /** Release status. For version in the post-0.1 format, this is always
2849 * VER_RELEASE. */
2850 enum { VER_PRE=0, VER_RC=1, VER_RELEASE=2, } status;
2851 int patchlevel;
2852 char status_tag[MAX_STATUS_TAG_LEN];
2853 } tor_version_t;
2855 typedef enum version_status_t {
2856 VS_RECOMMENDED=0, /**< This version is listed as recommended. */
2857 VS_OLD=1, /**< This version is older than any recommended version. */
2858 VS_NEW=2, /**< This version is newer than any recommended version. */
2859 VS_NEW_IN_SERIES=3, /**< This version is newer than any recommended version
2860 * in its series, and such recommended versions exist. */
2861 VS_UNRECOMMENDED=4 /**< This version is not recommended (general case) */
2862 } version_status_t;
2864 int router_get_router_hash(const char *s, char *digest);
2865 int router_get_dir_hash(const char *s, char *digest);
2866 int router_get_runningrouters_hash(const char *s, char *digest);
2867 int router_get_networkstatus_v2_hash(const char *s, char *digest);
2868 int router_append_dirobj_signature(char *buf, size_t buf_len,
2869 const char *digest,
2870 crypto_pk_env_t *private_key);
2871 int router_parse_list_from_string(const char **s,
2872 smartlist_t *dest,
2873 saved_location_t saved_location);
2874 int router_parse_routerlist_from_directory(const char *s,
2875 routerlist_t **dest,
2876 crypto_pk_env_t *pkey,
2877 int check_version,
2878 int write_to_cache);
2879 int router_parse_runningrouters(const char *str);
2880 int router_parse_directory(const char *str);
2881 routerinfo_t *router_parse_entry_from_string(const char *s, const char *end,
2882 int cache_copy);
2883 addr_policy_t *router_parse_addr_policy_from_string(const char *s,
2884 int assume_action);
2885 version_status_t tor_version_is_obsolete(const char *myversion,
2886 const char *versionlist);
2887 version_status_t version_status_join(version_status_t a, version_status_t b);
2888 int tor_version_parse(const char *s, tor_version_t *out);
2889 int tor_version_as_new_as(const char *platform, const char *cutoff);
2890 int tor_version_compare(tor_version_t *a, tor_version_t *b);
2891 void sort_version_list(smartlist_t *lst, int remove_duplicates);
2892 void assert_addr_policy_ok(addr_policy_t *t);
2893 void dump_distinct_digest_count(int severity);
2895 networkstatus_t *networkstatus_parse_from_string(const char *s);
2897 #endif