or.h
上传用户:awang829
上传日期:2019-07-14
资源大小:2356k
文件大小:207k
源码类别:

网络

开发平台:

Unix_Linux

  1.   int AutomapHostsOnResolve; /**< If true, when we get a resolve request for a
  2.                               * hostname ending with one of the suffixes in
  3.                               * <b>AutomapHostsSuffixes</b>, map it to a
  4.                               * virtual address. */
  5.   smartlist_t *AutomapHostsSuffixes; /**< List of suffixes for
  6.                                       * <b>AutomapHostsOnResolve</b>. */
  7.   int RendPostPeriod; /**< How often do we post each rendezvous service
  8.                        * descriptor? Remember to publish them independently. */
  9.   int KeepalivePeriod; /**< How often do we send padding cells to keep
  10.                         * connections alive? */
  11.   int SocksTimeout; /**< How long do we let a socks connection wait
  12.                      * unattached before we fail it? */
  13.   int CircuitBuildTimeout; /**< Cull non-open circuits that were born
  14.                             * at least this many seconds ago. */
  15.   int CircuitIdleTimeout; /**< Cull open clean circuits that were born
  16.                            * at least this many seconds ago. */
  17.   int MaxOnionsPending; /**< How many circuit CREATE requests do we allow
  18.                          * to wait simultaneously before we start dropping
  19.                          * them? */
  20.   int NewCircuitPeriod; /**< How long do we use a circuit before building
  21.                          * a new one? */
  22.   int MaxCircuitDirtiness; /**< Never use circs that were first used more than
  23.                                 this interval ago. */
  24.   uint64_t BandwidthRate; /**< How much bandwidth, on average, are we willing
  25.                            * to use in a second? */
  26.   uint64_t BandwidthBurst; /**< How much bandwidth, at maximum, are we willing
  27.                             * to use in a second? */
  28.   uint64_t MaxAdvertisedBandwidth; /**< How much bandwidth are we willing to
  29.                                     * tell people we have? */
  30.   uint64_t RelayBandwidthRate; /**< How much bandwidth, on average, are we
  31.                                  * willing to use for all relayed conns? */
  32.   uint64_t RelayBandwidthBurst; /**< How much bandwidth, at maximum, will we
  33.                                  * use in a second for all relayed conns? */
  34.   int NumCpus; /**< How many CPUs should we try to use? */
  35.   int RunTesting; /**< If true, create testing circuits to measure how well the
  36.                    * other ORs are running. */
  37.   config_line_t *RendConfigLines; /**< List of configuration lines
  38.                                           * for rendezvous services. */
  39.   config_line_t *HidServAuth; /**< List of configuration lines for client-side
  40.                                * authorizations for hidden services */
  41.   char *ContactInfo; /**< Contact info to be published in the directory. */
  42.   char *HttpProxy; /**< hostname[:port] to use as http proxy, if any. */
  43.   uint32_t HttpProxyAddr; /**< Parsed IPv4 addr for http proxy, if any. */
  44.   uint16_t HttpProxyPort; /**< Parsed port for http proxy, if any. */
  45.   char *HttpProxyAuthenticator; /**< username:password string, if any. */
  46.   char *HttpsProxy; /**< hostname[:port] to use as https proxy, if any. */
  47.   uint32_t HttpsProxyAddr; /**< Parsed IPv4 addr for https proxy, if any. */
  48.   uint16_t HttpsProxyPort; /**< Parsed port for https proxy, if any. */
  49.   char *HttpsProxyAuthenticator; /**< username:password string, if any. */
  50.   /** List of configuration lines for replacement directory authorities.
  51.    * If you just want to replace one class of authority at a time,
  52.    * use the "Alternate*Authority" options below instead. */
  53.   config_line_t *DirServers;
  54.   /** If set, use these main (currently v3) directory authorities and
  55.    * not the default ones. */
  56.   config_line_t *AlternateDirAuthority;
  57.   /** If set, use these bridge authorities and not the default one. */
  58.   config_line_t *AlternateBridgeAuthority;
  59.   /** If set, use these HS authorities and not the default ones. */
  60.   config_line_t *AlternateHSAuthority;
  61.   char *MyFamily; /**< Declared family for this OR. */
  62.   config_line_t *NodeFamilies; /**< List of config lines for
  63.                                        * node families */
  64.   config_line_t *AuthDirBadDir; /**< Address policy for descriptors to
  65.                                  * mark as bad dir mirrors. */
  66.   config_line_t *AuthDirBadExit; /**< Address policy for descriptors to
  67.                                   * mark as bad exits. */
  68.   config_line_t *AuthDirReject; /**< Address policy for descriptors to
  69.                                  * reject. */
  70.   config_line_t *AuthDirInvalid; /**< Address policy for descriptors to
  71.                                   * never mark as valid. */
  72.   int AuthDirListBadDirs; /**< True iff we should list bad dirs,
  73.                            * and vote for all other dir mirrors as good. */
  74.   int AuthDirListBadExits; /**< True iff we should list bad exits,
  75.                             * and vote for all other exits as good. */
  76.   int AuthDirRejectUnlisted; /**< Boolean: do we reject all routers that
  77.                               * aren't named in our fingerprint file? */
  78.   int AuthDirMaxServersPerAddr; /**< Do not permit more than this
  79.                                  * number of servers per IP address. */
  80.   int AuthDirMaxServersPerAuthAddr; /**< Do not permit more than this
  81.                                      * number of servers per IP address shared
  82.                                      * with an authority. */
  83.   char *AccountingStart; /**< How long is the accounting interval, and when
  84.                           * does it start? */
  85.   uint64_t AccountingMax; /**< How many bytes do we allow per accounting
  86.                            * interval before hibernation?  0 for "never
  87.                            * hibernate." */
  88.   /** Base64-encoded hash of accepted passwords for the control system. */
  89.   config_line_t *HashedControlPassword;
  90.   /** As HashedControlPassword, but not saved. */
  91.   config_line_t *HashedControlSessionPassword;
  92.   int CookieAuthentication; /**< Boolean: do we enable cookie-based auth for
  93.                              * the control system? */
  94.   char *CookieAuthFile; /**< Location of a cookie authentication file. */
  95.   int CookieAuthFileGroupReadable; /**< Boolean: Is the CookieAuthFile g+r? */
  96.   int LeaveStreamsUnattached; /**< Boolean: Does Tor attach new streams to
  97.                           * circuits itself (0), or does it expect a controller
  98.                           * to cope? (1) */
  99.   int DisablePredictedCircuits; /**< Boolean: does Tor preemptively
  100.                                  * make circuits in the background (0),
  101.                                  * or not (1)? */
  102.   int ShutdownWaitLength; /**< When we get a SIGINT and we're a server, how
  103.                            * long do we wait before exiting? */
  104.   int SafeLogging; /**< Boolean: are we allowed to log sensitive strings
  105.                     * such as addresses (0), or do we scrub them first (1)? */
  106.   int SafeSocks; /**< Boolean: should we outright refuse application
  107.                   * connections that use socks4 or socks5-with-local-dns? */
  108. #define LOG_PROTOCOL_WARN (get_options()->ProtocolWarnings ? 
  109.                            LOG_WARN : LOG_INFO)
  110.   int ProtocolWarnings; /**< Boolean: when other parties screw up the Tor
  111.                          * protocol, is it a warn or an info in our logs? */
  112.   int TestSocks; /**< Boolean: when we get a socks connection, do we loudly
  113.                   * log whether it was DNS-leaking or not? */
  114.   int HardwareAccel; /**< Boolean: Should we enable OpenSSL hardware
  115.                       * acceleration where available? */
  116.   int UseEntryGuards; /**< Boolean: Do we try to enter from a smallish number
  117.                        * of fixed nodes? */
  118.   int NumEntryGuards; /**< How many entry guards do we try to establish? */
  119.   int RephistTrackTime; /**< How many seconds do we keep rephist info? */
  120.   int FastFirstHopPK; /**< If Tor believes it is safe, should we save a third
  121.                        * of our PK time by sending CREATE_FAST cells? */
  122.   /** Should we always fetch our dir info on the mirror schedule (which
  123.    * means directly from the authorities) no matter our other config? */
  124.   int FetchDirInfoEarly;
  125.   char *VirtualAddrNetwork; /**< Address and mask to hand out for virtual
  126.                              * MAPADDRESS requests. */
  127.   int ServerDNSSearchDomains; /**< Boolean: If set, we don't force exit
  128.                       * addresses to be FQDNs, but rather search for them in
  129.                       * the local domains. */
  130.   int ServerDNSDetectHijacking; /**< Boolean: If true, check for DNS failure
  131.                                  * hijacking. */
  132.   int ServerDNSRandomizeCase; /**< Boolean: Use the 0x20-hack to prevent
  133.                                * DNS poisoning attacks. */
  134.   char *ServerDNSResolvConfFile; /**< If provided, we configure our internal
  135.                      * resolver from the file here rather than from
  136.                      * /etc/resolv.conf (Unix) or the registry (Windows). */
  137.   char *DirPortFrontPage; /**< This is a full path to a file with an html
  138.                     disclaimer. This allows a server administrator to show
  139.                     that they're running Tor and anyone visiting their server
  140.                     will know this without any specialized knowledge. */
  141.   /** Boolean: if set, we start even if our resolv.conf file is missing
  142.    * or broken. */
  143.   int ServerDNSAllowBrokenConfig;
  144.   smartlist_t *ServerDNSTestAddresses; /**< A list of addresses that definitely
  145.                                         * should be resolvable. Used for
  146.                                         * testing our DNS server. */
  147.   int EnforceDistinctSubnets; /**< If true, don't allow multiple routers in the
  148.                                * same network zone in the same circuit. */
  149.   int TunnelDirConns; /**< If true, use BEGIN_DIR rather than BEGIN when
  150.                        * possible. */
  151.   int PreferTunneledDirConns; /**< If true, avoid dirservers that don't
  152.                                * support BEGIN_DIR, when possible. */
  153.   int AllowNonRFC953Hostnames; /**< If true, we allow connections to hostnames
  154.                                 * with weird characters. */
  155.   /** If true, we try resolving hostnames with weird characters. */
  156.   int ServerDNSAllowNonRFC953Hostnames;
  157.   /** If true, we try to download extra-info documents (and we serve them,
  158.    * if we are a cache).  For authorities, this is always true. */
  159.   int DownloadExtraInfo;
  160.   /** If true, and we are acting as a relay, allow exit circuits even when
  161.    * we are the first hop of a circuit. */
  162.   int AllowSingleHopExits;
  163.   /** If true, don't allow relays with AllowSingleHopExits=1 to be used in
  164.    * circuits that we build. */
  165.   int ExcludeSingleHopRelays;
  166.   /** If true, and the controller tells us to use a one-hop circuit, and the
  167.    * exit allows it, we use it. */
  168.   int AllowSingleHopCircuits;
  169.   /** If true, do not believe anybody who tells us that a domain resolves
  170.    * to an internal address, or that an internal address has a PTR mapping.
  171.    * Helps avoid some cross-site attacks. */
  172.   int ClientDNSRejectInternalAddresses;
  173.   /** The length of time that we think a consensus should be fresh. */
  174.   int V3AuthVotingInterval;
  175.   /** The length of time we think it will take to distribute votes. */
  176.   int V3AuthVoteDelay;
  177.   /** The length of time we think it will take to distribute signatures. */
  178.   int V3AuthDistDelay;
  179.   /** The number of intervals we think a consensus should be valid. */
  180.   int V3AuthNIntervalsValid;
  181.   /** Should advertise and sign consensuses with a legacy key, for key
  182.    * migration purposes? */
  183.   int V3AuthUseLegacyKey;
  184.   /** The length of time that we think an initial consensus should be fresh.
  185.    * Only altered on testing networks. */
  186.   int TestingV3AuthInitialVotingInterval;
  187.   /** The length of time we think it will take to distribute initial votes.
  188.    * Only altered on testing networks. */
  189.   int TestingV3AuthInitialVoteDelay;
  190.   /** The length of time we think it will take to distribute initial
  191.    * signatures.  Only altered on testing networks.*/
  192.   int TestingV3AuthInitialDistDelay;
  193.   /** If an authority has been around for less than this amount of time, it
  194.    * does not believe its reachability information is accurate.  Only
  195.    * altered on testing networks. */
  196.   int TestingAuthDirTimeToLearnReachability;
  197.   /** Clients don't download any descriptor this recent, since it will
  198.    * probably not have propagated to enough caches.  Only altered on testing
  199.    * networks. */
  200.   int TestingEstimatedDescriptorPropagationTime;
  201.   /** If true, we take part in a testing network. Change the defaults of a
  202.    * couple of other configuration options and allow to change the values
  203.    * of certain configuration options. */
  204.   int TestingTorNetwork;
  205.   /** File to check for a consensus networkstatus, if we don't have one
  206.    * cached. */
  207.   char *FallbackNetworkstatusFile;
  208.   /** If true, and we have GeoIP data, and we're a bridge, keep a per-country
  209.    * count of how many client addresses have contacted us so that we can help
  210.    * the bridge authority guess which countries have blocked access to us. */
  211.   int BridgeRecordUsageByCountry;
  212. #ifdef ENABLE_GEOIP_STATS
  213.   /** If true, and Tor is built with GEOIP_STATS support, and we're a
  214.    * directory, record how many directory requests we get from each country. */
  215.   int DirRecordUsageByCountry;
  216.   /** Round all GeoIP results to the next multiple of this value, to avoid
  217.    * leaking information. */
  218.   int DirRecordUsageGranularity;
  219.   /** Time interval: purge geoip stats after this long. */
  220.   int DirRecordUsageRetainIPs;
  221.   /** Time interval: Flush geoip data to disk this often. */
  222.   int DirRecordUsageSaveInterval;
  223. #endif
  224.   /** Optionally, a file with GeoIP data. */
  225.   char *GeoIPFile;
  226.   /** If true, SIGHUP should reload the torrc.  Sometimes controllers want
  227.    * to make this false. */
  228.   int ReloadTorrcOnSIGHUP;
  229. } or_options_t;
  230. /** Persistent state for an onion router, as saved to disk. */
  231. typedef struct {
  232.   uint32_t _magic;
  233.   /** The time at which we next plan to write the state to the disk.  Equal to
  234.    * TIME_MAX if there are no savable changes, 0 if there are changes that
  235.    * should be saved right away. */
  236.   time_t next_write;
  237.   /** When was the state last written to disk? */
  238.   time_t LastWritten;
  239.   /** Fields for accounting bandwidth use. */
  240.   time_t AccountingIntervalStart;
  241.   uint64_t AccountingBytesReadInInterval;
  242.   uint64_t AccountingBytesWrittenInInterval;
  243.   int AccountingSecondsActive;
  244.   uint64_t AccountingExpectedUsage;
  245.   /** A list of Entry Guard-related configuration lines. */
  246.   config_line_t *EntryGuards;
  247.   /** These fields hold information on the history of bandwidth usage for
  248.    * servers.  The "Ends" fields hold the time when we last updated the
  249.    * bandwidth usage. The "Interval" fields hold the granularity, in seconds,
  250.    * of the entries of Values.  The "Values" lists hold decimal string
  251.    * representations of the number of bytes read or written in each
  252.    * interval. */
  253.   time_t      BWHistoryReadEnds;
  254.   int         BWHistoryReadInterval;
  255.   smartlist_t *BWHistoryReadValues;
  256.   time_t      BWHistoryWriteEnds;
  257.   int         BWHistoryWriteInterval;
  258.   smartlist_t *BWHistoryWriteValues;
  259.   /** What version of Tor wrote this state file? */
  260.   char *TorVersion;
  261.   /** Holds any unrecognized values we found in the state file, in the order
  262.    * in which we found them. */
  263.   config_line_t *ExtraLines;
  264.   /** When did we last rotate our onion key?  "0" for 'no idea'. */
  265.   time_t LastRotatedOnionKey;
  266. } or_state_t;
  267. /** Change the next_write time of <b>state</b> to <b>when</b>, unless the
  268.  * state is already scheduled to be written to disk earlier than <b>when</b>.
  269.  */
  270. static INLINE void or_state_mark_dirty(or_state_t *state, time_t when)
  271. {
  272.   if (state->next_write > when)
  273.     state->next_write = when;
  274. }
  275. #define MAX_SOCKS_REPLY_LEN 1024
  276. #define MAX_SOCKS_ADDR_LEN 256
  277. /** Please open a TCP connection to this addr:port. */
  278. #define SOCKS_COMMAND_CONNECT       0x01
  279. /** Please turn this FQDN into an IP address, privately. */
  280. #define SOCKS_COMMAND_RESOLVE       0xF0
  281. /** Please turn this IP address into an FQDN, privately. */
  282. #define SOCKS_COMMAND_RESOLVE_PTR   0xF1
  283. #define SOCKS_COMMAND_IS_CONNECT(c) ((c)==SOCKS_COMMAND_CONNECT)
  284. #define SOCKS_COMMAND_IS_RESOLVE(c) ((c)==SOCKS_COMMAND_RESOLVE || 
  285.                                      (c)==SOCKS_COMMAND_RESOLVE_PTR)
  286. /** State of a SOCKS request from a user to an OP.  Also used to encode other
  287.  * information for non-socks user request (such as those on TransPort and
  288.  * DNSPort) */
  289. struct socks_request_t {
  290.   /** Which version of SOCKS did the client use? One of "0, 4, 5" -- where
  291.    * 0 means that no socks handshake ever took place, and this is just a
  292.    * stub connection (e.g. see connection_ap_make_link()). */
  293.   char socks_version;
  294.   int command; /**< What is this stream's goal? One from the above list. */
  295.   size_t replylen; /**< Length of <b>reply</b>. */
  296.   char reply[MAX_SOCKS_REPLY_LEN]; /**< Write an entry into this string if
  297.                                     * we want to specify our own socks reply,
  298.                                     * rather than using the default socks4 or
  299.                                     * socks5 socks reply. We use this for the
  300.                                     * two-stage socks5 handshake.
  301.                                     */
  302.   char address[MAX_SOCKS_ADDR_LEN]; /**< What address did the client ask to
  303.                                        connect to/resolve? */
  304.   uint16_t port; /**< What port did the client ask to connect to? */
  305.   unsigned int has_finished : 1; /**< Has the SOCKS handshake finished? Used to
  306.                               * make sure we send back a socks reply for
  307.                               * every connection. */
  308. };
  309. /* all the function prototypes go here */
  310. /********************************* buffers.c ***************************/
  311. buf_t *buf_new(void);
  312. buf_t *buf_new_with_capacity(size_t size);
  313. void buf_free(buf_t *buf);
  314. void buf_clear(buf_t *buf);
  315. void buf_shrink(buf_t *buf);
  316. void buf_shrink_freelists(int free_all);
  317. void buf_dump_freelist_sizes(int severity);
  318. size_t buf_datalen(const buf_t *buf);
  319. size_t buf_allocation(const buf_t *buf);
  320. size_t buf_slack(const buf_t *buf);
  321. const char *_buf_peek_raw_buffer(const buf_t *buf);
  322. int read_to_buf(int s, size_t at_most, buf_t *buf, int *reached_eof,
  323.                 int *socket_error);
  324. int read_to_buf_tls(tor_tls_t *tls, size_t at_most, buf_t *buf);
  325. int flush_buf(int s, buf_t *buf, size_t sz, size_t *buf_flushlen);
  326. int flush_buf_tls(tor_tls_t *tls, buf_t *buf, size_t sz, size_t *buf_flushlen);
  327. int write_to_buf(const char *string, size_t string_len, buf_t *buf);
  328. int write_to_buf_zlib(buf_t *buf, tor_zlib_state_t *state,
  329.                       const char *data, size_t data_len, int done);
  330. int move_buf_to_buf(buf_t *buf_out, buf_t *buf_in, size_t *buf_flushlen);
  331. int fetch_from_buf(char *string, size_t string_len, buf_t *buf);
  332. int fetch_var_cell_from_buf(buf_t *buf, var_cell_t **out, int linkproto);
  333. int fetch_from_buf_http(buf_t *buf,
  334.                         char **headers_out, size_t max_headerlen,
  335.                         char **body_out, size_t *body_used, size_t max_bodylen,
  336.                         int force_complete);
  337. int fetch_from_buf_socks(buf_t *buf, socks_request_t *req,
  338.                          int log_sockstype, int safe_socks);
  339. int fetch_from_buf_line(buf_t *buf, char *data_out, size_t *data_len);
  340. int peek_buf_has_control0_command(buf_t *buf);
  341. void assert_buf_ok(buf_t *buf);
  342. #ifdef BUFFERS_PRIVATE
  343. int buf_find_string_offset(const buf_t *buf, const char *s, size_t n);
  344. #endif
  345. /********************************* circuitbuild.c **********************/
  346. char *circuit_list_path(origin_circuit_t *circ, int verbose);
  347. char *circuit_list_path_for_controller(origin_circuit_t *circ);
  348. void circuit_log_path(int severity, unsigned int domain,
  349.                       origin_circuit_t *circ);
  350. void circuit_rep_hist_note_result(origin_circuit_t *circ);
  351. origin_circuit_t *origin_circuit_init(uint8_t purpose, int flags);
  352. origin_circuit_t *circuit_establish_circuit(uint8_t purpose,
  353.                                             extend_info_t *exit,
  354.                                             int flags);
  355. int circuit_handle_first_hop(origin_circuit_t *circ);
  356. void circuit_n_conn_done(or_connection_t *or_conn, int status);
  357. int inform_testing_reachability(void);
  358. int circuit_send_next_onion_skin(origin_circuit_t *circ);
  359. void circuit_note_clock_jumped(int seconds_elapsed);
  360. int circuit_extend(cell_t *cell, circuit_t *circ);
  361. int circuit_init_cpath_crypto(crypt_path_t *cpath, const char *key_data,
  362.                               int reverse);
  363. int circuit_finish_handshake(origin_circuit_t *circ, uint8_t cell_type,
  364.                              const char *reply);
  365. int circuit_truncated(origin_circuit_t *circ, crypt_path_t *layer);
  366. int onionskin_answer(or_circuit_t *circ, uint8_t cell_type,
  367.                      const char *payload, const char *keys);
  368. int circuit_all_predicted_ports_handled(time_t now, int *need_uptime,
  369.                                         int *need_capacity);
  370. int circuit_append_new_exit(origin_circuit_t *circ, extend_info_t *info);
  371. int circuit_extend_to_new_exit(origin_circuit_t *circ, extend_info_t *info);
  372. void onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop);
  373. extend_info_t *extend_info_alloc(const char *nickname, const char *digest,
  374.                                  crypto_pk_env_t *onion_key,
  375.                                  const tor_addr_t *addr, uint16_t port);
  376. extend_info_t *extend_info_from_router(routerinfo_t *r);
  377. extend_info_t *extend_info_dup(extend_info_t *info);
  378. void extend_info_free(extend_info_t *info);
  379. routerinfo_t *build_state_get_exit_router(cpath_build_state_t *state);
  380. const char *build_state_get_exit_nickname(cpath_build_state_t *state);
  381. void entry_guards_compute_status(void);
  382. int entry_guard_register_connect_status(const char *digest, int succeeded,
  383.                                         int mark_relay_status, time_t now);
  384. void entry_nodes_should_be_added(void);
  385. int entry_list_can_grow(or_options_t *options);
  386. routerinfo_t *choose_random_entry(cpath_build_state_t *state);
  387. int entry_guards_parse_state(or_state_t *state, int set, char **msg);
  388. void entry_guards_update_state(or_state_t *state);
  389. int getinfo_helper_entry_guards(control_connection_t *conn,
  390.                                 const char *question, char **answer);
  391. void clear_bridge_list(void);
  392. int routerinfo_is_a_configured_bridge(routerinfo_t *ri);
  393. void bridge_add_from_config(const tor_addr_t *addr, uint16_t port,
  394.                             char *digest);
  395. void retry_bridge_descriptor_fetch_directly(const char *digest);
  396. void fetch_bridge_descriptors(time_t now);
  397. void learned_bridge_descriptor(routerinfo_t *ri, int from_cache);
  398. int any_bridge_descriptors_known(void);
  399. int any_pending_bridge_descriptor_fetches(void);
  400. int bridges_known_but_down(void);
  401. void bridges_retry_all(void);
  402. void entry_guards_free_all(void);
  403. /********************************* circuitlist.c ***********************/
  404. circuit_t * _circuit_get_global_list(void);
  405. const char *circuit_state_to_string(int state);
  406. const char *circuit_purpose_to_controller_string(uint8_t purpose);
  407. void circuit_dump_by_conn(connection_t *conn, int severity);
  408. void circuit_set_p_circid_orconn(or_circuit_t *circ, circid_t id,
  409.                                  or_connection_t *conn);
  410. void circuit_set_n_circid_orconn(circuit_t *circ, circid_t id,
  411.                                  or_connection_t *conn);
  412. void circuit_set_state(circuit_t *circ, uint8_t state);
  413. void circuit_close_all_marked(void);
  414. int32_t circuit_initial_package_window(void);
  415. origin_circuit_t *origin_circuit_new(void);
  416. or_circuit_t *or_circuit_new(circid_t p_circ_id, or_connection_t *p_conn);
  417. circuit_t *circuit_get_by_circid_orconn(circid_t circ_id,
  418.                                         or_connection_t *conn);
  419. int circuit_id_in_use_on_orconn(circid_t circ_id, or_connection_t *conn);
  420. circuit_t *circuit_get_by_edge_conn(edge_connection_t *conn);
  421. void circuit_unlink_all_from_or_conn(or_connection_t *conn, int reason);
  422. origin_circuit_t *circuit_get_by_global_id(uint32_t id);
  423. origin_circuit_t *circuit_get_by_rend_query_and_purpose(const char *rend_query,
  424.                                                         uint8_t purpose);
  425. origin_circuit_t *circuit_get_next_by_pk_and_purpose(origin_circuit_t *start,
  426.                                          const char *digest, uint8_t purpose);
  427. or_circuit_t *circuit_get_rendezvous(const char *cookie);
  428. or_circuit_t *circuit_get_intro_point(const char *digest);
  429. origin_circuit_t *circuit_find_to_cannibalize(uint8_t purpose,
  430.                                               extend_info_t *info, int flags);
  431. void circuit_mark_all_unused_circs(void);
  432. void circuit_expire_all_dirty_circs(void);
  433. void _circuit_mark_for_close(circuit_t *circ, int reason,
  434.                              int line, const char *file);
  435. int circuit_get_cpath_len(origin_circuit_t *circ);
  436. crypt_path_t *circuit_get_cpath_hop(origin_circuit_t *circ, int hopnum);
  437. void circuit_get_all_pending_on_or_conn(smartlist_t *out,
  438.                                         or_connection_t *or_conn);
  439. int circuit_count_pending_on_or_conn(or_connection_t *or_conn);
  440. #define circuit_mark_for_close(c, reason)                               
  441.   _circuit_mark_for_close((c), (reason), __LINE__, _SHORT_FILE_)
  442. void assert_cpath_layer_ok(const crypt_path_t *cp);
  443. void assert_circuit_ok(const circuit_t *c);
  444. void circuit_free_all(void);
  445. /********************************* circuituse.c ************************/
  446. void circuit_expire_building(time_t now);
  447. void circuit_remove_handled_ports(smartlist_t *needed_ports);
  448. int circuit_stream_is_being_handled(edge_connection_t *conn, uint16_t port,
  449.                                     int min);
  450. int circuit_conforms_to_options(const origin_circuit_t *circ,
  451.                                 const or_options_t *options);
  452. void circuit_build_needed_circs(time_t now);
  453. void circuit_detach_stream(circuit_t *circ, edge_connection_t *conn);
  454. void reset_bandwidth_test(void);
  455. int circuit_enough_testing_circs(void);
  456. void circuit_has_opened(origin_circuit_t *circ);
  457. void circuit_build_failed(origin_circuit_t *circ);
  458. /** Flag to set when a circuit should have only a single hop. */
  459. #define CIRCLAUNCH_ONEHOP_TUNNEL  (1<<0)
  460. /** Flag to set when a circuit needs to be built of high-uptime nodes */
  461. #define CIRCLAUNCH_NEED_UPTIME    (1<<1)
  462. /** Flag to set when a circuit needs to be built of high-capacity nodes */
  463. #define CIRCLAUNCH_NEED_CAPACITY  (1<<2)
  464. /** Flag to set when the last hop of a circuit doesn't need to be an
  465.  * exit node. */
  466. #define CIRCLAUNCH_IS_INTERNAL    (1<<3)
  467. origin_circuit_t *circuit_launch_by_extend_info(uint8_t purpose,
  468.                                                 extend_info_t *info,
  469.                                                 int flags);
  470. origin_circuit_t *circuit_launch_by_router(uint8_t purpose,
  471.                                            routerinfo_t *exit, int flags);
  472. void circuit_reset_failure_count(int timeout);
  473. int connection_ap_handshake_attach_chosen_circuit(edge_connection_t *conn,
  474.                                                   origin_circuit_t *circ,
  475.                                                   crypt_path_t *cpath);
  476. int connection_ap_handshake_attach_circuit(edge_connection_t *conn);
  477. /********************************* command.c ***************************/
  478. void command_process_cell(cell_t *cell, or_connection_t *conn);
  479. void command_process_var_cell(var_cell_t *cell, or_connection_t *conn);
  480. extern uint64_t stats_n_padding_cells_processed;
  481. extern uint64_t stats_n_create_cells_processed;
  482. extern uint64_t stats_n_created_cells_processed;
  483. extern uint64_t stats_n_relay_cells_processed;
  484. extern uint64_t stats_n_destroy_cells_processed;
  485. /********************************* config.c ***************************/
  486. /** An error from options_trial_assign() or options_init_from_string(). */
  487. typedef enum setopt_err_t {
  488.   SETOPT_OK = 0,
  489.   SETOPT_ERR_MISC = -1,
  490.   SETOPT_ERR_PARSE = -2,
  491.   SETOPT_ERR_TRANSITION = -3,
  492.   SETOPT_ERR_SETTING = -4,
  493. } setopt_err_t;
  494. const char *get_dirportfrontpage(void);
  495. or_options_t *get_options(void);
  496. int set_options(or_options_t *new_val, char **msg);
  497. void config_free_all(void);
  498. const char *safe_str(const char *address);
  499. const char *escaped_safe_str(const char *address);
  500. const char *get_version(void);
  501. int config_get_lines(const char *string, config_line_t **result);
  502. void config_free_lines(config_line_t *front);
  503. setopt_err_t options_trial_assign(config_line_t *list, int use_defaults,
  504.                                   int clear_first, char **msg);
  505. int resolve_my_address(int warn_severity, or_options_t *options,
  506.                        uint32_t *addr, char **hostname_out);
  507. int is_local_addr(const tor_addr_t *addr) ATTR_PURE;
  508. void options_init(or_options_t *options);
  509. int options_init_from_torrc(int argc, char **argv);
  510. setopt_err_t options_init_from_string(const char *cf,
  511.                             int command, const char *command_arg, char **msg);
  512. int option_is_recognized(const char *key);
  513. const char *option_get_canonical_name(const char *key);
  514. config_line_t *option_get_assignment(or_options_t *options,
  515.                                      const char *key);
  516. int options_save_current(void);
  517. const char *get_torrc_fname(void);
  518. char *options_get_datadir_fname2_suffix(or_options_t *options,
  519.                                         const char *sub1, const char *sub2,
  520.                                         const char *suffix);
  521. #define get_datadir_fname2_suffix(sub1, sub2, suffix) 
  522.   options_get_datadir_fname2_suffix(get_options(), (sub1), (sub2), (suffix))
  523. /** Return a newly allocated string containing datadir/sub1.  See
  524.  * get_datadir_fname2_suffix.  */
  525. #define get_datadir_fname(sub1) get_datadir_fname2_suffix((sub1), NULL, NULL)
  526. /** Return a newly allocated string containing datadir/sub1/sub2.  See
  527.  * get_datadir_fname2_suffix.  */
  528. #define get_datadir_fname2(sub1,sub2) 
  529.   get_datadir_fname2_suffix((sub1), (sub2), NULL)
  530. /** Return a newly allocated string containing datadir/sub1suffix.  See
  531.  * get_datadir_fname2_suffix. */
  532. #define get_datadir_fname_suffix(sub1, suffix) 
  533.   get_datadir_fname2_suffix((sub1), NULL, (suffix))
  534. or_state_t *get_or_state(void);
  535. int or_state_save(time_t now);
  536. int options_need_geoip_info(or_options_t *options, const char **reason_out);
  537. int getinfo_helper_config(control_connection_t *conn,
  538.                           const char *question, char **answer);
  539. uint32_t get_effective_bwrate(or_options_t *options);
  540. uint32_t get_effective_bwburst(or_options_t *options);
  541. #ifdef CONFIG_PRIVATE
  542. /* Used only by config.c and test.c */
  543. or_options_t *options_new(void);
  544. #endif
  545. /********************************* connection.c ***************************/
  546. const char *conn_type_to_string(int type);
  547. const char *conn_state_to_string(int type, int state);
  548. dir_connection_t *dir_connection_new(int socket_family);
  549. or_connection_t *or_connection_new(int socket_family);
  550. edge_connection_t *edge_connection_new(int type, int socket_family);
  551. control_connection_t *control_connection_new(int socket_family);
  552. connection_t *connection_new(int type, int socket_family);
  553. void connection_link_connections(connection_t *conn_a, connection_t *conn_b);
  554. void connection_unregister_events(connection_t *conn);
  555. void connection_free(connection_t *conn);
  556. void connection_free_all(void);
  557. void connection_about_to_close_connection(connection_t *conn);
  558. void connection_close_immediate(connection_t *conn);
  559. void _connection_mark_for_close(connection_t *conn,int line, const char *file);
  560. #define connection_mark_for_close(c) 
  561.   _connection_mark_for_close((c), __LINE__, _SHORT_FILE_)
  562. void connection_expire_held_open(void);
  563. int connection_connect(connection_t *conn, const char *address,
  564.                        const tor_addr_t *addr,
  565.                        uint16_t port, int *socket_error);
  566. int retry_all_listeners(smartlist_t *replaced_conns,
  567.                         smartlist_t *new_conns);
  568. ssize_t connection_bucket_write_limit(connection_t *conn, time_t now);
  569. int global_write_bucket_low(connection_t *conn, size_t attempt, int priority);
  570. void connection_bucket_init(void);
  571. void connection_bucket_refill(int seconds_elapsed, time_t now);
  572. int connection_handle_read(connection_t *conn);
  573. int connection_fetch_from_buf(char *string, size_t len, connection_t *conn);
  574. int connection_wants_to_flush(connection_t *conn);
  575. int connection_outbuf_too_full(connection_t *conn);
  576. int connection_handle_write(connection_t *conn, int force);
  577. void _connection_write_to_buf_impl(const char *string, size_t len,
  578.                                    connection_t *conn, int zlib);
  579. static void connection_write_to_buf(const char *string, size_t len,
  580.                                     connection_t *conn);
  581. static void connection_write_to_buf_zlib(const char *string, size_t len,
  582.                                          dir_connection_t *conn, int done);
  583. static INLINE void
  584. connection_write_to_buf(const char *string, size_t len, connection_t *conn)
  585. {
  586.   _connection_write_to_buf_impl(string, len, conn, 0);
  587. }
  588. static INLINE void
  589. connection_write_to_buf_zlib(const char *string, size_t len,
  590.                              dir_connection_t *conn, int done)
  591. {
  592.   _connection_write_to_buf_impl(string, len, TO_CONN(conn), done ? -1 : 1);
  593. }
  594. connection_t *connection_get_by_global_id(uint64_t id);
  595. connection_t *connection_get_by_type(int type);
  596. connection_t *connection_get_by_type_purpose(int type, int purpose);
  597. connection_t *connection_get_by_type_addr_port_purpose(int type,
  598.                                                    const tor_addr_t *addr,
  599.                                                    uint16_t port, int purpose);
  600. connection_t *connection_get_by_type_state(int type, int state);
  601. connection_t *connection_get_by_type_state_rendquery(int type, int state,
  602.                                                      const char *rendquery,
  603.                                                      int rendversion);
  604. #define connection_speaks_cells(conn) ((conn)->type == CONN_TYPE_OR)
  605. int connection_is_listener(connection_t *conn);
  606. int connection_state_is_open(connection_t *conn);
  607. int connection_state_is_connecting(connection_t *conn);
  608. char *alloc_http_authenticator(const char *authenticator);
  609. void assert_connection_ok(connection_t *conn, time_t now);
  610. int connection_or_nonopen_was_started_here(or_connection_t *conn);
  611. void connection_dump_buffer_mem_stats(int severity);
  612. void remove_file_if_very_old(const char *fname, time_t now);
  613. /********************************* connection_edge.c *************************/
  614. #define connection_mark_unattached_ap(conn, endreason) 
  615.   _connection_mark_unattached_ap((conn), (endreason), __LINE__, _SHORT_FILE_)
  616. void _connection_mark_unattached_ap(edge_connection_t *conn, int endreason,
  617.                                     int line, const char *file);
  618. int connection_edge_reached_eof(edge_connection_t *conn);
  619. int connection_edge_process_inbuf(edge_connection_t *conn,
  620.                                   int package_partial);
  621. int connection_edge_destroy(circid_t circ_id, edge_connection_t *conn);
  622. int connection_edge_end(edge_connection_t *conn, uint8_t reason);
  623. int connection_edge_end_errno(edge_connection_t *conn);
  624. int connection_edge_finished_flushing(edge_connection_t *conn);
  625. int connection_edge_finished_connecting(edge_connection_t *conn);
  626. int connection_ap_handshake_send_begin(edge_connection_t *ap_conn);
  627. int connection_ap_handshake_send_resolve(edge_connection_t *ap_conn);
  628. edge_connection_t  *connection_ap_make_link(char *address, uint16_t port,
  629.                                             const char *digest,
  630.                                             int use_begindir, int want_onehop);
  631. void connection_ap_handshake_socks_reply(edge_connection_t *conn, char *reply,
  632.                                          size_t replylen,
  633.                                          int endreason);
  634. void connection_ap_handshake_socks_resolved(edge_connection_t *conn,
  635.                                             int answer_type,
  636.                                             size_t answer_len,
  637.                                             const char *answer,
  638.                                             int ttl,
  639.                                             time_t expires);
  640. int connection_exit_begin_conn(cell_t *cell, circuit_t *circ);
  641. int connection_exit_begin_resolve(cell_t *cell, or_circuit_t *circ);
  642. void connection_exit_connect(edge_connection_t *conn);
  643. int connection_edge_is_rendezvous_stream(edge_connection_t *conn);
  644. int connection_ap_can_use_exit(edge_connection_t *conn, routerinfo_t *exit);
  645. void connection_ap_expire_beginning(void);
  646. void connection_ap_attach_pending(void);
  647. void connection_ap_fail_onehop(const char *failed_digest,
  648.                                cpath_build_state_t *build_state);
  649. void circuit_discard_optional_exit_enclaves(extend_info_t *info);
  650. int connection_ap_detach_retriable(edge_connection_t *conn,
  651.                                    origin_circuit_t *circ,
  652.                                    int reason);
  653. int connection_ap_process_transparent(edge_connection_t *conn);
  654. int address_is_invalid_destination(const char *address, int client);
  655. void addressmap_init(void);
  656. void addressmap_clean(time_t now);
  657. void addressmap_clear_configured(void);
  658. void addressmap_clear_transient(void);
  659. void addressmap_free_all(void);
  660. int addressmap_rewrite(char *address, size_t maxlen, time_t *expires_out);
  661. int addressmap_have_mapping(const char *address, int update_timeout);
  662. /** Enumerates possible origins of a client-side address mapping. */
  663. typedef enum {
  664.   /** We're remapping this address because the controller told us to. */
  665.   ADDRMAPSRC_CONTROLLER,
  666.   /** We're remapping this address because our configuration (via torrc, the
  667.    * command line, or a SETCONF command) told us to. */
  668.   ADDRMAPSRC_TORRC,
  669.   /** We're remapping this address because we have TrackHostExit configured,
  670.    * and we want to remember to use the same exit next time. */
  671.   ADDRMAPSRC_TRACKEXIT,
  672.   /** We're remapping this address because we got a DNS resolution from a
  673.    * Tor server that told us what its value was. */
  674.   ADDRMAPSRC_DNS,
  675. } addressmap_entry_source_t;
  676. void addressmap_register(const char *address, char *new_address,
  677.                          time_t expires, addressmap_entry_source_t source);
  678. int parse_virtual_addr_network(const char *val, int validate_only,
  679.                                char **msg);
  680. int client_dns_incr_failures(const char *address);
  681. void client_dns_clear_failures(const char *address);
  682. void client_dns_set_addressmap(const char *address, uint32_t val,
  683.                                const char *exitname, int ttl);
  684. const char *addressmap_register_virtual_address(int type, char *new_address);
  685. void addressmap_get_mappings(smartlist_t *sl, time_t min_expires,
  686.                              time_t max_expires, int want_expiry);
  687. int connection_ap_handshake_rewrite_and_attach(edge_connection_t *conn,
  688.                                                origin_circuit_t *circ,
  689.                                                crypt_path_t *cpath);
  690. int hostname_is_noconnect_address(const char *address);
  691. /** Possible return values for parse_extended_hostname. */
  692. typedef enum hostname_type_t {
  693.   NORMAL_HOSTNAME, ONION_HOSTNAME, EXIT_HOSTNAME, BAD_HOSTNAME
  694. } hostname_type_t;
  695. hostname_type_t parse_extended_hostname(char *address);
  696. #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
  697. int get_pf_socket(void);
  698. #endif
  699. /********************************* connection_or.c ***************************/
  700. void connection_or_remove_from_identity_map(or_connection_t *conn);
  701. void connection_or_clear_identity_map(void);
  702. or_connection_t *connection_or_get_for_extend(const char *digest,
  703.                                               const tor_addr_t *target_addr,
  704.                                               const char **msg_out,
  705.                                               int *launch_out);
  706. void connection_or_set_bad_connections(void);
  707. int connection_or_reached_eof(or_connection_t *conn);
  708. int connection_or_process_inbuf(or_connection_t *conn);
  709. int connection_or_flushed_some(or_connection_t *conn);
  710. int connection_or_finished_flushing(or_connection_t *conn);
  711. int connection_or_finished_connecting(or_connection_t *conn);
  712. void connection_or_connect_failed(or_connection_t *conn,
  713.                                   int reason, const char *msg);
  714. or_connection_t *connection_or_connect(const tor_addr_t *addr, uint16_t port,
  715.                                        const char *id_digest);
  716. int connection_tls_start_handshake(or_connection_t *conn, int receiving);
  717. int connection_tls_continue_handshake(or_connection_t *conn);
  718. void or_handshake_state_free(or_handshake_state_t *state);
  719. int connection_or_set_state_open(or_connection_t *conn);
  720. void connection_or_write_cell_to_buf(const cell_t *cell,
  721.                                      or_connection_t *conn);
  722. void connection_or_write_var_cell_to_buf(const var_cell_t *cell,
  723.                                          or_connection_t *conn);
  724. int connection_or_send_destroy(circid_t circ_id, or_connection_t *conn,
  725.                                int reason);
  726. int connection_or_send_netinfo(or_connection_t *conn);
  727. int connection_or_send_cert(or_connection_t *conn);
  728. int connection_or_send_link_auth(or_connection_t *conn);
  729. int connection_or_compute_link_auth_hmac(or_connection_t *conn,
  730.                                          char *hmac_out);
  731. int is_or_protocol_version_known(uint16_t version);
  732. void cell_pack(packed_cell_t *dest, const cell_t *src);
  733. void var_cell_pack_header(const var_cell_t *cell, char *hdr_out);
  734. var_cell_t *var_cell_new(uint16_t payload_len);
  735. void var_cell_free(var_cell_t *cell);
  736. /********************************* control.c ***************************/
  737. /** Used to indicate the type of a circuit event passed to the controller.
  738.  * The various types are defined in control-spec.txt */
  739. typedef enum circuit_status_event_t {
  740.   CIRC_EVENT_LAUNCHED = 0,
  741.   CIRC_EVENT_BUILT    = 1,
  742.   CIRC_EVENT_EXTENDED = 2,
  743.   CIRC_EVENT_FAILED   = 3,
  744.   CIRC_EVENT_CLOSED   = 4,
  745. } circuit_status_event_t;
  746. /** Used to indicate the type of a stream event passed to the controller.
  747.  * The various types are defined in control-spec.txt */
  748. typedef enum stream_status_event_t {
  749.   STREAM_EVENT_SENT_CONNECT = 0,
  750.   STREAM_EVENT_SENT_RESOLVE = 1,
  751.   STREAM_EVENT_SUCCEEDED    = 2,
  752.   STREAM_EVENT_FAILED       = 3,
  753.   STREAM_EVENT_CLOSED       = 4,
  754.   STREAM_EVENT_NEW          = 5,
  755.   STREAM_EVENT_NEW_RESOLVE  = 6,
  756.   STREAM_EVENT_FAILED_RETRIABLE = 7,
  757.   STREAM_EVENT_REMAP        = 8
  758. } stream_status_event_t;
  759. /** Used to indicate the type of an OR connection event passed to the
  760.  * controller.  The various types are defined in control-spec.txt */
  761. typedef enum or_conn_status_event_t {
  762.   OR_CONN_EVENT_LAUNCHED     = 0,
  763.   OR_CONN_EVENT_CONNECTED    = 1,
  764.   OR_CONN_EVENT_FAILED       = 2,
  765.   OR_CONN_EVENT_CLOSED       = 3,
  766.   OR_CONN_EVENT_NEW          = 4,
  767. } or_conn_status_event_t;
  768. void control_update_global_event_mask(void);
  769. void control_adjust_event_log_severity(void);
  770. /** Execute the statement <b>stmt</b>, which may log events concerning the
  771.  * connection <b>conn</b>.  To prevent infinite loops, disable log messages
  772.  * being sent to controllers if <b>conn</b> is a control connection.
  773.  *
  774.  * Stmt must not contain any return or goto statements.
  775.  */
  776. #define CONN_LOG_PROTECT(conn, stmt)                                    
  777.   STMT_BEGIN                                                            
  778.     int _log_conn_is_control = (conn && conn->type == CONN_TYPE_CONTROL); 
  779.     if (_log_conn_is_control)                                           
  780.       disable_control_logging();                                        
  781.   STMT_BEGIN stmt; STMT_END;                                            
  782.     if (_log_conn_is_control)                                           
  783.       enable_control_logging();                                         
  784.   STMT_END
  785. /** Log information about the connection <b>conn</b>, protecting it as with
  786.  * CONN_LOG_PROTECT. Example:
  787.  *
  788.  * LOG_FN_CONN(conn, (LOG_DEBUG, "Socket %d wants to write", conn->s));
  789.  **/
  790. #define LOG_FN_CONN(conn, args)                 
  791.   CONN_LOG_PROTECT(conn, log_fn args)
  792. int connection_control_finished_flushing(control_connection_t *conn);
  793. int connection_control_reached_eof(control_connection_t *conn);
  794. int connection_control_process_inbuf(control_connection_t *conn);
  795. #define EVENT_AUTHDIR_NEWDESCS 0x000D
  796. #define EVENT_NS 0x000F
  797. int control_event_is_interesting(int event);
  798. int control_event_circuit_status(origin_circuit_t *circ,
  799.                                  circuit_status_event_t e, int reason);
  800. int control_event_stream_status(edge_connection_t *conn,
  801.                                 stream_status_event_t e,
  802.                                 int reason);
  803. int control_event_or_conn_status(or_connection_t *conn,
  804.                                  or_conn_status_event_t e, int reason);
  805. int control_event_bandwidth_used(uint32_t n_read, uint32_t n_written);
  806. int control_event_stream_bandwidth(edge_connection_t *edge_conn);
  807. int control_event_stream_bandwidth_used(void);
  808. void control_event_logmsg(int severity, unsigned int domain, const char *msg);
  809. int control_event_descriptors_changed(smartlist_t *routers);
  810. int control_event_address_mapped(const char *from, const char *to,
  811.                                  time_t expires, const char *error);
  812. int control_event_or_authdir_new_descriptor(const char *action,
  813.                                             const char *desc,
  814.                                             size_t desclen,
  815.                                             const char *msg);
  816. int control_event_my_descriptor_changed(void);
  817. int control_event_networkstatus_changed(smartlist_t *statuses);
  818. int control_event_newconsensus(const networkstatus_t *consensus);
  819. int control_event_networkstatus_changed_single(routerstatus_t *rs);
  820. int control_event_general_status(int severity, const char *format, ...)
  821.   CHECK_PRINTF(2,3);
  822. int control_event_client_status(int severity, const char *format, ...)
  823.   CHECK_PRINTF(2,3);
  824. int control_event_server_status(int severity, const char *format, ...)
  825.   CHECK_PRINTF(2,3);
  826. int control_event_guard(const char *nickname, const char *digest,
  827.                         const char *status);
  828. int init_cookie_authentication(int enabled);
  829. smartlist_t *decode_hashed_passwords(config_line_t *passwords);
  830. void disable_control_logging(void);
  831. void enable_control_logging(void);
  832. /** Enum describing various stages of bootstrapping, for use with controller
  833.  * bootstrap status events. The values range from 0 to 100. */
  834. typedef enum {
  835.   BOOTSTRAP_STATUS_UNDEF=-1,
  836.   BOOTSTRAP_STATUS_STARTING=0,
  837.   BOOTSTRAP_STATUS_CONN_DIR=5,
  838.   BOOTSTRAP_STATUS_HANDSHAKE=-2,
  839.   BOOTSTRAP_STATUS_HANDSHAKE_DIR=10,
  840.   BOOTSTRAP_STATUS_ONEHOP_CREATE=15,
  841.   BOOTSTRAP_STATUS_REQUESTING_STATUS=20,
  842.   BOOTSTRAP_STATUS_LOADING_STATUS=25,
  843.   BOOTSTRAP_STATUS_LOADING_KEYS=40,
  844.   BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS=45,
  845.   BOOTSTRAP_STATUS_LOADING_DESCRIPTORS=50,
  846.   BOOTSTRAP_STATUS_CONN_OR=80,
  847.   BOOTSTRAP_STATUS_HANDSHAKE_OR=85,
  848.   BOOTSTRAP_STATUS_CIRCUIT_CREATE=90,
  849.   BOOTSTRAP_STATUS_DONE=100
  850. } bootstrap_status_t;
  851. void control_event_bootstrap(bootstrap_status_t status, int progress);
  852. void control_event_bootstrap_problem(const char *warn, int reason);
  853. void control_event_clients_seen(const char *timestarted,
  854.                                 const char *countries);
  855. #ifdef CONTROL_PRIVATE
  856. /* Used only by control.c and test.c */
  857. size_t write_escaped_data(const char *data, size_t len, char **out);
  858. size_t read_escaped_data(const char *data, size_t len, char **out);
  859. #endif
  860. /********************************* cpuworker.c *****************************/
  861. void cpu_init(void);
  862. void cpuworkers_rotate(void);
  863. int connection_cpu_finished_flushing(connection_t *conn);
  864. int connection_cpu_reached_eof(connection_t *conn);
  865. int connection_cpu_process_inbuf(connection_t *conn);
  866. int assign_onionskin_to_cpuworker(connection_t *cpuworker,
  867.                                   or_circuit_t *circ,
  868.                                   char *onionskin);
  869. /********************************* directory.c ***************************/
  870. int directories_have_accepted_server_descriptor(void);
  871. char *authority_type_to_string(authority_type_t auth);
  872. void directory_post_to_dirservers(uint8_t dir_purpose, uint8_t router_purpose,
  873.                                   authority_type_t type, const char *payload,
  874.                                   size_t payload_len, size_t extrainfo_len);
  875. void directory_get_from_dirserver(uint8_t dir_purpose, uint8_t router_purpose,
  876.                                   const char *resource,
  877.                                   int pds_flags);
  878. void directory_get_from_all_authorities(uint8_t dir_purpose,
  879.                                         uint8_t router_purpose,
  880.                                         const char *resource);
  881. void directory_initiate_command_routerstatus(routerstatus_t *status,
  882.                                              uint8_t dir_purpose,
  883.                                              uint8_t router_purpose,
  884.                                              int anonymized_connection,
  885.                                              const char *resource,
  886.                                              const char *payload,
  887.                                              size_t payload_len,
  888.                                              time_t if_modified_since);
  889. void directory_initiate_command_routerstatus_rend(routerstatus_t *status,
  890.                                                   uint8_t dir_purpose,
  891.                                                   uint8_t router_purpose,
  892.                                                   int anonymized_connection,
  893.                                                   const char *resource,
  894.                                                   const char *payload,
  895.                                                   size_t payload_len,
  896.                                                   time_t if_modified_since,
  897.                                                 const rend_data_t *rend_query);
  898. int parse_http_response(const char *headers, int *code, time_t *date,
  899.                         compress_method_t *compression, char **response);
  900. int connection_dir_is_encrypted(dir_connection_t *conn);
  901. int connection_dir_reached_eof(dir_connection_t *conn);
  902. int connection_dir_process_inbuf(dir_connection_t *conn);
  903. int connection_dir_finished_flushing(dir_connection_t *conn);
  904. int connection_dir_finished_connecting(dir_connection_t *conn);
  905. void connection_dir_request_failed(dir_connection_t *conn);
  906. void directory_initiate_command(const char *address, const tor_addr_t *addr,
  907.                                 uint16_t or_port, uint16_t dir_port,
  908.                                 int supports_conditional_consensus,
  909.                                 int supports_begindir, const char *digest,
  910.                                 uint8_t dir_purpose, uint8_t router_purpose,
  911.                                 int anonymized_connection,
  912.                                 const char *resource,
  913.                                 const char *payload, size_t payload_len,
  914.                                 time_t if_modified_since);
  915. int dir_split_resource_into_fingerprints(const char *resource,
  916.                                     smartlist_t *fp_out, int *compresseed_out,
  917.                                     int decode_hex, int sort_uniq);
  918. /** A pair of digests created by dir_split_resource_info_fingerprint_pairs() */
  919. typedef struct {
  920.   char first[DIGEST_LEN];
  921.   char second[DIGEST_LEN];
  922. } fp_pair_t;
  923. int dir_split_resource_into_fingerprint_pairs(const char *res,
  924.                                               smartlist_t *pairs_out);
  925. char *directory_dump_request_log(void);
  926. void note_request(const char *key, size_t bytes);
  927. int router_supports_extrainfo(const char *identity_digest, int is_authority);
  928. time_t download_status_increment_failure(download_status_t *dls,
  929.                                          int status_code, const char *item,
  930.                                          int server, time_t now);
  931. /** Increment the failure count of the download_status_t <b>dls</b>, with
  932.  * the optional status code <b>sc</b>. */
  933. #define download_status_failed(dls, sc)                                 
  934.   download_status_increment_failure((dls), (sc), NULL,                  
  935.                                     get_options()->DirPort, time(NULL))
  936. void download_status_reset(download_status_t *dls);
  937. static int download_status_is_ready(download_status_t *dls, time_t now,
  938.                                     int max_failures);
  939. /** Return true iff, as of <b>now</b>, the resource tracked by <b>dls</b> is
  940.  * ready to get its download reattempted. */
  941. static INLINE int
  942. download_status_is_ready(download_status_t *dls, time_t now,
  943.                          int max_failures)
  944. {
  945.   return (dls->n_download_failures <= max_failures
  946.           && dls->next_attempt_at <= now);
  947. }
  948. static void download_status_mark_impossible(download_status_t *dl);
  949. /** Mark <b>dl</b> as never downloadable. */
  950. static INLINE void
  951. download_status_mark_impossible(download_status_t *dl)
  952. {
  953.   dl->n_download_failures = IMPOSSIBLE_TO_DOWNLOAD;
  954. }
  955. /********************************* dirserv.c ***************************/
  956. /** Maximum length of an exit policy summary. */
  957. #define MAX_EXITPOLICY_SUMMARY_LEN (1000)
  958. /** Maximum allowable length of a version line in a networkstatus. */
  959. #define MAX_V_LINE_LEN 128
  960. /** Length of "r Authority BadDirectory BadExit Exit Fast Guard HSDir Named
  961.  * Running Stable Unnamed V2Dir Validn". */
  962. #define MAX_FLAG_LINE_LEN 96
  963. /** Length of "w" line for weighting.  Currently at most
  964.  * "w Bandwidth=<uint32t>n" */
  965. #define MAX_WEIGHT_LINE_LEN (13+10)
  966. /** Maximum length of an exit policy summary line. */
  967. #define MAX_POLICY_LINE_LEN (3+MAX_EXITPOLICY_SUMMARY_LEN)
  968. /** Amount of space to allocate for each entry: r, s, and v lines. */
  969. #define RS_ENTRY_LEN                                                    
  970.   ( /* first line */                                                    
  971.    MAX_NICKNAME_LEN+BASE64_DIGEST_LEN*2+ISO_TIME_LEN+INET_NTOA_BUF_LEN+ 
  972.    5*2 /* ports */ + 10 /* punctuation */ +                             
  973.    /* second line */                                                    
  974.    MAX_FLAG_LINE_LEN +                                                  
  975.    /* weight line */                                                    
  976.    MAX_WEIGHT_LINE_LEN +                                                
  977.    /* p line. */                                                        
  978.    MAX_POLICY_LINE_LEN +                                                
  979.    /* v line. */                                                        
  980.    MAX_V_LINE_LEN                                                       
  981.    )
  982. #define UNNAMED_ROUTER_NICKNAME "Unnamed"
  983. int connection_dirserv_flushed_some(dir_connection_t *conn);
  984. int dirserv_add_own_fingerprint(const char *nickname, crypto_pk_env_t *pk);
  985. int dirserv_load_fingerprint_file(void);
  986. void dirserv_free_fingerprint_list(void);
  987. const char *dirserv_get_nickname_by_digest(const char *digest);
  988. enum was_router_added_t dirserv_add_multiple_descriptors(
  989.                                      const char *desc, uint8_t purpose,
  990.                                      const char *source,
  991.                                      const char **msg);
  992. enum was_router_added_t dirserv_add_descriptor(routerinfo_t *ri,
  993.                                                const char **msg,
  994.                                                const char *source);
  995. int getinfo_helper_dirserv_unregistered(control_connection_t *conn,
  996.                                         const char *question, char **answer);
  997. void dirserv_free_descriptors(void);
  998. void dirserv_set_router_is_running(routerinfo_t *router, time_t now);
  999. int list_server_status_v1(smartlist_t *routers, char **router_status_out,
  1000.                           int for_controller);
  1001. int dirserv_dump_directory_to_string(char **dir_out,
  1002.                                      crypto_pk_env_t *private_key);
  1003. int directory_fetches_from_authorities(or_options_t *options);
  1004. int directory_fetches_dir_info_early(or_options_t *options);
  1005. int directory_fetches_dir_info_later(or_options_t *options);
  1006. int directory_caches_v2_dir_info(or_options_t *options);
  1007. #define directory_caches_v1_dir_info(o) directory_caches_v2_dir_info(o)
  1008. int directory_caches_dir_info(or_options_t *options);
  1009. int directory_permits_begindir_requests(or_options_t *options);
  1010. int directory_permits_controller_requests(or_options_t *options);
  1011. int directory_too_idle_to_fetch_descriptors(or_options_t *options, time_t now);
  1012. void directory_set_dirty(void);
  1013. cached_dir_t *dirserv_get_directory(void);
  1014. cached_dir_t *dirserv_get_runningrouters(void);
  1015. cached_dir_t *dirserv_get_consensus(void);
  1016. void dirserv_set_cached_directory(const char *directory, time_t when,
  1017.                                   int is_running_routers);
  1018. void dirserv_set_cached_networkstatus_v2(const char *directory,
  1019.                                          const char *identity,
  1020.                                          time_t published);
  1021. void dirserv_set_cached_networkstatus_v3(const char *consensus,
  1022.                                          time_t published);
  1023. void dirserv_clear_old_networkstatuses(time_t cutoff);
  1024. void dirserv_clear_old_v1_info(time_t now);
  1025. void dirserv_get_networkstatus_v2(smartlist_t *result, const char *key);
  1026. void dirserv_get_networkstatus_v2_fingerprints(smartlist_t *result,
  1027.                                                const char *key);
  1028. int dirserv_get_routerdesc_fingerprints(smartlist_t *fps_out, const char *key,
  1029.                                         const char **msg,
  1030.                                         int for_unencrypted_conn,
  1031.                                         int is_extrainfo);
  1032. int dirserv_get_routerdescs(smartlist_t *descs_out, const char *key,
  1033.                             const char **msg);
  1034. void dirserv_orconn_tls_done(const char *address,
  1035.                              uint16_t or_port,
  1036.                              const char *digest_rcvd,
  1037.                              int as_advertised);
  1038. void dirserv_test_reachability(time_t now, int try_all);
  1039. int authdir_wants_to_reject_router(routerinfo_t *ri, const char **msg,
  1040.                                    int complain);
  1041. int dirserv_would_reject_router(routerstatus_t *rs);
  1042. int dirserv_remove_old_statuses(smartlist_t *fps, time_t cutoff);
  1043. int dirserv_have_any_serverdesc(smartlist_t *fps, int spool_src);
  1044. size_t dirserv_estimate_data_size(smartlist_t *fps, int is_serverdescs,
  1045.                                   int compressed);
  1046. int routerstatus_format_entry(char *buf, size_t buf_len,
  1047.                               routerstatus_t *rs, const char *platform,
  1048.                               int first_line_only, int v2_format);
  1049. void dirserv_free_all(void);
  1050. void cached_dir_decref(cached_dir_t *d);
  1051. cached_dir_t *new_cached_dir(char *s, time_t published);
  1052. /********************************* dirvote.c ************************/
  1053. /** Lowest allowable value for VoteSeconds. */
  1054. #define MIN_VOTE_SECONDS 20
  1055. /** Lowest allowable value for DistSeconds. */
  1056. #define MIN_DIST_SECONDS 20
  1057. /** Smallest allowable voting interval. */
  1058. #define MIN_VOTE_INTERVAL 300
  1059. void dirvote_free_all(void);
  1060. /* vote manipulation */
  1061. char *networkstatus_compute_consensus(smartlist_t *votes,
  1062.                                       int total_authorities,
  1063.                                       crypto_pk_env_t *identity_key,
  1064.                                       crypto_pk_env_t *signing_key,
  1065.                                       const char *legacy_identity_key_digest,
  1066.                                       crypto_pk_env_t *legacy_signing_key);
  1067. int networkstatus_add_detached_signatures(networkstatus_t *target,
  1068.                                           ns_detached_signatures_t *sigs,
  1069.                                           const char **msg_out);
  1070. char *networkstatus_get_detached_signatures(networkstatus_t *consensus);
  1071. void ns_detached_signatures_free(ns_detached_signatures_t *s);
  1072. /* cert manipulation */
  1073. authority_cert_t *authority_cert_dup(authority_cert_t *cert);
  1074. /** Describes the schedule by which votes should be generated. */
  1075. typedef struct vote_timing_t {
  1076.   int vote_interval;
  1077.   int n_intervals_valid;
  1078.   int vote_delay;
  1079.   int dist_delay;
  1080. } vote_timing_t;
  1081. /* vote scheduling */
  1082. void dirvote_get_preferred_voting_intervals(vote_timing_t *timing_out);
  1083. time_t dirvote_get_start_of_next_interval(time_t now, int interval);
  1084. void dirvote_recalculate_timing(or_options_t *options, time_t now);
  1085. void dirvote_act(or_options_t *options, time_t now);
  1086. /* invoked on timers and by outside triggers. */
  1087. struct pending_vote_t * dirvote_add_vote(const char *vote_body,
  1088.                                          const char **msg_out,
  1089.                                          int *status_out);
  1090. int dirvote_add_signatures(const char *detached_signatures_body,
  1091.                            const char *source,
  1092.                            const char **msg_out);
  1093. /* Item access */
  1094. const char *dirvote_get_pending_consensus(void);
  1095. const char *dirvote_get_pending_detached_signatures(void);
  1096. #define DGV_BY_ID 1
  1097. #define DGV_INCLUDE_PENDING 2
  1098. #define DGV_INCLUDE_PREVIOUS 4
  1099. const cached_dir_t *dirvote_get_vote(const char *fp, int flags);
  1100. void set_routerstatus_from_routerinfo(routerstatus_t *rs,
  1101.                                       routerinfo_t *ri, time_t now,
  1102.                                       int naming, int exits_can_be_guards,
  1103.                                       int listbadexits, int listbaddirs);
  1104. void router_clear_status_flags(routerinfo_t *ri);
  1105. networkstatus_t *
  1106. dirserv_generate_networkstatus_vote_obj(crypto_pk_env_t *private_key,
  1107.                                         authority_cert_t *cert);
  1108. #ifdef DIRVOTE_PRIVATE
  1109. char *format_networkstatus_vote(crypto_pk_env_t *private_key,
  1110.                                  networkstatus_t *v3_ns);
  1111. char *dirvote_compute_params(smartlist_t *votes);
  1112. #endif
  1113. /********************************* dns.c ***************************/
  1114. int dns_init(void);
  1115. int has_dns_init_failed(void);
  1116. void dns_free_all(void);
  1117. uint32_t dns_clip_ttl(uint32_t ttl);
  1118. int dns_reset(void);
  1119. void connection_dns_remove(edge_connection_t *conn);
  1120. void assert_connection_edge_not_dns_pending(edge_connection_t *conn);
  1121. void assert_all_pending_dns_resolves_ok(void);
  1122. void dns_cancel_pending_resolve(const char *question);
  1123. int dns_resolve(edge_connection_t *exitconn);
  1124. void dns_launch_correctness_checks(void);
  1125. int dns_seems_to_be_broken(void);
  1126. void dns_reset_correctness_checks(void);
  1127. /********************************* dnsserv.c ************************/
  1128. void dnsserv_configure_listener(connection_t *conn);
  1129. void dnsserv_close_listener(connection_t *conn);
  1130. void dnsserv_resolved(edge_connection_t *conn,
  1131.                       int answer_type,
  1132.                       size_t answer_len,
  1133.                       const char *answer,
  1134.                       int ttl);
  1135. void dnsserv_reject_request(edge_connection_t *conn);
  1136. int dnsserv_launch_request(const char *name, int is_reverse);
  1137. /********************************* geoip.c **************************/
  1138. #ifdef GEOIP_PRIVATE
  1139. int geoip_parse_entry(const char *line);
  1140. #endif
  1141. int should_record_bridge_info(or_options_t *options);
  1142. int geoip_load_file(const char *filename, or_options_t *options);
  1143. int geoip_get_country_by_ip(uint32_t ipaddr);
  1144. int geoip_get_n_countries(void);
  1145. const char *geoip_get_country_name(country_t num);
  1146. int geoip_is_loaded(void);
  1147. country_t geoip_get_country(const char *countrycode);
  1148. /** Indicates an action that we might be noting geoip statistics on.
  1149.  * Note that if we're noticing CONNECT, we're a bridge, and if we're noticing
  1150.  * the others, we're not.
  1151.  */
  1152. typedef enum {
  1153.   /** We've noticed a connection as a bridge relay. */
  1154.   GEOIP_CLIENT_CONNECT = 0,
  1155.   /** We've served a networkstatus consensus as a directory server. */
  1156.   GEOIP_CLIENT_NETWORKSTATUS = 1,
  1157.   /** We've served a v2 networkstatus consensus as a directory server. */
  1158.   GEOIP_CLIENT_NETWORKSTATUS_V2 = 2,
  1159. } geoip_client_action_t;
  1160. void geoip_note_client_seen(geoip_client_action_t action,
  1161.                             uint32_t addr, time_t now);
  1162. void geoip_remove_old_clients(time_t cutoff);
  1163. time_t geoip_get_history_start(void);
  1164. char *geoip_get_client_history(time_t now, geoip_client_action_t action);
  1165. char *geoip_get_request_history(time_t now, geoip_client_action_t action);
  1166. int getinfo_helper_geoip(control_connection_t *control_conn,
  1167.                          const char *question, char **answer);
  1168. void geoip_free_all(void);
  1169. void dump_geoip_stats(void);
  1170. /********************************* hibernate.c **********************/
  1171. int accounting_parse_options(or_options_t *options, int validate_only);
  1172. int accounting_is_enabled(or_options_t *options);
  1173. void configure_accounting(time_t now);
  1174. void accounting_run_housekeeping(time_t now);
  1175. void accounting_add_bytes(size_t n_read, size_t n_written, int seconds);
  1176. int accounting_record_bandwidth_usage(time_t now, or_state_t *state);
  1177. void hibernate_begin_shutdown(void);
  1178. int we_are_hibernating(void);
  1179. void consider_hibernation(time_t now);
  1180. int getinfo_helper_accounting(control_connection_t *conn,
  1181.                               const char *question, char **answer);
  1182. void accounting_set_bandwidth_usage_from_state(or_state_t *state);
  1183. /********************************* main.c ***************************/
  1184. extern int has_completed_circuit;
  1185. int connection_add(connection_t *conn);
  1186. int connection_remove(connection_t *conn);
  1187. int connection_in_array(connection_t *conn);
  1188. void add_connection_to_closeable_list(connection_t *conn);
  1189. int connection_is_on_closeable_list(connection_t *conn);
  1190. smartlist_t *get_connection_array(void);
  1191. void connection_watch_events(connection_t *conn, short events);
  1192. int connection_is_reading(connection_t *conn);
  1193. void connection_stop_reading(connection_t *conn);
  1194. void connection_start_reading(connection_t *conn);
  1195. int connection_is_writing(connection_t *conn);
  1196. void connection_stop_writing(connection_t *conn);
  1197. void connection_start_writing(connection_t *conn);
  1198. void connection_stop_reading_from_linked_conn(connection_t *conn);
  1199. void directory_all_unreachable(time_t now);
  1200. void directory_info_has_arrived(time_t now, int from_cache);
  1201. void ip_address_changed(int at_interface);
  1202. void dns_servers_relaunch_checks(void);
  1203. void control_signal_act(int the_signal);
  1204. void handle_signals(int is_parent);
  1205. int try_locking(or_options_t *options, int err_if_locked);
  1206. int have_lockfile(void);
  1207. void release_lockfile(void);
  1208. void tor_cleanup(void);
  1209. void tor_free_all(int postfork);
  1210. int tor_main(int argc, char *argv[]);
  1211. #ifdef MAIN_PRIVATE
  1212. int do_main_loop(void);
  1213. int do_list_fingerprint(void);
  1214. void do_hash_password(void);
  1215. int tor_init(int argc, char **argv);
  1216. #endif
  1217. /********************************* networkstatus.c *********************/
  1218. /** How old do we allow a v2 network-status to get before removing it
  1219.  * completely? */
  1220. #define MAX_NETWORKSTATUS_AGE (10*24*60*60)
  1221. /** Location where we found a v2 networkstatus. */
  1222. typedef enum {
  1223.   NS_FROM_CACHE, NS_FROM_DIR_BY_FP, NS_FROM_DIR_ALL, NS_GENERATED
  1224. } v2_networkstatus_source_t;
  1225. /** Possible statuses of a version of Tor, given opinions from the directory
  1226.  * servers. */
  1227. typedef enum version_status_t {
  1228.   VS_RECOMMENDED=0, /**< This version is listed as recommended. */
  1229.   VS_OLD=1, /**< This version is older than any recommended version. */
  1230.   VS_NEW=2, /**< This version is newer than any recommended version. */
  1231.   VS_NEW_IN_SERIES=3, /**< This version is newer than any recommended version
  1232.                        * in its series, but later recommended versions exist.
  1233.                        */
  1234.   VS_UNRECOMMENDED=4, /**< This version is not recommended (general case). */
  1235.   VS_EMPTY=5, /**< The version list was empty; no agreed-on versions. */
  1236.   VS_UNKNOWN, /**< We have no idea. */
  1237. } version_status_t;
  1238. void networkstatus_reset_warnings(void);
  1239. void networkstatus_reset_download_failures(void);
  1240. int router_reload_v2_networkstatus(void);
  1241. int router_reload_consensus_networkstatus(void);
  1242. void routerstatus_free(routerstatus_t *rs);
  1243. void networkstatus_v2_free(networkstatus_v2_t *ns);
  1244. void networkstatus_vote_free(networkstatus_t *ns);
  1245. networkstatus_voter_info_t *networkstatus_get_voter_by_id(
  1246.                                        networkstatus_t *vote,
  1247.                                        const char *identity);
  1248. int networkstatus_check_consensus_signature(networkstatus_t *consensus,
  1249.                                             int warn);
  1250. int networkstatus_check_voter_signature(networkstatus_t *consensus,
  1251.                                         networkstatus_voter_info_t *voter,
  1252.                                         authority_cert_t *cert);
  1253. char *networkstatus_get_cache_filename(const char *identity_digest);
  1254. int router_set_networkstatus_v2(const char *s, time_t arrived_at,
  1255.                              v2_networkstatus_source_t source,
  1256.                              smartlist_t *requested_fingerprints);
  1257. void networkstatus_v2_list_clean(time_t now);
  1258. routerstatus_t *networkstatus_v2_find_entry(networkstatus_v2_t *ns,
  1259.                                          const char *digest);
  1260. routerstatus_t *networkstatus_vote_find_entry(networkstatus_t *ns,
  1261.                                               const char *digest);
  1262. int networkstatus_vote_find_entry_idx(networkstatus_t *ns,
  1263.                                       const char *digest, int *found_out);
  1264. const smartlist_t *networkstatus_get_v2_list(void);
  1265. download_status_t *router_get_dl_status_by_descriptor_digest(const char *d);
  1266. routerstatus_t *router_get_consensus_status_by_id(const char *digest);
  1267. routerstatus_t *router_get_consensus_status_by_descriptor_digest(
  1268.                                                         const char *digest);
  1269. routerstatus_t *router_get_consensus_status_by_nickname(const char *nickname,
  1270.                                                        int warn_if_unnamed);
  1271. const char *networkstatus_get_router_digest_by_nickname(const char *nickname);
  1272. int networkstatus_nickname_is_unnamed(const char *nickname);
  1273. void networkstatus_consensus_download_failed(int status_code);
  1274. void update_consensus_networkstatus_fetch_time(time_t now);
  1275. int should_delay_dir_fetches(or_options_t *options);
  1276. void update_networkstatus_downloads(time_t now);
  1277. void update_certificate_downloads(time_t now);
  1278. int consensus_is_waiting_for_certs(void);
  1279. networkstatus_v2_t *networkstatus_v2_get_by_digest(const char *digest);
  1280. networkstatus_t *networkstatus_get_latest_consensus(void);
  1281. networkstatus_t *networkstatus_get_live_consensus(time_t now);
  1282. networkstatus_t *networkstatus_get_reasonably_live_consensus(time_t now);
  1283. #define NSSET_FROM_CACHE 1
  1284. #define NSSET_WAS_WAITING_FOR_CERTS 2
  1285. #define NSSET_DONT_DOWNLOAD_CERTS 4
  1286. #define NSSET_ACCEPT_OBSOLETE 8
  1287. int networkstatus_set_current_consensus(const char *consensus, unsigned flags);
  1288. void networkstatus_note_certs_arrived(void);
  1289. void routers_update_all_from_networkstatus(time_t now, int dir_version);
  1290. void routerstatus_list_update_from_consensus_networkstatus(time_t now);
  1291. void routers_update_status_from_consensus_networkstatus(smartlist_t *routers,
  1292.                                                         int reset_failures);
  1293. void signed_descs_update_status_from_consensus_networkstatus(
  1294.                                                          smartlist_t *descs);
  1295. char *networkstatus_getinfo_helper_single(routerstatus_t *rs);
  1296. char *networkstatus_getinfo_by_purpose(const char *purpose_string, time_t now);
  1297. void networkstatus_dump_bridge_status_to_file(time_t now);
  1298. int32_t networkstatus_get_param(networkstatus_t *ns, const char *param_name,
  1299.                                 int32_t default_val);
  1300. int getinfo_helper_networkstatus(control_connection_t *conn,
  1301.                                  const char *question, char **answer);
  1302. void networkstatus_free_all(void);
  1303. /********************************* ntmain.c ***************************/
  1304. #ifdef MS_WINDOWS
  1305. #define NT_SERVICE
  1306. #endif
  1307. #ifdef NT_SERVICE
  1308. int nt_service_parse_options(int argc, char **argv, int *should_exit);
  1309. int nt_service_is_stopping(void);
  1310. void nt_service_set_state(DWORD state);
  1311. #else
  1312. #define nt_service_is_stopping() (0)
  1313. #endif
  1314. /********************************* onion.c ***************************/
  1315. int onion_pending_add(or_circuit_t *circ, char *onionskin);
  1316. or_circuit_t *onion_next_task(char **onionskin_out);
  1317. void onion_pending_remove(or_circuit_t *circ);
  1318. int onion_skin_create(crypto_pk_env_t *router_key,
  1319.                       crypto_dh_env_t **handshake_state_out,
  1320.                       char *onion_skin_out);
  1321. int onion_skin_server_handshake(const char *onion_skin,
  1322.                                 crypto_pk_env_t *private_key,
  1323.                                 crypto_pk_env_t *prev_private_key,
  1324.                                 char *handshake_reply_out,
  1325.                                 char *key_out,
  1326.                                 size_t key_out_len);
  1327. int onion_skin_client_handshake(crypto_dh_env_t *handshake_state,
  1328.                                 const char *handshake_reply,
  1329.                                 char *key_out,
  1330.                                 size_t key_out_len);
  1331. int fast_server_handshake(const char *key_in,
  1332.                           char *handshake_reply_out,
  1333.                           char *key_out,
  1334.                           size_t key_out_len);
  1335. int fast_client_handshake(const char *handshake_state,
  1336.                           const char *handshake_reply_out,
  1337.                           char *key_out,
  1338.                           size_t key_out_len);
  1339. void clear_pending_onions(void);
  1340. /********************************* policies.c ************************/
  1341. /* (length of "accept 255.255.255.255/255.255.255.255:65535-65535n" plus a
  1342.  * NUL.)
  1343.  */
  1344. #define POLICY_BUF_LEN 52
  1345. /** Outcome of applying an address policy to an address. */
  1346. typedef enum {
  1347.   /** The address was accepted */
  1348.   ADDR_POLICY_ACCEPTED=0,
  1349.   /** The address was rejected */
  1350.   ADDR_POLICY_REJECTED=-1,
  1351.   /** Part of the address was unknown, but as far as we can tell, it was
  1352.    * accepted. */
  1353.   ADDR_POLICY_PROBABLY_ACCEPTED=1,
  1354.   /** Part of the address was unknown, but as far as we can tell, it was
  1355.    * rejected. */
  1356.   ADDR_POLICY_PROBABLY_REJECTED=2
  1357. } addr_policy_result_t;
  1358. int firewall_is_fascist_or(void);
  1359. int fascist_firewall_allows_address_or(const tor_addr_t *addr, uint16_t port);
  1360. int fascist_firewall_allows_or(routerinfo_t *ri);
  1361. int fascist_firewall_allows_address_dir(const tor_addr_t *addr, uint16_t port);
  1362. int dir_policy_permits_address(const tor_addr_t *addr);
  1363. int socks_policy_permits_address(const tor_addr_t *addr);
  1364. int authdir_policy_permits_address(uint32_t addr, uint16_t port);
  1365. int authdir_policy_valid_address(uint32_t addr, uint16_t port);
  1366. int authdir_policy_baddir_address(uint32_t addr, uint16_t port);
  1367. int authdir_policy_badexit_address(uint32_t addr, uint16_t port);
  1368. int validate_addr_policies(or_options_t *options, char **msg);
  1369. void policy_expand_private(smartlist_t **policy);
  1370. int policies_parse_from_options(or_options_t *options);
  1371. addr_policy_t *addr_policy_get_canonical_entry(addr_policy_t *ent);
  1372. int cmp_addr_policies(smartlist_t *a, smartlist_t *b);
  1373. addr_policy_result_t compare_tor_addr_to_addr_policy(const tor_addr_t *addr,
  1374.                               uint16_t port, const smartlist_t *policy);
  1375. addr_policy_result_t compare_addr_to_addr_policy(uint32_t addr,
  1376.                               uint16_t port, const smartlist_t *policy);
  1377. int policies_parse_exit_policy(config_line_t *cfg, smartlist_t **dest,
  1378.                                int rejectprivate, const char *local_address);
  1379. void policies_set_router_exitpolicy_to_reject_all(routerinfo_t *exitrouter);
  1380. int exit_policy_is_general_exit(smartlist_t *policy);
  1381. int policy_is_reject_star(const smartlist_t *policy);
  1382. int getinfo_helper_policies(control_connection_t *conn,
  1383.                             const char *question, char **answer);
  1384. int policy_write_item(char *buf, size_t buflen, addr_policy_t *item,
  1385.                       int format_for_desc);
  1386. void addr_policy_list_free(smartlist_t *p);
  1387. void addr_policy_free(addr_policy_t *p);
  1388. void policies_free_all(void);
  1389. char *policy_summarize(smartlist_t *policy);
  1390. /********************************* reasons.c ***************************/
  1391. const char *stream_end_reason_to_control_string(int reason);
  1392. const char *stream_end_reason_to_string(int reason);
  1393. socks5_reply_status_t stream_end_reason_to_socks5_response(int reason);
  1394. uint8_t errno_to_stream_end_reason(int e);
  1395. const char *orconn_end_reason_to_control_string(int r);
  1396. int tls_error_to_orconn_end_reason(int e);
  1397. int errno_to_orconn_end_reason(int e);
  1398. const char *circuit_end_reason_to_control_string(int reason);
  1399. /********************************* relay.c ***************************/
  1400. extern uint64_t stats_n_relay_cells_relayed;
  1401. extern uint64_t stats_n_relay_cells_delivered;
  1402. int circuit_receive_relay_cell(cell_t *cell, circuit_t *circ,
  1403.                                cell_direction_t cell_direction);
  1404. void relay_header_pack(char *dest, const relay_header_t *src);
  1405. void relay_header_unpack(relay_header_t *dest, const char *src);
  1406. int relay_send_command_from_edge(streamid_t stream_id, circuit_t *circ,
  1407.                                uint8_t relay_command, const char *payload,
  1408.                                size_t payload_len, crypt_path_t *cpath_layer);
  1409. int connection_edge_send_command(edge_connection_t *fromconn,
  1410.                                  uint8_t relay_command, const char *payload,
  1411.                                  size_t payload_len);
  1412. int connection_edge_package_raw_inbuf(edge_connection_t *conn,
  1413.                                       int package_partial);
  1414. void connection_edge_consider_sending_sendme(edge_connection_t *conn);
  1415. extern uint64_t stats_n_data_cells_packaged;
  1416. extern uint64_t stats_n_data_bytes_packaged;
  1417. extern uint64_t stats_n_data_cells_received;
  1418. extern uint64_t stats_n_data_bytes_received;
  1419. void init_cell_pool(void);
  1420. void free_cell_pool(void);
  1421. void clean_cell_pool(void);
  1422. void dump_cell_pool_usage(int severity);
  1423. void cell_queue_clear(cell_queue_t *queue);
  1424. void cell_queue_append(cell_queue_t *queue, packed_cell_t *cell);
  1425. void cell_queue_append_packed_copy(cell_queue_t *queue, const cell_t *cell);
  1426. void append_cell_to_circuit_queue(circuit_t *circ, or_connection_t *orconn,
  1427.                                   cell_t *cell, cell_direction_t direction);
  1428. void connection_or_unlink_all_active_circs(or_connection_t *conn);
  1429. int connection_or_flush_from_first_active_circuit(or_connection_t *conn,
  1430.                                                   int max, time_t now);
  1431. void assert_active_circuits_ok(or_connection_t *orconn);
  1432. void make_circuit_inactive_on_conn(circuit_t *circ, or_connection_t *conn);
  1433. void make_circuit_active_on_conn(circuit_t *circ, or_connection_t *conn);
  1434. int append_address_to_payload(char *payload_out, const tor_addr_t *addr);
  1435. const char *decode_address_from_payload(tor_addr_t *addr_out,
  1436.                                         const char *payload,
  1437.                                         int payload_len);
  1438. /********************************* rephist.c ***************************/
  1439. void rep_hist_init(void);
  1440. void rep_hist_note_connect_failed(const char* nickname, time_t when);
  1441. void rep_hist_note_connect_succeeded(const char* nickname, time_t when);
  1442. void rep_hist_note_disconnect(const char* nickname, time_t when);
  1443. void rep_hist_note_connection_died(const char* nickname, time_t when);
  1444. void rep_hist_note_extend_succeeded(const char *from_name,
  1445.                                     const char *to_name);
  1446. void rep_hist_note_extend_failed(const char *from_name, const char *to_name);
  1447. void rep_hist_dump_stats(time_t now, int severity);
  1448. void rep_hist_note_bytes_read(size_t num_bytes, time_t when);
  1449. void rep_hist_note_bytes_written(size_t num_bytes, time_t when);
  1450. int rep_hist_bandwidth_assess(void);
  1451. char *rep_hist_get_bandwidth_lines(int for_extrainfo);
  1452. void rep_hist_update_state(or_state_t *state);
  1453. int rep_hist_load_state(or_state_t *state, char **err);
  1454. void rep_history_clean(time_t before);
  1455. void rep_hist_note_router_reachable(const char *id, time_t when);
  1456. void rep_hist_note_router_unreachable(const char *id, time_t when);
  1457. int rep_hist_record_mtbf_data(time_t now, int missing_means_down);
  1458. int rep_hist_load_mtbf_data(time_t now);
  1459. time_t rep_hist_downrate_old_runs(time_t now);
  1460. double rep_hist_get_stability(const char *id, time_t when);
  1461. double rep_hist_get_weighted_fractional_uptime(const char *id, time_t when);
  1462. long rep_hist_get_weighted_time_known(const char *id, time_t when);
  1463. int rep_hist_have_measured_enough_stability(void);
  1464. const char *rep_hist_get_router_stability_doc(time_t now);
  1465. void rep_hist_note_used_port(time_t now, uint16_t port);
  1466. smartlist_t *rep_hist_get_predicted_ports(time_t now);
  1467. void rep_hist_note_used_resolve(time_t now);
  1468. void rep_hist_note_used_internal(time_t now, int need_uptime,
  1469.                                  int need_capacity);
  1470. int rep_hist_get_predicted_internal(time_t now, int *need_uptime,
  1471.                                     int *need_capacity);
  1472. int any_predicted_circuits(time_t now);
  1473. int rep_hist_circbuilding_dormant(time_t now);
  1474. /** Possible public/private key operations in Tor: used to keep track of where
  1475.  * we're spending our time. */
  1476. typedef enum {
  1477.   SIGN_DIR, SIGN_RTR,
  1478.   VERIFY_DIR, VERIFY_RTR,
  1479.   ENC_ONIONSKIN, DEC_ONIONSKIN,
  1480.   TLS_HANDSHAKE_C, TLS_HANDSHAKE_S,
  1481.   REND_CLIENT, REND_MID, REND_SERVER,
  1482. } pk_op_t;
  1483. void note_crypto_pk_op(pk_op_t operation);
  1484. void dump_pk_ops(int severity);
  1485. void rep_hist_free_all(void);
  1486. /* for hidden service usage statistics */
  1487. void hs_usage_note_publish_total(const char *service_id, time_t now);
  1488. void hs_usage_note_publish_novel(const char *service_id, time_t now);
  1489. void hs_usage_note_fetch_total(const char *service_id, time_t now);
  1490. void hs_usage_note_fetch_successful(const char *service_id, time_t now);
  1491. void hs_usage_write_statistics_to_file(time_t now);
  1492. void hs_usage_free_all(void);
  1493. /********************************* rendclient.c ***************************/
  1494. void rend_client_introcirc_has_opened(origin_circuit_t *circ);
  1495. void rend_client_rendcirc_has_opened(origin_circuit_t *circ);
  1496. int rend_client_introduction_acked(origin_circuit_t *circ, const char *request,
  1497.                                    size_t request_len);
  1498. void rend_client_refetch_renddesc(const char *query);
  1499. void rend_client_refetch_v2_renddesc(const rend_data_t *rend_query);
  1500. int rend_client_remove_intro_point(extend_info_t *failed_intro,
  1501.                                    const rend_data_t *rend_query);
  1502. int rend_client_rendezvous_acked(origin_circuit_t *circ, const char *request,
  1503.                                  size_t request_len);
  1504. int rend_client_receive_rendezvous(origin_circuit_t *circ, const char *request,
  1505.                                    size_t request_len);
  1506. void rend_client_desc_trynow(const char *query, int rend_version);
  1507. extend_info_t *rend_client_get_random_intro(const rend_data_t *rend_query);
  1508. int rend_client_send_introduction(origin_circuit_t *introcirc,
  1509.                                   origin_circuit_t *rendcirc);
  1510. int rend_parse_service_authorization(or_options_t *options,
  1511.                                      int validate_only);
  1512. rend_service_authorization_t *rend_client_lookup_service_authorization(
  1513.                                                 const char *onion_address);
  1514. void rend_service_authorization_free_all(void);
  1515. rend_data_t *rend_data_dup(const rend_data_t *request);
  1516. /********************************* rendcommon.c ***************************/
  1517. /** Hidden-service side configuration of client authorization. */
  1518. typedef struct rend_authorized_client_t {
  1519.   char *client_name;
  1520.   char descriptor_cookie[REND_DESC_COOKIE_LEN];
  1521.   crypto_pk_env_t *client_key;
  1522. } rend_authorized_client_t;
  1523. /** ASCII-encoded v2 hidden service descriptor. */
  1524. typedef struct rend_encoded_v2_service_descriptor_t {
  1525.   char desc_id[DIGEST_LEN]; /**< Descriptor ID. */
  1526.   char *desc_str; /**< Descriptor string. */
  1527. } rend_encoded_v2_service_descriptor_t;
  1528. /** Introduction point information. */
  1529. typedef struct rend_intro_point_t {
  1530.   extend_info_t *extend_info; /**< Extend info of this introduction point. */
  1531.   crypto_pk_env_t *intro_key; /**< Introduction key that replaces the service
  1532.                                * key, if this descriptor is V2. */
  1533. } rend_intro_point_t;
  1534. /** Information used to connect to a hidden service. */
  1535. typedef struct rend_service_descriptor_t {
  1536.   crypto_pk_env_t *pk; /**< This service's public key. */
  1537.   int version; /**< Version of the descriptor format: 0 or 2. */
  1538.   time_t timestamp; /**< Time when the descriptor was generated. */
  1539.   uint16_t protocols; /**< Bitmask: which rendezvous protocols are supported?
  1540.                        * (We allow bits '0', '1', and '2' to be set.) */
  1541.   /** List of the service's introduction points.  Elements are removed if
  1542.    * introduction attempts fail. */
  1543.   smartlist_t *intro_nodes;
  1544.   /** Has descriptor been uploaded to all hidden service directories? */
  1545.   int all_uploads_performed;
  1546.   /** List of hidden service directories to which an upload request for
  1547.    * this descriptor could be sent. Smartlist exists only when at least one
  1548.    * of the previous upload requests failed (otherwise it's not important
  1549.    * to know which uploads succeeded and which not). */
  1550.   smartlist_t *successful_uploads;
  1551. } rend_service_descriptor_t;
  1552. /** Free all storage associated with <b>data</b> */
  1553. static INLINE void
  1554. rend_data_free(rend_data_t *data)
  1555. {
  1556.   tor_free(data);
  1557. }
  1558. int rend_cmp_service_ids(const char *one, const char *two);
  1559. void rend_process_relay_cell(circuit_t *circ, const crypt_path_t *layer_hint,
  1560.                              int command, size_t length, const char *payload);
  1561. void rend_service_descriptor_free(rend_service_descriptor_t *desc);
  1562. int rend_encode_service_descriptor(rend_service_descriptor_t *desc,
  1563.                                    crypto_pk_env_t *key,
  1564.                                    char **str_out,
  1565.                                    size_t *len_out);
  1566. rend_service_descriptor_t *rend_parse_service_descriptor(const char *str,
  1567.                                                          size_t len);
  1568. int rend_get_service_id(crypto_pk_env_t *pk, char *out);
  1569. void rend_encoded_v2_service_descriptor_free(
  1570.                                rend_encoded_v2_service_descriptor_t *desc);
  1571. void rend_intro_point_free(rend_intro_point_t *intro);
  1572. /** A cached rendezvous descriptor. */
  1573. typedef struct rend_cache_entry_t {
  1574.   size_t len; /**< Length of <b>desc</b> */
  1575.   time_t received; /**< When was the descriptor received? */
  1576.   char *desc; /**< Service descriptor */
  1577.   rend_service_descriptor_t *parsed; /**< Parsed value of 'desc' */
  1578. } rend_cache_entry_t;
  1579. void rend_cache_init(void);
  1580. void rend_cache_clean(void);
  1581. void rend_cache_clean_v2_descs_as_dir(void);
  1582. void rend_cache_free_all(void);
  1583. int rend_valid_service_id(const char *query);
  1584. int rend_cache_lookup_desc(const char *query, int version, const char **desc,
  1585.                            size_t *desc_len);
  1586. int rend_cache_lookup_entry(const char *query, int version,
  1587.                             rend_cache_entry_t **entry_out);
  1588. int rend_cache_lookup_v2_desc_as_dir(const char *query, const char **desc);
  1589. int rend_cache_store(const char *desc, size_t desc_len, int published);
  1590. int rend_cache_store_v2_desc_as_client(const char *desc,
  1591.                                        const rend_data_t *rend_query);
  1592. int rend_cache_store_v2_desc_as_dir(const char *desc);
  1593. int rend_cache_size(void);
  1594. int rend_encode_v2_descriptors(smartlist_t *descs_out,
  1595.                                rend_service_descriptor_t *desc, time_t now,
  1596.                                uint8_t period, rend_auth_type_t auth_type,
  1597.                                crypto_pk_env_t *client_key,
  1598.                                smartlist_t *client_cookies);
  1599. int rend_compute_v2_desc_id(char *desc_id_out, const char *service_id,
  1600.                             const char *descriptor_cookie,
  1601.                             time_t now, uint8_t replica);
  1602. int rend_id_is_in_interval(const char *a, const char *b, const char *c);
  1603. void rend_get_descriptor_id_bytes(char *descriptor_id_out,
  1604.                                   const char *service_id,
  1605.                                   const char *secret_id_part);
  1606. /********************************* rendservice.c ***************************/
  1607. int num_rend_services(void);
  1608. int rend_config_services(or_options_t *options, int validate_only);
  1609. int rend_service_load_keys(void);
  1610. void rend_services_init(void);
  1611. void rend_services_introduce(void);
  1612. void rend_consider_services_upload(time_t now);
  1613. void rend_hsdir_routers_changed(void);
  1614. void rend_consider_descriptor_republication(void);
  1615. void rend_service_intro_has_opened(origin_circuit_t *circuit);
  1616. int rend_service_intro_established(origin_circuit_t *circuit,
  1617.                                    const char *request,
  1618.                                    size_t request_len);
  1619. void rend_service_rendezvous_has_opened(origin_circuit_t *circuit);
  1620. int rend_service_introduce(origin_circuit_t *circuit, const char *request,
  1621.                            size_t request_len);
  1622. void rend_service_relaunch_rendezvous(origin_circuit_t *oldcirc);
  1623. int rend_service_set_connection_addr_port(edge_connection_t *conn,
  1624.                                           origin_circuit_t *circ);
  1625. void rend_service_dump_stats(int severity);
  1626. void rend_service_free_all(void);
  1627. /********************************* rendmid.c *******************************/
  1628. int rend_mid_establish_intro(or_circuit_t *circ, const char *request,
  1629.                              size_t request_len);
  1630. int rend_mid_introduce(or_circuit_t *circ, const char *request,
  1631.                        size_t request_len);
  1632. int rend_mid_establish_rendezvous(or_circuit_t *circ, const char *request,
  1633.                                   size_t request_len);
  1634. int rend_mid_rendezvous(or_circuit_t *circ, const char *request,
  1635.                         size_t request_len);
  1636. /********************************* router.c ***************************/
  1637. crypto_pk_env_t *get_onion_key(void);
  1638. time_t get_onion_key_set_at(void);
  1639. void set_identity_key(crypto_pk_env_t *k);
  1640. crypto_pk_env_t *get_identity_key(void);
  1641. int identity_key_is_set(void);
  1642. authority_cert_t *get_my_v3_authority_cert(void);
  1643. crypto_pk_env_t *get_my_v3_authority_signing_key(void);
  1644. authority_cert_t *get_my_v3_legacy_cert(void);
  1645. crypto_pk_env_t *get_my_v3_legacy_signing_key(void);
  1646. void dup_onion_keys(crypto_pk_env_t **key, crypto_pk_env_t **last);
  1647. void rotate_onion_key(void);
  1648. crypto_pk_env_t *init_key_from_file(const char *fname, int generate,
  1649.                                     int severity);
  1650. void v3_authority_check_key_expiry(void);
  1651. int init_keys(void);
  1652. int check_whether_orport_reachable(void);
  1653. int check_whether_dirport_reachable(void);
  1654. void consider_testing_reachability(int test_or, int test_dir);
  1655. void router_orport_found_reachable(void);
  1656. void router_dirport_found_reachable(void);
  1657. void router_perform_bandwidth_test(int num_circs, time_t now);
  1658. int authdir_mode(or_options_t *options);
  1659. int authdir_mode_v1(or_options_t *options);
  1660. int authdir_mode_v2(or_options_t *options);
  1661. int authdir_mode_v3(or_options_t *options);
  1662. int authdir_mode_any_main(or_options_t *options);
  1663. int authdir_mode_any_nonhidserv(or_options_t *options);
  1664. int authdir_mode_handles_descs(or_options_t *options, int purpose);
  1665. int authdir_mode_publishes_statuses(or_options_t *options);
  1666. int authdir_mode_tests_reachability(or_options_t *options);
  1667. int authdir_mode_bridge(or_options_t *options);
  1668. int clique_mode(or_options_t *options);
  1669. int server_mode(or_options_t *options);
  1670. int advertised_server_mode(void);
  1671. int proxy_mode(or_options_t *options);
  1672. void consider_publishable_server(int force);
  1673. int router_is_clique_mode(routerinfo_t *router);
  1674. void router_upload_dir_desc_to_dirservers(int force);
  1675. void mark_my_descriptor_dirty_if_older_than(time_t when);
  1676. void mark_my_descriptor_dirty(void);
  1677. void check_descriptor_bandwidth_changed(time_t now);
  1678. void check_descriptor_ipaddress_changed(time_t now);
  1679. void router_new_address_suggestion(const char *suggestion,
  1680.                                    const dir_connection_t *d_conn);
  1681. int router_compare_to_my_exit_policy(edge_connection_t *conn);
  1682. routerinfo_t *router_get_my_routerinfo(void);
  1683. extrainfo_t *router_get_my_extrainfo(void);
  1684. const char *router_get_my_descriptor(void);
  1685. int router_digest_is_me(const char *digest);
  1686. int router_extrainfo_digest_is_me(const char *digest);
  1687. int router_is_me(routerinfo_t *router);
  1688. int router_fingerprint_is_me(const char *fp);
  1689. int router_pick_published_address(or_options_t *options, uint32_t *addr);
  1690. int router_rebuild_descriptor(int force);
  1691. int router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
  1692.                                  crypto_pk_env_t *ident_key);
  1693. int extrainfo_dump_to_string(char *s, size_t maxlen, extrainfo_t *extrainfo,
  1694.                              crypto_pk_env_t *ident_key);
  1695. char *extrainfo_get_client_geoip_summary(time_t);
  1696. int is_legal_nickname(const char *s);
  1697. int is_legal_nickname_or_hexdigest(const char *s);
  1698. int is_legal_hexdigest(const char *s);
  1699. void router_get_verbose_nickname(char *buf, const routerinfo_t *router);
  1700. void routerstatus_get_verbose_nickname(char *buf,
  1701.                                        const routerstatus_t *router);
  1702. void router_reset_warnings(void);
  1703. void router_reset_reachability(void);
  1704. void router_free_all(void);
  1705. const char *router_purpose_to_string(uint8_t p);
  1706. uint8_t router_purpose_from_string(const char *s);
  1707. #ifdef ROUTER_PRIVATE
  1708. /* Used only by router.c and test.c */
  1709. void get_platform_str(char *platform, size_t len);
  1710. #endif
  1711. /********************************* routerlist.c ***************************/
  1712. /** Represents information about a single trusted directory server. */
  1713. typedef struct trusted_dir_server_t {
  1714.   char *description;
  1715.   char *nickname;
  1716.   char *address; /**< Hostname. */
  1717.   uint32_t addr; /**< IPv4 address. */
  1718.   uint16_t dir_port; /**< Directory port. */
  1719.   uint16_t or_port; /**< OR port: Used for tunneling connections. */
  1720.   char digest[DIGEST_LEN]; /**< Digest of identity key. */
  1721.   char v3_identity_digest[DIGEST_LEN]; /**< Digest of v3 (authority only,
  1722.                                         * high-security) identity key. */
  1723.   unsigned int is_running:1; /**< True iff we think this server is running. */
  1724.   /** True iff this server has accepted the most recent server descriptor
  1725.    * we tried to upload to it. */
  1726.   unsigned int has_accepted_serverdesc:1;
  1727.   /** What kind of authority is this? (Bitfield.) */
  1728.   authority_type_t type;
  1729.   download_status_t v2_ns_dl_status; /**< Status of downloading this server's
  1730.                                * v2 network status. */
  1731.   time_t addr_current_at; /**< When was the document that we derived the
  1732.                            * address information from published? */
  1733.   routerstatus_t fake_status; /**< Used when we need to pass this trusted
  1734.                                * dir_server_t to directory_initiate_command_*
  1735.                                * as a routerstatus_t.  Not updated by the
  1736.                                * router-status management code!
  1737.                                **/
  1738. } trusted_dir_server_t;
  1739. #define ROUTER_REQUIRED_MIN_BANDWIDTH (20*1024)
  1740. #define ROUTER_MAX_DECLARED_BANDWIDTH INT32_MAX
  1741. int get_n_authorities(authority_type_t type);
  1742. int trusted_dirs_reload_certs(void);
  1743. int trusted_dirs_load_certs_from_string(const char *contents, int from_store,
  1744.                                         int flush);
  1745. void trusted_dirs_flush_certs_to_disk(void);
  1746. authority_cert_t *authority_cert_get_newest_by_id(const char *id_digest);
  1747. authority_cert_t *authority_cert_get_by_sk_digest(const char *sk_digest);
  1748. authority_cert_t *authority_cert_get_by_digests(const char *id_digest,
  1749.                                                 const char *sk_digest);
  1750. void authority_cert_get_all(smartlist_t *certs_out);
  1751. void authority_cert_dl_failed(const char *id_digest, int status);
  1752. void authority_certs_fetch_missing(networkstatus_t *status, time_t now);
  1753. int router_reload_router_list(void);
  1754. smartlist_t *router_get_trusted_dir_servers(void);
  1755. /* Flags for pick_directory_server and pick_trusteddirserver. */
  1756. /** Flag to indicate that we should not automatically be willing to use
  1757.  * ourself to answer a directory request.
  1758.  * Passed to router_pick_directory_server (et al).*/
  1759. #define PDS_ALLOW_SELF                 (1<<0)
  1760. /** Flag to indicate that if no servers seem to be up, we should mark all
  1761.  * directory servers as up and try again.
  1762.  * Passed to router_pick_directory_server (et al).*/
  1763. #define PDS_RETRY_IF_NO_SERVERS        (1<<1)
  1764. /** Flag to indicate that we should not exclude directory servers that
  1765.  * our ReachableAddress settings would exclude.  This usually means that
  1766.  * we're going to connect to the server over Tor, and so we don't need to
  1767.  * worry about our firewall telling us we can't.
  1768.  * Passed to router_pick_directory_server (et al).*/
  1769. #define PDS_IGNORE_FASCISTFIREWALL     (1<<2)
  1770. /** Flag to indicate that we should not use any directory authority to which
  1771.  * we have an existing directory connection for downloading server descriptors
  1772.  * or extrainfo documents.
  1773.  *
  1774.  * Passed to router_pick_directory_server (et al)
  1775.  *
  1776.  * [XXXX NOTE: This option is only implemented for pick_trusteddirserver,
  1777.  *  not pick_directory_server.  If we make it work on pick_directory_server
  1778.  *  too, we could conservatively make it only prevent multiple fetches to
  1779.  *  the same authority, or we could aggressively make it prevent multiple
  1780.  *  fetches to _any_ single directory server.]
  1781.  */
  1782. #define PDS_NO_EXISTING_SERVERDESC_FETCH (1<<3)
  1783. #define _PDS_PREFER_TUNNELED_DIR_CONNS (1<<16)
  1784. routerstatus_t *router_pick_directory_server(authority_type_t type, int flags);
  1785. trusted_dir_server_t *router_get_trusteddirserver_by_digest(const char *d);
  1786. trusted_dir_server_t *trusteddirserver_get_by_v3_auth_digest(const char *d);
  1787. routerstatus_t *router_pick_trusteddirserver(authority_type_t type, int flags);
  1788. int router_get_my_share_of_directory_requests(double *v2_share_out,
  1789.                                               double *v3_share_out);
  1790. void router_reset_status_download_failures(void);
  1791. void routerlist_add_family(smartlist_t *sl, routerinfo_t *router);
  1792. int routers_in_same_family(routerinfo_t *r1, routerinfo_t *r2);
  1793. void add_nickname_list_to_smartlist(smartlist_t *sl, const char *list,
  1794.                                     int must_be_running);
  1795. int router_nickname_is_in_list(routerinfo_t *router, const char *list);
  1796. routerinfo_t *routerlist_find_my_routerinfo(void);
  1797. routerinfo_t *router_find_exact_exit_enclave(const char *address,
  1798.                                              uint16_t port);
  1799. int router_is_unreliable(routerinfo_t *router, int need_uptime,
  1800.                          int need_capacity, int need_guard);
  1801. uint32_t router_get_advertised_bandwidth(routerinfo_t *router);
  1802. uint32_t router_get_advertised_bandwidth_capped(routerinfo_t *router);
  1803. /** Possible ways to weight routers when choosing one randomly.  See
  1804.  * routerlist_sl_choose_by_bandwidth() for more information.*/
  1805. typedef enum {
  1806.   NO_WEIGHTING, WEIGHT_FOR_EXIT, WEIGHT_FOR_GUARD
  1807. } bandwidth_weight_rule_t;
  1808. routerinfo_t *routerlist_sl_choose_by_bandwidth(smartlist_t *sl,
  1809.                                                 bandwidth_weight_rule_t rule);
  1810. routerstatus_t *routerstatus_sl_choose_by_bandwidth(smartlist_t *sl);
  1811. /** Flags to be passed to control router_choose_random_node() to indicate what
  1812.  * kind of nodes to pick according to what algorithm. */
  1813. typedef enum {
  1814.   CRN_NEED_UPTIME = 1<<0,
  1815.   CRN_NEED_CAPACITY = 1<<1,
  1816.   CRN_NEED_GUARD = 1<<2,
  1817.   CRN_ALLOW_INVALID = 1<<3,
  1818.   /* XXXX not used, apparently. */
  1819.   CRN_STRICT_PREFERRED = 1<<4,
  1820.   /* XXXX not used, apparently. */
  1821.   CRN_WEIGHT_AS_EXIT = 1<<5
  1822. } router_crn_flags_t;
  1823. routerinfo_t *router_choose_random_node(const char *preferred,
  1824.                                         smartlist_t *excludedsmartlist,
  1825.                                         struct routerset_t *excludedset,
  1826.                                         router_crn_flags_t flags);
  1827. routerinfo_t *router_get_by_nickname(const char *nickname,
  1828.                                      int warn_if_unnamed);
  1829. int router_digest_version_as_new_as(const char *digest, const char *cutoff);
  1830. int router_digest_is_trusted_dir_type(const char *digest,
  1831.                                       authority_type_t type);
  1832. #define router_digest_is_trusted_dir(d) 
  1833.   router_digest_is_trusted_dir_type((d), NO_AUTHORITY)
  1834. int router_addr_is_trusted_dir(uint32_t addr);
  1835. int hexdigest_to_digest(const char *hexdigest, char *digest);
  1836. routerinfo_t *router_get_by_hexdigest(const char *hexdigest);
  1837. routerinfo_t *router_get_by_digest(const char *digest);
  1838. signed_descriptor_t *router_get_by_descriptor_digest(const char *digest);
  1839. signed_descriptor_t *router_get_by_extrainfo_digest(const char *digest);
  1840. signed_descriptor_t *extrainfo_get_by_descriptor_digest(const char *digest);
  1841. const char *signed_descriptor_get_body(signed_descriptor_t *desc);
  1842. const char *signed_descriptor_get_annotations(signed_descriptor_t *desc);
  1843. routerlist_t *router_get_routerlist(void);
  1844. void routerinfo_free(routerinfo_t *router);
  1845. void extrainfo_free(extrainfo_t *extrainfo);
  1846. void routerlist_free(routerlist_t *rl);
  1847. void dump_routerlist_mem_usage(int severity);
  1848. void routerlist_remove(routerlist_t *rl, routerinfo_t *ri, int make_old,
  1849.                        time_t now);
  1850. void routerlist_free_all(void);
  1851. void routerlist_reset_warnings(void);
  1852. void router_set_status(const char *digest, int up);
  1853. /** Return value for router_add_to_routerlist() and dirserv_add_descriptor() */
  1854. typedef enum was_router_added_t {
  1855.   ROUTER_ADDED_SUCCESSFULLY = 1,
  1856.   ROUTER_ADDED_NOTIFY_GENERATOR = 0,
  1857.   ROUTER_BAD_EI = -1,
  1858.   ROUTER_WAS_NOT_NEW = -2,
  1859.   ROUTER_NOT_IN_CONSENSUS = -3,
  1860.   ROUTER_NOT_IN_CONSENSUS_OR_NETWORKSTATUS = -4,
  1861.   ROUTER_AUTHDIR_REJECTS = -5,
  1862. } was_router_added_t;
  1863. static int WRA_WAS_ADDED(was_router_added_t s);
  1864. static int WRA_WAS_OUTDATED(was_router_added_t s);
  1865. static int WRA_WAS_REJECTED(was_router_added_t s);
  1866. /** Return true iff the descriptor was added. It might still be necessary to
  1867.  * check whether the descriptor generator should be notified.
  1868.  */
  1869. static INLINE int
  1870. WRA_WAS_ADDED(was_router_added_t s) {
  1871.   return s == ROUTER_ADDED_SUCCESSFULLY || s == ROUTER_ADDED_NOTIFY_GENERATOR;
  1872. }
  1873. /** Return true iff the descriptor was not added because it was either:
  1874.  * - not in the consensus
  1875.  * - neither in the consensus nor in any networkstatus document
  1876.  * - it was outdated.
  1877.  */
  1878. static INLINE int WRA_WAS_OUTDATED(was_router_added_t s)
  1879. {
  1880.   return (s == ROUTER_WAS_NOT_NEW ||
  1881.           s == ROUTER_NOT_IN_CONSENSUS ||
  1882.           s == ROUTER_NOT_IN_CONSENSUS_OR_NETWORKSTATUS);
  1883. }
  1884. /** Return true iff the descriptor rejected because it was malformed. */
  1885. static INLINE int WRA_WAS_REJECTED(was_router_added_t s)
  1886. {
  1887.   return (s == ROUTER_AUTHDIR_REJECTS);
  1888. }
  1889. was_router_added_t router_add_to_routerlist(routerinfo_t *router,
  1890.                                             const char **msg,
  1891.                                             int from_cache,
  1892.                                             int from_fetch);
  1893. was_router_added_t router_add_extrainfo_to_routerlist(
  1894.                                         extrainfo_t *ei, const char **msg,
  1895.                                         int from_cache, int from_fetch);
  1896. void routerlist_remove_old_routers(void);
  1897. int router_load_single_router(const char *s, uint8_t purpose, int cache,
  1898.                               const char **msg);
  1899. int router_load_routers_from_string(const char *s, const char *eos,
  1900.                                      saved_location_t saved_location,
  1901.                                      smartlist_t *requested_fingerprints,
  1902.                                      int descriptor_digests,
  1903.                                      const char *prepend_annotations);
  1904. void router_load_extrainfo_from_string(const char *s, const char *eos,
  1905.                                        saved_location_t saved_location,
  1906.                                        smartlist_t *requested_fingerprints,
  1907.                                        int descriptor_digests);
  1908. void routerlist_retry_directory_downloads(time_t now);
  1909. int router_exit_policy_all_routers_reject(uint32_t addr, uint16_t port,
  1910.                                           int need_uptime);
  1911. int router_exit_policy_rejects_all(routerinfo_t *router);
  1912. trusted_dir_server_t *add_trusted_dir_server(const char *nickname,
  1913.                            const char *address,
  1914.                            uint16_t dir_port, uint16_t or_port,
  1915.                            const char *digest, const char *v3_auth_digest,
  1916.                            authority_type_t type);
  1917. void authority_cert_free(authority_cert_t *cert);
  1918. void clear_trusted_dir_servers(void);
  1919. int any_trusted_dir_is_v1_authority(void);
  1920. void update_router_descriptor_downloads(time_t now);
  1921. void update_extrainfo_downloads(time_t now);
  1922. int router_have_minimum_dir_info(void);
  1923. void router_dir_info_changed(void);
  1924. const char *get_dir_info_status_string(void);
  1925. int count_loading_descriptors_progress(void);
  1926. void router_reset_descriptor_download_failures(void);
  1927. int router_differences_are_cosmetic(routerinfo_t *r1, routerinfo_t *r2);
  1928. int routerinfo_incompatible_with_extrainfo(routerinfo_t *ri, extrainfo_t *ei,
  1929.                                            signed_descriptor_t *sd,
  1930.                                            const char **msg);
  1931. void routerlist_assert_ok(routerlist_t *rl);
  1932. const char *esc_router_info(routerinfo_t *router);
  1933. void routers_sort_by_identity(smartlist_t *routers);
  1934. routerset_t *routerset_new(void);
  1935. int routerset_parse(routerset_t *target, const char *s,
  1936.                     const char *description);
  1937. void routerset_union(routerset_t *target, const routerset_t *source);
  1938. int routerset_is_list(const routerset_t *set);
  1939. int routerset_needs_geoip(const routerset_t *set);
  1940. int routerset_contains_router(const routerset_t *set, routerinfo_t *ri);
  1941. int routerset_contains_routerstatus(const routerset_t *set,
  1942.                                     routerstatus_t *rs);
  1943. int routerset_contains_extendinfo(const routerset_t *set,
  1944.                                   const extend_info_t *ei);
  1945. void routerset_get_all_routers(smartlist_t *out, const routerset_t *routerset,
  1946.                                int running_only);
  1947. void routersets_get_disjunction(smartlist_t *target, const smartlist_t *source,
  1948.                                 const routerset_t *include,
  1949.                                 const routerset_t *exclude, int running_only);
  1950. void routerset_subtract_routers(smartlist_t *out,
  1951.                                 const routerset_t *routerset);
  1952. char *routerset_to_string(const routerset_t *routerset);
  1953. void routerset_refresh_countries(routerset_t *target);
  1954. int routerset_equal(const routerset_t *old, const routerset_t *new);
  1955. void routerset_free(routerset_t *routerset);
  1956. void routerinfo_set_country(routerinfo_t *ri);
  1957. void routerlist_refresh_countries(void);
  1958. void refresh_all_country_info(void);
  1959. int hid_serv_get_responsible_directories(smartlist_t *responsible_dirs,
  1960.                                          const char *id);
  1961. int hid_serv_acting_as_directory(void);
  1962. int hid_serv_responsible_for_desc_id(const char *id);
  1963. /********************************* routerparse.c ************************/
  1964. #define MAX_STATUS_TAG_LEN 32
  1965. /** Structure to hold parsed Tor versions.  This is a little messier
  1966.  * than we would like it to be, because we changed version schemes with 0.1.0.
  1967.  *
  1968.  * See version-spec.txt for the whole business.
  1969.  */
  1970. typedef struct tor_version_t {
  1971.   int major;
  1972.   int minor;
  1973.   int micro;
  1974.   /** Release status.  For version in the post-0.1 format, this is always
  1975.    * VER_RELEASE. */
  1976.   enum { VER_PRE=0, VER_RC=1, VER_RELEASE=2, } status;
  1977.   int patchlevel;
  1978.   char status_tag[MAX_STATUS_TAG_LEN];
  1979.   int svn_revision;
  1980. } tor_version_t;
  1981. int router_get_router_hash(const char *s, char *digest);
  1982. int router_get_dir_hash(const char *s, char *digest);
  1983. int router_get_runningrouters_hash(const char *s, char *digest);
  1984. int router_get_networkstatus_v2_hash(const char *s, char *digest);
  1985. int router_get_networkstatus_v3_hash(const char *s, char *digest);
  1986. int router_get_extrainfo_hash(const char *s, char *digest);
  1987. int router_append_dirobj_signature(char *buf, size_t buf_len,
  1988.                                    const char *digest,
  1989.                                    crypto_pk_env_t *private_key);
  1990. int router_parse_list_from_string(const char **s, const char *eos,
  1991.                                   smartlist_t *dest,
  1992.                                   saved_location_t saved_location,
  1993.                                   int is_extrainfo,
  1994.                                   int allow_annotations,
  1995.                                   const char *prepend_annotations);
  1996. int router_parse_routerlist_from_directory(const char *s,
  1997.                                            routerlist_t **dest,
  1998.                                            crypto_pk_env_t *pkey,
  1999.                                            int check_version,
  2000.                                            int write_to_cache);
  2001. int router_parse_runningrouters(const char *str);
  2002. int router_parse_directory(const char *str);
  2003. routerinfo_t *router_parse_entry_from_string(const char *s, const char *end,
  2004.                                              int cache_copy,
  2005.                                              int allow_annotations,
  2006.                                              const char *prepend_annotations);
  2007. extrainfo_t *extrainfo_parse_entry_from_string(const char *s, const char *end,
  2008.                          int cache_copy, struct digest_ri_map_t *routermap);
  2009. addr_policy_t *router_parse_addr_policy_item_from_string(const char *s,
  2010.                                                   int assume_action);
  2011. version_status_t tor_version_is_obsolete(const char *myversion,
  2012.                                          const char *versionlist);
  2013. int tor_version_parse(const char *s, tor_version_t *out);
  2014. int tor_version_as_new_as(const char *platform, const char *cutoff);
  2015. int tor_version_compare(tor_version_t *a, tor_version_t *b);
  2016. void sort_version_list(smartlist_t *lst, int remove_duplicates);
  2017. void assert_addr_policy_ok(smartlist_t *t);
  2018. void dump_distinct_digest_count(int severity);
  2019. networkstatus_v2_t *networkstatus_v2_parse_from_string(const char *s);
  2020. networkstatus_t *networkstatus_parse_vote_from_string(const char *s,
  2021.                                                  const char **eos_out,
  2022.                                                  networkstatus_type_t ns_type);
  2023. ns_detached_signatures_t *networkstatus_parse_detached_signatures(
  2024.                                           const char *s, const char *eos);
  2025. authority_cert_t *authority_cert_parse_from_string(const char *s,
  2026.                                                    const char **end_of_string);
  2027. int rend_parse_v2_service_descriptor(rend_service_descriptor_t **parsed_out,
  2028.                                      char *desc_id_out,
  2029.                                      char **intro_points_encrypted_out,
  2030.                                      size_t *intro_points_encrypted_size_out,
  2031.                                      size_t *encoded_size_out,
  2032.                                      const char **next_out, const char *desc);
  2033. int rend_decrypt_introduction_points(char **ipos_decrypted,
  2034.                                      size_t *ipos_decrypted_size,
  2035.                                      const char *descriptor_cookie,
  2036.                                      const char *ipos_encrypted,
  2037.                                      size_t ipos_encrypted_size);
  2038. int rend_parse_introduction_points(rend_service_descriptor_t *parsed,
  2039.                                    const char *intro_points_encoded,
  2040.                                    size_t intro_points_encoded_size);
  2041. int rend_parse_client_keys(strmap_t *parsed_clients, const char *str);
  2042. #endif