Allow servers with no hostname or IP address to learn their IP address
[tor.git] / src / or / or.h
blob5700221fa10e9bec65acc89eb8d19389dc7e4f67
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 #define MAXCONNECTIONS 15000
85 #ifdef MS_WINDOWS
86 /* No, we don't need to redefine FD_SETSIZE before including winsock:
87 * we use libevent now, and libevent handles the select() stuff. Yes,
88 * some documents imply that we need to redefine anyway if we're using
89 * select() anywhere in our application or in anything it links to: these
90 * documents are either the holy texts of a cargo cult of network
91 * programmers, or more likely a simplification of what's going on for
92 * people who haven't read winsock[2].c for themselves.
94 #if (_MSC_VER <= 1300)
95 #include <winsock.h>
96 #else
97 #include <winsock2.h>
98 #include <ws2tcpip.h>
99 #endif
100 #endif
102 #ifdef MS_WINDOWS
103 #include <io.h>
104 #include <process.h>
105 #include <direct.h>
106 #include <windows.h>
107 #define snprintf _snprintf
108 #endif
110 #ifdef HAVE_EVENT_H
111 #include <event.h>
112 #else
113 #error "Tor requires libevent to build."
114 #endif
116 #include "../common/crypto.h"
117 #include "../common/tortls.h"
118 #include "../common/log.h"
119 #include "../common/compat.h"
120 #include "../common/container.h"
121 #include "../common/util.h"
122 #include "../common/torgzip.h"
124 /* These signals are defined to help control_signal_act work.
125 * XXXX Move into compat.h ?
127 #ifndef SIGHUP
128 #define SIGHUP 1
129 #endif
130 #ifndef SIGINT
131 #define SIGINT 2
132 #endif
133 #ifndef SIGUSR1
134 #define SIGUSR1 10
135 #endif
136 #ifndef SIGUSR2
137 #define SIGUSR2 12
138 #endif
139 #ifndef SIGTERM
140 #define SIGTERM 15
141 #endif
142 /* Controller signals start at a high number so we don't
143 * conflict with system-defined signals. */
144 #define SIGNEWNYM 129
146 #if (SIZEOF_CELL_T != 0)
147 /* On Irix, stdlib.h defines a cell_t type, so we need to make sure
148 * that our stuff always calls cell_t something different. */
149 #define cell_t tor_cell_t
150 #endif
152 #define MAX_NICKNAME_LEN 19
153 /* Hex digest plus dollar sign. */
154 #define MAX_HEX_NICKNAME_LEN (HEX_DIGEST_LEN+1)
155 /** Maximum size, in bytes, for resized buffers. */
156 #define MAX_BUF_SIZE ((1<<24)-1)
157 #define MAX_DIR_SIZE MAX_BUF_SIZE
159 /* For http parsing */
160 #define MAX_HEADERS_SIZE 50000
161 #define MAX_BODY_SIZE 500000
163 /** How long do we keep DNS cache entries before purging them (regardless of
164 * their TTL)? */
165 #define MAX_DNS_ENTRY_AGE (30*60)
166 #define DEFAULT_DNS_TTL (30*60)
167 /** How long can a TTL be before we stop believing it? */
168 #define MAX_DNS_TTL (3*60*60)
169 /** How small can a TTL be before we stop believing it? */
170 #define MIN_DNS_TTL (60)
172 /** How often do we rotate onion keys? */
173 #define MIN_ONION_KEY_LIFETIME (7*24*60*60)
174 /** How often do we rotate TLS contexts? */
175 #define MAX_SSL_KEY_LIFETIME (2*60*60)
177 /** How old do we allow a router to get before removing it
178 * from the router list? In seconds. */
179 #define ROUTER_MAX_AGE (60*60*48)
180 /** How old can a router get before we (as a server) will no longer
181 * consider it live? In seconds. */
182 #define ROUTER_MAX_AGE_TO_PUBLISH (60*60*20)
183 /** How old do we let a saved descriptor get before removing it? */
184 #define OLD_ROUTER_DESC_MAX_AGE (60*60*60)
185 /** How old do we let a networkstatus get before ignoring it? */
186 #define NETWORKSTATUS_MAX_AGE (60*60*24)
188 typedef enum {
189 CIRC_ID_TYPE_LOWER=0,
190 CIRC_ID_TYPE_HIGHER=1
191 } circ_id_type_t;
193 #define _CONN_TYPE_MIN 3
194 /** Type for sockets listening for OR connections. */
195 #define CONN_TYPE_OR_LISTENER 3
196 /** A bidirectional TLS connection transmitting a sequence of cells.
197 * May be from an OR to an OR, or from an OP to an OR. */
198 #define CONN_TYPE_OR 4
199 /** A TCP connection from an onion router to a stream's destination. */
200 #define CONN_TYPE_EXIT 5
201 /** Type for sockets listening for SOCKS connections. */
202 #define CONN_TYPE_AP_LISTENER 6
203 /** A SOCKS proxy connection from the user application to the onion
204 * proxy. */
205 #define CONN_TYPE_AP 7
206 /** Type for sockets listening for HTTP connections to the directory server. */
207 #define CONN_TYPE_DIR_LISTENER 8
208 /** Type for HTTP connections to the directory server. */
209 #define CONN_TYPE_DIR 9
210 /** Connection from the main process to a DNS worker process. */
211 #define CONN_TYPE_DNSWORKER 10
212 /** Connection from the main process to a CPU worker process. */
213 #define CONN_TYPE_CPUWORKER 11
214 /** Type for listening for connections from user interface process. */
215 #define CONN_TYPE_CONTROL_LISTENER 12
216 /** Type for connections from user interface process. */
217 #define CONN_TYPE_CONTROL 13
218 #define _CONN_TYPE_MAX 13
220 #define CONN_IS_EDGE(x) \
221 ((x)->type == CONN_TYPE_EXIT || (x)->type == CONN_TYPE_AP)
223 /** State for any listener connection. */
224 #define LISTENER_STATE_READY 0
226 #define _DNSWORKER_STATE_MIN 1
227 /** State for a connection to a dnsworker process that's idle. */
228 #define DNSWORKER_STATE_IDLE 1
229 /** State for a connection to a dnsworker process that's resolving a
230 * hostname. */
231 #define DNSWORKER_STATE_BUSY 2
232 #define _DNSWORKER_STATE_MAX 2
234 #define _CPUWORKER_STATE_MIN 1
235 /** State for a connection to a cpuworker process that's idle. */
236 #define CPUWORKER_STATE_IDLE 1
237 /** State for a connection to a cpuworker process that's processing a
238 * handshake. */
239 #define CPUWORKER_STATE_BUSY_ONION 2
240 #define _CPUWORKER_STATE_MAX 2
242 #define CPUWORKER_TASK_ONION CPUWORKER_STATE_BUSY_ONION
244 #define _OR_CONN_STATE_MIN 1
245 /** State for a connection to an OR: waiting for connect() to finish. */
246 #define OR_CONN_STATE_CONNECTING 1
247 /** State for a connection to an OR: waiting for proxy command to flush. */
248 #define OR_CONN_STATE_PROXY_FLUSHING 2
249 /** State for a connection to an OR: waiting for proxy response. */
250 #define OR_CONN_STATE_PROXY_READING 3
251 /** State for a connection to an OR: SSL is handshaking, not done yet. */
252 #define OR_CONN_STATE_HANDSHAKING 4
253 /** State for a connection to an OR: Ready to send/receive cells. */
254 #define OR_CONN_STATE_OPEN 5
255 #define _OR_CONN_STATE_MAX 5
257 #define _EXIT_CONN_STATE_MIN 1
258 /** State for an exit connection: waiting for response from dns farm. */
259 #define EXIT_CONN_STATE_RESOLVING 1
260 /** State for an exit connection: waiting for connect() to finish. */
261 #define EXIT_CONN_STATE_CONNECTING 2
262 /** State for an exit connection: open and ready to transmit data. */
263 #define EXIT_CONN_STATE_OPEN 3
264 /** State for an exit connection: waiting to be removed. */
265 #define EXIT_CONN_STATE_RESOLVEFAILED 4
266 #define _EXIT_CONN_STATE_MAX 4
268 /* the AP state values must be disjoint from the EXIT state values */
269 #define _AP_CONN_STATE_MIN 5
270 /** State for a SOCKS connection: waiting for SOCKS request. */
271 #define AP_CONN_STATE_SOCKS_WAIT 5
272 /** State for a SOCKS connection: got a y.onion URL; waiting to receive
273 * rendezvous descriptor. */
274 #define AP_CONN_STATE_RENDDESC_WAIT 6
275 /** The controller will attach this connection to a circuit; it isn't our
276 * job to do so. */
277 #define AP_CONN_STATE_CONTROLLER_WAIT 7
278 /** State for a SOCKS connection: waiting for a completed circuit. */
279 #define AP_CONN_STATE_CIRCUIT_WAIT 8
280 /** State for a SOCKS connection: sent BEGIN, waiting for CONNECTED. */
281 #define AP_CONN_STATE_CONNECT_WAIT 9
282 /** State for a SOCKS connection: send RESOLVE, waiting for RESOLVED. */
283 #define AP_CONN_STATE_RESOLVE_WAIT 10
284 /** State for a SOCKS connection: ready to send and receive. */
285 #define AP_CONN_STATE_OPEN 11
286 #define _AP_CONN_STATE_MAX 11
288 #define _DIR_CONN_STATE_MIN 1
289 /** State for connection to directory server: waiting for connect(). */
290 #define DIR_CONN_STATE_CONNECTING 1
291 /** State for connection to directory server: sending HTTP request. */
292 #define DIR_CONN_STATE_CLIENT_SENDING 2
293 /** State for connection to directory server: reading HTTP response. */
294 #define DIR_CONN_STATE_CLIENT_READING 3
295 /** State for connection to directory server: happy and finished. */
296 #define DIR_CONN_STATE_CLIENT_FINISHED 4
297 /** State for connection at directory server: waiting for HTTP request. */
298 #define DIR_CONN_STATE_SERVER_COMMAND_WAIT 5
299 /** State for connection at directory server: sending HTTP response. */
300 #define DIR_CONN_STATE_SERVER_WRITING 6
301 #define _DIR_CONN_STATE_MAX 6
303 #define _CONTROL_CONN_STATE_MIN 1
304 #define CONTROL_CONN_STATE_OPEN_V0 1
305 #define CONTROL_CONN_STATE_OPEN_V1 2
306 #define CONTROL_CONN_STATE_NEEDAUTH_V0 3
307 #define CONTROL_CONN_STATE_NEEDAUTH_V1 4
308 #define _CONTROL_CONN_STATE_MAX 4
310 #define _DIR_PURPOSE_MIN 1
311 /** A connection to a directory server: download a directory. */
312 #define DIR_PURPOSE_FETCH_DIR 1
313 /** A connection to a directory server: download just the list
314 * of running routers. */
315 #define DIR_PURPOSE_FETCH_RUNNING_LIST 2
316 /** A connection to a directory server: download a rendezvous
317 * descriptor. */
318 #define DIR_PURPOSE_FETCH_RENDDESC 3
319 /** A connection to a directory server: set after a rendezvous
320 * descriptor is downloaded. */
321 #define DIR_PURPOSE_HAS_FETCHED_RENDDESC 4
322 /** A connection to a directory server: download one or more network-status
323 * objects */
324 #define DIR_PURPOSE_FETCH_NETWORKSTATUS 5
325 /** A connection to a directory server: download one or more server
326 * descriptors. */
327 #define DIR_PURPOSE_FETCH_SERVERDESC 6
328 /** A connection to a directory server: upload a server descriptor. */
329 #define DIR_PURPOSE_UPLOAD_DIR 7
330 /** A connection to a directory server: upload a rendezvous
331 * descriptor. */
332 #define DIR_PURPOSE_UPLOAD_RENDDESC 8
333 /** Purpose for connection at a directory server. */
334 #define DIR_PURPOSE_SERVER 9
335 #define _DIR_PURPOSE_MAX 9
337 #define _EXIT_PURPOSE_MIN 1
338 #define EXIT_PURPOSE_CONNECT 1
339 #define EXIT_PURPOSE_RESOLVE 2
340 #define _EXIT_PURPOSE_MAX 2
342 /** Circuit state: I'm the origin, still haven't done all my handshakes. */
343 #define CIRCUIT_STATE_BUILDING 0
344 /** Circuit state: Waiting to process the onionskin. */
345 #define CIRCUIT_STATE_ONIONSKIN_PENDING 1
346 /** Circuit state: I'd like to deliver a create, but my n_conn is still
347 * connecting. */
348 #define CIRCUIT_STATE_OR_WAIT 2
349 /** Circuit state: onionskin(s) processed, ready to send/receive cells. */
350 #define CIRCUIT_STATE_OPEN 3
352 #define _CIRCUIT_PURPOSE_MIN 1
354 /* these circuits were initiated elsewhere */
355 #define _CIRCUIT_PURPOSE_OR_MIN 1
356 /** OR-side circuit purpose: normal circuit, at OR. */
357 #define CIRCUIT_PURPOSE_OR 1
358 /** OR-side circuit purpose: At OR, from Bob, waiting for intro from Alices. */
359 #define CIRCUIT_PURPOSE_INTRO_POINT 2
360 /** OR-side circuit purpose: At OR, from Alice, waiting for Bob. */
361 #define CIRCUIT_PURPOSE_REND_POINT_WAITING 3
362 /** OR-side circuit purpose: At OR, both circuits have this purpose. */
363 #define CIRCUIT_PURPOSE_REND_ESTABLISHED 4
364 #define _CIRCUIT_PURPOSE_OR_MAX 4
366 /* these circuits originate at this node */
368 /* here's how circ client-side purposes work:
369 * normal circuits are C_GENERAL.
370 * circuits that are c_introducing are either on their way to
371 * becoming open, or they are open and waiting for a
372 * suitable rendcirc before they send the intro.
373 * circuits that are c_introduce_ack_wait have sent the intro,
374 * but haven't gotten a response yet.
375 * circuits that are c_establish_rend are either on their way
376 * to becoming open, or they are open and have sent the
377 * establish_rendezvous cell but haven't received an ack.
378 * circuits that are c_rend_ready are open and have received a
379 * rend ack, but haven't heard from bob yet. if they have a
380 * buildstate->pending_final_cpath then they're expecting a
381 * cell from bob, else they're not.
382 * circuits that are c_rend_ready_intro_acked are open, and
383 * some intro circ has sent its intro and received an ack.
384 * circuits that are c_rend_joined are open, have heard from
385 * bob, and are talking to him.
387 /** Client-side circuit purpose: Normal circuit, with cpath. */
388 #define CIRCUIT_PURPOSE_C_GENERAL 5
389 /** Client-side circuit purpose: at Alice, connecting to intro point. */
390 #define CIRCUIT_PURPOSE_C_INTRODUCING 6
391 /** Client-side circuit purpose: at Alice, sent INTRODUCE1 to intro point,
392 * waiting for ACK/NAK. */
393 #define CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT 7
394 /** Client-side circuit purpose: at Alice, introduced and acked, closing. */
395 #define CIRCUIT_PURPOSE_C_INTRODUCE_ACKED 8
396 /** Client-side circuit purpose: at Alice, waiting for ack. */
397 #define CIRCUIT_PURPOSE_C_ESTABLISH_REND 9
398 /** Client-side circuit purpose: at Alice, waiting for Bob. */
399 #define CIRCUIT_PURPOSE_C_REND_READY 10
400 /** Client-side circuit purpose: at Alice, waiting for Bob, INTRODUCE
401 * has been acknowledged. */
402 #define CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED 11
403 /** Client-side circuit purpose: at Alice, rendezvous established. */
404 #define CIRCUIT_PURPOSE_C_REND_JOINED 12
406 /** Hidden-service-side circuit purpose: at Bob, waiting for introductions. */
407 #define CIRCUIT_PURPOSE_S_ESTABLISH_INTRO 13
408 /** Hidden-service-side circuit purpose: at Bob, successfully established
409 * intro. */
410 #define CIRCUIT_PURPOSE_S_INTRO 14
411 /** Hidden-service-side circuit purpose: at Bob, connecting to rend point. */
412 #define CIRCUIT_PURPOSE_S_CONNECT_REND 15
413 /** Hidden-service-side circuit purpose: at Bob, rendezvous established. */
414 #define CIRCUIT_PURPOSE_S_REND_JOINED 16
415 /** A testing circuit; not meant to be used for actual traffic. */
416 #define CIRCUIT_PURPOSE_TESTING 17
417 /** A controller made this circuit and Tor should not use it. */
418 #define CIRCUIT_PURPOSE_CONTROLLER 18
419 #define _CIRCUIT_PURPOSE_MAX 18
421 /** True iff the circuit purpose <b>p</b> is for a circuit that
422 * originated at this node. */
423 #define CIRCUIT_PURPOSE_IS_ORIGIN(p) ((p)>_CIRCUIT_PURPOSE_OR_MAX)
424 #define CIRCUIT_IS_ORIGIN(c) (CIRCUIT_PURPOSE_IS_ORIGIN((c)->purpose))
426 #define RELAY_COMMAND_BEGIN 1
427 #define RELAY_COMMAND_DATA 2
428 #define RELAY_COMMAND_END 3
429 #define RELAY_COMMAND_CONNECTED 4
430 #define RELAY_COMMAND_SENDME 5
431 #define RELAY_COMMAND_EXTEND 6
432 #define RELAY_COMMAND_EXTENDED 7
433 #define RELAY_COMMAND_TRUNCATE 8
434 #define RELAY_COMMAND_TRUNCATED 9
435 #define RELAY_COMMAND_DROP 10
436 #define RELAY_COMMAND_RESOLVE 11
437 #define RELAY_COMMAND_RESOLVED 12
439 #define RELAY_COMMAND_ESTABLISH_INTRO 32
440 #define RELAY_COMMAND_ESTABLISH_RENDEZVOUS 33
441 #define RELAY_COMMAND_INTRODUCE1 34
442 #define RELAY_COMMAND_INTRODUCE2 35
443 #define RELAY_COMMAND_RENDEZVOUS1 36
444 #define RELAY_COMMAND_RENDEZVOUS2 37
445 #define RELAY_COMMAND_INTRO_ESTABLISHED 38
446 #define RELAY_COMMAND_RENDEZVOUS_ESTABLISHED 39
447 #define RELAY_COMMAND_INTRODUCE_ACK 40
449 #define END_STREAM_REASON_MISC 1
450 #define END_STREAM_REASON_RESOLVEFAILED 2
451 #define END_STREAM_REASON_CONNECTREFUSED 3
452 #define END_STREAM_REASON_EXITPOLICY 4
453 #define END_STREAM_REASON_DESTROY 5
454 #define END_STREAM_REASON_DONE 6
455 #define END_STREAM_REASON_TIMEOUT 7
456 /* 8 is unallocated. */
457 #define END_STREAM_REASON_HIBERNATING 9
458 #define END_STREAM_REASON_INTERNAL 10
459 #define END_STREAM_REASON_RESOURCELIMIT 11
460 #define END_STREAM_REASON_CONNRESET 12
461 #define END_STREAM_REASON_TORPROTOCOL 13
463 /* These high-numbered end reasons are not part of the official spec,
464 * and are not intended to be put in relay end cells. They are here
465 * to be more informative when sending back socks replies to the
466 * application. */
467 #define END_STREAM_REASON_ALREADY_SOCKS_REPLIED 256
468 #define END_STREAM_REASON_CANT_ATTACH 257
469 #define END_STREAM_REASON_NET_UNREACHABLE 258
471 #define RESOLVED_TYPE_HOSTNAME 0
472 #define RESOLVED_TYPE_IPV4 4
473 #define RESOLVED_TYPE_IPV6 6
474 #define RESOLVED_TYPE_ERROR_TRANSIENT 0xF0
475 #define RESOLVED_TYPE_ERROR 0xF1
477 /* XXX We should document the meaning of these. */
478 #define END_CIRC_AT_ORIGIN -1
479 #define _END_CIRC_REASON_MIN 0
480 #define END_CIRC_REASON_NONE 0
481 #define END_CIRC_REASON_TORPROTOCOL 1
482 #define END_CIRC_REASON_INTERNAL 2
483 #define END_CIRC_REASON_REQUESTED 3
484 #define END_CIRC_REASON_HIBERNATING 4
485 #define END_CIRC_REASON_RESOURCELIMIT 5
486 #define END_CIRC_REASON_CONNECTFAILED 6
487 #define END_CIRC_REASON_OR_IDENTITY 7
488 #define END_CIRC_REASON_OR_CONN_CLOSED 8
489 #define _END_CIRC_REASON_MAX 8
491 /** Length of 'y' portion of 'y.onion' URL. */
492 #define REND_SERVICE_ID_LEN 16
494 #define CELL_DIRECTION_IN 1
495 #define CELL_DIRECTION_OUT 2
497 #ifdef TOR_PERF
498 #define CIRCWINDOW_START 10000
499 #define CIRCWINDOW_INCREMENT 1000
500 #define STREAMWINDOW_START 5000
501 #define STREAMWINDOW_INCREMENT 500
502 #else
503 #define CIRCWINDOW_START 1000
504 #define CIRCWINDOW_INCREMENT 100
505 #define STREAMWINDOW_START 500
506 #define STREAMWINDOW_INCREMENT 50
507 #endif
509 /* cell commands */
510 #define CELL_PADDING 0
511 #define CELL_CREATE 1
512 #define CELL_CREATED 2
513 #define CELL_RELAY 3
514 #define CELL_DESTROY 4
515 #define CELL_CREATE_FAST 5
516 #define CELL_CREATED_FAST 6
518 /** How long to test reachability before complaining to the user. */
519 #define TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT (20*60)
521 /* legal characters in a nickname */
522 #define LEGAL_NICKNAME_CHARACTERS \
523 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
525 /** Name to use in client TLS certificates if no nickname is given.*/
526 #define DEFAULT_CLIENT_NICKNAME "client"
528 #define SOCKS4_NETWORK_LEN 8
530 typedef enum {
531 SOCKS5_SUCCEEDED = 0x00,
532 SOCKS5_GENERAL_ERROR = 0x01,
533 SOCKS5_NOT_ALLOWED = 0x02,
534 SOCKS5_NET_UNREACHABLE = 0x03,
535 SOCKS5_HOST_UNREACHABLE = 0x04,
536 SOCKS5_CONNECTION_REFUSED = 0x05,
537 SOCKS5_TTL_EXPIRED = 0x06,
538 SOCKS5_COMMAND_NOT_SUPPORTED = 0x07,
539 SOCKS5_ADDRESS_TYPE_NOT_SUPPORTED = 0x08,
540 } socks5_reply_status_t;
543 * Relay payload:
544 * Relay command [1 byte]
545 * Recognized [2 bytes]
546 * Stream ID [2 bytes]
547 * Partial SHA-1 [4 bytes]
548 * Length [2 bytes]
549 * Relay payload [498 bytes]
552 #define CELL_PAYLOAD_SIZE 509
553 #define CELL_NETWORK_SIZE 512
555 #define RELAY_HEADER_SIZE (1+2+2+4+2)
556 #define RELAY_PAYLOAD_SIZE (CELL_PAYLOAD_SIZE-RELAY_HEADER_SIZE)
558 /** Parsed onion routing cell. All communication between nodes
559 * is via cells. */
560 typedef struct {
561 uint16_t circ_id; /**< Circuit which received the cell. */
562 uint8_t command; /**< Type of the cell: one of PADDING, CREATE, RELAY,
563 * or DESTROY. */
564 char payload[CELL_PAYLOAD_SIZE]; /**< Cell body. */
565 } cell_t;
567 /** Beginning of a RELAY cell payload. */
568 typedef struct {
569 uint8_t command; /**< The end-to-end relay command. */
570 uint16_t recognized; /**< Used to tell whether cell is for us. */
571 uint16_t stream_id; /**< Which stream is this cell associated with? */
572 char integrity[4]; /**< Used to tell whether cell is corrupted. */
573 uint16_t length; /**< How long is the payload body? */
574 } relay_header_t;
576 typedef struct buf_t buf_t;
577 typedef struct socks_request_t socks_request_t;
579 #define CONNECTION_MAGIC 0x7C3C304Eu
581 /** Description of a connection to another host or process, and associated
582 * data.
584 * A connection is named based on what it's connected to -- an "OR
585 * connection" has a Tor node on the other end, an "exit
586 * connection" has a website or other server on the other end, and an
587 * "AP connection" has an application proxy (and thus a user) on the
588 * other end.
590 * Every connection has a type and a state. Connections never change
591 * their type, but can go through many state changes in their lifetime.
593 * Every connection has two associated input and output buffers.
594 * Listeners don't use them. For non-listener connections, incoming
595 * data is appended to conn->inbuf, and outgoing data is taken from
596 * conn->outbuf. Connections differ primarily in the functions called
597 * to fill and drain these buffers.
599 struct connection_t {
600 uint32_t magic; /**< For memory debugging: must equal CONNECTION_MAGIC. */
602 uint8_t type; /**< What kind of connection is this? */
603 uint8_t state; /**< Current state of this connection. */
604 uint8_t purpose; /**< Only used for DIR types currently. */
605 unsigned wants_to_read:1; /**< Boolean: should we start reading again once
606 * the bandwidth throttler allows it? */
607 unsigned wants_to_write:1; /**< Boolean: should we start writing again once
608 * the bandwidth throttler allows reads? */
609 unsigned hold_open_until_flushed:1; /**< Despite this connection's being
610 * marked for close, do we flush it
611 * before closing it? */
612 unsigned has_sent_end:1; /**< For debugging; only used on edge connections.
613 * Set once we've set the stream end,
614 * and check in circuit_about_to_close_connection(). */
615 /** For control connections only. If set, we send extended info with control
616 * events as appropriate. */
617 unsigned int control_events_are_extended:1;
618 /** Used for OR conns that shouldn't get any new circs attached to them. */
619 unsigned int is_obsolete:1;
621 int s; /**< Our socket; -1 if this connection is closed. */
622 int poll_index; /* XXXX rename. */
623 struct event *read_event; /**< Libevent event structure. */
624 struct event *write_event; /**< Libevent event structure. */
625 buf_t *inbuf; /**< Buffer holding data read over this connection. */
626 int inbuf_reached_eof; /**< Boolean: did read() return 0 on this conn? */
627 time_t timestamp_lastread; /**< When was the last time poll() said we could
628 * read? */
630 buf_t *outbuf; /**< Buffer holding data to write over this connection. */
631 size_t outbuf_flushlen; /**< How much data should we try to flush from the
632 * outbuf? */
633 time_t timestamp_lastwritten; /**< When was the last time poll() said we
634 * could write? */
636 time_t timestamp_created; /**< When was this connection_t created? */
637 time_t timestamp_lastempty; /**< When was the outbuf last completely empty?*/
639 uint32_t addr; /**< IP of the other side of the connection; used to identify
640 * routers, along with port. */
641 uint16_t port; /**< If non-zero, port on the other end
642 * of the connection. */
643 uint16_t marked_for_close; /**< Should we close this conn on the next
644 * iteration of the main loop? (If true, holds
645 * the line number where this connection was
646 * marked.) */
647 const char *marked_for_close_file; /**< For debugging: in which file were
648 * we marked for close? */
649 char *address; /**< FQDN (or IP) of the guy on the other end.
650 * strdup into this, because free_connection frees it. */
651 uint32_t address_ttl; /**< TTL for address-to-addr mapping on exit
652 * connection. Exit connections only. */
653 char identity_digest[DIGEST_LEN]; /**< Hash of the public RSA key for
654 * the other side's signing key. */
655 char *nickname; /**< Nickname of OR on other side (if any). */
657 /** Nickname of planned exit node -- used with .exit support. */
658 char *chosen_exit_name;
660 /* Used only by OR connections: */
661 tor_tls_t *tls; /**< TLS connection state (OR only.) */
663 /* bandwidth* and receiver_bucket only used by ORs in OPEN state: */
664 int bandwidthrate; /**< Bytes/s added to the bucket. (OPEN ORs only.) */
665 int bandwidthburst; /**< Max bucket size for this conn. (OPEN ORs only.) */
666 int receiver_bucket; /**< When this hits 0, stop receiving. Every second we
667 * add 'bandwidthrate' to this, capping it at
668 * bandwidthburst. (OPEN ORs only) */
669 circ_id_type_t circ_id_type; /**< When we send CREATE cells along this
670 * connection, which half of the space should
671 * we use? */
672 int n_circuits; /**< How many circuits use this connection as p_conn or
673 * n_conn ? */
674 struct connection_t *next_with_same_id; /**< Next connection with same
675 * identity digest as this one. */
676 uint16_t next_circ_id; /**< Which circ_id do we try to use next on
677 * this connection? This is always in the
678 * range 0..1<<15-1. (OR only.)*/
680 /* Used only by edge connections: */
681 uint16_t stream_id;
682 struct connection_t *next_stream; /**< Points to the next stream at this
683 * edge, if any (Edge only). */
684 struct crypt_path_t *cpath_layer; /**< A pointer to which node in the circ
685 * this conn exits at. (Edge only.) */
686 int package_window; /**< How many more relay cells can i send into the
687 * circuit? (Edge only.) */
688 int deliver_window; /**< How many more relay cells can end at me? (Edge
689 * only.) */
691 /* Used only by Dir connections */
692 char *requested_resource; /**< Which 'resource' did we ask the directory
693 * for? */
694 unsigned int dirconn_direct:1; /**< Is this dirconn direct, or via Tor? */
695 /* Used only for server sides of some dir connections. */
696 enum {
697 DIR_SPOOL_NONE=0, DIR_SPOOL_SERVER_BY_DIGEST, DIR_SPOOL_SERVER_BY_FP,
698 DIR_SPOOL_CACHED_DIR, DIR_SPOOL_NETWORKSTATUS
699 } dir_spool_src;
700 smartlist_t *fingerprint_stack;
701 struct cached_dir_t *cached_dir;
702 off_t cached_dir_offset;
703 tor_zlib_state_t *zlib_state;
705 /* Used only by AP connections */
706 socks_request_t *socks_request; /**< SOCKS structure describing request (AP
707 * only.) */
709 /** Quasi-global identifier for this connection; used for control.c */
710 /* XXXX NM This can get re-used after 2**32 circuits. */
711 uint32_t global_identifier;
713 /* Used only by control connections */
714 uint32_t event_mask;
715 uint32_t incoming_cmd_len;
716 uint32_t incoming_cmd_cur_len;
717 char *incoming_cmd;
719 /* Used only by DIR and AP connections: */
720 struct circuit_t *on_circuit; /**< The circuit (if any) that this edge
721 * connection is using. */
722 char rend_query[REND_SERVICE_ID_LEN+1]; /**< What rendezvous service are we
723 * querying for? (DIR/AP only) */
725 /* Used only by control v0 connections */
726 uint16_t incoming_cmd_type;
729 typedef struct connection_t connection_t;
731 typedef enum {
732 ADDR_POLICY_ACCEPT=1,
733 ADDR_POLICY_REJECT=2,
734 } addr_policy_action_t;
736 /** A linked list of policy rules */
737 typedef struct addr_policy_t {
738 addr_policy_action_t policy_type; /**< What to do when the policy matches.*/
739 char *string; /**< String representation of this rule. */
740 uint32_t addr; /**< Base address to accept or reject. */
741 uint32_t msk; /**< Accept/reject all addresses <b>a</b> such that
742 * a &amp; msk == <b>addr</b> &amp; msk . */
743 uint16_t prt_min; /**< Lowest port number to accept/reject. */
744 uint16_t prt_max; /**< Highest port number to accept/reject. */
746 struct addr_policy_t *next; /**< Next rule in list. */
747 } addr_policy_t;
749 /** A cached_dir_t represents a cacheable directory object, along with its
750 * compressed form. */
751 typedef struct cached_dir_t {
752 char *dir; /**< Contents of this object */
753 char *dir_z; /**< Compressed contents of this object. */
754 size_t dir_len; /**< Length of <b>dir</b> */
755 size_t dir_z_len; /**< Length of <b>dir_z</b> */
756 time_t published; /**< When was this object published */
757 int refcnt; /**< Reference count for this cached_dir_t. */
758 } cached_dir_t;
760 typedef enum {
761 SAVED_NOWHERE=0, SAVED_IN_CACHE, SAVED_IN_JOURNAL
762 } saved_location_t;
764 /** Information need to cache an onion router's descriptor. */
765 typedef struct signed_descriptor_t {
766 char *signed_descriptor_body;
767 size_t signed_descriptor_len;
768 char signed_descriptor_digest[DIGEST_LEN];
769 char identity_digest[DIGEST_LEN];
770 time_t published_on;
771 saved_location_t saved_location;
772 off_t saved_offset;
773 } signed_descriptor_t;
775 /** Information about another onion router in the network. */
776 typedef struct {
777 signed_descriptor_t cache_info;
778 char *address; /**< Location of OR: either a hostname or an IP address. */
779 char *nickname; /**< Human-readable OR name. */
781 uint32_t addr; /**< IPv4 address of OR, in host order. */
782 uint16_t or_port; /**< Port for TLS connections. */
783 uint16_t dir_port; /**< Port for HTTP directory connections. */
785 crypto_pk_env_t *onion_pkey; /**< Public RSA key for onions. */
786 crypto_pk_env_t *identity_pkey; /**< Public RSA key for signing. */
788 char *platform; /**< What software/operating system is this OR using? */
790 /* link info */
791 uint32_t bandwidthrate; /**< How many bytes does this OR add to its token
792 * bucket per second? */
793 uint32_t bandwidthburst; /**< How large is this OR's token bucket? */
794 /** How many bytes/s is this router known to handle? */
795 uint32_t bandwidthcapacity;
796 addr_policy_t *exit_policy; /**< What streams will this OR permit
797 * to exit? */
798 long uptime; /**< How many seconds the router claims to have been up */
799 smartlist_t *declared_family; /**< Nicknames of router which this router
800 * claims are its family. */
801 char *contact_info; /**< Declared contact info for this router. */
802 unsigned int is_hibernating:1; /**< Whether the router claims to be
803 * hibernating */
805 /* local info */
806 unsigned int is_running:1; /**< As far as we know, is this OR currently
807 * running? */
808 unsigned int is_valid:1; /**< Has a trusted dirserver validated this OR?
809 * (For Authdir: Have we validated this OR?)
811 unsigned int is_named:1; /**< Do we believe the nickname that this OR gives
812 * us? */
813 unsigned int is_fast:1; /** Do we think this is a fast OR? */
814 unsigned int is_stable:1; /** Do we think this is a stable OR? */
815 unsigned int is_possible_guard:1; /**< Do we think this is an OK guard? */
817 /** Tor can use this desc for circuit-building. */
818 #define ROUTER_PURPOSE_GENERAL 0
819 /** Tor should avoid using this desc for circuit-building. */
820 #define ROUTER_PURPOSE_CONTROLLER 1
821 uint8_t purpose; /** Should Tor use this desc for circuit-building? */
823 /* The below items are used only by authdirservers for
824 * reachability testing. */
825 /** When was the last time we could reach this OR? */
826 time_t last_reachable;
827 /** When did we start testing reachability for this OR? */
828 time_t testing_since;
829 /** How many times has a descriptor been posted and we believed
830 * this router to be unreachable? We only actually warn on the third. */
831 int num_unreachable_notifications;
832 } routerinfo_t;
834 /** Contents of a single router entry in a network status object.
836 typedef struct routerstatus_t {
837 time_t published_on; /**< When was this router published? */
838 char nickname[MAX_NICKNAME_LEN+1]; /**< The nickname this router says it
839 * has. */
840 char identity_digest[DIGEST_LEN]; /**< Digest of the router's identity
841 * key. */
842 char descriptor_digest[DIGEST_LEN]; /**< Digest of the router's most recent
843 * descriptor. */
844 uint32_t addr; /**< IPv4 address for this router. */
845 uint16_t or_port; /**< OR port for this router. */
846 uint16_t dir_port; /**< Directory port for this router. */
847 unsigned int is_exit:1; /**< True iff this router is a good exit. */
848 unsigned int is_stable:1; /**< True iff this router stays up a long time. */
849 unsigned int is_fast:1; /**< True iff this router has good bandwidth. */
850 unsigned int is_running:1; /**< True iff this router is up. */
851 unsigned int is_named:1; /**< True iff "nickname" belongs to this router. */
852 unsigned int is_valid:1; /**< True iff this router is validated. */
853 unsigned int is_v2_dir:1; /**< True iff this router can serve directory
854 * information with v2 of the directory
855 * protocol. (All directory caches cache v1
856 * directories.) */
857 unsigned int is_possible_guard:1; /**< True iff this router would be a good
858 * choice as an entry guard. */
860 /** True if we, as a directory mirror, want to download the corresponding
861 * routerinfo from the authority who gave us this routerstatus. (That is,
862 * if we don't have the routerinfo, and if we haven't already tried to get it
863 * from this authority.)
865 unsigned int need_to_mirror:1;
866 } routerstatus_t;
868 /** Our "local" or combined view of the info from all networkstatus objects
869 * about a single router. */
870 typedef struct local_routerstatus_t {
871 /** What do we believe to be the case about this router? In this field,
872 * descriptor_digest represents the descriptor we would most like to use for
873 * this router. */
874 routerstatus_t status;
875 time_t next_attempt_at; /**< When should we try this descriptor again? */
876 uint8_t n_download_failures; /**< Number of failures trying to download the
877 * most recent descriptor. */
878 unsigned int name_lookup_warned:1; /**< Have we warned the user for referring
879 * to this (unnamed) router by nickname?
881 } local_routerstatus_t;
883 /** How many times will we try to download a router's descriptor before giving
884 * up? */
885 #define MAX_ROUTERDESC_DOWNLOAD_FAILURES 8
887 /** Contents of a (v2 or later) network status object. */
888 typedef struct networkstatus_t {
889 /** When did we receive the network-status document? */
890 time_t received_on;
892 /** What was the digest of the document? */
893 char networkstatus_digest[DIGEST_LEN];
895 unsigned int is_recent; /**< Is this recent enough to influence running
896 * status? */
898 /* These fields come from the actual network-status document.*/
899 time_t published_on; /**< Declared publication date. */
901 char *source_address; /**< Canonical directory server hostname. */
902 uint32_t source_addr; /**< Canonical directory server IP. */
903 uint16_t source_dirport; /**< Canonical directory server dirport. */
905 char identity_digest[DIGEST_LEN]; /**< Digest of signing key. */
906 char *contact; /**< How to contact directory admin? (may be NULL). */
907 crypto_pk_env_t *signing_key; /**< Key used to sign this directory. */
908 char *client_versions; /**< comma-separated list of recommended client
909 * versions. */
910 char *server_versions; /**< comma-separated list of recommended server
911 * versions. */
913 unsigned int binds_names:1; /**< True iff this directory server binds
914 * names. */
915 unsigned int recommends_versions:1; /**< True iff this directory server
916 * recommends client and server software
917 * versions. */
919 smartlist_t *entries; /**< List of routerstatus_t*. This list is kept
920 * sorted by identity_digest. */
921 } networkstatus_t;
923 /** Contents of a directory of onion routers. */
924 typedef struct {
925 /** Map from server identity digest to a member of routers. */
926 digestmap_t *identity_map;
927 /** Map from server descriptor digest to a signed_descriptor_t from
928 * routers or old_routers. */
929 digestmap_t *desc_digest_map;
930 /** List of routerinfo_t for all currently live routers we know. */
931 smartlist_t *routers;
932 /** List of signed_descriptor_t for older router descriptors we're
933 * caching. */
934 smartlist_t *old_routers;
935 /** DOCDOC */
936 const char *mmap_descriptors;
937 size_t mmap_descriptors_len;
938 } routerlist_t;
940 /** Information on router used when extending a circuit. (We don't need a
941 * full routerinfo_t to extend: we only need addr:port:keyid to build an OR
942 * connection, and onion_key to create the onionskin.) */
943 typedef struct extend_info_t {
944 char nickname[MAX_HEX_NICKNAME_LEN+1]; /**< This router's nickname for
945 * display. */
946 char identity_digest[DIGEST_LEN]; /**< Hash of this router's identity key. */
947 uint32_t addr; /**< IP address in host order. */
948 uint16_t port; /**< OR port. */
949 crypto_pk_env_t *onion_key; /**< Current onionskin key. */
950 } extend_info_t;
952 #define CRYPT_PATH_MAGIC 0x70127012u
954 /** Holds accounting information for a single step in the layered encryption
955 * performed by a circuit. Used only at the client edge of a circuit. */
956 typedef struct crypt_path_t {
957 uint32_t magic;
959 /* crypto environments */
960 /** Encryption key and counter for cells heading towards the OR at this
961 * step. */
962 crypto_cipher_env_t *f_crypto;
963 /** Encryption key and counter for cells heading back from the OR at this
964 * step. */
965 crypto_cipher_env_t *b_crypto;
967 /** Digest state for cells heading towards the OR at this step. */
968 crypto_digest_env_t *f_digest; /* for integrity checking */
969 /** Digest state for cells heading away from the OR at this step. */
970 crypto_digest_env_t *b_digest;
972 /** Current state of Diffie-Hellman key negotiation with the OR at this
973 * step. */
974 crypto_dh_env_t *dh_handshake_state;
975 /** Current state of 'fast' (non-PK) key negotiation with the OR at this
976 * step. Used to save CPU when TLS is already providing all the
977 * authentication, secrecy, and integrity we need, and we're already
978 * distinguishable from an OR.
980 char fast_handshake_state[DIGEST_LEN];
981 /** Negotiated key material shared with the OR at this step. */
982 char handshake_digest[DIGEST_LEN];/* KH in tor-spec.txt */
984 /** Information to extend to the OR at this step. */
985 extend_info_t *extend_info;
987 /** Is the circuit built to this step? Must be one of:
988 * - CPATH_STATE_CLOSED (The circuit has not been extended to this step)
989 * - CPATH_STATE_AWAITING_KEYS (We have sent an EXTEND/CREATE to this step
990 * and not received an EXTENDED/CREATED)
991 * - CPATH_STATE_OPEN (The circuit has been extended to this step) */
992 uint8_t state;
993 #define CPATH_STATE_CLOSED 0
994 #define CPATH_STATE_AWAITING_KEYS 1
995 #define CPATH_STATE_OPEN 2
996 struct crypt_path_t *next; /**< Link to next crypt_path_t in the circuit.
997 * (The list is circular, so the last node
998 * links to the first.) */
999 struct crypt_path_t *prev; /**< Link to previous crypt_path_t in the
1000 * circuit. */
1002 int package_window; /**< How many bytes are we allowed to originate ending
1003 * at this step? */
1004 int deliver_window; /**< How many bytes are we willing to deliver originating
1005 * at this step? */
1006 } crypt_path_t;
1008 #define CPATH_KEY_MATERIAL_LEN (20*2+16*2)
1010 #define DH_KEY_LEN DH_BYTES
1011 #define ONIONSKIN_CHALLENGE_LEN (PKCS1_OAEP_PADDING_OVERHEAD+\
1012 CIPHER_KEY_LEN+\
1013 DH_KEY_LEN)
1014 #define ONIONSKIN_REPLY_LEN (DH_KEY_LEN+DIGEST_LEN)
1015 #define REND_COOKIE_LEN DIGEST_LEN
1017 /** Information used to build a circuit. */
1018 typedef struct {
1019 /** Intended length of the final circuit. */
1020 int desired_path_len;
1021 /** How to extend to the planned exit node. */
1022 extend_info_t *chosen_exit;
1023 /** Whether every node in the circ must have adequate uptime. */
1024 int need_uptime;
1025 /** Whether every node in the circ must have adequate capacity. */
1026 int need_capacity;
1027 /** Whether the last hop was picked with exiting in mind. */
1028 int is_internal;
1029 /** The crypt_path_t to append after rendezvous: used for rendezvous. */
1030 crypt_path_t *pending_final_cpath;
1031 /** How many times has building a circuit for this task failed? */
1032 int failure_count;
1033 /** At what time should we give up on this task? */
1034 time_t expiry_time;
1035 } cpath_build_state_t;
1037 #define CIRCUIT_MAGIC 0x35315243u
1040 * A circuit is a path over the onion routing
1041 * network. Applications can connect to one end of the circuit, and can
1042 * create exit connections at the other end of the circuit. AP and exit
1043 * connections have only one circuit associated with them (and thus these
1044 * connection types are closed when the circuit is closed), whereas
1045 * OR connections multiplex many circuits at once, and stay standing even
1046 * when there are no circuits running over them.
1048 * A circuit_t structure fills two roles. First, a circuit_t links two
1049 * connections together: either an edge connection and an OR connection,
1050 * or two OR connections. (When joined to an OR connection, a circuit_t
1051 * affects only cells sent to a particular circID on that connection. When
1052 * joined to an edge connection, a circuit_t affects all data.)
1054 * Second, a circuit_t holds the cipher keys and state for sending data
1055 * along a given circuit. At the OP, it has a sequence of ciphers, each
1056 * of which is shared with a single OR along the circuit. Separate
1057 * ciphers are used for data going "forward" (away from the OP) and
1058 * "backward" (towards the OP). At the OR, a circuit has only two stream
1059 * ciphers: one for data going forward, and one for data going backward.
1061 struct circuit_t {
1062 uint32_t magic; /**< For memory debugging: must equal CIRCUIT_MAGIC. */
1064 /** The OR connection that is previous in this circuit. */
1065 connection_t *p_conn;
1066 /** The OR connection that is next in this circuit. */
1067 connection_t *n_conn;
1068 /** The identity hash of n_conn. */
1069 char n_conn_id_digest[DIGEST_LEN];
1070 /** Linked list of AP streams associated with this circuit. */
1071 connection_t *p_streams;
1072 /** Linked list of Exit streams associated with this circuit. */
1073 connection_t *n_streams;
1074 /** Linked list of Exit streams associated with this circuit that are
1075 * still being resolved. */
1076 connection_t *resolving_streams;
1077 /** The IPv4 address of the OR that is next in this circuit. */
1078 uint32_t n_addr;
1079 /** The port for the OR that is next in this circuit. */
1080 uint16_t n_port;
1081 /** The next stream_id that will be tried when we're attempting to
1082 * construct a new AP stream originating at this circuit. */
1083 uint16_t next_stream_id;
1084 /** How many relay data cells can we package (read from edge streams)
1085 * on this circuit before we receive a circuit-level sendme cell asking
1086 * for more? */
1087 int package_window;
1088 /** How many relay data cells will we deliver (write to edge streams)
1089 * on this circuit? When deliver_window gets low, we send some
1090 * circuit-level sendme cells to indicate that we're willing to accept
1091 * more. */
1092 int deliver_window;
1094 /** The circuit_id used in the previous (backward) hop of this circuit. */
1095 uint16_t p_circ_id;
1096 /** The circuit_id used in the next (forward) hop of this circuit. */
1097 uint16_t n_circ_id;
1099 /** The cipher used by intermediate hops for cells heading toward the
1100 * OP. */
1101 crypto_cipher_env_t *p_crypto;
1102 /** The cipher used by intermediate hops for cells heading away from
1103 * the OP. */
1104 crypto_cipher_env_t *n_crypto;
1106 /** The integrity-checking digest used by intermediate hops, for
1107 * cells packaged here and heading towards the OP.
1109 crypto_digest_env_t *p_digest;
1110 /** The integrity-checking digest used by intermediate hops, for
1111 * cells packaged at the OP and arriving here.
1113 crypto_digest_env_t *n_digest;
1115 /** Build state for this circuit. It includes the intended path
1116 * length, the chosen exit router, rendezvous information, etc.
1118 cpath_build_state_t *build_state;
1119 /** The doubly-linked list of crypt_path_t entries, one per hop,
1120 * for this circuit. This includes ciphers for each hop,
1121 * integrity-checking digests for each hop, and package/delivery
1122 * windows for each hop.
1124 * The cpath field is defined only when we are the circuit's origin.
1126 crypt_path_t *cpath;
1128 /** For storage while passing to cpuworker (state
1129 * CIRCUIT_STATE_ONIONSKIN_PENDING), or while n_conn is pending
1130 * (state CIRCUIT_STATE_OR_WAIT). When defined, it is always
1131 * length ONIONSKIN_CHALLENGE_LEN. */
1132 char *onionskin;
1134 char handshake_digest[DIGEST_LEN]; /**< Stores KH for intermediate hops. */
1136 time_t timestamp_created; /**< When was this circuit created? */
1137 time_t timestamp_dirty; /**< When the circuit was first used, or 0 if the
1138 * circuit is clean. */
1140 uint8_t state; /**< Current status of this circuit. */
1141 uint8_t purpose; /**< Why are we creating this circuit? */
1143 uint16_t marked_for_close; /**< Should we close this circuit at the end of
1144 * the main loop? (If true, holds the line number
1145 * where this circuit was marked.) */
1146 const char *marked_for_close_file; /**< For debugging: in which file was this
1147 * circuit marked for close? */
1150 * The rend_query field holds the y portion of y.onion (nul-terminated)
1151 * if purpose is C_INTRODUCING or C_ESTABLISH_REND, or is a C_GENERAL
1152 * for a hidden service, or is S_*.
1154 char rend_query[REND_SERVICE_ID_LEN+1];
1156 /** The rend_pk_digest field holds a hash of location-hidden service's
1157 * PK if purpose is INTRO_POINT or S_ESTABLISH_INTRO or S_RENDEZVOUSING.
1159 char rend_pk_digest[DIGEST_LEN];
1161 /** Holds rendezvous cookie if purpose is REND_POINT_WAITING or
1162 * C_ESTABLISH_REND. Filled with zeroes otherwise.
1164 char rend_cookie[REND_COOKIE_LEN];
1166 /** Points to spliced circuit if purpose is REND_ESTABLISHED, and circuit
1167 * is not marked for close. */
1168 struct circuit_t *rend_splice;
1170 /** Quasi-global identifier for this circuit; used for control.c */
1171 /* XXXX NM This can get re-used after 2**32 circuits. */
1172 uint32_t global_identifier;
1174 struct circuit_t *next; /**< Next circuit in linked list. */
1177 typedef struct circuit_t circuit_t;
1179 #define ALLOW_INVALID_ENTRY 1
1180 #define ALLOW_INVALID_EXIT 2
1181 #define ALLOW_INVALID_MIDDLE 4
1182 #define ALLOW_INVALID_RENDEZVOUS 8
1183 #define ALLOW_INVALID_INTRODUCTION 16
1185 /** An entry specifying a set of addresses and ports that should be remapped
1186 * to another address and port before exiting this exit node. */
1187 typedef struct exit_redirect_t {
1188 uint32_t addr;
1189 uint32_t mask;
1190 uint16_t port_min;
1191 uint16_t port_max;
1193 uint32_t addr_dest;
1194 uint16_t port_dest;
1195 unsigned is_redirect:1;
1196 } exit_redirect_t;
1198 /** A linked list of lines in a config file. */
1199 typedef struct config_line_t {
1200 char *key;
1201 char *value;
1202 struct config_line_t *next;
1203 } config_line_t;
1205 /** Configuration options for a Tor process. */
1206 typedef struct {
1207 uint32_t _magic;
1209 /** What should the tor process actually do? */
1210 enum {
1211 CMD_RUN_TOR=0, CMD_LIST_FINGERPRINT, CMD_HASH_PASSWORD,
1212 CMD_VERIFY_CONFIG, CMD_RUN_UNITTESTS
1213 } command;
1214 const char *command_arg; /**< Argument for command-line option. */
1216 config_line_t *OldLogOptions; /**< List of configuration lines
1217 * for logfiles, old style. */
1219 config_line_t *Logs; /**< New-style list of configuration lines
1220 * for logs */
1222 char *DebugLogFile; /**< Where to send verbose log messages. */
1223 char *DataDirectory; /**< OR only: where to store long-term data. */
1224 char *Nickname; /**< OR only: nickname of this onion router. */
1225 char *Address; /**< OR only: configured address for this onion router. */
1226 char *PidFile; /**< Where to store PID of Tor process. */
1228 char *ExitNodes; /**< Comma-separated list of nicknames of ORs to consider
1229 * as exits. */
1230 char *EntryNodes; /**< Comma-separated list of nicknames of ORs to consider
1231 * as entry points. */
1232 int StrictExitNodes; /**< Boolean: When none of our ExitNodes are up, do we
1233 * stop building circuits? */
1234 int StrictEntryNodes; /**< Boolean: When none of our EntryNodes are up, do we
1235 * stop building circuits? */
1236 char *ExcludeNodes; /**< Comma-separated list of nicknames of ORs not to
1237 * use in circuits. */
1239 char *RendNodes; /**< Comma-separated list of nicknames used as introduction
1240 * points. */
1241 char *RendExcludeNodes; /**< Comma-separated list of nicknames not to use
1242 * as introduction points. */
1244 smartlist_t *AllowInvalidNodes; /**< List of "entry", "middle", "exit" */
1245 int _AllowInvalid; /**< Bitmask; derived from AllowInvalidNodes; */
1246 config_line_t *ExitPolicy; /**< Lists of exit policy components. */
1247 int ExitPolicyRejectPrivate; /**< Should we not exit to local addresses? */
1248 config_line_t *SocksPolicy; /**< Lists of socks policy components */
1249 config_line_t *DirPolicy; /**< Lists of dir policy components */
1250 /** Addresses to bind for listening for SOCKS connections. */
1251 config_line_t *SocksListenAddress;
1252 /** Addresses to bind for listening for OR connections. */
1253 config_line_t *ORListenAddress;
1254 /** Addresses to bind for listening for directory connections. */
1255 config_line_t *DirListenAddress;
1256 /** Addresses to bind for listening for control connections. */
1257 config_line_t *ControlListenAddress;
1258 /** Local address to bind outbound sockets */
1259 char *OutboundBindAddress;
1260 /** Directory server only: which versions of
1261 * Tor should we tell users to run? */
1262 config_line_t *RecommendedVersions;
1263 config_line_t *RecommendedClientVersions;
1264 config_line_t *RecommendedServerVersions;
1265 /** Whether dirservers refuse router descriptors with private IPs. */
1266 int DirAllowPrivateAddresses;
1267 char *User; /**< Name of user to run Tor as. */
1268 char *Group; /**< Name of group to run Tor as. */
1269 double PathlenCoinWeight; /**< Parameter used to configure average path
1270 * length (alpha in geometric distribution). */
1271 int ORPort; /**< Port to listen on for OR connections. */
1272 int SocksPort; /**< Port to listen on for SOCKS connections. */
1273 int ControlPort; /**< Port to listen on for control connections. */
1274 int DirPort; /**< Port to listen on for directory connections. */
1275 int AssumeReachable; /**< Whether to publish our descriptor regardless. */
1276 int AuthoritativeDir; /**< Boolean: is this an authoritative directory? */
1277 int V1AuthoritativeDir; /**< Boolean: is this an authoritative directory?
1278 * for version 1 directories? */
1279 int NamingAuthoritativeDir; /**< Boolean: is this an authoritative directory
1280 * that's willing to bind names? */
1281 int VersioningAuthoritativeDir; /**< Boolean: is this an authoritative
1282 * directory that's willing to recommend
1283 * versions? */
1284 int ClientOnly; /**< Boolean: should we never evolve into a server role? */
1285 int NoPublish; /**< Boolean: should we never publish a descriptor? */
1286 int PublishServerDescriptor; /**< Do we publish our descriptor as normal? */
1287 int PublishHidServDescriptors; /**< and our hidden service descriptors? */
1288 int FetchServerDescriptors; /**< Do we fetch server descriptors as normal? */
1289 int FetchHidServDescriptors; /** and hidden service descriptors? */
1290 int FetchUselessDescriptors; /**< Do we fetch non-running descriptors too? */
1291 int AllDirActionsPrivate; /**< Should every directory action be sent
1292 * through a Tor circuit? */
1294 int ConnLimit; /**< Demanded minimum number of simultaneous connections. */
1295 int _ConnLimit; /**< Maximum allowed number of simultaneous connections. */
1296 int RunAsDaemon; /**< If true, run in the background. (Unix only) */
1297 int FascistFirewall; /**< Whether to prefer ORs reachable on open ports. */
1298 smartlist_t *FirewallPorts; /**< Which ports our firewall allows
1299 * (strings). */
1300 config_line_t *ReachableAddresses; /**< IP:ports our firewall allows. */
1301 config_line_t *ReachableORAddresses; /**< IP:ports for OR conns. */
1302 config_line_t *ReachableDirAddresses; /**< IP:ports for Dir conns. */
1304 /** Application ports that require all nodes in circ to have sufficient
1305 * uptime. */
1306 smartlist_t *LongLivedPorts;
1307 /** Should we try to reuse the same exit node for a given host */
1308 smartlist_t *TrackHostExits;
1309 int TrackHostExitsExpire; /**< Number of seconds until we expire an
1310 * addressmap */
1311 config_line_t *AddressMap; /**< List of address map directives. */
1312 int RendPostPeriod; /**< How often do we post each rendezvous service
1313 * descriptor? Remember to publish them independently. */
1314 int KeepalivePeriod; /**< How often do we send padding cells to keep
1315 * connections alive? */
1316 int SocksTimeout; /**< How long do we let a socks connection wait
1317 * unattached before we fail it? */
1318 int CircuitBuildTimeout; /**< Cull non-open circuits that were born
1319 * at least this many seconds ago. */
1320 int CircuitIdleTimeout; /**< Cull open clean circuits that were born
1321 * at least this many seconds ago. */
1322 int MaxOnionsPending; /**< How many circuit CREATE requests do we allow
1323 * to wait simultaneously before we start dropping
1324 * them? */
1325 int NewCircuitPeriod; /**< How long do we use a circuit before building
1326 * a new one? */
1327 int MaxCircuitDirtiness; /**< Never use circs that were first used more than
1328 this interval ago. */
1329 uint64_t BandwidthRate; /**< How much bandwidth, on average, are we willing
1330 * to use in a second? */
1331 uint64_t BandwidthBurst; /**< How much bandwidth, at maximum, are we willing
1332 * to use in a second? */
1333 uint64_t MaxAdvertisedBandwidth; /**< How much bandwidth are we willing to
1334 * tell people we have? */
1335 uint64_t RelayBandwidthRate; /**< How much bandwidth, on average, are we
1336 * willing to use for all relayed conns? */
1337 uint64_t RelayBandwidthBurst; /**< How much bandwidth, at maximum, will we
1338 * use in a second for all relayed conns? */
1339 int NumCpus; /**< How many CPUs should we try to use? */
1340 int RunTesting; /**< If true, create testing circuits to measure how well the
1341 * other ORs are running. */
1342 char *TestVia; /**< When reachability testing, use these as middle hop. */
1343 config_line_t *RendConfigLines; /**< List of configuration lines
1344 * for rendezvous services. */
1345 char *ContactInfo; /**< Contact info to be published in the directory */
1347 char *HttpProxy; /**< hostname[:port] to use as http proxy, if any */
1348 uint32_t HttpProxyAddr; /**< Parsed IPv4 addr for http proxy, if any */
1349 uint16_t HttpProxyPort; /**< Parsed port for http proxy, if any */
1350 char *HttpProxyAuthenticator; /**< username:password string, if any */
1352 char *HttpsProxy; /**< hostname[:port] to use as https proxy, if any */
1353 uint32_t HttpsProxyAddr; /**< Parsed IPv4 addr for https proxy, if any */
1354 uint16_t HttpsProxyPort; /**< Parsed port for https proxy, if any */
1355 char *HttpsProxyAuthenticator; /**< username:password string, if any */
1357 config_line_t *DirServers; /**< List of configuration lines
1358 * for directory servers. */
1359 char *MyFamily; /**< Declared family for this OR. */
1360 config_line_t *NodeFamilies; /**< List of config lines for
1361 * node families */
1362 config_line_t *RedirectExit; /**< List of config lines for simple
1363 * addr/port redirection */
1364 smartlist_t *RedirectExitList; /**< List of exit_redirect_t */
1365 config_line_t *AuthDirReject; /**< Address policy for descriptors to
1366 * reject. */
1367 config_line_t *AuthDirInvalid; /**< Address policy for descriptors to
1368 * never mark as valid. */
1369 int AuthDirRejectUnlisted; /**< Boolean: do we reject all routers that
1370 * aren't named in our fingerprint file? */
1371 char *AccountingStart; /**< How long is the accounting interval, and when
1372 * does it start? */
1373 uint64_t AccountingMax; /**< How many bytes do we allow per accounting
1374 * interval before hibernation? 0 for "never
1375 * hibernate." */
1376 int _AccountingMaxKB; /**< How many KB do we allow per accounting
1377 * interval before hibernation? 0 for "never
1378 * hibernate." (Based on a deprecated option)*/
1380 char *HashedControlPassword; /**< Base64-encoded hash of a password for
1381 * the control system. */
1382 int CookieAuthentication; /**< Boolean: do we enable cookie-based auth for
1383 * the control system? */
1384 int LeaveStreamsUnattached; /**< Boolean: Does Tor attach new streams to
1385 * circuits itself (0), or does it expect a controller
1386 * to cope? (1) */
1387 int ShutdownWaitLength; /**< When we get a SIGINT and we're a server, how
1388 * long do we wait before exiting? */
1389 int SafeLogging; /**< Boolean: are we allowed to log sensitive strings
1390 * such as addresses (0), or do we scrub them first (1)? */
1391 int SafeSocks; /**< Boolean: should we outright refuse application
1392 * connections that use socks4 or socks5-with-local-dns? */
1393 #define LOG_PROTOCOL_WARN (get_options()->ProtocolWarnings ? \
1394 LOG_WARN : LOG_INFO)
1395 int ProtocolWarnings; /**< Boolean: when other parties screw up the Tor
1396 * protocol, is it a warn or an info in our logs? */
1397 int TestSocks; /**< Boolean: when we get a socks connection, do we loudly
1398 * log whether it was DNS-leaking or not? */
1399 int HardwareAccel; /**< Boolean: Should we enable OpenSSL hardware
1400 * acceleration where available? */
1401 int UseEntryGuards; /**< Boolean: Do we try to enter from a smallish number
1402 * of fixed nodes? */
1403 int NumEntryGuards; /**< How many entry guards do we try to establish? */
1404 int RephistTrackTime; /**< How many seconds do we keep rephist info? */
1405 int FastFirstHopPK; /**< If Tor believes it is safe, should we save a third
1406 * of our PK time by sending CREATE_FAST cells? */
1408 addr_policy_t *reachable_addr_policy; /**< Parsed from ReachableAddresses */
1410 char *VirtualAddrNetwork; /**< Address and mask to hand out for virtual
1411 * MAPADDRESS requests. */
1412 smartlist_t *Nameservers; /**< If provided, overrides the platform nameserver
1413 * list. when using eventdns. */
1414 } or_options_t;
1416 /** Persistent state for an onion router, as saved to disk. */
1417 typedef struct {
1418 uint32_t _magic;
1419 int dirty;
1421 /* XXXX These options aren't actually attached to anything yet. */
1422 time_t LastWritten;
1423 time_t AccountingIntervalStart;
1424 uint64_t AccountingBytesReadInInterval;
1425 uint64_t AccountingBytesWrittenInInterval;
1426 int AccountingSecondsActive;
1427 uint64_t AccountingExpectedUsage;
1429 config_line_t *EntryGuards;
1431 time_t BWHistoryReadEnds;
1432 int BWHistoryReadInterval;
1433 smartlist_t *BWHistoryReadValues;
1434 time_t BWHistoryWriteEnds;
1435 int BWHistoryWriteInterval;
1436 smartlist_t *BWHistoryWriteValues;
1438 char *TorVersion;
1440 config_line_t *ExtraLines;
1441 } or_state_t;
1443 #define MAX_SOCKS_REPLY_LEN 1024
1444 #define MAX_SOCKS_ADDR_LEN 256
1445 #define SOCKS_COMMAND_CONNECT 0x01
1446 #define SOCKS_COMMAND_RESOLVE 0xF0
1447 /** State of a SOCKS request from a user to an OP */
1448 struct socks_request_t {
1449 char socks_version; /**< Which version of SOCKS did the client use? */
1450 int command; /**< What has the user requested? One of CONNECT or RESOLVE. */
1451 size_t replylen; /**< Length of <b>reply</b>. */
1452 char reply[MAX_SOCKS_REPLY_LEN]; /**< Write an entry into this string if
1453 * we want to specify our own socks reply,
1454 * rather than using the default socks4 or
1455 * socks5 socks reply. We use this for the
1456 * two-stage socks5 handshake.
1458 int has_finished; /**< Has the SOCKS handshake finished? */
1459 char address[MAX_SOCKS_ADDR_LEN]; /**< What address did the client ask to
1460 connect to? */
1461 uint16_t port; /**< What port did the client ask to connect to? */
1464 /* all the function prototypes go here */
1466 /********************************* buffers.c ***************************/
1468 buf_t *buf_new(void);
1469 buf_t *buf_new_with_capacity(size_t size);
1470 void buf_free(buf_t *buf);
1471 void buf_clear(buf_t *buf);
1472 void buf_shrink(buf_t *buf);
1474 size_t buf_datalen(const buf_t *buf);
1475 size_t buf_capacity(const buf_t *buf);
1476 const char *_buf_peek_raw_buffer(const buf_t *buf);
1478 int read_to_buf(int s, size_t at_most, buf_t *buf, int *reached_eof);
1479 int read_to_buf_tls(tor_tls_t *tls, size_t at_most, buf_t *buf);
1481 int flush_buf(int s, buf_t *buf, size_t sz, size_t *buf_flushlen);
1482 int flush_buf_tls(tor_tls_t *tls, buf_t *buf, size_t sz, size_t *buf_flushlen);
1484 int write_to_buf(const char *string, size_t string_len, buf_t *buf);
1485 int write_to_buf_zlib(buf_t *buf, tor_zlib_state_t *state,
1486 const char *data, size_t data_len, int done);
1487 int fetch_from_buf(char *string, size_t string_len, buf_t *buf);
1488 int fetch_from_buf_http(buf_t *buf,
1489 char **headers_out, size_t max_headerlen,
1490 char **body_out, size_t *body_used, size_t max_bodylen,
1491 int force_complete);
1492 int fetch_from_buf_socks(buf_t *buf, socks_request_t *req,
1493 int log_sockstype, int safe_socks);
1494 int fetch_from_buf_control0(buf_t *buf, uint32_t *len_out, uint16_t *type_out,
1495 char **body_out, int check_for_v1);
1496 int fetch_from_buf_line(buf_t *buf, char *data_out, size_t *data_len);
1498 void assert_buf_ok(buf_t *buf);
1500 /********************************* circuitbuild.c **********************/
1502 char *circuit_list_path(circuit_t *circ, int verbose);
1503 void circuit_log_path(int severity, unsigned int domain, circuit_t *circ);
1504 void circuit_rep_hist_note_result(circuit_t *circ);
1505 void circuit_dump_by_conn(connection_t *conn, int severity);
1506 circuit_t *circuit_init(uint8_t purpose, int need_uptime,
1507 int need_capacity, int internal);
1508 circuit_t *circuit_establish_circuit(uint8_t purpose, extend_info_t *exit,
1509 int need_uptime, int need_capacity,
1510 int internal);
1511 int circuit_handle_first_hop(circuit_t *circ);
1512 void circuit_n_conn_done(connection_t *or_conn, int status);
1513 int inform_testing_reachability(void);
1514 int circuit_send_next_onion_skin(circuit_t *circ);
1515 void circuit_note_clock_jumped(int seconds_elapsed);
1516 int circuit_extend(cell_t *cell, circuit_t *circ);
1517 int circuit_init_cpath_crypto(crypt_path_t *cpath, char *key_data,
1518 int reverse);
1519 int circuit_finish_handshake(circuit_t *circ, uint8_t cell_type, char *reply);
1520 int circuit_truncated(circuit_t *circ, crypt_path_t *layer);
1521 int onionskin_answer(circuit_t *circ, uint8_t cell_type, char *payload,
1522 char *keys);
1523 int circuit_all_predicted_ports_handled(time_t now, int *need_uptime,
1524 int *need_capacity);
1526 int circuit_append_new_exit(circuit_t *circ, extend_info_t *info);
1527 int circuit_extend_to_new_exit(circuit_t *circ, extend_info_t *info);
1528 void onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop);
1529 extend_info_t *extend_info_from_router(routerinfo_t *r);
1530 extend_info_t *extend_info_dup(extend_info_t *info);
1531 void extend_info_free(extend_info_t *info);
1532 routerinfo_t *build_state_get_exit_router(cpath_build_state_t *state);
1533 const char *build_state_get_exit_nickname(cpath_build_state_t *state);
1535 void entry_guards_set_status_from_directory(void);
1536 int entry_guard_set_status(const char *digest, int succeeded);
1537 void entry_nodes_should_be_added(void);
1538 void entry_guards_prepend_from_config(void);
1539 void entry_guards_update_state(or_state_t *state);
1540 int entry_guards_parse_state(or_state_t *state, int set, char **msg);
1541 int entry_guards_getinfo(const char *question, char **answer);
1542 void entry_guards_free_all(void);
1544 /********************************* circuitlist.c ***********************/
1546 circuit_t * _circuit_get_global_list(void);
1547 const char *circuit_state_to_string(int state);
1548 enum which_conn_changed_t { P_CONN_CHANGED=1, N_CONN_CHANGED=0 };
1549 void circuit_set_circid_orconn(circuit_t *circ, uint16_t id,
1550 connection_t *conn,
1551 enum which_conn_changed_t which);
1552 void circuit_set_state(circuit_t *circ, int state);
1553 void circuit_close_all_marked(void);
1554 circuit_t *circuit_new(uint16_t p_circ_id, connection_t *p_conn);
1555 circuit_t *circuit_get_by_circid_orconn(uint16_t circ_id, connection_t *conn);
1556 int circuit_id_used_on_conn(uint16_t circ_id, connection_t *conn);
1557 circuit_t *circuit_get_by_edge_conn(connection_t *conn);
1558 void circuit_unlink_all_from_or_conn(connection_t *conn, int reason);
1559 circuit_t *circuit_get_by_global_id(uint32_t id);
1560 circuit_t *circuit_get_by_rend_query_and_purpose(const char *rend_query,
1561 uint8_t purpose);
1562 circuit_t *circuit_get_next_by_pk_and_purpose(circuit_t *start,
1563 const char *digest, uint8_t purpose);
1564 circuit_t *circuit_get_rendezvous(const char *cookie);
1565 circuit_t *circuit_find_to_cannibalize(uint8_t purpose, extend_info_t *info,
1566 int need_uptime,
1567 int need_capacity, int internal);
1568 void circuit_mark_all_unused_circs(void);
1569 void circuit_expire_all_dirty_circs(void);
1570 void _circuit_mark_for_close(circuit_t *circ, int reason,
1571 int line, const char *file);
1573 #define circuit_mark_for_close(c, reason) \
1574 _circuit_mark_for_close((c), (reason), __LINE__, _SHORT_FILE_)
1576 void assert_cpath_layer_ok(const crypt_path_t *cp);
1577 void assert_circuit_ok(const circuit_t *c);
1578 void circuit_free_all(void);
1580 /********************************* circuituse.c ************************/
1582 void circuit_expire_building(time_t now);
1583 void circuit_remove_handled_ports(smartlist_t *needed_ports);
1584 int circuit_stream_is_being_handled(connection_t *conn, uint16_t port,
1585 int min);
1586 void circuit_build_needed_circs(time_t now);
1587 void circuit_detach_stream(circuit_t *circ, connection_t *conn);
1588 void circuit_about_to_close_connection(connection_t *conn);
1589 void circuit_has_opened(circuit_t *circ);
1590 void circuit_build_failed(circuit_t *circ);
1591 circuit_t *circuit_launch_by_nickname(uint8_t purpose,
1592 const char *exit_nickname,
1593 int need_uptime, int need_capacity,
1594 int is_internal);
1595 circuit_t *circuit_launch_by_extend_info(uint8_t purpose,
1596 extend_info_t *info,
1597 int need_uptime, int need_capacity,
1598 int is_internal);
1599 circuit_t *circuit_launch_by_router(uint8_t purpose, routerinfo_t *exit,
1600 int need_uptime, int need_capacity,
1601 int is_internal);
1602 void circuit_reset_failure_count(int timeout);
1603 int connection_ap_handshake_attach_chosen_circuit(connection_t *conn,
1604 circuit_t *circ);
1605 int connection_ap_handshake_attach_circuit(connection_t *conn);
1607 /********************************* command.c ***************************/
1609 void command_process_cell(cell_t *cell, connection_t *conn);
1611 extern uint64_t stats_n_padding_cells_processed;
1612 extern uint64_t stats_n_create_cells_processed;
1613 extern uint64_t stats_n_created_cells_processed;
1614 extern uint64_t stats_n_relay_cells_processed;
1615 extern uint64_t stats_n_destroy_cells_processed;
1617 /********************************* config.c ***************************/
1619 or_options_t *get_options(void);
1620 int set_options(or_options_t *new_val, char **msg);
1621 void config_free_all(void);
1622 const char *safe_str(const char *address);
1623 const char *escaped_safe_str(const char *address);
1625 int config_get_lines(char *string, config_line_t **result);
1626 void config_free_lines(config_line_t *front);
1627 int options_trial_assign(config_line_t *list, int use_defaults,
1628 int clear_first, char **msg);
1629 int resolve_my_address(int warn_severity, or_options_t *options,
1630 uint32_t *addr, char **hostname_out);
1631 void options_init(or_options_t *options);
1632 int options_init_from_torrc(int argc, char **argv);
1633 int options_init_logs(or_options_t *options, int validate_only);
1634 int option_is_recognized(const char *key);
1635 const char *option_get_canonical_name(const char *key);
1636 config_line_t *option_get_assignment(or_options_t *options,
1637 const char *key);
1638 char *options_dump(or_options_t *options, int minimal);
1639 int options_save_current(void);
1640 const char *get_torrc_fname(void);
1642 or_state_t *get_or_state(void);
1643 int or_state_load(void);
1644 int or_state_save(void);
1646 int config_getinfo_helper(const char *question, char **answer);
1648 /********************************* connection.c ***************************/
1650 const char *conn_type_to_string(int type);
1651 const char *conn_state_to_string(int type, int state);
1653 connection_t *connection_new(int type);
1654 void connection_unregister(connection_t *conn);
1655 void connection_free(connection_t *conn);
1656 void connection_free_all(void);
1657 void connection_about_to_close_connection(connection_t *conn);
1658 void connection_close_immediate(connection_t *conn);
1659 void _connection_mark_for_close(connection_t *conn,int line, const char *file);
1661 #define connection_mark_for_close(c) \
1662 _connection_mark_for_close((c), __LINE__, _SHORT_FILE_)
1664 void connection_expire_held_open(void);
1666 int connection_connect(connection_t *conn, char *address, uint32_t addr,
1667 uint16_t port);
1668 int retry_all_listeners(int force, smartlist_t *replaced_conns,
1669 smartlist_t *new_conns);
1671 int connection_bucket_write_limit(connection_t *conn);
1672 int global_write_bucket_empty(void);
1673 void connection_bucket_init(void);
1674 void connection_bucket_refill(struct timeval *now);
1676 int connection_handle_read(connection_t *conn);
1678 int connection_fetch_from_buf(char *string, size_t len, connection_t *conn);
1680 int connection_wants_to_flush(connection_t *conn);
1681 int connection_outbuf_too_full(connection_t *conn);
1682 int connection_handle_write(connection_t *conn);
1683 void _connection_controller_force_write(connection_t *conn);
1684 void connection_write_to_buf(const char *string, size_t len,
1685 connection_t *conn);
1686 void connection_write_to_buf_zlib(connection_t *conn,
1687 tor_zlib_state_t *state,
1688 const char *data, size_t data_len,
1689 int done);
1691 connection_t *connection_or_exact_get_by_addr_port(uint32_t addr,
1692 uint16_t port);
1693 connection_t *connection_get_by_global_id(uint32_t id);
1695 connection_t *connection_get_by_type(int type);
1696 connection_t *connection_get_by_type_purpose(int type, int purpose);
1697 connection_t *connection_get_by_type_addr_port_purpose(int type, uint32_t addr,
1698 uint16_t port, int purpose);
1699 connection_t *connection_get_by_type_state(int type, int state);
1700 connection_t *connection_get_by_type_state_lastwritten(int type, int state);
1701 connection_t *connection_get_by_type_state_rendquery(int type, int state,
1702 const char *rendquery);
1704 #define connection_speaks_cells(conn) ((conn)->type == CONN_TYPE_OR)
1705 int connection_is_listener(connection_t *conn);
1706 int connection_state_is_open(connection_t *conn);
1707 int connection_state_is_connecting(connection_t *conn);
1709 char *alloc_http_authenticator(const char *authenticator);
1711 void assert_connection_ok(connection_t *conn, time_t now);
1712 int connection_or_nonopen_was_started_here(connection_t *conn);
1714 /********************************* connection_edge.c *************************/
1716 #define connection_mark_unattached_ap(conn, endreason) \
1717 _connection_mark_unattached_ap((conn), (endreason), __LINE__, _SHORT_FILE_)
1719 void _connection_mark_unattached_ap(connection_t *conn, int endreason,
1720 int line, const char *file);
1721 int connection_edge_reached_eof(connection_t *conn);
1722 int connection_edge_process_inbuf(connection_t *conn, int package_partial);
1723 int connection_edge_destroy(uint16_t circ_id, connection_t *conn);
1724 int connection_edge_end(connection_t *conn, char reason,
1725 crypt_path_t *cpath_layer);
1726 int connection_edge_end_errno(connection_t *conn, crypt_path_t *cpath_layer);
1727 int connection_edge_finished_flushing(connection_t *conn);
1728 int connection_edge_finished_connecting(connection_t *conn);
1730 int connection_ap_handshake_send_begin(connection_t *ap_conn, circuit_t *circ);
1731 int connection_ap_handshake_send_resolve(connection_t *ap_conn,
1732 circuit_t *circ);
1734 int connection_ap_make_bridge(char *address, uint16_t port);
1735 void connection_ap_handshake_socks_reply(connection_t *conn, char *reply,
1736 size_t replylen,
1737 socks5_reply_status_t status);
1738 void connection_ap_handshake_socks_resolved(connection_t *conn,
1739 int answer_type,
1740 size_t answer_len,
1741 const char *answer,
1742 int ttl);
1744 int connection_exit_begin_conn(cell_t *cell, circuit_t *circ);
1745 int connection_exit_begin_resolve(cell_t *cell, circuit_t *circ);
1746 void connection_exit_connect(connection_t *conn);
1747 int connection_edge_is_rendezvous_stream(connection_t *conn);
1748 int connection_ap_can_use_exit(connection_t *conn, routerinfo_t *exit);
1749 void connection_ap_expire_beginning(void);
1750 void connection_ap_attach_pending(void);
1751 int connection_ap_detach_retriable(connection_t *conn, circuit_t *circ);
1753 void addressmap_init(void);
1754 void addressmap_clean(time_t now);
1755 void addressmap_clear_configured(void);
1756 void addressmap_clear_transient(void);
1757 void addressmap_free_all(void);
1758 void addressmap_rewrite(char *address, size_t maxlen);
1759 int addressmap_already_mapped(const char *address);
1760 void addressmap_register(const char *address, char *new_address,
1761 time_t expires);
1762 int parse_virtual_addr_network(const char *val, int validate_only,
1763 char **msg);
1764 int client_dns_incr_failures(const char *address);
1765 void client_dns_clear_failures(const char *address);
1766 void client_dns_set_addressmap(const char *address, uint32_t val,
1767 const char *exitname, int ttl);
1768 int address_is_in_virtual_range(const char *addr);
1769 const char *addressmap_register_virtual_address(int type, char *new_address);
1770 void addressmap_get_mappings(smartlist_t *sl, time_t min_expires,
1771 time_t max_expires);
1772 int connection_ap_handshake_rewrite_and_attach(connection_t *conn,
1773 circuit_t *circ);
1775 void set_exit_redirects(smartlist_t *lst);
1776 typedef enum hostname_type_t {
1777 NORMAL_HOSTNAME, ONION_HOSTNAME, EXIT_HOSTNAME, BAD_HOSTNAME
1778 } hostname_type_t;
1779 hostname_type_t parse_extended_hostname(char *address);
1781 /********************************* connection_or.c ***************************/
1783 void connection_or_remove_from_identity_map(connection_t *conn);
1784 void connection_or_clear_identity_map(void);
1785 connection_t *connection_or_get_by_identity_digest(const char *digest);
1787 int connection_or_reached_eof(connection_t *conn);
1788 int connection_or_process_inbuf(connection_t *conn);
1789 int connection_or_finished_flushing(connection_t *conn);
1790 int connection_or_finished_connecting(connection_t *conn);
1792 connection_t *connection_or_connect(uint32_t addr, uint16_t port,
1793 const char *id_digest);
1795 int connection_tls_start_handshake(connection_t *conn, int receiving);
1796 int connection_tls_continue_handshake(connection_t *conn);
1798 void connection_or_write_cell_to_buf(const cell_t *cell, connection_t *conn);
1799 int connection_or_send_destroy(uint16_t circ_id, connection_t *conn,
1800 int reason);
1802 /********************************* control.c ***************************/
1804 typedef enum circuit_status_event_t {
1805 CIRC_EVENT_LAUNCHED = 0,
1806 CIRC_EVENT_BUILT = 1,
1807 CIRC_EVENT_EXTENDED = 2,
1808 CIRC_EVENT_FAILED = 3,
1809 CIRC_EVENT_CLOSED = 4,
1810 } circuit_status_event_t;
1812 typedef enum stream_status_event_t {
1813 STREAM_EVENT_SENT_CONNECT = 0,
1814 STREAM_EVENT_SENT_RESOLVE = 1,
1815 STREAM_EVENT_SUCCEEDED = 2,
1816 STREAM_EVENT_FAILED = 3,
1817 STREAM_EVENT_CLOSED = 4,
1818 STREAM_EVENT_NEW = 5,
1819 STREAM_EVENT_NEW_RESOLVE = 6,
1820 STREAM_EVENT_FAILED_RETRIABLE = 7
1821 } stream_status_event_t;
1823 typedef enum or_conn_status_event_t {
1824 OR_CONN_EVENT_LAUNCHED = 0,
1825 OR_CONN_EVENT_CONNECTED = 1,
1826 OR_CONN_EVENT_FAILED = 2,
1827 OR_CONN_EVENT_CLOSED = 3,
1828 OR_CONN_EVENT_NEW = 4,
1829 } or_conn_status_event_t;
1831 void control_update_global_event_mask(void);
1832 void control_adjust_event_log_severity(void);
1834 /** Execute the statement <b>stmt</b>, which may log events concerning the
1835 * connection <b>conn</b>. To prevent infinite loops, disable log messages
1836 * being sent to controllers if <b>conn</b> is a control connection.
1838 * Stmt must not contain any return or goto statements.
1840 #define CONN_LOG_PROTECT(conn, stmt) \
1841 do { \
1842 int _log_conn_is_control = (conn && conn->type == CONN_TYPE_CONTROL); \
1843 if (_log_conn_is_control) \
1844 disable_control_logging(); \
1845 do {stmt;} while (0); \
1846 if (_log_conn_is_control) \
1847 enable_control_logging(); \
1848 } while (0)
1850 /** Log information about the connection <b>conn</b>, protecting it as with
1851 * CONN_LOG_PROTECT. Example:
1853 * LOG_FN_CONN(conn, (LOG_DEBUG, "Socket %d wants to write", conn->s));
1855 #define LOG_FN_CONN(conn, args) \
1856 CONN_LOG_PROTECT(conn, log_fn args)
1858 int connection_control_finished_flushing(connection_t *conn);
1859 int connection_control_reached_eof(connection_t *conn);
1860 int connection_control_process_inbuf(connection_t *conn);
1862 int control_event_circuit_status(circuit_t *circ, circuit_status_event_t e);
1863 int control_event_stream_status(connection_t *conn, stream_status_event_t e);
1864 int control_event_or_conn_status(connection_t *conn, or_conn_status_event_t e);
1865 int control_event_bandwidth_used(uint32_t n_read, uint32_t n_written);
1866 void control_event_logmsg(int severity, unsigned int domain, const char *msg);
1867 int control_event_descriptors_changed(smartlist_t *routers);
1868 int control_event_address_mapped(const char *from, const char *to,
1869 time_t expires);
1870 int control_event_or_authdir_new_descriptor(const char *action,
1871 const char *descriptor,
1872 const char *msg);
1874 int init_cookie_authentication(int enabled);
1875 int decode_hashed_password(char *buf, const char *hashed);
1876 void disable_control_logging(void);
1877 void enable_control_logging(void);
1879 /********************************* cpuworker.c *****************************/
1881 void cpu_init(void);
1882 void cpuworkers_rotate(void);
1883 int connection_cpu_finished_flushing(connection_t *conn);
1884 int connection_cpu_reached_eof(connection_t *conn);
1885 int connection_cpu_process_inbuf(connection_t *conn);
1886 int assign_to_cpuworker(connection_t *cpuworker, uint8_t question_type,
1887 void *task);
1889 /********************************* directory.c ***************************/
1891 void directory_post_to_dirservers(uint8_t purpose, const char *payload,
1892 size_t payload_len);
1893 void directory_get_from_dirserver(uint8_t purpose, const char *resource,
1894 int retry_if_no_servers);
1895 void directory_initiate_command_router(routerinfo_t *router, uint8_t purpose,
1896 int private_connection,
1897 const char *resource,
1898 const char *payload,
1899 size_t payload_len);
1900 void directory_initiate_command_routerstatus(routerstatus_t *status,
1901 uint8_t purpose,
1902 int private_connection,
1903 const char *resource,
1904 const char *payload,
1905 size_t payload_len);
1907 int parse_http_response(const char *headers, int *code, time_t *date,
1908 int *compression, char **response);
1910 int connection_dir_reached_eof(connection_t *conn);
1911 int connection_dir_process_inbuf(connection_t *conn);
1912 int connection_dir_finished_flushing(connection_t *conn);
1913 int connection_dir_finished_connecting(connection_t *conn);
1914 void connection_dir_request_failed(connection_t *conn);
1915 int dir_split_resource_into_fingerprints(const char *resource,
1916 smartlist_t *fp_out, int *compresseed_out,
1917 int decode_hex, int sort_uniq);
1918 char *directory_dump_request_log(void);
1920 /********************************* dirserv.c ***************************/
1922 int connection_dirserv_flushed_some(connection_t *conn);
1923 int dirserv_add_own_fingerprint(const char *nickname, crypto_pk_env_t *pk);
1924 int dirserv_parse_fingerprint_file(const char *fname);
1925 void dirserv_free_fingerprint_list(void);
1926 const char *dirserv_get_nickname_by_digest(const char *digest);
1927 int dirserv_add_descriptor(const char *desc, const char **msg);
1928 char *dirserver_getinfo_unregistered(const char *question);
1929 void dirserv_free_descriptors(void);
1930 int dirserv_thinks_router_is_blatantly_unreachable(routerinfo_t *router,
1931 time_t now);
1932 int list_server_status(smartlist_t *routers, char **router_status_out);
1933 int dirserv_dump_directory_to_string(char **dir_out,
1934 crypto_pk_env_t *private_key,
1935 int complete);
1936 void directory_set_dirty(void);
1937 cached_dir_t *dirserv_get_directory(void);
1938 size_t dirserv_get_runningrouters(const char **rr, int compress);
1939 void dirserv_set_cached_directory(const char *directory, time_t when,
1940 int is_running_routers);
1941 void dirserv_set_cached_networkstatus_v2(const char *directory,
1942 const char *identity,
1943 time_t published);
1944 void dirserv_get_networkstatus_v2(smartlist_t *result, const char *key);
1945 void dirserv_get_networkstatus_v2_fingerprints(smartlist_t *result,
1946 const char *key);
1947 int dirserv_get_routerdesc_fingerprints(smartlist_t *fps_out, const char *key,
1948 const char **msg);
1949 int dirserv_get_routerdescs(smartlist_t *descs_out, const char *key,
1950 const char **msg);
1951 void dirserv_orconn_tls_done(const char *address,
1952 uint16_t or_port,
1953 const char *digest_rcvd,
1954 const char *nickname,
1955 int as_advertised);
1956 void dirserv_test_reachability(int try_all);
1957 int authdir_wants_to_reject_router(routerinfo_t *ri, const char **msg,
1958 int complain);
1959 int dirserv_would_reject_router(routerstatus_t *rs);
1960 void dirserv_free_all(void);
1961 void cached_dir_decref(cached_dir_t *d);
1963 /********************************* dns.c ***************************/
1965 void dns_init(void);
1966 void dns_free_all(void);
1967 uint32_t dns_clip_ttl(uint32_t ttl);
1968 int connection_dns_finished_flushing(connection_t *conn);
1969 int connection_dns_reached_eof(connection_t *conn);
1970 int connection_dns_process_inbuf(connection_t *conn);
1971 void dnsworkers_rotate(void);
1972 void connection_dns_remove(connection_t *conn);
1973 void assert_connection_edge_not_dns_pending(connection_t *conn);
1974 void assert_all_pending_dns_resolves_ok(void);
1975 void dns_cancel_pending_resolve(char *question);
1976 int dns_resolve(connection_t *exitconn);
1978 /********************************* hibernate.c **********************/
1980 int accounting_parse_options(or_options_t *options, int validate_only);
1981 int accounting_is_enabled(or_options_t *options);
1982 void configure_accounting(time_t now);
1983 void accounting_run_housekeeping(time_t now);
1984 void accounting_add_bytes(size_t n_read, size_t n_written, int seconds);
1985 int accounting_record_bandwidth_usage(time_t now);
1986 void hibernate_begin_shutdown(void);
1987 int we_are_hibernating(void);
1988 void consider_hibernation(time_t now);
1989 int accounting_getinfo_helper(const char *question, char **answer);
1990 void accounting_set_bandwidth_usage_from_state(or_state_t *state);
1992 /********************************* main.c ***************************/
1994 int connection_add(connection_t *conn);
1995 int connection_remove(connection_t *conn);
1996 int connection_in_array(connection_t *conn);
1997 void add_connection_to_closeable_list(connection_t *conn);
1998 int connection_is_on_closeable_list(connection_t *conn);
2000 void get_connection_array(connection_t ***array, int *n);
2002 void connection_watch_events(connection_t *conn, short events);
2003 int connection_is_reading(connection_t *conn);
2004 void connection_stop_reading(connection_t *conn);
2005 void connection_start_reading(connection_t *conn);
2007 int connection_is_writing(connection_t *conn);
2008 void connection_stop_writing(connection_t *conn);
2009 void connection_start_writing(connection_t *conn);
2011 void directory_all_unreachable(time_t now);
2012 void directory_info_has_arrived(time_t now, int from_cache);
2014 int control_signal_act(int the_signal);
2015 void handle_signals(int is_parent);
2016 void tor_cleanup(void);
2017 void tor_free_all(int postfork);
2019 int tor_main(int argc, char *argv[]);
2021 /********************************* onion.c ***************************/
2023 int onion_pending_add(circuit_t *circ);
2024 circuit_t *onion_next_task(void);
2025 void onion_pending_remove(circuit_t *circ);
2027 int onion_skin_create(crypto_pk_env_t *router_key,
2028 crypto_dh_env_t **handshake_state_out,
2029 char *onion_skin_out);
2031 int onion_skin_server_handshake(const char *onion_skin,
2032 crypto_pk_env_t *private_key,
2033 crypto_pk_env_t *prev_private_key,
2034 char *handshake_reply_out,
2035 char *key_out,
2036 size_t key_out_len);
2038 int onion_skin_client_handshake(crypto_dh_env_t *handshake_state,
2039 const char *handshake_reply,
2040 char *key_out,
2041 size_t key_out_len);
2043 int fast_server_handshake(const char *key_in,
2044 char *handshake_reply_out,
2045 char *key_out,
2046 size_t key_out_len);
2048 int fast_client_handshake(const char *handshake_state,
2049 const char *handshake_reply_out,
2050 char *key_out,
2051 size_t key_out_len);
2053 void clear_pending_onions(void);
2055 /********************************* policies.c ************************/
2057 typedef enum {
2058 ADDR_POLICY_ACCEPTED=0,
2059 ADDR_POLICY_REJECTED=-1,
2060 ADDR_POLICY_PROBABLY_ACCEPTED=1,
2061 ADDR_POLICY_PROBABLY_REJECTED=2
2062 } addr_policy_result_t;
2064 int firewall_is_fascist_or(void);
2065 int fascist_firewall_allows_address_or(uint32_t addr, uint16_t port);
2066 int fascist_firewall_allows_address_dir(uint32_t addr, uint16_t port);
2067 int dir_policy_permits_address(uint32_t addr);
2068 int socks_policy_permits_address(uint32_t addr);
2069 int authdir_policy_permits_address(uint32_t addr, uint16_t port);
2070 int authdir_policy_valid_address(uint32_t addr, uint16_t port);
2072 int validate_addr_policies(or_options_t *options, char **msg);
2073 void policies_parse_from_options(or_options_t *options);
2075 int cmp_addr_policies(addr_policy_t *a, addr_policy_t *b);
2076 addr_policy_result_t compare_addr_to_addr_policy(uint32_t addr,
2077 uint16_t port, addr_policy_t *policy);
2078 int policies_parse_exit_policy(config_line_t *cfg,
2079 addr_policy_t **dest,
2080 int rejectprivate);
2081 int exit_policy_is_general_exit(addr_policy_t *policy);
2082 int policies_getinfo_helper(const char *question, char **answer);
2084 void addr_policy_free(addr_policy_t *p);
2085 void policies_free_all(void);
2087 /********************************* relay.c ***************************/
2089 extern uint64_t stats_n_relay_cells_relayed;
2090 extern uint64_t stats_n_relay_cells_delivered;
2092 int circuit_receive_relay_cell(cell_t *cell, circuit_t *circ,
2093 int cell_direction);
2095 void relay_header_pack(char *dest, const relay_header_t *src);
2096 void relay_header_unpack(relay_header_t *dest, const char *src);
2097 int connection_edge_send_command(connection_t *fromconn, circuit_t *circ,
2098 int relay_command, const char *payload,
2099 size_t payload_len,
2100 crypt_path_t *cpath_layer);
2101 int connection_edge_package_raw_inbuf(connection_t *conn, int package_partial);
2102 void connection_edge_consider_sending_sendme(connection_t *conn);
2103 socks5_reply_status_t connection_edge_end_reason_socks5_response(int reason);
2104 int errno_to_end_reason(int e);
2106 extern uint64_t stats_n_data_cells_packaged;
2107 extern uint64_t stats_n_data_bytes_packaged;
2108 extern uint64_t stats_n_data_cells_received;
2109 extern uint64_t stats_n_data_bytes_received;
2111 /********************************* rephist.c ***************************/
2113 void rep_hist_init(void);
2114 void rep_hist_note_connect_failed(const char* nickname, time_t when);
2115 void rep_hist_note_connect_succeeded(const char* nickname, time_t when);
2116 void rep_hist_note_disconnect(const char* nickname, time_t when);
2117 void rep_hist_note_connection_died(const char* nickname, time_t when);
2118 void rep_hist_note_extend_succeeded(const char *from_name,
2119 const char *to_name);
2120 void rep_hist_note_extend_failed(const char *from_name, const char *to_name);
2121 void rep_hist_dump_stats(time_t now, int severity);
2122 void rep_hist_note_bytes_read(int num_bytes, time_t when);
2123 void rep_hist_note_bytes_written(int num_bytes, time_t when);
2124 int rep_hist_bandwidth_assess(void);
2125 char *rep_hist_get_bandwidth_lines(void);
2126 void rep_hist_update_state(or_state_t *state);
2127 int rep_hist_load_state(or_state_t *state, char **err);
2128 void rep_history_clean(time_t before);
2130 void rep_hist_note_used_port(uint16_t port, time_t now);
2131 smartlist_t *rep_hist_get_predicted_ports(time_t now);
2132 void rep_hist_note_used_resolve(time_t now);
2133 void rep_hist_note_used_internal(time_t now, int need_uptime,
2134 int need_capacity);
2135 int rep_hist_get_predicted_internal(time_t now, int *need_uptime,
2136 int *need_capacity);
2138 int rep_hist_circbuilding_dormant(time_t now);
2140 void rep_hist_free_all(void);
2142 /********************************* rendclient.c ***************************/
2144 void rend_client_introcirc_has_opened(circuit_t *circ);
2145 void rend_client_rendcirc_has_opened(circuit_t *circ);
2146 int rend_client_introduction_acked(circuit_t *circ, const char *request,
2147 size_t request_len);
2148 void rend_client_refetch_renddesc(const char *query);
2149 int rend_client_remove_intro_point(extend_info_t *failed_intro,
2150 const char *query);
2151 int rend_client_rendezvous_acked(circuit_t *circ, const char *request,
2152 size_t request_len);
2153 int rend_client_receive_rendezvous(circuit_t *circ, const char *request,
2154 size_t request_len);
2155 void rend_client_desc_here(const char *query);
2157 extend_info_t *rend_client_get_random_intro(const char *query);
2159 int rend_client_send_introduction(circuit_t *introcirc, circuit_t *rendcirc);
2161 /********************************* rendcommon.c ***************************/
2163 /** Information used to connect to a hidden service. */
2164 typedef struct rend_service_descriptor_t {
2165 crypto_pk_env_t *pk; /**< This service's public key. */
2166 int version; /**< 0 or 1. */
2167 time_t timestamp; /**< Time when the descriptor was generated. */
2168 uint16_t protocols; /**< Bitmask: which rendezvous protocols are supported?
2169 * (We allow bits '0', '1', and '2' to be set.) */
2170 int n_intro_points; /**< Number of introduction points. */
2171 /** Array of n_intro_points elements for this service's introduction points'
2172 * nicknames. Elements are removed from this array if introduction attempts
2173 * fail. */
2174 char **intro_points;
2175 /** Array of n_intro_points elements for this service's introduction points'
2176 * extend_infos, or NULL if this descriptor is V0. Elements are removed
2177 * from this array if introduction attempts fail. If this array is present,
2178 * its elements correspond to the elements of intro_points. */
2179 extend_info_t **intro_point_extend_info;
2180 } rend_service_descriptor_t;
2182 int rend_cmp_service_ids(const char *one, const char *two);
2184 void rend_process_relay_cell(circuit_t *circ, int command, size_t length,
2185 const char *payload);
2187 void rend_service_descriptor_free(rend_service_descriptor_t *desc);
2188 int rend_encode_service_descriptor(rend_service_descriptor_t *desc,
2189 int version,
2190 crypto_pk_env_t *key,
2191 char **str_out,
2192 size_t *len_out);
2193 rend_service_descriptor_t *rend_parse_service_descriptor(const char *str,
2194 size_t len);
2195 int rend_get_service_id(crypto_pk_env_t *pk, char *out);
2197 /** A cached rendezvous descriptor. */
2198 typedef struct rend_cache_entry_t {
2199 size_t len; /** Length of <b>desc</b> */
2200 time_t received; /** When was the descriptor received? */
2201 char *desc; /** Service descriptor */
2202 rend_service_descriptor_t *parsed; /* Parsed value of 'desc' */
2203 } rend_cache_entry_t;
2205 void rend_cache_init(void);
2206 void rend_cache_clean(void);
2207 void rend_cache_free_all(void);
2208 int rend_valid_service_id(const char *query);
2209 int rend_cache_lookup_desc(const char *query, int version, const char **desc,
2210 size_t *desc_len);
2211 int rend_cache_lookup_entry(const char *query, int version,
2212 rend_cache_entry_t **entry_out);
2213 int rend_cache_store(const char *desc, size_t desc_len);
2215 /********************************* rendservice.c ***************************/
2217 int num_rend_services(void);
2218 int rend_config_services(or_options_t *options, int validate_only);
2219 int rend_service_load_keys(void);
2220 void rend_services_init(void);
2221 void rend_services_introduce(void);
2222 void rend_consider_services_upload(time_t now);
2224 void rend_service_intro_has_opened(circuit_t *circuit);
2225 int rend_service_intro_established(circuit_t *circuit, const char *request,
2226 size_t request_len);
2227 void rend_service_rendezvous_has_opened(circuit_t *circuit);
2228 int rend_service_introduce(circuit_t *circuit, const char *request,
2229 size_t request_len);
2230 void rend_service_relaunch_rendezvous(circuit_t *oldcirc);
2231 int rend_service_set_connection_addr_port(connection_t *conn, circuit_t *circ);
2232 void rend_service_dump_stats(int severity);
2233 void rend_service_free_all(void);
2235 /********************************* rendmid.c *******************************/
2236 int rend_mid_establish_intro(circuit_t *circ, const char *request,
2237 size_t request_len);
2238 int rend_mid_introduce(circuit_t *circ, const char *request,
2239 size_t request_len);
2240 int rend_mid_establish_rendezvous(circuit_t *circ, const char *request,
2241 size_t request_len);
2242 int rend_mid_rendezvous(circuit_t *circ, const char *request,
2243 size_t request_len);
2245 /********************************* router.c ***************************/
2247 void set_onion_key(crypto_pk_env_t *k);
2248 crypto_pk_env_t *get_onion_key(void);
2249 time_t get_onion_key_set_at(void);
2250 void set_identity_key(crypto_pk_env_t *k);
2251 crypto_pk_env_t *get_identity_key(void);
2252 int identity_key_is_set(void);
2253 void dup_onion_keys(crypto_pk_env_t **key, crypto_pk_env_t **last);
2254 void rotate_onion_key(void);
2255 crypto_pk_env_t *init_key_from_file(const char *fname);
2256 int init_keys(void);
2258 int check_whether_orport_reachable(void);
2259 int check_whether_dirport_reachable(void);
2260 void consider_testing_reachability(void);
2261 void router_orport_found_reachable(void);
2262 void router_dirport_found_reachable(void);
2263 void server_has_changed_ip(void);
2264 void consider_publishable_server(int force);
2266 int authdir_mode(or_options_t *options);
2267 int clique_mode(or_options_t *options);
2268 int server_mode(or_options_t *options);
2269 int advertised_server_mode(void);
2270 int proxy_mode(or_options_t *options);
2272 int router_is_clique_mode(routerinfo_t *router);
2273 void router_upload_dir_desc_to_dirservers(int force);
2274 void mark_my_descriptor_dirty_if_older_than(time_t when);
2275 void mark_my_descriptor_dirty(void);
2276 void check_descriptor_bandwidth_changed(time_t now);
2277 void check_descriptor_ipaddress_changed(time_t now);
2278 void router_new_address_suggestion(const char *suggestion);
2279 int router_compare_to_my_exit_policy(connection_t *conn);
2280 routerinfo_t *router_get_my_routerinfo(void);
2281 const char *router_get_my_descriptor(void);
2282 int router_digest_is_me(const char *digest);
2283 int router_is_me(routerinfo_t *router);
2284 int router_fingerprint_is_me(const char *fp);
2285 int router_rebuild_descriptor(int force);
2286 int router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
2287 crypto_pk_env_t *ident_key);
2288 int is_legal_nickname(const char *s);
2289 int is_legal_nickname_or_hexdigest(const char *s);
2290 int is_legal_hexdigest(const char *s);
2291 void router_reset_warnings(void);
2292 void router_free_all(void);
2294 /********************************* routerlist.c ***************************/
2296 /** Represents information about a single trusted directory server. */
2297 typedef struct trusted_dir_server_t {
2298 char *description;
2299 char *nickname;
2300 char *address; /**< Hostname */
2301 uint32_t addr; /**< IPv4 address */
2302 uint16_t dir_port; /**< Directory port */
2303 char digest[DIGEST_LEN]; /**< Digest of identity key */
2304 unsigned int is_running:1; /**< True iff we think this server is running. */
2305 /** True iff this server is an authority for the older ("v1") directory
2306 * protocol. (All authorities are v2 authorities.) */
2307 unsigned int is_v1_authority:1;
2308 int n_networkstatus_failures; /**< How many times have we asked for this
2309 * server's network-status unsuccessfully? */
2310 routerstatus_t fake_status; /**< Used when we need to pass this trusted
2311 * dir_server_t to directory_initiate_command_*
2312 * as a routerstatus_t. Not updated by the
2313 * router-status management code!
2315 } trusted_dir_server_t;
2317 int router_reload_router_list(void);
2318 int router_reload_networkstatus(void);
2319 smartlist_t *router_get_trusted_dir_servers(void);
2320 routerstatus_t *router_pick_directory_server(int requireother,
2321 int fascistfirewall,
2322 int for_v2_directory,
2323 int retry_if_no_servers);
2324 routerstatus_t *router_pick_trusteddirserver(int need_v1_authority,
2325 int requireother,
2326 int fascistfirewall,
2327 int retry_if_no_servers);
2328 trusted_dir_server_t *router_get_trusteddirserver_by_digest(
2329 const char *digest);
2330 void routerlist_add_family(smartlist_t *sl, routerinfo_t *router);
2331 void add_nickname_list_to_smartlist(smartlist_t *sl, const char *list,
2332 int must_be_running,
2333 int warn_if_down, int warn_if_unnamed);
2334 routerinfo_t *routerlist_find_my_routerinfo(void);
2335 routerinfo_t *router_find_exact_exit_enclave(const char *address,
2336 uint16_t port);
2338 #define ROUTER_REQUIRED_MIN_BANDWIDTH 10000
2339 int router_is_unreliable(routerinfo_t *router, int need_uptime,
2340 int need_capacity, int need_guard);
2341 uint32_t router_get_advertised_bandwidth(routerinfo_t *router);
2342 routerinfo_t *routerlist_sl_choose_by_bandwidth(smartlist_t *sl);
2343 routerinfo_t *router_choose_random_node(const char *preferred,
2344 const char *excluded,
2345 smartlist_t *excludedsmartlist,
2346 int need_uptime, int need_bandwidth,
2347 int need_guard,
2348 int allow_invalid, int strict);
2349 routerinfo_t *router_get_by_nickname(const char *nickname,
2350 int warn_if_unnamed);
2351 routerinfo_t *router_get_by_hexdigest(const char *hexdigest);
2352 routerinfo_t *router_get_by_digest(const char *digest);
2353 signed_descriptor_t *router_get_by_descriptor_digest(const char *digest);
2354 const char *signed_descriptor_get_body(signed_descriptor_t *desc);
2355 int router_digest_version_as_new_as(const char *digest, const char *cutoff);
2356 int router_digest_is_trusted_dir(const char *digest);
2357 routerlist_t *router_get_routerlist(void);
2358 void routerlist_reset_warnings(void);
2359 void routerlist_free(routerlist_t *routerlist);
2360 void dump_routerlist_mem_usage(int severity);
2361 void routerlist_remove(routerlist_t *rl, routerinfo_t *ri, int idx,
2362 int make_old);
2363 void routerinfo_free(routerinfo_t *router);
2364 void routerstatus_free(routerstatus_t *routerstatus);
2365 void networkstatus_free(networkstatus_t *networkstatus);
2366 void routerlist_free_all(void);
2367 routerinfo_t *routerinfo_copy(const routerinfo_t *router);
2368 void router_set_status(const char *digest, int up);
2369 void routerlist_remove_old_routers(void);
2370 void networkstatus_list_clean(time_t now);
2371 int router_add_to_routerlist(routerinfo_t *router, const char **msg,
2372 int from_cache, int from_fetch);
2373 int router_load_single_router(const char *s, uint8_t purpose,
2374 const char **msg);
2375 void router_load_routers_from_string(const char *s,
2376 saved_location_t saved_location,
2377 smartlist_t *requested_fingerprints);
2378 typedef enum {
2379 NS_FROM_CACHE, NS_FROM_DIR, NS_GENERATED
2380 } networkstatus_source_t;
2381 int router_set_networkstatus(const char *s, time_t arrived_at,
2382 networkstatus_source_t source,
2383 smartlist_t *requested_fingerprints);
2385 int router_exit_policy_all_routers_reject(uint32_t addr, uint16_t port,
2386 int need_uptime);
2387 int router_exit_policy_rejects_all(routerinfo_t *router);
2389 void add_trusted_dir_server(const char *nickname,
2390 const char *address, uint16_t port,
2391 const char *digest, int is_v1_authority);
2392 void clear_trusted_dir_servers(void);
2393 int any_trusted_dir_is_v1_authority(void);
2394 networkstatus_t *networkstatus_get_by_digest(const char *digest);
2395 local_routerstatus_t *router_get_combined_status_by_digest(const char *digest);
2396 void update_networkstatus_downloads(time_t now);
2397 void update_router_descriptor_downloads(time_t now);
2398 void routers_update_all_from_networkstatus(void);
2399 void routers_update_status_from_networkstatus(smartlist_t *routers,
2400 int reset_failures);
2401 smartlist_t *router_list_superseded(void);
2402 int router_have_minimum_dir_info(void);
2403 void networkstatus_list_update_recent(time_t now);
2404 void router_reset_descriptor_download_failures(void);
2405 void router_reset_status_download_failures(void);
2406 int router_differences_are_cosmetic(routerinfo_t *r1, routerinfo_t *r2);
2407 const char *esc_router_info(routerinfo_t *router);
2409 /********************************* routerparse.c ************************/
2411 #define MAX_STATUS_TAG_LEN 32
2412 /** Structure to hold parsed Tor versions. This is a little messier
2413 * than we would like it to be, because we changed version schemes with 0.1.0.
2415 * See version-spec.txt for the whole business.
2417 typedef struct tor_version_t {
2418 int major;
2419 int minor;
2420 int micro;
2421 /** Release status. For version in the post-0.1 format, this is always
2422 * VER_RELEASE. */
2423 enum { VER_PRE=0, VER_RC=1, VER_RELEASE=2, } status;
2424 int patchlevel;
2425 /** CVS status. For version in the post-0.1 format, this is always
2426 * IS_NOT_CVS */
2427 enum { IS_CVS=0, IS_NOT_CVS=1} cvs;
2428 char status_tag[MAX_STATUS_TAG_LEN];
2429 } tor_version_t;
2431 typedef enum version_status_t {
2432 VS_RECOMMENDED=0, /**< This version is listed as recommended. */
2433 VS_OLD=1, /**< This version is older than any recommended version. */
2434 VS_NEW=2, /**< This version is newer than any recommended version. */
2435 VS_NEW_IN_SERIES=3, /**< This version is newer than any recommended version
2436 * in its series, and such recommended versions exist. */
2437 VS_UNRECOMMENDED=4 /**< This version is not recommended (general case) */
2438 } version_status_t;
2440 int router_get_router_hash(const char *s, char *digest);
2441 int router_get_dir_hash(const char *s, char *digest);
2442 int router_get_runningrouters_hash(const char *s, char *digest);
2443 int router_get_networkstatus_v2_hash(const char *s, char *digest);
2444 int router_append_dirobj_signature(char *buf, size_t buf_len,
2445 const char *digest,
2446 crypto_pk_env_t *private_key);
2447 int router_parse_list_from_string(const char **s,
2448 smartlist_t *dest,
2449 saved_location_t saved_location);
2450 int router_parse_routerlist_from_directory(const char *s,
2451 routerlist_t **dest,
2452 crypto_pk_env_t *pkey,
2453 int check_version,
2454 int write_to_cache);
2455 int router_parse_runningrouters(const char *str);
2456 int router_parse_directory(const char *str);
2457 routerinfo_t *router_parse_entry_from_string(const char *s, const char *end,
2458 int cache_copy);
2459 addr_policy_t *router_parse_addr_policy_from_string(const char *s,
2460 int assume_action);
2461 version_status_t tor_version_is_obsolete(const char *myversion,
2462 const char *versionlist);
2463 version_status_t version_status_join(version_status_t a, version_status_t b);
2464 int tor_version_parse(const char *s, tor_version_t *out);
2465 int tor_version_as_new_as(const char *platform, const char *cutoff);
2466 int tor_version_compare(tor_version_t *a, tor_version_t *b);
2467 void sort_version_list(smartlist_t *lst, int remove_duplicates);
2468 void assert_addr_policy_ok(addr_policy_t *t);
2470 networkstatus_t *networkstatus_parse_from_string(const char *s);
2472 #endif