Back to index

tor  0.2.3.18-rc
router.c
Go to the documentation of this file.
00001 /* Copyright (c) 2001 Matej Pfajfar.
00002  * Copyright (c) 2001-2004, Roger Dingledine.
00003  * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
00004  * Copyright (c) 2007-2012, The Tor Project, Inc. */
00005 /* See LICENSE for licensing information */
00006 
00007 #define ROUTER_PRIVATE
00008 
00009 #include "or.h"
00010 #include "circuitbuild.h"
00011 #include "circuitlist.h"
00012 #include "circuituse.h"
00013 #include "config.h"
00014 #include "connection.h"
00015 #include "control.h"
00016 #include "directory.h"
00017 #include "dirserv.h"
00018 #include "dns.h"
00019 #include "geoip.h"
00020 #include "hibernate.h"
00021 #include "main.h"
00022 #include "networkstatus.h"
00023 #include "nodelist.h"
00024 #include "policies.h"
00025 #include "relay.h"
00026 #include "rephist.h"
00027 #include "router.h"
00028 #include "routerlist.h"
00029 #include "routerparse.h"
00030 
00037 extern long stats_n_seconds_working;
00038 
00039 /************************************************************/
00040 
00041 /*****
00042  * Key management: ORs only.
00043  *****/
00044 
00047 static tor_mutex_t *key_lock=NULL;
00048 static time_t onionkey_set_at=0; 
00050 static crypto_pk_t *onionkey=NULL;
00053 static crypto_pk_t *lastonionkey=NULL;
00056 static crypto_pk_t *server_identitykey=NULL;
00058 static char server_identitykey_digest[DIGEST_LEN];
00062 static crypto_pk_t *client_identitykey=NULL;
00064 static crypto_pk_t *authority_signing_key = NULL;
00067 static authority_cert_t *authority_key_certificate = NULL;
00068 
00071 static crypto_pk_t *legacy_signing_key = NULL;
00074 static authority_cert_t *legacy_key_certificate = NULL;
00075 
00076 /* (Note that v3 authorities also have a separate "authority identity key",
00077  * but this key is never actually loaded by the Tor process.  Instead, it's
00078  * used by tor-gencert to sign new signing keys and make new key
00079  * certificates. */
00080 
00084 static void
00085 set_onion_key(crypto_pk_t *k)
00086 {
00087   if (onionkey && !crypto_pk_cmp_keys(onionkey, k)) {
00088     /* k is already our onion key; free it and return */
00089     crypto_pk_free(k);
00090     return;
00091   }
00092   tor_mutex_acquire(key_lock);
00093   crypto_pk_free(onionkey);
00094   onionkey = k;
00095   tor_mutex_release(key_lock);
00096   mark_my_descriptor_dirty("set onion key");
00097 }
00098 
00101 crypto_pk_t *
00102 get_onion_key(void)
00103 {
00104   tor_assert(onionkey);
00105   return onionkey;
00106 }
00107 
00111 void
00112 dup_onion_keys(crypto_pk_t **key, crypto_pk_t **last)
00113 {
00114   tor_assert(key);
00115   tor_assert(last);
00116   tor_mutex_acquire(key_lock);
00117   tor_assert(onionkey);
00118   *key = crypto_pk_copy_full(onionkey);
00119   if (lastonionkey)
00120     *last = crypto_pk_copy_full(lastonionkey);
00121   else
00122     *last = NULL;
00123   tor_mutex_release(key_lock);
00124 }
00125 
00130 time_t
00131 get_onion_key_set_at(void)
00132 {
00133   return onionkey_set_at;
00134 }
00135 
00138 void
00139 set_server_identity_key(crypto_pk_t *k)
00140 {
00141   crypto_pk_free(server_identitykey);
00142   server_identitykey = k;
00143   crypto_pk_get_digest(server_identitykey, server_identitykey_digest);
00144 }
00145 
00148 static void
00149 assert_identity_keys_ok(void)
00150 {
00151   tor_assert(client_identitykey);
00152   if (public_server_mode(get_options())) {
00153     /* assert that we have set the client and server keys to be equal */
00154     tor_assert(server_identitykey);
00155     tor_assert(0==crypto_pk_cmp_keys(client_identitykey, server_identitykey));
00156   } else {
00157     /* assert that we have set the client and server keys to be unequal */
00158     if (server_identitykey)
00159       tor_assert(0!=crypto_pk_cmp_keys(client_identitykey,
00160                                        server_identitykey));
00161   }
00162 }
00163 
00167 crypto_pk_t *
00168 get_server_identity_key(void)
00169 {
00170   tor_assert(server_identitykey);
00171   tor_assert(server_mode(get_options()));
00172   assert_identity_keys_ok();
00173   return server_identitykey;
00174 }
00175 
00177 int
00178 server_identity_key_is_set(void)
00179 {
00180   return server_identitykey != NULL;
00181 }
00182 
00185 void
00186 set_client_identity_key(crypto_pk_t *k)
00187 {
00188   crypto_pk_free(client_identitykey);
00189   client_identitykey = k;
00190 }
00191 
00195 crypto_pk_t *
00196 get_tlsclient_identity_key(void)
00197 {
00198   tor_assert(client_identitykey);
00199   assert_identity_keys_ok();
00200   return client_identitykey;
00201 }
00202 
00204 int
00205 client_identity_key_is_set(void)
00206 {
00207   return client_identitykey != NULL;
00208 }
00209 
00212 authority_cert_t *
00213 get_my_v3_authority_cert(void)
00214 {
00215   return authority_key_certificate;
00216 }
00217 
00220 crypto_pk_t *
00221 get_my_v3_authority_signing_key(void)
00222 {
00223   return authority_signing_key;
00224 }
00225 
00229 authority_cert_t *
00230 get_my_v3_legacy_cert(void)
00231 {
00232   return legacy_key_certificate;
00233 }
00234 
00237 crypto_pk_t *
00238 get_my_v3_legacy_signing_key(void)
00239 {
00240   return legacy_signing_key;
00241 }
00242 
00250 void
00251 rotate_onion_key(void)
00252 {
00253   char *fname, *fname_prev;
00254   crypto_pk_t *prkey;
00255   or_state_t *state = get_or_state();
00256   time_t now;
00257   fname = get_datadir_fname2("keys", "secret_onion_key");
00258   fname_prev = get_datadir_fname2("keys", "secret_onion_key.old");
00259   if (!(prkey = crypto_pk_new())) {
00260     log_err(LD_GENERAL,"Error constructing rotated onion key");
00261     goto error;
00262   }
00263   if (crypto_pk_generate_key(prkey)) {
00264     log_err(LD_BUG,"Error generating onion key");
00265     goto error;
00266   }
00267   if (file_status(fname) == FN_FILE) {
00268     if (replace_file(fname, fname_prev))
00269       goto error;
00270   }
00271   if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
00272     log_err(LD_FS,"Couldn't write generated onion key to \"%s\".", fname);
00273     goto error;
00274   }
00275   log_info(LD_GENERAL, "Rotating onion key");
00276   tor_mutex_acquire(key_lock);
00277   crypto_pk_free(lastonionkey);
00278   lastonionkey = onionkey;
00279   onionkey = prkey;
00280   now = time(NULL);
00281   state->LastRotatedOnionKey = onionkey_set_at = now;
00282   tor_mutex_release(key_lock);
00283   mark_my_descriptor_dirty("rotated onion key");
00284   or_state_mark_dirty(state, get_options()->AvoidDiskWrites ? now+3600 : 0);
00285   goto done;
00286  error:
00287   log_warn(LD_GENERAL, "Couldn't rotate onion key.");
00288   if (prkey)
00289     crypto_pk_free(prkey);
00290  done:
00291   tor_free(fname);
00292   tor_free(fname_prev);
00293 }
00294 
00300 crypto_pk_t *
00301 init_key_from_file(const char *fname, int generate, int severity)
00302 {
00303   crypto_pk_t *prkey = NULL;
00304 
00305   if (!(prkey = crypto_pk_new())) {
00306     log(severity, LD_GENERAL,"Error constructing key");
00307     goto error;
00308   }
00309 
00310   switch (file_status(fname)) {
00311     case FN_DIR:
00312     case FN_ERROR:
00313       log(severity, LD_FS,"Can't read key from \"%s\"", fname);
00314       goto error;
00315     case FN_NOENT:
00316       if (generate) {
00317         if (!have_lockfile()) {
00318           if (try_locking(get_options(), 0)<0) {
00319             /* Make sure that --list-fingerprint only creates new keys
00320              * if there is no possibility for a deadlock. */
00321             log(severity, LD_FS, "Another Tor process has locked \"%s\". Not "
00322                 "writing any new keys.", fname);
00323             /*XXXX The 'other process' might make a key in a second or two;
00324              * maybe we should wait for it. */
00325             goto error;
00326           }
00327         }
00328         log_info(LD_GENERAL, "No key found in \"%s\"; generating fresh key.",
00329                  fname);
00330         if (crypto_pk_generate_key(prkey)) {
00331           log(severity, LD_GENERAL,"Error generating onion key");
00332           goto error;
00333         }
00334         if (crypto_pk_check_key(prkey) <= 0) {
00335           log(severity, LD_GENERAL,"Generated key seems invalid");
00336           goto error;
00337         }
00338         log_info(LD_GENERAL, "Generated key seems valid");
00339         if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
00340           log(severity, LD_FS,
00341               "Couldn't write generated key to \"%s\".", fname);
00342           goto error;
00343         }
00344       } else {
00345         log_info(LD_GENERAL, "No key found in \"%s\"", fname);
00346       }
00347       return prkey;
00348     case FN_FILE:
00349       if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
00350         log(severity, LD_GENERAL,"Error loading private key.");
00351         goto error;
00352       }
00353       return prkey;
00354     default:
00355       tor_assert(0);
00356   }
00357 
00358  error:
00359   if (prkey)
00360     crypto_pk_free(prkey);
00361   return NULL;
00362 }
00363 
00369 static int
00370 load_authority_keyset(int legacy, crypto_pk_t **key_out,
00371                       authority_cert_t **cert_out)
00372 {
00373   int r = -1;
00374   char *fname = NULL, *cert = NULL;
00375   const char *eos = NULL;
00376   crypto_pk_t *signing_key = NULL;
00377   authority_cert_t *parsed = NULL;
00378 
00379   fname = get_datadir_fname2("keys",
00380                  legacy ? "legacy_signing_key" : "authority_signing_key");
00381   signing_key = init_key_from_file(fname, 0, LOG_INFO);
00382   if (!signing_key) {
00383     log_warn(LD_DIR, "No version 3 directory key found in %s", fname);
00384     goto done;
00385   }
00386   tor_free(fname);
00387   fname = get_datadir_fname2("keys",
00388                legacy ? "legacy_certificate" : "authority_certificate");
00389   cert = read_file_to_str(fname, 0, NULL);
00390   if (!cert) {
00391     log_warn(LD_DIR, "Signing key found, but no certificate found in %s",
00392                fname);
00393     goto done;
00394   }
00395   parsed = authority_cert_parse_from_string(cert, &eos);
00396   if (!parsed) {
00397     log_warn(LD_DIR, "Unable to parse certificate in %s", fname);
00398     goto done;
00399   }
00400   if (crypto_pk_cmp_keys(signing_key, parsed->signing_key) != 0) {
00401     log_warn(LD_DIR, "Stored signing key does not match signing key in "
00402              "certificate");
00403     goto done;
00404   }
00405 
00406   crypto_pk_free(*key_out);
00407   authority_cert_free(*cert_out);
00408 
00409   *key_out = signing_key;
00410   *cert_out = parsed;
00411   r = 0;
00412   signing_key = NULL;
00413   parsed = NULL;
00414 
00415  done:
00416   tor_free(fname);
00417   tor_free(cert);
00418   crypto_pk_free(signing_key);
00419   authority_cert_free(parsed);
00420   return r;
00421 }
00422 
00426 static int
00427 init_v3_authority_keys(void)
00428 {
00429   if (load_authority_keyset(0, &authority_signing_key,
00430                             &authority_key_certificate)<0)
00431     return -1;
00432 
00433   if (get_options()->V3AuthUseLegacyKey &&
00434       load_authority_keyset(1, &legacy_signing_key,
00435                             &legacy_key_certificate)<0)
00436     return -1;
00437 
00438   return 0;
00439 }
00440 
00443 void
00444 v3_authority_check_key_expiry(void)
00445 {
00446   time_t now, expires;
00447   static time_t last_warned = 0;
00448   int badness, time_left, warn_interval;
00449   if (!authdir_mode_v3(get_options()) || !authority_key_certificate)
00450     return;
00451 
00452   now = time(NULL);
00453   expires = authority_key_certificate->expires;
00454   time_left = (int)( expires - now );
00455   if (time_left <= 0) {
00456     badness = LOG_ERR;
00457     warn_interval = 60*60;
00458   } else if (time_left <= 24*60*60) {
00459     badness = LOG_WARN;
00460     warn_interval = 60*60;
00461   } else if (time_left <= 24*60*60*7) {
00462     badness = LOG_WARN;
00463     warn_interval = 24*60*60;
00464   } else if (time_left <= 24*60*60*30) {
00465     badness = LOG_WARN;
00466     warn_interval = 24*60*60*5;
00467   } else {
00468     return;
00469   }
00470 
00471   if (last_warned + warn_interval > now)
00472     return;
00473 
00474   if (time_left <= 0) {
00475     log(badness, LD_DIR, "Your v3 authority certificate has expired."
00476         " Generate a new one NOW.");
00477   } else if (time_left <= 24*60*60) {
00478     log(badness, LD_DIR, "Your v3 authority certificate expires in %d hours;"
00479         " Generate a new one NOW.", time_left/(60*60));
00480   } else {
00481     log(badness, LD_DIR, "Your v3 authority certificate expires in %d days;"
00482         " Generate a new one soon.", time_left/(24*60*60));
00483   }
00484   last_warned = now;
00485 }
00486 
00489 int
00490 router_initialize_tls_context(void)
00491 {
00492   return tor_tls_context_init(public_server_mode(get_options()),
00493                               get_tlsclient_identity_key(),
00494                               server_mode(get_options()) ?
00495                               get_server_identity_key() : NULL,
00496                               MAX_SSL_KEY_LIFETIME_ADVERTISED);
00497 }
00498 
00503 int
00504 init_keys(void)
00505 {
00506   char *keydir;
00507   char fingerprint[FINGERPRINT_LEN+1];
00508   /*nickname<space>fp\n\0 */
00509   char fingerprint_line[MAX_NICKNAME_LEN+FINGERPRINT_LEN+3];
00510   const char *mydesc;
00511   crypto_pk_t *prkey;
00512   char digest[DIGEST_LEN];
00513   char v3_digest[DIGEST_LEN];
00514   char *cp;
00515   const or_options_t *options = get_options();
00516   dirinfo_type_t type;
00517   time_t now = time(NULL);
00518   trusted_dir_server_t *ds;
00519   int v3_digest_set = 0;
00520   authority_cert_t *cert = NULL;
00521 
00522   if (!key_lock)
00523     key_lock = tor_mutex_new();
00524 
00525   /* There are a couple of paths that put us here before we've asked
00526    * openssl to initialize itself. */
00527   if (crypto_global_init(get_options()->HardwareAccel,
00528                          get_options()->AccelName,
00529                          get_options()->AccelDir)) {
00530     log_err(LD_BUG, "Unable to initialize OpenSSL. Exiting.");
00531     return -1;
00532   }
00533 
00534   /* OP's don't need persistent keys; just make up an identity and
00535    * initialize the TLS context. */
00536   if (!server_mode(options)) {
00537     if (!(prkey = crypto_pk_new()))
00538       return -1;
00539     if (crypto_pk_generate_key(prkey)) {
00540       crypto_pk_free(prkey);
00541       return -1;
00542     }
00543     set_client_identity_key(prkey);
00544     /* Create a TLS context. */
00545     if (router_initialize_tls_context() < 0) {
00546       log_err(LD_GENERAL,"Error creating TLS context for Tor client.");
00547       return -1;
00548     }
00549     return 0;
00550   }
00551   /* Make sure DataDirectory exists, and is private. */
00552   if (check_private_dir(options->DataDirectory, CPD_CREATE, options->User)) {
00553     return -1;
00554   }
00555   /* Check the key directory. */
00556   keydir = get_datadir_fname("keys");
00557   if (check_private_dir(keydir, CPD_CREATE, options->User)) {
00558     tor_free(keydir);
00559     return -1;
00560   }
00561   tor_free(keydir);
00562 
00563   /* 1a. Read v3 directory authority key/cert information. */
00564   memset(v3_digest, 0, sizeof(v3_digest));
00565   if (authdir_mode_v3(options)) {
00566     if (init_v3_authority_keys()<0) {
00567       log_err(LD_GENERAL, "We're configured as a V3 authority, but we "
00568               "were unable to load our v3 authority keys and certificate! "
00569               "Use tor-gencert to generate them. Dying.");
00570       return -1;
00571     }
00572     cert = get_my_v3_authority_cert();
00573     if (cert) {
00574       crypto_pk_get_digest(get_my_v3_authority_cert()->identity_key,
00575                            v3_digest);
00576       v3_digest_set = 1;
00577     }
00578   }
00579 
00580   /* 1b. Read identity key. Make it if none is found. */
00581   keydir = get_datadir_fname2("keys", "secret_id_key");
00582   log_info(LD_GENERAL,"Reading/making identity key \"%s\"...",keydir);
00583   prkey = init_key_from_file(keydir, 1, LOG_ERR);
00584   tor_free(keydir);
00585   if (!prkey) return -1;
00586   set_server_identity_key(prkey);
00587 
00588   /* 1c. If we are configured as a bridge, generate a client key;
00589    * otherwise, set the server identity key as our client identity
00590    * key. */
00591   if (public_server_mode(options)) {
00592     set_client_identity_key(crypto_pk_dup_key(prkey)); /* set above */
00593   } else {
00594     if (!(prkey = crypto_pk_new()))
00595       return -1;
00596     if (crypto_pk_generate_key(prkey)) {
00597       crypto_pk_free(prkey);
00598       return -1;
00599     }
00600     set_client_identity_key(prkey);
00601   }
00602 
00603   /* 2. Read onion key.  Make it if none is found. */
00604   keydir = get_datadir_fname2("keys", "secret_onion_key");
00605   log_info(LD_GENERAL,"Reading/making onion key \"%s\"...",keydir);
00606   prkey = init_key_from_file(keydir, 1, LOG_ERR);
00607   tor_free(keydir);
00608   if (!prkey) return -1;
00609   set_onion_key(prkey);
00610   if (options->command == CMD_RUN_TOR) {
00611     /* only mess with the state file if we're actually running Tor */
00612     or_state_t *state = get_or_state();
00613     if (state->LastRotatedOnionKey > 100 && state->LastRotatedOnionKey < now) {
00614       /* We allow for some parsing slop, but we don't want to risk accepting
00615        * values in the distant future.  If we did, we might never rotate the
00616        * onion key. */
00617       onionkey_set_at = state->LastRotatedOnionKey;
00618     } else {
00619       /* We have no LastRotatedOnionKey set; either we just created the key
00620        * or it's a holdover from 0.1.2.4-alpha-dev or earlier.  In either case,
00621        * start the clock ticking now so that we will eventually rotate it even
00622        * if we don't stay up for a full MIN_ONION_KEY_LIFETIME. */
00623       state->LastRotatedOnionKey = onionkey_set_at = now;
00624       or_state_mark_dirty(state, options->AvoidDiskWrites ?
00625                                    time(NULL)+3600 : 0);
00626     }
00627   }
00628 
00629   keydir = get_datadir_fname2("keys", "secret_onion_key.old");
00630   if (!lastonionkey && file_status(keydir) == FN_FILE) {
00631     prkey = init_key_from_file(keydir, 1, LOG_ERR);
00632     if (prkey)
00633       lastonionkey = prkey;
00634   }
00635   tor_free(keydir);
00636 
00637   /* 3. Initialize link key and TLS context. */
00638   if (router_initialize_tls_context() < 0) {
00639     log_err(LD_GENERAL,"Error initializing TLS context");
00640     return -1;
00641   }
00642 
00643   /* 4. Build our router descriptor. */
00644   /* Must be called after keys are initialized. */
00645   mydesc = router_get_my_descriptor();
00646   if (authdir_mode_handles_descs(options, ROUTER_PURPOSE_GENERAL)) {
00647     const char *m = NULL;
00648     routerinfo_t *ri;
00649     /* We need to add our own fingerprint so it gets recognized. */
00650     if (dirserv_add_own_fingerprint(options->Nickname,
00651                                     get_server_identity_key())) {
00652       log_err(LD_GENERAL,"Error adding own fingerprint to approved set");
00653       return -1;
00654     }
00655     if (mydesc) {
00656       was_router_added_t added;
00657       ri = router_parse_entry_from_string(mydesc, NULL, 1, 0, NULL);
00658       if (!ri) {
00659         log_err(LD_GENERAL,"Generated a routerinfo we couldn't parse.");
00660         return -1;
00661       }
00662       added = dirserv_add_descriptor(ri, &m, "self");
00663       if (!WRA_WAS_ADDED(added)) {
00664         if (!WRA_WAS_OUTDATED(added)) {
00665           log_err(LD_GENERAL, "Unable to add own descriptor to directory: %s",
00666                   m?m:"<unknown error>");
00667           return -1;
00668         } else {
00669           /* If the descriptor was outdated, that's ok. This can happen
00670            * when some config options are toggled that affect workers, but
00671            * we don't really need new keys yet so the descriptor doesn't
00672            * change and the old one is still fresh. */
00673           log_info(LD_GENERAL, "Couldn't add own descriptor to directory "
00674                    "after key init: %s. This is usually not a problem.",
00675                    m?m:"<unknown error>");
00676         }
00677       }
00678     }
00679   }
00680 
00681   /* 5. Dump fingerprint to 'fingerprint' */
00682   keydir = get_datadir_fname("fingerprint");
00683   log_info(LD_GENERAL,"Dumping fingerprint to \"%s\"...",keydir);
00684   if (crypto_pk_get_fingerprint(get_server_identity_key(),
00685                                 fingerprint, 0) < 0) {
00686     log_err(LD_GENERAL,"Error computing fingerprint");
00687     tor_free(keydir);
00688     return -1;
00689   }
00690   tor_assert(strlen(options->Nickname) <= MAX_NICKNAME_LEN);
00691   if (tor_snprintf(fingerprint_line, sizeof(fingerprint_line),
00692                    "%s %s\n",options->Nickname, fingerprint) < 0) {
00693     log_err(LD_GENERAL,"Error writing fingerprint line");
00694     tor_free(keydir);
00695     return -1;
00696   }
00697   /* Check whether we need to write the fingerprint file. */
00698   cp = NULL;
00699   if (file_status(keydir) == FN_FILE)
00700     cp = read_file_to_str(keydir, 0, NULL);
00701   if (!cp || strcmp(cp, fingerprint_line)) {
00702     if (write_str_to_file(keydir, fingerprint_line, 0)) {
00703       log_err(LD_FS, "Error writing fingerprint line to file");
00704       tor_free(keydir);
00705       tor_free(cp);
00706       return -1;
00707     }
00708   }
00709   tor_free(cp);
00710   tor_free(keydir);
00711 
00712   log(LOG_NOTICE, LD_GENERAL,
00713       "Your Tor server's identity key fingerprint is '%s %s'",
00714       options->Nickname, fingerprint);
00715   if (!authdir_mode(options))
00716     return 0;
00717   /* 6. [authdirserver only] load approved-routers file */
00718   if (dirserv_load_fingerprint_file() < 0) {
00719     log_err(LD_GENERAL,"Error loading fingerprints");
00720     return -1;
00721   }
00722   /* 6b. [authdirserver only] add own key to approved directories. */
00723   crypto_pk_get_digest(get_server_identity_key(), digest);
00724   type = ((options->V1AuthoritativeDir ? V1_DIRINFO : NO_DIRINFO) |
00725           (options->V2AuthoritativeDir ? V2_DIRINFO : NO_DIRINFO) |
00726           (options->V3AuthoritativeDir ?
00727                (V3_DIRINFO|MICRODESC_DIRINFO|EXTRAINFO_DIRINFO) : NO_DIRINFO) |
00728           (options->BridgeAuthoritativeDir ? BRIDGE_DIRINFO : NO_DIRINFO) |
00729           (options->HSAuthoritativeDir ? HIDSERV_DIRINFO : NO_DIRINFO));
00730 
00731   ds = router_get_trusteddirserver_by_digest(digest);
00732   if (!ds) {
00733     ds = add_trusted_dir_server(options->Nickname, NULL,
00734                                 router_get_advertised_dir_port(options, 0),
00735                                 router_get_advertised_or_port(options),
00736                                 digest,
00737                                 v3_digest,
00738                                 type);
00739     if (!ds) {
00740       log_err(LD_GENERAL,"We want to be a directory authority, but we "
00741               "couldn't add ourselves to the authority list. Failing.");
00742       return -1;
00743     }
00744   }
00745   if (ds->type != type) {
00746     log_warn(LD_DIR,  "Configured authority type does not match authority "
00747              "type in DirServer list.  Adjusting. (%d v %d)",
00748              type, ds->type);
00749     ds->type = type;
00750   }
00751   if (v3_digest_set && (ds->type & V3_DIRINFO) &&
00752       tor_memneq(v3_digest, ds->v3_identity_digest, DIGEST_LEN)) {
00753     log_warn(LD_DIR, "V3 identity key does not match identity declared in "
00754              "DirServer line.  Adjusting.");
00755     memcpy(ds->v3_identity_digest, v3_digest, DIGEST_LEN);
00756   }
00757 
00758   if (cert) { /* add my own cert to the list of known certs */
00759     log_info(LD_DIR, "adding my own v3 cert");
00760     if (trusted_dirs_load_certs_from_string(
00761                       cert->cache_info.signed_descriptor_body, 0, 0)<0) {
00762       log_warn(LD_DIR, "Unable to parse my own v3 cert! Failing.");
00763       return -1;
00764     }
00765   }
00766 
00767   return 0; /* success */
00768 }
00769 
00770 /* Keep track of whether we should upload our server descriptor,
00771  * and what type of server we are.
00772  */
00773 
00775 static int can_reach_or_port = 0;
00777 static int can_reach_dir_port = 0;
00778 
00780 void
00781 router_reset_reachability(void)
00782 {
00783   can_reach_or_port = can_reach_dir_port = 0;
00784 }
00785 
00787 int
00788 check_whether_orport_reachable(void)
00789 {
00790   const or_options_t *options = get_options();
00791   return options->AssumeReachable ||
00792          can_reach_or_port;
00793 }
00794 
00796 int
00797 check_whether_dirport_reachable(void)
00798 {
00799   const or_options_t *options = get_options();
00800   return !options->DirPort ||
00801          options->AssumeReachable ||
00802          net_is_disabled() ||
00803          can_reach_dir_port;
00804 }
00805 
00813 static int
00814 decide_to_advertise_dirport(const or_options_t *options, uint16_t dir_port)
00815 {
00816   static int advertising=1; /* start out assuming we will advertise */
00817   int new_choice=1;
00818   const char *reason = NULL;
00819 
00820   /* Section one: reasons to publish or not publish that aren't
00821    * worth mentioning to the user, either because they're obvious
00822    * or because they're normal behavior. */
00823 
00824   if (!dir_port) /* short circuit the rest of the function */
00825     return 0;
00826   if (authdir_mode(options)) /* always publish */
00827     return dir_port;
00828   if (net_is_disabled())
00829     return 0;
00830   if (!check_whether_dirport_reachable())
00831     return 0;
00832   if (!router_get_advertised_dir_port(options, dir_port))
00833     return 0;
00834 
00835   /* Section two: reasons to publish or not publish that the user
00836    * might find surprising. These are generally config options that
00837    * make us choose not to publish. */
00838 
00839   if (accounting_is_enabled(options)) {
00840     /* Don't spend bytes for directory traffic if we could end up hibernating,
00841      * but allow DirPort otherwise. Some people set AccountingMax because
00842      * they're confused or to get statistics. */
00843     int interval_length = accounting_get_interval_length();
00844     uint32_t effective_bw = get_effective_bwrate(options);
00845     if (!interval_length) {
00846       log_warn(LD_BUG, "An accounting interval is not allowed to be zero "
00847                        "seconds long. Raising to 1.");
00848       interval_length = 1;
00849     }
00850     log_info(LD_GENERAL, "Calculating whether to disable dirport: effective "
00851                          "bwrate: %u, AccountingMax: "U64_FORMAT", "
00852                          "accounting interval length %d", effective_bw,
00853                          U64_PRINTF_ARG(options->AccountingMax),
00854                          interval_length);
00855     if (effective_bw >=
00856         options->AccountingMax / interval_length) {
00857       new_choice = 0;
00858       reason = "AccountingMax enabled";
00859     }
00860 #define MIN_BW_TO_ADVERTISE_DIRPORT 51200
00861   } else if (options->BandwidthRate < MIN_BW_TO_ADVERTISE_DIRPORT ||
00862              (options->RelayBandwidthRate > 0 &&
00863               options->RelayBandwidthRate < MIN_BW_TO_ADVERTISE_DIRPORT)) {
00864     /* if we're advertising a small amount */
00865     new_choice = 0;
00866     reason = "BandwidthRate under 50KB";
00867   }
00868 
00869   if (advertising != new_choice) {
00870     if (new_choice == 1) {
00871       log(LOG_NOTICE, LD_DIR, "Advertising DirPort as %d", dir_port);
00872     } else {
00873       tor_assert(reason);
00874       log(LOG_NOTICE, LD_DIR, "Not advertising DirPort (Reason: %s)", reason);
00875     }
00876     advertising = new_choice;
00877   }
00878 
00879   return advertising ? dir_port : 0;
00880 }
00881 
00893 void
00894 consider_testing_reachability(int test_or, int test_dir)
00895 {
00896   const routerinfo_t *me = router_get_my_routerinfo();
00897   int orport_reachable = check_whether_orport_reachable();
00898   tor_addr_t addr;
00899   const or_options_t *options = get_options();
00900   if (!me)
00901     return;
00902 
00903   if (routerset_contains_router(options->ExcludeNodes, me, -1) &&
00904       options->StrictNodes) {
00905     /* If we've excluded ourself, and StrictNodes is set, we can't test
00906      * ourself. */
00907     if (test_or || test_dir) {
00908 #define SELF_EXCLUDED_WARN_INTERVAL 3600
00909       static ratelim_t warning_limit=RATELIM_INIT(SELF_EXCLUDED_WARN_INTERVAL);
00910       char *msg;
00911       if ((msg = rate_limit_log(&warning_limit, approx_time()))) {
00912         log_warn(LD_CIRC, "Can't peform self-tests for this relay: we have "
00913                  "listed ourself in ExcludeNodes, and StrictNodes is set. "
00914                  "We cannot learn whether we are usable, and will not "
00915                  "be able to advertise ourself.%s", msg);
00916         tor_free(msg);
00917       }
00918     }
00919     return;
00920   }
00921 
00922   if (test_or && (!orport_reachable || !circuit_enough_testing_circs())) {
00923     extend_info_t *ei;
00924     log_info(LD_CIRC, "Testing %s of my ORPort: %s:%d.",
00925              !orport_reachable ? "reachability" : "bandwidth",
00926              me->address, me->or_port);
00927     /* XXX IPv6 self testing IPv6 orports will need pref_addr */
00928     ei = extend_info_from_router(me, 0);
00929     circuit_launch_by_extend_info(CIRCUIT_PURPOSE_TESTING, ei,
00930                             CIRCLAUNCH_NEED_CAPACITY|CIRCLAUNCH_IS_INTERNAL);
00931     extend_info_free(ei);
00932   }
00933 
00934   tor_addr_from_ipv4h(&addr, me->addr);
00935   if (test_dir && !check_whether_dirport_reachable() &&
00936       !connection_get_by_type_addr_port_purpose(
00937                 CONN_TYPE_DIR, &addr, me->dir_port,
00938                 DIR_PURPOSE_FETCH_SERVERDESC)) {
00939     /* ask myself, via tor, for my server descriptor. */
00940     directory_initiate_command(me->address, &addr,
00941                                me->or_port, me->dir_port,
00942                                0, /* does not matter */
00943                                0, me->cache_info.identity_digest,
00944                                DIR_PURPOSE_FETCH_SERVERDESC,
00945                                ROUTER_PURPOSE_GENERAL,
00946                                1, "authority.z", NULL, 0, 0);
00947   }
00948 }
00949 
00951 void
00952 router_orport_found_reachable(void)
00953 {
00954   const routerinfo_t *me = router_get_my_routerinfo();
00955   if (!can_reach_or_port && me) {
00956     log_notice(LD_OR,"Self-testing indicates your ORPort is reachable from "
00957                "the outside. Excellent.%s",
00958                get_options()->_PublishServerDescriptor != NO_DIRINFO ?
00959                  " Publishing server descriptor." : "");
00960     can_reach_or_port = 1;
00961     mark_my_descriptor_dirty("ORPort found reachable");
00962     control_event_server_status(LOG_NOTICE,
00963                                 "REACHABILITY_SUCCEEDED ORADDRESS=%s:%d",
00964                                 me->address, me->or_port);
00965   }
00966 }
00967 
00969 void
00970 router_dirport_found_reachable(void)
00971 {
00972   const routerinfo_t *me = router_get_my_routerinfo();
00973   if (!can_reach_dir_port && me) {
00974     log_notice(LD_DIRSERV,"Self-testing indicates your DirPort is reachable "
00975                "from the outside. Excellent.");
00976     can_reach_dir_port = 1;
00977     if (decide_to_advertise_dirport(get_options(), me->dir_port))
00978       mark_my_descriptor_dirty("DirPort found reachable");
00979     control_event_server_status(LOG_NOTICE,
00980                                 "REACHABILITY_SUCCEEDED DIRADDRESS=%s:%d",
00981                                 me->address, me->dir_port);
00982   }
00983 }
00984 
00987 void
00988 router_perform_bandwidth_test(int num_circs, time_t now)
00989 {
00990   int num_cells = (int)(get_options()->BandwidthRate * 10 / CELL_NETWORK_SIZE);
00991   int max_cells = num_cells < CIRCWINDOW_START ?
00992                     num_cells : CIRCWINDOW_START;
00993   int cells_per_circuit = max_cells / num_circs;
00994   origin_circuit_t *circ = NULL;
00995 
00996   log_notice(LD_OR,"Performing bandwidth self-test...done.");
00997   while ((circ = circuit_get_next_by_pk_and_purpose(circ, NULL,
00998                                               CIRCUIT_PURPOSE_TESTING))) {
00999     /* dump cells_per_circuit drop cells onto this circ */
01000     int i = cells_per_circuit;
01001     if (circ->_base.state != CIRCUIT_STATE_OPEN)
01002       continue;
01003     circ->_base.timestamp_dirty = now;
01004     while (i-- > 0) {
01005       if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
01006                                        RELAY_COMMAND_DROP,
01007                                        NULL, 0, circ->cpath->prev)<0) {
01008         return; /* stop if error */
01009       }
01010     }
01011   }
01012 }
01013 
01016 int
01017 net_is_disabled(void)
01018 {
01019   return get_options()->DisableNetwork || we_are_hibernating();
01020 }
01021 
01025 int
01026 authdir_mode(const or_options_t *options)
01027 {
01028   return options->AuthoritativeDir != 0;
01029 }
01033 int
01034 authdir_mode_v1(const or_options_t *options)
01035 {
01036   return authdir_mode(options) && options->V1AuthoritativeDir != 0;
01037 }
01041 int
01042 authdir_mode_v2(const or_options_t *options)
01043 {
01044   return authdir_mode(options) && options->V2AuthoritativeDir != 0;
01045 }
01049 int
01050 authdir_mode_v3(const or_options_t *options)
01051 {
01052   return authdir_mode(options) && options->V3AuthoritativeDir != 0;
01053 }
01055 int
01056 authdir_mode_any_main(const or_options_t *options)
01057 {
01058   return options->V1AuthoritativeDir ||
01059          options->V2AuthoritativeDir ||
01060          options->V3AuthoritativeDir;
01061 }
01064 int
01065 authdir_mode_any_nonhidserv(const or_options_t *options)
01066 {
01067   return options->BridgeAuthoritativeDir ||
01068          authdir_mode_any_main(options);
01069 }
01073 int
01074 authdir_mode_handles_descs(const or_options_t *options, int purpose)
01075 {
01076   if (purpose < 0)
01077     return authdir_mode_any_nonhidserv(options);
01078   else if (purpose == ROUTER_PURPOSE_GENERAL)
01079     return authdir_mode_any_main(options);
01080   else if (purpose == ROUTER_PURPOSE_BRIDGE)
01081     return (options->BridgeAuthoritativeDir);
01082   else
01083     return 0;
01084 }
01088 int
01089 authdir_mode_publishes_statuses(const or_options_t *options)
01090 {
01091   if (authdir_mode_bridge(options))
01092     return 0;
01093   return authdir_mode_any_nonhidserv(options);
01094 }
01098 int
01099 authdir_mode_tests_reachability(const or_options_t *options)
01100 {
01101   return authdir_mode_handles_descs(options, -1);
01102 }
01106 int
01107 authdir_mode_bridge(const or_options_t *options)
01108 {
01109   return authdir_mode(options) && options->BridgeAuthoritativeDir != 0;
01110 }
01111 
01114 int
01115 server_mode(const or_options_t *options)
01116 {
01117   if (options->ClientOnly) return 0;
01118   return (options->ORPort || options->ORListenAddress);
01119 }
01120 
01123 int
01124 public_server_mode(const or_options_t *options)
01125 {
01126   if (!server_mode(options)) return 0;
01127   return (!options->BridgeRelay);
01128 }
01129 
01133 int
01134 should_refuse_unknown_exits(const or_options_t *options)
01135 {
01136   if (options->RefuseUnknownExits != -1) {
01137     return options->RefuseUnknownExits;
01138   } else {
01139     return networkstatus_get_param(NULL, "refuseunknownexits", 1, 0, 1);
01140   }
01141 }
01142 
01144 static int server_is_advertised=0;
01145 
01148 int
01149 advertised_server_mode(void)
01150 {
01151   return server_is_advertised;
01152 }
01153 
01158 static void
01159 set_server_advertised(int s)
01160 {
01161   server_is_advertised = s;
01162 }
01163 
01165 int
01166 proxy_mode(const or_options_t *options)
01167 {
01168   (void)options;
01169   SMARTLIST_FOREACH_BEGIN(get_configured_ports(), const port_cfg_t *, p) {
01170     if (p->type == CONN_TYPE_AP_LISTENER ||
01171         p->type == CONN_TYPE_AP_TRANS_LISTENER ||
01172         p->type == CONN_TYPE_AP_DNS_LISTENER ||
01173         p->type == CONN_TYPE_AP_NATD_LISTENER)
01174       return 1;
01175   } SMARTLIST_FOREACH_END(p);
01176   return 0;
01177 }
01178 
01189 static int
01190 decide_if_publishable_server(void)
01191 {
01192   const or_options_t *options = get_options();
01193 
01194   if (options->ClientOnly)
01195     return 0;
01196   if (options->_PublishServerDescriptor == NO_DIRINFO)
01197     return 0;
01198   if (!server_mode(options))
01199     return 0;
01200   if (authdir_mode(options))
01201     return 1;
01202   if (!router_get_advertised_or_port(options))
01203     return 0;
01204 
01205   return check_whether_orport_reachable();
01206 }
01207 
01215 void
01216 consider_publishable_server(int force)
01217 {
01218   int rebuilt;
01219 
01220   if (!server_mode(get_options()))
01221     return;
01222 
01223   rebuilt = router_rebuild_descriptor(0);
01224   if (decide_if_publishable_server()) {
01225     set_server_advertised(1);
01226     if (rebuilt == 0)
01227       router_upload_dir_desc_to_dirservers(force);
01228   } else {
01229     set_server_advertised(0);
01230   }
01231 }
01232 
01237 uint16_t
01238 router_get_active_listener_port_by_type(int listener_type)
01239 {
01240   /* Iterate all connections, find one of the right kind and return
01241      the port. Not very sophisticated or fast, but effective. */
01242   const connection_t *c = connection_get_by_type(listener_type);
01243   if (c)
01244     return c->port;
01245 
01246   return 0;
01247 }
01248 
01253 uint16_t
01254 router_get_advertised_or_port(const or_options_t *options)
01255 {
01256   int port = get_primary_or_port();
01257   (void)options;
01258 
01259   /* If the port is in 'auto' mode, we have to use
01260      router_get_listener_port_by_type(). */
01261   if (port == CFG_AUTO_PORT)
01262     return router_get_active_listener_port_by_type(CONN_TYPE_OR_LISTENER);
01263 
01264   return port;
01265 }
01266 
01272 uint16_t
01273 router_get_advertised_dir_port(const or_options_t *options, uint16_t dirport)
01274 {
01275   int dirport_configured = get_primary_dir_port();
01276   (void)options;
01277 
01278   if (!dirport_configured)
01279     return dirport;
01280 
01281   if (dirport_configured == CFG_AUTO_PORT)
01282     return router_get_active_listener_port_by_type(CONN_TYPE_DIR_LISTENER);
01283 
01284   return dirport_configured;
01285 }
01286 
01287 /*
01288  * OR descriptor generation.
01289  */
01290 
01292 static routerinfo_t *desc_routerinfo = NULL;
01294 static extrainfo_t *desc_extrainfo = NULL;
01297 static const char *desc_gen_reason = NULL;
01300 static time_t desc_clean_since = 0;
01302 static const char *desc_dirty_reason = NULL;
01304 static int desc_needs_upload = 0;
01305 
01310 void
01311 router_upload_dir_desc_to_dirservers(int force)
01312 {
01313   const routerinfo_t *ri;
01314   extrainfo_t *ei;
01315   char *msg;
01316   size_t desc_len, extra_len = 0, total_len;
01317   dirinfo_type_t auth = get_options()->_PublishServerDescriptor;
01318 
01319   ri = router_get_my_routerinfo();
01320   if (!ri) {
01321     log_info(LD_GENERAL, "No descriptor; skipping upload");
01322     return;
01323   }
01324   ei = router_get_my_extrainfo();
01325   if (auth == NO_DIRINFO)
01326     return;
01327   if (!force && !desc_needs_upload)
01328     return;
01329 
01330   log_info(LD_OR, "Uploading relay descriptor to directory authorities%s",
01331            force ? " (forced)" : "");
01332 
01333   desc_needs_upload = 0;
01334 
01335   desc_len = ri->cache_info.signed_descriptor_len;
01336   extra_len = ei ? ei->cache_info.signed_descriptor_len : 0;
01337   total_len = desc_len + extra_len + 1;
01338   msg = tor_malloc(total_len);
01339   memcpy(msg, ri->cache_info.signed_descriptor_body, desc_len);
01340   if (ei) {
01341     memcpy(msg+desc_len, ei->cache_info.signed_descriptor_body, extra_len);
01342   }
01343   msg[desc_len+extra_len] = 0;
01344 
01345   directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR,
01346                                (auth & BRIDGE_DIRINFO) ?
01347                                  ROUTER_PURPOSE_BRIDGE :
01348                                  ROUTER_PURPOSE_GENERAL,
01349                                auth, msg, desc_len, extra_len);
01350   tor_free(msg);
01351 }
01352 
01356 int
01357 router_compare_to_my_exit_policy(edge_connection_t *conn)
01358 {
01359   if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
01360     return -1;
01361 
01362   /* make sure it's resolved to something. this way we can't get a
01363      'maybe' below. */
01364   if (tor_addr_is_null(&conn->_base.addr))
01365     return -1;
01366 
01367   /* XXXX IPv6 */
01368   if (tor_addr_family(&conn->_base.addr) != AF_INET)
01369     return -1;
01370 
01371   return compare_tor_addr_to_addr_policy(&conn->_base.addr, conn->_base.port,
01372                    desc_routerinfo->exit_policy) != ADDR_POLICY_ACCEPTED;
01373 }
01374 
01377 int
01378 router_my_exit_policy_is_reject_star(void)
01379 {
01380   if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
01381     return -1;
01382 
01383   return desc_routerinfo->policy_is_reject_star;
01384 }
01385 
01388 int
01389 router_digest_is_me(const char *digest)
01390 {
01391   return (server_identitykey &&
01392           tor_memeq(server_identitykey_digest, digest, DIGEST_LEN));
01393 }
01394 
01397 int
01398 router_extrainfo_digest_is_me(const char *digest)
01399 {
01400   extrainfo_t *ei = router_get_my_extrainfo();
01401   if (!ei)
01402     return 0;
01403 
01404   return tor_memeq(digest,
01405                  ei->cache_info.signed_descriptor_digest,
01406                  DIGEST_LEN);
01407 }
01408 
01410 int
01411 router_is_me(const routerinfo_t *router)
01412 {
01413   return router_digest_is_me(router->cache_info.identity_digest);
01414 }
01415 
01417 int
01418 router_fingerprint_is_me(const char *fp)
01419 {
01420   char digest[DIGEST_LEN];
01421   if (strlen(fp) == HEX_DIGEST_LEN &&
01422       base16_decode(digest, sizeof(digest), fp, HEX_DIGEST_LEN) == 0)
01423     return router_digest_is_me(digest);
01424 
01425   return 0;
01426 }
01427 
01430 const routerinfo_t *
01431 router_get_my_routerinfo(void)
01432 {
01433   if (!server_mode(get_options()))
01434     return NULL;
01435   if (router_rebuild_descriptor(0))
01436     return NULL;
01437   return desc_routerinfo;
01438 }
01439 
01443 const char *
01444 router_get_my_descriptor(void)
01445 {
01446   const char *body;
01447   if (!router_get_my_routerinfo())
01448     return NULL;
01449   /* Make sure this is nul-terminated. */
01450   tor_assert(desc_routerinfo->cache_info.saved_location == SAVED_NOWHERE);
01451   body = signed_descriptor_get_body(&desc_routerinfo->cache_info);
01452   tor_assert(!body[desc_routerinfo->cache_info.signed_descriptor_len]);
01453   log_debug(LD_GENERAL,"my desc is '%s'", body);
01454   return body;
01455 }
01456 
01459 extrainfo_t *
01460 router_get_my_extrainfo(void)
01461 {
01462   if (!server_mode(get_options()))
01463     return NULL;
01464   if (router_rebuild_descriptor(0))
01465     return NULL;
01466   return desc_extrainfo;
01467 }
01468 
01471 const char *
01472 router_get_descriptor_gen_reason(void)
01473 {
01474   return desc_gen_reason;
01475 }
01476 
01479 static smartlist_t *warned_nonexistent_family = NULL;
01480 
01481 static int router_guess_address_from_dir_headers(uint32_t *guess);
01482 
01487 int
01488 router_pick_published_address(const or_options_t *options, uint32_t *addr)
01489 {
01490   if (resolve_my_address(LOG_INFO, options, addr, NULL) < 0) {
01491     log_info(LD_CONFIG, "Could not determine our address locally. "
01492              "Checking if directory headers provide any hints.");
01493     if (router_guess_address_from_dir_headers(addr) < 0) {
01494       log_info(LD_CONFIG, "No hints from directory headers either. "
01495                "Will try again later.");
01496       return -1;
01497     }
01498   }
01499   log_info(LD_CONFIG,"Success: chose address '%s'.", fmt_addr32(*addr));
01500   return 0;
01501 }
01502 
01507 int
01508 router_rebuild_descriptor(int force)
01509 {
01510   routerinfo_t *ri;
01511   extrainfo_t *ei;
01512   uint32_t addr;
01513   char platform[256];
01514   int hibernating = we_are_hibernating();
01515   const or_options_t *options = get_options();
01516 
01517   if (desc_clean_since && !force)
01518     return 0;
01519 
01520   if (router_pick_published_address(options, &addr) < 0 ||
01521       router_get_advertised_or_port(options) == 0) {
01522     /* Stop trying to rebuild our descriptor every second. We'll
01523      * learn that it's time to try again when ip_address_changed()
01524      * marks it dirty. */
01525     desc_clean_since = time(NULL);
01526     return -1;
01527   }
01528 
01529   log_info(LD_OR, "Rebuilding relay descriptor%s", force ? " (forced)" : "");
01530 
01531   ri = tor_malloc_zero(sizeof(routerinfo_t));
01532   ri->cache_info.routerlist_index = -1;
01533   ri->address = tor_dup_ip(addr);
01534   ri->nickname = tor_strdup(options->Nickname);
01535   ri->addr = addr;
01536   ri->or_port = router_get_advertised_or_port(options);
01537   ri->dir_port = router_get_advertised_dir_port(options, 0);
01538   ri->cache_info.published_on = time(NULL);
01539   ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from
01540                                                         * main thread */
01541   if (options->BridgeRelay) {
01542     /* For now, only bridges advertise an ipv6 or-address.  And only one. */
01543     const port_cfg_t *ipv6_orport = NULL;
01544     SMARTLIST_FOREACH_BEGIN(get_configured_ports(), const port_cfg_t *, p) {
01545       if (p->type == CONN_TYPE_OR_LISTENER &&
01546           ! p->no_advertise &&
01547           ! p->ipv4_only &&
01548           tor_addr_family(&p->addr) == AF_INET6) {
01549         if (! tor_addr_is_internal(&p->addr, 0)) {
01550           ipv6_orport = p;
01551           break;
01552         } else {
01553           char addrbuf[TOR_ADDR_BUF_LEN];
01554           log_warn(LD_CONFIG,
01555                    "Unable to use configured IPv6 address \"%s\" in a "
01556                    "descriptor. Skipping it. "
01557                    "Try specifying a globally reachable address explicitly. ",
01558                    tor_addr_to_str(addrbuf, &p->addr, sizeof(addrbuf), 1));
01559         }
01560       }
01561     } SMARTLIST_FOREACH_END(p);
01562     if (ipv6_orport) {
01563       tor_addr_copy(&ri->ipv6_addr, &ipv6_orport->addr);
01564       ri->ipv6_orport = ipv6_orport->port;
01565     }
01566   }
01567   ri->identity_pkey = crypto_pk_dup_key(get_server_identity_key());
01568   if (crypto_pk_get_digest(ri->identity_pkey,
01569                            ri->cache_info.identity_digest)<0) {
01570     routerinfo_free(ri);
01571     return -1;
01572   }
01573   get_platform_str(platform, sizeof(platform));
01574   ri->platform = tor_strdup(platform);
01575 
01576   /* compute ri->bandwidthrate as the min of various options */
01577   ri->bandwidthrate = get_effective_bwrate(options);
01578 
01579   /* and compute ri->bandwidthburst similarly */
01580   ri->bandwidthburst = get_effective_bwburst(options);
01581 
01582   ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
01583 
01584   if (dns_seems_to_be_broken() || has_dns_init_failed()) {
01585     /* DNS is screwed up; don't claim to be an exit. */
01586     policies_exit_policy_append_reject_star(&ri->exit_policy);
01587   } else {
01588     policies_parse_exit_policy(options->ExitPolicy, &ri->exit_policy,
01589                                options->ExitPolicyRejectPrivate,
01590                                ri->address, !options->BridgeRelay);
01591   }
01592   ri->policy_is_reject_star =
01593     policy_is_reject_star(ri->exit_policy);
01594 
01595 #if 0
01596   /* XXXX NM NM I belive this is safe to remove */
01597   if (authdir_mode(options))
01598     ri->is_valid = ri->is_named = 1; /* believe in yourself */
01599 #endif
01600 
01601   if (options->MyFamily && ! options->BridgeRelay) {
01602     smartlist_t *family;
01603     if (!warned_nonexistent_family)
01604       warned_nonexistent_family = smartlist_new();
01605     family = smartlist_new();
01606     ri->declared_family = smartlist_new();
01607     smartlist_split_string(family, options->MyFamily, ",",
01608       SPLIT_SKIP_SPACE|SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
01609     SMARTLIST_FOREACH_BEGIN(family, char *, name) {
01610        const node_t *member;
01611        if (!strcasecmp(name, options->Nickname))
01612          goto skip; /* Don't list ourself, that's redundant */
01613        else
01614          member = node_get_by_nickname(name, 1);
01615        if (!member) {
01616          int is_legal = is_legal_nickname_or_hexdigest(name);
01617          if (!smartlist_string_isin(warned_nonexistent_family, name) &&
01618              !is_legal_hexdigest(name)) {
01619            if (is_legal)
01620              log_warn(LD_CONFIG,
01621                       "I have no descriptor for the router named \"%s\" in my "
01622                       "declared family; I'll use the nickname as is, but "
01623                       "this may confuse clients.", name);
01624            else
01625              log_warn(LD_CONFIG, "There is a router named \"%s\" in my "
01626                       "declared family, but that isn't a legal nickname. "
01627                       "Skipping it.", escaped(name));
01628            smartlist_add(warned_nonexistent_family, tor_strdup(name));
01629          }
01630          if (is_legal) {
01631            smartlist_add(ri->declared_family, name);
01632            name = NULL;
01633          }
01634        } else if (router_digest_is_me(member->identity)) {
01635          /* Don't list ourself in our own family; that's redundant */
01636          /* XXX shouldn't be possible */
01637        } else {
01638          char *fp = tor_malloc(HEX_DIGEST_LEN+2);
01639          fp[0] = '$';
01640          base16_encode(fp+1,HEX_DIGEST_LEN+1,
01641                        member->identity, DIGEST_LEN);
01642          smartlist_add(ri->declared_family, fp);
01643          if (smartlist_string_isin(warned_nonexistent_family, name))
01644            smartlist_string_remove(warned_nonexistent_family, name);
01645        }
01646     skip:
01647        tor_free(name);
01648     } SMARTLIST_FOREACH_END(name);
01649 
01650     /* remove duplicates from the list */
01651     smartlist_sort_strings(ri->declared_family);
01652     smartlist_uniq_strings(ri->declared_family);
01653 
01654     smartlist_free(family);
01655   }
01656 
01657   /* Now generate the extrainfo. */
01658   ei = tor_malloc_zero(sizeof(extrainfo_t));
01659   ei->cache_info.is_extrainfo = 1;
01660   strlcpy(ei->nickname, get_options()->Nickname, sizeof(ei->nickname));
01661   ei->cache_info.published_on = ri->cache_info.published_on;
01662   memcpy(ei->cache_info.identity_digest, ri->cache_info.identity_digest,
01663          DIGEST_LEN);
01664   if (extrainfo_dump_to_string(&ei->cache_info.signed_descriptor_body,
01665                                ei, get_server_identity_key()) < 0) {
01666     log_warn(LD_BUG, "Couldn't generate extra-info descriptor.");
01667     extrainfo_free(ei);
01668     ei = NULL;
01669   } else {
01670     ei->cache_info.signed_descriptor_len =
01671       strlen(ei->cache_info.signed_descriptor_body);
01672     router_get_extrainfo_hash(ei->cache_info.signed_descriptor_body,
01673                               ei->cache_info.signed_descriptor_len,
01674                               ei->cache_info.signed_descriptor_digest);
01675   }
01676 
01677   /* Now finish the router descriptor. */
01678   if (ei) {
01679     memcpy(ri->cache_info.extra_info_digest,
01680            ei->cache_info.signed_descriptor_digest,
01681            DIGEST_LEN);
01682   } else {
01683     /* ri was allocated with tor_malloc_zero, so there is no need to
01684      * zero ri->cache_info.extra_info_digest here. */
01685   }
01686   ri->cache_info.signed_descriptor_body = tor_malloc(8192);
01687   if (router_dump_router_to_string(ri->cache_info.signed_descriptor_body, 8192,
01688                                    ri, get_server_identity_key()) < 0) {
01689     log_warn(LD_BUG, "Couldn't generate router descriptor.");
01690     routerinfo_free(ri);
01691     extrainfo_free(ei);
01692     return -1;
01693   }
01694   ri->cache_info.signed_descriptor_len =
01695     strlen(ri->cache_info.signed_descriptor_body);
01696 
01697   ri->purpose =
01698     options->BridgeRelay ? ROUTER_PURPOSE_BRIDGE : ROUTER_PURPOSE_GENERAL;
01699   if (options->BridgeRelay) {
01700     /* Bridges shouldn't be able to send their descriptors unencrypted,
01701        anyway, since they don't have a DirPort, and always connect to the
01702        bridge authority anonymously.  But just in case they somehow think of
01703        sending them on an unencrypted connection, don't allow them to try. */
01704     ri->cache_info.send_unencrypted = ei->cache_info.send_unencrypted = 0;
01705   } else {
01706     ri->cache_info.send_unencrypted = ei->cache_info.send_unencrypted = 1;
01707   }
01708 
01709   router_get_router_hash(ri->cache_info.signed_descriptor_body,
01710                          strlen(ri->cache_info.signed_descriptor_body),
01711                          ri->cache_info.signed_descriptor_digest);
01712 
01713   if (ei) {
01714     tor_assert(! routerinfo_incompatible_with_extrainfo(ri, ei, NULL, NULL));
01715   }
01716 
01717   routerinfo_free(desc_routerinfo);
01718   desc_routerinfo = ri;
01719   extrainfo_free(desc_extrainfo);
01720   desc_extrainfo = ei;
01721 
01722   desc_clean_since = time(NULL);
01723   desc_needs_upload = 1;
01724   desc_gen_reason = desc_dirty_reason;
01725   desc_dirty_reason = NULL;
01726   control_event_my_descriptor_changed();
01727   return 0;
01728 }
01729 
01732 #define FORCE_REGENERATE_DESCRIPTOR_INTERVAL (18*60*60)
01733 
01736 #define FAST_RETRY_DESCRIPTOR_INTERVAL (90*60)
01737 
01740 void
01741 mark_my_descriptor_dirty_if_too_old(time_t now)
01742 {
01743   networkstatus_t *ns;
01744   const routerstatus_t *rs;
01745   const char *retry_fast_reason = NULL; /* Set if we should retry frequently */
01746   const time_t slow_cutoff = now - FORCE_REGENERATE_DESCRIPTOR_INTERVAL;
01747   const time_t fast_cutoff = now - FAST_RETRY_DESCRIPTOR_INTERVAL;
01748 
01749   /* If it's already dirty, don't mark it. */
01750   if (! desc_clean_since)
01751     return;
01752 
01753   /* If it's older than FORCE_REGENERATE_DESCRIPTOR_INTERVAL, it's always
01754    * time to rebuild it. */
01755   if (desc_clean_since < slow_cutoff) {
01756     mark_my_descriptor_dirty("time for new descriptor");
01757     return;
01758   }
01759   /* Now we see whether we want to be retrying frequently or no.  The
01760    * rule here is that we'll retry frequently if we aren't listed in the
01761    * live consensus we have, or if the publication time of the
01762    * descriptor listed for us in the consensus is very old. */
01763   ns = networkstatus_get_live_consensus(now);
01764   if (ns) {
01765     rs = networkstatus_vote_find_entry(ns, server_identitykey_digest);
01766     if (rs == NULL)
01767       retry_fast_reason = "not listed in consensus";
01768     else if (rs->published_on < slow_cutoff)
01769       retry_fast_reason = "version listed in consensus is quite old";
01770   }
01771 
01772   if (retry_fast_reason && desc_clean_since < fast_cutoff)
01773     mark_my_descriptor_dirty(retry_fast_reason);
01774 }
01775 
01777 void
01778 mark_my_descriptor_dirty(const char *reason)
01779 {
01780   const or_options_t *options = get_options();
01781   if (server_mode(options) && options->_PublishServerDescriptor)
01782     log_info(LD_OR, "Decided to publish new relay descriptor: %s", reason);
01783   desc_clean_since = 0;
01784   if (!desc_dirty_reason)
01785     desc_dirty_reason = reason;
01786 }
01787 
01790 #define MAX_BANDWIDTH_CHANGE_FREQ (20*60)
01791 
01794 void
01795 check_descriptor_bandwidth_changed(time_t now)
01796 {
01797   static time_t last_changed = 0;
01798   uint64_t prev, cur;
01799   if (!desc_routerinfo)
01800     return;
01801 
01802   prev = desc_routerinfo->bandwidthcapacity;
01803   cur = we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
01804   if ((prev != cur && (!prev || !cur)) ||
01805       cur > prev*2 ||
01806       cur < prev/2) {
01807     if (last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now) {
01808       log_info(LD_GENERAL,
01809                "Measured bandwidth has changed; rebuilding descriptor.");
01810       mark_my_descriptor_dirty("bandwidth has changed");
01811       last_changed = now;
01812     }
01813   }
01814 }
01815 
01818 static void
01819 log_addr_has_changed(int severity,
01820                      const tor_addr_t *prev,
01821                      const tor_addr_t *cur,
01822                      const char *source)
01823 {
01824   char addrbuf_prev[TOR_ADDR_BUF_LEN];
01825   char addrbuf_cur[TOR_ADDR_BUF_LEN];
01826 
01827   if (tor_addr_to_str(addrbuf_prev, prev, sizeof(addrbuf_prev), 1) == NULL)
01828     strlcpy(addrbuf_prev, "???", TOR_ADDR_BUF_LEN);
01829   if (tor_addr_to_str(addrbuf_cur, cur, sizeof(addrbuf_cur), 1) == NULL)
01830     strlcpy(addrbuf_cur, "???", TOR_ADDR_BUF_LEN);
01831 
01832   if (!tor_addr_is_null(prev))
01833     log_fn(severity, LD_GENERAL,
01834            "Our IP Address has changed from %s to %s; "
01835            "rebuilding descriptor (source: %s).",
01836            addrbuf_prev, addrbuf_cur, source);
01837   else
01838     log_notice(LD_GENERAL,
01839              "Guessed our IP address as %s (source: %s).",
01840              addrbuf_cur, source);
01841 }
01842 
01846 void
01847 check_descriptor_ipaddress_changed(time_t now)
01848 {
01849   uint32_t prev, cur;
01850   const or_options_t *options = get_options();
01851   (void) now;
01852 
01853   if (!desc_routerinfo)
01854     return;
01855 
01856   /* XXXX ipv6 */
01857   prev = desc_routerinfo->addr;
01858   if (resolve_my_address(LOG_INFO, options, &cur, NULL) < 0) {
01859     log_info(LD_CONFIG,"options->Address didn't resolve into an IP.");
01860     return;
01861   }
01862 
01863   if (prev != cur) {
01864     tor_addr_t tmp_prev, tmp_cur;
01865     tor_addr_from_ipv4h(&tmp_prev, prev);
01866     tor_addr_from_ipv4h(&tmp_cur, cur);
01867     log_addr_has_changed(LOG_NOTICE, &tmp_prev, &tmp_cur, "resolve");
01868     ip_address_changed(0);
01869   }
01870 }
01871 
01874 static tor_addr_t last_guessed_ip = TOR_ADDR_NULL;
01875 
01880 void
01881 router_new_address_suggestion(const char *suggestion,
01882                               const dir_connection_t *d_conn)
01883 {
01884   tor_addr_t addr;
01885   uint32_t cur = 0;             /* Current IPv4 address.  */
01886   const or_options_t *options = get_options();
01887 
01888   /* first, learn what the IP address actually is */
01889   if (tor_addr_parse(&addr, suggestion) == -1) {
01890     log_debug(LD_DIR, "Malformed X-Your-Address-Is header %s. Ignoring.",
01891               escaped(suggestion));
01892     return;
01893   }
01894 
01895   log_debug(LD_DIR, "Got X-Your-Address-Is: %s.", suggestion);
01896 
01897   if (!server_mode(options)) {
01898     tor_addr_copy(&last_guessed_ip, &addr);
01899     return;
01900   }
01901 
01902   /* XXXX ipv6 */
01903   if (resolve_my_address(LOG_INFO, options, &cur, NULL) >= 0) {
01904     /* We're all set -- we already know our address. Great. */
01905     tor_addr_from_ipv4h(&last_guessed_ip, cur); /* store it in case we
01906                                                    need it later */
01907     return;
01908   }
01909   if (tor_addr_is_internal(&addr, 0)) {
01910     /* Don't believe anybody who says our IP is, say, 127.0.0.1. */
01911     return;
01912   }
01913   if (tor_addr_eq(&d_conn->_base.addr, &addr)) {
01914     /* Don't believe anybody who says our IP is their IP. */
01915     log_debug(LD_DIR, "A directory server told us our IP address is %s, "
01916               "but he's just reporting his own IP address. Ignoring.",
01917               suggestion);
01918     return;
01919   }
01920 
01921   /* Okay.  We can't resolve our own address, and X-Your-Address-Is is giving
01922    * us an answer different from what we had the last time we managed to
01923    * resolve it. */
01924   if (!tor_addr_eq(&last_guessed_ip, &addr)) {
01925     control_event_server_status(LOG_NOTICE,
01926                                 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=DIRSERV",
01927                                 suggestion);
01928     log_addr_has_changed(LOG_NOTICE, &last_guessed_ip, &addr,
01929                          d_conn->_base.address);
01930     ip_address_changed(0);
01931     tor_addr_copy(&last_guessed_ip, &addr); /* router_rebuild_descriptor()
01932                                                will fetch it */
01933   }
01934 }
01935 
01940 static int
01941 router_guess_address_from_dir_headers(uint32_t *guess)
01942 {
01943   if (!tor_addr_is_null(&last_guessed_ip)) {
01944     *guess = tor_addr_to_ipv4h(&last_guessed_ip);
01945     return 0;
01946   }
01947   return -1;
01948 }
01949 
01954 void
01955 get_platform_str(char *platform, size_t len)
01956 {
01957   tor_snprintf(platform, len, "Tor %s on %s",
01958                get_short_version(), get_uname());
01959 }
01960 
01961 /* XXX need to audit this thing and count fenceposts. maybe
01962  *     refactor so we don't have to keep asking if we're
01963  *     near the end of maxlen?
01964  */
01965 #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
01966 
01972 int
01973 router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
01974                              crypto_pk_t *ident_key)
01975 {
01976   char *onion_pkey; /* Onion key, PEM-encoded. */
01977   char *identity_pkey; /* Identity key, PEM-encoded. */
01978   char digest[DIGEST_LEN];
01979   char published[ISO_TIME_LEN+1];
01980   char fingerprint[FINGERPRINT_LEN+1];
01981   int has_extra_info_digest;
01982   char extra_info_digest[HEX_DIGEST_LEN+1];
01983   size_t onion_pkeylen, identity_pkeylen;
01984   size_t written;
01985   int result=0;
01986   addr_policy_t *tmpe;
01987   char *family_line;
01988   char *extra_or_address = NULL;
01989   const or_options_t *options = get_options();
01990 
01991   /* Make sure the identity key matches the one in the routerinfo. */
01992   if (crypto_pk_cmp_keys(ident_key, router->identity_pkey)) {
01993     log_warn(LD_BUG,"Tried to sign a router with a private key that didn't "
01994              "match router's public key!");
01995     return -1;
01996   }
01997 
01998   /* record our fingerprint, so we can include it in the descriptor */
01999   if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
02000     log_err(LD_BUG,"Error computing fingerprint");
02001     return -1;
02002   }
02003 
02004   /* PEM-encode the onion key */
02005   if (crypto_pk_write_public_key_to_string(router->onion_pkey,
02006                                            &onion_pkey,&onion_pkeylen)<0) {
02007     log_warn(LD_BUG,"write onion_pkey to string failed!");
02008     return -1;
02009   }
02010 
02011   /* PEM-encode the identity key */
02012   if (crypto_pk_write_public_key_to_string(router->identity_pkey,
02013                                         &identity_pkey,&identity_pkeylen)<0) {
02014     log_warn(LD_BUG,"write identity_pkey to string failed!");
02015     tor_free(onion_pkey);
02016     return -1;
02017   }
02018 
02019   /* Encode the publication time. */
02020   format_iso_time(published, router->cache_info.published_on);
02021 
02022   if (router->declared_family && smartlist_len(router->declared_family)) {
02023     char *family = smartlist_join_strings(router->declared_family,
02024                                           " ", 0, NULL);
02025     tor_asprintf(&family_line, "family %s\n", family);
02026     tor_free(family);
02027   } else {
02028     family_line = tor_strdup("");
02029   }
02030 
02031   has_extra_info_digest =
02032     ! tor_digest_is_zero(router->cache_info.extra_info_digest);
02033 
02034   if (has_extra_info_digest) {
02035     base16_encode(extra_info_digest, sizeof(extra_info_digest),
02036                   router->cache_info.extra_info_digest, DIGEST_LEN);
02037   }
02038 
02039   if (router->ipv6_orport &&
02040       tor_addr_family(&router->ipv6_addr) == AF_INET6) {
02041     char addr[TOR_ADDR_BUF_LEN];
02042     const char *a;
02043     a = tor_addr_to_str(addr, &router->ipv6_addr, sizeof(addr), 1);
02044     if (a) {
02045       tor_asprintf(&extra_or_address,
02046                    "or-address %s:%d\n", a, router->ipv6_orport);
02047       log_debug(LD_OR, "My or-address line is <%s>", extra_or_address);
02048     }
02049   }
02050 
02051   /* Generate the easy portion of the router descriptor. */
02052   result = tor_snprintf(s, maxlen,
02053                     "router %s %s %d 0 %d\n"
02054                     "%s"
02055                     "platform %s\n"
02056                     "opt protocols Link 1 2 Circuit 1\n"
02057                     "published %s\n"
02058                     "opt fingerprint %s\n"
02059                     "uptime %ld\n"
02060                     "bandwidth %d %d %d\n"
02061                     "%s%s%s%s"
02062                     "onion-key\n%s"
02063                     "signing-key\n%s"
02064                     "%s%s%s%s",
02065     router->nickname,
02066     router->address,
02067     router->or_port,
02068     decide_to_advertise_dirport(options, router->dir_port),
02069     extra_or_address ? extra_or_address : "",
02070     router->platform,
02071     published,
02072     fingerprint,
02073     stats_n_seconds_working,
02074     (int) router->bandwidthrate,
02075     (int) router->bandwidthburst,
02076     (int) router->bandwidthcapacity,
02077     has_extra_info_digest ? "opt extra-info-digest " : "",
02078     has_extra_info_digest ? extra_info_digest : "",
02079     has_extra_info_digest ? "\n" : "",
02080     options->DownloadExtraInfo ? "opt caches-extra-info\n" : "",
02081     onion_pkey, identity_pkey,
02082     family_line,
02083     we_are_hibernating() ? "opt hibernating 1\n" : "",
02084     options->HidServDirectoryV2 ? "opt hidden-service-dir\n" : "",
02085     options->AllowSingleHopExits ? "opt allow-single-hop-exits\n" : "");
02086 
02087   tor_free(family_line);
02088   tor_free(onion_pkey);
02089   tor_free(identity_pkey);
02090   tor_free(extra_or_address);
02091 
02092   if (result < 0) {
02093     log_warn(LD_BUG,"descriptor snprintf #1 ran out of room!");
02094     return -1;
02095   }
02096   /* From now on, we use 'written' to remember the current length of 's'. */
02097   written = result;
02098 
02099   if (options->ContactInfo && strlen(options->ContactInfo)) {
02100     const char *ci = options->ContactInfo;
02101     if (strchr(ci, '\n') || strchr(ci, '\r'))
02102       ci = escaped(ci);
02103     result = tor_snprintf(s+written,maxlen-written, "contact %s\n", ci);
02104     if (result<0) {
02105       log_warn(LD_BUG,"descriptor snprintf #2 ran out of room!");
02106       return -1;
02107     }
02108     written += result;
02109   }
02110 
02111   /* Write the exit policy to the end of 's'. */
02112   if (!router->exit_policy || !smartlist_len(router->exit_policy)) {
02113     strlcat(s+written, "reject *:*\n", maxlen-written);
02114     written += strlen("reject *:*\n");
02115     tmpe = NULL;
02116   } else if (router->exit_policy) {
02117     int i;
02118     for (i = 0; i < smartlist_len(router->exit_policy); ++i) {
02119       tmpe = smartlist_get(router->exit_policy, i);
02120       result = policy_write_item(s+written, maxlen-written, tmpe, 1);
02121       if (result < 0) {
02122         log_warn(LD_BUG,"descriptor policy_write_item ran out of room!");
02123         return -1;
02124       }
02125       tor_assert(result == (int)strlen(s+written));
02126       written += result;
02127       if (written+2 > maxlen) {
02128         log_warn(LD_BUG,"descriptor policy_write_item ran out of room (2)!");
02129         return -1;
02130       }
02131       s[written++] = '\n';
02132     }
02133   }
02134 
02135   if (written + DIROBJ_MAX_SIG_LEN > maxlen) {
02136     /* Not enough room for signature. */
02137     log_warn(LD_BUG,"not enough room left in descriptor for signature!");
02138     return -1;
02139   }
02140 
02141   /* Sign the descriptor */
02142   strlcpy(s+written, "router-signature\n", maxlen-written);
02143   written += strlen(s+written);
02144   s[written] = '\0';
02145   if (router_get_router_hash(s, strlen(s), digest) < 0) {
02146     return -1;
02147   }
02148 
02149   note_crypto_pk_op(SIGN_RTR);
02150   if (router_append_dirobj_signature(s+written,maxlen-written,
02151                                      digest,DIGEST_LEN,ident_key)<0) {
02152     log_warn(LD_BUG, "Couldn't sign router descriptor");
02153     return -1;
02154   }
02155   written += strlen(s+written);
02156 
02157   if (written+2 > maxlen) {
02158     log_warn(LD_BUG,"Not enough room to finish descriptor.");
02159     return -1;
02160   }
02161   /* include a last '\n' */
02162   s[written] = '\n';
02163   s[written+1] = 0;
02164 
02165 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
02166   {
02167     char *s_dup;
02168     const char *cp;
02169     routerinfo_t *ri_tmp;
02170     cp = s_dup = tor_strdup(s);
02171     ri_tmp = router_parse_entry_from_string(cp, NULL, 1, 0, NULL);
02172     if (!ri_tmp) {
02173       log_err(LD_BUG,
02174               "We just generated a router descriptor we can't parse.");
02175       log_err(LD_BUG, "Descriptor was: <<%s>>", s);
02176       return -1;
02177     }
02178     tor_free(s_dup);
02179     routerinfo_free(ri_tmp);
02180   }
02181 #endif
02182 
02183   return (int)written+1;
02184 }
02185 
02188 void
02189 router_get_prim_orport(const routerinfo_t *router, tor_addr_port_t *ap_out)
02190 {
02191   tor_assert(ap_out != NULL);
02192   tor_addr_from_ipv4h(&ap_out->addr, router->addr);
02193   ap_out->port = router->or_port;
02194 }
02195 
02203 int
02204 router_ipv6_preferred(const routerinfo_t *router)
02205 {
02206   return (!tor_addr_is_null(&router->ipv6_addr)
02207           && (router->ipv6_preferred || router->addr == 0));
02208 }
02209 
02212 void
02213 router_get_pref_orport(const routerinfo_t *router, tor_addr_port_t *ap_out)
02214 {
02215   if (router_ipv6_preferred(router))
02216     router_get_pref_ipv6_orport(router, ap_out);
02217   else
02218     router_get_prim_orport(router, ap_out);
02219 }
02220 
02223 void
02224 router_get_pref_ipv6_orport(const routerinfo_t *router,
02225                             tor_addr_port_t *ap_out)
02226 {
02227   tor_assert(ap_out != NULL);
02228   tor_addr_copy(&ap_out->addr, &router->ipv6_addr);
02229   ap_out->port = router->ipv6_orport;
02230 }
02231 
02238 static int
02239 load_stats_file(const char *filename, const char *end_line, time_t now,
02240                 char **out)
02241 {
02242   int r = -1;
02243   char *fname = get_datadir_fname(filename);
02244   char *contents, *start = NULL, *tmp, timestr[ISO_TIME_LEN+1];
02245   time_t written;
02246   switch (file_status(fname)) {
02247     case FN_FILE:
02248       /* X022 Find an alternative to reading the whole file to memory. */
02249       if ((contents = read_file_to_str(fname, 0, NULL))) {
02250         tmp = strstr(contents, end_line);
02251         /* Find last block starting with end_line */
02252         while (tmp) {
02253           start = tmp;
02254           tmp = strstr(tmp + 1, end_line);
02255         }
02256         if (!start)
02257           goto notfound;
02258         if (strlen(start) < strlen(end_line) + 1 + sizeof(timestr))
02259           goto notfound;
02260         strlcpy(timestr, start + 1 + strlen(end_line), sizeof(timestr));
02261         if (parse_iso_time(timestr, &written) < 0)
02262           goto notfound;
02263         if (written < now - (25*60*60) || written > now + (1*60*60))
02264           goto notfound;
02265         *out = tor_strdup(start);
02266         r = 1;
02267       }
02268      notfound:
02269       tor_free(contents);
02270       break;
02271     case FN_NOENT:
02272       r = 0;
02273       break;
02274     case FN_ERROR:
02275     case FN_DIR:
02276     default:
02277       break;
02278   }
02279   tor_free(fname);
02280   return r;
02281 }
02282 
02286 int
02287 extrainfo_dump_to_string(char **s_out, extrainfo_t *extrainfo,
02288                          crypto_pk_t *ident_key)
02289 {
02290   const or_options_t *options = get_options();
02291   char identity[HEX_DIGEST_LEN+1];
02292   char published[ISO_TIME_LEN+1];
02293   char digest[DIGEST_LEN];
02294   char *bandwidth_usage;
02295   int result;
02296   static int write_stats_to_extrainfo = 1;
02297   char sig[DIROBJ_MAX_SIG_LEN+1];
02298   char *s, *pre, *contents, *cp, *s_dup = NULL;
02299   time_t now = time(NULL);
02300   smartlist_t *chunks = smartlist_new();
02301   extrainfo_t *ei_tmp = NULL;
02302 
02303   base16_encode(identity, sizeof(identity),
02304                 extrainfo->cache_info.identity_digest, DIGEST_LEN);
02305   format_iso_time(published, extrainfo->cache_info.published_on);
02306   bandwidth_usage = rep_hist_get_bandwidth_lines();
02307 
02308   tor_asprintf(&pre, "extra-info %s %s\npublished %s\n%s",
02309                extrainfo->nickname, identity,
02310                published, bandwidth_usage);
02311   tor_free(bandwidth_usage);
02312   smartlist_add(chunks, pre);
02313 
02314   if (geoip_is_loaded()) {
02315     smartlist_add_asprintf(chunks, "geoip-db-digest %s\n", geoip_db_digest());
02316   }
02317 
02318   if (options->ExtraInfoStatistics && write_stats_to_extrainfo) {
02319     log_info(LD_GENERAL, "Adding stats to extra-info descriptor.");
02320     if (options->DirReqStatistics &&
02321         load_stats_file("stats"PATH_SEPARATOR"dirreq-stats",
02322                         "dirreq-stats-end", now, &contents) > 0) {
02323       smartlist_add(chunks, contents);
02324     }
02325     if (options->EntryStatistics &&
02326         load_stats_file("stats"PATH_SEPARATOR"entry-stats",
02327                         "entry-stats-end", now, &contents) > 0) {
02328       smartlist_add(chunks, contents);
02329     }
02330     if (options->CellStatistics &&
02331         load_stats_file("stats"PATH_SEPARATOR"buffer-stats",
02332                         "cell-stats-end", now, &contents) > 0) {
02333       smartlist_add(chunks, contents);
02334     }
02335     if (options->ExitPortStatistics &&
02336         load_stats_file("stats"PATH_SEPARATOR"exit-stats",
02337                         "exit-stats-end", now, &contents) > 0) {
02338       smartlist_add(chunks, contents);
02339     }
02340     if (options->ConnDirectionStatistics &&
02341         load_stats_file("stats"PATH_SEPARATOR"conn-stats",
02342                         "conn-bi-direct", now, &contents) > 0) {
02343       smartlist_add(chunks, contents);
02344     }
02345   }
02346 
02347   if (should_record_bridge_info(options) && write_stats_to_extrainfo) {
02348     const char *bridge_stats = geoip_get_bridge_stats_extrainfo(now);
02349     if (bridge_stats) {
02350       smartlist_add(chunks, tor_strdup(bridge_stats));
02351     }
02352   }
02353 
02354   smartlist_add(chunks, tor_strdup("router-signature\n"));
02355   s = smartlist_join_strings(chunks, "", 0, NULL);
02356 
02357   while (strlen(s) > MAX_EXTRAINFO_UPLOAD_SIZE - DIROBJ_MAX_SIG_LEN) {
02358     /* So long as there are at least two chunks (one for the initial
02359      * extra-info line and one for the router-signature), we can keep removing
02360      * things. */
02361     if (smartlist_len(chunks) > 2) {
02362       /* We remove the next-to-last element (remember, len-1 is the last
02363          element), since we need to keep the router-signature element. */
02364       int idx = smartlist_len(chunks) - 2;
02365       char *e = smartlist_get(chunks, idx);
02366       smartlist_del_keeporder(chunks, idx);
02367       log_warn(LD_GENERAL, "We just generated an extra-info descriptor "
02368                            "with statistics that exceeds the 50 KB "
02369                            "upload limit. Removing last added "
02370                            "statistics.");
02371       tor_free(e);
02372       tor_free(s);
02373       s = smartlist_join_strings(chunks, "", 0, NULL);
02374     } else {
02375       log_warn(LD_BUG, "We just generated an extra-info descriptors that "
02376                        "exceeds the 50 KB upload limit.");
02377       goto err;
02378     }
02379   }
02380 
02381   memset(sig, 0, sizeof(sig));
02382   if (router_get_extrainfo_hash(s, strlen(s), digest) < 0 ||
02383       router_append_dirobj_signature(sig, sizeof(sig), digest, DIGEST_LEN,
02384                                      ident_key) < 0) {
02385     log_warn(LD_BUG, "Could not append signature to extra-info "
02386                      "descriptor.");
02387     goto err;
02388   }
02389   smartlist_add(chunks, tor_strdup(sig));
02390   tor_free(s);
02391   s = smartlist_join_strings(chunks, "", 0, NULL);
02392 
02393   cp = s_dup = tor_strdup(s);
02394   ei_tmp = extrainfo_parse_entry_from_string(cp, NULL, 1, NULL);
02395   if (!ei_tmp) {
02396     if (write_stats_to_extrainfo) {
02397       log_warn(LD_GENERAL, "We just generated an extra-info descriptor "
02398                            "with statistics that we can't parse. Not "
02399                            "adding statistics to this or any future "
02400                            "extra-info descriptors.");
02401       write_stats_to_extrainfo = 0;
02402       result = extrainfo_dump_to_string(s_out, extrainfo, ident_key);
02403       goto done;
02404     } else {
02405       log_warn(LD_BUG, "We just generated an extrainfo descriptor we "
02406                        "can't parse.");
02407       goto err;
02408     }
02409   }
02410 
02411   *s_out = s;
02412   s = NULL; /* prevent free */
02413   result = 0;
02414   goto done;
02415 
02416  err:
02417   result = -1;
02418 
02419  done:
02420   tor_free(s);
02421   SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
02422   smartlist_free(chunks);
02423   tor_free(s_dup);
02424   extrainfo_free(ei_tmp);
02425 
02426   return result;
02427 }
02428 
02430 int
02431 is_legal_nickname(const char *s)
02432 {
02433   size_t len;
02434   tor_assert(s);
02435   len = strlen(s);
02436   return len > 0 && len <= MAX_NICKNAME_LEN &&
02437     strspn(s,LEGAL_NICKNAME_CHARACTERS) == len;
02438 }
02439 
02442 int
02443 is_legal_nickname_or_hexdigest(const char *s)
02444 {
02445   if (*s!='$')
02446     return is_legal_nickname(s);
02447   else
02448     return is_legal_hexdigest(s);
02449 }
02450 
02453 int
02454 is_legal_hexdigest(const char *s)
02455 {
02456   size_t len;
02457   tor_assert(s);
02458   if (s[0] == '$') s++;
02459   len = strlen(s);
02460   if (len > HEX_DIGEST_LEN) {
02461     if (s[HEX_DIGEST_LEN] == '=' ||
02462         s[HEX_DIGEST_LEN] == '~') {
02463       if (!is_legal_nickname(s+HEX_DIGEST_LEN+1))
02464         return 0;
02465     } else {
02466       return 0;
02467     }
02468   }
02469   return (len >= HEX_DIGEST_LEN &&
02470           strspn(s,HEX_CHARACTERS)==HEX_DIGEST_LEN);
02471 }
02472 
02483 const char *
02484 format_node_description(char *buf,
02485                         const char *id_digest,
02486                         int is_named,
02487                         const char *nickname,
02488                         const tor_addr_t *addr,
02489                         uint32_t addr32h)
02490 {
02491   char *cp;
02492 
02493   if (!buf)
02494     return "<NULL BUFFER>";
02495 
02496   buf[0] = '$';
02497   base16_encode(buf+1, HEX_DIGEST_LEN+1, id_digest, DIGEST_LEN);
02498   cp = buf+1+HEX_DIGEST_LEN;
02499   if (nickname) {
02500     buf[1+HEX_DIGEST_LEN] = is_named ? '=' : '~';
02501     strlcpy(buf+1+HEX_DIGEST_LEN+1, nickname, MAX_NICKNAME_LEN+1);
02502     cp += strlen(cp);
02503   }
02504   if (addr32h || addr) {
02505     memcpy(cp, " at ", 4);
02506     cp += 4;
02507     if (addr) {
02508       tor_addr_to_str(cp, addr, TOR_ADDR_BUF_LEN, 0);
02509     } else {
02510       struct in_addr in;
02511       in.s_addr = htonl(addr32h);
02512       tor_inet_ntoa(&in, cp, INET_NTOA_BUF_LEN);
02513     }
02514   }
02515   return buf;
02516 }
02517 
02524 const char *
02525 router_get_description(char *buf, const routerinfo_t *ri)
02526 {
02527   if (!ri)
02528     return "<null>";
02529   return format_node_description(buf,
02530                                  ri->cache_info.identity_digest,
02531                                  router_is_named(ri),
02532                                  ri->nickname,
02533                                  NULL,
02534                                  ri->addr);
02535 }
02536 
02542 const char *
02543 node_get_description(char *buf, const node_t *node)
02544 {
02545   const char *nickname = NULL;
02546   uint32_t addr32h = 0;
02547   int is_named = 0;
02548 
02549   if (!node)
02550     return "<null>";
02551 
02552   if (node->rs) {
02553     nickname = node->rs->nickname;
02554     is_named = node->rs->is_named;
02555     addr32h = node->rs->addr;
02556   } else if (node->ri) {
02557     nickname = node->ri->nickname;
02558     addr32h = node->ri->addr;
02559   }
02560 
02561   return format_node_description(buf,
02562                                  node->identity,
02563                                  is_named,
02564                                  nickname,
02565                                  NULL,
02566                                  addr32h);
02567 }
02568 
02574 const char *
02575 routerstatus_get_description(char *buf, const routerstatus_t *rs)
02576 {
02577   if (!rs)
02578     return "<null>";
02579   return format_node_description(buf,
02580                                  rs->identity_digest,
02581                                  rs->is_named,
02582                                  rs->nickname,
02583                                  NULL,
02584                                  rs->addr);
02585 }
02586 
02592 const char *
02593 extend_info_get_description(char *buf, const extend_info_t *ei)
02594 {
02595   if (!ei)
02596     return "<null>";
02597   return format_node_description(buf,
02598                                  ei->identity_digest,
02599                                  0,
02600                                  ei->nickname,
02601                                  &ei->addr,
02602                                  0);
02603 }
02604 
02610 const char *
02611 router_describe(const routerinfo_t *ri)
02612 {
02613   static char buf[NODE_DESC_BUF_LEN];
02614   return router_get_description(buf, ri);
02615 }
02616 
02622 const char *
02623 node_describe(const node_t *node)
02624 {
02625   static char buf[NODE_DESC_BUF_LEN];
02626   return node_get_description(buf, node);
02627 }
02628 
02634 const char *
02635 routerstatus_describe(const routerstatus_t *rs)
02636 {
02637   static char buf[NODE_DESC_BUF_LEN];
02638   return routerstatus_get_description(buf, rs);
02639 }
02640 
02646 const char *
02647 extend_info_describe(const extend_info_t *ei)
02648 {
02649   static char buf[NODE_DESC_BUF_LEN];
02650   return extend_info_get_description(buf, ei);
02651 }
02652 
02660 void
02661 router_get_verbose_nickname(char *buf, const routerinfo_t *router)
02662 {
02663   const char *good_digest = networkstatus_get_router_digest_by_nickname(
02664                                                          router->nickname);
02665   int is_named = good_digest && tor_memeq(good_digest,
02666                                         router->cache_info.identity_digest,
02667                                         DIGEST_LEN);
02668   buf[0] = '$';
02669   base16_encode(buf+1, HEX_DIGEST_LEN+1, router->cache_info.identity_digest,
02670                 DIGEST_LEN);
02671   buf[1+HEX_DIGEST_LEN] = is_named ? '=' : '~';
02672   strlcpy(buf+1+HEX_DIGEST_LEN+1, router->nickname, MAX_NICKNAME_LEN+1);
02673 }
02674 
02682 void
02683 routerstatus_get_verbose_nickname(char *buf, const routerstatus_t *router)
02684 {
02685   buf[0] = '$';
02686   base16_encode(buf+1, HEX_DIGEST_LEN+1, router->identity_digest,
02687                 DIGEST_LEN);
02688   buf[1+HEX_DIGEST_LEN] = router->is_named ? '=' : '~';
02689   strlcpy(buf+1+HEX_DIGEST_LEN+1, router->nickname, MAX_NICKNAME_LEN+1);
02690 }
02691 
02694 void
02695 router_reset_warnings(void)
02696 {
02697   if (warned_nonexistent_family) {
02698     SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
02699     smartlist_clear(warned_nonexistent_family);
02700   }
02701 }
02702 
02706 const char *
02707 router_purpose_to_string(uint8_t p)
02708 {
02709   switch (p)
02710     {
02711     case ROUTER_PURPOSE_GENERAL: return "general";
02712     case ROUTER_PURPOSE_BRIDGE: return "bridge";
02713     case ROUTER_PURPOSE_CONTROLLER: return "controller";
02714     default:
02715       tor_assert(0);
02716     }
02717   return NULL;
02718 }
02719 
02721 uint8_t
02722 router_purpose_from_string(const char *s)
02723 {
02724   if (!strcmp(s, "general"))
02725     return ROUTER_PURPOSE_GENERAL;
02726   else if (!strcmp(s, "bridge"))
02727     return ROUTER_PURPOSE_BRIDGE;
02728   else if (!strcmp(s, "controller"))
02729     return ROUTER_PURPOSE_CONTROLLER;
02730   else
02731     return ROUTER_PURPOSE_UNKNOWN;
02732 }
02733 
02735 void
02736 router_free_all(void)
02737 {
02738   crypto_pk_free(onionkey);
02739   crypto_pk_free(lastonionkey);
02740   crypto_pk_free(server_identitykey);
02741   crypto_pk_free(client_identitykey);
02742   tor_mutex_free(key_lock);
02743   routerinfo_free(desc_routerinfo);
02744   extrainfo_free(desc_extrainfo);
02745   crypto_pk_free(authority_signing_key);
02746   authority_cert_free(authority_key_certificate);
02747   crypto_pk_free(legacy_signing_key);
02748   authority_cert_free(legacy_key_certificate);
02749 
02750   if (warned_nonexistent_family) {
02751     SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
02752     smartlist_free(warned_nonexistent_family);
02753   }
02754 }
02755