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