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

网络

开发平台:

Unix_Linux

  1. /* Copyright (c) 2001-2004, Roger Dingledine.
  2.  * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3.  * Copyright (c) 2007-2009, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. #include "or.h"
  6. #if defined(EXPORTMALLINFO) && defined(HAVE_MALLOC_H) && defined(HAVE_MALLINFO)
  7. #ifndef OPENBSD
  8. #include <malloc.h>
  9. #endif
  10. #endif
  11. /**
  12.  * file directory.c
  13.  * brief Code to send and fetch directories and router
  14.  * descriptors via HTTP.  Directories use dirserv.c to generate the
  15.  * results; clients use routers.c to parse them.
  16.  **/
  17. /* In-points to directory.c:
  18.  *
  19.  * - directory_post_to_dirservers(), called from
  20.  *   router_upload_dir_desc_to_dirservers() in router.c
  21.  *   upload_service_descriptor() in rendservice.c
  22.  * - directory_get_from_dirserver(), called from
  23.  *   rend_client_refetch_renddesc() in rendclient.c
  24.  *   run_scheduled_events() in main.c
  25.  *   do_hup() in main.c
  26.  * - connection_dir_process_inbuf(), called from
  27.  *   connection_process_inbuf() in connection.c
  28.  * - connection_dir_finished_flushing(), called from
  29.  *   connection_finished_flushing() in connection.c
  30.  * - connection_dir_finished_connecting(), called from
  31.  *   connection_finished_connecting() in connection.c
  32.  */
  33. static void directory_send_command(dir_connection_t *conn,
  34.                              int purpose, int direct, const char *resource,
  35.                              const char *payload, size_t payload_len,
  36.                              int supports_conditional_consensus,
  37.                              time_t if_modified_since);
  38. static int directory_handle_command(dir_connection_t *conn);
  39. static int body_is_plausible(const char *body, size_t body_len, int purpose);
  40. static int purpose_needs_anonymity(uint8_t dir_purpose,
  41.                                    uint8_t router_purpose);
  42. static char *http_get_header(const char *headers, const char *which);
  43. static void http_set_address_origin(const char *headers, connection_t *conn);
  44. static void connection_dir_download_networkstatus_failed(
  45.                                dir_connection_t *conn, int status_code);
  46. static void connection_dir_download_routerdesc_failed(dir_connection_t *conn);
  47. static void connection_dir_download_cert_failed(
  48.                                dir_connection_t *conn, int status_code);
  49. static void dir_networkstatus_download_failed(smartlist_t *failed,
  50.                                               int status_code);
  51. static void dir_routerdesc_download_failed(smartlist_t *failed,
  52.                                            int status_code,
  53.                                            int router_purpose,
  54.                                            int was_extrainfo,
  55.                                            int was_descriptor_digests);
  56. static void note_client_request(int purpose, int compressed, size_t bytes);
  57. static int client_likes_consensus(networkstatus_t *v, const char *want_url);
  58. static void directory_initiate_command_rend(const char *address,
  59.                                             const tor_addr_t *addr,
  60.                                             uint16_t or_port,
  61.                                             uint16_t dir_port,
  62.                                             int supports_conditional_consensus,
  63.                                             int supports_begindir,
  64.                                             const char *digest,
  65.                                             uint8_t dir_purpose,
  66.                                             uint8_t router_purpose,
  67.                                             int anonymized_connection,
  68.                                             const char *resource,
  69.                                             const char *payload,
  70.                                             size_t payload_len,
  71.                                             time_t if_modified_since,
  72.                                             const rend_data_t *rend_query);
  73. /********* START VARIABLES **********/
  74. /** How far in the future do we allow a directory server to tell us it is
  75.  * before deciding that one of us has the wrong time? */
  76. #define ALLOW_DIRECTORY_TIME_SKEW (30*60)
  77. #define X_ADDRESS_HEADER "X-Your-Address-Is: "
  78. /** HTTP cache control: how long do we tell proxies they can cache each
  79.  * kind of document we serve? */
  80. #define FULL_DIR_CACHE_LIFETIME (60*60)
  81. #define RUNNINGROUTERS_CACHE_LIFETIME (20*60)
  82. #define DIRPORTFRONTPAGE_CACHE_LIFETIME (20*60)
  83. #define NETWORKSTATUS_CACHE_LIFETIME (5*60)
  84. #define ROUTERDESC_CACHE_LIFETIME (30*60)
  85. #define ROUTERDESC_BY_DIGEST_CACHE_LIFETIME (48*60*60)
  86. #define ROBOTS_CACHE_LIFETIME (24*60*60)
  87. /********* END VARIABLES ************/
  88. /** Return true iff the directory purpose 'purpose' must use an
  89.  * anonymous connection to a directory. */
  90. static int
  91. purpose_needs_anonymity(uint8_t dir_purpose, uint8_t router_purpose)
  92. {
  93.   if (get_options()->AllDirActionsPrivate)
  94.     return 1;
  95.   if (router_purpose == ROUTER_PURPOSE_BRIDGE && has_completed_circuit)
  96.     return 1; /* if no circuits yet, we may need this info to bootstrap. */
  97.   if (dir_purpose == DIR_PURPOSE_UPLOAD_DIR ||
  98.       dir_purpose == DIR_PURPOSE_UPLOAD_VOTE ||
  99.       dir_purpose == DIR_PURPOSE_UPLOAD_SIGNATURES ||
  100.       dir_purpose == DIR_PURPOSE_FETCH_V2_NETWORKSTATUS ||
  101.       dir_purpose == DIR_PURPOSE_FETCH_STATUS_VOTE ||
  102.       dir_purpose == DIR_PURPOSE_FETCH_DETACHED_SIGNATURES ||
  103.       dir_purpose == DIR_PURPOSE_FETCH_CONSENSUS ||
  104.       dir_purpose == DIR_PURPOSE_FETCH_CERTIFICATE ||
  105.       dir_purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
  106.       dir_purpose == DIR_PURPOSE_FETCH_EXTRAINFO)
  107.     return 0;
  108.   return 1;
  109. }
  110. /** Return a newly allocated string describing <b>auth</b>. */
  111. char *
  112. authority_type_to_string(authority_type_t auth)
  113. {
  114.   char *result;
  115.   smartlist_t *lst = smartlist_create();
  116.   if (auth & V1_AUTHORITY)
  117.     smartlist_add(lst, (void*)"V1");
  118.   if (auth & V2_AUTHORITY)
  119.     smartlist_add(lst, (void*)"V2");
  120.   if (auth & BRIDGE_AUTHORITY)
  121.     smartlist_add(lst, (void*)"Bridge");
  122.   if (auth & HIDSERV_AUTHORITY)
  123.     smartlist_add(lst, (void*)"Hidden service");
  124.   if (smartlist_len(lst)) {
  125.     result = smartlist_join_strings(lst, ", ", 0, NULL);
  126.   } else {
  127.     result = tor_strdup("[Not an authority]");
  128.   }
  129.   smartlist_free(lst);
  130.   return result;
  131. }
  132. /** Return a string describing a given directory connection purpose. */
  133. static const char *
  134. dir_conn_purpose_to_string(int purpose)
  135. {
  136.   switch (purpose)
  137.     {
  138.     case DIR_PURPOSE_FETCH_RENDDESC:
  139.       return "hidden-service descriptor fetch";
  140.     case DIR_PURPOSE_UPLOAD_DIR:
  141.       return "server descriptor upload";
  142.     case DIR_PURPOSE_UPLOAD_RENDDESC:
  143.       return "hidden-service descriptor upload";
  144.     case DIR_PURPOSE_UPLOAD_VOTE:
  145.       return "server vote upload";
  146.     case DIR_PURPOSE_UPLOAD_SIGNATURES:
  147.       return "consensus signature upload";
  148.     case DIR_PURPOSE_FETCH_V2_NETWORKSTATUS:
  149.       return "network-status fetch";
  150.     case DIR_PURPOSE_FETCH_SERVERDESC:
  151.       return "server descriptor fetch";
  152.     case DIR_PURPOSE_FETCH_EXTRAINFO:
  153.       return "extra-info fetch";
  154.     case DIR_PURPOSE_FETCH_CONSENSUS:
  155.       return "consensus network-status fetch";
  156.     case DIR_PURPOSE_FETCH_CERTIFICATE:
  157.       return "authority cert fetch";
  158.     case DIR_PURPOSE_FETCH_STATUS_VOTE:
  159.       return "status vote fetch";
  160.     case DIR_PURPOSE_FETCH_DETACHED_SIGNATURES:
  161.       return "consensus signature fetch";
  162.     case DIR_PURPOSE_FETCH_RENDDESC_V2:
  163.       return "hidden-service v2 descriptor fetch";
  164.     case DIR_PURPOSE_UPLOAD_RENDDESC_V2:
  165.       return "hidden-service v2 descriptor upload";
  166.     }
  167.   log_warn(LD_BUG, "Called with unknown purpose %d", purpose);
  168.   return "(unknown)";
  169. }
  170. /** Return true iff <b>identity_digest</b> is the digest of a router we
  171.  * believe to support extrainfo downloads.  (If <b>is_authority</b> we do
  172.  * additional checking that's only valid for authorities.) */
  173. int
  174. router_supports_extrainfo(const char *identity_digest, int is_authority)
  175. {
  176.   routerinfo_t *ri = router_get_by_digest(identity_digest);
  177.   if (ri) {
  178.     if (ri->caches_extra_info)
  179.       return 1;
  180.     if (is_authority && ri->platform &&
  181.         tor_version_as_new_as(ri->platform, "Tor 0.2.0.0-alpha-dev (r10070)"))
  182.       return 1;
  183.   }
  184.   if (is_authority) {
  185.     routerstatus_t *rs = router_get_consensus_status_by_id(identity_digest);
  186.     if (rs && rs->version_supports_extrainfo_upload)
  187.       return 1;
  188.   }
  189.   return 0;
  190. }
  191. /** Return true iff any trusted directory authority has accepted our
  192.  * server descriptor.
  193.  *
  194.  * We consider any authority sufficient because waiting for all of
  195.  * them means it never happens while any authority is down; we don't
  196.  * go for something more complex in the middle (like >1/3 or >1/2 or
  197.  * >=1/2) because that doesn't seem necessary yet.
  198.  */
  199. int
  200. directories_have_accepted_server_descriptor(void)
  201. {
  202.   smartlist_t *servers = router_get_trusted_dir_servers();
  203.   or_options_t *options = get_options();
  204.   SMARTLIST_FOREACH(servers, trusted_dir_server_t *, d, {
  205.     if ((d->type & options->_PublishServerDescriptor) &&
  206.         d->has_accepted_serverdesc) {
  207.       return 1;
  208.     }
  209.   });
  210.   return 0;
  211. }
  212. /** Start a connection to every suitable directory authority, using
  213.  * connection purpose 'purpose' and uploading the payload 'payload'
  214.  * (length 'payload_len').  The purpose should be one of
  215.  * 'DIR_PURPOSE_UPLOAD_DIR' or 'DIR_PURPOSE_UPLOAD_RENDDESC'.
  216.  *
  217.  * <b>type</b> specifies what sort of dir authorities (V1, V2,
  218.  * HIDSERV, BRIDGE) we should upload to.
  219.  *
  220.  * If <b>extrainfo_len</b> is nonzero, the first <b>payload_len</b> bytes of
  221.  * <b>payload</b> hold a router descriptor, and the next <b>extrainfo_len</b>
  222.  * bytes of <b>payload</b> hold an extra-info document.  Upload the descriptor
  223.  * to all authorities, and the extra-info document to all authorities that
  224.  * support it.
  225.  */
  226. void
  227. directory_post_to_dirservers(uint8_t dir_purpose, uint8_t router_purpose,
  228.                              authority_type_t type,
  229.                              const char *payload,
  230.                              size_t payload_len, size_t extrainfo_len)
  231. {
  232.   int post_via_tor;
  233.   smartlist_t *dirservers = router_get_trusted_dir_servers();
  234.   int found = 0;
  235.   tor_assert(dirservers);
  236.   /* This tries dirservers which we believe to be down, but ultimately, that's
  237.    * harmless, and we may as well err on the side of getting things uploaded.
  238.    */
  239.   SMARTLIST_FOREACH_BEGIN(dirservers, trusted_dir_server_t *, ds) {
  240.       routerstatus_t *rs = &(ds->fake_status);
  241.       size_t upload_len = payload_len;
  242.       tor_addr_t ds_addr;
  243.       if ((type & ds->type) == 0)
  244.         continue;
  245.       found = 1; /* at least one authority of this type was listed */
  246.       if (dir_purpose == DIR_PURPOSE_UPLOAD_DIR)
  247.         ds->has_accepted_serverdesc = 0;
  248.       if (extrainfo_len && router_supports_extrainfo(ds->digest, 1)) {
  249.         upload_len += extrainfo_len;
  250.         log_info(LD_DIR, "Uploading an extrainfo too (length %d)",
  251.                  (int) extrainfo_len);
  252.       }
  253.       tor_addr_from_ipv4h(&ds_addr, ds->addr);
  254.       post_via_tor = purpose_needs_anonymity(dir_purpose, router_purpose) ||
  255.         !fascist_firewall_allows_address_dir(&ds_addr, ds->dir_port);
  256.       directory_initiate_command_routerstatus(rs, dir_purpose,
  257.                                               router_purpose,
  258.                                               post_via_tor,
  259.                                               NULL, payload, upload_len, 0);
  260.   } SMARTLIST_FOREACH_END(ds);
  261.   if (!found) {
  262.     char *s = authority_type_to_string(type);
  263.     log_warn(LD_DIR, "Publishing server descriptor to directory authorities "
  264.              "of type '%s', but no authorities of that type listed!", s);
  265.     tor_free(s);
  266.   }
  267. }
  268. /** Start a connection to a random running directory server, using
  269.  * connection purpose <b>dir_purpose</b>, intending to fetch descriptors
  270.  * of purpose <b>router_purpose</b>, and requesting <b>resource</b>.
  271.  * Use <b>pds_flags</b> as arguments to router_pick_directory_server()
  272.  * or router_pick_trusteddirserver().
  273.  */
  274. void
  275. directory_get_from_dirserver(uint8_t dir_purpose, uint8_t router_purpose,
  276.                              const char *resource, int pds_flags)
  277. {
  278.   routerstatus_t *rs = NULL;
  279.   or_options_t *options = get_options();
  280.   int prefer_authority = directory_fetches_from_authorities(options);
  281.   int get_via_tor = purpose_needs_anonymity(dir_purpose, router_purpose);
  282.   authority_type_t type;
  283.   time_t if_modified_since = 0;
  284.   /* FFFF we could break this switch into its own function, and call
  285.    * it elsewhere in directory.c. -RD */
  286.   switch (dir_purpose) {
  287.     case DIR_PURPOSE_FETCH_EXTRAINFO:
  288.       type = EXTRAINFO_CACHE |
  289.              (router_purpose == ROUTER_PURPOSE_BRIDGE ? BRIDGE_AUTHORITY :
  290.                                                         V2_AUTHORITY);
  291.       break;
  292.     case DIR_PURPOSE_FETCH_V2_NETWORKSTATUS:
  293.     case DIR_PURPOSE_FETCH_SERVERDESC:
  294.       type = (router_purpose == ROUTER_PURPOSE_BRIDGE ? BRIDGE_AUTHORITY :
  295.                                                         V2_AUTHORITY);
  296.       break;
  297.     case DIR_PURPOSE_FETCH_RENDDESC:
  298.       type = HIDSERV_AUTHORITY;
  299.       break;
  300.     case DIR_PURPOSE_FETCH_STATUS_VOTE:
  301.     case DIR_PURPOSE_FETCH_DETACHED_SIGNATURES:
  302.       type = V3_AUTHORITY;
  303.       break;
  304.     case DIR_PURPOSE_FETCH_CONSENSUS:
  305.     case DIR_PURPOSE_FETCH_CERTIFICATE:
  306.       type = V3_AUTHORITY;
  307.       break;
  308.     default:
  309.       log_warn(LD_BUG, "Unexpected purpose %d", (int)dir_purpose);
  310.       return;
  311.   }
  312.   if (DIR_PURPOSE_FETCH_CONSENSUS) {
  313.     networkstatus_t *v = networkstatus_get_latest_consensus();
  314.     if (v)
  315.       if_modified_since = v->valid_after + 180;
  316.   }
  317.   if (!options->FetchServerDescriptors && type != HIDSERV_AUTHORITY)
  318.     return;
  319.   if (!get_via_tor) {
  320.     if (options->UseBridges && type != BRIDGE_AUTHORITY) {
  321.       /* want to ask a running bridge for which we have a descriptor. */
  322.       /* XXX022 we assume that all of our bridges can answer any
  323.        * possible directory question. This won't be true forever. -RD */
  324.       /* It certainly is not true with conditional consensus downloading,
  325.        * so, for now, never assume the server supports that. */
  326.       routerinfo_t *ri = choose_random_entry(NULL);
  327.       if (ri) {
  328.         tor_addr_t addr;
  329.         tor_addr_from_ipv4h(&addr, ri->addr);
  330.         directory_initiate_command(ri->address, &addr,
  331.                                    ri->or_port, 0,
  332.                                    0, /* don't use conditional consensus url */
  333.                                    1, ri->cache_info.identity_digest,
  334.                                    dir_purpose,
  335.                                    router_purpose,
  336.                                    0, resource, NULL, 0, if_modified_since);
  337.       } else
  338.         log_notice(LD_DIR, "Ignoring directory request, since no bridge "
  339.                            "nodes are available yet.");
  340.       return;
  341.     } else {
  342.       if (prefer_authority || type == BRIDGE_AUTHORITY) {
  343.         /* only ask authdirservers, and don't ask myself */
  344.         rs = router_pick_trusteddirserver(type, pds_flags);
  345.         if (rs == NULL && (pds_flags & PDS_NO_EXISTING_SERVERDESC_FETCH)) {
  346.           /* We don't want to fetch from any authorities that we're currently
  347.            * fetching server descriptors from, and we got no match.  Did we
  348.            * get no match because all the authorities have connections
  349.            * fetching server descriptors (in which case we should just
  350.            * return,) or because all the authorities are down or on fire or
  351.            * unreachable or something (in which case we should go on with
  352.            * our fallback code)? */
  353.           pds_flags &= ~PDS_NO_EXISTING_SERVERDESC_FETCH;
  354.           rs = router_pick_trusteddirserver(type, pds_flags);
  355.           if (rs) {
  356.             log_debug(LD_DIR, "Deferring serverdesc fetch: all authorities "
  357.                       "are in use.");
  358.             return;
  359.           }
  360.         }
  361.       }
  362.       if (!rs && type != BRIDGE_AUTHORITY) {
  363.         /* anybody with a non-zero dirport will do */
  364.         rs = router_pick_directory_server(type, pds_flags);
  365.         if (!rs) {
  366.           log_info(LD_DIR, "No router found for %s; falling back to "
  367.                    "dirserver list.", dir_conn_purpose_to_string(dir_purpose));
  368.           rs = router_pick_trusteddirserver(type, pds_flags);
  369.           if (!rs)
  370.             get_via_tor = 1; /* last resort: try routing it via Tor */
  371.         }
  372.       }
  373.     }
  374.   } else { /* get_via_tor */
  375.     /* Never use fascistfirewall; we're going via Tor. */
  376.     if (dir_purpose == DIR_PURPOSE_FETCH_RENDDESC) {
  377.       /* only ask hidserv authorities, any of them will do */
  378.       pds_flags |= PDS_IGNORE_FASCISTFIREWALL|PDS_ALLOW_SELF;
  379.       rs = router_pick_trusteddirserver(HIDSERV_AUTHORITY, pds_flags);
  380.     } else {
  381.       /* anybody with a non-zero dirport will do. Disregard firewalls. */
  382.       pds_flags |= PDS_IGNORE_FASCISTFIREWALL;
  383.       rs = router_pick_directory_server(type, pds_flags);
  384.       /* If we have any hope of building an indirect conn, we know some router
  385.        * descriptors.  If (rs==NULL), we can't build circuits anyway, so
  386.        * there's no point in falling back to the authorities in this case. */
  387.     }
  388.   }
  389.   if (rs)
  390.     directory_initiate_command_routerstatus(rs, dir_purpose,
  391.                                             router_purpose,
  392.                                             get_via_tor,
  393.                                             resource, NULL, 0,
  394.                                             if_modified_since);
  395.   else {
  396.     log_notice(LD_DIR,
  397.                "While fetching directory info, "
  398.                "no running dirservers known. Will try again later. "
  399.                "(purpose %d)", dir_purpose);
  400.     if (!purpose_needs_anonymity(dir_purpose, router_purpose)) {
  401.       /* remember we tried them all and failed. */
  402.       directory_all_unreachable(time(NULL));
  403.     }
  404.   }
  405. }
  406. /** As directory_get_from_dirserver, but initiates a request to <i>every</i>
  407.  * directory authority other than ourself.  Only for use by authorities when
  408.  * searching for missing information while voting. */
  409. void
  410. directory_get_from_all_authorities(uint8_t dir_purpose,
  411.                                    uint8_t router_purpose,
  412.                                    const char *resource)
  413. {
  414.   tor_assert(dir_purpose == DIR_PURPOSE_FETCH_STATUS_VOTE ||
  415.              dir_purpose == DIR_PURPOSE_FETCH_DETACHED_SIGNATURES);
  416.   SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
  417.                     trusted_dir_server_t *, ds,
  418.     {
  419.       routerstatus_t *rs;
  420.       if (router_digest_is_me(ds->digest))
  421.         continue;
  422.       if (!(ds->type & V3_AUTHORITY))
  423.         continue;
  424.       rs = &ds->fake_status;
  425.       directory_initiate_command_routerstatus(rs, dir_purpose, router_purpose,
  426.                                               0, resource, NULL, 0, 0);
  427.     });
  428. }
  429. /** Same as directory_initiate_command_routerstatus(), but accepts
  430.  * rendezvous data to fetch a hidden service descriptor. */
  431. void
  432. directory_initiate_command_routerstatus_rend(routerstatus_t *status,
  433.                                              uint8_t dir_purpose,
  434.                                              uint8_t router_purpose,
  435.                                              int anonymized_connection,
  436.                                              const char *resource,
  437.                                              const char *payload,
  438.                                              size_t payload_len,
  439.                                              time_t if_modified_since,
  440.                                              const rend_data_t *rend_query)
  441. {
  442.   routerinfo_t *router;
  443.   char address_buf[INET_NTOA_BUF_LEN+1];
  444.   struct in_addr in;
  445.   const char *address;
  446.   tor_addr_t addr;
  447.   router = router_get_by_digest(status->identity_digest);
  448.   if (!router && anonymized_connection) {
  449.     log_info(LD_DIR, "Not sending anonymized request to directory '%s'; we "
  450.                      "don't have its router descriptor.", status->nickname);
  451.     return;
  452.   } else if (router) {
  453.     address = router->address;
  454.   } else {
  455.     in.s_addr = htonl(status->addr);
  456.     tor_inet_ntoa(&in, address_buf, sizeof(address_buf));
  457.     address = address_buf;
  458.   }
  459.   tor_addr_from_ipv4h(&addr, status->addr);
  460.   directory_initiate_command_rend(address, &addr,
  461.                              status->or_port, status->dir_port,
  462.                              status->version_supports_conditional_consensus,
  463.                              status->version_supports_begindir,
  464.                              status->identity_digest,
  465.                              dir_purpose, router_purpose,
  466.                              anonymized_connection, resource,
  467.                              payload, payload_len, if_modified_since,
  468.                              rend_query);
  469. }
  470. /** Launch a new connection to the directory server <b>status</b> to
  471.  * upload or download a server or rendezvous
  472.  * descriptor. <b>dir_purpose</b> determines what
  473.  * kind of directory connection we're launching, and must be one of
  474.  * DIR_PURPOSE_{FETCH|UPLOAD}_{DIR|RENDDESC|RENDDESC_V2}. <b>router_purpose</b>
  475.  * specifies the descriptor purposes we have in mind (currently only
  476.  * used for FETCH_DIR).
  477.  *
  478.  * When uploading, <b>payload</b> and <b>payload_len</b> determine the content
  479.  * of the HTTP post.  Otherwise, <b>payload</b> should be NULL.
  480.  *
  481.  * When fetching a rendezvous descriptor, <b>resource</b> is the service ID we
  482.  * want to fetch.
  483.  */
  484. void
  485. directory_initiate_command_routerstatus(routerstatus_t *status,
  486.                                         uint8_t dir_purpose,
  487.                                         uint8_t router_purpose,
  488.                                         int anonymized_connection,
  489.                                         const char *resource,
  490.                                         const char *payload,
  491.                                         size_t payload_len,
  492.                                         time_t if_modified_since)
  493. {
  494.   directory_initiate_command_routerstatus_rend(status, dir_purpose,
  495.                                           router_purpose,
  496.                                           anonymized_connection, resource,
  497.                                           payload, payload_len,
  498.                                           if_modified_since, NULL);
  499. }
  500. /** Return true iff <b>conn</b> is the client side of a directory connection
  501.  * we launched to ourself in order to determine the reachability of our
  502.  * dir_port. */
  503. static int
  504. directory_conn_is_self_reachability_test(dir_connection_t *conn)
  505. {
  506.   if (conn->requested_resource &&
  507.       !strcmpstart(conn->requested_resource,"authority")) {
  508.     routerinfo_t *me = router_get_my_routerinfo();
  509.     if (me &&
  510.         router_digest_is_me(conn->identity_digest) &&
  511.         tor_addr_eq_ipv4h(&conn->_base.addr, me->addr) && /*XXXX prop 118*/
  512.         me->dir_port == conn->_base.port)
  513.       return 1;
  514.   }
  515.   return 0;
  516. }
  517. /** Called when we are unable to complete the client's request to a directory
  518.  * server due to a network error: Mark the router as down and try again if
  519.  * possible.
  520.  */
  521. void
  522. connection_dir_request_failed(dir_connection_t *conn)
  523. {
  524.   if (directory_conn_is_self_reachability_test(conn)) {
  525.     return; /* this was a test fetch. don't retry. */
  526.   }
  527.   if (entry_list_can_grow(get_options()))
  528.     router_set_status(conn->identity_digest, 0); /* don't try him again */
  529.   if (conn->_base.purpose == DIR_PURPOSE_FETCH_V2_NETWORKSTATUS) {
  530.     log_info(LD_DIR, "Giving up on directory server at '%s'; retrying",
  531.              conn->_base.address);
  532.     connection_dir_download_networkstatus_failed(conn, -1);
  533.   } else if (conn->_base.purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
  534.              conn->_base.purpose == DIR_PURPOSE_FETCH_EXTRAINFO) {
  535.     log_info(LD_DIR, "Giving up on directory server at '%s'; retrying",
  536.              conn->_base.address);
  537.     connection_dir_download_routerdesc_failed(conn);
  538.   } else if (conn->_base.purpose == DIR_PURPOSE_FETCH_CONSENSUS) {
  539.     networkstatus_consensus_download_failed(0);
  540.   } else if (conn->_base.purpose == DIR_PURPOSE_FETCH_CERTIFICATE) {
  541.     log_info(LD_DIR, "Giving up on directory server at '%s'; retrying",
  542.              conn->_base.address);
  543.     connection_dir_download_cert_failed(conn, 0);
  544.   } else if (conn->_base.purpose == DIR_PURPOSE_FETCH_DETACHED_SIGNATURES) {
  545.     log_info(LD_DIR, "Giving up downloading detached signatures from '%s'",
  546.              conn->_base.address);
  547.   } else if (conn->_base.purpose == DIR_PURPOSE_FETCH_STATUS_VOTE) {
  548.     log_info(LD_DIR, "Giving up downloading votes from '%s'",
  549.              conn->_base.address);
  550.   }
  551. }
  552. /** Called when an attempt to download one or more network status
  553.  * documents on connection <b>conn</b> failed. Decide whether to
  554.  * retry the fetch now, later, or never.
  555.  */
  556. static void
  557. connection_dir_download_networkstatus_failed(dir_connection_t *conn,
  558.                                              int status_code)
  559. {
  560.   if (!conn->requested_resource) {
  561.     /* We never reached directory_send_command, which means that we never
  562.      * opened a network connection.  Either we're out of sockets, or the
  563.      * network is down.  Either way, retrying would be pointless. */
  564.     return;
  565.   }
  566.   if (!strcmpstart(conn->requested_resource, "all")) {
  567.     /* We're a non-authoritative directory cache; try again. Ignore status
  568.      * code, since we don't want to keep trying forever in a tight loop
  569.      * if all the authorities are shutting us out. */
  570.     smartlist_t *trusted_dirs = router_get_trusted_dir_servers();
  571.     SMARTLIST_FOREACH(trusted_dirs, trusted_dir_server_t *, ds,
  572.                       download_status_failed(&ds->v2_ns_dl_status, 0));
  573.     directory_get_from_dirserver(conn->_base.purpose, conn->router_purpose,
  574.                                  "all.z", 0 /* don't retry_if_no_servers */);
  575.   } else if (!strcmpstart(conn->requested_resource, "fp/")) {
  576.     /* We were trying to download by fingerprint; mark them all as having
  577.      * failed, and possibly retry them later.*/
  578.     smartlist_t *failed = smartlist_create();
  579.     dir_split_resource_into_fingerprints(conn->requested_resource+3,
  580.                                          failed, NULL, 0, 0);
  581.     if (smartlist_len(failed)) {
  582.       dir_networkstatus_download_failed(failed, status_code);
  583.       SMARTLIST_FOREACH(failed, char *, cp, tor_free(cp));
  584.     }
  585.     smartlist_free(failed);
  586.   }
  587. }
  588. /** Called when an attempt to download one or more router descriptors
  589.  * or extra-info documents on connection <b>conn</b> failed.
  590.  */
  591. static void
  592. connection_dir_download_routerdesc_failed(dir_connection_t *conn)
  593. {
  594.   /* No need to increment the failure count for routerdescs, since
  595.    * it's not their fault. */
  596.   /* No need to relaunch descriptor downloads here: we already do it
  597.    * every 10 or 60 seconds (FOO_DESCRIPTOR_RETRY_INTERVAL) in main.c. */
  598.   tor_assert(conn->_base.purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
  599.              conn->_base.purpose == DIR_PURPOSE_FETCH_EXTRAINFO);
  600.   (void) conn;
  601. }
  602. /** Called when an attempt to fetch a certificate fails. */
  603. static void
  604. connection_dir_download_cert_failed(dir_connection_t *conn, int status)
  605. {
  606.   smartlist_t *failed;
  607.   tor_assert(conn->_base.purpose == DIR_PURPOSE_FETCH_CERTIFICATE);
  608.   if (!conn->requested_resource)
  609.     return;
  610.   failed = smartlist_create();
  611.   dir_split_resource_into_fingerprints(conn->requested_resource+3,
  612.                                        failed, NULL, 1, 0);
  613.   SMARTLIST_FOREACH(failed, char *, cp,
  614.   {
  615.     authority_cert_dl_failed(cp, status);
  616.     tor_free(cp);
  617.   });
  618.   smartlist_free(failed);
  619.   update_certificate_downloads(time(NULL));
  620. }
  621. /** Evaluate the situation and decide if we should use an encrypted
  622.  * "begindir-style" connection for this directory request.
  623.  * 1) If or_port is 0, or it's a direct conn and or_port is firewalled
  624.  *    or we're a dir mirror, no.
  625.  * 2) If we prefer to avoid begindir conns, and we're not fetching or
  626.  * publishing a bridge relay descriptor, no.
  627.  * 3) Else yes.
  628.  */
  629. static int
  630. directory_command_should_use_begindir(or_options_t *options,
  631.                                       const tor_addr_t *addr,
  632.                                       int or_port, uint8_t router_purpose,
  633.                                       int anonymized_connection)
  634. {
  635.   if (!or_port)
  636.     return 0; /* We don't know an ORPort -- no chance. */
  637.   if (!anonymized_connection)
  638.     if (!fascist_firewall_allows_address_or(addr, or_port) ||
  639.         directory_fetches_from_authorities(options) ||
  640.         (server_mode(options) && !options->Address))
  641.       return 0; /* We're firewalled or are acting like a relay -- also no. */
  642.   if (!options->TunnelDirConns &&
  643.       router_purpose != ROUTER_PURPOSE_BRIDGE)
  644.     return 0; /* We prefer to avoid using begindir conns. Fine. */
  645.   return 1;
  646. }
  647. /** Helper for directory_initiate_command_routerstatus: send the
  648.  * command to a server whose address is <b>address</b>, whose IP is
  649.  * <b>addr</b>, whose directory port is <b>dir_port</b>, whose tor version
  650.  * <b>supports_begindir</b>, and whose identity key digest is
  651.  * <b>digest</b>. */
  652. void
  653. directory_initiate_command(const char *address, const tor_addr_t *_addr,
  654.                            uint16_t or_port, uint16_t dir_port,
  655.                            int supports_conditional_consensus,
  656.                            int supports_begindir, const char *digest,
  657.                            uint8_t dir_purpose, uint8_t router_purpose,
  658.                            int anonymized_connection, const char *resource,
  659.                            const char *payload, size_t payload_len,
  660.                            time_t if_modified_since)
  661. {
  662.   directory_initiate_command_rend(address, _addr, or_port, dir_port,
  663.                              supports_conditional_consensus,
  664.                              supports_begindir, digest, dir_purpose,
  665.                              router_purpose, anonymized_connection,
  666.                              resource, payload, payload_len,
  667.                              if_modified_since, NULL);
  668. }
  669. /** Same as directory_initiate_command(), but accepts rendezvous data to
  670.  * fetch a hidden service descriptor. */
  671. static void
  672. directory_initiate_command_rend(const char *address, const tor_addr_t *_addr,
  673.                                 uint16_t or_port, uint16_t dir_port,
  674.                                 int supports_conditional_consensus,
  675.                                 int supports_begindir, const char *digest,
  676.                                 uint8_t dir_purpose, uint8_t router_purpose,
  677.                                 int anonymized_connection,
  678.                                 const char *resource,
  679.                                 const char *payload, size_t payload_len,
  680.                                 time_t if_modified_since,
  681.                                 const rend_data_t *rend_query)
  682. {
  683.   dir_connection_t *conn;
  684.   or_options_t *options = get_options();
  685.   int socket_error = 0;
  686.   int use_begindir = supports_begindir &&
  687.                      directory_command_should_use_begindir(options, _addr,
  688.                        or_port, router_purpose, anonymized_connection);
  689.   tor_addr_t addr;
  690.   tor_assert(address);
  691.   tor_assert(_addr);
  692.   tor_assert(or_port || dir_port);
  693.   tor_assert(digest);
  694.   tor_addr_copy(&addr, _addr);
  695.   log_debug(LD_DIR, "anonymized %d, use_begindir %d.",
  696.             anonymized_connection, use_begindir);
  697.   log_debug(LD_DIR, "Initiating %s", dir_conn_purpose_to_string(dir_purpose));
  698.   conn = dir_connection_new(AF_INET);
  699.   /* set up conn so it's got all the data we need to remember */
  700.   tor_addr_copy(&conn->_base.addr, &addr);
  701.   conn->_base.port = use_begindir ? or_port : dir_port;
  702.   conn->_base.address = tor_strdup(address);
  703.   memcpy(conn->identity_digest, digest, DIGEST_LEN);
  704.   conn->_base.purpose = dir_purpose;
  705.   conn->router_purpose = router_purpose;
  706.   /* give it an initial state */
  707.   conn->_base.state = DIR_CONN_STATE_CONNECTING;
  708.   /* decide whether we can learn our IP address from this conn */
  709.   conn->dirconn_direct = !anonymized_connection;
  710.   /* copy rendezvous data, if any */
  711.   if (rend_query)
  712.     conn->rend_data = rend_data_dup(rend_query);
  713.   if (!anonymized_connection && !use_begindir) {
  714.     /* then we want to connect to dirport directly */
  715.     if (options->HttpProxy) {
  716.       tor_addr_from_ipv4h(&addr, options->HttpProxyAddr);
  717.       dir_port = options->HttpProxyPort;
  718.     }
  719.     switch (connection_connect(TO_CONN(conn), conn->_base.address, &addr,
  720.                                dir_port, &socket_error)) {
  721.       case -1:
  722.         connection_dir_request_failed(conn); /* retry if we want */
  723.         /* XXX we only pass 'conn' above, not 'resource', 'payload',
  724.          * etc. So in many situations it can't retry! -RD */
  725.         connection_free(TO_CONN(conn));
  726.         return;
  727.       case 1:
  728.         /* start flushing conn */
  729.         conn->_base.state = DIR_CONN_STATE_CLIENT_SENDING;
  730.         /* fall through */
  731.       case 0:
  732.         /* queue the command on the outbuf */
  733.         directory_send_command(conn, dir_purpose, 1, resource,
  734.                                payload, payload_len,
  735.                                supports_conditional_consensus,
  736.                                if_modified_since);
  737.         connection_watch_events(TO_CONN(conn), EV_READ | EV_WRITE);
  738.         /* writable indicates finish, readable indicates broken link,
  739.            error indicates broken link in windowsland. */
  740.     }
  741.   } else { /* we want to connect via a tor connection */
  742.     edge_connection_t *linked_conn;
  743.     /* If it's an anonymized connection, remember the fact that we
  744.      * wanted it for later: maybe we'll want it again soon. */
  745.     if (anonymized_connection && use_begindir)
  746.       rep_hist_note_used_internal(time(NULL), 0, 1);
  747.     else if (anonymized_connection && !use_begindir)
  748.       rep_hist_note_used_port(time(NULL), conn->_base.port);
  749.     /* make an AP connection
  750.      * populate it and add it at the right state
  751.      * hook up both sides
  752.      */
  753.     linked_conn =
  754.       connection_ap_make_link(conn->_base.address, conn->_base.port,
  755.                               digest, use_begindir, conn->dirconn_direct);
  756.     if (!linked_conn) {
  757.       log_warn(LD_NET,"Making tunnel to dirserver failed.");
  758.       connection_mark_for_close(TO_CONN(conn));
  759.       return;
  760.     }
  761.     connection_link_connections(TO_CONN(conn), TO_CONN(linked_conn));
  762.     if (connection_add(TO_CONN(conn)) < 0) {
  763.       log_warn(LD_NET,"Unable to add connection for link to dirserver.");
  764.       connection_mark_for_close(TO_CONN(conn));
  765.       return;
  766.     }
  767.     conn->_base.state = DIR_CONN_STATE_CLIENT_SENDING;
  768.     /* queue the command on the outbuf */
  769.     directory_send_command(conn, dir_purpose, 0, resource,
  770.                            payload, payload_len,
  771.                            supports_conditional_consensus,
  772.                            if_modified_since);
  773.     connection_watch_events(TO_CONN(conn), EV_READ | EV_WRITE);
  774.     connection_start_reading(TO_CONN(linked_conn));
  775.   }
  776. }
  777. /** Return true iff anything we say on <b>conn</b> is being encrypted before
  778.  * we send it to the client/server. */
  779. int
  780. connection_dir_is_encrypted(dir_connection_t *conn)
  781. {
  782.   /* Right now it's sufficient to see if conn is or has been linked, since
  783.    * the only thing it could be linked to is an edge connection on a
  784.    * circuit, and the only way it could have been unlinked is at the edge
  785.    * connection getting closed.
  786.    */
  787.   return TO_CONN(conn)->linked;
  788. }
  789. /** Helper for sorting
  790.  *
  791.  * sort strings alphabetically
  792.  */
  793. static int
  794. _compare_strs(const void **a, const void **b)
  795. {
  796.   const char *s1 = *a, *s2 = *b;
  797.   return strcmp(s1, s2);
  798. }
  799. #define CONDITIONAL_CONSENSUS_FPR_LEN 3
  800. #if (CONDITIONAL_CONSENSUS_FPR_LEN > DIGEST_LEN)
  801. #error "conditional consensus fingerprint length is larger than digest length"
  802. #endif
  803. /** Return the URL we should use for a consensus download.
  804.  *
  805.  * This url depends on whether or not the server we go to
  806.  * is sufficiently new to support conditional consensus downloading,
  807.  * i.e. GET .../consensus/<b>fpr</b>+<b>fpr</b>+<b>fpr</b>
  808.  */
  809. static char *
  810. directory_get_consensus_url(int supports_conditional_consensus)
  811. {
  812.   char *url;
  813.   size_t len;
  814.   if (supports_conditional_consensus) {
  815.     char *authority_id_list;
  816.     smartlist_t *authority_digets = smartlist_create();
  817.     SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
  818.                       trusted_dir_server_t *, ds,
  819.       {
  820.         char *hex;
  821.         if (!(ds->type & V3_AUTHORITY))
  822.           continue;
  823.         hex = tor_malloc(2*CONDITIONAL_CONSENSUS_FPR_LEN+1);
  824.         base16_encode(hex, 2*CONDITIONAL_CONSENSUS_FPR_LEN+1,
  825.                       ds->v3_identity_digest, CONDITIONAL_CONSENSUS_FPR_LEN);
  826.         smartlist_add(authority_digets, hex);
  827.       });
  828.     smartlist_sort(authority_digets, _compare_strs);
  829.     authority_id_list = smartlist_join_strings(authority_digets,
  830.                                                "+", 0, NULL);
  831.     len = strlen(authority_id_list)+64;
  832.     url = tor_malloc(len);
  833.     tor_snprintf(url, len, "/tor/status-vote/current/consensus/%s.z",
  834.                  authority_id_list);
  835.     SMARTLIST_FOREACH(authority_digets, char *, cp, tor_free(cp));
  836.     smartlist_free(authority_digets);
  837.     tor_free(authority_id_list);
  838.   } else {
  839.     url = tor_strdup("/tor/status-vote/current/consensus.z");
  840.   }
  841.   return url;
  842. }
  843. /** Queue an appropriate HTTP command on conn->outbuf.  The other args
  844.  * are as in directory_initiate_command.
  845.  */
  846. static void
  847. directory_send_command(dir_connection_t *conn,
  848.                        int purpose, int direct, const char *resource,
  849.                        const char *payload, size_t payload_len,
  850.                        int supports_conditional_consensus,
  851.                        time_t if_modified_since)
  852. {
  853.   char proxystring[256];
  854.   char proxyauthstring[256];
  855.   char hoststring[128];
  856.   char imsstring[RFC1123_TIME_LEN+32];
  857.   char *url;
  858.   char request[8192];
  859.   const char *httpcommand = NULL;
  860.   size_t len;
  861.   tor_assert(conn);
  862.   tor_assert(conn->_base.type == CONN_TYPE_DIR);
  863.   tor_free(conn->requested_resource);
  864.   if (resource)
  865.     conn->requested_resource = tor_strdup(resource);
  866.   /* come up with a string for which Host: we want */
  867.   if (conn->_base.port == 80) {
  868.     strlcpy(hoststring, conn->_base.address, sizeof(hoststring));
  869.   } else {
  870.     tor_snprintf(hoststring, sizeof(hoststring),"%s:%d",
  871.                  conn->_base.address, conn->_base.port);
  872.   }
  873.   /* Format if-modified-since */
  874.   if (!if_modified_since) {
  875.     imsstring[0] = '';
  876.   } else {
  877.     char b[RFC1123_TIME_LEN+1];
  878.     format_rfc1123_time(b, if_modified_since);
  879.     tor_snprintf(imsstring, sizeof(imsstring), "rnIf-Modified-Since: %s", b);
  880.   }
  881.   /* come up with some proxy lines, if we're using one. */
  882.   if (direct && get_options()->HttpProxy) {
  883.     char *base64_authenticator=NULL;
  884.     const char *authenticator = get_options()->HttpProxyAuthenticator;
  885.     tor_snprintf(proxystring, sizeof(proxystring),"http://%s", hoststring);
  886.     if (authenticator) {
  887.       base64_authenticator = alloc_http_authenticator(authenticator);
  888.       if (!base64_authenticator)
  889.         log_warn(LD_BUG, "Encoding http authenticator failed");
  890.     }
  891.     if (base64_authenticator) {
  892.       tor_snprintf(proxyauthstring, sizeof(proxyauthstring),
  893.                    "rnProxy-Authorization: Basic %s",
  894.                    base64_authenticator);
  895.       tor_free(base64_authenticator);
  896.     } else {
  897.       proxyauthstring[0] = 0;
  898.     }
  899.   } else {
  900.     proxystring[0] = 0;
  901.     proxyauthstring[0] = 0;
  902.   }
  903.   switch (purpose) {
  904.     case DIR_PURPOSE_FETCH_V2_NETWORKSTATUS:
  905.       tor_assert(resource);
  906.       httpcommand = "GET";
  907.       len = strlen(resource)+32;
  908.       url = tor_malloc(len);
  909.       tor_snprintf(url, len, "/tor/status/%s", resource);
  910.       break;
  911.     case DIR_PURPOSE_FETCH_CONSENSUS:
  912.       tor_assert(!resource);
  913.       tor_assert(!payload);
  914.       httpcommand = "GET";
  915.       url = directory_get_consensus_url(supports_conditional_consensus);
  916.       log_info(LD_DIR, "Downloading consensus from %s using %s",
  917.                hoststring, url);
  918.       break;
  919.     case DIR_PURPOSE_FETCH_CERTIFICATE:
  920.       tor_assert(resource);
  921.       tor_assert(!payload);
  922.       httpcommand = "GET";
  923.       len = strlen(resource)+32;
  924.       url = tor_malloc(len);
  925.       tor_snprintf(url, len, "/tor/keys/%s", resource);
  926.       break;
  927.     case DIR_PURPOSE_FETCH_STATUS_VOTE:
  928.       tor_assert(resource);
  929.       tor_assert(!payload);
  930.       httpcommand = "GET";
  931.       len = strlen(resource)+32;
  932.       url = tor_malloc(len);
  933.       tor_snprintf(url, len, "/tor/status-vote/next/%s.z", resource);
  934.       break;
  935.     case DIR_PURPOSE_FETCH_DETACHED_SIGNATURES:
  936.       tor_assert(!resource);
  937.       tor_assert(!payload);
  938.       httpcommand = "GET";
  939.       url = tor_strdup("/tor/status-vote/next/consensus-signatures.z");
  940.       break;
  941.     case DIR_PURPOSE_FETCH_SERVERDESC:
  942.       tor_assert(resource);
  943.       httpcommand = "GET";
  944.       len = strlen(resource)+32;
  945.       url = tor_malloc(len);
  946.       tor_snprintf(url, len, "/tor/server/%s", resource);
  947.       break;
  948.     case DIR_PURPOSE_FETCH_EXTRAINFO:
  949.       tor_assert(resource);
  950.       httpcommand = "GET";
  951.       len = strlen(resource)+32;
  952.       url = tor_malloc(len);
  953.       tor_snprintf(url, len, "/tor/extra/%s", resource);
  954.       break;
  955.     case DIR_PURPOSE_UPLOAD_DIR:
  956.       tor_assert(!resource);
  957.       tor_assert(payload);
  958.       httpcommand = "POST";
  959.       url = tor_strdup("/tor/");
  960.       break;
  961.     case DIR_PURPOSE_UPLOAD_VOTE:
  962.       tor_assert(!resource);
  963.       tor_assert(payload);
  964.       httpcommand = "POST";
  965.       url = tor_strdup("/tor/post/vote");
  966.       break;
  967.     case DIR_PURPOSE_UPLOAD_SIGNATURES:
  968.       tor_assert(!resource);
  969.       tor_assert(payload);
  970.       httpcommand = "POST";
  971.       url = tor_strdup("/tor/post/consensus-signature");
  972.       break;
  973.     case DIR_PURPOSE_FETCH_RENDDESC:
  974.       tor_assert(resource);
  975.       tor_assert(!payload);
  976.       /* this must be true or we wouldn't be doing the lookup */
  977.       tor_assert(strlen(resource) <= REND_SERVICE_ID_LEN_BASE32);
  978.       /* This breaks the function abstraction. */
  979.       conn->rend_data = tor_malloc_zero(sizeof(rend_data_t));
  980.       strlcpy(conn->rend_data->onion_address, resource,
  981.               sizeof(conn->rend_data->onion_address));
  982.       conn->rend_data->rend_desc_version = 0;
  983.       httpcommand = "GET";
  984.       /* Request the most recent versioned descriptor. */
  985.       // (XXXX We were going to switch this to fetch rendezvous1 descriptors,
  986.       // but that never got testing, and it wasn't a good design.)
  987.       len = strlen(resource)+32;
  988.       url = tor_malloc(len);
  989.       tor_snprintf(url, len, "/tor/rendezvous/%s", resource);
  990.       break;
  991.     case DIR_PURPOSE_FETCH_RENDDESC_V2:
  992.       tor_assert(resource);
  993.       tor_assert(strlen(resource) <= REND_DESC_ID_V2_LEN_BASE32);
  994.       tor_assert(!payload);
  995.       conn->rend_data->rend_desc_version = 2;
  996.       httpcommand = "GET";
  997.       len = strlen(resource) + 32;
  998.       url = tor_malloc(len);
  999.       tor_snprintf(url, len, "/tor/rendezvous2/%s", resource);
  1000.       break;
  1001.     case DIR_PURPOSE_UPLOAD_RENDDESC:
  1002.       tor_assert(!resource);
  1003.       tor_assert(payload);
  1004.       httpcommand = "POST";
  1005.       url = tor_strdup("/tor/rendezvous/publish");
  1006.       break;
  1007.     case DIR_PURPOSE_UPLOAD_RENDDESC_V2:
  1008.       tor_assert(!resource);
  1009.       tor_assert(payload);
  1010.       httpcommand = "POST";
  1011.       url = tor_strdup("/tor/rendezvous2/publish");
  1012.       break;
  1013.     default:
  1014.       tor_assert(0);
  1015.       return;
  1016.   }
  1017.   if (strlen(proxystring) + strlen(url) >= 4096) {
  1018.     log_warn(LD_BUG,
  1019.              "Squid does not like URLs longer than 4095 bytes, and this "
  1020.              "one is %d bytes long: %s%s",
  1021.              (int)(strlen(proxystring) + strlen(url)), proxystring, url);
  1022.   }
  1023.   tor_snprintf(request, sizeof(request), "%s %s", httpcommand, proxystring);
  1024.   connection_write_to_buf(request, strlen(request), TO_CONN(conn));
  1025.   connection_write_to_buf(url, strlen(url), TO_CONN(conn));
  1026.   tor_free(url);
  1027.   if (!strcmp(httpcommand, "GET") && !payload) {
  1028.     tor_snprintf(request, sizeof(request),
  1029.                  " HTTP/1.0rnHost: %s%s%srnrn",
  1030.                  hoststring,
  1031.                  imsstring,
  1032.                  proxyauthstring);
  1033.   } else {
  1034.     tor_snprintf(request, sizeof(request),
  1035.                  " HTTP/1.0rnContent-Length: %lurnHost: %s%s%srnrn",
  1036.                  payload ? (unsigned long)payload_len : 0,
  1037.                  hoststring,
  1038.                  imsstring,
  1039.                  proxyauthstring);
  1040.   }
  1041.   connection_write_to_buf(request, strlen(request), TO_CONN(conn));
  1042.   if (payload) {
  1043.     /* then send the payload afterwards too */
  1044.     connection_write_to_buf(payload, payload_len, TO_CONN(conn));
  1045.   }
  1046. }
  1047. /** Parse an HTTP request string <b>headers</b> of the form
  1048.  * verbatim
  1049.  * "%s [http[s]://]%s HTTP/1..."
  1050.  * endverbatim
  1051.  * If it's well-formed, strdup the second %s into *<b>url</b>, and
  1052.  * nul-terminate it. If the url doesn't start with "/tor/", rewrite it
  1053.  * so it does. Return 0.
  1054.  * Otherwise, return -1.
  1055.  */
  1056. static int
  1057. parse_http_url(const char *headers, char **url)
  1058. {
  1059.   char *s, *start, *tmp;
  1060.   s = (char *)eat_whitespace_no_nl(headers);
  1061.   if (!*s) return -1;
  1062.   s = (char *)find_whitespace(s); /* get past GET/POST */
  1063.   if (!*s) return -1;
  1064.   s = (char *)eat_whitespace_no_nl(s);
  1065.   if (!*s) return -1;
  1066.   start = s; /* this is it, assuming it's valid */
  1067.   s = (char *)find_whitespace(start);
  1068.   if (!*s) return -1;
  1069.   /* tolerate the http[s] proxy style of putting the hostname in the url */
  1070.   if (s-start >= 4 && !strcmpstart(start,"http")) {
  1071.     tmp = start + 4;
  1072.     if (*tmp == 's')
  1073.       tmp++;
  1074.     if (s-tmp >= 3 && !strcmpstart(tmp,"://")) {
  1075.       tmp = strchr(tmp+3, '/');
  1076.       if (tmp && tmp < s) {
  1077.         log_debug(LD_DIR,"Skipping over 'http[s]://hostname' string");
  1078.         start = tmp;
  1079.       }
  1080.     }
  1081.   }
  1082.   if (s-start < 5 || strcmpstart(start,"/tor/")) { /* need to rewrite it */
  1083.     *url = tor_malloc(s - start + 5);
  1084.     strlcpy(*url,"/tor", s-start+5);
  1085.     strlcat((*url)+4, start, s-start+1);
  1086.   } else {
  1087.     *url = tor_strndup(start, s-start);
  1088.   }
  1089.   return 0;
  1090. }
  1091. /** Return a copy of the first HTTP header in <b>headers</b> whose key is
  1092.  * <b>which</b>.  The key should be given with a terminating colon and space;
  1093.  * this function copies everything after, up to but not including the
  1094.  * following \r\n. */
  1095. static char *
  1096. http_get_header(const char *headers, const char *which)
  1097. {
  1098.   const char *cp = headers;
  1099.   while (cp) {
  1100.     if (!strcasecmpstart(cp, which)) {
  1101.       char *eos;
  1102.       cp += strlen(which);
  1103.       if ((eos = strchr(cp,'r')))
  1104.         return tor_strndup(cp, eos-cp);
  1105.       else
  1106.         return tor_strdup(cp);
  1107.     }
  1108.     cp = strchr(cp, 'n');
  1109.     if (cp)
  1110.       ++cp;
  1111.   }
  1112.   return NULL;
  1113. }
  1114. /** If <b>headers</b> indicates that a proxy was involved, then rewrite
  1115.  * <b>conn</b>->address to describe our best guess of the address that
  1116.  * originated this HTTP request. */
  1117. static void
  1118. http_set_address_origin(const char *headers, connection_t *conn)
  1119. {
  1120.   char *fwd;
  1121.   fwd = http_get_header(headers, "Forwarded-For: ");
  1122.   if (!fwd)
  1123.     fwd = http_get_header(headers, "X-Forwarded-For: ");
  1124.   if (fwd) {
  1125.     struct in_addr in;
  1126.     if (!tor_inet_aton(fwd, &in) || is_internal_IP(ntohl(in.s_addr), 0)) {
  1127.       log_debug(LD_DIR, "Ignoring unrecognized or internal IP %s",
  1128.                 escaped(fwd));
  1129.       tor_free(fwd);
  1130.       return;
  1131.     }
  1132.     tor_free(conn->address);
  1133.     conn->address = tor_strdup(fwd);
  1134.     tor_free(fwd);
  1135.   }
  1136. }
  1137. /** Parse an HTTP response string <b>headers</b> of the form
  1138.  * verbatim
  1139.  * "HTTP/1.%d %d%srn...".
  1140.  * endverbatim
  1141.  *
  1142.  * If it's well-formed, assign the status code to *<b>code</b> and
  1143.  * return 0.  Otherwise, return -1.
  1144.  *
  1145.  * On success: If <b>date</b> is provided, set *date to the Date
  1146.  * header in the http headers, or 0 if no such header is found.  If
  1147.  * <b>compression</b> is provided, set *<b>compression</b> to the
  1148.  * compression method given in the Content-Encoding header, or 0 if no
  1149.  * such header is found, or -1 if the value of the header is not
  1150.  * recognized.  If <b>reason</b> is provided, strdup the reason string
  1151.  * into it.
  1152.  */
  1153. int
  1154. parse_http_response(const char *headers, int *code, time_t *date,
  1155.                     compress_method_t *compression, char **reason)
  1156. {
  1157.   unsigned n1, n2;
  1158.   char datestr[RFC1123_TIME_LEN+1];
  1159.   smartlist_t *parsed_headers;
  1160.   tor_assert(headers);
  1161.   tor_assert(code);
  1162.   while (TOR_ISSPACE(*headers)) headers++; /* tolerate leading whitespace */
  1163.   if (tor_sscanf(headers, "HTTP/1.%u %u", &n1, &n2) < 2 ||
  1164.       (n1 != 0 && n1 != 1) ||
  1165.       (n2 < 100 || n2 >= 600)) {
  1166.     log_warn(LD_HTTP,"Failed to parse header %s",escaped(headers));
  1167.     return -1;
  1168.   }
  1169.   *code = n2;
  1170.   parsed_headers = smartlist_create();
  1171.   smartlist_split_string(parsed_headers, headers, "n",
  1172.                          SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  1173.   if (reason) {
  1174.     smartlist_t *status_line_elements = smartlist_create();
  1175.     tor_assert(smartlist_len(parsed_headers));
  1176.     smartlist_split_string(status_line_elements,
  1177.                            smartlist_get(parsed_headers, 0),
  1178.                            " ", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
  1179.     tor_assert(smartlist_len(status_line_elements) <= 3);
  1180.     if (smartlist_len(status_line_elements) == 3) {
  1181.       *reason = smartlist_get(status_line_elements, 2);
  1182.       smartlist_set(status_line_elements, 2, NULL); /* Prevent free */
  1183.     }
  1184.     SMARTLIST_FOREACH(status_line_elements, char *, cp, tor_free(cp));
  1185.     smartlist_free(status_line_elements);
  1186.   }
  1187.   if (date) {
  1188.     *date = 0;
  1189.     SMARTLIST_FOREACH(parsed_headers, const char *, s,
  1190.       if (!strcmpstart(s, "Date: ")) {
  1191.         strlcpy(datestr, s+6, sizeof(datestr));
  1192.         /* This will do nothing on failure, so we don't need to check
  1193.            the result.   We shouldn't warn, since there are many other valid
  1194.            date formats besides the one we use. */
  1195.         parse_rfc1123_time(datestr, date);
  1196.         break;
  1197.       });
  1198.   }
  1199.   if (compression) {
  1200.     const char *enc = NULL;
  1201.     SMARTLIST_FOREACH(parsed_headers, const char *, s,
  1202.       if (!strcmpstart(s, "Content-Encoding: ")) {
  1203.         enc = s+18; break;
  1204.       });
  1205.     if (!enc || !strcmp(enc, "identity")) {
  1206.       *compression = NO_METHOD;
  1207.     } else if (!strcmp(enc, "deflate") || !strcmp(enc, "x-deflate")) {
  1208.       *compression = ZLIB_METHOD;
  1209.     } else if (!strcmp(enc, "gzip") || !strcmp(enc, "x-gzip")) {
  1210.       *compression = GZIP_METHOD;
  1211.     } else {
  1212.       log_info(LD_HTTP, "Unrecognized content encoding: %s. Trying to deal.",
  1213.                escaped(enc));
  1214.       *compression = UNKNOWN_METHOD;
  1215.     }
  1216.   }
  1217.   SMARTLIST_FOREACH(parsed_headers, char *, s, tor_free(s));
  1218.   smartlist_free(parsed_headers);
  1219.   return 0;
  1220. }
  1221. /** Return true iff <b>body</b> doesn't start with a plausible router or
  1222.  * running-list or directory opening.  This is a sign of possible compression.
  1223.  **/
  1224. static int
  1225. body_is_plausible(const char *body, size_t len, int purpose)
  1226. {
  1227.   int i;
  1228.   if (len == 0)
  1229.     return 1; /* empty bodies don't need decompression */
  1230.   if (len < 32)
  1231.     return 0;
  1232.   if (purpose != DIR_PURPOSE_FETCH_RENDDESC) {
  1233.     if (!strcmpstart(body,"router") ||
  1234.         !strcmpstart(body,"signed-directory") ||
  1235.         !strcmpstart(body,"network-status") ||
  1236.         !strcmpstart(body,"running-routers"))
  1237.     return 1;
  1238.     for (i=0;i<32;++i) {
  1239.       if (!TOR_ISPRINT(body[i]) && !TOR_ISSPACE(body[i]))
  1240.         return 0;
  1241.     }
  1242.     return 1;
  1243.   } else {
  1244.     return 1;
  1245.   }
  1246. }
  1247. /** Called when we've just fetched a bunch of router descriptors in
  1248.  * <b>body</b>.  The list <b>which</b>, if present, holds digests for
  1249.  * descriptors we requested: descriptor digests if <b>descriptor_digests</b>
  1250.  * is true, or identity digests otherwise.  Parse the descriptors, validate
  1251.  * them, and annotate them as having purpose <b>purpose</b> and as having been
  1252.  * downloaded from <b>source</b>.
  1253.  *
  1254.  * Return the number of routers actually added. */
  1255. static int
  1256. load_downloaded_routers(const char *body, smartlist_t *which,
  1257.                         int descriptor_digests,
  1258.                         int router_purpose,
  1259.                         const char *source)
  1260. {
  1261.   char buf[256];
  1262.   char time_buf[ISO_TIME_LEN+1];
  1263.   int added = 0;
  1264.   int general = router_purpose == ROUTER_PURPOSE_GENERAL;
  1265.   format_iso_time(time_buf, time(NULL));
  1266.   tor_assert(source);
  1267.   if (tor_snprintf(buf, sizeof(buf),
  1268.                    "@downloaded-at %sn"
  1269.                    "@source %sn"
  1270.                    "%s%s%s", time_buf, escaped(source),
  1271.                    !general ? "@purpose " : "",
  1272.                    !general ? router_purpose_to_string(router_purpose) : "",
  1273.                    !general ? "n" : "")<0)
  1274.     return added;
  1275.   added = router_load_routers_from_string(body, NULL, SAVED_NOWHERE, which,
  1276.                                   descriptor_digests, buf);
  1277.   control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_DESCRIPTORS,
  1278.                           count_loading_descriptors_progress());
  1279.   return added;
  1280. }
  1281. /** We are a client, and we've finished reading the server's
  1282.  * response. Parse it and act appropriately.
  1283.  *
  1284.  * If we're still happy with using this directory server in the future, return
  1285.  * 0. Otherwise return -1; and the caller should consider trying the request
  1286.  * again.
  1287.  *
  1288.  * The caller will take care of marking the connection for close.
  1289.  */
  1290. static int
  1291. connection_dir_client_reached_eof(dir_connection_t *conn)
  1292. {
  1293.   char *body;
  1294.   char *headers;
  1295.   char *reason = NULL;
  1296.   size_t body_len=0, orig_len=0;
  1297.   int status_code;
  1298.   time_t date_header=0;
  1299.   long delta;
  1300.   compress_method_t compression;
  1301.   int plausible;
  1302.   int skewed=0;
  1303.   int allow_partial = (conn->_base.purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
  1304.                        conn->_base.purpose == DIR_PURPOSE_FETCH_EXTRAINFO);
  1305.   int was_compressed=0;
  1306.   time_t now = time(NULL);
  1307.   switch (fetch_from_buf_http(conn->_base.inbuf,
  1308.                               &headers, MAX_HEADERS_SIZE,
  1309.                               &body, &body_len, MAX_DIR_DL_SIZE,
  1310.                               allow_partial)) {
  1311.     case -1: /* overflow */
  1312.       log_warn(LD_PROTOCOL,
  1313.                "'fetch' response too large (server '%s:%d'). Closing.",
  1314.                conn->_base.address, conn->_base.port);
  1315.       return -1;
  1316.     case 0:
  1317.       log_info(LD_HTTP,
  1318.                "'fetch' response not all here, but we're at eof. Closing.");
  1319.       return -1;
  1320.     /* case 1, fall through */
  1321.   }
  1322.   orig_len = body_len;
  1323.   if (parse_http_response(headers, &status_code, &date_header,
  1324.                           &compression, &reason) < 0) {
  1325.     log_warn(LD_HTTP,"Unparseable headers (server '%s:%d'). Closing.",
  1326.              conn->_base.address, conn->_base.port);
  1327.     tor_free(body); tor_free(headers);
  1328.     return -1;
  1329.   }
  1330.   if (!reason) reason = tor_strdup("[no reason given]");
  1331.   log_debug(LD_DIR,
  1332.             "Received response from directory server '%s:%d': %d %s",
  1333.             conn->_base.address, conn->_base.port, status_code,
  1334.             escaped(reason));
  1335.   /* now check if it's got any hints for us about our IP address. */
  1336.   if (conn->dirconn_direct) {
  1337.     char *guess = http_get_header(headers, X_ADDRESS_HEADER);
  1338.     if (guess) {
  1339.       router_new_address_suggestion(guess, conn);
  1340.       tor_free(guess);
  1341.     }
  1342.   }
  1343.   if (date_header > 0) {
  1344.     /* The date header was written very soon after we sent our request,
  1345.      * so compute the skew as the difference between sending the request
  1346.      * and the date header.  (We used to check now-date_header, but that's
  1347.      * inaccurate if we spend a lot of time downloading.)
  1348.      */
  1349.     delta = conn->_base.timestamp_lastwritten - date_header;
  1350.     if (labs(delta)>ALLOW_DIRECTORY_TIME_SKEW) {
  1351.       char dbuf[64];
  1352.       int trusted = router_digest_is_trusted_dir(conn->identity_digest);
  1353.       format_time_interval(dbuf, sizeof(dbuf), delta);
  1354.       log_fn(trusted ? LOG_WARN : LOG_INFO,
  1355.              LD_HTTP,
  1356.              "Received directory with skewed time (server '%s:%d'): "
  1357.              "It seems that our clock is %s by %s, or that theirs is %s. "
  1358.              "Tor requires an accurate clock to work: please check your time, "
  1359.              "timezone, and date settings.",
  1360.              conn->_base.address, conn->_base.port,
  1361.              delta>0 ? "ahead" : "behind", dbuf,
  1362.              delta>0 ? "behind" : "ahead");
  1363.       skewed = 1; /* don't check the recommended-versions line */
  1364.       control_event_general_status(trusted ? LOG_WARN : LOG_NOTICE,
  1365.                                "CLOCK_SKEW SKEW=%ld SOURCE=DIRSERV:%s:%d",
  1366.                                delta, conn->_base.address, conn->_base.port);
  1367.     } else {
  1368.       log_debug(LD_HTTP, "Time on received directory is within tolerance; "
  1369.                 "we are %ld seconds skewed.  (That's okay.)", delta);
  1370.     }
  1371.   }
  1372.   (void) skewed; /* skewed isn't used yet. */
  1373.   if (status_code == 503 && body_len < 16) {
  1374.     routerstatus_t *rs;
  1375.     trusted_dir_server_t *ds;
  1376.     log_info(LD_DIR,"Received http status code %d (%s) from server "
  1377.              "'%s:%d'. I'll try again soon.",
  1378.              status_code, escaped(reason), conn->_base.address,
  1379.              conn->_base.port);
  1380.     if ((rs = router_get_consensus_status_by_id(conn->identity_digest)))
  1381.       rs->last_dir_503_at = now;
  1382.     if ((ds = router_get_trusteddirserver_by_digest(conn->identity_digest)))
  1383.       ds->fake_status.last_dir_503_at = now;
  1384.     tor_free(body); tor_free(headers); tor_free(reason);
  1385.     return -1;
  1386.   } else if (status_code == 503) {
  1387.     /* XXXX022 Remove this once every server with bug 539 is obsolete. */
  1388.     log_info(LD_DIR, "Server at '%s:%d' sent us a 503 response, but included "
  1389.              "a body anyway.  We'll pretend it gave us a 200.",
  1390.              conn->_base.address, conn->_base.port);
  1391.     status_code = 200;
  1392.   }
  1393.   plausible = body_is_plausible(body, body_len, conn->_base.purpose);
  1394.   if (compression != NO_METHOD || !plausible) {
  1395.     char *new_body = NULL;
  1396.     size_t new_len = 0;
  1397.     compress_method_t guessed = detect_compression_method(body, body_len);
  1398.     if (compression == UNKNOWN_METHOD || guessed != compression) {
  1399.       /* Tell the user if we don't believe what we're told about compression.*/
  1400.       const char *description1, *description2;
  1401.       if (compression == ZLIB_METHOD)
  1402.         description1 = "as deflated";
  1403.       else if (compression == GZIP_METHOD)
  1404.         description1 = "as gzipped";
  1405.       else if (compression == NO_METHOD)
  1406.         description1 = "as uncompressed";
  1407.       else
  1408.         description1 = "with an unknown Content-Encoding";
  1409.       if (guessed == ZLIB_METHOD)
  1410.         description2 = "deflated";
  1411.       else if (guessed == GZIP_METHOD)
  1412.         description2 = "gzipped";
  1413.       else if (!plausible)
  1414.         description2 = "confusing binary junk";
  1415.       else
  1416.         description2 = "uncompressed";
  1417.       log_info(LD_HTTP, "HTTP body from server '%s:%d' was labeled %s, "
  1418.                "but it seems to be %s.%s",
  1419.                conn->_base.address, conn->_base.port, description1,
  1420.                description2,
  1421.                (compression>0 && guessed>0)?"  Trying both.":"");
  1422.     }
  1423.     /* Try declared compression first if we can. */
  1424.     if (compression == GZIP_METHOD  || compression == ZLIB_METHOD)
  1425.       tor_gzip_uncompress(&new_body, &new_len, body, body_len, compression,
  1426.                           !allow_partial, LOG_PROTOCOL_WARN);
  1427.     /* Okay, if that didn't work, and we think that it was compressed
  1428.      * differently, try that. */
  1429.     if (!new_body &&
  1430.         (guessed == GZIP_METHOD || guessed == ZLIB_METHOD) &&
  1431.         compression != guessed)
  1432.       tor_gzip_uncompress(&new_body, &new_len, body, body_len, guessed,
  1433.                           !allow_partial, LOG_PROTOCOL_WARN);
  1434.     /* If we're pretty sure that we have a compressed directory, and
  1435.      * we didn't manage to uncompress it, then warn and bail. */
  1436.     if (!plausible && !new_body) {
  1437.       log_fn(LOG_PROTOCOL_WARN, LD_HTTP,
  1438.              "Unable to decompress HTTP body (server '%s:%d').",
  1439.              conn->_base.address, conn->_base.port);
  1440.       tor_free(body); tor_free(headers); tor_free(reason);
  1441.       return -1;
  1442.     }
  1443.     if (new_body) {
  1444.       tor_free(body);
  1445.       body = new_body;
  1446.       body_len = new_len;
  1447.       was_compressed = 1;
  1448.     }
  1449.   }
  1450.   if (conn->_base.purpose == DIR_PURPOSE_FETCH_V2_NETWORKSTATUS) {
  1451.     smartlist_t *which = NULL;
  1452.     v2_networkstatus_source_t source;
  1453.     char *cp;
  1454.     log_info(LD_DIR,"Received networkstatus objects (size %d) from server "
  1455.              "'%s:%d'",(int) body_len, conn->_base.address, conn->_base.port);
  1456.     if (status_code != 200) {
  1457.       log_warn(LD_DIR,
  1458.            "Received http status code %d (%s) from server "
  1459.            "'%s:%d' while fetching "/tor/status/%s". I'll try again soon.",
  1460.            status_code, escaped(reason), conn->_base.address,
  1461.            conn->_base.port, conn->requested_resource);
  1462.       tor_free(body); tor_free(headers); tor_free(reason);
  1463.       connection_dir_download_networkstatus_failed(conn, status_code);
  1464.       return -1;
  1465.     }
  1466.     if (conn->requested_resource &&
  1467.         !strcmpstart(conn->requested_resource,"fp/")) {
  1468.       source = NS_FROM_DIR_BY_FP;
  1469.       which = smartlist_create();
  1470.       dir_split_resource_into_fingerprints(conn->requested_resource+3,
  1471.                                            which, NULL, 0, 0);
  1472.     } else if (conn->requested_resource &&
  1473.                !strcmpstart(conn->requested_resource, "all")) {
  1474.       source = NS_FROM_DIR_ALL;
  1475.       which = smartlist_create();
  1476.       SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
  1477.                         trusted_dir_server_t *, ds,
  1478.         {
  1479.           char *hex = tor_malloc(HEX_DIGEST_LEN+1);
  1480.           base16_encode(hex, HEX_DIGEST_LEN+1, ds->digest, DIGEST_LEN);
  1481.           smartlist_add(which, hex);
  1482.         });
  1483.     } else {
  1484.       /* XXXX Can we even end up here? -- weasel*/
  1485.       source = NS_FROM_DIR_BY_FP;
  1486.       log_warn(LD_BUG, "We received a networkstatus but we didn't ask "
  1487.                        "for it by fp, nor did we ask for all.");
  1488.     }
  1489.     cp = body;
  1490.     while (*cp) {
  1491.       char *next = strstr(cp, "nnetwork-status-version");
  1492.       if (next)
  1493.         next[1] = '';
  1494.       /* learn from it, and then remove it from 'which' */
  1495.       if (router_set_networkstatus_v2(cp, now, source, which)<0)
  1496.         break;
  1497.       if (next) {
  1498.         next[1] = 'n';
  1499.         cp = next+1;
  1500.       } else
  1501.         break;
  1502.     }
  1503.     /* launches router downloads as needed */
  1504.     routers_update_all_from_networkstatus(now, 2);
  1505.     directory_info_has_arrived(now, 0);
  1506.     if (which) {
  1507.       if (smartlist_len(which)) {
  1508.         dir_networkstatus_download_failed(which, status_code);
  1509.       }
  1510.       SMARTLIST_FOREACH(which, char *, s, tor_free(s));
  1511.       smartlist_free(which);
  1512.     }
  1513.   }
  1514.   if (conn->_base.purpose == DIR_PURPOSE_FETCH_CONSENSUS) {
  1515.     int r;
  1516.     if (status_code != 200) {
  1517.       int severity = (status_code == 304) ? LOG_INFO : LOG_WARN;
  1518.       log(severity, LD_DIR,
  1519.           "Received http status code %d (%s) from server "
  1520.           "'%s:%d' while fetching consensus directory.",
  1521.            status_code, escaped(reason), conn->_base.address,
  1522.            conn->_base.port);
  1523.       tor_free(body); tor_free(headers); tor_free(reason);
  1524.       networkstatus_consensus_download_failed(status_code);
  1525.       return -1;
  1526.     }
  1527.     log_info(LD_DIR,"Received consensus directory (size %d) from server "
  1528.              "'%s:%d'",(int) body_len, conn->_base.address, conn->_base.port);
  1529.     if ((r=networkstatus_set_current_consensus(body, 0))<0) {
  1530.       log_fn(r<-1?LOG_WARN:LOG_INFO, LD_DIR,
  1531.              "Unable to load consensus directory downloaded from "
  1532.              "server '%s:%d'. I'll try again soon.",
  1533.              conn->_base.address, conn->_base.port);
  1534.       tor_free(body); tor_free(headers); tor_free(reason);
  1535.       networkstatus_consensus_download_failed(0);
  1536.       return -1;
  1537.     }
  1538.     /* launches router downloads as needed */
  1539.     routers_update_all_from_networkstatus(now, 3);
  1540.     directory_info_has_arrived(now, 0);
  1541.     log_info(LD_DIR, "Successfully loaded consensus.");
  1542.   }
  1543.   if (conn->_base.purpose == DIR_PURPOSE_FETCH_CERTIFICATE) {
  1544.     if (status_code != 200) {
  1545.       log_warn(LD_DIR,
  1546.           "Received http status code %d (%s) from server "
  1547.           "'%s:%d' while fetching "/tor/keys/%s".",
  1548.            status_code, escaped(reason), conn->_base.address,
  1549.            conn->_base.port, conn->requested_resource);
  1550.       connection_dir_download_cert_failed(conn, status_code);
  1551.       tor_free(body); tor_free(headers); tor_free(reason);
  1552.       return -1;
  1553.     }
  1554.     log_info(LD_DIR,"Received authority certificates (size %d) from server "
  1555.              "'%s:%d'",(int) body_len, conn->_base.address, conn->_base.port);
  1556.     if (trusted_dirs_load_certs_from_string(body, 0, 1)<0) {
  1557.       log_warn(LD_DIR, "Unable to parse fetched certificates");
  1558.       connection_dir_download_cert_failed(conn, status_code);
  1559.     } else {
  1560.       directory_info_has_arrived(now, 0);
  1561.       log_info(LD_DIR, "Successfully loaded certificates from fetch.");
  1562.     }
  1563.   }
  1564.   if (conn->_base.purpose == DIR_PURPOSE_FETCH_STATUS_VOTE) {
  1565.     const char *msg;
  1566.     int st;
  1567.     log_info(LD_DIR,"Got votes (size %d) from server %s:%d",
  1568.              (int) body_len, conn->_base.address, conn->_base.port);
  1569.     if (status_code != 200) {
  1570.       log_warn(LD_DIR,
  1571.              "Received http status code %d (%s) from server "
  1572.              "'%s:%d' while fetching "/tor/status-vote/next/%s.z".",
  1573.              status_code, escaped(reason), conn->_base.address,
  1574.              conn->_base.port, conn->requested_resource);
  1575.       tor_free(body); tor_free(headers); tor_free(reason);
  1576.       return -1;
  1577.     }
  1578.     dirvote_add_vote(body, &msg, &st);
  1579.     if (st > 299) {
  1580.       log_warn(LD_DIR, "Error adding retrieved vote: %s", msg);
  1581.     } else {
  1582.       log_info(LD_DIR, "Added vote(s) successfully [msg: %s]", msg);
  1583.     }
  1584.   }
  1585.   if (conn->_base.purpose == DIR_PURPOSE_FETCH_DETACHED_SIGNATURES) {
  1586.     const char *msg = NULL;
  1587.     log_info(LD_DIR,"Got detached signatures (size %d) from server %s:%d",
  1588.              (int) body_len, conn->_base.address, conn->_base.port);
  1589.     if (status_code != 200) {
  1590.       log_warn(LD_DIR,
  1591.         "Received http status code %d (%s) from server "
  1592.         "'%s:%d' while fetching "/tor/status-vote/consensus-signatures.z".",
  1593.              status_code, escaped(reason), conn->_base.address,
  1594.              conn->_base.port);
  1595.       tor_free(body); tor_free(headers); tor_free(reason);
  1596.       return -1;
  1597.     }
  1598.     if (dirvote_add_signatures(body, conn->_base.address, &msg)<0) {
  1599.       log_warn(LD_DIR, "Problem adding detached signatures from %s:%d: %s",
  1600.                conn->_base.address, conn->_base.port, msg?msg:"???");
  1601.     }
  1602.   }
  1603.   if (conn->_base.purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
  1604.       conn->_base.purpose == DIR_PURPOSE_FETCH_EXTRAINFO) {
  1605.     int was_ei = conn->_base.purpose == DIR_PURPOSE_FETCH_EXTRAINFO;
  1606.     smartlist_t *which = NULL;
  1607.     int n_asked_for = 0;
  1608.     int descriptor_digests = conn->requested_resource &&
  1609.                              !strcmpstart(conn->requested_resource,"d/");
  1610.     log_info(LD_DIR,"Received %s (size %d) from server '%s:%d'",
  1611.              was_ei ? "extra server info" : "server info",
  1612.              (int)body_len, conn->_base.address, conn->_base.port);
  1613.     if (conn->requested_resource &&
  1614.         (!strcmpstart(conn->requested_resource,"d/") ||
  1615.          !strcmpstart(conn->requested_resource,"fp/"))) {
  1616.       which = smartlist_create();
  1617.       dir_split_resource_into_fingerprints(conn->requested_resource +
  1618.                                              (descriptor_digests ? 2 : 3),
  1619.                                            which, NULL, 0, 0);
  1620.       n_asked_for = smartlist_len(which);
  1621.     }
  1622.     if (status_code != 200) {
  1623.       int dir_okay = status_code == 404 ||
  1624.         (status_code == 400 && !strcmp(reason, "Servers unavailable."));
  1625.       /* 404 means that it didn't have them; no big deal.
  1626.        * Older (pre-0.1.1.8) servers said 400 Servers unavailable instead. */
  1627.       log_fn(dir_okay ? LOG_INFO : LOG_WARN, LD_DIR,
  1628.              "Received http status code %d (%s) from server '%s:%d' "
  1629.              "while fetching "/tor/server/%s". I'll try again soon.",
  1630.              status_code, escaped(reason), conn->_base.address,
  1631.              conn->_base.port, conn->requested_resource);
  1632.       if (!which) {
  1633.         connection_dir_download_routerdesc_failed(conn);
  1634.       } else {
  1635.         dir_routerdesc_download_failed(which, status_code,
  1636.                                        conn->router_purpose,
  1637.                                        was_ei, descriptor_digests);
  1638.         SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
  1639.         smartlist_free(which);
  1640.       }
  1641.       tor_free(body); tor_free(headers); tor_free(reason);
  1642.       return dir_okay ? 0 : -1;
  1643.     }
  1644.     /* Learn the routers, assuming we requested by fingerprint or "all"
  1645.      * or "authority".
  1646.      *
  1647.      * We use "authority" to fetch our own descriptor for
  1648.      * testing, and to fetch bridge descriptors for bootstrapping. Ignore
  1649.      * the output of "authority" requests unless we are using bridges,
  1650.      * since otherwise they'll be the response from reachability tests,
  1651.      * and we don't really want to add that to our routerlist. */
  1652.     if (which || (conn->requested_resource &&
  1653.                   (!strcmpstart(conn->requested_resource, "all") ||
  1654.                    (!strcmpstart(conn->requested_resource, "authority") &&
  1655.                     get_options()->UseBridges)))) {
  1656.       /* as we learn from them, we remove them from 'which' */
  1657.       if (was_ei) {
  1658.         router_load_extrainfo_from_string(body, NULL, SAVED_NOWHERE, which,
  1659.                                           descriptor_digests);
  1660.       } else {
  1661.         //router_load_routers_from_string(body, NULL, SAVED_NOWHERE, which,
  1662.         //                       descriptor_digests, conn->router_purpose);
  1663.         if (load_downloaded_routers(body, which, descriptor_digests,
  1664.                                 conn->router_purpose,
  1665.                                 conn->_base.address))
  1666.           directory_info_has_arrived(now, 0);
  1667.       }
  1668.     }
  1669.     if (which) { /* mark remaining ones as failed */
  1670.       log_info(LD_DIR, "Received %d/%d %s requested from %s:%d",
  1671.                n_asked_for-smartlist_len(which), n_asked_for,
  1672.                was_ei ? "extra-info documents" : "router descriptors",
  1673.                conn->_base.address, (int)conn->_base.port);
  1674.       if (smartlist_len(which)) {
  1675.         dir_routerdesc_download_failed(which, status_code,
  1676.                                        conn->router_purpose,
  1677.                                        was_ei, descriptor_digests);
  1678.       }
  1679.       SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
  1680.       smartlist_free(which);
  1681.     }
  1682.     if (directory_conn_is_self_reachability_test(conn))
  1683.       router_dirport_found_reachable();