bugfix on r9568: we were throwing around an uninitialized
[tor.git] / src / or / or.h
blob54b2f15bcd7952646ae0be7613bf8e739e6c4354
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2007, 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 /** Length of longest allowable configured nickname. */
159 #define MAX_NICKNAME_LEN 19
160 /** Length of a router identity encoded as a hexadecimal digest, plus
161 * possible dollar sign. */
162 #define MAX_HEX_NICKNAME_LEN (HEX_DIGEST_LEN+1)
163 /** Maximum length of verbose router identifier (Dollar sign, hex ID digest,
164 * equal or tilde, nickname) */
165 #define MAX_VERBOSE_NICKNAME_LEN (1+HEX_DIGEST_LEN+1+MAX_NICKNAME_LEN)
167 /** Maximum size, in bytes, for resized buffers. */
168 #define MAX_BUF_SIZE ((1<<24)-1) /* 16MB-1 */
169 /** Maximum size, in bytes, for any directory object that we've downloaded */
170 #define MAX_DIR_DL_SIZE MAX_BUF_SIZE
172 /** For http parsing: Maximum number of bytes we'll accept in the headers
173 * of an HTTP request or response.*/
174 #define MAX_HEADERS_SIZE 50000
175 /** Maximum size, in bytes, for any directory object that we're accepting
176 * as an upload. */
177 #define MAX_DIR_UL_SIZE 500000
179 /** How long do we keep DNS cache entries before purging them (regardless of
180 * their TTL)? */
181 #define MAX_DNS_ENTRY_AGE (30*60)
182 /** How long do we cache/tell clients to cache DNS records when no TTL is
183 * known? */
184 #define DEFAULT_DNS_TTL (30*60)
185 /** How long can a TTL be before we stop believing it? */
186 #define MAX_DNS_TTL (3*60*60)
187 /** How small can a TTL be before we stop believing it? */
188 #define MIN_DNS_TTL (60)
190 /** How often do we rotate onion keys? */
191 #define MIN_ONION_KEY_LIFETIME (7*24*60*60)
192 /** How often do we rotate TLS contexts? */
193 #define MAX_SSL_KEY_LIFETIME (2*60*60)
195 /** How old do we allow a router to get before removing it
196 * from the router list? In seconds. */
197 #define ROUTER_MAX_AGE (60*60*48)
198 /** How old can a router get before we (as a server) will no longer
199 * consider it live? In seconds. */
200 #define ROUTER_MAX_AGE_TO_PUBLISH (60*60*20)
201 /** How old do we let a saved descriptor get before force-removing it? */
202 #define OLD_ROUTER_DESC_MAX_AGE (60*60*24*5)
203 /** How old do we let a networkstatus get before ignoring it? */
204 #define NETWORKSTATUS_MAX_AGE (60*60*24)
206 /** Possible rules for generating circuit IDs on an OR connection. */
207 typedef enum {
208 CIRC_ID_TYPE_LOWER=0, /**< Pick from 0..1<<15-1. */
209 CIRC_ID_TYPE_HIGHER=1, /**< Pick from 1<<15..1<<16-1 */
210 /** The other side of a connection is an OP: never create circuits to it,
211 * and let it use any circuit ID it wants. */
212 CIRC_ID_TYPE_NEITHER=2
213 } circ_id_type_t;
215 #define _CONN_TYPE_MIN 3
216 /** Type for sockets listening for OR connections. */
217 #define CONN_TYPE_OR_LISTENER 3
218 /** A bidirectional TLS connection transmitting a sequence of cells.
219 * May be from an OR to an OR, or from an OP to an OR. */
220 #define CONN_TYPE_OR 4
221 /** A TCP connection from an onion router to a stream's destination. */
222 #define CONN_TYPE_EXIT 5
223 /** Type for sockets listening for SOCKS connections. */
224 #define CONN_TYPE_AP_LISTENER 6
225 /** A SOCKS proxy connection from the user application to the onion
226 * proxy. */
227 #define CONN_TYPE_AP 7
228 /** Type for sockets listening for HTTP connections to the directory server. */
229 #define CONN_TYPE_DIR_LISTENER 8
230 /** Type for HTTP connections to the directory server. */
231 #define CONN_TYPE_DIR 9
232 /** Connection from the main process to a DNS worker process. */
233 #define CONN_TYPE_DNSWORKER 10
234 /** Connection from the main process to a CPU worker process. */
235 #define CONN_TYPE_CPUWORKER 11
236 /** Type for listening for connections from user interface process. */
237 #define CONN_TYPE_CONTROL_LISTENER 12
238 /** Type for connections from user interface process. */
239 #define CONN_TYPE_CONTROL 13
240 /** Type for sockets listening for transparent connections redirected by pf or
241 * netfilter. */
242 #define CONN_TYPE_AP_TRANS_LISTENER 14
243 /** Type for sockets listening for transparent connections redirected by
244 * natd. */
245 #define CONN_TYPE_AP_NATD_LISTENER 15
246 #define _CONN_TYPE_MAX 15
248 #define CONN_IS_EDGE(x) \
249 ((x)->type == CONN_TYPE_EXIT || (x)->type == CONN_TYPE_AP)
251 /** State for any listener connection. */
252 #define LISTENER_STATE_READY 0
254 #define _DNSWORKER_STATE_MIN 1
255 /** State for a connection to a dnsworker process that's idle. */
256 #define DNSWORKER_STATE_IDLE 1
257 /** State for a connection to a dnsworker process that's resolving a
258 * hostname. */
259 #define DNSWORKER_STATE_BUSY 2
260 #define _DNSWORKER_STATE_MAX 2
262 #define _CPUWORKER_STATE_MIN 1
263 /** State for a connection to a cpuworker process that's idle. */
264 #define CPUWORKER_STATE_IDLE 1
265 /** State for a connection to a cpuworker process that's processing a
266 * handshake. */
267 #define CPUWORKER_STATE_BUSY_ONION 2
268 #define _CPUWORKER_STATE_MAX 2
270 #define CPUWORKER_TASK_ONION CPUWORKER_STATE_BUSY_ONION
272 #define _OR_CONN_STATE_MIN 1
273 /** State for a connection to an OR: waiting for connect() to finish. */
274 #define OR_CONN_STATE_CONNECTING 1
275 /** State for a connection to an OR: waiting for proxy command to flush. */
276 #define OR_CONN_STATE_PROXY_FLUSHING 2
277 /** State for a connection to an OR: waiting for proxy response. */
278 #define OR_CONN_STATE_PROXY_READING 3
279 /** State for a connection to an OR: SSL is handshaking, not done yet. */
280 #define OR_CONN_STATE_HANDSHAKING 4
281 /** State for a connection to an OR: Ready to send/receive cells. */
282 #define OR_CONN_STATE_OPEN 5
283 #define _OR_CONN_STATE_MAX 5
285 #define _EXIT_CONN_STATE_MIN 1
286 /** State for an exit connection: waiting for response from dns farm. */
287 #define EXIT_CONN_STATE_RESOLVING 1
288 /** State for an exit connection: waiting for connect() to finish. */
289 #define EXIT_CONN_STATE_CONNECTING 2
290 /** State for an exit connection: open and ready to transmit data. */
291 #define EXIT_CONN_STATE_OPEN 3
292 /** State for an exit connection: waiting to be removed. */
293 #define EXIT_CONN_STATE_RESOLVEFAILED 4
294 #define _EXIT_CONN_STATE_MAX 4
296 /* the AP state values must be disjoint from the EXIT state values */
297 #define _AP_CONN_STATE_MIN 5
298 /** State for a SOCKS connection: waiting for SOCKS request. */
299 #define AP_CONN_STATE_SOCKS_WAIT 5
300 /** State for a SOCKS connection: got a y.onion URL; waiting to receive
301 * rendezvous descriptor. */
302 #define AP_CONN_STATE_RENDDESC_WAIT 6
303 /** The controller will attach this connection to a circuit; it isn't our
304 * job to do so. */
305 #define AP_CONN_STATE_CONTROLLER_WAIT 7
306 /** State for a SOCKS connection: waiting for a completed circuit. */
307 #define AP_CONN_STATE_CIRCUIT_WAIT 8
308 /** State for a SOCKS connection: sent BEGIN, waiting for CONNECTED. */
309 #define AP_CONN_STATE_CONNECT_WAIT 9
310 /** State for a SOCKS connection: sent RESOLVE, waiting for RESOLVED. */
311 #define AP_CONN_STATE_RESOLVE_WAIT 10
312 /** State for a SOCKS connection: ready to send and receive. */
313 #define AP_CONN_STATE_OPEN 11
314 /** State for a transparent natd connection: waiting for original
315 * destination. */
316 #define AP_CONN_STATE_NATD_WAIT 12
317 #define _AP_CONN_STATE_MAX 12
319 /** True iff the AP_CONN_STATE_* value <b>s</b> means that the corresponding
320 * edge connection is not attached to any circuit. */
321 #define AP_CONN_STATE_IS_UNATTACHED(s) \
322 ((s) <= AP_CONN_STATE_CIRCUIT_WAIT || (s) == AP_CONN_STATE_NATD_WAIT)
324 #define _DIR_CONN_STATE_MIN 1
325 /** State for connection to directory server: waiting for connect(). */
326 #define DIR_CONN_STATE_CONNECTING 1
327 /** State for connection to directory server: sending HTTP request. */
328 #define DIR_CONN_STATE_CLIENT_SENDING 2
329 /** State for connection to directory server: reading HTTP response. */
330 #define DIR_CONN_STATE_CLIENT_READING 3
331 /** State for connection to directory server: happy and finished. */
332 #define DIR_CONN_STATE_CLIENT_FINISHED 4
333 /** State for connection at directory server: waiting for HTTP request. */
334 #define DIR_CONN_STATE_SERVER_COMMAND_WAIT 5
335 /** State for connection at directory server: sending HTTP response. */
336 #define DIR_CONN_STATE_SERVER_WRITING 6
337 #define _DIR_CONN_STATE_MAX 6
339 /** True iff the purpose of <b>conn</b> means that it's a server-side
340 * directory connection. */
341 #define DIR_CONN_IS_SERVER(conn) ((conn)->purpose == DIR_PURPOSE_SERVER)
343 #define _CONTROL_CONN_STATE_MIN 1
344 /** State for a control connection: Authenticated and accepting v0 commands. */
345 #define CONTROL_CONN_STATE_OPEN_V0 1
346 /** State for a control connection: Authenticated and accepting v1 commands. */
347 #define CONTROL_CONN_STATE_OPEN_V1 2
348 /** State for a control connection: Waiting for authentication; either
349 * speaking v0 commands or waiting for evidence that it's a v1
350 * connection. */
351 #define CONTROL_CONN_STATE_NEEDAUTH_V0 3
352 /** State for a control connection: Waiting for authentication; speaking
353 * protocol v1. */
354 #define CONTROL_CONN_STATE_NEEDAUTH_V1 4
355 #define _CONTROL_CONN_STATE_MAX 4
357 #define _DIR_PURPOSE_MIN 1
358 /** A connection to a directory server: download a directory. */
359 #define DIR_PURPOSE_FETCH_DIR 1
360 /** A connection to a directory server: download just the list
361 * of running routers. */
362 #define DIR_PURPOSE_FETCH_RUNNING_LIST 2
363 /** A connection to a directory server: download a rendezvous
364 * descriptor. */
365 #define DIR_PURPOSE_FETCH_RENDDESC 3
366 /** A connection to a directory server: set after a rendezvous
367 * descriptor is downloaded. */
368 #define DIR_PURPOSE_HAS_FETCHED_RENDDESC 4
369 /** A connection to a directory server: download one or more network-status
370 * objects */
371 #define DIR_PURPOSE_FETCH_NETWORKSTATUS 5
372 /** A connection to a directory server: download one or more server
373 * descriptors. */
374 #define DIR_PURPOSE_FETCH_SERVERDESC 6
375 /** A connection to a directory server: upload a server descriptor. */
376 #define DIR_PURPOSE_UPLOAD_DIR 7
377 /** A connection to a directory server: upload a rendezvous
378 * descriptor. */
379 #define DIR_PURPOSE_UPLOAD_RENDDESC 8
380 /** Purpose for connection at a directory server. */
381 #define DIR_PURPOSE_SERVER 9
382 #define _DIR_PURPOSE_MAX 9
384 #define _EXIT_PURPOSE_MIN 1
385 /** This exit stream wants to do an ordinary connect. */
386 #define EXIT_PURPOSE_CONNECT 1
387 /** This exit stream wants to do a resolve (either normal or reverse). */
388 #define EXIT_PURPOSE_RESOLVE 2
389 #define _EXIT_PURPOSE_MAX 2
391 /** Circuit state: I'm the origin, still haven't done all my handshakes. */
392 #define CIRCUIT_STATE_BUILDING 0
393 /** Circuit state: Waiting to process the onionskin. */
394 #define CIRCUIT_STATE_ONIONSKIN_PENDING 1
395 /** Circuit state: I'd like to deliver a create, but my n_conn is still
396 * connecting. */
397 #define CIRCUIT_STATE_OR_WAIT 2
398 /** Circuit state: onionskin(s) processed, ready to send/receive cells. */
399 #define CIRCUIT_STATE_OPEN 3
401 #define _CIRCUIT_PURPOSE_MIN 1
403 /* these circuits were initiated elsewhere */
404 #define _CIRCUIT_PURPOSE_OR_MIN 1
405 /** OR-side circuit purpose: normal circuit, at OR. */
406 #define CIRCUIT_PURPOSE_OR 1
407 /** OR-side circuit purpose: At OR, from Bob, waiting for intro from Alices. */
408 #define CIRCUIT_PURPOSE_INTRO_POINT 2
409 /** OR-side circuit purpose: At OR, from Alice, waiting for Bob. */
410 #define CIRCUIT_PURPOSE_REND_POINT_WAITING 3
411 /** OR-side circuit purpose: At OR, both circuits have this purpose. */
412 #define CIRCUIT_PURPOSE_REND_ESTABLISHED 4
413 #define _CIRCUIT_PURPOSE_OR_MAX 4
415 /* these circuits originate at this node */
417 /* here's how circ client-side purposes work:
418 * normal circuits are C_GENERAL.
419 * circuits that are c_introducing are either on their way to
420 * becoming open, or they are open and waiting for a
421 * suitable rendcirc before they send the intro.
422 * circuits that are c_introduce_ack_wait have sent the intro,
423 * but haven't gotten a response yet.
424 * circuits that are c_establish_rend are either on their way
425 * to becoming open, or they are open and have sent the
426 * establish_rendezvous cell but haven't received an ack.
427 * circuits that are c_rend_ready are open and have received a
428 * rend ack, but haven't heard from bob yet. if they have a
429 * buildstate->pending_final_cpath then they're expecting a
430 * cell from bob, else they're not.
431 * circuits that are c_rend_ready_intro_acked are open, and
432 * some intro circ has sent its intro and received an ack.
433 * circuits that are c_rend_joined are open, have heard from
434 * bob, and are talking to him.
436 /** Client-side circuit purpose: Normal circuit, with cpath. */
437 #define CIRCUIT_PURPOSE_C_GENERAL 5
438 /** Client-side circuit purpose: at Alice, connecting to intro point. */
439 #define CIRCUIT_PURPOSE_C_INTRODUCING 6
440 /** Client-side circuit purpose: at Alice, sent INTRODUCE1 to intro point,
441 * waiting for ACK/NAK. */
442 #define CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT 7
443 /** Client-side circuit purpose: at Alice, introduced and acked, closing. */
444 #define CIRCUIT_PURPOSE_C_INTRODUCE_ACKED 8
445 /** Client-side circuit purpose: at Alice, waiting for ack. */
446 #define CIRCUIT_PURPOSE_C_ESTABLISH_REND 9
447 /** Client-side circuit purpose: at Alice, waiting for Bob. */
448 #define CIRCUIT_PURPOSE_C_REND_READY 10
449 /** Client-side circuit purpose: at Alice, waiting for Bob, INTRODUCE
450 * has been acknowledged. */
451 #define CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED 11
452 /** Client-side circuit purpose: at Alice, rendezvous established. */
453 #define CIRCUIT_PURPOSE_C_REND_JOINED 12
455 /** Hidden-service-side circuit purpose: at Bob, waiting for introductions. */
456 #define CIRCUIT_PURPOSE_S_ESTABLISH_INTRO 13
457 /** Hidden-service-side circuit purpose: at Bob, successfully established
458 * intro. */
459 #define CIRCUIT_PURPOSE_S_INTRO 14
460 /** Hidden-service-side circuit purpose: at Bob, connecting to rend point. */
461 #define CIRCUIT_PURPOSE_S_CONNECT_REND 15
462 /** Hidden-service-side circuit purpose: at Bob, rendezvous established. */
463 #define CIRCUIT_PURPOSE_S_REND_JOINED 16
464 /** A testing circuit; not meant to be used for actual traffic. */
465 #define CIRCUIT_PURPOSE_TESTING 17
466 /** A controller made this circuit and Tor should not use it. */
467 #define CIRCUIT_PURPOSE_CONTROLLER 18
468 #define _CIRCUIT_PURPOSE_MAX 18
470 /** True iff the circuit purpose <b>p</b> is for a circuit that
471 * originated at this node. */
472 #define CIRCUIT_PURPOSE_IS_ORIGIN(p) ((p)>_CIRCUIT_PURPOSE_OR_MAX)
473 #define CIRCUIT_IS_ORIGIN(c) (CIRCUIT_PURPOSE_IS_ORIGIN((c)->purpose))
475 /** How many circuits do we want simultaneously in-progress to handle
476 * a given stream? */
477 #define MIN_CIRCUITS_HANDLING_STREAM 2
479 #define RELAY_COMMAND_BEGIN 1
480 #define RELAY_COMMAND_DATA 2
481 #define RELAY_COMMAND_END 3
482 #define RELAY_COMMAND_CONNECTED 4
483 #define RELAY_COMMAND_SENDME 5
484 #define RELAY_COMMAND_EXTEND 6
485 #define RELAY_COMMAND_EXTENDED 7
486 #define RELAY_COMMAND_TRUNCATE 8
487 #define RELAY_COMMAND_TRUNCATED 9
488 #define RELAY_COMMAND_DROP 10
489 #define RELAY_COMMAND_RESOLVE 11
490 #define RELAY_COMMAND_RESOLVED 12
491 #define RELAY_COMMAND_BEGIN_DIR 13
493 #define RELAY_COMMAND_ESTABLISH_INTRO 32
494 #define RELAY_COMMAND_ESTABLISH_RENDEZVOUS 33
495 #define RELAY_COMMAND_INTRODUCE1 34
496 #define RELAY_COMMAND_INTRODUCE2 35
497 #define RELAY_COMMAND_RENDEZVOUS1 36
498 #define RELAY_COMMAND_RENDEZVOUS2 37
499 #define RELAY_COMMAND_INTRO_ESTABLISHED 38
500 #define RELAY_COMMAND_RENDEZVOUS_ESTABLISHED 39
501 #define RELAY_COMMAND_INTRODUCE_ACK 40
503 /* Reasons why an OR connection is closed */
504 #define END_OR_CONN_REASON_DONE 1
505 #define END_OR_CONN_REASON_TCP_REFUSED 2
506 #define END_OR_CONN_REASON_OR_IDENTITY 3
507 #define END_OR_CONN_REASON_TLS_CONNRESET 4 /* tls connection reset by peer */
508 #define END_OR_CONN_REASON_TLS_TIMEOUT 5
509 #define END_OR_CONN_REASON_TLS_NO_ROUTE 6 /* no route to host/net */
510 #define END_OR_CONN_REASON_TLS_IO_ERROR 7 /* tls read/write error */
511 #define END_OR_CONN_REASON_TLS_MISC 8
513 /* Reasons why we (or a remote OR) might close a stream. See tor-spec.txt for
514 * documentation of these. */
515 #define END_STREAM_REASON_MISC 1
516 #define END_STREAM_REASON_RESOLVEFAILED 2
517 #define END_STREAM_REASON_CONNECTREFUSED 3
518 #define END_STREAM_REASON_EXITPOLICY 4
519 #define END_STREAM_REASON_DESTROY 5
520 #define END_STREAM_REASON_DONE 6
521 #define END_STREAM_REASON_TIMEOUT 7
522 /* 8 is unallocated for historical reasons. */
523 #define END_STREAM_REASON_HIBERNATING 9
524 #define END_STREAM_REASON_INTERNAL 10
525 #define END_STREAM_REASON_RESOURCELIMIT 11
526 #define END_STREAM_REASON_CONNRESET 12
527 #define END_STREAM_REASON_TORPROTOCOL 13
528 #define END_STREAM_REASON_NOTDIRECTORY 14
530 /* These high-numbered end reasons are not part of the official spec,
531 * and are not intended to be put in relay end cells. They are here
532 * to be more informative when sending back socks replies to the
533 * application. */
534 /* XXXX 256 is no longer used; feel free to reuse it. */
535 /** We were unable to attach the connection to any circuit at all. */
536 /* XXXX the ways we use this one don't make a lot of sense. */
537 #define END_STREAM_REASON_CANT_ATTACH 257
538 /** We can't connect to any directories at all, so we killed our streams
539 * before they can time out. */
540 #define END_STREAM_REASON_NET_UNREACHABLE 258
541 /** This is a SOCKS connection, and the client used (or misused) the SOCKS
542 * protocol in a way we couldn't handle. */
543 #define END_STREAM_REASON_SOCKSPROTOCOL 259
544 /** This is a transparent proxy connection, but we can't extract the original
545 * target address:port. */
546 #define END_STREAM_REASON_CANT_FETCH_ORIG_DEST 260
547 /** This is a connection on the NATD port, and the destination IP:Port was
548 * either ill-formed or out-of-range.*/
549 #define END_STREAM_REASON_INVALID_NATD_DEST 261
551 /** Bitwise-and this value with endreason to mask out all flags. */
552 #define END_STREAM_REASON_MASK 511
554 /** Bitwise-or this with the argument to control_event_stream_status
555 * to indicate that the reason came from an END cell. */
556 #define END_STREAM_REASON_FLAG_REMOTE 512
557 /** Bitwise-or this with the argument to control_event_stream_status
558 * to indicate that we already sent a CLOSED stream event. */
559 #define END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED 1024
560 /** Bitwise-or this with endreason to indicate that we already sent
561 * a socks reply, and no further reply needs to be sent from
562 * connection_mark_unattached_ap(). */
563 #define END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED 2048
565 /** Reason for remapping an AP connection's address: we have a cached
566 * answer. */
567 #define REMAP_STREAM_SOURCE_CACHE 1
568 /** Reason for remapping an AP connection's address: the exit node told us an
569 * answer. */
570 #define REMAP_STREAM_SOURCE_EXIT 2
572 /* 'type' values to use in RESOLVED cells. Specified in tor-spec.txt */
573 #define RESOLVED_TYPE_HOSTNAME 0
574 #define RESOLVED_TYPE_IPV4 4
575 #define RESOLVED_TYPE_IPV6 6
576 #define RESOLVED_TYPE_ERROR_TRANSIENT 0xF0
577 #define RESOLVED_TYPE_ERROR 0xF1
579 /* Negative reasons are internal: we never send them in a DESTROY or TRUNCATE
580 * call; they only go to the controller for tracking */
581 /** We couldn't build a path for this circuit. */
582 #define END_CIRC_REASON_NOPATH -2
583 /** Catch-all "other" reason for closing origin circuits. */
584 #define END_CIRC_AT_ORIGIN -1
586 /* Reasons why we (or a remote OR) might close a circuit. See tor-spec.txt for
587 * documentation of these. */
588 #define _END_CIRC_REASON_MIN 0
589 #define END_CIRC_REASON_NONE 0
590 #define END_CIRC_REASON_TORPROTOCOL 1
591 #define END_CIRC_REASON_INTERNAL 2
592 #define END_CIRC_REASON_REQUESTED 3
593 #define END_CIRC_REASON_HIBERNATING 4
594 #define END_CIRC_REASON_RESOURCELIMIT 5
595 #define END_CIRC_REASON_CONNECTFAILED 6
596 #define END_CIRC_REASON_OR_IDENTITY 7
597 #define END_CIRC_REASON_OR_CONN_CLOSED 8
598 #define END_CIRC_REASON_FINISHED 9
599 #define END_CIRC_REASON_TIMEOUT 10
600 #define END_CIRC_REASON_DESTROYED 11
601 #define END_CIRC_REASON_NOSUCHSERVICE 12
602 #define _END_CIRC_REASON_MAX 12
604 /* OR this with the argument to circuit_mark_for_close, or
605 * control_event_circuit_status to indicate that the reason came from a
606 * destroy or truncate cell. */
607 #define END_CIRC_REASON_FLAG_REMOTE 512
609 /** Length of 'y' portion of 'y.onion' URL. */
610 #define REND_SERVICE_ID_LEN 16
612 #define CELL_DIRECTION_IN 1
613 #define CELL_DIRECTION_OUT 2
615 #ifdef TOR_PERF
616 #define CIRCWINDOW_START 10000
617 #define CIRCWINDOW_INCREMENT 1000
618 #define STREAMWINDOW_START 5000
619 #define STREAMWINDOW_INCREMENT 500
620 #else
621 /** Initial value for both sides of a circuit transmission window when the
622 * circuit is initialized. Measured in cells. */
623 #define CIRCWINDOW_START 1000
624 /** Amount to increment a circuit window when we get a circuit SENDME. */
625 #define CIRCWINDOW_INCREMENT 100
626 /** Initial value on both sides of a stream transmission window when the
627 * stream is initialized. Measured in cells. */
628 #define STREAMWINDOW_START 500
629 /** Amount to increment a stream window when we get a stream SENDME. */
630 #define STREAMWINDOW_INCREMENT 50
631 #endif
633 /* cell commands */
634 #define CELL_PADDING 0
635 #define CELL_CREATE 1
636 #define CELL_CREATED 2
637 #define CELL_RELAY 3
638 #define CELL_DESTROY 4
639 #define CELL_CREATE_FAST 5
640 #define CELL_CREATED_FAST 6
642 /** How long to test reachability before complaining to the user. */
643 #define TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT (20*60)
645 /** Legal characters in a nickname. */
646 #define LEGAL_NICKNAME_CHARACTERS \
647 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
649 /** Name to use in client TLS certificates if no nickname is given. */
650 #define DEFAULT_CLIENT_NICKNAME "client"
652 /** Number of bytes in a SOCKS4 header. */
653 #define SOCKS4_NETWORK_LEN 8
655 /** Specified SOCKS5 status codes. */
656 typedef enum {
657 SOCKS5_SUCCEEDED = 0x00,
658 SOCKS5_GENERAL_ERROR = 0x01,
659 SOCKS5_NOT_ALLOWED = 0x02,
660 SOCKS5_NET_UNREACHABLE = 0x03,
661 SOCKS5_HOST_UNREACHABLE = 0x04,
662 SOCKS5_CONNECTION_REFUSED = 0x05,
663 SOCKS5_TTL_EXPIRED = 0x06,
664 SOCKS5_COMMAND_NOT_SUPPORTED = 0x07,
665 SOCKS5_ADDRESS_TYPE_NOT_SUPPORTED = 0x08,
666 } socks5_reply_status_t;
669 * Relay payload:
670 * Relay command [1 byte]
671 * Recognized [2 bytes]
672 * Stream ID [2 bytes]
673 * Partial SHA-1 [4 bytes]
674 * Length [2 bytes]
675 * Relay payload [498 bytes]
678 /** Number of bytes in a cell, minus cell header. */
679 #define CELL_PAYLOAD_SIZE 509
680 /** Number of bytes in a cell transmitted over the network. */
681 #define CELL_NETWORK_SIZE 512
683 /** Number of bytes in a relay cell's header (not including general cell
684 * header). */
685 #define RELAY_HEADER_SIZE (1+2+2+4+2)
686 /** Largest number of bytes that can fit in a relay cell payload. */
687 #define RELAY_PAYLOAD_SIZE (CELL_PAYLOAD_SIZE-RELAY_HEADER_SIZE)
689 /** Parsed onion routing cell. All communication between nodes
690 * is via cells. */
691 typedef struct {
692 uint16_t circ_id; /**< Circuit which received the cell. */
693 uint8_t command; /**< Type of the cell: one of PADDING, CREATE, RELAY,
694 * or DESTROY. */
695 char payload[CELL_PAYLOAD_SIZE]; /**< Cell body. */
696 } cell_t;
698 /** Beginning of a RELAY cell payload. */
699 typedef struct {
700 uint8_t command; /**< The end-to-end relay command. */
701 uint16_t recognized; /**< Used to tell whether cell is for us. */
702 uint16_t stream_id; /**< Which stream is this cell associated with? */
703 char integrity[4]; /**< Used to tell whether cell is corrupted. */
704 uint16_t length; /**< How long is the payload body? */
705 } relay_header_t;
707 typedef struct buf_t buf_t;
708 typedef struct socks_request_t socks_request_t;
710 /* Values for connection_t.magic: used to make sure that downcasts (casts from
711 * connection_t to foo_connection_t) are safe. */
712 #define BASE_CONNECTION_MAGIC 0x7C3C304Eu
713 #define OR_CONNECTION_MAGIC 0x7D31FF03u
714 #define EDGE_CONNECTION_MAGIC 0xF0374013u
715 #define DIR_CONNECTION_MAGIC 0x9988ffeeu
716 #define CONTROL_CONNECTION_MAGIC 0x8abc765du
718 /** Description of a connection to another host or process, and associated
719 * data.
721 * A connection is named based on what it's connected to -- an "OR
722 * connection" has a Tor node on the other end, an "exit
723 * connection" has a website or other server on the other end, and an
724 * "AP connection" has an application proxy (and thus a user) on the
725 * other end.
727 * Every connection has a type and a state. Connections never change
728 * their type, but can go through many state changes in their lifetime.
730 * Every connection has two associated input and output buffers.
731 * Listeners don't use them. For non-listener connections, incoming
732 * data is appended to conn->inbuf, and outgoing data is taken from
733 * conn->outbuf. Connections differ primarily in the functions called
734 * to fill and drain these buffers.
736 typedef struct connection_t {
737 uint32_t magic; /**< For memory debugging: must equal one of
738 * *_CONNECTION_MAGIC. */
740 uint8_t type; /**< What kind of connection is this? */
741 uint8_t state; /**< Current state of this connection. */
742 uint8_t purpose; /**< Only used for DIR and EXIT types currently. */
744 /* The next fields are all one-bit booleans. Some are only applicable
745 * to connection subtypes, but we hold them here anyway, to save space.
746 * (Currently, they all fit into a single byte.) */
747 unsigned wants_to_read:1; /**< Boolean: should we start reading again once
748 * the bandwidth throttler allows it? */
749 unsigned wants_to_write:1; /**< Boolean: should we start writing again once
750 * the bandwidth throttler allows reads? */
751 unsigned hold_open_until_flushed:1; /**< Despite this connection's being
752 * marked for close, do we flush it
753 * before closing it? */
754 unsigned int inbuf_reached_eof:1; /**< Boolean: did read() return 0 on this
755 * conn? */
756 unsigned edge_has_sent_end:1; /**< For debugging; only used on edge
757 * connections. Set once we've set the stream end,
758 * and check in connection_about_to_close_connection().
760 /** Used for OR conns that shouldn't get any new circs attached to them. */
761 unsigned int or_is_obsolete:1;
762 /** For AP connections only. If 1, and we fail to reach the chosen exit,
763 * stop requiring it. */
764 unsigned int chosen_exit_optional:1;
766 int s; /**< Our socket; -1 if this connection is closed. */
767 int conn_array_index; /**< Index into the global connection array. */
768 struct event *read_event; /**< Libevent event structure. */
769 struct event *write_event; /**< Libevent event structure. */
770 buf_t *inbuf; /**< Buffer holding data read over this connection. */
771 buf_t *outbuf; /**< Buffer holding data to write over this connection. */
772 size_t outbuf_flushlen; /**< How much data should we try to flush from the
773 * outbuf? */
774 time_t timestamp_lastread; /**< When was the last time libevent said we could
775 * read? */
776 time_t timestamp_lastwritten; /**< When was the last time libevent said we
777 * could write? */
778 time_t timestamp_created; /**< When was this connection_t created? */
780 uint32_t addr; /**< IP of the other side of the connection; used to identify
781 * routers, along with port. */
782 uint16_t port; /**< If non-zero, port on the other end
783 * of the connection. */
784 uint16_t marked_for_close; /**< Should we close this conn on the next
785 * iteration of the main loop? (If true, holds
786 * the line number where this connection was
787 * marked.) */
788 const char *marked_for_close_file; /**< For debugging: in which file were
789 * we marked for close? */
790 char *address; /**< FQDN (or IP) of the guy on the other end.
791 * strdup into this, because free_connection frees it. */
793 } connection_t;
795 /** Subtype of connection_t for an "OR connection" -- that is, one that speaks
796 * cells over TLS. */
797 typedef struct or_connection_t {
798 connection_t _base;
800 /** Hash of the public RSA key for the other side's identity key, or zeroes
801 * if the other side hasn't shown us a valid identity key. */
802 char identity_digest[DIGEST_LEN];
803 char *nickname; /**< Nickname of OR on other side (if any). */
805 tor_tls_t *tls; /**< TLS connection state */
806 int tls_error; /**< Last tor_tls error code */
808 time_t timestamp_lastempty; /**< When was the outbuf last completely empty?*/
810 /* bandwidth* and read_bucket only used by ORs in OPEN state: */
811 int bandwidthrate; /**< Bytes/s added to the bucket. (OPEN ORs only.) */
812 int bandwidthburst; /**< Max bucket size for this conn. (OPEN ORs only.) */
813 int read_bucket; /**< When this hits 0, stop receiving. Every second we
814 * add 'bandwidthrate' to this, capping it at
815 * bandwidthburst. (OPEN ORs only) */
816 int n_circuits; /**< How many circuits use this connection as p_conn or
817 * n_conn ? */
818 struct or_connection_t *next_with_same_id; /**< Next connection with same
819 * identity digest as this one. */
820 /** Linked list of bridged dirserver connections that can't write until
821 * this connection's outbuf is less full. */
822 struct dir_connection_t *blocked_dir_connections;
823 circ_id_type_t circ_id_type:2; /**< When we send CREATE cells along this
824 * connection, which half of the space should
825 * we use? */
826 uint16_t next_circ_id; /**< Which circ_id do we try to use next on
827 * this connection? This is always in the
828 * range 0..1<<15-1. */
829 } or_connection_t;
831 /** Subtype of connection_t for an "edge connection" -- that is, a socks (ap)
832 * connection, or an exit. */
833 typedef struct edge_connection_t {
834 connection_t _base;
836 struct edge_connection_t *next_stream; /**< Points to the next stream at this
837 * edge, if any */
838 struct crypt_path_t *cpath_layer; /**< A pointer to which node in the circ
839 * this conn exits at. */
840 int package_window; /**< How many more relay cells can I send into the
841 * circuit? */
842 int deliver_window; /**< How many more relay cells can end at me? */
844 /** Nickname of planned exit node -- used with .exit support. */
845 char *chosen_exit_name;
847 socks_request_t *socks_request; /**< SOCKS structure describing request (AP
848 * only.) */
849 struct circuit_t *on_circuit; /**< The circuit (if any) that this edge
850 * connection is using. */
852 uint32_t address_ttl; /**< TTL for address-to-addr mapping on exit
853 * connection. Exit connections only. */
855 uint16_t stream_id; /**< The stream ID used for this edge connection on its
856 * circuit */
858 /** The reason why this connection is closing; passed to the controller. */
859 uint16_t end_reason;
861 /** Quasi-global identifier for this connection; used for control.c */
862 /* XXXX NM This can get re-used after 2**32 streams */
863 uint32_t global_identifier;
865 /** Bytes read since last call to control_event_stream_bandwidth_used() */
866 uint32_t n_read;
868 /** Bytes written since last call to control_event_stream_bandwidth_used() */
869 uint32_t n_written;
871 /** Exit only: a dirserv connection that is tunneled over this connection
872 * using a socketpair. */
873 struct dir_connection_t *bridge_for_conn;
875 char rend_query[REND_SERVICE_ID_LEN+1]; /**< What rendezvous service are we
876 * querying for? (AP only) */
878 /** Number of times we've reassigned this application connection to
879 * a new circuit. We keep track because the timeout is longer if we've
880 * already retried several times. */
881 uint8_t num_socks_retries;
883 } edge_connection_t;
885 /** Subtype of connection_t for an "directory connection" -- that is, an HTTP
886 * connection to retrieve or serve directory material. */
887 typedef struct dir_connection_t {
888 connection_t _base;
890 char *requested_resource; /**< Which 'resource' did we ask the directory
891 * for? */
892 unsigned int dirconn_direct:1; /**< Is this dirconn direct, or via Tor? */
893 /** True iff this is a dirserv conn, and it's tunneled over an or_conn,
894 * and we've stopped writing because the or_conn had too much pending
895 * data to write */
896 unsigned int is_blocked_on_or_conn : 1;
898 /* Used only for server sides of some dir connections, to implement
899 * "spooling" of directory material to the outbuf. Otherwise, we'd have
900 * to append everything to the outbuf in one enormous chunk. */
901 /** What exactly are we spooling right now? */
902 enum {
903 DIR_SPOOL_NONE=0, DIR_SPOOL_SERVER_BY_DIGEST, DIR_SPOOL_SERVER_BY_FP,
904 DIR_SPOOL_CACHED_DIR, DIR_SPOOL_NETWORKSTATUS
905 } dir_spool_src : 3;
906 /** List of fingerprints for networkstatuses or desriptors to be spooled. */
907 smartlist_t *fingerprint_stack;
908 /** A cached_dir_t object that we're currently spooling out */
909 struct cached_dir_t *cached_dir;
910 /** The current offset into cached_dir. */
911 off_t cached_dir_offset;
912 /** The zlib object doing on-the-fly compression for spooled data. */
913 tor_zlib_state_t *zlib_state;
915 char rend_query[REND_SERVICE_ID_LEN+1]; /**< What rendezvous service are we
916 * querying for? */
918 char identity_digest[DIGEST_LEN]; /**< Hash of the public RSA key for
919 * the directory server's signing key. */
921 /** If this is a dirserv conn created with a BEGIN_DIR (a "bridged" dirserv
922 * connection), a pointer to the edge_conn at the other end of its
923 * socketpair. */
924 edge_connection_t *bridge_conn;
925 /** Next connection in linked list of dirserv connections blocked until
926 * the or_conns over which they're bridged have enough space in their
927 * outbufs. */
928 struct dir_connection_t *next_blocked_on_same_or_conn;
930 } dir_connection_t;
932 /** Subtype of connection_t for an connection to a controller. */
933 typedef struct control_connection_t {
934 connection_t _base;
936 uint32_t event_mask; /**< Bitfield: which events does this controller
937 * care about? */
938 unsigned int use_long_names:1; /**< True if we should use long nicknames
939 * on this (v1) connection. Only settable
940 * via v1 controllers. */
941 /** For control connections only. If set, we send extended info with control
942 * events as appropriate. */
943 unsigned int use_extended_events:1;
945 uint32_t incoming_cmd_len;
946 uint32_t incoming_cmd_cur_len;
947 char *incoming_cmd;
948 /* Used only by control v0 connections */
949 uint16_t incoming_cmd_type;
950 } control_connection_t;
952 /** Cast a connection_t subtype pointer to a connection_t **/
953 #define TO_CONN(c) (&(((c)->_base)))
954 /** Helper macro: Given a pointer to to._base, of type from*, return &to. */
955 #define DOWNCAST(to, ptr) ((to*)SUBTYPE_P(ptr, to, _base))
957 /** Convert a connection_t* to an or_connection_t*; assert if the cast is
958 * invalid. */
959 static or_connection_t *TO_OR_CONN(connection_t *);
960 /** Convert a connection_t* to a dir_connection_t*; assert if the cast is
961 * invalid. */
962 static dir_connection_t *TO_DIR_CONN(connection_t *);
963 /** Convert a connection_t* to an edge_connection_t*; assert if the cast is
964 * invalid. */
965 static edge_connection_t *TO_EDGE_CONN(connection_t *);
966 /** Convert a connection_t* to an control_connection_t*; assert if the cast is
967 * invalid. */
968 static control_connection_t *TO_CONTROL_CONN(connection_t *);
970 static INLINE or_connection_t *TO_OR_CONN(connection_t *c)
972 tor_assert(c->magic == OR_CONNECTION_MAGIC);
973 return DOWNCAST(or_connection_t, c);
975 static INLINE dir_connection_t *TO_DIR_CONN(connection_t *c)
977 tor_assert(c->magic == DIR_CONNECTION_MAGIC);
978 return DOWNCAST(dir_connection_t, c);
980 static INLINE edge_connection_t *TO_EDGE_CONN(connection_t *c)
982 tor_assert(c->magic == EDGE_CONNECTION_MAGIC);
983 return DOWNCAST(edge_connection_t, c);
985 static INLINE control_connection_t *TO_CONTROL_CONN(connection_t *c)
987 tor_assert(c->magic == CONTROL_CONNECTION_MAGIC);
988 return DOWNCAST(control_connection_t, c);
991 typedef enum {
992 ADDR_POLICY_ACCEPT=1,
993 ADDR_POLICY_REJECT=2,
994 } addr_policy_action_t;
996 /** A linked list of policy rules */
997 typedef struct addr_policy_t {
998 addr_policy_action_t policy_type; /**< What to do when the policy matches.*/
999 char *string; /**< String representation of this rule. */
1000 uint32_t addr; /**< Base address to accept or reject. */
1001 uint32_t msk; /**< Accept/reject all addresses <b>a</b> such that
1002 * a &amp; msk == <b>addr</b> &amp; msk . */
1003 uint16_t prt_min; /**< Lowest port number to accept/reject. */
1004 uint16_t prt_max; /**< Highest port number to accept/reject. */
1006 struct addr_policy_t *next; /**< Next rule in list. */
1007 } addr_policy_t;
1009 /** A cached_dir_t represents a cacheable directory object, along with its
1010 * compressed form. */
1011 typedef struct cached_dir_t {
1012 char *dir; /**< Contents of this object */
1013 char *dir_z; /**< Compressed contents of this object. */
1014 size_t dir_len; /**< Length of <b>dir</b> */
1015 size_t dir_z_len; /**< Length of <b>dir_z</b> */
1016 time_t published; /**< When was this object published */
1017 int refcnt; /**< Reference count for this cached_dir_t. */
1018 } cached_dir_t;
1020 /** Enum used to remember where a signed_descriptor_t is stored and how to
1021 * manage the memory for signed_descriptor_body. */
1022 typedef enum {
1023 /** The descriptor isn't stored on disk at all: the copy in memory is
1024 * canonical; the saved_offset field is meaningless. */
1025 SAVED_NOWHERE=0,
1026 /** The descriptor is stored in the cached_routers file: the
1027 * signed_descriptor_body is meaningless; the signed_descriptor_len and
1028 * saved_offset are used to index into the mmaped cache file. */
1029 SAVED_IN_CACHE,
1030 /** The descriptor is stored in the cached_routers.new file: the
1031 * signed_descriptor_body and saved_offset fields are both set. */
1032 /* FFFF (We could also mmap the file and grow the mmap as needed, or
1033 * lazy-load the descriptor text by using seek and read. We don't, for
1034 * now.)
1036 SAVED_IN_JOURNAL
1037 } saved_location_t;
1039 /** Information need to cache an onion router's descriptor. */
1040 typedef struct signed_descriptor_t {
1041 /** Pointer to the raw server descriptor. Not necessarily NUL-terminated.
1042 * If saved_location is SAVED_IN_CACHE, this pointer is null. */
1043 char *signed_descriptor_body;
1044 /** Length of the server descriptor. */
1045 size_t signed_descriptor_len;
1046 /** Digest of the server descriptor, computed as specified in dir-spec.txt */
1047 char signed_descriptor_digest[DIGEST_LEN];
1048 /** Identity digest of the router. */
1049 char identity_digest[DIGEST_LEN];
1050 /** Declared publication time of the descriptor */
1051 time_t published_on;
1052 /** Where is the descriptor saved? */
1053 saved_location_t saved_location;
1054 /** If saved_location is SAVED_IN_CACHE or SAVED_IN_JOURNAL, the offset of
1055 * this descriptor in the corresponding file. */
1056 off_t saved_offset;
1057 } signed_descriptor_t;
1059 /** Information about another onion router in the network. */
1060 typedef struct {
1061 signed_descriptor_t cache_info;
1062 char *address; /**< Location of OR: either a hostname or an IP address. */
1063 char *nickname; /**< Human-readable OR name. */
1065 uint32_t addr; /**< IPv4 address of OR, in host order. */
1066 uint16_t or_port; /**< Port for TLS connections. */
1067 uint16_t dir_port; /**< Port for HTTP directory connections. */
1069 crypto_pk_env_t *onion_pkey; /**< Public RSA key for onions. */
1070 crypto_pk_env_t *identity_pkey; /**< Public RSA key for signing. */
1072 char *platform; /**< What software/operating system is this OR using? */
1074 /* link info */
1075 uint32_t bandwidthrate; /**< How many bytes does this OR add to its token
1076 * bucket per second? */
1077 uint32_t bandwidthburst; /**< How large is this OR's token bucket? */
1078 /** How many bytes/s is this router known to handle? */
1079 uint32_t bandwidthcapacity;
1080 addr_policy_t *exit_policy; /**< What streams will this OR permit
1081 * to exit? */
1082 long uptime; /**< How many seconds the router claims to have been up */
1083 smartlist_t *declared_family; /**< Nicknames of router which this router
1084 * claims are its family. */
1085 char *contact_info; /**< Declared contact info for this router. */
1086 unsigned int is_hibernating:1; /**< Whether the router claims to be
1087 * hibernating */
1088 unsigned int has_old_dnsworkers:1; /**< Whether the router is using
1089 * dnsworker code. */
1091 /* local info */
1092 unsigned int is_running:1; /**< As far as we know, is this OR currently
1093 * running? */
1094 unsigned int is_valid:1; /**< Has a trusted dirserver validated this OR?
1095 * (For Authdir: Have we validated this OR?)
1097 unsigned int is_named:1; /**< Do we believe the nickname that this OR gives
1098 * us? */
1099 unsigned int is_fast:1; /** Do we think this is a fast OR? */
1100 unsigned int is_stable:1; /** Do we think this is a stable OR? */
1101 unsigned int is_possible_guard:1; /**< Do we think this is an OK guard? */
1102 unsigned int is_exit:1; /**< Do we think this is an OK exit? */
1103 unsigned int is_bad_exit:1; /**< Do we think this exit is censored, borked,
1104 * or otherwise nasty? */
1106 /** Tor can use this desc for circuit-building. */
1107 #define ROUTER_PURPOSE_GENERAL 0
1108 /** Tor should avoid using this desc for circuit-building. */
1109 #define ROUTER_PURPOSE_CONTROLLER 1
1110 uint8_t purpose; /** Should Tor use this desc for circuit-building? */
1112 /* The below items are used only by authdirservers for
1113 * reachability testing. */
1114 /** When was the last time we could reach this OR? */
1115 time_t last_reachable;
1116 /** When did we start testing reachability for this OR? */
1117 time_t testing_since;
1118 /** How many times has a descriptor been posted and we believed
1119 * this router to be unreachable? We only actually warn on the third. */
1120 int num_unreachable_notifications;
1122 /** What position is this descriptor within routerlist->routers? -1 for
1123 * none. */
1124 int routerlist_index;
1125 } routerinfo_t;
1127 /** Contents of a single router entry in a network status object.
1129 typedef struct routerstatus_t {
1130 time_t published_on; /**< When was this router published? */
1131 char nickname[MAX_NICKNAME_LEN+1]; /**< The nickname this router says it
1132 * has. */
1133 char identity_digest[DIGEST_LEN]; /**< Digest of the router's identity
1134 * key. */
1135 char descriptor_digest[DIGEST_LEN]; /**< Digest of the router's most recent
1136 * descriptor. */
1137 uint32_t addr; /**< IPv4 address for this router. */
1138 uint16_t or_port; /**< OR port for this router. */
1139 uint16_t dir_port; /**< Directory port for this router. */
1140 unsigned int is_exit:1; /**< True iff this router is a good exit. */
1141 unsigned int is_stable:1; /**< True iff this router stays up a long time. */
1142 unsigned int is_fast:1; /**< True iff this router has good bandwidth. */
1143 unsigned int is_running:1; /**< True iff this router is up. */
1144 unsigned int is_named:1; /**< True iff "nickname" belongs to this router. */
1145 unsigned int is_valid:1; /**< True iff this router is validated. */
1146 unsigned int is_v2_dir:1; /**< True iff this router can serve directory
1147 * information with v2 of the directory
1148 * protocol. (All directory caches cache v1
1149 * directories.) */
1150 unsigned int is_possible_guard:1; /**< True iff this router would be a good
1151 * choice as an entry guard. */
1152 unsigned int is_bad_exit:1; /**< True iff this node is a bad choice for
1153 * an exit node. */
1154 unsigned int is_bad_directory:1; /**< Do we think this directory is junky,
1155 * underpowered, or otherwise useless? */
1157 /** True iff we know version info for this router. (i.e., a "v" entry was
1158 * included.) We'll replace all these with a big tor_version_t or a char[]
1159 * if the number of traits we care about ever becomes incredibly big. */
1160 unsigned int version_known:1;
1161 /** True iff this router is a version that supports BEGIN_DIR cells. */
1162 unsigned int version_supports_begindir:1;
1164 /** True if we, as a directory mirror, want to download the corresponding
1165 * routerinfo from the authority who gave us this routerstatus. (That is,
1166 * if we don't have the routerinfo, and if we haven't already tried to get it
1167 * from this authority.)
1169 unsigned int need_to_mirror:1;
1170 } routerstatus_t;
1172 /** Our "local" or combined view of the info from all networkstatus objects
1173 * about a single router. */
1174 typedef struct local_routerstatus_t {
1175 /** What do we believe to be the case about this router? In this field,
1176 * descriptor_digest represents the descriptor we would most like to use for
1177 * this router. */
1178 routerstatus_t status;
1179 time_t next_attempt_at; /**< When should we try downloading this descriptor
1180 * again? */
1181 time_t last_dir_503_at; /**< When did this router last tell us that it
1182 * was too busy to serve directory info? */
1183 uint8_t n_download_failures; /**< Number of failures trying to download the
1184 * most recent descriptor. */
1185 unsigned int name_lookup_warned:1; /**< Have we warned the user for referring
1186 * to this (unnamed) router by nickname?
1188 } local_routerstatus_t;
1190 /** How many times will we try to download a router's descriptor before giving
1191 * up? */
1192 #define MAX_ROUTERDESC_DOWNLOAD_FAILURES 8
1194 /** Contents of a (v2 or later) network status object. */
1195 typedef struct networkstatus_t {
1196 /** When did we receive the network-status document? */
1197 time_t received_on;
1199 /** What was the digest of the document? */
1200 char networkstatus_digest[DIGEST_LEN];
1202 unsigned int is_recent; /**< Is this recent enough to influence running
1203 * status? */
1205 /* These fields come from the actual network-status document.*/
1206 time_t published_on; /**< Declared publication date. */
1208 char *source_address; /**< Canonical directory server hostname. */
1209 uint32_t source_addr; /**< Canonical directory server IP. */
1210 uint16_t source_dirport; /**< Canonical directory server dirport. */
1212 char identity_digest[DIGEST_LEN]; /**< Digest of signing key. */
1213 char *contact; /**< How to contact directory admin? (may be NULL). */
1214 crypto_pk_env_t *signing_key; /**< Key used to sign this directory. */
1215 char *client_versions; /**< comma-separated list of recommended client
1216 * versions. */
1217 char *server_versions; /**< comma-separated list of recommended server
1218 * versions. */
1220 unsigned int binds_names:1; /**< True iff this directory server binds
1221 * names. */
1222 unsigned int recommends_versions:1; /**< True iff this directory server
1223 * recommends client and server software
1224 * versions. */
1225 unsigned int lists_bad_exits:1; /**< True iff this directory server marks
1226 * malfunctioning exits as bad. */
1227 /** True iff this directory server marks malfunctioning directories as
1228 * bad. */
1229 unsigned int lists_bad_directories:1;
1230 smartlist_t *entries; /**< List of routerstatus_t*. This list is kept
1231 * sorted by identity_digest. */
1232 } networkstatus_t;
1234 /** Contents of a directory of onion routers. */
1235 typedef struct {
1236 /** Map from server identity digest to a member of routers. */
1237 digestmap_t *identity_map;
1238 /** Map from server descriptor digest to a signed_descriptor_t from
1239 * routers or old_routers. */
1240 digestmap_t *desc_digest_map;
1241 /** List of routerinfo_t for all currently live routers we know. */
1242 smartlist_t *routers;
1243 /** List of signed_descriptor_t for older router descriptors we're
1244 * caching. */
1245 smartlist_t *old_routers;
1246 /** Mmaped file holding server descriptors. If present, any router whose
1247 * cache_info.saved_location == SAVED_IN_CACHE is stored in this file
1248 * starting at cache_info.saved_offset */
1249 tor_mmap_t *mmap_descriptors;
1250 } routerlist_t;
1252 /** Information on router used when extending a circuit. We don't need a
1253 * full routerinfo_t to extend: we only need addr:port:keyid to build an OR
1254 * connection, and onion_key to create the onionskin. Note that for onehop
1255 * general-purpose tunnels, the onion_key is NULL. */
1256 typedef struct extend_info_t {
1257 char nickname[MAX_HEX_NICKNAME_LEN+1]; /**< This router's nickname for
1258 * display. */
1259 char identity_digest[DIGEST_LEN]; /**< Hash of this router's identity key. */
1260 uint32_t addr; /**< IP address in host order. */
1261 uint16_t port; /**< OR port. */
1262 crypto_pk_env_t *onion_key; /**< Current onionskin key. */
1263 } extend_info_t;
1265 #define CRYPT_PATH_MAGIC 0x70127012u
1267 /** Holds accounting information for a single step in the layered encryption
1268 * performed by a circuit. Used only at the client edge of a circuit. */
1269 typedef struct crypt_path_t {
1270 uint32_t magic;
1272 /* crypto environments */
1273 /** Encryption key and counter for cells heading towards the OR at this
1274 * step. */
1275 crypto_cipher_env_t *f_crypto;
1276 /** Encryption key and counter for cells heading back from the OR at this
1277 * step. */
1278 crypto_cipher_env_t *b_crypto;
1280 /** Digest state for cells heading towards the OR at this step. */
1281 crypto_digest_env_t *f_digest; /* for integrity checking */
1282 /** Digest state for cells heading away from the OR at this step. */
1283 crypto_digest_env_t *b_digest;
1285 /** Current state of Diffie-Hellman key negotiation with the OR at this
1286 * step. */
1287 crypto_dh_env_t *dh_handshake_state;
1288 /** Current state of 'fast' (non-PK) key negotiation with the OR at this
1289 * step. Used to save CPU when TLS is already providing all the
1290 * authentication, secrecy, and integrity we need, and we're already
1291 * distinguishable from an OR.
1293 char fast_handshake_state[DIGEST_LEN];
1294 /** Negotiated key material shared with the OR at this step. */
1295 char handshake_digest[DIGEST_LEN];/* KH in tor-spec.txt */
1297 /** Information to extend to the OR at this step. */
1298 extend_info_t *extend_info;
1300 /** Is the circuit built to this step? Must be one of:
1301 * - CPATH_STATE_CLOSED (The circuit has not been extended to this step)
1302 * - CPATH_STATE_AWAITING_KEYS (We have sent an EXTEND/CREATE to this step
1303 * and not received an EXTENDED/CREATED)
1304 * - CPATH_STATE_OPEN (The circuit has been extended to this step) */
1305 uint8_t state;
1306 #define CPATH_STATE_CLOSED 0
1307 #define CPATH_STATE_AWAITING_KEYS 1
1308 #define CPATH_STATE_OPEN 2
1309 struct crypt_path_t *next; /**< Link to next crypt_path_t in the circuit.
1310 * (The list is circular, so the last node
1311 * links to the first.) */
1312 struct crypt_path_t *prev; /**< Link to previous crypt_path_t in the
1313 * circuit. */
1315 int package_window; /**< How many bytes are we allowed to originate ending
1316 * at this step? */
1317 int deliver_window; /**< How many bytes are we willing to deliver originating
1318 * at this step? */
1319 } crypt_path_t;
1321 #define CPATH_KEY_MATERIAL_LEN (20*2+16*2)
1323 #define DH_KEY_LEN DH_BYTES
1324 #define ONIONSKIN_CHALLENGE_LEN (PKCS1_OAEP_PADDING_OVERHEAD+\
1325 CIPHER_KEY_LEN+\
1326 DH_KEY_LEN)
1327 #define ONIONSKIN_REPLY_LEN (DH_KEY_LEN+DIGEST_LEN)
1328 #define REND_COOKIE_LEN DIGEST_LEN
1330 /** Information used to build a circuit. */
1331 typedef struct {
1332 /** Intended length of the final circuit. */
1333 int desired_path_len;
1334 /** How to extend to the planned exit node. */
1335 extend_info_t *chosen_exit;
1336 /** Whether every node in the circ must have adequate uptime. */
1337 int need_uptime;
1338 /** Whether every node in the circ must have adequate capacity. */
1339 int need_capacity;
1340 /** Whether the last hop was picked with exiting in mind. */
1341 int is_internal;
1342 /** Did we pick this as a one-hop tunnel (not safe for other conns)?
1343 * These are for encrypted connections that exit to this router, not
1344 * for arbitrary exits from the circuit. */
1345 int onehop_tunnel;
1346 /** The crypt_path_t to append after rendezvous: used for rendezvous. */
1347 crypt_path_t *pending_final_cpath;
1348 /** How many times has building a circuit for this task failed? */
1349 int failure_count;
1350 /** At what time should we give up on this task? */
1351 time_t expiry_time;
1352 } cpath_build_state_t;
1354 #define ORIGIN_CIRCUIT_MAGIC 0x35315243u
1355 #define OR_CIRCUIT_MAGIC 0x98ABC04Fu
1357 typedef uint16_t circid_t;
1360 * A circuit is a path over the onion routing
1361 * network. Applications can connect to one end of the circuit, and can
1362 * create exit connections at the other end of the circuit. AP and exit
1363 * connections have only one circuit associated with them (and thus these
1364 * connection types are closed when the circuit is closed), whereas
1365 * OR connections multiplex many circuits at once, and stay standing even
1366 * when there are no circuits running over them.
1368 * A circuit_t structure can fill one of two roles. First, a or_circuit_t
1369 * links two connections together: either an edge connection and an OR
1370 * connection, or two OR connections. (When joined to an OR connection, a
1371 * circuit_t affects only cells sent to a particular circID on that
1372 * connection. When joined to an edge connection, a circuit_t affects all
1373 * data.)
1375 * Second, an origin_circuit_t holds the cipher keys and state for sending data
1376 * along a given circuit. At the OP, it has a sequence of ciphers, each
1377 * of which is shared with a single OR along the circuit. Separate
1378 * ciphers are used for data going "forward" (away from the OP) and
1379 * "backward" (towards the OP). At the OR, a circuit has only two stream
1380 * ciphers: one for data going forward, and one for data going backward.
1382 typedef struct circuit_t {
1383 uint32_t magic; /**< For memory and type debugging: must equal
1384 * ORIGIN_CIRCUIT_MAGIC or OR_CIRCUIT_MAGIC. */
1386 /** The OR connection that is next in this circuit. */
1387 or_connection_t *n_conn;
1388 /** The identity hash of n_conn. */
1389 char n_conn_id_digest[DIGEST_LEN];
1390 /** The circuit_id used in the next (forward) hop of this circuit. */
1391 uint16_t n_circ_id;
1392 /** The port for the OR that is next in this circuit. */
1393 uint16_t n_port;
1394 /** The IPv4 address of the OR that is next in this circuit. */
1395 uint32_t n_addr;
1396 /** How many relay data cells can we package (read from edge streams)
1397 * on this circuit before we receive a circuit-level sendme cell asking
1398 * for more? */
1399 int package_window;
1400 /** How many relay data cells will we deliver (write to edge streams)
1401 * on this circuit? When deliver_window gets low, we send some
1402 * circuit-level sendme cells to indicate that we're willing to accept
1403 * more. */
1404 int deliver_window;
1406 /** For storage while passing to cpuworker (state
1407 * CIRCUIT_STATE_ONIONSKIN_PENDING), or while n_conn is pending
1408 * (state CIRCUIT_STATE_OR_WAIT). When defined, it is always
1409 * length ONIONSKIN_CHALLENGE_LEN. */
1410 char *onionskin;
1412 time_t timestamp_created; /**< When was this circuit created? */
1413 time_t timestamp_dirty; /**< When the circuit was first used, or 0 if the
1414 * circuit is clean. */
1416 uint8_t state; /**< Current status of this circuit. */
1417 uint8_t purpose; /**< Why are we creating this circuit? */
1419 uint16_t marked_for_close; /**< Should we close this circuit at the end of
1420 * the main loop? (If true, holds the line number
1421 * where this circuit was marked.) */
1422 const char *marked_for_close_file; /**< For debugging: in which file was this
1423 * circuit marked for close? */
1425 struct circuit_t *next; /**< Next circuit in linked list. */
1426 } circuit_t;
1428 /** An origin_circuit_t holds data necessary to build and use a circuit.
1430 typedef struct origin_circuit_t {
1431 circuit_t _base;
1433 /** Linked list of AP streams (or EXIT streams if hidden service)
1434 * associated with this circuit. */
1435 edge_connection_t *p_streams;
1436 /** Build state for this circuit. It includes the intended path
1437 * length, the chosen exit router, rendezvous information, etc.
1439 cpath_build_state_t *build_state;
1440 /** The doubly-linked list of crypt_path_t entries, one per hop,
1441 * for this circuit. This includes ciphers for each hop,
1442 * integrity-checking digests for each hop, and package/delivery
1443 * windows for each hop.
1445 crypt_path_t *cpath;
1447 /** The rend_pk_digest field holds a hash of location-hidden service's
1448 * PK if purpose is S_ESTABLISH_INTRO or S_RENDEZVOUSING.
1450 char rend_pk_digest[DIGEST_LEN];
1452 /** Holds rendezvous cookie if purpose is C_ESTABLISH_REND. Filled with
1453 * zeroes otherwise.
1455 char rend_cookie[REND_COOKIE_LEN];
1458 * The rend_query field holds the y portion of y.onion (nul-terminated)
1459 * if purpose is C_INTRODUCING or C_ESTABLISH_REND, or is a C_GENERAL
1460 * for a hidden service, or is S_*.
1462 char rend_query[REND_SERVICE_ID_LEN+1];
1464 /** The next stream_id that will be tried when we're attempting to
1465 * construct a new AP stream originating at this circuit. */
1466 uint16_t next_stream_id;
1468 /** Quasi-global identifier for this circuit; used for control.c */
1469 /* XXXX NM This can get re-used after 2**32 circuits. */
1470 uint32_t global_identifier;
1472 } origin_circuit_t;
1474 /** An or_circuit_t holds information needed to implement a circuit at an
1475 * OR. */
1476 typedef struct or_circuit_t {
1477 circuit_t _base;
1479 /** The circuit_id used in the previous (backward) hop of this circuit. */
1480 circid_t p_circ_id;
1481 /** The OR connection that is previous in this circuit. */
1482 or_connection_t *p_conn;
1483 /** Linked list of Exit streams associated with this circuit. */
1484 edge_connection_t *n_streams;
1485 /** Linked list of Exit streams associated with this circuit that are
1486 * still being resolved. */
1487 edge_connection_t *resolving_streams;
1488 /** The cipher used by intermediate hops for cells heading toward the
1489 * OP. */
1490 crypto_cipher_env_t *p_crypto;
1491 /** The cipher used by intermediate hops for cells heading away from
1492 * the OP. */
1493 crypto_cipher_env_t *n_crypto;
1495 /** The integrity-checking digest used by intermediate hops, for
1496 * cells packaged here and heading towards the OP.
1498 crypto_digest_env_t *p_digest;
1499 /** The integrity-checking digest used by intermediate hops, for
1500 * cells packaged at the OP and arriving here.
1502 crypto_digest_env_t *n_digest;
1504 /** Points to spliced circuit if purpose is REND_ESTABLISHED, and circuit
1505 * is not marked for close. */
1506 struct or_circuit_t *rend_splice;
1508 #if REND_COOKIE_LEN >= DIGEST_LEN
1509 #define REND_TOKEN_LEN REND_COOKIE_LEN
1510 #else
1511 #define REND_TOKEN_LEN DIGEST_LEN
1512 #endif
1514 /** A hash of location-hidden service's PK if purpose is INTRO_POINT, or a
1515 * rendezvous cookie if purpose is REND_POINT_WAITING. Filled with zeroes
1516 * otherwise.
1517 * ???? move to a subtype or adjunct structure? Wastes 20 bytes. -NM
1519 char rend_token[REND_TOKEN_LEN];
1521 /* ???? move to a subtype or adjunct structure? Wastes 20 bytes -NM */
1522 char handshake_digest[DIGEST_LEN]; /**< Stores KH for the handshake. */
1524 /** True iff this circuit was made with a CREATE_FAST cell. */
1525 unsigned int is_first_hop : 1;
1526 } or_circuit_t;
1528 /** Convert a circuit subtype to a circuit_t.*/
1529 #define TO_CIRCUIT(x) (&((x)->_base))
1531 /** Convert a circuit_t* to a pointer to the enclosing or_circuit_t. Asserts
1532 * if the cast is impossible. */
1533 static or_circuit_t *TO_OR_CIRCUIT(circuit_t *);
1534 /** Convert a circuit_t* to a pointer to the enclosing origin_circuit_t.
1535 * Asserts if the cast is impossible. */
1536 static origin_circuit_t *TO_ORIGIN_CIRCUIT(circuit_t *);
1538 static INLINE or_circuit_t *TO_OR_CIRCUIT(circuit_t *x)
1540 tor_assert(x->magic == OR_CIRCUIT_MAGIC);
1541 return DOWNCAST(or_circuit_t, x);
1543 static INLINE origin_circuit_t *TO_ORIGIN_CIRCUIT(circuit_t *x)
1545 tor_assert(x->magic == ORIGIN_CIRCUIT_MAGIC);
1546 return DOWNCAST(origin_circuit_t, x);
1549 #define ALLOW_INVALID_ENTRY 1
1550 #define ALLOW_INVALID_EXIT 2
1551 #define ALLOW_INVALID_MIDDLE 4
1552 #define ALLOW_INVALID_RENDEZVOUS 8
1553 #define ALLOW_INVALID_INTRODUCTION 16
1555 /** An entry specifying a set of addresses and ports that should be remapped
1556 * to another address and port before exiting this exit node. */
1557 typedef struct exit_redirect_t {
1558 uint32_t addr;
1559 uint32_t mask;
1560 uint16_t port_min;
1561 uint16_t port_max;
1563 uint32_t addr_dest;
1564 uint16_t port_dest;
1565 unsigned is_redirect:1;
1566 } exit_redirect_t;
1568 /** A linked list of lines in a config file. */
1569 typedef struct config_line_t {
1570 char *key;
1571 char *value;
1572 struct config_line_t *next;
1573 } config_line_t;
1575 /** Configuration options for a Tor process. */
1576 typedef struct {
1577 uint32_t _magic;
1579 /** What should the tor process actually do? */
1580 enum {
1581 CMD_RUN_TOR=0, CMD_LIST_FINGERPRINT, CMD_HASH_PASSWORD,
1582 CMD_VERIFY_CONFIG, CMD_RUN_UNITTESTS
1583 } command;
1584 const char *command_arg; /**< Argument for command-line option. */
1586 config_line_t *Logs; /**< New-style list of configuration lines
1587 * for logs */
1589 char *DebugLogFile; /**< Where to send verbose log messages. */
1590 char *DataDirectory; /**< OR only: where to store long-term data. */
1591 char *Nickname; /**< OR only: nickname of this onion router. */
1592 char *Address; /**< OR only: configured address for this onion router. */
1593 char *PidFile; /**< Where to store PID of Tor process. */
1595 char *ExitNodes; /**< Comma-separated list of nicknames of ORs to consider
1596 * as exits. */
1597 char *EntryNodes; /**< Comma-separated list of nicknames of ORs to consider
1598 * as entry points. */
1599 int StrictExitNodes; /**< Boolean: When none of our ExitNodes are up, do we
1600 * stop building circuits? */
1601 int StrictEntryNodes; /**< Boolean: When none of our EntryNodes are up, do we
1602 * stop building circuits? */
1603 char *ExcludeNodes; /**< Comma-separated list of nicknames of ORs not to
1604 * use in circuits. */
1606 char *RendNodes; /**< Comma-separated list of nicknames used as introduction
1607 * points. */
1608 char *RendExcludeNodes; /**< Comma-separated list of nicknames not to use
1609 * as introduction points. */
1611 smartlist_t *AllowInvalidNodes; /**< List of "entry", "middle", "exit" */
1612 int _AllowInvalid; /**< Bitmask; derived from AllowInvalidNodes; */
1613 config_line_t *ExitPolicy; /**< Lists of exit policy components. */
1614 int ExitPolicyRejectPrivate; /**< Should we not exit to local addresses? */
1615 config_line_t *SocksPolicy; /**< Lists of socks policy components */
1616 config_line_t *DirPolicy; /**< Lists of dir policy components */
1617 /** Addresses to bind for listening for SOCKS connections. */
1618 config_line_t *SocksListenAddress;
1619 /** Addresses to bind for listening for transparent pf/nefilter
1620 * connections. */
1621 config_line_t *TransListenAddress;
1622 /** Addresses to bind for listening for transparent natd connections */
1623 config_line_t *NatdListenAddress;
1624 /** Addresses to bind for listening for OR connections. */
1625 config_line_t *ORListenAddress;
1626 /** Addresses to bind for listening for directory connections. */
1627 config_line_t *DirListenAddress;
1628 /** Addresses to bind for listening for control connections. */
1629 config_line_t *ControlListenAddress;
1630 /** Local address to bind outbound sockets */
1631 char *OutboundBindAddress;
1632 /** Directory server only: which versions of
1633 * Tor should we tell users to run? */
1634 config_line_t *RecommendedVersions;
1635 config_line_t *RecommendedClientVersions;
1636 config_line_t *RecommendedServerVersions;
1637 /** Whether dirservers refuse router descriptors with private IPs. */
1638 int DirAllowPrivateAddresses;
1639 char *User; /**< Name of user to run Tor as. */
1640 char *Group; /**< Name of group to run Tor as. */
1641 int ORPort; /**< Port to listen on for OR connections. */
1642 int SocksPort; /**< Port to listen on for SOCKS connections. */
1643 /** Port to listen on for transparent pf/netfilter connections. */
1644 int TransPort;
1645 int NatdPort; /**< Port to listen on for transparent natd connections. */
1646 int ControlPort; /**< Port to listen on for control connections. */
1647 int DirPort; /**< Port to listen on for directory connections. */
1648 int AssumeReachable; /**< Whether to publish our descriptor regardless. */
1649 int AuthoritativeDir; /**< Boolean: is this an authoritative directory? */
1650 int V1AuthoritativeDir; /**< Boolean: is this an authoritative directory
1651 * for version 1 directories? */
1652 int HSAuthoritativeDir; /**< Boolean: does this an authoritative directory
1653 * handle hidden service requests? */
1654 int NamingAuthoritativeDir; /**< Boolean: is this an authoritative directory
1655 * that's willing to bind names? */
1656 int VersioningAuthoritativeDir; /**< Boolean: is this an authoritative
1657 * directory that's willing to recommend
1658 * versions? */
1659 int AvoidDiskWrites; /**< Boolean: should we never cache things to disk?
1660 * Not used yet. */
1661 int ClientOnly; /**< Boolean: should we never evolve into a server role? */
1662 int NoPublish; /**< Boolean: should we never publish a descriptor? */
1663 int PublishServerDescriptor; /**< Do we publish our descriptor as normal? */
1664 int PublishHidServDescriptors; /**< and our hidden service descriptors? */
1665 int FetchServerDescriptors; /**< Do we fetch server descriptors as normal? */
1666 int FetchHidServDescriptors; /** and hidden service descriptors? */
1667 int FetchUselessDescriptors; /**< Do we fetch non-running descriptors too? */
1668 int AllDirActionsPrivate; /**< Should every directory action be sent
1669 * through a Tor circuit? */
1671 int ConnLimit; /**< Demanded minimum number of simultaneous connections. */
1672 int _ConnLimit; /**< Maximum allowed number of simultaneous connections. */
1673 int RunAsDaemon; /**< If true, run in the background. (Unix only) */
1674 int FascistFirewall; /**< Whether to prefer ORs reachable on open ports. */
1675 smartlist_t *FirewallPorts; /**< Which ports our firewall allows
1676 * (strings). */
1677 config_line_t *ReachableAddresses; /**< IP:ports our firewall allows. */
1678 config_line_t *ReachableORAddresses; /**< IP:ports for OR conns. */
1679 config_line_t *ReachableDirAddresses; /**< IP:ports for Dir conns. */
1681 /** Application ports that require all nodes in circ to have sufficient
1682 * uptime. */
1683 smartlist_t *LongLivedPorts;
1684 /** Should we try to reuse the same exit node for a given host */
1685 smartlist_t *TrackHostExits;
1686 int TrackHostExitsExpire; /**< Number of seconds until we expire an
1687 * addressmap */
1688 config_line_t *AddressMap; /**< List of address map directives. */
1689 int RendPostPeriod; /**< How often do we post each rendezvous service
1690 * descriptor? Remember to publish them independently. */
1691 int KeepalivePeriod; /**< How often do we send padding cells to keep
1692 * connections alive? */
1693 int SocksTimeout; /**< How long do we let a socks connection wait
1694 * unattached before we fail it? */
1695 int CircuitBuildTimeout; /**< Cull non-open circuits that were born
1696 * at least this many seconds ago. */
1697 int CircuitIdleTimeout; /**< Cull open clean circuits that were born
1698 * at least this many seconds ago. */
1699 int MaxOnionsPending; /**< How many circuit CREATE requests do we allow
1700 * to wait simultaneously before we start dropping
1701 * them? */
1702 int NewCircuitPeriod; /**< How long do we use a circuit before building
1703 * a new one? */
1704 int MaxCircuitDirtiness; /**< Never use circs that were first used more than
1705 this interval ago. */
1706 uint64_t BandwidthRate; /**< How much bandwidth, on average, are we willing
1707 * to use in a second? */
1708 uint64_t BandwidthBurst; /**< How much bandwidth, at maximum, are we willing
1709 * to use in a second? */
1710 uint64_t MaxAdvertisedBandwidth; /**< How much bandwidth are we willing to
1711 * tell people we have? */
1712 int NumCpus; /**< How many CPUs should we try to use? */
1713 int RunTesting; /**< If true, create testing circuits to measure how well the
1714 * other ORs are running. */
1715 char *TestVia; /**< When reachability testing, use these as middle hop. */
1716 config_line_t *RendConfigLines; /**< List of configuration lines
1717 * for rendezvous services. */
1718 char *ContactInfo; /**< Contact info to be published in the directory */
1720 char *HttpProxy; /**< hostname[:port] to use as http proxy, if any */
1721 uint32_t HttpProxyAddr; /**< Parsed IPv4 addr for http proxy, if any */
1722 uint16_t HttpProxyPort; /**< Parsed port for http proxy, if any */
1723 char *HttpProxyAuthenticator; /**< username:password string, if any */
1725 char *HttpsProxy; /**< hostname[:port] to use as https proxy, if any */
1726 uint32_t HttpsProxyAddr; /**< Parsed IPv4 addr for https proxy, if any */
1727 uint16_t HttpsProxyPort; /**< Parsed port for https proxy, if any */
1728 char *HttpsProxyAuthenticator; /**< username:password string, if any */
1730 config_line_t *DirServers; /**< List of configuration lines
1731 * for directory servers. */
1732 char *MyFamily; /**< Declared family for this OR. */
1733 config_line_t *NodeFamilies; /**< List of config lines for
1734 * node families */
1735 config_line_t *RedirectExit; /**< List of config lines for simple
1736 * addr/port redirection */
1737 smartlist_t *RedirectExitList; /**< List of exit_redirect_t */
1738 config_line_t *AuthDirBadExit; /**< Address policy for descriptors to
1739 * mark as bad exits. */
1740 config_line_t *AuthDirReject; /**< Address policy for descriptors to
1741 * reject. */
1742 config_line_t *AuthDirInvalid; /**< Address policy for descriptors to
1743 * never mark as valid. */
1744 int AuthDirListBadExits; /**< True iff we should list bad exits,
1745 * and vote for all other exits as good. */
1746 int AuthDirRejectUnlisted; /**< Boolean: do we reject all routers that
1747 * aren't named in our fingerprint file? */
1748 char *AccountingStart; /**< How long is the accounting interval, and when
1749 * does it start? */
1750 uint64_t AccountingMax; /**< How many bytes do we allow per accounting
1751 * interval before hibernation? 0 for "never
1752 * hibernate." */
1754 char *HashedControlPassword; /**< Base64-encoded hash of a password for
1755 * the control system. */
1756 int CookieAuthentication; /**< Boolean: do we enable cookie-based auth for
1757 * the control system? */
1758 int LeaveStreamsUnattached; /**< Boolean: Does Tor attach new streams to
1759 * circuits itself (0), or does it expect a controller
1760 * to cope? (1) */
1761 int ShutdownWaitLength; /**< When we get a SIGINT and we're a server, how
1762 * long do we wait before exiting? */
1763 int SafeLogging; /**< Boolean: are we allowed to log sensitive strings
1764 * such as addresses (0), or do we scrub them first (1)? */
1765 int SafeSocks; /**< Boolean: should we outright refuse application
1766 * connections that use socks4 or socks5-with-local-dns? */
1767 #define LOG_PROTOCOL_WARN (get_options()->ProtocolWarnings ? \
1768 LOG_WARN : LOG_INFO)
1769 int ProtocolWarnings; /**< Boolean: when other parties screw up the Tor
1770 * protocol, is it a warn or an info in our logs? */
1771 int TestSocks; /**< Boolean: when we get a socks connection, do we loudly
1772 * log whether it was DNS-leaking or not? */
1773 int HardwareAccel; /**< Boolean: Should we enable OpenSSL hardware
1774 * acceleration where available? */
1775 int UseEntryGuards; /**< Boolean: Do we try to enter from a smallish number
1776 * of fixed nodes? */
1777 int NumEntryGuards; /**< How many entry guards do we try to establish? */
1778 int RephistTrackTime; /**< How many seconds do we keep rephist info? */
1779 int FastFirstHopPK; /**< If Tor believes it is safe, should we save a third
1780 * of our PK time by sending CREATE_FAST cells? */
1782 addr_policy_t *reachable_addr_policy; /**< Parsed from ReachableAddresses */
1784 char *VirtualAddrNetwork; /**< Address and mask to hand out for virtual
1785 * MAPADDRESS requests. */
1786 int ServerDNSSearchDomains; /**< Boolean: If set, we don't force exit
1787 * addresses to be FQDNs, but rather search for them in
1788 * the local domains. */
1789 int ServerDNSDetectHijacking; /**< Boolean: If true, check for DNS failure
1790 * hijacking. */
1791 char *ServerDNSResolvConfFile; /**< If provided, we configure our internal
1792 * resolver from the file here rather than from
1793 * /etc/resolv.conf (Unix) or the registry (Windows). */
1794 smartlist_t *ServerDNSTestAddresses; /**< A list of addresses that definitely
1795 * should be resolveable. Used for
1796 * testing our DNS server. */
1797 int EnforceDistinctSubnets; /**< If true, don't allow multiple routers in the
1798 * same network zone in the same circuit. */
1799 int TunnelDirConns; /**< If true, use BEGIN_DIR rather than BEGIN when
1800 * possible. */
1801 int PreferTunneledDirConns; /**< If true, avoid dirservers that don't
1802 * support BEGIN_DIR, when possible. */
1803 int AllowNonRFC953Hostnames; /**< If true, we allow connections to hostnames
1804 * with weird characters. */
1805 /** If true, we try resolving hostnames with weird characters. */
1806 int ServerDNSAllowNonRFC953Hostnames;
1807 } or_options_t;
1809 /** Persistent state for an onion router, as saved to disk. */
1810 typedef struct {
1811 uint32_t _magic;
1812 /** The time at which we next plan to write the state to the disk. Equal to
1813 * TIME_MAX if there are no saveable changes, 0 if there are changes that
1814 * should be saved right away. */
1815 time_t next_write;
1817 /** When was the state last written to disk? */
1818 time_t LastWritten;
1820 /** Fields for accounting bandwidth use. */
1821 time_t AccountingIntervalStart;
1822 uint64_t AccountingBytesReadInInterval;
1823 uint64_t AccountingBytesWrittenInInterval;
1824 int AccountingSecondsActive;
1825 uint64_t AccountingExpectedUsage;
1827 /** A list of Entry Guard-related configuration lines. */
1828 config_line_t *EntryGuards;
1830 /** These fields hold information on the history of bandwidth usage for
1831 * servers. The "Ends" fields hold the time when we last updated the
1832 * bandwidth usage. The "Interval" fields hold the granularity, in seconds,
1833 * of the entries of Values. The "Values" lists hold decimal string
1834 * representations of the number of bytes read or written in each
1835 * interval. */
1836 time_t BWHistoryReadEnds;
1837 int BWHistoryReadInterval;
1838 smartlist_t *BWHistoryReadValues;
1839 time_t BWHistoryWriteEnds;
1840 int BWHistoryWriteInterval;
1841 smartlist_t *BWHistoryWriteValues;
1843 /** What version of Tor wrote this state file? */
1844 char *TorVersion;
1846 /** Holds any unrecognized values we found in the state file, in the order
1847 * in which we found them. */
1848 config_line_t *ExtraLines;
1850 /** When did we last rotate our onion key? "0" for 'no idea'. */
1851 time_t LastRotatedOnionKey;
1852 } or_state_t;
1854 /** Change the next_write time of <b>state</b> to <b>when</b>, unless the
1855 * state is already scheduled to be written to disk earlier than <b>when</b>.
1857 static INLINE void or_state_mark_dirty(or_state_t *state, time_t when)
1859 if (state->next_write > when)
1860 state->next_write = when;
1863 #define MAX_SOCKS_REPLY_LEN 1024
1864 #define MAX_SOCKS_ADDR_LEN 256
1866 /** Please open a TCP connection to this addr:port. */
1867 #define SOCKS_COMMAND_CONNECT 0x01
1868 /** Please turn this FQDN into an IP address, privately. */
1869 #define SOCKS_COMMAND_RESOLVE 0xF0
1870 /** Please turn this IP address into an FQDN, privately. */
1871 #define SOCKS_COMMAND_RESOLVE_PTR 0xF1
1872 /** Please open an encrypted direct TCP connection to the directory port
1873 * of the Tor server specified by address:port. (In this case address:port
1874 * specifies the ORPort of the server.) */
1875 #define SOCKS_COMMAND_CONNECT_DIR 0xF2
1877 #define SOCKS_COMMAND_IS_CONNECT(c) ((c)==SOCKS_COMMAND_CONNECT || \
1878 (c)==SOCKS_COMMAND_CONNECT_DIR)
1879 #define SOCKS_COMMAND_IS_RESOLVE(c) ((c)==SOCKS_COMMAND_RESOLVE || \
1880 (c)==SOCKS_COMMAND_RESOLVE_PTR)
1882 /** State of a SOCKS request from a user to an OP */
1883 struct socks_request_t {
1884 /** Which version of SOCKS did the client use? One of "0, 4, 5" -- where
1885 * 0 means that no socks handshake ever took place, and this is just a
1886 * stub connection (e.g. see connection_ap_make_bridge()). */
1887 char socks_version;
1888 int command; /**< What is this stream's goal? One from the above list. */
1889 size_t replylen; /**< Length of <b>reply</b>. */
1890 char reply[MAX_SOCKS_REPLY_LEN]; /**< Write an entry into this string if
1891 * we want to specify our own socks reply,
1892 * rather than using the default socks4 or
1893 * socks5 socks reply. We use this for the
1894 * two-stage socks5 handshake.
1896 int has_finished; /**< Has the SOCKS handshake finished? */
1897 char address[MAX_SOCKS_ADDR_LEN]; /**< What address did the client ask to
1898 connect to? */
1899 uint16_t port; /**< What port did the client ask to connect to? */
1902 /* all the function prototypes go here */
1904 /********************************* buffers.c ***************************/
1906 buf_t *buf_new(void);
1907 buf_t *buf_new_with_capacity(size_t size);
1908 void buf_free(buf_t *buf);
1909 void buf_clear(buf_t *buf);
1910 void buf_shrink(buf_t *buf);
1912 size_t buf_datalen(const buf_t *buf);
1913 size_t buf_capacity(const buf_t *buf);
1914 const char *_buf_peek_raw_buffer(const buf_t *buf);
1916 int read_to_buf(int s, size_t at_most, buf_t *buf, int *reached_eof);
1917 int read_to_buf_tls(tor_tls_t *tls, size_t at_most, buf_t *buf);
1919 int flush_buf(int s, buf_t *buf, size_t sz, size_t *buf_flushlen);
1920 int flush_buf_tls(tor_tls_t *tls, buf_t *buf, size_t sz, size_t *buf_flushlen);
1922 int write_to_buf(const char *string, size_t string_len, buf_t *buf);
1923 int write_to_buf_zlib(buf_t *buf, tor_zlib_state_t *state,
1924 const char *data, size_t data_len, int done);
1925 int fetch_from_buf(char *string, size_t string_len, buf_t *buf);
1926 int fetch_from_buf_http(buf_t *buf,
1927 char **headers_out, size_t max_headerlen,
1928 char **body_out, size_t *body_used, size_t max_bodylen,
1929 int force_complete);
1930 int fetch_from_buf_socks(buf_t *buf, socks_request_t *req,
1931 int log_sockstype, int safe_socks);
1932 int fetch_from_buf_control0(buf_t *buf, uint32_t *len_out, uint16_t *type_out,
1933 char **body_out, int check_for_v1);
1934 int fetch_from_buf_line(buf_t *buf, char *data_out, size_t *data_len);
1935 int fetch_from_buf_line_lf(buf_t *buf, char *data_out, size_t *data_len);
1937 void assert_buf_ok(buf_t *buf);
1939 /********************************* circuitbuild.c **********************/
1941 char *circuit_list_path(origin_circuit_t *circ, int verbose);
1942 char *circuit_list_path_for_controller(origin_circuit_t *circ);
1943 void circuit_log_path(int severity, unsigned int domain,
1944 origin_circuit_t *circ);
1945 void circuit_rep_hist_note_result(origin_circuit_t *circ);
1946 origin_circuit_t *origin_circuit_init(uint8_t purpose, int onehop_tunnel,
1947 int need_uptime,
1948 int need_capacity, int internal);
1949 origin_circuit_t *circuit_establish_circuit(uint8_t purpose,
1950 int onehop_tunnel, extend_info_t *exit,
1951 int need_uptime, int need_capacity,
1952 int internal);
1953 int circuit_handle_first_hop(origin_circuit_t *circ);
1954 void circuit_n_conn_done(or_connection_t *or_conn, int status);
1955 int inform_testing_reachability(void);
1956 int circuit_send_next_onion_skin(origin_circuit_t *circ);
1957 void circuit_note_clock_jumped(int seconds_elapsed);
1958 int circuit_extend(cell_t *cell, circuit_t *circ);
1959 int circuit_init_cpath_crypto(crypt_path_t *cpath, const char *key_data,
1960 int reverse);
1961 int circuit_finish_handshake(origin_circuit_t *circ, uint8_t cell_type,
1962 const char *reply);
1963 int circuit_truncated(origin_circuit_t *circ, crypt_path_t *layer);
1964 int onionskin_answer(or_circuit_t *circ, uint8_t cell_type,
1965 const char *payload, const char *keys);
1966 int circuit_all_predicted_ports_handled(time_t now, int *need_uptime,
1967 int *need_capacity);
1969 int circuit_append_new_exit(origin_circuit_t *circ, extend_info_t *info);
1970 int circuit_extend_to_new_exit(origin_circuit_t *circ, extend_info_t *info);
1971 void onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop);
1972 extend_info_t *extend_info_from_router(routerinfo_t *r);
1973 extend_info_t *extend_info_from_routerstatus(routerstatus_t *s);
1974 extend_info_t *extend_info_dup(extend_info_t *info);
1975 void extend_info_free(extend_info_t *info);
1976 routerinfo_t *build_state_get_exit_router(cpath_build_state_t *state);
1977 const char *build_state_get_exit_nickname(cpath_build_state_t *state);
1979 void entry_guards_compute_status(void);
1980 int entry_guard_register_connect_status(const char *digest, int succeeded,
1981 time_t now);
1982 void entry_nodes_should_be_added(void);
1983 void entry_guards_prepend_from_config(void);
1984 void entry_guards_update_state(or_state_t *state);
1985 int entry_guards_parse_state(or_state_t *state, int set, char **msg);
1986 int getinfo_helper_entry_guards(control_connection_t *conn,
1987 const char *question, char **answer);
1988 void entry_guards_free_all(void);
1990 /********************************* circuitlist.c ***********************/
1992 circuit_t * _circuit_get_global_list(void);
1993 const char *circuit_state_to_string(int state);
1994 void circuit_dump_by_conn(connection_t *conn, int severity);
1995 void circuit_set_p_circid_orconn(or_circuit_t *circ, uint16_t id,
1996 or_connection_t *conn);
1997 void circuit_set_n_circid_orconn(circuit_t *circ, uint16_t id,
1998 or_connection_t *conn);
1999 void circuit_set_state(circuit_t *circ, int state);
2000 void circuit_close_all_marked(void);
2001 origin_circuit_t *origin_circuit_new(void);
2002 or_circuit_t *or_circuit_new(uint16_t p_circ_id, or_connection_t *p_conn);
2003 circuit_t *circuit_get_by_circid_orconn(uint16_t circ_id,
2004 or_connection_t *conn);
2005 circuit_t *circuit_get_by_edge_conn(edge_connection_t *conn);
2006 void circuit_unlink_all_from_or_conn(or_connection_t *conn, int reason);
2007 origin_circuit_t *circuit_get_by_global_id(uint32_t id);
2008 origin_circuit_t *circuit_get_by_rend_query_and_purpose(const char *rend_query,
2009 uint8_t purpose);
2010 origin_circuit_t *circuit_get_next_by_pk_and_purpose(origin_circuit_t *start,
2011 const char *digest, uint8_t purpose);
2012 or_circuit_t *circuit_get_rendezvous(const char *cookie);
2013 or_circuit_t *circuit_get_intro_point(const char *digest);
2014 origin_circuit_t *circuit_find_to_cannibalize(uint8_t purpose,
2015 extend_info_t *info,
2016 int need_uptime,
2017 int need_capacity, int internal);
2018 void circuit_mark_all_unused_circs(void);
2019 void circuit_expire_all_dirty_circs(void);
2020 void _circuit_mark_for_close(circuit_t *circ, int reason,
2021 int line, const char *file);
2022 int circuit_get_cpath_len(origin_circuit_t *circ);
2023 void circuit_get_all_pending_on_or_conn(smartlist_t *out,
2024 or_connection_t *or_conn);
2025 int circuit_count_pending_on_or_conn(or_connection_t *or_conn);
2027 #define circuit_mark_for_close(c, reason) \
2028 _circuit_mark_for_close((c), (reason), __LINE__, _SHORT_FILE_)
2030 void assert_cpath_layer_ok(const crypt_path_t *cp);
2031 void assert_circuit_ok(const circuit_t *c);
2032 void circuit_free_all(void);
2034 /********************************* circuituse.c ************************/
2036 void circuit_expire_building(time_t now);
2037 void circuit_remove_handled_ports(smartlist_t *needed_ports);
2038 int circuit_stream_is_being_handled(edge_connection_t *conn, uint16_t port,
2039 int min);
2040 void circuit_build_needed_circs(time_t now);
2041 void circuit_detach_stream(circuit_t *circ, edge_connection_t *conn);
2043 void reset_bandwidth_test(void);
2044 int circuit_enough_testing_circs(void);
2046 void circuit_has_opened(origin_circuit_t *circ);
2047 void circuit_build_failed(origin_circuit_t *circ);
2048 origin_circuit_t *circuit_launch_by_nickname(uint8_t purpose,
2049 int onehop_tunnel,
2050 const char *exit_nickname,
2051 int need_uptime, int need_capacity,
2052 int is_internal);
2053 origin_circuit_t *circuit_launch_by_extend_info(uint8_t purpose,
2054 int onehop_tunnel,
2055 extend_info_t *info,
2056 int need_uptime, int need_capacity,
2057 int is_internal);
2058 origin_circuit_t *circuit_launch_by_router(uint8_t purpose,
2059 int onehop_tunnel,
2060 routerinfo_t *exit,
2061 int need_uptime, int need_capacity,
2062 int is_internal);
2063 void circuit_reset_failure_count(int timeout);
2064 int connection_ap_handshake_attach_chosen_circuit(edge_connection_t *conn,
2065 origin_circuit_t *circ);
2066 int connection_ap_handshake_attach_circuit(edge_connection_t *conn);
2068 /********************************* command.c ***************************/
2070 void command_process_cell(cell_t *cell, or_connection_t *conn);
2072 extern uint64_t stats_n_padding_cells_processed;
2073 extern uint64_t stats_n_create_cells_processed;
2074 extern uint64_t stats_n_created_cells_processed;
2075 extern uint64_t stats_n_relay_cells_processed;
2076 extern uint64_t stats_n_destroy_cells_processed;
2078 /********************************* config.c ***************************/
2080 or_options_t *get_options(void);
2081 int set_options(or_options_t *new_val, char **msg);
2082 void config_free_all(void);
2083 const char *safe_str(const char *address);
2084 const char *escaped_safe_str(const char *address);
2086 int config_get_lines(char *string, config_line_t **result);
2087 void config_free_lines(config_line_t *front);
2088 int options_trial_assign(config_line_t *list, int use_defaults,
2089 int clear_first, char **msg);
2090 int resolve_my_address(int warn_severity, or_options_t *options,
2091 uint32_t *addr, char **hostname_out);
2092 int is_local_IP(uint32_t ip) ATTR_PURE;
2093 void options_init(or_options_t *options);
2094 int options_init_from_torrc(int argc, char **argv);
2095 int options_init_logs(or_options_t *options, int validate_only);
2096 int option_is_recognized(const char *key);
2097 const char *option_get_canonical_name(const char *key);
2098 config_line_t *option_get_assignment(or_options_t *options,
2099 const char *key);
2100 char *options_dump(or_options_t *options, int minimal);
2101 int options_save_current(void);
2102 const char *get_torrc_fname(void);
2104 or_state_t *get_or_state(void);
2105 int or_state_load(void);
2106 int or_state_save(time_t now);
2108 int getinfo_helper_config(control_connection_t *conn,
2109 const char *question, char **answer);
2111 /********************************* connection.c ***************************/
2113 const char *conn_type_to_string(int type);
2114 const char *conn_state_to_string(int type, int state);
2116 connection_t *connection_new(int type);
2117 void connection_unregister(connection_t *conn);
2118 void connection_free(connection_t *conn);
2119 void connection_free_all(void);
2120 void connection_about_to_close_connection(connection_t *conn);
2121 void connection_close_immediate(connection_t *conn);
2122 void _connection_mark_for_close(connection_t *conn,int line, const char *file);
2124 #define connection_mark_for_close(c) \
2125 _connection_mark_for_close((c), __LINE__, _SHORT_FILE_)
2127 void connection_expire_held_open(void);
2129 int connection_connect(connection_t *conn, const char *address, uint32_t addr,
2130 uint16_t port);
2131 int retry_all_listeners(int force, smartlist_t *replaced_conns,
2132 smartlist_t *new_conns);
2134 int connection_bucket_write_limit(connection_t *conn);
2135 int global_write_bucket_low(connection_t *conn, size_t attempt, int priority);
2136 void connection_bucket_init(void);
2137 void connection_bucket_refill(int seconds_elapsed);
2139 int connection_handle_read(connection_t *conn);
2141 int connection_fetch_from_buf(char *string, size_t len, connection_t *conn);
2143 int connection_wants_to_flush(connection_t *conn);
2144 int connection_outbuf_too_full(connection_t *conn);
2145 int connection_handle_write(connection_t *conn, int force);
2146 void _connection_write_to_buf_impl(const char *string, size_t len,
2147 connection_t *conn, int zlib);
2148 static void connection_write_to_buf(const char *string, size_t len,
2149 connection_t *conn);
2150 static void connection_write_to_buf_zlib(const char *string, size_t len,
2151 dir_connection_t *conn, int done);
2152 static INLINE void
2153 connection_write_to_buf(const char *string, size_t len, connection_t *conn)
2155 _connection_write_to_buf_impl(string, len, conn, 0);
2157 static INLINE void
2158 connection_write_to_buf_zlib(const char *string, size_t len,
2159 dir_connection_t *conn, int done)
2161 _connection_write_to_buf_impl(string, len, TO_CONN(conn), done ? -1 : 1);
2164 or_connection_t *connection_or_exact_get_by_addr_port(uint32_t addr,
2165 uint16_t port);
2166 edge_connection_t *connection_get_by_global_id(uint32_t id);
2168 connection_t *connection_get_by_type(int type);
2169 connection_t *connection_get_by_type_purpose(int type, int purpose);
2170 connection_t *connection_get_by_type_addr_port_purpose(int type, uint32_t addr,
2171 uint16_t port, int purpose);
2172 connection_t *connection_get_by_type_state(int type, int state);
2173 connection_t *connection_get_by_type_state_lastwritten(int type, int state);
2174 connection_t *connection_get_by_type_state_rendquery(int type, int state,
2175 const char *rendquery);
2177 #define connection_speaks_cells(conn) ((conn)->type == CONN_TYPE_OR)
2178 int connection_is_listener(connection_t *conn);
2179 int connection_state_is_open(connection_t *conn);
2180 int connection_state_is_connecting(connection_t *conn);
2182 char *alloc_http_authenticator(const char *authenticator);
2184 void assert_connection_ok(connection_t *conn, time_t now);
2185 int connection_or_nonopen_was_started_here(or_connection_t *conn);
2186 int connection_or_too_full_for_dirserv_data(or_connection_t *conn);
2188 /********************************* connection_edge.c *************************/
2190 #define connection_mark_unattached_ap(conn, endreason) \
2191 _connection_mark_unattached_ap((conn), (endreason), __LINE__, _SHORT_FILE_)
2193 void _connection_mark_unattached_ap(edge_connection_t *conn, int endreason,
2194 int line, const char *file);
2195 int connection_edge_reached_eof(edge_connection_t *conn);
2196 int connection_edge_process_inbuf(edge_connection_t *conn,
2197 int package_partial);
2198 int connection_edge_destroy(uint16_t circ_id, edge_connection_t *conn);
2199 int connection_edge_end(edge_connection_t *conn, char reason,
2200 crypt_path_t *cpath_layer);
2201 int connection_edge_end_errno(edge_connection_t *conn,
2202 crypt_path_t *cpath_layer);
2203 int connection_edge_finished_flushing(edge_connection_t *conn);
2204 int connection_edge_finished_connecting(edge_connection_t *conn);
2206 int connection_ap_handshake_send_begin(edge_connection_t *ap_conn,
2207 origin_circuit_t *circ);
2208 int connection_ap_handshake_send_resolve(edge_connection_t *ap_conn,
2209 origin_circuit_t *circ);
2211 int connection_ap_make_bridge(char *address, uint16_t port,
2212 const char *digest, int command);
2213 void connection_ap_handshake_socks_reply(edge_connection_t *conn, char *reply,
2214 size_t replylen,
2215 int endreason);
2216 void connection_ap_handshake_socks_resolved(edge_connection_t *conn,
2217 int answer_type,
2218 size_t answer_len,
2219 const char *answer,
2220 int ttl);
2222 int connection_exit_begin_conn(cell_t *cell, circuit_t *circ);
2223 int connection_exit_begin_resolve(cell_t *cell, or_circuit_t *circ);
2224 void connection_exit_connect(edge_connection_t *conn);
2225 int connection_edge_is_rendezvous_stream(edge_connection_t *conn);
2226 int connection_ap_can_use_exit(edge_connection_t *conn, routerinfo_t *exit);
2227 void connection_ap_expire_beginning(void);
2228 void connection_ap_attach_pending(void);
2229 void circuit_discard_optional_exit_enclaves(extend_info_t *info);
2230 int connection_ap_detach_retriable(edge_connection_t *conn,
2231 origin_circuit_t *circ,
2232 int reason);
2233 int connection_ap_process_transparent(edge_connection_t *conn);
2235 int address_is_invalid_destination(const char *address, int client);
2237 void addressmap_init(void);
2238 void addressmap_clean(time_t now);
2239 void addressmap_clear_configured(void);
2240 void addressmap_clear_transient(void);
2241 void addressmap_free_all(void);
2242 int addressmap_rewrite(char *address, size_t maxlen);
2243 int addressmap_have_mapping(const char *address);
2244 void addressmap_register(const char *address, char *new_address,
2245 time_t expires);
2246 int parse_virtual_addr_network(const char *val, int validate_only,
2247 char **msg);
2248 int client_dns_incr_failures(const char *address);
2249 void client_dns_clear_failures(const char *address);
2250 void client_dns_set_addressmap(const char *address, uint32_t val,
2251 const char *exitname, int ttl);
2252 int address_is_in_virtual_range(const char *addr);
2253 const char *addressmap_register_virtual_address(int type, char *new_address);
2254 void addressmap_get_mappings(smartlist_t *sl, time_t min_expires,
2255 time_t max_expires);
2256 int connection_ap_handshake_rewrite_and_attach(edge_connection_t *conn,
2257 origin_circuit_t *circ);
2259 void set_exit_redirects(smartlist_t *lst);
2260 typedef enum hostname_type_t {
2261 NORMAL_HOSTNAME, ONION_HOSTNAME, EXIT_HOSTNAME, BAD_HOSTNAME
2262 } hostname_type_t;
2263 hostname_type_t parse_extended_hostname(char *address);
2265 /********************************* connection_or.c ***************************/
2267 void connection_or_remove_from_identity_map(or_connection_t *conn);
2268 void connection_or_clear_identity_map(void);
2269 or_connection_t *connection_or_get_by_identity_digest(const char *digest);
2271 int connection_or_reached_eof(or_connection_t *conn);
2272 int connection_or_process_inbuf(or_connection_t *conn);
2273 int connection_or_flushed_some(or_connection_t *conn);
2274 int connection_or_finished_flushing(or_connection_t *conn);
2275 int connection_or_finished_connecting(or_connection_t *conn);
2277 or_connection_t *connection_or_connect(uint32_t addr, uint16_t port,
2278 const char *id_digest);
2280 int connection_tls_start_handshake(or_connection_t *conn, int receiving);
2281 int connection_tls_continue_handshake(or_connection_t *conn);
2283 void connection_or_write_cell_to_buf(const cell_t *cell,
2284 or_connection_t *conn);
2285 int connection_or_send_destroy(uint16_t circ_id, or_connection_t *conn,
2286 int reason);
2288 /********************************* control.c ***************************/
2290 typedef enum circuit_status_event_t {
2291 CIRC_EVENT_LAUNCHED = 0,
2292 CIRC_EVENT_BUILT = 1,
2293 CIRC_EVENT_EXTENDED = 2,
2294 CIRC_EVENT_FAILED = 3,
2295 CIRC_EVENT_CLOSED = 4,
2296 } circuit_status_event_t;
2298 typedef enum stream_status_event_t {
2299 STREAM_EVENT_SENT_CONNECT = 0,
2300 STREAM_EVENT_SENT_RESOLVE = 1,
2301 STREAM_EVENT_SUCCEEDED = 2,
2302 STREAM_EVENT_FAILED = 3,
2303 STREAM_EVENT_CLOSED = 4,
2304 STREAM_EVENT_NEW = 5,
2305 STREAM_EVENT_NEW_RESOLVE = 6,
2306 STREAM_EVENT_FAILED_RETRIABLE = 7,
2307 STREAM_EVENT_REMAP = 8
2308 } stream_status_event_t;
2310 typedef enum or_conn_status_event_t {
2311 OR_CONN_EVENT_LAUNCHED = 0,
2312 OR_CONN_EVENT_CONNECTED = 1,
2313 OR_CONN_EVENT_FAILED = 2,
2314 OR_CONN_EVENT_CLOSED = 3,
2315 OR_CONN_EVENT_NEW = 4,
2316 } or_conn_status_event_t;
2318 void control_update_global_event_mask(void);
2319 void control_adjust_event_log_severity(void);
2321 /** Execute the statement <b>stmt</b>, which may log events concerning the
2322 * connection <b>conn</b>. To prevent infinite loops, disable log messages
2323 * being sent to controllers if <b>conn</b> is a control connection.
2325 * Stmt must not contain any return or goto statements.
2327 #define CONN_LOG_PROTECT(conn, stmt) \
2328 do { \
2329 int _log_conn_is_control = (conn && conn->type == CONN_TYPE_CONTROL); \
2330 if (_log_conn_is_control) \
2331 disable_control_logging(); \
2332 do {stmt;} while (0); \
2333 if (_log_conn_is_control) \
2334 enable_control_logging(); \
2335 } while (0)
2337 /** Log information about the connection <b>conn</b>, protecting it as with
2338 * CONN_LOG_PROTECT. Example:
2340 * LOG_FN_CONN(conn, (LOG_DEBUG, "Socket %d wants to write", conn->s));
2342 #define LOG_FN_CONN(conn, args) \
2343 CONN_LOG_PROTECT(conn, log_fn args)
2345 int connection_control_finished_flushing(control_connection_t *conn);
2346 int connection_control_reached_eof(control_connection_t *conn);
2347 int connection_control_process_inbuf(control_connection_t *conn);
2349 int control_event_circuit_status(origin_circuit_t *circ,
2350 circuit_status_event_t e, int reason);
2351 int control_event_stream_status(edge_connection_t *conn,
2352 stream_status_event_t e,
2353 int reason);
2354 int control_tls_error_to_reason(int e);
2355 int control_event_or_conn_status(or_connection_t *conn,
2356 or_conn_status_event_t e, int reason);
2357 int control_event_bandwidth_used(uint32_t n_read, uint32_t n_written);
2358 int control_event_stream_bandwidth_used(void);
2359 void control_event_logmsg(int severity, unsigned int domain, const char *msg);
2360 int control_event_descriptors_changed(smartlist_t *routers);
2361 int control_event_address_mapped(const char *from, const char *to,
2362 time_t expires);
2363 int control_event_or_authdir_new_descriptor(const char *action,
2364 const char *descriptor,
2365 const char *msg);
2366 int control_event_my_descriptor_changed(void);
2367 int control_event_networkstatus_changed(smartlist_t *statuses);
2368 int control_event_networkstatus_changed_single(local_routerstatus_t *rs);
2369 int control_event_general_status(int severity, const char *format, ...)
2370 CHECK_PRINTF(2,3);
2371 int control_event_client_status(int severity, const char *format, ...)
2372 CHECK_PRINTF(2,3);
2373 int control_event_server_status(int severity, const char *format, ...)
2374 CHECK_PRINTF(2,3);
2375 int control_event_guard(const char *nickname, const char *digest,
2376 const char *status);
2378 int init_cookie_authentication(int enabled);
2379 int decode_hashed_password(char *buf, const char *hashed);
2380 void disable_control_logging(void);
2381 void enable_control_logging(void);
2383 /********************************* cpuworker.c *****************************/
2385 void cpu_init(void);
2386 void cpuworkers_rotate(void);
2387 int connection_cpu_finished_flushing(connection_t *conn);
2388 int connection_cpu_reached_eof(connection_t *conn);
2389 int connection_cpu_process_inbuf(connection_t *conn);
2390 int assign_to_cpuworker(connection_t *cpuworker, uint8_t question_type,
2391 void *task);
2393 /********************************* directory.c ***************************/
2395 void directory_post_to_dirservers(uint8_t purpose, const char *payload,
2396 size_t payload_len);
2397 void directory_get_from_dirserver(uint8_t purpose, const char *resource,
2398 int retry_if_no_servers);
2399 void directory_initiate_command_routerstatus(routerstatus_t *status,
2400 uint8_t purpose,
2401 int private_connection,
2402 const char *resource,
2403 const char *payload,
2404 size_t payload_len);
2406 int parse_http_response(const char *headers, int *code, time_t *date,
2407 compress_method_t *compression, char **response);
2409 int connection_dir_reached_eof(dir_connection_t *conn);
2410 int connection_dir_process_inbuf(dir_connection_t *conn);
2411 int connection_dir_finished_flushing(dir_connection_t *conn);
2412 int connection_dir_finished_connecting(dir_connection_t *conn);
2413 void connection_dir_request_failed(dir_connection_t *conn);
2414 void directory_initiate_command(const char *address, uint32_t addr,
2415 uint16_t dir_port, int supports_begindir,
2416 const char *digest, uint8_t purpose,
2417 int private_connection, const char *resource,
2418 const char *payload, size_t payload_len);
2420 int dir_split_resource_into_fingerprints(const char *resource,
2421 smartlist_t *fp_out, int *compresseed_out,
2422 int decode_hex, int sort_uniq);
2423 char *directory_dump_request_log(void);
2425 /********************************* dirserv.c ***************************/
2427 #define UNNAMED_ROUTER_NICKNAME "Unnamed"
2429 int connection_dirserv_flushed_some(dir_connection_t *conn);
2430 void connection_dirserv_unlink_from_bridge(dir_connection_t *dir_conn);
2431 void connection_dirserv_stop_blocking_all_on_or_conn(or_connection_t *or_conn);
2433 int dirserv_add_own_fingerprint(const char *nickname, crypto_pk_env_t *pk);
2434 int dirserv_load_fingerprint_file(void);
2435 void dirserv_free_fingerprint_list(void);
2436 const char *dirserv_get_nickname_by_digest(const char *digest);
2437 int dirserv_add_descriptor(const char *desc, const char **msg);
2438 int getinfo_helper_dirserv_unregistered(control_connection_t *conn,
2439 const char *question, char **answer);
2440 void dirserv_free_descriptors(void);
2441 int dirserv_thinks_router_is_blatantly_unreachable(routerinfo_t *router,
2442 time_t now);
2443 int list_server_status(smartlist_t *routers, char **router_status_out,
2444 int for_controller);
2445 int dirserv_dump_directory_to_string(char **dir_out,
2446 crypto_pk_env_t *private_key,
2447 int complete);
2448 void directory_set_dirty(void);
2449 cached_dir_t *dirserv_get_directory(void);
2450 size_t dirserv_get_runningrouters(const char **rr, int compress);
2451 void dirserv_set_cached_directory(const char *directory, time_t when,
2452 int is_running_routers);
2453 void dirserv_set_cached_networkstatus_v2(const char *directory,
2454 const char *identity,
2455 time_t published);
2456 void dirserv_clear_old_networkstatuses(time_t cutoff);
2457 void dirserv_clear_old_v1_info(time_t now);
2458 void dirserv_get_networkstatus_v2(smartlist_t *result, const char *key);
2459 void dirserv_get_networkstatus_v2_fingerprints(smartlist_t *result,
2460 const char *key);
2461 int dirserv_get_routerdesc_fingerprints(smartlist_t *fps_out, const char *key,
2462 const char **msg);
2463 int dirserv_get_routerdescs(smartlist_t *descs_out, const char *key,
2464 const char **msg);
2465 void dirserv_orconn_tls_done(const char *address,
2466 uint16_t or_port,
2467 const char *digest_rcvd,
2468 int as_advertised);
2469 void dirserv_test_reachability(int try_all);
2470 int authdir_wants_to_reject_router(routerinfo_t *ri, const char **msg,
2471 int complain);
2472 int dirserv_would_reject_router(routerstatus_t *rs);
2473 size_t dirserv_estimate_data_size(smartlist_t *fps, int is_serverdescs,
2474 int compressed);
2475 void dirserv_free_all(void);
2476 void cached_dir_decref(cached_dir_t *d);
2478 /********************************* dns.c ***************************/
2480 int dns_init(void);
2481 void dns_free_all(void);
2482 uint32_t dns_clip_ttl(uint32_t ttl);
2483 int connection_dns_finished_flushing(connection_t *conn);
2484 int connection_dns_reached_eof(connection_t *conn);
2485 int connection_dns_process_inbuf(connection_t *conn);
2486 int dns_reset(void);
2487 void connection_dns_remove(edge_connection_t *conn);
2488 void assert_connection_edge_not_dns_pending(edge_connection_t *conn);
2489 void assert_all_pending_dns_resolves_ok(void);
2490 void dns_cancel_pending_resolve(const char *question);
2491 int dns_resolve(edge_connection_t *exitconn, or_circuit_t *circ);
2492 void dns_launch_correctness_checks(void);
2493 int dns_seems_to_be_broken(void);
2494 void dns_reset_correctness_checks(void);
2496 /********************************* hibernate.c **********************/
2498 int accounting_parse_options(or_options_t *options, int validate_only);
2499 int accounting_is_enabled(or_options_t *options);
2500 void configure_accounting(time_t now);
2501 void accounting_run_housekeeping(time_t now);
2502 void accounting_add_bytes(size_t n_read, size_t n_written, int seconds);
2503 int accounting_record_bandwidth_usage(time_t now, or_state_t *state);
2504 void hibernate_begin_shutdown(void);
2505 int we_are_hibernating(void);
2506 void consider_hibernation(time_t now);
2507 int getinfo_helper_accounting(control_connection_t *conn,
2508 const char *question, char **answer);
2509 void accounting_set_bandwidth_usage_from_state(or_state_t *state);
2511 /********************************* main.c ***************************/
2513 extern int has_completed_circuit;
2515 int connection_add(connection_t *conn);
2516 int connection_remove(connection_t *conn);
2517 int connection_in_array(connection_t *conn);
2518 void add_connection_to_closeable_list(connection_t *conn);
2519 int connection_is_on_closeable_list(connection_t *conn);
2521 void get_connection_array(connection_t ***array, int *n);
2523 void connection_watch_events(connection_t *conn, short events);
2524 int connection_is_reading(connection_t *conn);
2525 void connection_stop_reading(connection_t *conn);
2526 void connection_start_reading(connection_t *conn);
2528 int connection_is_writing(connection_t *conn);
2529 void connection_stop_writing(connection_t *conn);
2530 void connection_start_writing(connection_t *conn);
2532 void directory_all_unreachable(time_t now);
2533 void directory_info_has_arrived(time_t now, int from_cache);
2535 void ip_address_changed(int at_interface);
2536 void dns_servers_relaunch_checks(void);
2538 void control_signal_act(int the_signal);
2539 void handle_signals(int is_parent);
2540 void tor_cleanup(void);
2541 void tor_free_all(int postfork);
2543 int tor_main(int argc, char *argv[]);
2545 /********************************* onion.c ***************************/
2547 int onion_pending_add(or_circuit_t *circ);
2548 or_circuit_t *onion_next_task(void);
2549 void onion_pending_remove(or_circuit_t *circ);
2551 int onion_skin_create(crypto_pk_env_t *router_key,
2552 crypto_dh_env_t **handshake_state_out,
2553 char *onion_skin_out);
2555 int onion_skin_server_handshake(const char *onion_skin,
2556 crypto_pk_env_t *private_key,
2557 crypto_pk_env_t *prev_private_key,
2558 char *handshake_reply_out,
2559 char *key_out,
2560 size_t key_out_len);
2562 int onion_skin_client_handshake(crypto_dh_env_t *handshake_state,
2563 const char *handshake_reply,
2564 char *key_out,
2565 size_t key_out_len);
2567 int fast_server_handshake(const char *key_in,
2568 char *handshake_reply_out,
2569 char *key_out,
2570 size_t key_out_len);
2572 int fast_client_handshake(const char *handshake_state,
2573 const char *handshake_reply_out,
2574 char *key_out,
2575 size_t key_out_len);
2577 void clear_pending_onions(void);
2579 /********************************* policies.c ************************/
2581 /* (length of "accept 255.255.255.255/255.255.255.255:65535-65535\n" plus a
2582 * nul.)
2584 #define POLICY_BUF_LEN 52
2586 typedef enum {
2587 ADDR_POLICY_ACCEPTED=0,
2588 ADDR_POLICY_REJECTED=-1,
2589 ADDR_POLICY_PROBABLY_ACCEPTED=1,
2590 ADDR_POLICY_PROBABLY_REJECTED=2
2591 } addr_policy_result_t;
2593 int firewall_is_fascist_or(void);
2594 int fascist_firewall_allows_address_or(uint32_t addr, uint16_t port);
2595 int fascist_firewall_allows_address_dir(uint32_t addr, uint16_t port);
2596 int dir_policy_permits_address(uint32_t addr);
2597 int socks_policy_permits_address(uint32_t addr);
2598 int authdir_policy_permits_address(uint32_t addr, uint16_t port);
2599 int authdir_policy_valid_address(uint32_t addr, uint16_t port);
2600 int authdir_policy_badexit_address(uint32_t addr, uint16_t port);
2602 int validate_addr_policies(or_options_t *options, char **msg);
2603 void policies_parse_from_options(or_options_t *options);
2605 int cmp_addr_policies(addr_policy_t *a, addr_policy_t *b);
2606 addr_policy_result_t compare_addr_to_addr_policy(uint32_t addr,
2607 uint16_t port, addr_policy_t *policy);
2608 int policies_parse_exit_policy(config_line_t *cfg,
2609 addr_policy_t **dest,
2610 int rejectprivate);
2611 int exit_policy_is_general_exit(addr_policy_t *policy);
2612 int policy_is_reject_star(addr_policy_t *policy);
2613 int getinfo_helper_policies(control_connection_t *conn,
2614 const char *question, char **answer);
2615 int policy_write_item(char *buf, size_t buflen, addr_policy_t *policy);
2617 void addr_policy_free(addr_policy_t *p);
2618 void policies_free_all(void);
2620 /********************************* relay.c ***************************/
2622 extern uint64_t stats_n_relay_cells_relayed;
2623 extern uint64_t stats_n_relay_cells_delivered;
2625 int circuit_receive_relay_cell(cell_t *cell, circuit_t *circ,
2626 int cell_direction);
2628 void relay_header_pack(char *dest, const relay_header_t *src);
2629 void relay_header_unpack(relay_header_t *dest, const char *src);
2630 int relay_send_command_from_edge(uint16_t stream_id, circuit_t *circ,
2631 int relay_command, const char *payload,
2632 size_t payload_len, crypt_path_t *cpath_layer);
2633 int connection_edge_send_command(edge_connection_t *fromconn, circuit_t *circ,
2634 int relay_command, const char *payload,
2635 size_t payload_len,
2636 crypt_path_t *cpath_layer);
2637 int connection_edge_package_raw_inbuf(edge_connection_t *conn,
2638 int package_partial);
2639 void connection_edge_consider_sending_sendme(edge_connection_t *conn);
2640 socks5_reply_status_t connection_edge_end_reason_socks5_response(int reason);
2641 int errno_to_end_reason(int e);
2643 extern uint64_t stats_n_data_cells_packaged;
2644 extern uint64_t stats_n_data_bytes_packaged;
2645 extern uint64_t stats_n_data_cells_received;
2646 extern uint64_t stats_n_data_bytes_received;
2648 /********************************* rephist.c ***************************/
2650 void rep_hist_init(void);
2651 void rep_hist_note_connect_failed(const char* nickname, time_t when);
2652 void rep_hist_note_connect_succeeded(const char* nickname, time_t when);
2653 void rep_hist_note_disconnect(const char* nickname, time_t when);
2654 void rep_hist_note_connection_died(const char* nickname, time_t when);
2655 void rep_hist_note_extend_succeeded(const char *from_name,
2656 const char *to_name);
2657 void rep_hist_note_extend_failed(const char *from_name, const char *to_name);
2658 void rep_hist_dump_stats(time_t now, int severity);
2659 void rep_hist_note_bytes_read(int num_bytes, time_t when);
2660 void rep_hist_note_bytes_written(int num_bytes, time_t when);
2661 int rep_hist_bandwidth_assess(void);
2662 char *rep_hist_get_bandwidth_lines(void);
2663 void rep_hist_update_state(or_state_t *state);
2664 int rep_hist_load_state(or_state_t *state, char **err);
2665 void rep_history_clean(time_t before);
2667 void rep_hist_note_used_port(uint16_t port, time_t now);
2668 smartlist_t *rep_hist_get_predicted_ports(time_t now);
2669 void rep_hist_note_used_resolve(time_t now);
2670 void rep_hist_note_used_internal(time_t now, int need_uptime,
2671 int need_capacity);
2672 int rep_hist_get_predicted_internal(time_t now, int *need_uptime,
2673 int *need_capacity);
2675 int any_predicted_circuits(time_t now);
2676 int rep_hist_circbuilding_dormant(time_t now);
2678 /** Possible public/private key operations in Tor: used to keep track of where
2679 * we're spending our time. */
2680 typedef enum {
2681 SIGN_DIR, SIGN_RTR,
2682 VERIFY_DIR, VERIFY_RTR,
2683 ENC_ONIONSKIN, DEC_ONIONSKIN,
2684 TLS_HANDSHAKE_C, TLS_HANDSHAKE_S,
2685 REND_CLIENT, REND_MID, REND_SERVER,
2686 } pk_op_t;
2687 void note_crypto_pk_op(pk_op_t operation);
2688 void dump_pk_ops(int severity);
2690 void rep_hist_free_all(void);
2692 /********************************* rendclient.c ***************************/
2694 void rend_client_introcirc_has_opened(origin_circuit_t *circ);
2695 void rend_client_rendcirc_has_opened(origin_circuit_t *circ);
2696 int rend_client_introduction_acked(origin_circuit_t *circ, const char *request,
2697 size_t request_len);
2698 void rend_client_refetch_renddesc(const char *query);
2699 int rend_client_remove_intro_point(extend_info_t *failed_intro,
2700 const char *query);
2701 int rend_client_rendezvous_acked(origin_circuit_t *circ, const char *request,
2702 size_t request_len);
2703 int rend_client_receive_rendezvous(origin_circuit_t *circ, const char *request,
2704 size_t request_len);
2705 void rend_client_desc_here(const char *query);
2707 extend_info_t *rend_client_get_random_intro(const char *query);
2709 int rend_client_send_introduction(origin_circuit_t *introcirc,
2710 origin_circuit_t *rendcirc);
2712 /********************************* rendcommon.c ***************************/
2714 /** Information used to connect to a hidden service. */
2715 typedef struct rend_service_descriptor_t {
2716 crypto_pk_env_t *pk; /**< This service's public key. */
2717 int version; /**< 0 or 1. */
2718 time_t timestamp; /**< Time when the descriptor was generated. */
2719 uint16_t protocols; /**< Bitmask: which rendezvous protocols are supported?
2720 * (We allow bits '0', '1', and '2' to be set.) */
2721 int n_intro_points; /**< Number of introduction points. */
2722 /** Array of n_intro_points elements for this service's introduction points'
2723 * nicknames. Elements are removed from this array if introduction attempts
2724 * fail. */
2725 char **intro_points;
2726 /** Array of n_intro_points elements for this service's introduction points'
2727 * extend_infos, or NULL if this descriptor is V0. Elements are removed
2728 * from this array if introduction attempts fail. If this array is present,
2729 * its elements correspond to the elements of intro_points. */
2730 extend_info_t **intro_point_extend_info;
2731 } rend_service_descriptor_t;
2733 int rend_cmp_service_ids(const char *one, const char *two);
2735 void rend_process_relay_cell(circuit_t *circ, int command, size_t length,
2736 const char *payload);
2738 void rend_service_descriptor_free(rend_service_descriptor_t *desc);
2739 int rend_encode_service_descriptor(rend_service_descriptor_t *desc,
2740 int version,
2741 crypto_pk_env_t *key,
2742 char **str_out,
2743 size_t *len_out);
2744 rend_service_descriptor_t *rend_parse_service_descriptor(const char *str,
2745 size_t len);
2746 int rend_get_service_id(crypto_pk_env_t *pk, char *out);
2748 /** A cached rendezvous descriptor. */
2749 typedef struct rend_cache_entry_t {
2750 size_t len; /**< Length of <b>desc</b> */
2751 time_t received; /**< When was the descriptor received? */
2752 char *desc; /**< Service descriptor */
2753 rend_service_descriptor_t *parsed; /**< Parsed value of 'desc' */
2754 } rend_cache_entry_t;
2756 void rend_cache_init(void);
2757 void rend_cache_clean(void);
2758 void rend_cache_free_all(void);
2759 int rend_valid_service_id(const char *query);
2760 int rend_cache_lookup_desc(const char *query, int version, const char **desc,
2761 size_t *desc_len);
2762 int rend_cache_lookup_entry(const char *query, int version,
2763 rend_cache_entry_t **entry_out);
2764 int rend_cache_store(const char *desc, size_t desc_len);
2766 /********************************* rendservice.c ***************************/
2768 int num_rend_services(void);
2769 int rend_config_services(or_options_t *options, int validate_only);
2770 int rend_service_load_keys(void);
2771 void rend_services_init(void);
2772 void rend_services_introduce(void);
2773 void rend_consider_services_upload(time_t now);
2775 void rend_service_intro_has_opened(origin_circuit_t *circuit);
2776 int rend_service_intro_established(origin_circuit_t *circuit,
2777 const char *request,
2778 size_t request_len);
2779 void rend_service_rendezvous_has_opened(origin_circuit_t *circuit);
2780 int rend_service_introduce(origin_circuit_t *circuit, const char *request,
2781 size_t request_len);
2782 void rend_service_relaunch_rendezvous(origin_circuit_t *oldcirc);
2783 int rend_service_set_connection_addr_port(edge_connection_t *conn,
2784 origin_circuit_t *circ);
2785 void rend_service_dump_stats(int severity);
2786 void rend_service_free_all(void);
2788 /********************************* rendmid.c *******************************/
2789 int rend_mid_establish_intro(or_circuit_t *circ, const char *request,
2790 size_t request_len);
2791 int rend_mid_introduce(or_circuit_t *circ, const char *request,
2792 size_t request_len);
2793 int rend_mid_establish_rendezvous(or_circuit_t *circ, const char *request,
2794 size_t request_len);
2795 int rend_mid_rendezvous(or_circuit_t *circ, const char *request,
2796 size_t request_len);
2798 /********************************* router.c ***************************/
2800 crypto_pk_env_t *get_onion_key(void);
2801 time_t get_onion_key_set_at(void);
2802 void set_identity_key(crypto_pk_env_t *k);
2803 crypto_pk_env_t *get_identity_key(void);
2804 int identity_key_is_set(void);
2805 void dup_onion_keys(crypto_pk_env_t **key, crypto_pk_env_t **last);
2806 void rotate_onion_key(void);
2807 crypto_pk_env_t *init_key_from_file(const char *fname);
2808 int init_keys(void);
2810 int check_whether_orport_reachable(void);
2811 int check_whether_dirport_reachable(void);
2812 void consider_testing_reachability(int test_or, int test_dir);
2813 void router_orport_found_reachable(void);
2814 void router_dirport_found_reachable(void);
2815 void router_perform_bandwidth_test(int num_circs, time_t now);
2817 int authdir_mode(or_options_t *options);
2818 int clique_mode(or_options_t *options);
2819 int server_mode(or_options_t *options);
2820 int advertised_server_mode(void);
2821 int proxy_mode(or_options_t *options);
2822 void consider_publishable_server(int force);
2824 int router_is_clique_mode(routerinfo_t *router);
2825 void router_upload_dir_desc_to_dirservers(int force);
2826 void mark_my_descriptor_dirty_if_older_than(time_t when);
2827 void mark_my_descriptor_dirty(void);
2828 void check_descriptor_bandwidth_changed(time_t now);
2829 void check_descriptor_ipaddress_changed(time_t now);
2830 void router_new_address_suggestion(const char *suggestion);
2831 int router_compare_to_my_exit_policy(edge_connection_t *conn);
2832 routerinfo_t *router_get_my_routerinfo(void);
2833 const char *router_get_my_descriptor(void);
2834 int router_digest_is_me(const char *digest);
2835 int router_is_me(routerinfo_t *router);
2836 int router_fingerprint_is_me(const char *fp);
2837 int router_pick_published_address(or_options_t *options, uint32_t *addr);
2838 int router_rebuild_descriptor(int force);
2839 int router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
2840 crypto_pk_env_t *ident_key);
2841 int is_legal_nickname(const char *s);
2842 int is_legal_nickname_or_hexdigest(const char *s);
2843 int is_legal_hexdigest(const char *s);
2844 void router_get_verbose_nickname(char *buf, routerinfo_t *router);
2845 void router_reset_warnings(void);
2846 void router_reset_reachability(void);
2847 void router_free_all(void);
2849 /********************************* routerlist.c ***************************/
2851 /** Represents information about a single trusted directory server. */
2852 typedef struct trusted_dir_server_t {
2853 char *description;
2854 char *nickname;
2855 char *address; /**< Hostname. */
2856 uint32_t addr; /**< IPv4 address. */
2857 uint16_t dir_port; /**< Directory port. */
2858 uint16_t or_port; /**< OR port: Used for tunneling connections. */
2859 char digest[DIGEST_LEN]; /**< Digest of identity key. */
2860 unsigned int is_running:1; /**< True iff we think this server is running. */
2861 /** True iff this server is an authority for the older ("v1") directory
2862 * protocol. */
2863 unsigned int is_v1_authority:1;
2864 /** True iff this server is an authority for the newer ("v2") directory
2865 * protocol. */
2866 unsigned int is_v2_authority:1;
2867 /** True iff this server is an authority for hidden services. */
2868 unsigned int is_hidserv_authority:1;
2869 /** True iff this server has accepted the most recent server descriptor
2870 * we tried to upload to it. */
2871 unsigned int has_accepted_serverdesc:1;
2873 int n_networkstatus_failures; /**< How many times have we asked for this
2874 * server's network-status unsuccessfully? */
2875 local_routerstatus_t fake_status; /**< Used when we need to pass this trusted
2876 * dir_server_t to directory_initiate_command_*
2877 * as a routerstatus_t. Not updated by the
2878 * router-status management code!
2880 } trusted_dir_server_t;
2882 int router_reload_router_list(void);
2883 int router_reload_networkstatus(void);
2884 smartlist_t *router_get_trusted_dir_servers(void);
2885 routerstatus_t *router_pick_directory_server(int requireother,
2886 int fascistfirewall,
2887 int for_v2_directory,
2888 int retry_if_no_servers);
2889 typedef enum {
2890 V1_AUTHORITY, V2_AUTHORITY, HIDSERV_AUTHORITY,
2891 } authority_type_t;
2892 routerstatus_t *router_pick_trusteddirserver(authority_type_t type,
2893 int requireother,
2894 int fascistfirewall,
2895 int retry_if_no_servers);
2896 trusted_dir_server_t *router_get_trusteddirserver_by_digest(
2897 const char *digest);
2898 void routerlist_add_family(smartlist_t *sl, routerinfo_t *router);
2899 void add_nickname_list_to_smartlist(smartlist_t *sl, const char *list,
2900 int must_be_running);
2901 int router_nickname_is_in_list(routerinfo_t *router, const char *list);
2902 routerinfo_t *routerlist_find_my_routerinfo(void);
2903 routerinfo_t *router_find_exact_exit_enclave(const char *address,
2904 uint16_t port);
2906 #define ROUTER_REQUIRED_MIN_BANDWIDTH 10000
2907 int router_is_unreliable(routerinfo_t *router, int need_uptime,
2908 int need_capacity, int need_guard);
2909 uint32_t router_get_advertised_bandwidth(routerinfo_t *router);
2910 routerinfo_t *routerlist_sl_choose_by_bandwidth(smartlist_t *sl, int for_exit);
2911 routerstatus_t *routerstatus_sl_choose_by_bandwidth(smartlist_t *sl);
2913 routerinfo_t *router_choose_random_node(const char *preferred,
2914 const char *excluded,
2915 smartlist_t *excludedsmartlist,
2916 int need_uptime, int need_bandwidth,
2917 int need_guard,
2918 int allow_invalid, int strict,
2919 int weight_for_exit);
2920 routerinfo_t *router_get_by_nickname(const char *nickname,
2921 int warn_if_unnamed);
2922 routerinfo_t *router_get_by_hexdigest(const char *hexdigest);
2923 routerinfo_t *router_get_by_digest(const char *digest);
2924 signed_descriptor_t *router_get_by_descriptor_digest(const char *digest);
2925 const char *signed_descriptor_get_body(signed_descriptor_t *desc);
2926 int router_digest_version_as_new_as(const char *digest, const char *cutoff);
2927 int router_digest_is_trusted_dir(const char *digest);
2928 routerlist_t *router_get_routerlist(void);
2929 void routerlist_reset_warnings(void);
2930 void routerlist_free(routerlist_t *routerlist);
2931 void dump_routerlist_mem_usage(int severity);
2932 void routerlist_remove(routerlist_t *rl, routerinfo_t *ri, int idx,
2933 int make_old);
2934 void routerinfo_free(routerinfo_t *router);
2935 void routerstatus_free(routerstatus_t *routerstatus);
2936 void networkstatus_free(networkstatus_t *networkstatus);
2937 void routerlist_free_all(void);
2938 routerinfo_t *routerinfo_copy(const routerinfo_t *router);
2939 void router_set_status(const char *digest, int up);
2940 void routerlist_remove_old_routers(void);
2941 void networkstatus_list_clean(time_t now);
2942 int router_add_to_routerlist(routerinfo_t *router, const char **msg,
2943 int from_cache, int from_fetch);
2944 int router_load_single_router(const char *s, uint8_t purpose,
2945 const char **msg);
2946 void router_load_routers_from_string(const char *s,
2947 saved_location_t saved_location,
2948 smartlist_t *requested_fingerprints);
2949 typedef enum {
2950 NS_FROM_CACHE, NS_FROM_DIR_BY_FP, NS_FROM_DIR_ALL, NS_GENERATED
2951 } networkstatus_source_t;
2952 int router_set_networkstatus(const char *s, time_t arrived_at,
2953 networkstatus_source_t source,
2954 smartlist_t *requested_fingerprints);
2955 char *networkstatus_get_cache_filename(const char *identity_digest);
2957 int router_exit_policy_all_routers_reject(uint32_t addr, uint16_t port,
2958 int need_uptime);
2959 int router_exit_policy_rejects_all(routerinfo_t *router);
2961 void add_trusted_dir_server(const char *nickname, const char *address,
2962 uint16_t dir_port, uint16_t or_port,
2963 const char *digest, int is_v1_authority,
2964 int is_v2_authority, int is_hidserv_authority);
2965 void clear_trusted_dir_servers(void);
2966 int any_trusted_dir_is_v1_authority(void);
2967 networkstatus_t *networkstatus_get_by_digest(const char *digest);
2968 local_routerstatus_t *router_get_combined_status_by_digest(const char *digest);
2969 routerstatus_t *routerstatus_get_by_hexdigest(const char *hexdigest);
2970 void update_networkstatus_downloads(time_t now);
2971 void update_router_descriptor_downloads(time_t now);
2972 void routers_update_all_from_networkstatus(void);
2973 void routers_update_status_from_networkstatus(smartlist_t *routers,
2974 int reset_failures);
2975 smartlist_t *router_list_superseded(void);
2976 int router_have_minimum_dir_info(void);
2977 void networkstatus_list_update_recent(time_t now);
2978 void router_reset_descriptor_download_failures(void);
2979 void router_reset_status_download_failures(void);
2980 int router_differences_are_cosmetic(routerinfo_t *r1, routerinfo_t *r2);
2981 const char *esc_router_info(routerinfo_t *router);
2983 char *networkstatus_getinfo_helper_single(routerstatus_t *rs);
2984 int getinfo_helper_networkstatus(control_connection_t *conn,
2985 const char *question, char **answer);
2987 /********************************* routerparse.c ************************/
2989 #define MAX_STATUS_TAG_LEN 32
2990 /** Structure to hold parsed Tor versions. This is a little messier
2991 * than we would like it to be, because we changed version schemes with 0.1.0.
2993 * See version-spec.txt for the whole business.
2995 typedef struct tor_version_t {
2996 int major;
2997 int minor;
2998 int micro;
2999 /** Release status. For version in the post-0.1 format, this is always
3000 * VER_RELEASE. */
3001 enum { VER_PRE=0, VER_RC=1, VER_RELEASE=2, } status;
3002 int patchlevel;
3003 char status_tag[MAX_STATUS_TAG_LEN];
3004 } tor_version_t;
3006 typedef enum version_status_t {
3007 VS_RECOMMENDED=0, /**< This version is listed as recommended. */
3008 VS_OLD=1, /**< This version is older than any recommended version. */
3009 VS_NEW=2, /**< This version is newer than any recommended version. */
3010 VS_NEW_IN_SERIES=3, /**< This version is newer than any recommended version
3011 * in its series, but later recommended versions exist.
3013 VS_UNRECOMMENDED=4 /**< This version is not recommended (general case) */
3014 } version_status_t;
3016 int router_get_router_hash(const char *s, char *digest);
3017 int router_get_dir_hash(const char *s, char *digest);
3018 int router_get_runningrouters_hash(const char *s, char *digest);
3019 int router_get_networkstatus_v2_hash(const char *s, char *digest);
3020 int router_append_dirobj_signature(char *buf, size_t buf_len,
3021 const char *digest,
3022 crypto_pk_env_t *private_key);
3023 int router_parse_list_from_string(const char **s,
3024 smartlist_t *dest,
3025 saved_location_t saved_location);
3026 int router_parse_routerlist_from_directory(const char *s,
3027 routerlist_t **dest,
3028 crypto_pk_env_t *pkey,
3029 int check_version,
3030 int write_to_cache);
3031 int router_parse_runningrouters(const char *str);
3032 int router_parse_directory(const char *str);
3033 routerinfo_t *router_parse_entry_from_string(const char *s, const char *end,
3034 int cache_copy);
3035 addr_policy_t *router_parse_addr_policy_from_string(const char *s,
3036 int assume_action);
3037 version_status_t tor_version_is_obsolete(const char *myversion,
3038 const char *versionlist);
3039 version_status_t version_status_join(version_status_t a, version_status_t b);
3040 int tor_version_parse(const char *s, tor_version_t *out);
3041 int tor_version_as_new_as(const char *platform, const char *cutoff);
3042 int tor_version_compare(tor_version_t *a, tor_version_t *b);
3043 void sort_version_list(smartlist_t *lst, int remove_duplicates);
3044 void assert_addr_policy_ok(addr_policy_t *t);
3045 void dump_distinct_digest_count(int severity);
3047 networkstatus_t *networkstatus_parse_from_string(const char *s);
3049 #endif