Tor 0.4.9.13
Loading...
Searching...
No Matches
dirclient.c
Go to the documentation of this file.
1/* Copyright (c) 2001-2004, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2021, The Tor Project, Inc. */
4/* See LICENSE for licensing information */
5
6/**
7 * @file dirclient.c
8 * @brief Download directory information
9 **/
10
11#define DIRCLIENT_PRIVATE
12
13#include "core/or/or.h"
14
15#include "app/config/config.h"
19#include "core/or/policies.h"
34#include "feature/hs/hs_cache.h"
52
53#include "lib/cc/ctassert.h"
58#include "lib/err/backtrace.h"
59
67
68/** Maximum size, in bytes, for any directory object that we've downloaded. */
69#define MAX_DIR_DL_SIZE ((1<<24)-1) /* 16 MB - 1 */
70
71/** How far in the future do we allow a directory server to tell us it is
72 * before deciding that one of us has the wrong time? */
73#define ALLOW_DIRECTORY_TIME_SKEW (30*60)
74
75static int body_is_plausible(const char *body, size_t body_len, int purpose);
79 dir_connection_t *conn, int status_code);
82 int status_code,
83 int router_purpose,
84 int was_extrainfo,
85 int was_descriptor_digests);
87 int status_code,
88 const char *dir_id);
90 const int direct,
91 const directory_request_t *req);
92static void connection_dir_close_consensus_fetches(
93 dir_connection_t *except_this_one, const char *resource);
94
95/** Return a string describing a given directory connection purpose. */
96STATIC const char *
98{
99 switch (purpose)
100 {
102 return "server descriptor upload";
104 return "consensus vote upload";
106 return "consensus signature upload";
108 return "server descriptor fetch";
110 return "extra-info fetch";
112 return "consensus network-status fetch";
114 return "authority cert fetch";
116 return "status vote fetch";
118 return "consensus signature fetch";
120 return "hidden-service descriptor fetch";
122 return "hidden-service descriptor upload";
124 return "microdescriptor fetch";
125 }
126
127 log_warn(LD_BUG, "Called with unknown purpose %d", purpose);
128 return "(unknown)";
129}
130
131/** Return the requisite directory information types. */
133dir_fetch_type(int dir_purpose, int router_purpose, const char *resource)
134{
135 dirinfo_type_t type;
136 switch (dir_purpose) {
138 type = EXTRAINFO_DIRINFO;
139 if (router_purpose == ROUTER_PURPOSE_BRIDGE)
140 type |= BRIDGE_DIRINFO;
141 else
142 type |= V3_DIRINFO;
143 break;
145 if (router_purpose == ROUTER_PURPOSE_BRIDGE)
146 type = BRIDGE_DIRINFO;
147 else
148 type = V3_DIRINFO;
149 break;
153 type = V3_DIRINFO;
154 break;
156 type = V3_DIRINFO;
157 if (resource && !strcmp(resource, "microdesc"))
158 type |= MICRODESC_DIRINFO;
159 break;
161 type = MICRODESC_DIRINFO;
162 break;
163 default:
164 log_warn(LD_BUG, "Unexpected purpose %d", (int)dir_purpose);
165 type = NO_DIRINFO;
166 break;
167 }
168 return type;
169}
170
171/** Return true iff <b>identity_digest</b> is the digest of a router which
172 * says that it caches extrainfos. (If <b>is_authority</b> we always
173 * believe that to be true.) */
174int
175router_supports_extrainfo(const char *identity_digest, int is_authority)
176{
177 const node_t *node = node_get_by_id(identity_digest);
178
179 if (node && node->ri) {
180 if (node->ri->caches_extra_info)
181 return 1;
182 }
183 if (is_authority) {
184 return 1;
185 }
186 return 0;
187}
188
189/** Return true iff any trusted directory authority has accepted our
190 * server descriptor.
191 *
192 * We consider any authority sufficient because waiting for all of
193 * them means it never happens while any authority is down; we don't
194 * go for something more complex in the middle (like >1/3 or >1/2 or
195 * >=1/2) because that doesn't seem necessary yet.
196 */
197int
199{
200 const smartlist_t *servers = router_get_trusted_dir_servers();
201 const or_options_t *options = get_options();
202 SMARTLIST_FOREACH(servers, dir_server_t *, d, {
203 if ((d->type & options->PublishServerDescriptor_) &&
204 d->has_accepted_serverdesc) {
205 return 1;
206 }
207 });
208 return 0;
209}
210
211/** Start a connection to every suitable directory authority, using
212 * connection purpose <b>dir_purpose</b> and uploading <b>payload</b>
213 * (of length <b>payload_len</b>). The dir_purpose should be one of
214 * 'DIR_PURPOSE_UPLOAD_{DIR|VOTE|SIGNATURES}'.
215 *
216 * <b>router_purpose</b> describes the type of descriptor we're
217 * publishing, if we're publishing a descriptor -- e.g. general or bridge.
218 *
219 * <b>type</b> specifies what sort of dir authorities (V3,
220 * BRIDGE, etc) we should upload to.
221 *
222 * If <b>extrainfo_len</b> is nonzero, the first <b>payload_len</b> bytes of
223 * <b>payload</b> hold a router descriptor, and the next <b>extrainfo_len</b>
224 * bytes of <b>payload</b> hold an extra-info document. Upload the descriptor
225 * to all authorities, and the extra-info document to all authorities that
226 * support it.
227 */
228void
229directory_post_to_dirservers(uint8_t dir_purpose, uint8_t router_purpose,
230 dirinfo_type_t type,
231 const char *payload,
232 size_t payload_len, size_t extrainfo_len)
233{
234 const or_options_t *options = get_options();
235 dir_indirection_t indirection;
236 const smartlist_t *dirservers = router_get_trusted_dir_servers();
237 int found = 0;
238 const int exclude_self = (dir_purpose == DIR_PURPOSE_UPLOAD_VOTE ||
239 dir_purpose == DIR_PURPOSE_UPLOAD_SIGNATURES);
240 tor_assert(dirservers);
241 /* This tries dirservers which we believe to be down, but ultimately, that's
242 * harmless, and we may as well err on the side of getting things uploaded.
243 */
244 SMARTLIST_FOREACH_BEGIN(dirservers, dir_server_t *, ds) {
246 if (!rs) {
247 /* prefer to use the address in the consensus, but fall back to
248 * the hard-coded trusted_dir_server address if we don't have a
249 * consensus or this digest isn't in our consensus. */
250 rs = &ds->fake_status;
251 }
252
253 size_t upload_len = payload_len;
254
255 if ((type & ds->type) == 0)
256 continue;
257
258 if (exclude_self && router_digest_is_me(ds->digest)) {
259 /* we don't upload to ourselves, but there's now at least
260 * one authority of this type that has what we wanted to upload. */
261 found = 1;
262 continue;
263 }
264
265 if (options->StrictNodes &&
267 log_warn(LD_DIR, "Wanted to contact authority '%s' for %s, but "
268 "it's in our ExcludedNodes list and StrictNodes is set. "
269 "Skipping.",
270 ds->nickname,
271 dir_conn_purpose_to_string(dir_purpose));
272 continue;
273 }
274
275 found = 1; /* at least one authority of this type was listed */
276 if (dir_purpose == DIR_PURPOSE_UPLOAD_DIR)
277 ds->has_accepted_serverdesc = 0;
278
279 if (extrainfo_len && router_supports_extrainfo(ds->digest, 1)) {
280 upload_len += extrainfo_len;
281 log_info(LD_DIR, "Uploading an extrainfo too (length %d)",
282 (int) extrainfo_len);
283 }
284 if (purpose_needs_anonymity(dir_purpose, router_purpose, NULL)) {
285 indirection = DIRIND_ANONYMOUS;
286 } else if (!reachable_addr_allows_rs(rs, FIREWALL_DIR_CONNECTION, 0)) {
287 if (reachable_addr_allows_rs(rs, FIREWALL_OR_CONNECTION, 0))
288 indirection = DIRIND_ONEHOP;
289 else
290 indirection = DIRIND_ANONYMOUS;
291 } else {
292 indirection = DIRIND_DIRECT_CONN;
293 }
294
295 directory_request_t *req = directory_request_new(dir_purpose);
297 directory_request_set_router_purpose(req, router_purpose);
298 directory_request_set_indirection(req, indirection);
299 directory_request_set_payload(req, payload, upload_len);
301 directory_request_free(req);
302 } SMARTLIST_FOREACH_END(ds);
303 if (!found) {
304 char *s = authdir_type_to_string(type);
305 log_warn(LD_DIR, "Publishing server descriptor to directory authorities "
306 "of type '%s', but no authorities of that type listed!", s);
307 tor_free(s);
308 }
309}
310
311/** Return true iff, according to the values in <b>options</b>, we should be
312 * using directory guards for direct downloads of directory information. */
313STATIC int
315{
316 /* Public (non-bridge) servers never use directory guards. */
317 if (public_server_mode(options))
318 return 0;
319 /* If guards are disabled, we can't use directory guards.
320 */
321 if (!options->UseEntryGuards)
322 return 0;
323 /* If we're configured to fetch directory info aggressively or of a
324 * nonstandard type, don't use directory guards. */
325 if (options->DownloadExtraInfo || options->FetchDirInfoEarly ||
327 return 0;
328 return 1;
329}
330
331/** Pick an unconstrained directory server from among our guards, the latest
332 * networkstatus, or the fallback dirservers, for use in downloading
333 * information of type <b>type</b>, and return its routerstatus. */
334static const routerstatus_t *
336 uint8_t dir_purpose,
337 circuit_guard_state_t **guard_state_out)
338{
339 const routerstatus_t *rs = NULL;
340 const or_options_t *options = get_options();
341
342 if (options->UseBridges)
343 log_warn(LD_BUG, "Called when we have UseBridges set.");
344
345 if (should_use_directory_guards(options)) {
346 const node_t *node = guards_choose_dirguard(dir_purpose, guard_state_out);
347 if (node)
348 rs = node->rs;
349 } else {
350 /* anybody with a non-zero dirport will do */
351 rs = router_pick_directory_server(type, pds_flags);
352 }
353 if (!rs) {
354 log_info(LD_DIR, "No router found for %s; falling back to "
355 "dirserver list.", dir_conn_purpose_to_string(dir_purpose));
356 rs = router_pick_fallback_dirserver(type, pds_flags);
357 }
358
359 return rs;
360}
361
362/**
363 * Set the extra fields in <b>req</b> that are used when requesting a
364 * consensus of type <b>resource</b>.
365 *
366 * Right now, these fields are if-modified-since and x-or-diff-from-consensus.
367 */
368static void
370 const char *resource)
371{
372 time_t if_modified_since = 0;
373 uint8_t or_diff_from[DIGEST256_LEN];
374 int or_diff_from_is_set = 0;
375
376 /* DEFAULT_IF_MODIFIED_SINCE_DELAY is 1/20 of the default consensus
377 * period of 1 hour.
378 */
379 const int DEFAULT_IF_MODIFIED_SINCE_DELAY = 180;
380 const int32_t DEFAULT_TRY_DIFF_FOR_CONSENSUS_NEWER = 72;
381 const int32_t MIN_TRY_DIFF_FOR_CONSENSUS_NEWER = 0;
382 const int32_t MAX_TRY_DIFF_FOR_CONSENSUS_NEWER = 8192;
383 const char TRY_DIFF_FOR_CONSENSUS_NEWER_NAME[] =
384 "try-diff-for-consensus-newer-than";
385
386 int flav = FLAV_NS;
387 if (resource)
388 flav = networkstatus_parse_flavor_name(resource);
389
390 int32_t max_age_for_diff = 3600 *
392 TRY_DIFF_FOR_CONSENSUS_NEWER_NAME,
393 DEFAULT_TRY_DIFF_FOR_CONSENSUS_NEWER,
394 MIN_TRY_DIFF_FOR_CONSENSUS_NEWER,
395 MAX_TRY_DIFF_FOR_CONSENSUS_NEWER);
396
397 if (flav != -1) {
398 /* IF we have a parsed consensus of this type, we can do an
399 * if-modified-time based on it. */
402 if (v) {
403 /* In networks with particularly short V3AuthVotingIntervals,
404 * ask for the consensus if it's been modified since half the
405 * V3AuthVotingInterval of the most recent consensus. */
406 time_t ims_delay = DEFAULT_IF_MODIFIED_SINCE_DELAY;
407 if (v->fresh_until > v->valid_after
408 && ims_delay > (v->fresh_until - v->valid_after)/2) {
409 ims_delay = (v->fresh_until - v->valid_after)/2;
410 }
411 if_modified_since = v->valid_after + ims_delay;
412 if (v->valid_after >= approx_time() - max_age_for_diff) {
413 memcpy(or_diff_from, v->digest_sha3_as_signed, DIGEST256_LEN);
414 or_diff_from_is_set = 1;
415 }
416 }
417 } else {
418 /* Otherwise it might be a consensus we don't parse, but which we
419 * do cache. Look at the cached copy, perhaps. */
420 cached_dir_t *cd = dirserv_get_consensus(resource);
421 /* We have no method of determining the voting interval from an
422 * unparsed consensus, so we use the default. */
423 if (cd) {
424 if_modified_since = cd->published + DEFAULT_IF_MODIFIED_SINCE_DELAY;
425 if (cd->published >= approx_time() - max_age_for_diff) {
426 memcpy(or_diff_from, cd->digest_sha3_as_signed, DIGEST256_LEN);
427 or_diff_from_is_set = 1;
428 }
429 }
430 }
431
432 if (if_modified_since > 0)
433 directory_request_set_if_modified_since(req, if_modified_since);
434 if (or_diff_from_is_set) {
435 char hex[HEX_DIGEST256_LEN + 1];
436 base16_encode(hex, sizeof(hex),
437 (const char*)or_diff_from, sizeof(or_diff_from));
438 directory_request_add_header(req, X_OR_DIFF_FROM_CONSENSUS_HEADER, hex);
439 }
440}
441/** Start a connection to a random running directory server, using
442 * connection purpose <b>dir_purpose</b>, intending to fetch descriptors
443 * of purpose <b>router_purpose</b>, and requesting <b>resource</b>.
444 * Use <b>pds_flags</b> as arguments to router_pick_directory_server()
445 * or router_pick_trusteddirserver().
446 */
447MOCK_IMPL(void,
449 uint8_t dir_purpose,
450 uint8_t router_purpose,
451 const char *resource,
452 int pds_flags,
454{
455 const routerstatus_t *rs = NULL;
456 const or_options_t *options = get_options();
457 int prefer_authority = (dirclient_fetches_from_authorities(options)
458 || want_authority == DL_WANT_AUTHORITY);
459 int require_authority = 0;
460 int get_via_tor = purpose_needs_anonymity(dir_purpose, router_purpose,
461 resource);
462 dirinfo_type_t type = dir_fetch_type(dir_purpose, router_purpose, resource);
463
464 if (type == NO_DIRINFO)
465 return;
466
467 if (!options->FetchServerDescriptors)
468 return;
469
470 circuit_guard_state_t *guard_state = NULL;
471 if (!get_via_tor) {
472 if (options->UseBridges && !(type & BRIDGE_DIRINFO)) {
473 /* We want to ask a running bridge for which we have a descriptor.
474 *
475 * When we ask choose_random_entry() for a bridge, we specify what
476 * sort of dir fetch we'll be doing, so it won't return a bridge
477 * that can't answer our question.
478 */
479 const node_t *node = guards_choose_dirguard(dir_purpose, &guard_state);
480 if (node && node->ri) {
481 /* every bridge has a routerinfo. */
482 routerinfo_t *ri = node->ri;
483 /* clients always make OR connections to bridges */
484 tor_addr_port_t or_ap;
485 directory_request_t *req = directory_request_new(dir_purpose);
486 /* we are willing to use a non-preferred address if we need to */
487 reachable_addr_choose_from_node(node, FIREWALL_OR_CONNECTION, 0,
488 &or_ap);
491 ri->cache_info.identity_digest);
492 directory_request_set_router_purpose(req, router_purpose);
493 directory_request_set_resource(req, resource);
494 if (dir_purpose == DIR_PURPOSE_FETCH_CONSENSUS)
496 directory_request_set_guard_state(req, guard_state);
498 directory_request_free(req);
499 } else {
500 if (guard_state) {
501 entry_guard_cancel(&guard_state);
502 }
503 log_notice(LD_DIR, "Ignoring directory request, since no bridge "
504 "nodes are available yet.");
505 }
506
507 return;
508 } else {
509 if (prefer_authority || (type & BRIDGE_DIRINFO)) {
510 /* only ask authdirservers, and don't ask myself */
511 rs = router_pick_trusteddirserver(type, pds_flags);
512 if (rs == NULL && (pds_flags & (PDS_NO_EXISTING_SERVERDESC_FETCH|
514 /* We don't want to fetch from any authorities that we're currently
515 * fetching server descriptors from, and we got no match. Did we
516 * get no match because all the authorities have connections
517 * fetching server descriptors (in which case we should just
518 * return,) or because all the authorities are down or on fire or
519 * unreachable or something (in which case we should go on with
520 * our fallback code)? */
523 rs = router_pick_trusteddirserver(type, pds_flags);
524 if (rs) {
525 log_debug(LD_DIR, "Deferring serverdesc fetch: all authorities "
526 "are in use.");
527 return;
528 }
529 }
530 if (rs == NULL && require_authority) {
531 log_info(LD_DIR, "No authorities were available for %s: will try "
532 "later.", dir_conn_purpose_to_string(dir_purpose));
533 return;
534 }
535 }
536 if (!rs && !(type & BRIDGE_DIRINFO)) {
537 rs = directory_pick_generic_dirserver(type, pds_flags,
538 dir_purpose,
539 &guard_state);
540 if (!rs)
541 get_via_tor = 1; /* last resort: try routing it via Tor */
542 }
543 }
544 }
545
546 if (get_via_tor) {
547 /* Never use fascistfirewall; we're going via Tor. */
548 pds_flags |= PDS_IGNORE_FASCISTFIREWALL;
549 rs = router_pick_directory_server(type, pds_flags);
550 }
551
552 /* If we have any hope of building an indirect conn, we know some router
553 * descriptors. If (rs==NULL), we can't build circuits anyway, so
554 * there's no point in falling back to the authorities in this case. */
555 if (rs) {
556 const dir_indirection_t indirection =
557 get_via_tor ? DIRIND_ANONYMOUS : DIRIND_ONEHOP;
558 directory_request_t *req = directory_request_new(dir_purpose);
560 directory_request_set_router_purpose(req, router_purpose);
561 directory_request_set_indirection(req, indirection);
562 directory_request_set_resource(req, resource);
563 if (dir_purpose == DIR_PURPOSE_FETCH_CONSENSUS)
565 if (guard_state)
566 directory_request_set_guard_state(req, guard_state);
568 directory_request_free(req);
569 } else {
570 log_notice(LD_DIR,
571 "While fetching directory info, "
572 "no running dirservers known. Will try again later. "
573 "(purpose %d)", dir_purpose);
574 if (!purpose_needs_anonymity(dir_purpose, router_purpose, resource)) {
575 /* remember we tried them all and failed. */
576 directory_all_unreachable(time(NULL));
577 }
578 }
579}
580
581/** As directory_get_from_dirserver, but initiates a request to <i>every</i>
582 * directory authority other than ourself. Only for use by authorities when
583 * searching for missing information while voting. */
584void
586 uint8_t router_purpose,
587 const char *resource)
588{
591
592 SMARTLIST_FOREACH_BEGIN(router_get_trusted_dir_servers(),
593 dir_server_t *, ds) {
594 if (router_digest_is_me(ds->digest))
595 continue;
596 if (!(ds->type & V3_DIRINFO))
597 continue;
599 if (!rs) {
600 /* prefer to use the address in the consensus, but fall back to
601 * the hard-coded trusted_dir_server address if we don't have a
602 * consensus or this digest isn't in our consensus. */
603 rs = &ds->fake_status;
604 }
605 directory_request_t *req = directory_request_new(dir_purpose);
607 directory_request_set_router_purpose(req, router_purpose);
608 directory_request_set_resource(req, resource);
610 directory_request_free(req);
611 } SMARTLIST_FOREACH_END(ds);
612}
613
614/** Return true iff <b>ind</b> requires a multihop circuit. */
615static int
617{
618 return ind == DIRIND_ANON_DIRPORT || ind == DIRIND_ANONYMOUS;
619}
620
621/* Choose reachable OR and Dir addresses and ports from status, copying them
622 * into use_or_ap and use_dir_ap. If indirection is anonymous, then we're
623 * connecting via another relay, so choose the primary IPv4 address and ports.
624 *
625 * status should have at least one reachable address, if we can't choose a
626 * reachable address, warn and return -1. Otherwise, return 0.
627 */
628static int
629directory_choose_address_routerstatus(const routerstatus_t *status,
630 dir_indirection_t indirection,
631 tor_addr_port_t *use_or_ap,
632 tor_addr_port_t *use_dir_ap)
633{
634 tor_assert(status != NULL);
635 tor_assert(use_or_ap != NULL);
636 tor_assert(use_dir_ap != NULL);
637
638 const or_options_t *options = get_options();
639 int have_or = 0, have_dir = 0;
640
641 /* We expect status to have at least one reachable address if we're
642 * connecting to it directly.
643 *
644 * Therefore, we can simply use the other address if the one we want isn't
645 * allowed by the firewall.
646 *
647 * (When Tor uploads and downloads a hidden service descriptor, it uses
648 * DIRIND_ANONYMOUS. Even Single Onion Servers (NYI) use DIRIND_ANONYMOUS,
649 * to avoid HSDirs denying service by rejecting descriptors.)
650 */
651
652 /* Initialise the OR / Dir addresses */
653 tor_addr_make_null(&use_or_ap->addr, AF_UNSPEC);
654 use_or_ap->port = 0;
655 tor_addr_make_null(&use_dir_ap->addr, AF_UNSPEC);
656 use_dir_ap->port = 0;
657
658 /* ORPort connections */
659 if (indirection == DIRIND_ANONYMOUS) {
660 if (!tor_addr_is_null(&status->ipv4_addr)) {
661 /* Since we're going to build a 3-hop circuit and ask the 2nd relay
662 * to extend to this address, always use the primary (IPv4) OR address */
663 tor_addr_copy(&use_or_ap->addr, &status->ipv4_addr);
664 use_or_ap->port = status->ipv4_orport;
665 have_or = 1;
666 }
667 } else if (indirection == DIRIND_ONEHOP) {
668 /* We use an IPv6 address if we have one and we prefer it.
669 * Use the preferred address and port if they are reachable, otherwise,
670 * use the alternate address and port (if any).
671 */
672 reachable_addr_choose_from_rs(status, FIREWALL_OR_CONNECTION, 0,
673 use_or_ap);
674 have_or = tor_addr_port_is_valid_ap(use_or_ap, 0);
675 }
676
677 /* DirPort connections
678 * DIRIND_ONEHOP uses ORPort, but may fall back to the DirPort on relays */
679 if (indirection == DIRIND_DIRECT_CONN ||
680 indirection == DIRIND_ANON_DIRPORT ||
681 (indirection == DIRIND_ONEHOP
682 && !dirclient_must_use_begindir(options))) {
683 reachable_addr_choose_from_rs(status, FIREWALL_DIR_CONNECTION, 0,
684 use_dir_ap);
685 have_dir = tor_addr_port_is_valid_ap(use_dir_ap, 0);
686 }
687
688 /* We rejected all addresses in the relay's status. This means we can't
689 * connect to it. */
690 if (!have_or && !have_dir) {
691 char *ipv6_str = tor_addr_to_str_dup(&status->ipv6_addr);
692 log_info(LD_BUG, "Rejected all OR and Dir addresses from %s when "
693 "launching an outgoing directory connection to: IPv4 %s OR %d "
694 "Dir %d IPv6 %s OR %d Dir %d", routerstatus_describe(status),
695 fmt_addr(&status->ipv4_addr), status->ipv4_orport,
696 status->ipv4_dirport, ipv6_str, status->ipv6_orport,
697 status->ipv4_dirport);
698 tor_free(ipv6_str);
699 log_backtrace_once(LOG_INFO, LD_BUG, "Addresses came from");
700 return -1;
701 }
702
703 return 0;
704}
705
706/** Called when we are unable to complete the client's request to a directory
707 * server due to a network error: Mark the router as down and try again if
708 * possible.
709 */
710void
712{
714 /* We must not set a directory to non-running for HS purposes else we end
715 * up flagging nodes from the hashring has unusable. It doesn't have direct
716 * effect on the HS subsystem because the nodes are selected regardless of
717 * their status but still, we shouldn't flag them as non running.
718 *
719 * One example where this can go bad is if a tor instance gets added a lot
720 * of ephemeral services and with a network with problem then many nodes in
721 * the consenus ends up unusable.
722 *
723 * Furthermore, a service does close any pending directory connections
724 * before uploading a descriptor and thus we can end up here in a natural
725 * way since closing a pending directory connection leads to this code
726 * path. */
727 if (!DIR_PURPOSE_IS_HS(TO_CONN(conn)->purpose)) {
729 }
730 if (conn->base_.purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
731 conn->base_.purpose == DIR_PURPOSE_FETCH_EXTRAINFO) {
732 log_info(LD_DIR, "Giving up on serverdesc/extrainfo fetch from "
733 "directory server at %s; retrying",
738 } else if (conn->base_.purpose == DIR_PURPOSE_FETCH_CONSENSUS) {
739 if (conn->requested_resource)
741 } else if (conn->base_.purpose == DIR_PURPOSE_FETCH_CERTIFICATE) {
742 log_info(LD_DIR, "Giving up on certificate fetch from directory server "
743 "at %s; retrying",
746 } else if (conn->base_.purpose == DIR_PURPOSE_FETCH_DETACHED_SIGNATURES) {
747 log_info(LD_DIR, "Giving up downloading detached signatures from %s",
749 } else if (conn->base_.purpose == DIR_PURPOSE_FETCH_STATUS_VOTE) {
750 log_info(LD_DIR, "Giving up downloading votes from %s",
752 } else if (conn->base_.purpose == DIR_PURPOSE_FETCH_MICRODESC) {
753 log_info(LD_DIR, "Giving up on downloading microdescriptors from "
754 "directory server at %s; will retry",
757 } else if (conn->base_.purpose == DIR_PURPOSE_UPLOAD_VOTE ||
758 conn->base_.purpose == DIR_PURPOSE_UPLOAD_SIGNATURES) {
759 log_warn(LD_DIR, "Failed to post %s to %s.",
762 }
763}
764
765/** Helper: Attempt to fetch directly the descriptors of each bridge
766 * listed in <b>failed</b>.
767 */
768static void
770{
771 char digest[DIGEST_LEN];
772 SMARTLIST_FOREACH(descs, const char *, cp,
773 {
774 if (base16_decode(digest, DIGEST_LEN, cp, strlen(cp)) != DIGEST_LEN) {
775 log_warn(LD_BUG, "Malformed fingerprint in list: %s",
776 escaped(cp));
777 continue;
778 }
780 });
781}
782
783/** Called when an attempt to download one or more router descriptors
784 * or extra-info documents on connection <b>conn</b> failed.
785 */
786static void
788{
789 /* No need to increment the failure count for routerdescs, since
790 * it's not their fault. */
791
792 /* No need to relaunch descriptor downloads here: we already do it
793 * every 10 or 60 seconds (FOO_DESCRIPTOR_RETRY_INTERVAL) in main.c. */
795 conn->base_.purpose == DIR_PURPOSE_FETCH_EXTRAINFO ||
796 conn->base_.purpose == DIR_PURPOSE_FETCH_MICRODESC);
797
798 (void) conn;
799}
800
801/** Called when an attempt to download a bridge's routerdesc from
802 * one of the authorities failed due to a network error. If
803 * possible attempt to download descriptors from the bridge directly.
804 */
805static void
807{
808 smartlist_t *which = NULL;
809
810 /* Requests for bridge descriptors are in the form 'fp/', so ignore
811 anything else. */
812 if (!conn->requested_resource || strcmpstart(conn->requested_resource,"fp/"))
813 return;
814
815 which = smartlist_new();
817 + strlen("fp/"),
818 which, NULL, 0);
819
821 if (smartlist_len(which)) {
823 SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
824 }
825 smartlist_free(which);
826}
827
828/** Called when an attempt to fetch a certificate fails. */
829static void
831{
832 const char *fp_pfx = "fp/";
833 const char *fpsk_pfx = "fp-sk/";
834 smartlist_t *failed;
836
837 if (!conn->requested_resource)
838 return;
839 failed = smartlist_new();
840 /*
841 * We have two cases download by fingerprint (resource starts
842 * with "fp/") or download by fingerprint/signing key pair
843 * (resource starts with "fp-sk/").
844 */
845 if (!strcmpstart(conn->requested_resource, fp_pfx)) {
846 /* Download by fingerprint case */
848 strlen(fp_pfx),
849 failed, NULL, DSR_HEX);
850 SMARTLIST_FOREACH_BEGIN(failed, char *, cp) {
851 /* Null signing key digest indicates download by fp only */
852 authority_cert_dl_failed(cp, NULL, status);
853 tor_free(cp);
854 } SMARTLIST_FOREACH_END(cp);
855 } else if (!strcmpstart(conn->requested_resource, fpsk_pfx)) {
856 /* Download by (fp,sk) pairs */
858 strlen(fpsk_pfx), failed);
859 SMARTLIST_FOREACH_BEGIN(failed, fp_pair_t *, cp) {
860 authority_cert_dl_failed(cp->first, cp->second, status);
861 tor_free(cp);
862 } SMARTLIST_FOREACH_END(cp);
863 } else {
864 log_warn(LD_DIR,
865 "Don't know what to do with failure for cert fetch %s",
866 conn->requested_resource);
867 }
868
869 smartlist_free(failed);
870
872}
873
874/** Evaluate the situation and decide if we should use an encrypted
875 * "begindir-style" connection for this directory request.
876 * 0) If there is no DirPort, yes.
877 * 1) If or_port is 0, or it's a direct conn and or_port is firewalled
878 * or we're a dir mirror, no.
879 * 2) If we prefer to avoid begindir conns, and we're not fetching or
880 * publishing a bridge relay descriptor, no.
881 * 3) Else yes.
882 * If returning 0, return in *reason why we can't use begindir.
883 * reason must not be NULL.
884 */
885static int
887 const directory_request_t *req,
888 const char **reason)
889{
890 const tor_addr_t *or_addr = &req->or_addr_port.addr;
891 //const tor_addr_t *dir_addr = &req->dir_addr_port.addr;
892 const int or_port = req->or_addr_port.port;
893 const int dir_port = req->dir_addr_port.port;
894
895 const dir_indirection_t indirection = req->indirection;
896
897 tor_assert(reason);
898 *reason = NULL;
899
900 /* Reasons why we must use begindir */
901 if (!dir_port) {
902 *reason = "(using begindir - directory with no DirPort)";
903 return 1; /* We don't know a DirPort -- must begindir. */
904 }
905 /* Reasons why we can't possibly use begindir */
906 if (!or_port) {
907 *reason = "directory with unknown ORPort";
908 return 0; /* We don't know an ORPort -- no chance. */
909 }
910 if (indirection == DIRIND_DIRECT_CONN ||
911 indirection == DIRIND_ANON_DIRPORT) {
912 *reason = "DirPort connection";
913 return 0;
914 }
915 if (indirection == DIRIND_ONEHOP) {
916 /* We're firewalled and want a direct OR connection */
917 if (!reachable_addr_allows_addr(or_addr, or_port,
918 FIREWALL_OR_CONNECTION, 0, 0)) {
919 *reason = "ORPort not reachable";
920 return 0;
921 }
922 }
923 /* Reasons why we want to avoid using begindir */
924 if (indirection == DIRIND_ONEHOP) {
925 if (!dirclient_must_use_begindir(options)) {
926 *reason = "in relay mode";
927 return 0;
928 }
929 }
930 /* DIRIND_ONEHOP on a client, or DIRIND_ANONYMOUS
931 */
932 *reason = "(using begindir)";
933 return 1;
934}
935
936/**
937 * Create and return a new directory_request_t with purpose
938 * <b>dir_purpose</b>.
939 */
941directory_request_new(uint8_t dir_purpose)
942{
943 tor_assert(dir_purpose >= DIR_PURPOSE_MIN_);
944 tor_assert(dir_purpose <= DIR_PURPOSE_MAX_);
945 tor_assert(dir_purpose != DIR_PURPOSE_SERVER);
947
948 directory_request_t *result = tor_malloc_zero(sizeof(*result));
949 tor_addr_make_null(&result->or_addr_port.addr, AF_INET);
950 result->or_addr_port.port = 0;
951 tor_addr_make_null(&result->dir_addr_port.addr, AF_INET);
952 result->dir_addr_port.port = 0;
953 result->dir_purpose = dir_purpose;
954 result->router_purpose = ROUTER_PURPOSE_GENERAL;
955 result->indirection = DIRIND_ONEHOP;
956 return result;
957}
958/**
959 * Release all resources held by <b>req</b>.
960 */
961void
963{
964 if (req == NULL)
965 return;
966 config_free_lines(req->additional_headers);
967 tor_free(req);
968}
969/**
970 * Set the address and OR port to use for this directory request. If there is
971 * no OR port, we'll have to connect over the dirport. (If there are both,
972 * the indirection setting determines which to use.)
973 */
974void
976 const tor_addr_port_t *p)
977{
978 memcpy(&req->or_addr_port, p, sizeof(*p));
979}
980/**
981 * Set the address and dirport to use for this directory request. If there
982 * is no dirport, we'll have to connect over the OR port. (If there are both,
983 * the indirection setting determines which to use.)
984 */
985void
987 const tor_addr_port_t *p)
988{
989 memcpy(&req->dir_addr_port, p, sizeof(*p));
990}
991/**
992 * Set the RSA identity digest of the directory to use for this directory
993 * request.
994 */
995void
997 const char *digest)
998{
999 memcpy(req->digest, digest, DIGEST_LEN);
1000}
1001/**
1002 * Set the router purpose associated with uploaded and downloaded router
1003 * descriptors and extrainfo documents in this directory request. The purpose
1004 * must be one of ROUTER_PURPOSE_GENERAL (the default) or
1005 * ROUTER_PURPOSE_BRIDGE.
1006 */
1007void
1009 uint8_t router_purpose)
1010{
1011 tor_assert(router_purpose == ROUTER_PURPOSE_GENERAL ||
1012 router_purpose == ROUTER_PURPOSE_BRIDGE);
1013 // assert that it actually makes sense to set this purpose, given
1014 // the dir_purpose.
1015 req->router_purpose = router_purpose;
1016}
1017/**
1018 * Set the indirection to be used for the directory request. The indirection
1019 * parameter configures whether to connect to a DirPort or ORPort, and whether
1020 * to anonymize the connection. DIRIND_ONEHOP (use ORPort, don't anonymize)
1021 * is the default. See dir_indirection_t for more information.
1022 */
1023void
1025 dir_indirection_t indirection)
1026{
1027 req->indirection = indirection;
1028}
1029
1030/**
1031 * Set a pointer to the resource to request from a directory. Different
1032 * request types use resources to indicate different components of their URL.
1033 * Note that only an alias to <b>resource</b> is stored, so the
1034 * <b>resource</b> must outlive the request.
1035 */
1036void
1038 const char *resource)
1039{
1040 req->resource = resource;
1041}
1042/**
1043 * Set a pointer to the payload to include with this directory request, along
1044 * with its length. Note that only an alias to <b>payload</b> is stored, so
1045 * the <b>payload</b> must outlive the request.
1046 */
1047void
1049 const char *payload,
1050 size_t payload_len)
1051{
1052 tor_assert(DIR_PURPOSE_IS_UPLOAD(req->dir_purpose));
1053
1054 req->payload = payload;
1055 req->payload_len = payload_len;
1056}
1057/**
1058 * Set an if-modified-since date to send along with the request. The
1059 * default is 0 (meaning, send no if-modified-since header).
1060 */
1061void
1063 time_t if_modified_since)
1064{
1065 req->if_modified_since = if_modified_since;
1066}
1067
1068/** Include a header of name <b>key</b> with content <b>val</b> in the
1069 * request. Neither may include newlines or other odd characters. Their
1070 * ordering is not currently guaranteed.
1071 *
1072 * Note that, as elsewhere in this module, header keys include a trailing
1073 * colon and space.
1074 */
1075void
1077 const char *key,
1078 const char *val)
1079{
1080 config_line_prepend(&req->additional_headers, key, val);
1081}
1082/**
1083 * Set an object containing HS connection identifier to be associated with
1084 * this request. Note that only an alias to <b>ident</b> is stored, so the
1085 * <b>ident</b> object must outlive the request.
1086 */
1087void
1089 const hs_ident_dir_conn_t *ident)
1090{
1091 if (ident) {
1092 tor_assert(req->dir_purpose == DIR_PURPOSE_UPLOAD_HSDESC);
1093 }
1094 req->hs_ident = ident;
1095}
1096/**
1097 * Set an object containing HS connection identifier to be associated with
1098 * this fetch request. Note that only an alias to <b>ident</b> is stored, so
1099 * the <b>ident</b> object must outlive the request.
1100 */
1101void
1103 const hs_ident_dir_conn_t *ident)
1104{
1105 if (ident) {
1106 tor_assert(req->dir_purpose == DIR_PURPOSE_FETCH_HSDESC);
1107 }
1108 req->hs_ident = ident;
1109}
1110/** Set a static circuit_guard_state_t object to affliate with the request in
1111 * <b>req</b>. This object will receive notification when the attempt to
1112 * connect to the guard either succeeds or fails. */
1113void
1115 circuit_guard_state_t *state)
1116{
1117 req->guard_state = state;
1118}
1119
1120/**
1121 * Internal: Return true if any information for contacting the directory in
1122 * <b>req</b> has been set, other than by the routerstatus. */
1123static int
1125{
1126 /* We only check for ports here, since we don't use an addr unless the port
1127 * is set */
1128 return (req->or_addr_port.port ||
1129 req->dir_addr_port.port ||
1130 ! tor_digest_is_zero(req->digest));
1131}
1132
1133/**
1134 * Set the routerstatus to use for the directory associated with this
1135 * request. If this option is set, then no other function to set the
1136 * directory's address or identity should be called.
1137 */
1138void
1140 const routerstatus_t *status)
1141{
1142 req->routerstatus = status;
1143}
1144
1145/**
1146 * Helper: update the addresses, ports, and identities in <b>req</b>
1147 * from the routerstatus object in <b>req</b>. Return 0 on success.
1148 * On failure, warn and return -1.
1149 */
1150static int
1152
1153{
1154 const routerstatus_t *status = req->routerstatus;
1155 if (BUG(status == NULL))
1156 return -1;
1157 const or_options_t *options = get_options();
1158 const node_t *node;
1159 tor_addr_port_t use_or_ap, use_dir_ap;
1160 const int anonymized_connection = dirind_is_anon(req->indirection);
1161
1162 tor_assert(status != NULL);
1163
1164 node = node_get_by_id(status->identity_digest);
1165
1166 /* XXX The below check is wrong: !node means it's not in the consensus,
1167 * but we haven't checked if we have a descriptor for it -- and also,
1168 * we only care about the descriptor if it's a begindir-style anonymized
1169 * connection. */
1170 if (!node && anonymized_connection) {
1171 log_info(LD_DIR, "Not sending anonymized request to directory '%s'; we "
1172 "don't have its router descriptor.",
1173 routerstatus_describe(status));
1174 return -1;
1175 }
1176
1177 if (options->ExcludeNodes && options->StrictNodes &&
1178 routerset_contains_routerstatus(options->ExcludeNodes, status, -1)) {
1179 log_warn(LD_DIR, "Wanted to contact directory mirror %s for %s, but "
1180 "it's in our ExcludedNodes list and StrictNodes is set. "
1181 "Skipping. This choice might make your Tor not work.",
1182 routerstatus_describe(status),
1183 dir_conn_purpose_to_string(req->dir_purpose));
1184 return -1;
1185 }
1186
1187 /* At this point, if we are a client making a direct connection to a
1188 * directory server, we have selected a server that has at least one address
1189 * allowed by ClientUseIPv4/6 and Reachable{"",OR,Dir}Addresses. This
1190 * selection uses the preference in ClientPreferIPv6{OR,Dir}Port, if
1191 * possible. (If UseBridges is set, clients always use IPv6, and prefer it
1192 * by default.)
1193 *
1194 * Now choose an address that we can use to connect to the directory server.
1195 */
1196 if (directory_choose_address_routerstatus(status,
1197 req->indirection, &use_or_ap,
1198 &use_dir_ap) < 0) {
1199 return -1;
1200 }
1201
1202 /* One last thing: If we're talking to an authority, we might want to use
1203 * a special HTTP port for it based on our purpose.
1204 */
1205 if (req->indirection == DIRIND_DIRECT_CONN && status->is_authority) {
1207 status->identity_digest);
1208 if (ds) {
1209 const tor_addr_port_t *v4 = NULL;
1210 if (authdir_mode_v3(get_options())) {
1211 // An authority connecting to another authority should always
1212 // prefer the VOTING usage, if one is specifically configured.
1214 ds, AUTH_USAGE_VOTING, AF_INET);
1215 }
1216 if (! v4) {
1217 // Everybody else should prefer a usage dependent on their
1218 // the dir_purpose.
1219 auth_dirport_usage_t usage =
1220 auth_dirport_usage_for_purpose(req->dir_purpose);
1221 v4 = trusted_dir_server_get_dirport(ds, usage, AF_INET);
1222 }
1223 tor_assert_nonfatal(v4);
1224 if (v4) {
1225 // XXXX We could, if we wanted, also select a v6 address. But a v4
1226 // address must exist here, and we as a relay are required to support
1227 // ipv4. So we just that.
1228 tor_addr_port_copy(&use_dir_ap, v4);
1229 }
1230 }
1231 }
1232
1233 directory_request_set_or_addr_port(req, &use_or_ap);
1234 directory_request_set_dir_addr_port(req, &use_dir_ap);
1235 directory_request_set_directory_id_digest(req, status->identity_digest);
1236 return 0;
1237}
1238
1239/**
1240 * Launch the provided directory request, configured in <b>request</b>.
1241 * After this function is called, you can free <b>request</b>.
1242 */
1243MOCK_IMPL(void,
1245{
1246 tor_assert(request);
1247 if (request->routerstatus) {
1248 tor_assert_nonfatal(
1251 return; // or here XXXX
1252 }
1253 }
1254
1255 const tor_addr_port_t *or_addr_port = &request->or_addr_port;
1256 const tor_addr_port_t *dir_addr_port = &request->dir_addr_port;
1257 const char *digest = request->digest;
1258 const uint8_t dir_purpose = request->dir_purpose;
1259 const uint8_t router_purpose = request->router_purpose;
1260 const dir_indirection_t indirection = request->indirection;
1261 const char *resource = request->resource;
1262 const hs_ident_dir_conn_t *hs_ident = request->hs_ident;
1263 circuit_guard_state_t *guard_state = request->guard_state;
1264
1265 tor_assert(or_addr_port->port || dir_addr_port->port);
1266 tor_assert(digest);
1267
1268 dir_connection_t *conn;
1269 const or_options_t *options = get_options();
1270 int socket_error = 0;
1271 const char *begindir_reason = NULL;
1272 /* Should the connection be to a relay's OR port (and inside that we will
1273 * send our directory request)? */
1274 const int use_begindir =
1275 directory_command_should_use_begindir(options, request, &begindir_reason);
1276
1277 /* Will the connection go via a three-hop Tor circuit? Note that this
1278 * is separate from whether it will use_begindir. */
1279 const int anonymized_connection = dirind_is_anon(indirection);
1280
1281 /* What is the address we want to make the directory request to? If
1282 * we're making a begindir request this is the ORPort of the relay
1283 * we're contacting; if not a begindir request, this is its DirPort.
1284 * Note that if anonymized_connection is true, we won't be initiating
1285 * a connection directly to this address. */
1286 tor_addr_t addr;
1287 tor_addr_copy(&addr, &(use_begindir ? or_addr_port : dir_addr_port)->addr);
1288 uint16_t port = (use_begindir ? or_addr_port : dir_addr_port)->port;
1289
1290 log_debug(LD_DIR, "anonymized %d, use_begindir %d.",
1291 anonymized_connection, use_begindir);
1292
1293 log_debug(LD_DIR, "Initiating %s", dir_conn_purpose_to_string(dir_purpose));
1294
1295 if (purpose_needs_anonymity(dir_purpose, router_purpose, resource)) {
1296 tor_assert(anonymized_connection ||
1297 hs_service_non_anonymous_mode_enabled(options));
1298 }
1299
1300 /* use encrypted begindir connections for everything except relays
1301 * this provides better protection for directory fetches */
1302 if (!use_begindir && dirclient_must_use_begindir(options)) {
1303 log_warn(LD_BUG, "Client could not use begindir connection: %s",
1304 begindir_reason ? begindir_reason : "(NULL)");
1305 return;
1306 }
1307
1308 /* ensure that we don't make direct connections when a SOCKS server is
1309 * configured. */
1310 if (!anonymized_connection && !use_begindir && !options->HTTPProxy &&
1311 (options->Socks4Proxy || options->Socks5Proxy)) {
1312 log_warn(LD_DIR, "Cannot connect to a directory server through a "
1313 "SOCKS proxy!");
1314 return;
1315 }
1316
1317 /* Make sure that the destination addr and port we picked is viable. */
1318 if (!port || tor_addr_is_null(&addr)) {
1319 log_warn(LD_DIR,
1320 "Cannot make an outgoing %sconnection without a remote %sPort.",
1321 use_begindir ? "begindir " : "",
1322 use_begindir ? "OR" : "Dir");
1323 log_backtrace_once(LOG_INFO, LD_BUG, "Address came from");
1324 return;
1325 }
1326
1327 conn = dir_connection_new(tor_addr_family(&addr));
1328
1329 /* set up conn so it's got all the data we need to remember */
1330 tor_addr_copy(&conn->base_.addr, &addr);
1331 conn->base_.port = port;
1332 conn->base_.address = tor_addr_to_str_dup(&addr);
1333 memcpy(conn->identity_digest, digest, DIGEST_LEN);
1334
1335 conn->base_.purpose = dir_purpose;
1336 conn->router_purpose = router_purpose;
1337
1338 /* give it an initial state */
1339 conn->base_.state = DIR_CONN_STATE_CONNECTING;
1340
1341 /* decide whether we can learn our IP address from this conn */
1342 /* XXXX This is a bad name for this field now. */
1343 conn->dirconn_direct = !anonymized_connection;
1344
1345 if (hs_ident) {
1346 conn->hs_ident = hs_ident_dir_conn_dup(hs_ident);
1347 }
1348
1349 if (!anonymized_connection && !use_begindir) {
1350 /* then we want to connect to dirport directly */
1351
1352 if (options->HTTPProxy) {
1353 tor_addr_copy(&addr, &options->HTTPProxyAddr);
1354 port = options->HTTPProxyPort;
1355 }
1356
1357 // In this case we should not have picked a directory guard.
1358 if (BUG(guard_state)) {
1359 entry_guard_cancel(&guard_state);
1360 }
1361
1362 // XXXX This is the case where we replace.
1363
1364 switch (connection_connect(TO_CONN(conn), conn->base_.address, &addr,
1365 port, &socket_error)) {
1366 case -1:
1367 connection_mark_for_close(TO_CONN(conn));
1368 return;
1369 case 1:
1370 /* start flushing conn */
1372 FALLTHROUGH;
1373 case 0:
1374 /* queue the command on the outbuf */
1375 directory_send_command(conn, 1, request);
1377 /* writable indicates finish, readable indicates broken link,
1378 error indicates broken link in windowsland. */
1379 }
1380 } else {
1381 /* We will use a Tor circuit (maybe 1-hop, maybe 3-hop, maybe with
1382 * begindir, maybe not with begindir) */
1383
1384 entry_connection_t *linked_conn;
1385
1386 /* Anonymized tunneled connections can never share a circuit.
1387 * One-hop directory connections can share circuits with each other
1388 * but nothing else. */
1389 int iso_flags = anonymized_connection ? ISO_STREAM : ISO_SESSIONGRP;
1390
1391 /* If it's an anonymized connection, remember the fact that we
1392 * wanted it for later: maybe we'll want it again soon. */
1393 if (anonymized_connection && use_begindir)
1394 rep_hist_note_used_internal(time(NULL), 0, 1);
1395 else if (anonymized_connection && !use_begindir)
1396 rep_hist_note_used_port(time(NULL), conn->base_.port);
1397
1398 // In this case we should not have a directory guard; we'll
1399 // get a regular guard later when we build the circuit.
1400 if (BUG(anonymized_connection && guard_state)) {
1401 entry_guard_cancel(&guard_state);
1402 }
1403
1404 conn->guard_state = guard_state;
1405
1406 /* make an AP connection
1407 * populate it and add it at the right state
1408 * hook up both sides
1409 */
1410 linked_conn =
1412 conn->base_.address, conn->base_.port,
1413 digest,
1414 SESSION_GROUP_DIRCONN, iso_flags,
1415 use_begindir, !anonymized_connection);
1416 if (!linked_conn) {
1417 log_warn(LD_NET,"Making tunnel to dirserver failed.");
1418 connection_mark_for_close(TO_CONN(conn));
1419 return;
1420 }
1421
1422 if (connection_add(TO_CONN(conn)) < 0) {
1423 log_warn(LD_NET,"Unable to add connection for link to dirserver.");
1424 connection_mark_for_close(TO_CONN(conn));
1425 return;
1426 }
1428 /* queue the command on the outbuf */
1429 directory_send_command(conn, 0, request);
1430
1433 }
1434}
1435
1436/** Helper for sorting
1437 *
1438 * sort strings alphabetically
1439 *
1440 * XXXX we have a smartlist_sort_strings() function, right?
1441 */
1442static int
1443compare_strs_(const void **a, const void **b)
1444{
1445 const char *s1 = *a, *s2 = *b;
1446 return strcmp(s1, s2);
1447}
1448
1449#define CONDITIONAL_CONSENSUS_FPR_LEN 3
1450CTASSERT(CONDITIONAL_CONSENSUS_FPR_LEN <= DIGEST_LEN);
1451
1452/** Return the URL we should use for a consensus download.
1453 *
1454 * Use the "conditional consensus downloading" feature described in
1455 * dir-spec.txt, i.e.
1456 * GET .../consensus/<b>fpr</b>+<b>fpr</b>+<b>fpr</b>
1457 *
1458 * If 'resource' is provided, it is the name of a consensus flavor to request.
1459 */
1460static char *
1461directory_get_consensus_url(const char *resource)
1462{
1463 char *url = NULL;
1464 const char *hyphen, *flavor;
1465 if (resource==NULL || strcmp(resource, "ns")==0) {
1466 flavor = ""; /* Request ns consensuses as "", so older servers will work*/
1467 hyphen = "";
1468 } else {
1469 flavor = resource;
1470 hyphen = "-";
1471 }
1472
1473 {
1474 char *authority_id_list;
1475 smartlist_t *authority_digests = smartlist_new();
1476
1477 SMARTLIST_FOREACH_BEGIN(router_get_trusted_dir_servers(),
1478 dir_server_t *, ds) {
1479 char *hex;
1480 if (!(ds->type & V3_DIRINFO))
1481 continue;
1482
1483 hex = tor_malloc(2*CONDITIONAL_CONSENSUS_FPR_LEN+1);
1484 base16_encode(hex, 2*CONDITIONAL_CONSENSUS_FPR_LEN+1,
1485 ds->v3_identity_digest, CONDITIONAL_CONSENSUS_FPR_LEN);
1486 smartlist_add(authority_digests, hex);
1487 } SMARTLIST_FOREACH_END(ds);
1488 smartlist_sort(authority_digests, compare_strs_);
1489 authority_id_list = smartlist_join_strings(authority_digests,
1490 "+", 0, NULL);
1491
1492 tor_asprintf(&url, "/tor/status-vote/current/consensus%s%s/%s.z",
1493 hyphen, flavor, authority_id_list);
1494
1495 SMARTLIST_FOREACH(authority_digests, char *, cp, tor_free(cp));
1496 smartlist_free(authority_digests);
1497 tor_free(authority_id_list);
1498 }
1499 return url;
1500}
1501
1502/**
1503 * Copies the ipv6 from source to destination, subject to buffer size limit
1504 * size. If decorate is true, makes sure the copied address is decorated.
1505 */
1506static void
1507copy_ipv6_address(char* destination, const char* source, size_t len,
1508 int decorate) {
1509 tor_assert(destination);
1510 tor_assert(source);
1511
1512 if (decorate && source[0] != '[') {
1513 tor_snprintf(destination, len, "[%s]", source);
1514 } else {
1515 strlcpy(destination, source, len);
1516 }
1517}
1518
1519/** Queue an appropriate HTTP command for <b>request</b> on
1520 * <b>conn</b>->outbuf. If <b>direct</b> is true, we're making a
1521 * non-anonymized connection to the dirport.
1522 */
1523static void
1525 const int direct,
1526 const directory_request_t *req)
1527{
1528 tor_assert(req);
1529 const int purpose = req->dir_purpose;
1530 const char *resource = req->resource;
1531 const char *payload = req->payload;
1532 const size_t payload_len = req->payload_len;
1533 const time_t if_modified_since = req->if_modified_since;
1534 const int anonymized_connection = dirind_is_anon(req->indirection);
1535
1536 char proxystring[256];
1537 char hoststring[128];
1538 /* NEEDS to be the same size hoststring.
1539 Will be decorated with brackets around it if it is ipv6. */
1540 char decorated_address[128];
1541 smartlist_t *headers = smartlist_new();
1542 char *url;
1543 char *accept_encoding;
1544 size_t url_len;
1545 char request[8192];
1546 size_t request_len, total_request_len = 0;
1547 const char *httpcommand = NULL;
1548
1549 tor_assert(conn);
1550 tor_assert(conn->base_.type == CONN_TYPE_DIR);
1551
1553 if (resource)
1554 conn->requested_resource = tor_strdup(resource);
1555
1556 /* decorate the ip address if it is ipv6 */
1557 if (strchr(conn->base_.address, ':')) {
1558 copy_ipv6_address(decorated_address, conn->base_.address,
1559 sizeof(decorated_address), 1);
1560 } else {
1561 strlcpy(decorated_address, conn->base_.address, sizeof(decorated_address));
1562 }
1563
1564 /* come up with a string for which Host: we want */
1565 if (conn->base_.port == 80) {
1566 strlcpy(hoststring, decorated_address, sizeof(hoststring));
1567 } else {
1568 tor_snprintf(hoststring, sizeof(hoststring), "%s:%d",
1569 decorated_address, conn->base_.port);
1570 }
1571
1572 /* Format if-modified-since */
1573 if (if_modified_since) {
1574 char b[RFC1123_TIME_LEN+1];
1575 format_rfc1123_time(b, if_modified_since);
1576 smartlist_add_asprintf(headers, "If-Modified-Since: %s\r\n", b);
1577 }
1578
1579 /* come up with some proxy lines, if we're using one. */
1580 if (direct && get_options()->HTTPProxy) {
1581 char *base64_authenticator=NULL;
1582 const char *authenticator = get_options()->HTTPProxyAuthenticator;
1583
1584 tor_snprintf(proxystring, sizeof(proxystring),"http://%s", hoststring);
1585 if (authenticator) {
1586 base64_authenticator = alloc_http_authenticator(authenticator);
1587 if (!base64_authenticator)
1588 log_warn(LD_BUG, "Encoding http authenticator failed");
1589 }
1590 if (base64_authenticator) {
1591 smartlist_add_asprintf(headers,
1592 "Proxy-Authorization: Basic %s\r\n",
1593 base64_authenticator);
1594 tor_free(base64_authenticator);
1595 }
1596 } else {
1597 proxystring[0] = 0;
1598 }
1599
1600 if (! anonymized_connection) {
1601 /* Add Accept-Encoding. */
1602 accept_encoding = accept_encoding_header();
1603 smartlist_add_asprintf(headers, "Accept-Encoding: %s\r\n",
1604 accept_encoding);
1605 tor_free(accept_encoding);
1606 }
1607
1608 /* Add additional headers, if any */
1609 {
1610 config_line_t *h;
1611 for (h = req->additional_headers; h; h = h->next) {
1612 smartlist_add_asprintf(headers, "%s%s\r\n", h->key, h->value);
1613 }
1614 }
1615
1616 switch (purpose) {
1618 /* resource is optional. If present, it's a flavor name */
1619 tor_assert(!payload);
1620 httpcommand = "GET";
1621 url = directory_get_consensus_url(resource);
1622 log_info(LD_DIR, "Downloading consensus from %s using %s",
1623 hoststring, url);
1624 break;
1626 tor_assert(resource);
1627 tor_assert(!payload);
1628 httpcommand = "GET";
1629 tor_asprintf(&url, "/tor/keys/%s", resource);
1630 break;
1632 tor_assert(resource);
1633 tor_assert(!payload);
1634 httpcommand = "GET";
1635 tor_asprintf(&url, "/tor/status-vote/next/%s.z", resource);
1636 break;
1638 tor_assert(!resource);
1639 tor_assert(!payload);
1640 httpcommand = "GET";
1641 url = tor_strdup("/tor/status-vote/next/consensus-signatures.z");
1642 break;
1644 tor_assert(resource);
1645 httpcommand = "GET";
1646 tor_asprintf(&url, "/tor/server/%s", resource);
1647 break;
1649 tor_assert(resource);
1650 httpcommand = "GET";
1651 tor_asprintf(&url, "/tor/extra/%s", resource);
1652 break;
1654 tor_assert(resource);
1655 httpcommand = "GET";
1656 tor_asprintf(&url, "/tor/micro/%s", resource);
1657 break;
1659 const char *why = router_get_descriptor_gen_reason();
1660 tor_assert(!resource);
1661 tor_assert(payload);
1662 httpcommand = "POST";
1663 url = tor_strdup("/tor/");
1664 if (!why) {
1665 why = "for no reason at all";
1666 }
1667 smartlist_add_asprintf(headers, "X-Desc-Gen-Reason: %s\r\n", why);
1668 break;
1669 }
1671 tor_assert(!resource);
1672 tor_assert(payload);
1673 httpcommand = "POST";
1674 url = tor_strdup("/tor/post/vote");
1675 break;
1677 tor_assert(!resource);
1678 tor_assert(payload);
1679 httpcommand = "POST";
1680 url = tor_strdup("/tor/post/consensus-signature");
1681 break;
1683 tor_assert(resource);
1684 tor_assert(strlen(resource) <= ED25519_BASE64_LEN);
1685 tor_assert(!payload);
1686 httpcommand = "GET";
1687 tor_asprintf(&url, "/tor/hs/3/%s", resource);
1688 break;
1690 tor_assert(resource);
1691 tor_assert(payload);
1692 httpcommand = "POST";
1693 tor_asprintf(&url, "/tor/hs/%s/publish", resource);
1694 break;
1695 default:
1696 tor_assert(0);
1697 return;
1698 }
1699
1700 /* warn in the non-tunneled case */
1701 if (direct && (strlen(proxystring) + strlen(url) >= 4096)) {
1702 log_warn(LD_BUG,
1703 "Squid does not like URLs longer than 4095 bytes, and this "
1704 "one is %d bytes long: %s%s",
1705 (int)(strlen(proxystring) + strlen(url)), proxystring, url);
1706 }
1707
1708 tor_snprintf(request, sizeof(request), "%s %s", httpcommand, proxystring);
1709
1710 request_len = strlen(request);
1711 total_request_len += request_len;
1712 connection_buf_add(request, request_len, TO_CONN(conn));
1713
1714 url_len = strlen(url);
1715 total_request_len += url_len;
1716 connection_buf_add(url, url_len, TO_CONN(conn));
1717 tor_free(url);
1718
1719 if (!strcmp(httpcommand, "POST") || payload) {
1720 smartlist_add_asprintf(headers, "Content-Length: %lu\r\n",
1721 payload ? (unsigned long)payload_len : 0);
1722 }
1723
1724 {
1725 char *header = smartlist_join_strings(headers, "", 0, NULL);
1726 tor_snprintf(request, sizeof(request), " HTTP/1.0\r\nHost: %s\r\n%s\r\n",
1727 hoststring, header);
1728 tor_free(header);
1729 }
1730
1731 request_len = strlen(request);
1732 total_request_len += request_len;
1733 connection_buf_add(request, request_len, TO_CONN(conn));
1734
1735 if (payload) {
1736 /* then send the payload afterwards too */
1737 connection_buf_add(payload, payload_len, TO_CONN(conn));
1738 total_request_len += payload_len;
1739 }
1740
1741 SMARTLIST_FOREACH(headers, char *, h, tor_free(h));
1742 smartlist_free(headers);
1743
1744 log_debug(LD_DIR,
1745 "Sent request to directory server %s "
1746 "(purpose: %d, request size: %"TOR_PRIuSZ", "
1747 "payload size: %"TOR_PRIuSZ")",
1749 conn->base_.purpose,
1750 (total_request_len),
1751 (payload ? payload_len : 0));
1752}
1753
1754/** Return true iff <b>body</b> doesn't start with a plausible router or
1755 * network-status or microdescriptor opening. This is a sign of possible
1756 * compression. */
1757static int
1758body_is_plausible(const char *body, size_t len, int purpose)
1759{
1760 int i;
1761 if (len == 0)
1762 return 1; /* empty bodies don't need decompression */
1763 if (len < 32)
1764 return 0;
1765 if (purpose == DIR_PURPOSE_FETCH_MICRODESC) {
1766 return (!strcmpstart(body,"onion-key"));
1767 }
1768
1769 if (!strcmpstart(body,"router") ||
1770 !strcmpstart(body,"network-status"))
1771 return 1;
1772 for (i=0;i<32;++i) {
1773 if (!TOR_ISPRINT(body[i]) && !TOR_ISSPACE(body[i]))
1774 return 0;
1775 }
1776
1777 return 1;
1778}
1779
1780/** Called when we've just fetched a bunch of router descriptors in
1781 * <b>body</b>. The list <b>which</b>, if present, holds digests for
1782 * descriptors we requested: descriptor digests if <b>descriptor_digests</b>
1783 * is true, or identity digests otherwise. Parse the descriptors, validate
1784 * them, and annotate them as having purpose <b>purpose</b> and as having been
1785 * downloaded from <b>source</b>.
1786 *
1787 * Return the number of routers actually added. */
1788static int
1789load_downloaded_routers(const char *body, smartlist_t *which,
1790 int descriptor_digests,
1791 int router_purpose,
1792 const char *source)
1793{
1794 char buf[256];
1795 char time_buf[ISO_TIME_LEN+1];
1796 int added = 0;
1797 int general = router_purpose == ROUTER_PURPOSE_GENERAL;
1798 format_iso_time(time_buf, time(NULL));
1799 tor_assert(source);
1800
1801 if (tor_snprintf(buf, sizeof(buf),
1802 "@downloaded-at %s\n"
1803 "@source %s\n"
1804 "%s%s%s", time_buf, escaped(source),
1805 !general ? "@purpose " : "",
1806 !general ? router_purpose_to_string(router_purpose) : "",
1807 !general ? "\n" : "")<0)
1808 return added;
1809
1810 added = router_load_routers_from_string(body, NULL, SAVED_NOWHERE, which,
1811 descriptor_digests, buf);
1812 if (added && general)
1813 control_event_boot_dir(BOOTSTRAP_STATUS_LOADING_DESCRIPTORS,
1815 return added;
1816}
1817
1819 const response_handler_args_t *);
1821 const response_handler_args_t *);
1823 const response_handler_args_t *);
1825 const response_handler_args_t *);
1827 const response_handler_args_t *);
1829 const response_handler_args_t *);
1831 const response_handler_args_t *);
1833 const response_handler_args_t *);
1834
1835static int
1836dir_client_decompress_response_body(char **bodyp, size_t *bodylenp,
1837 dir_connection_t *conn,
1838 compress_method_t compression,
1839 int anonymized_connection)
1840{
1841 int rv = 0;
1842 const char *body = *bodyp;
1843 size_t body_len = *bodylenp;
1844 int allow_partial = (conn->base_.purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
1845 conn->base_.purpose == DIR_PURPOSE_FETCH_EXTRAINFO ||
1846 conn->base_.purpose == DIR_PURPOSE_FETCH_MICRODESC);
1847
1848 int plausible = body_is_plausible(body, body_len, conn->base_.purpose);
1849
1850 if (plausible && compression == NO_METHOD) {
1851 return 0;
1852 }
1853
1854 int severity = LOG_DEBUG;
1855 char *new_body = NULL;
1856 size_t new_len = 0;
1857 const char *description1, *description2;
1858 int want_to_try_both = 0;
1859 int tried_both = 0;
1860 compress_method_t guessed = detect_compression_method(body, body_len);
1861
1862 description1 = compression_method_get_human_name(compression);
1863
1864 if (BUG(description1 == NULL))
1865 description1 = compression_method_get_human_name(UNKNOWN_METHOD);
1866
1867 if (guessed == UNKNOWN_METHOD && !plausible)
1868 description2 = "confusing binary junk";
1869 else
1870 description2 = compression_method_get_human_name(guessed);
1871
1872 /* Tell the user if we don't believe what we're told about compression.*/
1873 want_to_try_both = (compression == UNKNOWN_METHOD ||
1874 guessed != compression);
1875 if (want_to_try_both) {
1876 severity = LOG_PROTOCOL_WARN;
1877 }
1878
1879 tor_log(severity, LD_HTTP,
1880 "HTTP body from %s was labeled as %s, "
1881 "%s it seems to be %s.%s",
1883 description1,
1884 guessed != compression?"but":"and",
1885 description2,
1886 (compression>0 && guessed>0 && want_to_try_both)?
1887 " Trying both.":"");
1888
1889 /* Try declared compression first if we can.
1890 * tor_compress_supports_method() also returns true for NO_METHOD.
1891 * Ensure that the server is not sending us data compressed using a
1892 * compression method that is not allowed for anonymous connections. */
1893 if (anonymized_connection &&
1896 rv = -1;
1897 goto done;
1898 }
1899
1900 if (tor_compress_supports_method(compression)) {
1901 tor_uncompress(&new_body, &new_len, body, body_len, compression,
1902 !allow_partial, LOG_PROTOCOL_WARN);
1903 if (new_body) {
1904 /* We succeeded with the declared compression method. Great! */
1905 rv = 0;
1906 goto done;
1907 }
1908 }
1909
1910 /* Okay, if that didn't work, and we think that it was compressed
1911 * differently, try that. */
1912 if (anonymized_connection &&
1915 rv = -1;
1916 goto done;
1917 }
1918
1919 if (tor_compress_supports_method(guessed) &&
1920 compression != guessed) {
1921 tor_uncompress(&new_body, &new_len, body, body_len, guessed,
1922 !allow_partial, LOG_INFO);
1923 tried_both = 1;
1924 }
1925 /* If we're pretty sure that we have a compressed directory, and
1926 * we didn't manage to uncompress it, then warn and bail. */
1927 if (!plausible && !new_body) {
1928 static ratelim_t warning_limit = RATELIM_INIT(60 * 60);
1929 log_fn_ratelim(&warning_limit, LOG_WARN, LD_HTTP,
1930 "Unable to decompress HTTP body (tried %s%s%s, on %s).",
1931 description1,
1932 tried_both?" and ":"",
1933 tried_both?description2:"",
1935 rv = -1;
1936 goto done;
1937 }
1938
1939 done:
1940 if (new_body) {
1941 if (rv == 0) {
1942 /* success! */
1943 tor_free(*bodyp);
1944 *bodyp = new_body;
1945 *bodylenp = new_len;
1946 } else {
1947 tor_free(new_body);
1948 }
1949 }
1950
1951 return rv;
1952}
1953
1954/**
1955 * Total number of bytes downloaded of each directory purpose, when
1956 * bootstrapped, and when not bootstrapped.
1957 *
1958 * (For example, the number of bytes downloaded of purpose p while
1959 * not fully bootstrapped is total_dl[p][false].)
1960 **/
1961static uint64_t total_dl[DIR_PURPOSE_MAX_][2];
1962
1963/**
1964 * Heartbeat: dump a summary of how many bytes of which purpose we've
1965 * downloaded, when bootstrapping and when not bootstrapping.
1966 **/
1967void
1969{
1970 const or_options_t *options = get_options();
1971 for (int bootstrapped = 0; bootstrapped < 2; ++bootstrapped) {
1972 smartlist_t *lines = smartlist_new();
1973 for (int i=0; i < DIR_PURPOSE_MAX_; ++i) {
1974 uint64_t n = total_dl[i][bootstrapped];
1975 if (n == 0)
1976 continue;
1977 if (options->SafeLogging_ != SAFELOG_SCRUB_NONE &&
1979 continue;
1980 smartlist_add_asprintf(lines, "%"PRIu64" (%s)",
1982 }
1983
1984 if (smartlist_len(lines) > 0) {
1985 char *log_line = smartlist_join_strings(lines, "; ", 0, NULL);
1986 log_notice(LD_NET, "While %sbootstrapping, fetched this many bytes: %s",
1987 bootstrapped?"not ":"", log_line);
1988 tor_free(log_line);
1989
1990 SMARTLIST_FOREACH(lines, char *, s, tor_free(s));
1991 }
1992 smartlist_free(lines);
1993 }
1994}
1995
1996/** We are a client, and we've finished reading the server's
1997 * response. Parse it and act appropriately.
1998 *
1999 * If we're still happy with using this directory server in the future, return
2000 * 0. Otherwise return -1; and the caller should consider trying the request
2001 * again.
2002 *
2003 * The caller will take care of marking the connection for close.
2004 */
2005static int
2007{
2008 char *body = NULL;
2009 char *headers = NULL;
2010 char *reason = NULL;
2011 size_t body_len = 0;
2012 int status_code;
2013 time_t date_header = 0;
2014 long apparent_skew;
2015 compress_method_t compression;
2016 int skewed = 0;
2017 int rv;
2018 int allow_partial = (conn->base_.purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
2019 conn->base_.purpose == DIR_PURPOSE_FETCH_EXTRAINFO ||
2020 conn->base_.purpose == DIR_PURPOSE_FETCH_MICRODESC);
2021 size_t received_bytes;
2022 const int anonymized_connection =
2023 purpose_needs_anonymity(conn->base_.purpose,
2024 conn->router_purpose,
2025 conn->requested_resource);
2026
2027 received_bytes = connection_get_inbuf_len(TO_CONN(conn));
2028
2029 log_debug(LD_DIR, "Downloaded %"TOR_PRIuSZ" bytes on connection of purpose "
2030 "%s; bootstrap %d%%",
2031 received_bytes,
2033 control_get_bootstrap_percent());
2034 {
2035 bool bootstrapped = control_get_bootstrap_percent() == 100;
2036 total_dl[conn->base_.purpose][bootstrapped] += received_bytes;
2037 }
2038
2040 &headers, MAX_HEADERS_SIZE,
2041 &body, &body_len, MAX_DIR_DL_SIZE,
2042 allow_partial)) {
2043 case -1: /* overflow */
2044 log_warn(LD_PROTOCOL,
2045 "'fetch' response too large (%s). Closing.",
2047 return -1;
2048 case 0:
2049 log_info(LD_HTTP,
2050 "'fetch' response not all here, but we're at eof. Closing.");
2051 return -1;
2052 /* case 1, fall through */
2053 }
2054
2055 if (parse_http_response(headers, &status_code, &date_header,
2056 &compression, &reason) < 0) {
2057 log_warn(LD_HTTP,"Unparseable headers (%s). Closing.",
2059 rv = -1;
2060 goto done;
2061 }
2062 if (!reason) reason = tor_strdup("[no reason given]");
2063
2065 "Received response on %s: %d %s "
2066 "(purpose: %d, response size: %"TOR_PRIuSZ
2067#ifdef MEASUREMENTS_21206
2068 ", data cells received: %d, data cells sent: %d"
2069#endif
2070 ", compression: %d)",
2072 status_code,
2073 escaped(reason), conn->base_.purpose,
2074 (received_bytes),
2075#ifdef MEASUREMENTS_21206
2076 conn->data_cells_received, conn->data_cells_sent,
2077#endif
2078 compression);
2079
2080 if (conn->guard_state) {
2081 /* we count the connection as successful once we can read from it. We do
2082 * not, however, delay use of the circuit here, since it's just for a
2083 * one-hop directory request. */
2084 /* XXXXprop271 note that this will not do the right thing for other
2085 * waiting circuits that would be triggered by this circuit becoming
2086 * complete/usable. But that's ok, I think.
2087 */
2089 circuit_guard_state_free(conn->guard_state);
2090 conn->guard_state = NULL;
2091 }
2092
2093 /* now check if it's got any hints for us about our IP address. */
2094 if (conn->dirconn_direct) {
2095 char *guess = http_get_header(headers, X_ADDRESS_HEADER);
2096 if (guess) {
2097 tor_addr_t addr;
2098 if (tor_addr_parse(&addr, guess) < 0) {
2099 log_debug(LD_DIR, "Malformed X-Your-Address-Is header %s. Ignoring.",
2100 escaped(guess));
2101 } else {
2102 relay_address_new_suggestion(&addr, &TO_CONN(conn)->addr, NULL);
2103 }
2104 tor_free(guess);
2105 }
2106 }
2107
2108 if (date_header > 0) {
2109 /* The date header was written very soon after we sent our request,
2110 * so compute the skew as the difference between sending the request
2111 * and the date header. (We used to check now-date_header, but that's
2112 * inaccurate if we spend a lot of time downloading.)
2113 */
2114 apparent_skew = conn->base_.timestamp_last_write_allowed - date_header;
2115 if (labs(apparent_skew)>ALLOW_DIRECTORY_TIME_SKEW) {
2116 int trusted = router_digest_is_trusted_dir(conn->identity_digest);
2117 clock_skew_warning(TO_CONN(conn), apparent_skew, trusted, LD_HTTP,
2118 "directory", "DIRSERV");
2119 skewed = 1; /* don't check the recommended-versions line */
2120 } else {
2121 log_debug(LD_HTTP, "Time on received directory is within tolerance; "
2122 "we are %ld seconds skewed. (That's okay.)", apparent_skew);
2123 }
2124 }
2125 (void) skewed; /* skewed isn't used yet. */
2126
2127 if (status_code == 503) {
2128 routerstatus_t *rs;
2129 dir_server_t *ds;
2130 const char *id_digest = conn->identity_digest;
2131 log_info(LD_DIR,"Received http status code %d (%s) from server "
2132 "%s. I'll try again soon.",
2133 status_code, escaped(reason),
2135 time_t now = approx_time();
2136 if ((rs = router_get_mutable_consensus_status_by_id(id_digest)))
2137 rs->last_dir_503_at = now;
2138 if ((ds = router_get_fallback_dirserver_by_digest(id_digest)))
2139 ds->fake_status.last_dir_503_at = now;
2140
2141 rv = -1;
2142 goto done;
2143 }
2144
2145 if (dir_client_decompress_response_body(&body, &body_len,
2146 conn, compression, anonymized_connection) < 0) {
2147 rv = -1;
2148 goto done;
2149 }
2150
2151 response_handler_args_t args;
2152 memset(&args, 0, sizeof(args));
2153 args.status_code = status_code;
2154 args.reason = reason;
2155 args.body = body;
2156 args.body_len = body_len;
2157 args.headers = headers;
2158
2159 switch (conn->base_.purpose) {
2161 rv = handle_response_fetch_consensus(conn, &args);
2162 break;
2164 rv = handle_response_fetch_certificate(conn, &args);
2165 break;
2167 rv = handle_response_fetch_status_vote(conn, &args);
2168 break;
2171 break;
2174 rv = handle_response_fetch_desc(conn, &args);
2175 break;
2177 rv = handle_response_fetch_microdesc(conn, &args);
2178 break;
2180 rv = handle_response_upload_dir(conn, &args);
2181 break;
2183 rv = handle_response_upload_signatures(conn, &args);
2184 break;
2186 rv = handle_response_upload_vote(conn, &args);
2187 break;
2189 rv = handle_response_upload_hsdesc(conn, &args);
2190 break;
2192 rv = handle_response_fetch_hsdesc_v3(conn, &args);
2193 break;
2194 default:
2196 rv = -1;
2197 break;
2198 }
2199
2200 done:
2201 tor_free(body);
2202 tor_free(headers);
2203 tor_free(reason);
2204 return rv;
2205}
2206
2207/**
2208 * Handler function: processes a response to a request for a networkstatus
2209 * consensus document by checking the consensus, storing it, and marking
2210 * router requests as reachable.
2211 **/
2212STATIC int
2214 const response_handler_args_t *args)
2215{
2217 const int status_code = args->status_code;
2218 const char *body = args->body;
2219 const size_t body_len = args->body_len;
2220 const char *reason = args->reason;
2221 const time_t now = approx_time();
2222
2223 const char *consensus;
2224 char *new_consensus = NULL;
2225 const char *sourcename;
2226
2227 int r;
2228 const char *flavname = conn->requested_resource;
2229 if (status_code != 200) {
2230 int severity = (status_code == 304) ? LOG_INFO : LOG_WARN;
2231 tor_log(severity, LD_DIR,
2232 "Received http status code %d (%s) from server "
2233 "%s while fetching consensus directory.",
2234 status_code, escaped(reason),
2236 networkstatus_consensus_download_failed(status_code, flavname);
2237 return -1;
2238 }
2239
2240 if (looks_like_a_consensus_diff(body, body_len)) {
2241 /* First find our previous consensus. Maybe it's in ram, maybe not. */
2242 cached_dir_t *cd = NULL;
2243 const char *consensus_body = NULL;
2244 size_t consensus_body_len;
2245 tor_mmap_t *mapped_consensus = NULL;
2246
2247 /* We prefer the mmap'd version over the cached_dir_t version,
2248 * since that matches the logic we used when we picked a consensus
2249 * back in dir_consensus_request_set_additional_headers. */
2250 mapped_consensus = networkstatus_map_cached_consensus(flavname);
2251 if (mapped_consensus) {
2252 consensus_body = mapped_consensus->data;
2253 consensus_body_len = mapped_consensus->size;
2254 } else {
2255 cd = dirserv_get_consensus(flavname);
2256 if (cd) {
2257 consensus_body = cd->dir;
2258 consensus_body_len = cd->dir_len;
2259 }
2260 }
2261 if (!consensus_body) {
2262 log_warn(LD_DIR, "Received a consensus diff, but we can't find "
2263 "any %s-flavored consensus in our current cache.",flavname);
2264 tor_munmap_file(mapped_consensus);
2266 // XXXX if this happens too much, see below
2267 return -1;
2268 }
2269
2270 new_consensus = consensus_diff_apply(consensus_body, consensus_body_len,
2271 body, body_len);
2272 tor_munmap_file(mapped_consensus);
2273 if (new_consensus == NULL) {
2274 log_warn(LD_DIR, "Could not apply consensus diff received from server "
2275 "%s", connection_describe_peer(TO_CONN(conn)));
2276 // XXXX If this happens too many times, we should maybe not use
2277 // XXXX this directory for diffs any more?
2279 return -1;
2280 }
2281 log_info(LD_DIR, "Applied consensus diff (size %d) from server "
2282 "%s, resulting in a new consensus document (size %d).",
2283 (int)body_len, connection_describe_peer(TO_CONN(conn)),
2284 (int)strlen(new_consensus));
2285 consensus = new_consensus;
2286 sourcename = "generated based on a diff";
2287 } else {
2288 log_info(LD_DIR,"Received consensus directory (body size %d) from server "
2289 "%s", (int)body_len, connection_describe_peer(TO_CONN(conn)));
2290 consensus = body;
2291 sourcename = "downloaded";
2292 }
2293
2294 if ((r=networkstatus_set_current_consensus(consensus,
2295 strlen(consensus),
2296 flavname, 0,
2297 conn->identity_digest))<0) {
2299 "Unable to load %s consensus directory %s from "
2300 "server %s. I'll try again soon.",
2301 flavname, sourcename,
2304 tor_free(new_consensus);
2305 return -1;
2306 }
2307
2308 /* If we launched other fetches for this consensus, cancel them. */
2309 connection_dir_close_consensus_fetches(conn, flavname);
2310
2311 /* update the list of routers and directory guards */
2314 directory_info_has_arrived(now, 0, 0);
2315
2316 if (authdir_mode_v3(get_options())) {
2319 }
2320 log_info(LD_DIR, "Successfully loaded consensus.");
2321
2322 tor_free(new_consensus);
2323 return 0;
2324}
2325
2326/**
2327 * Handler function: processes a response to a request for one or more
2328 * authority certificates
2329 **/
2330static int
2332 const response_handler_args_t *args)
2333{
2335 const int status_code = args->status_code;
2336 const char *reason = args->reason;
2337 const char *body = args->body;
2338 const size_t body_len = args->body_len;
2339
2340 if (status_code != 200) {
2341 log_warn(LD_DIR,
2342 "Received http status code %d (%s) from server "
2343 "%s while fetching \"/tor/keys/%s\".",
2344 status_code, escaped(reason),
2346 conn->requested_resource);
2347 connection_dir_download_cert_failed(conn, status_code);
2348 return -1;
2349 }
2350 log_info(LD_DIR,"Received authority certificates (body size %d) from "
2351 "server %s",
2352 (int)body_len, connection_describe_peer(TO_CONN(conn)));
2353
2354 /*
2355 * Tell trusted_dirs_load_certs_from_string() whether it was by fp
2356 * or fp-sk pair.
2357 */
2358 int src_code = -1;
2359 if (!strcmpstart(conn->requested_resource, "fp/")) {
2360 src_code = TRUSTED_DIRS_CERTS_SRC_DL_BY_ID_DIGEST;
2361 } else if (!strcmpstart(conn->requested_resource, "fp-sk/")) {
2362 src_code = TRUSTED_DIRS_CERTS_SRC_DL_BY_ID_SK_DIGEST;
2363 }
2364
2365 if (src_code != -1) {
2366 if (trusted_dirs_load_certs_from_string(body, src_code, 1,
2367 conn->identity_digest)<0) {
2368 log_warn(LD_DIR, "Unable to parse fetched certificates");
2369 /* if we fetched more than one and only some failed, the successful
2370 * ones got flushed to disk so it's safe to call this on them */
2371 connection_dir_download_cert_failed(conn, status_code);
2372 } else {
2373 time_t now = approx_time();
2374 directory_info_has_arrived(now, 0, 0);
2375 log_info(LD_DIR, "Successfully loaded certificates from fetch.");
2376 }
2377 } else {
2378 log_warn(LD_DIR,
2379 "Couldn't figure out what to do with fetched certificates for "
2380 "unknown resource %s",
2381 conn->requested_resource);
2382 connection_dir_download_cert_failed(conn, status_code);
2383 }
2384 return 0;
2385}
2386
2387/**
2388 * Handler function: processes a response to a request for an authority's
2389 * current networkstatus vote.
2390 **/
2391static int
2393 const response_handler_args_t *args)
2394{
2396 const int status_code = args->status_code;
2397 const char *reason = args->reason;
2398 const char *body = args->body;
2399 const size_t body_len = args->body_len;
2400
2401 const char *msg;
2402 int st;
2403 log_notice(LD_DIR,"Got votes (body size %d) from server %s",
2404 (int)body_len, connection_describe_peer(TO_CONN(conn)));
2405 if (status_code != 200) {
2406 log_warn(LD_DIR,
2407 "Received http status code %d (%s) from server "
2408 "%s while fetching \"/tor/status-vote/next/%s.z\".",
2409 status_code, escaped(reason),
2411 conn->requested_resource);
2412 return -1;
2413 }
2414 dirvote_add_vote(body, 0, TO_CONN(conn)->address, &msg, &st);
2415 if (st > 299) {
2416 log_warn(LD_DIR, "Error adding retrieved vote: %s", msg);
2417 } else {
2418 log_info(LD_DIR, "Added vote(s) successfully [msg: %s]", msg);
2419 }
2420
2421 return 0;
2422}
2423
2424/**
2425 * Handler function: processes a response to a request for the signatures
2426 * that an authority knows about on a given consensus.
2427 **/
2428static int
2430 const response_handler_args_t *args)
2431{
2433 const int status_code = args->status_code;
2434 const char *reason = args->reason;
2435 const char *body = args->body;
2436 const size_t body_len = args->body_len;
2437
2438 const char *msg = NULL;
2439 log_info(LD_DIR,"Got detached signatures (body size %d) from server %s",
2440 (int)body_len,
2442 if (status_code != 200) {
2443 log_warn(LD_DIR,
2444 "Received http status code %d (%s) from server %s while fetching "
2445 "\"/tor/status-vote/next/consensus-signatures.z\".",
2446 status_code, escaped(reason),
2448 return -1;
2449 }
2450 if (dirvote_add_signatures(body, conn->base_.address, &msg)<0) {
2451 log_warn(LD_DIR, "Problem adding detached signatures from %s: %s",
2453 msg?msg:"???");
2454 }
2455
2456 return 0;
2457}
2458
2459/**
2460 * Handler function: processes a response to a request for a group of server
2461 * descriptors or an extrainfo documents.
2462 **/
2463static int
2465 const response_handler_args_t *args)
2466{
2468 conn->base_.purpose == DIR_PURPOSE_FETCH_EXTRAINFO);
2469 const int status_code = args->status_code;
2470 const char *reason = args->reason;
2471 const char *body = args->body;
2472 const size_t body_len = args->body_len;
2473
2474 int was_ei = conn->base_.purpose == DIR_PURPOSE_FETCH_EXTRAINFO;
2475 smartlist_t *which = NULL;
2476 int n_asked_for = 0;
2477 int descriptor_digests = conn->requested_resource &&
2478 !strcmpstart(conn->requested_resource,"d/");
2479 log_info(LD_DIR,"Received %s (body size %d) from server %s",
2480 was_ei ? "extra server info" : "server info",
2481 (int)body_len, connection_describe_peer(TO_CONN(conn)));
2482 if (conn->requested_resource &&
2483 (!strcmpstart(conn->requested_resource,"d/") ||
2484 !strcmpstart(conn->requested_resource,"fp/"))) {
2485 which = smartlist_new();
2487 (descriptor_digests ? 2 : 3),
2488 which, NULL, 0);
2489 n_asked_for = smartlist_len(which);
2490 }
2491 if (status_code != 200) {
2492 int dir_okay = status_code == 404 ||
2493 (status_code == 400 && !strcmp(reason, "Servers unavailable.")) ||
2494 status_code == 301;
2495 /* 404 means that it didn't have them; no big deal.
2496 * Older (pre-0.1.1.8) servers said 400 Servers unavailable instead.
2497 * 301 is considered as an error since Tor does not follow redirects,
2498 * which means we failed to reach the server we wanted. */
2499 log_fn(dir_okay ? LOG_INFO : LOG_WARN, LD_DIR,
2500 "Received http status code %d (%s) from server %s "
2501 "while fetching \"/tor/server/%s\". I'll try again soon.",
2502 status_code, escaped(reason),
2504 conn->requested_resource);
2505 if (!which) {
2507 } else {
2508 dir_routerdesc_download_failed(which, status_code,
2509 conn->router_purpose,
2510 was_ei, descriptor_digests);
2511 SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
2512 smartlist_free(which);
2513 }
2514 return dir_okay ? 0 : -1;
2515 }
2516 /* Learn the routers, assuming we requested by fingerprint or "all"
2517 * or "authority".
2518 *
2519 * We use "authority" to fetch our own descriptor for
2520 * testing, and to fetch bridge descriptors for bootstrapping. Ignore
2521 * the output of "authority" requests unless we are using bridges,
2522 * since otherwise they'll be the response from reachability tests,
2523 * and we don't really want to add that to our routerlist. */
2524 if (which || (conn->requested_resource &&
2525 (!strcmpstart(conn->requested_resource, "all") ||
2526 (!strcmpstart(conn->requested_resource, "authority") &&
2527 get_options()->UseBridges)))) {
2528 /* as we learn from them, we remove them from 'which' */
2529 if (was_ei) {
2531 descriptor_digests);
2532 } else {
2533 //router_load_routers_from_string(body, NULL, SAVED_NOWHERE, which,
2534 // descriptor_digests, conn->router_purpose);
2535 if (load_downloaded_routers(body, which, descriptor_digests,
2536 conn->router_purpose,
2537 conn->base_.address)) {
2538 time_t now = approx_time();
2539 directory_info_has_arrived(now, 0, 1);
2540 }
2541 }
2542 }
2543 if (which) { /* mark remaining ones as failed */
2544 log_info(LD_DIR, "Received %d/%d %s requested from %s",
2545 n_asked_for-smartlist_len(which), n_asked_for,
2546 was_ei ? "extra-info documents" : "router descriptors",
2548 if (smartlist_len(which)) {
2549 dir_routerdesc_download_failed(which, status_code,
2550 conn->router_purpose,
2551 was_ei, descriptor_digests);
2552 }
2553 SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
2554 smartlist_free(which);
2555 }
2556
2557 return 0;
2558}
2559
2560/**
2561 * Handler function: processes a response to a request for a group of
2562 * microdescriptors
2563 **/
2564STATIC int
2566 const response_handler_args_t *args)
2567{
2569 const int status_code = args->status_code;
2570 const char *reason = args->reason;
2571 const char *body = args->body;
2572 const size_t body_len = args->body_len;
2573
2574 smartlist_t *which = NULL;
2575 log_info(LD_DIR,"Received answer to microdescriptor request (status %d, "
2576 "body size %d) from server %s",
2577 status_code, (int)body_len,
2580 !strcmpstart(conn->requested_resource, "d/"));
2581 tor_assert_nonfatal(!fast_mem_is_zero(conn->identity_digest, DIGEST_LEN));
2582 which = smartlist_new();
2584 which, NULL,
2585 DSR_DIGEST256|DSR_BASE64);
2586 if (status_code != 200) {
2587 log_info(LD_DIR, "Received status code %d (%s) from server "
2588 "%s while fetching \"/tor/micro/%s\". I'll try again "
2589 "soon.",
2590 status_code, escaped(reason),
2592 conn->requested_resource);
2593 dir_microdesc_download_failed(which, status_code, conn->identity_digest);
2594 SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
2595 smartlist_free(which);
2596 return 0;
2597 } else {
2598 smartlist_t *mds;
2599 time_t now = approx_time();
2601 body, body+body_len, SAVED_NOWHERE, 0,
2602 now, which);
2603 if (smartlist_len(which)) {
2604 /* Mark remaining ones as failed. */
2605 dir_microdesc_download_failed(which, status_code, conn->identity_digest);
2606 }
2607 if (mds && smartlist_len(mds)) {
2608 control_event_boot_dir(BOOTSTRAP_STATUS_LOADING_DESCRIPTORS,
2610 directory_info_has_arrived(now, 0, 1);
2611 }
2612 SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
2613 smartlist_free(which);
2614 smartlist_free(mds);
2615 }
2616
2617 return 0;
2618}
2619
2620/**
2621 * Handler function: processes a response to a POST request to upload our
2622 * router descriptor.
2623 **/
2624static int
2626 const response_handler_args_t *args)
2627{
2629 const int status_code = args->status_code;
2630 const char *reason = args->reason;
2631 const char *headers = args->headers;
2632
2633 switch (status_code) {
2634 case 200: {
2635 dir_server_t *ds =
2637 char *rejected_hdr = http_get_header(headers,
2638 "X-Descriptor-Not-New: ");
2639 if (rejected_hdr) {
2640 if (!strcmp(rejected_hdr, "Yes")) {
2641 log_info(LD_GENERAL,
2642 "Authority '%s' declined our descriptor (not new)",
2643 ds->nickname);
2644 /* XXXX use this information; be sure to upload next one
2645 * sooner. -NM */
2646 /* XXXX++ On further thought, the task above implies that we're
2647 * basing our regenerate-descriptor time on when we uploaded the
2648 * last descriptor, not on the published time of the last
2649 * descriptor. If those are different, that's a bad thing to
2650 * do. -NM */
2651 }
2652 tor_free(rejected_hdr);
2653 }
2654 log_info(LD_GENERAL,"eof (status 200) after uploading server "
2655 "descriptor: finished.");
2657 LOG_NOTICE, "ACCEPTED_SERVER_DESCRIPTOR DIRAUTH=%s:%d",
2658 conn->base_.address, conn->base_.port);
2659
2662 control_event_server_status(LOG_NOTICE, "GOOD_SERVER_DESCRIPTOR");
2663 }
2664 break;
2665 case 400:
2666 log_warn(LD_GENERAL,"http status 400 (%s) response from "
2667 "dirserver %s. Please correct.",
2668 escaped(reason), connection_describe_peer(TO_CONN(conn)));
2670 "BAD_SERVER_DESCRIPTOR DIRAUTH=%s:%d REASON=\"%s\"",
2671 conn->base_.address, conn->base_.port, escaped(reason));
2672 break;
2673 default:
2674 log_warn(LD_GENERAL,
2675 "HTTP status %d (%s) was unexpected while uploading "
2676 "descriptor to server %s'. Possibly the server is "
2677 "misconfigured?",
2678 status_code, escaped(reason),
2680 break;
2681 }
2682 /* return 0 in all cases, since we don't want to mark any
2683 * dirservers down just because they don't like us. */
2684
2685 return 0;
2686}
2687
2688/**
2689 * Handler function: processes a response to POST request to upload our
2690 * own networkstatus vote.
2691 **/
2692static int
2694 const response_handler_args_t *args)
2695{
2697 const int status_code = args->status_code;
2698 const char *reason = args->reason;
2699
2700 switch (status_code) {
2701 case 200: {
2702 log_notice(LD_DIR,"Uploaded my vote to dirserver %s",
2704 }
2705 break;
2706 case 400:
2707 log_warn(LD_DIR,"http status 400 (%s) response after uploading "
2708 "vote to dirserver %s. Please correct.",
2709 escaped(reason), connection_describe_peer(TO_CONN(conn)));
2710 break;
2711 default:
2712 log_warn(LD_GENERAL,
2713 "HTTP status %d (%s) was unexpected while uploading "
2714 "vote to server %s.",
2715 status_code, escaped(reason),
2717 break;
2718 }
2719 /* return 0 in all cases, since we don't want to mark any
2720 * dirservers down just because they don't like us. */
2721 return 0;
2722}
2723
2724/**
2725 * Handler function: processes a response to POST request to upload our
2726 * view of the signatures on the current consensus.
2727 **/
2728static int
2730 const response_handler_args_t *args)
2731{
2733 const int status_code = args->status_code;
2734 const char *reason = args->reason;
2735
2736 switch (status_code) {
2737 case 200: {
2738 log_notice(LD_DIR,"Uploaded signature(s) to dirserver %s",
2740 }
2741 break;
2742 case 400:
2743 log_warn(LD_DIR,"http status 400 (%s) response after uploading "
2744 "signatures to dirserver %s. Please correct.",
2745 escaped(reason), connection_describe_peer(TO_CONN(conn)));
2746 break;
2747 default:
2748 log_warn(LD_GENERAL,
2749 "HTTP status %d (%s) was unexpected while uploading "
2750 "signatures to server %s.",
2751 status_code, escaped(reason),
2753 break;
2754 }
2755 /* return 0 in all cases, since we don't want to mark any
2756 * dirservers down just because they don't like us. */
2757
2758 return 0;
2759}
2760
2761/**
2762 * Handler function: processes a response to a request for a v3 hidden service
2763 * descriptor.
2764 **/
2765STATIC int
2767 const response_handler_args_t *args)
2768{
2769 const int status_code = args->status_code;
2770 const char *reason = args->reason;
2771 const char *body = args->body;
2772 const size_t body_len = args->body_len;
2773
2774 tor_assert(conn->hs_ident);
2775
2776 log_info(LD_REND,"Received v3 hsdesc (body size %d, status %d (%s))",
2777 (int)body_len, status_code, escaped(reason));
2778
2779 hs_client_dir_fetch_done(conn, reason, body, status_code);
2780 return 0;
2781}
2782
2783/**
2784 * Handler function: processes a response to a POST request to upload an
2785 * hidden service descriptor.
2786 **/
2787static int
2789 const response_handler_args_t *args)
2790{
2791 const int status_code = args->status_code;
2792 const char *reason = args->reason;
2793
2794 tor_assert(conn);
2796
2797 log_info(LD_REND, "Uploaded hidden service descriptor (status %d "
2798 "(%s))",
2799 status_code, escaped(reason));
2800 /* For this directory response, it MUST have an hidden service identifier on
2801 * this connection. */
2802 tor_assert(conn->hs_ident);
2803 switch (status_code) {
2804 case 200:
2805 log_info(LD_REND, "Uploading hidden service descriptor: "
2806 "finished with status 200 (%s)", escaped(reason));
2807 hs_control_desc_event_uploaded(conn->hs_ident, conn->identity_digest);
2808 break;
2809 case 400:
2810 log_fn(LOG_PROTOCOL_WARN, LD_REND,
2811 "Uploading hidden service descriptor: http "
2812 "status 400 (%s) response from dirserver "
2813 "%s. Malformed hidden service descriptor?",
2814 escaped(reason), connection_describe_peer(TO_CONN(conn)));
2815 hs_control_desc_event_failed(conn->hs_ident, conn->identity_digest,
2816 "UPLOAD_REJECTED");
2817 break;
2818 default:
2819 log_warn(LD_REND, "Uploading hidden service descriptor: http "
2820 "status %d (%s) response unexpected (server "
2821 "%s').",
2822 status_code, escaped(reason),
2824 hs_control_desc_event_failed(conn->hs_ident, conn->identity_digest,
2825 "UNEXPECTED");
2826 break;
2827 }
2828
2829 return 0;
2830}
2831
2832/** Called when a directory connection reaches EOF. */
2833int
2835{
2836 int retval;
2837 if (conn->base_.state != DIR_CONN_STATE_CLIENT_READING) {
2838 log_info(LD_HTTP,"conn reached eof, not reading. [state=%d] Closing.",
2839 conn->base_.state);
2840 connection_close_immediate(TO_CONN(conn)); /* error: give up on flushing */
2841 connection_mark_for_close(TO_CONN(conn));
2842 return -1;
2843 }
2844
2845 retval = connection_dir_client_reached_eof(conn);
2846 if (retval == 0) /* success */
2848 connection_mark_for_close(TO_CONN(conn));
2849 return retval;
2850}
2851/** We are closing a dir connection: If <b>dir_conn</b> is a dir connection
2852 * that tried to fetch an HS descriptor, check if it successfully fetched it,
2853 * or if we need to try again. */
2854void
2856{
2857 connection_t *conn = TO_CONN(dir_conn);
2858
2859 /* Check for v3 rend desc fetch */
2860 if (conn->purpose == DIR_PURPOSE_FETCH_HSDESC &&
2861 dir_conn->hs_ident &&
2862 !ed25519_public_key_is_zero(&dir_conn->hs_ident->identity_pk)) {
2863 hs_client_refetch_hsdesc(&dir_conn->hs_ident->identity_pk);
2864 }
2865}
2866
2867/** Array of compression methods to use (if supported) for requesting
2868 * compressed data, ordered from best to worst. */
2870 LZMA_METHOD,
2871 ZSTD_METHOD,
2872 ZLIB_METHOD,
2873 GZIP_METHOD,
2874 NO_METHOD
2875};
2876
2877/** Array of allowed compression methods to use (if supported) when receiving a
2878 * response from a request that was required to be anonymous. */
2880 ZLIB_METHOD,
2881 GZIP_METHOD,
2882 NO_METHOD
2883};
2884
2885/** Return a newly allocated string containing a comma separated list of
2886 * supported encodings. */
2887STATIC char *
2889{
2890 smartlist_t *methods = smartlist_new();
2891 char *header = NULL;
2892 compress_method_t method;
2893 unsigned i;
2894
2895 for (i = 0; i < ARRAY_LENGTH(client_meth_pref); ++i) {
2896 method = client_meth_pref[i];
2897 if (tor_compress_supports_method(method))
2898 smartlist_add(methods, (char *)compression_method_get_name(method));
2899 }
2900
2901 header = smartlist_join_strings(methods, ", ", 0, NULL);
2902 smartlist_free(methods);
2903
2904 return header;
2905}
2906
2907/** Check if the given compression method is allowed for a connection that is
2908 * supposed to be anonymous. Returns 1 if the compression method is allowed,
2909 * otherwise 0. */
2910STATIC int
2912{
2913 unsigned u;
2914
2916 ++u) {
2917 compress_method_t allowed_method =
2919
2920 if (! tor_compress_supports_method(allowed_method))
2921 continue;
2922
2923 if (method == allowed_method)
2924 return 1;
2925 }
2926
2927 return 0;
2928}
2929
2930/** Log a warning when a remote server has sent us a document using a
2931 * compression method that is not allowed for anonymous directory requests. */
2932STATIC void
2934{
2935 log_fn(LOG_PROTOCOL_WARN, LD_HTTP,
2936 "Received a %s HTTP response, which is not "
2937 "allowed for anonymous directory requests.",
2939}
2940
2941/* We just got a new consensus! If there are other in-progress requests
2942 * for this consensus flavor (for example because we launched several in
2943 * parallel), cancel them.
2944 *
2945 * We do this check here (not just in
2946 * connection_ap_handshake_attach_circuit()) to handle the edge case where
2947 * a consensus fetch begins and ends before some other one tries to attach to
2948 * a circuit, in which case the other one won't know that we're all happy now.
2949 *
2950 * Don't mark the conn that just gave us the consensus -- otherwise we
2951 * would end up double-marking it when it cleans itself up.
2952 */
2953static void
2954connection_dir_close_consensus_fetches(dir_connection_t *except_this_one,
2955 const char *resource)
2956{
2957 smartlist_t *conns_to_close =
2959 resource);
2960 SMARTLIST_FOREACH_BEGIN(conns_to_close, dir_connection_t *, d) {
2961 if (d == except_this_one)
2962 continue;
2963 log_info(LD_DIR, "Closing consensus fetch (to %s) since one "
2964 "has just arrived.", connection_describe_peer(TO_CONN(d)));
2965 connection_mark_for_close(TO_CONN(d));
2966 } SMARTLIST_FOREACH_END(d);
2967 smartlist_free(conns_to_close);
2968}
2969/** Called when one or more routerdesc (or extrainfo, if <b>was_extrainfo</b>)
2970 * fetches have failed (with uppercase fingerprints listed in <b>failed</b>,
2971 * either as descriptor digests or as identity digests based on
2972 * <b>was_descriptor_digests</b>).
2973 */
2974static void
2976 int router_purpose,
2977 int was_extrainfo, int was_descriptor_digests)
2978{
2979 char digest[DIGEST_LEN];
2980 time_t now = time(NULL);
2982 if (!was_descriptor_digests) {
2983 if (router_purpose == ROUTER_PURPOSE_BRIDGE) {
2984 tor_assert(!was_extrainfo);
2986 }
2987 return; /* FFFF should implement for other-than-router-purpose someday */
2988 }
2989 SMARTLIST_FOREACH_BEGIN(failed, const char *, cp) {
2990 download_status_t *dls = NULL;
2991 if (base16_decode(digest, DIGEST_LEN, cp, strlen(cp)) != DIGEST_LEN) {
2992 log_warn(LD_BUG, "Malformed fingerprint in list: %s", escaped(cp));
2993 continue;
2994 }
2995 if (was_extrainfo) {
2998 if (sd)
2999 dls = &sd->ei_dl_status;
3000 } else {
3002 }
3003 if (!dls)
3004 continue;
3005 download_status_increment_failure(dls, status_code, cp, server, now);
3006 } SMARTLIST_FOREACH_END(cp);
3007
3008 /* No need to relaunch descriptor downloads here: we already do it
3009 * every 10 or 60 seconds (FOO_DESCRIPTOR_RETRY_INTERVAL) in main.c. */
3010}
3011
3012/** Called when a connection to download microdescriptors from relay with
3013 * <b>dir_id</b> has failed in whole or in part. <b>failed</b> is a list
3014 * of every microdesc digest we didn't get. <b>status_code</b> is the http
3015 * status code we received. Reschedule the microdesc downloads as
3016 * appropriate. */
3017static void
3019 int status_code, const char *dir_id)
3020{
3021 networkstatus_t *consensus
3023 routerstatus_t *rs;
3024 download_status_t *dls;
3025 time_t now = time(NULL);
3027
3028 if (! consensus)
3029 return;
3030
3031 /* We failed to fetch a microdescriptor from 'dir_id', note it down
3032 * so that we don't try the same relay next time... */
3034
3035 SMARTLIST_FOREACH_BEGIN(failed, const char *, d) {
3037 if (!rs)
3038 continue;
3039 dls = &rs->dl_status;
3040
3041 { /* Increment the failure count for this md fetch */
3042 char buf[BASE64_DIGEST256_LEN+1];
3043 digest256_to_base64(buf, d);
3044 log_info(LD_DIR, "Failed to download md %s from %s",
3045 buf, hex_str(dir_id, DIGEST_LEN));
3046 download_status_increment_failure(dls, status_code, buf,
3047 server, now);
3048 }
3049 } SMARTLIST_FOREACH_END(d);
3050}
void tor_addr_copy(tor_addr_t *dest, const tor_addr_t *src)
Definition address.c:933
int tor_addr_parse(tor_addr_t *addr, const char *src)
Definition address.c:1349
void tor_addr_make_null(tor_addr_t *a, sa_family_t family)
Definition address.c:235
int tor_addr_is_null(const tor_addr_t *addr)
Definition address.c:780
char * tor_addr_to_str_dup(const tor_addr_t *addr)
Definition address.c:1164
void tor_addr_port_copy(tor_addr_port_t *dest, const tor_addr_port_t *source)
Definition address.c:2121
static sa_family_t tor_addr_family(const tor_addr_t *a)
Definition address.h:189
#define fmt_addr(a)
Definition address.h:241
time_t approx_time(void)
Definition approx_time.c:32
void authority_cert_dl_failed(const char *id_digest, const char *signing_key_digest, int status)
Definition authcert.c:681
int trusted_dirs_load_certs_from_string(const char *contents, int source, int flush, const char *source_dir)
Definition authcert.c:373
Header file for authcert.c.
Header file for directory authority mode.
Header for backtrace.c.
const char * hex_str(const char *from, size_t fromlen)
Definition binascii.c:34
int base16_decode(char *dest, size_t destlen, const char *src, size_t srclen)
Definition binascii.c:506
void base16_encode(char *dest, size_t destlen, const char *src, size_t srclen)
Definition binascii.c:478
void retry_bridge_descriptor_fetch_directly(const char *digest)
Definition bridges.c:769
Header file for circuitbuild.c.
Cached large directory object structure.
#define ARRAY_LENGTH(x)
int tor_compress_supports_method(compress_method_t method)
Definition compress.c:334
compress_method_t detect_compression_method(const char *in, size_t in_len)
Definition compress.c:314
int tor_uncompress(char **out, size_t *out_len, const char *in, size_t in_len, compress_method_t method, int complete_only, int protocol_warn_level)
Definition compress.c:298
const char * compression_method_get_name(compress_method_t method)
Definition compress.c:394
const char * compression_method_get_human_name(compress_method_t method)
Definition compress.c:420
Headers for compress.c.
compress_method_t
Definition compress.h:21
const or_options_t * get_options(void)
Definition config.c:949
Header file for config.c.
void config_line_prepend(config_line_t **lst, const char *key, const char *val)
Definition confline.c:53
Header for confline.c.
smartlist_t * connection_dir_list_by_purpose_and_resource(int purpose, const char *resource)
void clock_skew_warning(const connection_t *conn, long apparent_skew, int trusted, log_domain_mask_t domain, const char *received, const char *source)
int connection_fetch_from_buf_http(connection_t *conn, char **headers_out, size_t max_headerlen, char **body_out, size_t *body_used, size_t max_bodylen, int force_complete)
void connection_close_immediate(connection_t *conn)
char * alloc_http_authenticator(const char *authenticator)
const char * connection_describe_peer(const connection_t *conn)
Definition connection.c:523
const char * connection_describe(const connection_t *conn)
Definition connection.c:538
dir_connection_t * dir_connection_new(int socket_family)
Definition connection.c:556
int connection_connect(connection_t *conn, const char *address, const tor_addr_t *addr, uint16_t port, int *socket_error)
Header file for connection.c.
#define CONN_TYPE_DIR
Definition connection.h:55
entry_connection_t * connection_ap_make_link(connection_t *partner, char *address, uint16_t port, const char *digest, int session_group, int isolation_flags, int use_begindir, int want_onehop)
Header file for connection_edge.c.
char * consensus_diff_apply(const char *consensus, size_t consensus_len, const char *diff, size_t diff_len)
Definition consdiff.c:1390
int looks_like_a_consensus_diff(const char *document, size_t len)
Definition consdiff.c:1445
Header for consdiff.c.
void control_event_boot_dir(bootstrap_status_t status, int progress)
int control_event_server_status(int severity, const char *format,...)
Header file for control_events.c.
#define BASE64_DIGEST256_LEN
#define HEX_DIGEST256_LEN
int ed25519_public_key_is_zero(const ed25519_public_key_t *pubkey)
void digest256_to_base64(char *d64, const char *digest)
Header for crypto_format.c.
Common functions for cryptographic routines.
Compile-time assertions: CTASSERT(expression).
#define CTASSERT(x)
Definition ctassert.h:44
const char * routerstatus_describe(const routerstatus_t *rs)
Definition describe.c:203
Header file for describe.c.
#define DIGEST_LEN
#define DIGEST256_LEN
Client/server directory connection structure.
Trusted/fallback directory server structure.
STATIC void warn_disallowed_anonymous_compression_method(compress_method_t method)
Definition dirclient.c:2933
void directory_request_set_resource(directory_request_t *req, const char *resource)
Definition dirclient.c:1037
void directory_request_set_or_addr_port(directory_request_t *req, const tor_addr_port_t *p)
Definition dirclient.c:975
STATIC char * accept_encoding_header(void)
Definition dirclient.c:2888
static void connection_dir_download_cert_failed(dir_connection_t *conn, int status_code)
Definition dirclient.c:830
void directory_get_from_all_authorities(uint8_t dir_purpose, uint8_t router_purpose, const char *resource)
Definition dirclient.c:585
static int handle_response_upload_hsdesc(dir_connection_t *, const response_handler_args_t *)
Definition dirclient.c:2788
static void connection_dir_download_routerdesc_failed(dir_connection_t *conn)
Definition dirclient.c:787
void directory_request_set_if_modified_since(directory_request_t *req, time_t if_modified_since)
Definition dirclient.c:1062
#define ALLOW_DIRECTORY_TIME_SKEW
Definition dirclient.c:73
static void dir_microdesc_download_failed(smartlist_t *failed, int status_code, const char *dir_id)
Definition dirclient.c:3018
void connection_dir_client_request_failed(dir_connection_t *conn)
Definition dirclient.c:711
static void connection_dir_retry_bridges(smartlist_t *descs)
Definition dirclient.c:769
static compress_method_t client_meth_allowed_anonymous_compression[]
Definition dirclient.c:2879
static int directory_command_should_use_begindir(const or_options_t *options, const directory_request_t *req, const char **reason)
Definition dirclient.c:886
STATIC int handle_response_fetch_consensus(dir_connection_t *conn, const response_handler_args_t *args)
Definition dirclient.c:2213
static void connection_dir_bridge_routerdesc_failed(dir_connection_t *conn)
Definition dirclient.c:806
STATIC int should_use_directory_guards(const or_options_t *options)
Definition dirclient.c:314
void directory_request_set_dir_addr_port(directory_request_t *req, const tor_addr_port_t *p)
Definition dirclient.c:986
#define MAX_DIR_DL_SIZE
Definition dirclient.c:69
void connection_dir_client_refetch_hsdesc_if_needed(dir_connection_t *dir_conn)
Definition dirclient.c:2855
static int handle_response_fetch_certificate(dir_connection_t *, const response_handler_args_t *)
Definition dirclient.c:2331
void directory_request_set_guard_state(directory_request_t *req, circuit_guard_state_t *state)
Definition dirclient.c:1114
void dirclient_dump_total_dls(void)
Definition dirclient.c:1968
STATIC int allowed_anonymous_connection_compression_method(compress_method_t method)
Definition dirclient.c:2911
void directory_request_set_indirection(directory_request_t *req, dir_indirection_t indirection)
Definition dirclient.c:1024
void directory_request_free_(directory_request_t *req)
Definition dirclient.c:962
static int handle_response_upload_vote(dir_connection_t *, const response_handler_args_t *)
Definition dirclient.c:2693
void directory_request_set_routerstatus(directory_request_t *req, const routerstatus_t *status)
Definition dirclient.c:1139
static int connection_dir_client_reached_eof(dir_connection_t *conn)
Definition dirclient.c:2006
static int handle_response_fetch_desc(dir_connection_t *, const response_handler_args_t *)
Definition dirclient.c:2464
static int load_downloaded_routers(const char *body, smartlist_t *which, int descriptor_digests, int router_purpose, const char *source)
Definition dirclient.c:1789
void directory_request_set_router_purpose(directory_request_t *req, uint8_t router_purpose)
Definition dirclient.c:1008
static int handle_response_fetch_status_vote(dir_connection_t *, const response_handler_args_t *)
Definition dirclient.c:2392
static int body_is_plausible(const char *body, size_t body_len, int purpose)
Definition dirclient.c:1758
static compress_method_t client_meth_pref[]
Definition dirclient.c:2869
static void dir_consensus_request_set_additional_headers(directory_request_t *req, const char *resource)
Definition dirclient.c:369
static int handle_response_fetch_detached_signatures(dir_connection_t *, const response_handler_args_t *)
Definition dirclient.c:2429
void directory_get_from_dirserver(uint8_t dir_purpose, uint8_t router_purpose, const char *resource, int pds_flags, download_want_authority_t want_authority)
Definition dirclient.c:453
static void copy_ipv6_address(char *destination, const char *source, size_t len, int decorate)
Definition dirclient.c:1507
void directory_request_set_directory_id_digest(directory_request_t *req, const char *digest)
Definition dirclient.c:996
static const routerstatus_t * directory_pick_generic_dirserver(dirinfo_type_t type, int pds_flags, uint8_t dir_purpose, circuit_guard_state_t **guard_state_out)
Definition dirclient.c:335
void directory_post_to_dirservers(uint8_t dir_purpose, uint8_t router_purpose, dirinfo_type_t type, const char *payload, size_t payload_len, size_t extrainfo_len)
Definition dirclient.c:229
STATIC const char * dir_conn_purpose_to_string(int purpose)
Definition dirclient.c:97
static int handle_response_upload_signatures(dir_connection_t *, const response_handler_args_t *)
Definition dirclient.c:2729
static int handle_response_upload_dir(dir_connection_t *, const response_handler_args_t *)
Definition dirclient.c:2625
STATIC int handle_response_fetch_hsdesc_v3(dir_connection_t *conn, const response_handler_args_t *args)
Definition dirclient.c:2766
void directory_initiate_request(directory_request_t *request)
Definition dirclient.c:1244
static int directory_request_set_dir_from_routerstatus(directory_request_t *req)
Definition dirclient.c:1151
static int directory_request_dir_contact_info_specified(const directory_request_t *req)
Definition dirclient.c:1124
void directory_request_set_payload(directory_request_t *req, const char *payload, size_t payload_len)
Definition dirclient.c:1048
static char * directory_get_consensus_url(const char *resource)
Definition dirclient.c:1461
int connection_dir_reached_eof(dir_connection_t *conn)
Definition dirclient.c:2834
static void directory_send_command(dir_connection_t *conn, const int direct, const directory_request_t *req)
Definition dirclient.c:1524
directory_request_t * directory_request_new(uint8_t dir_purpose)
Definition dirclient.c:941
STATIC dirinfo_type_t dir_fetch_type(int dir_purpose, int router_purpose, const char *resource)
Definition dirclient.c:133
static int dirind_is_anon(dir_indirection_t ind)
Definition dirclient.c:616
void directory_request_fetch_set_hs_ident(directory_request_t *req, const hs_ident_dir_conn_t *ident)
Definition dirclient.c:1102
STATIC int handle_response_fetch_microdesc(dir_connection_t *conn, const response_handler_args_t *args)
Definition dirclient.c:2565
int router_supports_extrainfo(const char *identity_digest, int is_authority)
Definition dirclient.c:175
int directories_have_accepted_server_descriptor(void)
Definition dirclient.c:198
static uint64_t total_dl[DIR_PURPOSE_MAX_][2]
Definition dirclient.c:1961
static void dir_routerdesc_download_failed(smartlist_t *failed, int status_code, int router_purpose, int was_extrainfo, int was_descriptor_digests)
Definition dirclient.c:2975
void directory_request_add_header(directory_request_t *req, const char *key, const char *val)
Definition dirclient.c:1076
static int compare_strs_(const void **a, const void **b)
Definition dirclient.c:1443
void directory_request_upload_set_hs_ident(directory_request_t *req, const hs_ident_dir_conn_t *ident)
Definition dirclient.c:1088
Header file for dirclient.c.
dir_indirection_t
Definition dirclient.h:34
@ DIRIND_ONEHOP
Definition dirclient.h:37
@ DIRIND_ANON_DIRPORT
Definition dirclient.h:43
@ DIRIND_ANONYMOUS
Definition dirclient.h:39
@ DIRIND_DIRECT_CONN
Definition dirclient.h:41
struct directory_request_t directory_request_t
Definition dirclient.h:52
int dirclient_fetches_from_authorities(const or_options_t *options)
Header for feature/dirclient/dirclient_modes.c.
int purpose_needs_anonymity(uint8_t dir_purpose, uint8_t router_purpose, const char *resource)
Definition directory.c:114
int dir_split_resource_into_fingerprint_pairs(const char *res, smartlist_t *pairs_out)
Definition directory.c:625
int parse_http_response(const char *headers, int *code, time_t *date, compress_method_t *compression, char **reason)
Definition directory.c:393
char * authdir_type_to_string(dirinfo_type_t auth)
Definition directory.c:161
int dir_split_resource_into_fingerprints(const char *resource, smartlist_t *fp_out, int *compressed_out, int flags)
Definition directory.c:684
char * http_get_header(const char *headers, const char *which)
Definition directory.c:358
Header file for directory.c.
#define DIR_PURPOSE_FETCH_EXTRAINFO
Definition directory.h:39
#define DIR_PURPOSE_FETCH_CERTIFICATE
Definition directory.h:57
#define DIR_PURPOSE_UPLOAD_HSDESC
Definition directory.h:67
#define DIR_PURPOSE_FETCH_MICRODESC
Definition directory.h:65
#define DIR_CONN_STATE_CONNECTING
Definition directory.h:20
#define DIR_CONN_STATE_CLIENT_FINISHED
Definition directory.h:26
#define DIR_CONN_STATE_CLIENT_READING
Definition directory.h:24
#define DIR_PURPOSE_UPLOAD_VOTE
Definition directory.h:43
#define DIR_PURPOSE_FETCH_DETACHED_SIGNATURES
Definition directory.h:51
#define DIR_PURPOSE_IS_UPLOAD(p)
Definition directory.h:77
#define DIR_PURPOSE_FETCH_CONSENSUS
Definition directory.h:54
#define DIR_PURPOSE_SERVER
Definition directory.h:60
#define DIR_PURPOSE_FETCH_SERVERDESC
Definition directory.h:36
#define DIR_PURPOSE_UPLOAD_SIGNATURES
Definition directory.h:45
#define DIR_PURPOSE_IS_HS(p)
Definition directory.h:85
#define DIR_CONN_STATE_CLIENT_SENDING
Definition directory.h:22
#define DIR_PURPOSE_FETCH_STATUS_VOTE
Definition directory.h:48
#define DIR_PURPOSE_HAS_FETCHED_HSDESC
Definition directory.h:72
#define DIR_PURPOSE_UPLOAD_DIR
Definition directory.h:41
#define DIR_PURPOSE_FETCH_HSDESC
Definition directory.h:69
dir_server_t * router_get_trusteddirserver_by_digest(const char *digest)
Definition dirlist.c:160
const tor_addr_port_t * trusted_dir_server_get_dirport(const dir_server_t *ds, auth_dirport_usage_t usage, int addr_family)
Definition dirlist.c:529
auth_dirport_usage_t auth_dirport_usage_for_purpose(int purpose)
Definition dirlist.c:304
const tor_addr_port_t * trusted_dir_server_get_dirport_exact(const dir_server_t *ds, auth_dirport_usage_t usage, int addr_family)
Definition dirlist.c:503
dir_server_t * router_get_fallback_dirserver_by_digest(const char *digest)
Definition dirlist.c:181
Header file for dirlist.c.
auth_dirport_usage_t
Definition dirlist.h:22
@ AUTH_USAGE_VOTING
Definition dirlist.h:30
Header file for dirserv.c.
pending_vote_t * dirvote_add_vote(const char *vote_body, time_t time_posted, const char *where_from, const char **msg_out, int *status_out)
Definition dirvote.c:3206
int dirvote_add_signatures(const char *detached_signatures_body, const char *source, const char **msg)
Definition dirvote.c:3771
Header file for dirvote.c.
time_t download_status_increment_failure(download_status_t *dls, int status_code, const char *item, int server, time_t now)
Definition dlstatus.c:249
Header file for dlstatus.c.
Entry connection structure.
void entry_guard_cancel(circuit_guard_state_t **guard_state_p)
int entry_list_is_constrained(const or_options_t *options)
guard_usable_t entry_guard_succeeded(circuit_guard_state_t **guard_state_p)
const node_t * guards_choose_dirguard(uint8_t dir_purpose, circuit_guard_state_t **guard_state_out)
Header file for circuitbuild.c.
const char * escaped(const char *s)
Definition escape.c:126
Header file for fp_pair.c.
Header file for hs_cache.c.
int hs_client_refetch_hsdesc(const ed25519_public_key_t *identity_pk)
Definition hs_client.c:2247
void hs_client_dir_fetch_done(dir_connection_t *dir_conn, const char *reason, const char *body, const int status_code)
Definition hs_client.c:2582
Header file containing client data for the HS subsystem.
void hs_control_desc_event_uploaded(const hs_ident_dir_conn_t *ident, const char *hsdir_id_digest)
Definition hs_control.c:159
void hs_control_desc_event_failed(const hs_ident_dir_conn_t *ident, const char *hsdir_id_digest, const char *reason)
Definition hs_control.c:65
Header file containing control port event related code.
hs_ident_dir_conn_t * hs_ident_dir_conn_dup(const hs_ident_dir_conn_t *src)
Definition hs_ident.c:47
void tor_log(int severity, log_domain_mask_t domain, const char *format,...)
Definition log.c:591
#define log_fn(severity, domain, args,...)
Definition log.h:283
#define LD_HTTP
Definition log.h:76
#define LD_REND
Definition log.h:84
#define log_fn_ratelim(ratelim, severity, domain, args,...)
Definition log.h:288
#define LD_PROTOCOL
Definition log.h:72
#define LOG_DEBUG
Definition log.h:42
#define LD_BUG
Definition log.h:86
#define LD_NET
Definition log.h:66
#define LD_GENERAL
Definition log.h:62
#define LD_DIR
Definition log.h:88
#define LOG_NOTICE
Definition log.h:50
#define LOG_WARN
Definition log.h:53
#define LOG_INFO
Definition log.h:45
void connection_watch_events(connection_t *conn, watchable_events_t events)
Definition mainloop.c:486
void directory_all_unreachable(time_t now)
Definition mainloop.c:1119
void connection_start_reading(connection_t *conn)
Definition mainloop.c:636
void directory_info_has_arrived(time_t now, int from_cache, int suppress_logs)
Definition mainloop.c:1137
Header file for mainloop.c.
@ WRITE_EVENT
Definition mainloop.h:38
@ READ_EVENT
Definition mainloop.h:37
#define tor_free(p)
Definition malloc.h:56
void microdesc_note_outdated_dirserver(const char *relay_digest)
Definition microdesc.c:111
smartlist_t * microdescs_add_to_cache(microdesc_cache_t *cache, const char *s, const char *eos, saved_location_t where, int no_save, time_t listed_at, smartlist_t *requested_digests256)
Definition microdesc.c:293
microdesc_cache_t * get_microdesc_cache(void)
Definition microdesc.c:251
void update_microdescs_from_networkstatus(time_t now)
Definition microdesc.c:1035
Header file for microdesc.c.
networkstatus_t * networkstatus_get_latest_consensus_by_flavor(consensus_flavor_t f)
void routers_update_all_from_networkstatus(time_t now, int dir_version)
int networkstatus_parse_flavor_name(const char *flavname)
int networkstatus_set_current_consensus(const char *consensus, size_t consensus_len, const char *flavor, unsigned flags, const char *source_dir)
download_status_t * router_get_dl_status_by_descriptor_digest(const char *d)
routerstatus_t * router_get_mutable_consensus_status_by_descriptor_digest(networkstatus_t *consensus, const char *digest)
tor_mmap_t * networkstatus_map_cached_consensus(const char *flavorname)
void update_certificate_downloads(time_t now)
const routerstatus_t * router_get_consensus_status_by_id(const char *digest)
int32_t networkstatus_get_param(const networkstatus_t *ns, const char *param_name, int32_t default_val, int32_t min_val, int32_t max_val)
routerstatus_t * router_get_mutable_consensus_status_by_id(const char *digest)
void networkstatus_consensus_download_failed(int status_code, const char *flavname)
Header file for networkstatus.c.
Networkstatus consensus/vote structure.
const routerstatus_t * router_pick_directory_server(dirinfo_type_t type, int flags)
Definition node_select.c:72
const routerstatus_t * router_pick_fallback_dirserver(dirinfo_type_t type, int flags)
const routerstatus_t * router_pick_trusteddirserver(dirinfo_type_t type, int flags)
Header file for node_select.c.
#define PDS_NO_EXISTING_SERVERDESC_FETCH
Definition node_select.h:69
#define PDS_NO_EXISTING_MICRODESC_FETCH
Definition node_select.h:75
#define PDS_IGNORE_FASCISTFIREWALL
Definition node_select.h:62
Node information structure.
const node_t * node_get_by_id(const char *identity_digest)
Definition nodelist.c:226
int count_loading_descriptors_progress(void)
Definition nodelist.c:2826
void router_set_status(const char *digest, int up)
Definition nodelist.c:2427
Header file for nodelist.c.
Master header file for Tor-specific functionality.
@ SAVED_NOWHERE
Definition or.h:723
#define ISO_STREAM
Definition or.h:974
#define ISO_SESSIONGRP
Definition or.h:970
#define SESSION_GROUP_DIRCONN
Definition or.h:983
download_want_authority_t
Definition or.h:752
#define TO_CONN(c)
Definition or.h:709
#define MAX_HEADERS_SIZE
Definition or.h:122
dirinfo_type_t
Definition or.h:890
@ V3_DIRINFO
Definition or.h:893
@ BRIDGE_DIRINFO
Definition or.h:895
@ EXTRAINFO_DIRINFO
Definition or.h:897
@ MICRODESC_DIRINFO
Definition or.h:899
#define ENTRY_TO_CONN(c)
Definition or.h:712
int reachable_addr_allows_rs(const routerstatus_t *rs, firewall_connection_t fw_connection, int pref_only)
Definition policies.c:647
int reachable_addr_allows_addr(const tor_addr_t *addr, uint16_t port, firewall_connection_t fw_connection, int pref_only, int pref_ipv6)
Definition policies.c:536
void reachable_addr_choose_from_node(const node_t *node, firewall_connection_t fw_connection, int pref_only, tor_addr_port_t *ap)
Definition policies.c:988
void reachable_addr_choose_from_rs(const routerstatus_t *rs, firewall_connection_t fw_connection, int pref_only, tor_addr_port_t *ap)
Definition policies.c:874
Header file for policies.c.
void rep_hist_note_used_port(time_t now, uint16_t port)
void rep_hist_note_used_internal(time_t now, int need_uptime, int need_capacity)
Header file for predict_ports.c.
int tor_asprintf(char **strp, const char *fmt,...)
Definition printf.c:75
int tor_snprintf(char *str, size_t size, const char *format,...)
Definition printf.c:27
void relay_address_new_suggestion(const tor_addr_t *suggested_addr, const tor_addr_t *peer_addr, const char *identity_digest)
Header file for relay_find_addr.c.
Header file for rendcommon.c.
const char * router_get_descriptor_gen_reason(void)
Definition router.c:1882
int router_digest_is_me(const char *digest)
Definition router.c:1755
const char * router_purpose_to_string(uint8_t p)
Definition routerinfo.c:98
Header file for routerinfo.c.
Router descriptor structure.
#define ROUTER_PURPOSE_GENERAL
#define ROUTER_PURPOSE_BRIDGE
void router_load_extrainfo_from_string(const char *s, const char *eos, saved_location_t saved_location, smartlist_t *requested_fingerprints, int descriptor_digests)
signed_descriptor_t * router_get_by_extrainfo_digest(const char *digest)
Definition routerlist.c:799
int router_load_routers_from_string(const char *s, const char *eos, saved_location_t saved_location, smartlist_t *requested_fingerprints, int descriptor_digests, const char *prepend_annotations)
Header file for routerlist.c.
Header file for routermode.c.
int routerset_contains_routerstatus(const routerset_t *set, const routerstatus_t *rs, country_t country)
Definition routerset.c:339
Header file for routerset.c.
Header file for selftest.c.
void sr_act_post_consensus(const networkstatus_t *consensus)
This file contains ABI/API of the shared random protocol defined in proposal #250....
void smartlist_add_asprintf(struct smartlist_t *sl, const char *pattern,...)
Definition smartlist.c:36
char * smartlist_join_strings(smartlist_t *sl, const char *join, int terminate, size_t *len_out)
Definition smartlist.c:279
void smartlist_sort(smartlist_t *sl, int(*compare)(const void **a, const void **b))
Definition smartlist.c:334
smartlist_t * smartlist_new(void)
void smartlist_add(smartlist_t *sl, void *element)
#define SMARTLIST_FOREACH_BEGIN(sl, type, var)
#define SMARTLIST_FOREACH(sl, type, var, cmd)
uint8_t digest_sha3_as_signed[DIGEST256_LEN]
unsigned int type
unsigned int purpose
time_t timestamp_last_write_allowed
tor_addr_t addr
unsigned int dirconn_direct
char identity_digest[DIGEST_LEN]
struct circuit_guard_state_t * guard_state
routerstatus_t fake_status
unsigned int has_accepted_serverdesc
ed25519_public_key_t identity_pk
Definition hs_ident.h:96
tor_addr_t HTTPProxyAddr
dirinfo_type_t PublishServerDescriptor_
int FetchServerDescriptors
int FetchDirInfoExtraEarly
char * HTTPProxyAuthenticator
int FetchUselessDescriptors
struct routerset_t * ExcludeNodes
uint16_t HTTPProxyPort
unsigned int caches_extra_info
char identity_digest[DIGEST_LEN]
download_status_t ei_dl_status
size_t size
Definition mmap.h:27
const char * data
Definition mmap.h:26
#define STATIC
Definition testsupport.h:32
#define MOCK_IMPL(rv, funcname, arglist)
void format_rfc1123_time(char *buf, time_t t)
Definition time_fmt.c:213
void format_iso_time(char *buf, time_t t)
Definition time_fmt.c:326
#define tor_assert_nonfatal_unreached()
Definition util_bug.h:177
#define tor_assert(expr)
Definition util_bug.h:103
int strcmpstart(const char *s1, const char *s2)
int fast_mem_is_zero(const char *mem, size_t len)
Definition util_string.c:76
int tor_digest_is_zero(const char *digest)
Definition util_string.c:98
#define ED25519_BASE64_LEN