Back to index

tor  0.2.3.19-rc
rendclient.c
Go to the documentation of this file.
00001 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
00002  * Copyright (c) 2007-2012, The Tor Project, Inc. */
00003 /* See LICENSE for licensing information */
00004 
00010 #include "or.h"
00011 #include "circuitbuild.h"
00012 #include "circuitlist.h"
00013 #include "circuituse.h"
00014 #include "config.h"
00015 #include "connection.h"
00016 #include "connection_edge.h"
00017 #include "directory.h"
00018 #include "main.h"
00019 #include "nodelist.h"
00020 #include "relay.h"
00021 #include "rendclient.h"
00022 #include "rendcommon.h"
00023 #include "rephist.h"
00024 #include "router.h"
00025 #include "routerlist.h"
00026 
00027 static extend_info_t *rend_client_get_random_intro_impl(
00028                           const rend_cache_entry_t *rend_query,
00029                           const int strict, const int warnings);
00030 
00033 void
00034 rend_client_purge_state(void)
00035 {
00036   rend_cache_purge();
00037   rend_client_cancel_descriptor_fetches();
00038   rend_client_purge_last_hid_serv_requests();
00039 }
00040 
00043 void
00044 rend_client_introcirc_has_opened(origin_circuit_t *circ)
00045 {
00046   tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
00047   tor_assert(circ->cpath);
00048 
00049   log_info(LD_REND,"introcirc is open");
00050   connection_ap_attach_pending();
00051 }
00052 
00056 static int
00057 rend_client_send_establish_rendezvous(origin_circuit_t *circ)
00058 {
00059   tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND);
00060   tor_assert(circ->rend_data);
00061   log_info(LD_REND, "Sending an ESTABLISH_RENDEZVOUS cell");
00062 
00063   if (crypto_rand(circ->rend_data->rend_cookie, REND_COOKIE_LEN) < 0) {
00064     log_warn(LD_BUG, "Internal error: Couldn't produce random cookie.");
00065     circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL);
00066     return -1;
00067   }
00068   if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
00069                                    RELAY_COMMAND_ESTABLISH_RENDEZVOUS,
00070                                    circ->rend_data->rend_cookie,
00071                                    REND_COOKIE_LEN,
00072                                    circ->cpath->prev)<0) {
00073     /* circ is already marked for close */
00074     log_warn(LD_GENERAL, "Couldn't send ESTABLISH_RENDEZVOUS cell");
00075     return -1;
00076   }
00077 
00078   return 0;
00079 }
00080 
00089 static int
00090 rend_client_reextend_intro_circuit(origin_circuit_t *circ)
00091 {
00092   extend_info_t *extend_info;
00093   int result;
00094   extend_info = rend_client_get_random_intro(circ->rend_data);
00095   if (!extend_info) {
00096     log_warn(LD_REND,
00097              "No usable introduction points left for %s. Closing.",
00098              safe_str_client(circ->rend_data->onion_address));
00099     circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL);
00100     return -1;
00101   }
00102   if (circ->remaining_relay_early_cells) {
00103     log_info(LD_REND,
00104              "Re-extending circ %d, this time to %s.",
00105              circ->_base.n_circ_id,
00106              safe_str_client(extend_info_describe(extend_info)));
00107     result = circuit_extend_to_new_exit(circ, extend_info);
00108   } else {
00109     log_info(LD_REND,
00110              "Closing intro circ %d (out of RELAY_EARLY cells).",
00111              circ->_base.n_circ_id);
00112     circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
00113     /* connection_ap_handshake_attach_circuit will launch a new intro circ. */
00114     result = 0;
00115   }
00116   extend_info_free(extend_info);
00117   return result;
00118 }
00119 
00123 int
00124 rend_client_send_introduction(origin_circuit_t *introcirc,
00125                               origin_circuit_t *rendcirc)
00126 {
00127   size_t payload_len;
00128   int r, v3_shift = 0;
00129   char payload[RELAY_PAYLOAD_SIZE];
00130   char tmp[RELAY_PAYLOAD_SIZE];
00131   rend_cache_entry_t *entry;
00132   crypt_path_t *cpath;
00133   off_t dh_offset;
00134   crypto_pk_t *intro_key = NULL;
00135 
00136   tor_assert(introcirc->_base.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
00137   tor_assert(rendcirc->_base.purpose == CIRCUIT_PURPOSE_C_REND_READY);
00138   tor_assert(introcirc->rend_data);
00139   tor_assert(rendcirc->rend_data);
00140   tor_assert(!rend_cmp_service_ids(introcirc->rend_data->onion_address,
00141                                    rendcirc->rend_data->onion_address));
00142 #ifndef NON_ANONYMOUS_MODE_ENABLED
00143   tor_assert(!(introcirc->build_state->onehop_tunnel));
00144   tor_assert(!(rendcirc->build_state->onehop_tunnel));
00145 #endif
00146 
00147   if (rend_cache_lookup_entry(introcirc->rend_data->onion_address, -1,
00148                               &entry) < 1) {
00149     log_info(LD_REND,
00150              "query %s didn't have valid rend desc in cache. "
00151              "Refetching descriptor.",
00152              safe_str_client(introcirc->rend_data->onion_address));
00153     rend_client_refetch_v2_renddesc(introcirc->rend_data);
00154     {
00155       connection_t *conn;
00156 
00157       while ((conn = connection_get_by_type_state_rendquery(CONN_TYPE_AP,
00158                        AP_CONN_STATE_CIRCUIT_WAIT,
00159                        introcirc->rend_data->onion_address))) {
00160         conn->state = AP_CONN_STATE_RENDDESC_WAIT;
00161       }
00162     }
00163 
00164     return -1;
00165   }
00166 
00167   /* first 20 bytes of payload are the hash of Bob's pk */
00168   intro_key = NULL;
00169   SMARTLIST_FOREACH(entry->parsed->intro_nodes, rend_intro_point_t *,
00170                     intro, {
00171     if (tor_memeq(introcirc->build_state->chosen_exit->identity_digest,
00172                 intro->extend_info->identity_digest, DIGEST_LEN)) {
00173       intro_key = intro->intro_key;
00174       break;
00175     }
00176   });
00177   if (!intro_key) {
00178     log_info(LD_REND, "Could not find intro key for %s at %s; we "
00179              "have a v2 rend desc with %d intro points. "
00180              "Trying a different intro point...",
00181              safe_str_client(introcirc->rend_data->onion_address),
00182              safe_str_client(extend_info_describe(
00183                                    introcirc->build_state->chosen_exit)),
00184              smartlist_len(entry->parsed->intro_nodes));
00185 
00186     if (rend_client_reextend_intro_circuit(introcirc)) {
00187       goto perm_err;
00188     } else {
00189       return -1;
00190     }
00191   }
00192   if (crypto_pk_get_digest(intro_key, payload)<0) {
00193     log_warn(LD_BUG, "Internal error: couldn't hash public key.");
00194     goto perm_err;
00195   }
00196 
00197   /* Initialize the pending_final_cpath and start the DH handshake. */
00198   cpath = rendcirc->build_state->pending_final_cpath;
00199   if (!cpath) {
00200     cpath = rendcirc->build_state->pending_final_cpath =
00201       tor_malloc_zero(sizeof(crypt_path_t));
00202     cpath->magic = CRYPT_PATH_MAGIC;
00203     if (!(cpath->dh_handshake_state = crypto_dh_new(DH_TYPE_REND))) {
00204       log_warn(LD_BUG, "Internal error: couldn't allocate DH.");
00205       goto perm_err;
00206     }
00207     if (crypto_dh_generate_public(cpath->dh_handshake_state)<0) {
00208       log_warn(LD_BUG, "Internal error: couldn't generate g^x.");
00209       goto perm_err;
00210     }
00211   }
00212 
00213   /* If version is 3, write (optional) auth data and timestamp. */
00214   if (entry->parsed->protocols & (1<<3)) {
00215     tmp[0] = 3; /* version 3 of the cell format */
00216     tmp[1] = (uint8_t)introcirc->rend_data->auth_type; /* auth type, if any */
00217     v3_shift = 1;
00218     if (introcirc->rend_data->auth_type != REND_NO_AUTH) {
00219       set_uint16(tmp+2, htons(REND_DESC_COOKIE_LEN));
00220       memcpy(tmp+4, introcirc->rend_data->descriptor_cookie,
00221              REND_DESC_COOKIE_LEN);
00222       v3_shift += 2+REND_DESC_COOKIE_LEN;
00223     }
00224     set_uint32(tmp+v3_shift+1, htonl((uint32_t)time(NULL)));
00225     v3_shift += 4;
00226   } /* if version 2 only write version number */
00227   else if (entry->parsed->protocols & (1<<2)) {
00228     tmp[0] = 2; /* version 2 of the cell format */
00229   }
00230 
00231   /* write the remaining items into tmp */
00232   if (entry->parsed->protocols & (1<<3) || entry->parsed->protocols & (1<<2)) {
00233     /* version 2 format */
00234     extend_info_t *extend_info = rendcirc->build_state->chosen_exit;
00235     int klen;
00236     /* nul pads */
00237     set_uint32(tmp+v3_shift+1, tor_addr_to_ipv4h(&extend_info->addr));
00238     set_uint16(tmp+v3_shift+5, htons(extend_info->port));
00239     memcpy(tmp+v3_shift+7, extend_info->identity_digest, DIGEST_LEN);
00240     klen = crypto_pk_asn1_encode(extend_info->onion_key,
00241                                  tmp+v3_shift+7+DIGEST_LEN+2,
00242                                  sizeof(tmp)-(v3_shift+7+DIGEST_LEN+2));
00243     set_uint16(tmp+v3_shift+7+DIGEST_LEN, htons(klen));
00244     memcpy(tmp+v3_shift+7+DIGEST_LEN+2+klen, rendcirc->rend_data->rend_cookie,
00245            REND_COOKIE_LEN);
00246     dh_offset = v3_shift+7+DIGEST_LEN+2+klen+REND_COOKIE_LEN;
00247   } else {
00248     /* Version 0. */
00249     strncpy(tmp, rendcirc->build_state->chosen_exit->nickname,
00250             (MAX_NICKNAME_LEN+1)); /* nul pads */
00251     memcpy(tmp+MAX_NICKNAME_LEN+1, rendcirc->rend_data->rend_cookie,
00252            REND_COOKIE_LEN);
00253     dh_offset = MAX_NICKNAME_LEN+1+REND_COOKIE_LEN;
00254   }
00255 
00256   if (crypto_dh_get_public(cpath->dh_handshake_state, tmp+dh_offset,
00257                            DH_KEY_LEN)<0) {
00258     log_warn(LD_BUG, "Internal error: couldn't extract g^x.");
00259     goto perm_err;
00260   }
00261 
00262   note_crypto_pk_op(REND_CLIENT);
00263   /*XXX maybe give crypto_pk_public_hybrid_encrypt a max_len arg,
00264    * to avoid buffer overflows? */
00265   r = crypto_pk_public_hybrid_encrypt(intro_key, payload+DIGEST_LEN,
00266                                       sizeof(payload)-DIGEST_LEN,
00267                                       tmp,
00268                                       (int)(dh_offset+DH_KEY_LEN),
00269                                       PK_PKCS1_OAEP_PADDING, 0);
00270   if (r<0) {
00271     log_warn(LD_BUG,"Internal error: hybrid pk encrypt failed.");
00272     goto perm_err;
00273   }
00274 
00275   payload_len = DIGEST_LEN + r;
00276   tor_assert(payload_len <= RELAY_PAYLOAD_SIZE); /* we overran something */
00277 
00278   /* Copy the rendezvous cookie from rendcirc to introcirc, so that
00279    * when introcirc gets an ack, we can change the state of the right
00280    * rendezvous circuit. */
00281   memcpy(introcirc->rend_data->rend_cookie, rendcirc->rend_data->rend_cookie,
00282          REND_COOKIE_LEN);
00283 
00284   log_info(LD_REND, "Sending an INTRODUCE1 cell");
00285   if (relay_send_command_from_edge(0, TO_CIRCUIT(introcirc),
00286                                    RELAY_COMMAND_INTRODUCE1,
00287                                    payload, payload_len,
00288                                    introcirc->cpath->prev)<0) {
00289     /* introcirc is already marked for close. leave rendcirc alone. */
00290     log_warn(LD_BUG, "Couldn't send INTRODUCE1 cell");
00291     return -2;
00292   }
00293 
00294   /* Now, we wait for an ACK or NAK on this circuit. */
00295   circuit_change_purpose(TO_CIRCUIT(introcirc),
00296                          CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT);
00297   /* Set timestamp_dirty, because circuit_expire_building expects it
00298    * to specify when a circuit entered the _C_INTRODUCE_ACK_WAIT
00299    * state. */
00300   introcirc->_base.timestamp_dirty = time(NULL);
00301 
00302   return 0;
00303  perm_err:
00304   if (!introcirc->_base.marked_for_close)
00305     circuit_mark_for_close(TO_CIRCUIT(introcirc), END_CIRC_REASON_INTERNAL);
00306   circuit_mark_for_close(TO_CIRCUIT(rendcirc), END_CIRC_REASON_INTERNAL);
00307   return -2;
00308 }
00309 
00312 void
00313 rend_client_rendcirc_has_opened(origin_circuit_t *circ)
00314 {
00315   tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND);
00316 
00317   log_info(LD_REND,"rendcirc is open");
00318 
00319   /* generate a rendezvous cookie, store it in circ */
00320   if (rend_client_send_establish_rendezvous(circ) < 0) {
00321     return;
00322   }
00323 }
00324 
00327 int
00328 rend_client_introduction_acked(origin_circuit_t *circ,
00329                                const uint8_t *request, size_t request_len)
00330 {
00331   origin_circuit_t *rendcirc;
00332   (void) request; // XXXX Use this.
00333 
00334   if (circ->_base.purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
00335     log_warn(LD_PROTOCOL,
00336              "Received REND_INTRODUCE_ACK on unexpected circuit %d.",
00337              circ->_base.n_circ_id);
00338     circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
00339     return -1;
00340   }
00341 
00342   tor_assert(circ->build_state->chosen_exit);
00343 #ifndef NON_ANONYMOUS_MODE_ENABLED
00344   tor_assert(!(circ->build_state->onehop_tunnel));
00345 #endif
00346   tor_assert(circ->rend_data);
00347 
00348   if (request_len == 0) {
00349     /* It's an ACK; the introduction point relayed our introduction request. */
00350     /* Locate the rend circ which is waiting to hear about this ack,
00351      * and tell it.
00352      */
00353     log_info(LD_REND,"Received ack. Telling rend circ...");
00354     rendcirc = circuit_get_ready_rend_circ_by_rend_data(circ->rend_data);
00355     if (rendcirc) { /* remember the ack */
00356 #ifndef NON_ANONYMOUS_MODE_ENABLED
00357       tor_assert(!(rendcirc->build_state->onehop_tunnel));
00358 #endif
00359       circuit_change_purpose(TO_CIRCUIT(rendcirc),
00360                              CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED);
00361       /* Set timestamp_dirty, because circuit_expire_building expects
00362        * it to specify when a circuit entered the
00363        * _C_REND_READY_INTRO_ACKED state. */
00364       rendcirc->_base.timestamp_dirty = time(NULL);
00365     } else {
00366       log_info(LD_REND,"...Found no rend circ. Dropping on the floor.");
00367     }
00368     /* close the circuit: we won't need it anymore. */
00369     circuit_change_purpose(TO_CIRCUIT(circ),
00370                            CIRCUIT_PURPOSE_C_INTRODUCE_ACKED);
00371     circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
00372   } else {
00373     /* It's a NAK; the introduction point didn't relay our request. */
00374     circuit_change_purpose(TO_CIRCUIT(circ), CIRCUIT_PURPOSE_C_INTRODUCING);
00375     /* Remove this intro point from the set of viable introduction
00376      * points. If any remain, extend to a new one and try again.
00377      * If none remain, refetch the service descriptor.
00378      */
00379     log_info(LD_REND, "Got nack for %s from %s...",
00380         safe_str_client(circ->rend_data->onion_address),
00381         safe_str_client(extend_info_describe(circ->build_state->chosen_exit)));
00382     if (rend_client_report_intro_point_failure(circ->build_state->chosen_exit,
00383                                              circ->rend_data,
00384                                              INTRO_POINT_FAILURE_GENERIC)>0) {
00385       /* There are introduction points left. Re-extend the circuit to
00386        * another intro point and try again. */
00387       int result = rend_client_reextend_intro_circuit(circ);
00388       /* XXXX If that call failed, should we close the rend circuit,
00389        * too? */
00390       return result;
00391     }
00392   }
00393   return 0;
00394 }
00395 
00398 #define REND_HID_SERV_DIR_REQUERY_PERIOD (15 * 60)
00399 
00407 static strmap_t *last_hid_serv_requests_ = NULL;
00408 
00411 static strmap_t *
00412 get_last_hid_serv_requests(void)
00413 {
00414   if (!last_hid_serv_requests_)
00415     last_hid_serv_requests_ = strmap_new();
00416   return last_hid_serv_requests_;
00417 }
00418 
00419 #define LAST_HID_SERV_REQUEST_KEY_LEN (REND_DESC_ID_V2_LEN_BASE32 + \
00420                                        REND_DESC_ID_V2_LEN_BASE32 + \
00421                                        REND_SERVICE_ID_LEN_BASE32)
00422 
00429 static time_t
00430 lookup_last_hid_serv_request(routerstatus_t *hs_dir,
00431                              const char *desc_id_base32,
00432                              const rend_data_t *rend_query,
00433                              time_t now, int set)
00434 {
00435   char hsdir_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
00436   char hsdir_desc_comb_id[LAST_HID_SERV_REQUEST_KEY_LEN + 1];
00437   time_t *last_request_ptr;
00438   strmap_t *last_hid_serv_requests = get_last_hid_serv_requests();
00439   base32_encode(hsdir_id_base32, sizeof(hsdir_id_base32),
00440                 hs_dir->identity_digest, DIGEST_LEN);
00441   tor_snprintf(hsdir_desc_comb_id, sizeof(hsdir_desc_comb_id), "%s%s%s",
00442                hsdir_id_base32,
00443                desc_id_base32,
00444                rend_query->onion_address);
00445   /* XXX023 tor_assert(strlen(hsdir_desc_comb_id) ==
00446                        LAST_HID_SERV_REQUEST_KEY_LEN); */
00447   if (set) {
00448     time_t *oldptr;
00449     last_request_ptr = tor_malloc_zero(sizeof(time_t));
00450     *last_request_ptr = now;
00451     oldptr = strmap_set(last_hid_serv_requests, hsdir_desc_comb_id,
00452                         last_request_ptr);
00453     tor_free(oldptr);
00454   } else
00455     last_request_ptr = strmap_get_lc(last_hid_serv_requests,
00456                                      hsdir_desc_comb_id);
00457   return (last_request_ptr) ? *last_request_ptr : 0;
00458 }
00459 
00463 static void
00464 directory_clean_last_hid_serv_requests(time_t now)
00465 {
00466   strmap_iter_t *iter;
00467   time_t cutoff = now - REND_HID_SERV_DIR_REQUERY_PERIOD;
00468   strmap_t *last_hid_serv_requests = get_last_hid_serv_requests();
00469   for (iter = strmap_iter_init(last_hid_serv_requests);
00470        !strmap_iter_done(iter); ) {
00471     const char *key;
00472     void *val;
00473     time_t *ent;
00474     strmap_iter_get(iter, &key, &val);
00475     ent = (time_t *) val;
00476     if (*ent < cutoff) {
00477       iter = strmap_iter_next_rmv(last_hid_serv_requests, iter);
00478       tor_free(ent);
00479     } else {
00480       iter = strmap_iter_next(last_hid_serv_requests, iter);
00481     }
00482   }
00483 }
00484 
00488 static void
00489 purge_hid_serv_from_last_hid_serv_requests(const char *onion_address)
00490 {
00491   strmap_iter_t *iter;
00492   strmap_t *last_hid_serv_requests = get_last_hid_serv_requests();
00493   /* XXX023 tor_assert(strlen(onion_address) == REND_SERVICE_ID_LEN_BASE32); */
00494   for (iter = strmap_iter_init(last_hid_serv_requests);
00495        !strmap_iter_done(iter); ) {
00496     const char *key;
00497     void *val;
00498     strmap_iter_get(iter, &key, &val);
00499     /* XXX023 tor_assert(strlen(key) == LAST_HID_SERV_REQUEST_KEY_LEN); */
00500     if (tor_memeq(key + LAST_HID_SERV_REQUEST_KEY_LEN -
00501                   REND_SERVICE_ID_LEN_BASE32,
00502                   onion_address,
00503                   REND_SERVICE_ID_LEN_BASE32)) {
00504       iter = strmap_iter_next_rmv(last_hid_serv_requests, iter);
00505       tor_free(val);
00506     } else {
00507       iter = strmap_iter_next(last_hid_serv_requests, iter);
00508     }
00509   }
00510 }
00511 
00516 void
00517 rend_client_purge_last_hid_serv_requests(void)
00518 {
00519   /* Don't create the table if it doesn't exist yet (and it may very
00520    * well not exist if the user hasn't accessed any HSes)... */
00521   strmap_t *old_last_hid_serv_requests = last_hid_serv_requests_;
00522   /* ... and let get_last_hid_serv_requests re-create it for us if
00523    * necessary. */
00524   last_hid_serv_requests_ = NULL;
00525 
00526   if (old_last_hid_serv_requests != NULL) {
00527     log_info(LD_REND, "Purging client last-HS-desc-request-time table");
00528     strmap_free(old_last_hid_serv_requests, _tor_free);
00529   }
00530 }
00531 
00538 static int
00539 directory_get_from_hs_dir(const char *desc_id, const rend_data_t *rend_query)
00540 {
00541   smartlist_t *responsible_dirs = smartlist_new();
00542   routerstatus_t *hs_dir;
00543   char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
00544   time_t now = time(NULL);
00545   char descriptor_cookie_base64[3*REND_DESC_COOKIE_LEN_BASE64];
00546   int tor2web_mode = get_options()->Tor2webMode;
00547   tor_assert(desc_id);
00548   tor_assert(rend_query);
00549   /* Determine responsible dirs. Even if we can't get all we want,
00550    * work with the ones we have. If it's empty, we'll notice below. */
00551   hid_serv_get_responsible_directories(responsible_dirs, desc_id);
00552 
00553   base32_encode(desc_id_base32, sizeof(desc_id_base32),
00554                 desc_id, DIGEST_LEN);
00555 
00556   /* Only select those hidden service directories to which we did not send
00557    * a request recently and for which we have a router descriptor here. */
00558 
00559   /* Clean request history first. */
00560   directory_clean_last_hid_serv_requests(now);
00561 
00562   SMARTLIST_FOREACH(responsible_dirs, routerstatus_t *, dir, {
00563       time_t last = lookup_last_hid_serv_request(
00564                             dir, desc_id_base32, rend_query, 0, 0);
00565       const node_t *node = node_get_by_id(dir->identity_digest);
00566       if (last + REND_HID_SERV_DIR_REQUERY_PERIOD >= now ||
00567           !node || !node_has_descriptor(node))
00568       SMARTLIST_DEL_CURRENT(responsible_dirs, dir);
00569   });
00570 
00571   hs_dir = smartlist_choose(responsible_dirs);
00572   smartlist_free(responsible_dirs);
00573   if (!hs_dir) {
00574     log_info(LD_REND, "Could not pick one of the responsible hidden "
00575                       "service directories, because we requested them all "
00576                       "recently without success.");
00577     return 0;
00578   }
00579 
00580   /* Remember that we are requesting a descriptor from this hidden service
00581    * directory now. */
00582   lookup_last_hid_serv_request(hs_dir, desc_id_base32, rend_query, now, 1);
00583 
00584   /* Encode descriptor cookie for logging purposes. */
00585   if (rend_query->auth_type != REND_NO_AUTH) {
00586     if (base64_encode(descriptor_cookie_base64,
00587                       sizeof(descriptor_cookie_base64),
00588                       rend_query->descriptor_cookie, REND_DESC_COOKIE_LEN)<0) {
00589       log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
00590       return 0;
00591     }
00592     /* Remove == signs and newline. */
00593     descriptor_cookie_base64[strlen(descriptor_cookie_base64)-3] = '\0';
00594   } else {
00595     strlcpy(descriptor_cookie_base64, "(none)",
00596             sizeof(descriptor_cookie_base64));
00597   }
00598 
00599   /* Send fetch request. (Pass query and possibly descriptor cookie so that
00600    * they can be written to the directory connection and be referred to when
00601    * the response arrives. */
00602   directory_initiate_command_routerstatus_rend(hs_dir,
00603                                           DIR_PURPOSE_FETCH_RENDDESC_V2,
00604                                           ROUTER_PURPOSE_GENERAL,
00605                                           !tor2web_mode, desc_id_base32,
00606                                           NULL, 0, 0,
00607                                           rend_query);
00608   log_info(LD_REND, "Sending fetch request for v2 descriptor for "
00609                     "service '%s' with descriptor ID '%s', auth type %d, "
00610                     "and descriptor cookie '%s' to hidden service "
00611                     "directory %s",
00612            rend_query->onion_address, desc_id_base32,
00613            rend_query->auth_type,
00614            (rend_query->auth_type == REND_NO_AUTH ? "[none]" :
00615             escaped_safe_str_client(descriptor_cookie_base64)),
00616            routerstatus_describe(hs_dir));
00617   return 1;
00618 }
00619 
00623 void
00624 rend_client_refetch_v2_renddesc(const rend_data_t *rend_query)
00625 {
00626   char descriptor_id[DIGEST_LEN];
00627   int replicas_left_to_try[REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS];
00628   int i, tries_left;
00629   rend_cache_entry_t *e = NULL;
00630   tor_assert(rend_query);
00631   /* Are we configured to fetch descriptors? */
00632   if (!get_options()->FetchHidServDescriptors) {
00633     log_warn(LD_REND, "We received an onion address for a v2 rendezvous "
00634         "service descriptor, but are not fetching service descriptors.");
00635     return;
00636   }
00637   /* Before fetching, check if we already have a usable descriptor here. */
00638   if (rend_cache_lookup_entry(rend_query->onion_address, -1, &e) > 0 &&
00639       rend_client_any_intro_points_usable(e)) {
00640     log_info(LD_REND, "We would fetch a v2 rendezvous descriptor, but we "
00641                       "already have a usable descriptor here. Not fetching.");
00642     return;
00643   }
00644   log_debug(LD_REND, "Fetching v2 rendezvous descriptor for service %s",
00645             safe_str_client(rend_query->onion_address));
00646   /* Randomly iterate over the replicas until a descriptor can be fetched
00647    * from one of the consecutive nodes, or no options are left. */
00648   tries_left = REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS;
00649   for (i = 0; i < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS; i++)
00650     replicas_left_to_try[i] = i;
00651   while (tries_left > 0) {
00652     int rand = crypto_rand_int(tries_left);
00653     int chosen_replica = replicas_left_to_try[rand];
00654     replicas_left_to_try[rand] = replicas_left_to_try[--tries_left];
00655 
00656     if (rend_compute_v2_desc_id(descriptor_id, rend_query->onion_address,
00657                                 rend_query->auth_type == REND_STEALTH_AUTH ?
00658                                     rend_query->descriptor_cookie : NULL,
00659                                 time(NULL), chosen_replica) < 0) {
00660       log_warn(LD_REND, "Internal error: Computing v2 rendezvous "
00661                         "descriptor ID did not succeed.");
00662       return;
00663     }
00664     if (directory_get_from_hs_dir(descriptor_id, rend_query) != 0)
00665       return; /* either success or failure, but we're done */
00666   }
00667   /* If we come here, there are no hidden service directories left. */
00668   log_info(LD_REND, "Could not pick one of the responsible hidden "
00669                     "service directories to fetch descriptors, because "
00670                     "we already tried them all unsuccessfully.");
00671   /* Close pending connections. */
00672   rend_client_desc_trynow(rend_query->onion_address);
00673   return;
00674 }
00675 
00678 void
00679 rend_client_cancel_descriptor_fetches(void)
00680 {
00681   smartlist_t *connection_array = get_connection_array();
00682 
00683   SMARTLIST_FOREACH_BEGIN(connection_array, connection_t *, conn) {
00684     if (conn->type == CONN_TYPE_DIR &&
00685         (conn->purpose == DIR_PURPOSE_FETCH_RENDDESC ||
00686          conn->purpose == DIR_PURPOSE_FETCH_RENDDESC_V2)) {
00687       /* It's a rendezvous descriptor fetch in progress -- cancel it
00688        * by marking the connection for close.
00689        *
00690        * Even if this connection has already reached EOF, this is
00691        * enough to make sure that if the descriptor hasn't been
00692        * processed yet, it won't be.  See the end of
00693        * connection_handle_read; connection_reached_eof (indirectly)
00694        * processes whatever response the connection received. */
00695 
00696       const rend_data_t *rd = (TO_DIR_CONN(conn))->rend_data;
00697       if (!rd) {
00698         log_warn(LD_BUG | LD_REND,
00699                  "Marking for close dir conn fetching rendezvous "
00700                  "descriptor for unknown service!");
00701       } else {
00702         log_debug(LD_REND, "Marking for close dir conn fetching "
00703                   "rendezvous descriptor for service %s",
00704                   safe_str(rd->onion_address));
00705       }
00706       connection_mark_for_close(conn);
00707     }
00708   } SMARTLIST_FOREACH_END(conn);
00709 }
00710 
00732 int
00733 rend_client_report_intro_point_failure(extend_info_t *failed_intro,
00734                                        const rend_data_t *rend_query,
00735                                        unsigned int failure_type)
00736 {
00737   int i, r;
00738   rend_cache_entry_t *ent;
00739   connection_t *conn;
00740 
00741   r = rend_cache_lookup_entry(rend_query->onion_address, -1, &ent);
00742   if (r<0) {
00743     log_warn(LD_BUG, "Malformed service ID %s.",
00744              escaped_safe_str_client(rend_query->onion_address));
00745     return -1;
00746   }
00747   if (r==0) {
00748     log_info(LD_REND, "Unknown service %s. Re-fetching descriptor.",
00749              escaped_safe_str_client(rend_query->onion_address));
00750     rend_client_refetch_v2_renddesc(rend_query);
00751     return 0;
00752   }
00753 
00754   for (i = 0; i < smartlist_len(ent->parsed->intro_nodes); i++) {
00755     rend_intro_point_t *intro = smartlist_get(ent->parsed->intro_nodes, i);
00756     if (tor_memeq(failed_intro->identity_digest,
00757                 intro->extend_info->identity_digest, DIGEST_LEN)) {
00758       switch (failure_type) {
00759       default:
00760         log_warn(LD_BUG, "Unknown failure type %u. Removing intro point.",
00761                  failure_type);
00762         tor_fragile_assert();
00763         /* fall through */
00764       case INTRO_POINT_FAILURE_GENERIC:
00765         rend_intro_point_free(intro);
00766         smartlist_del(ent->parsed->intro_nodes, i);
00767         break;
00768       case INTRO_POINT_FAILURE_TIMEOUT:
00769         intro->timed_out = 1;
00770         break;
00771       case INTRO_POINT_FAILURE_UNREACHABLE:
00772         ++(intro->unreachable_count);
00773         {
00774           int zap_intro_point =
00775             intro->unreachable_count >= MAX_INTRO_POINT_REACHABILITY_FAILURES;
00776           log_info(LD_REND, "Failed to reach this intro point %u times.%s",
00777                    intro->unreachable_count,
00778                    zap_intro_point ? " Removing from descriptor.": "");
00779           if (zap_intro_point) {
00780             rend_intro_point_free(intro);
00781             smartlist_del(ent->parsed->intro_nodes, i);
00782           }
00783         }
00784         break;
00785       }
00786       break;
00787     }
00788   }
00789 
00790   if (! rend_client_any_intro_points_usable(ent)) {
00791     log_info(LD_REND,
00792              "No more intro points remain for %s. Re-fetching descriptor.",
00793              escaped_safe_str_client(rend_query->onion_address));
00794     rend_client_refetch_v2_renddesc(rend_query);
00795 
00796     /* move all pending streams back to renddesc_wait */
00797     while ((conn = connection_get_by_type_state_rendquery(CONN_TYPE_AP,
00798                                    AP_CONN_STATE_CIRCUIT_WAIT,
00799                                    rend_query->onion_address))) {
00800       conn->state = AP_CONN_STATE_RENDDESC_WAIT;
00801     }
00802 
00803     return 0;
00804   }
00805   log_info(LD_REND,"%d options left for %s.",
00806            smartlist_len(ent->parsed->intro_nodes),
00807            escaped_safe_str_client(rend_query->onion_address));
00808   return 1;
00809 }
00810 
00814 int
00815 rend_client_rendezvous_acked(origin_circuit_t *circ, const uint8_t *request,
00816                              size_t request_len)
00817 {
00818   (void) request;
00819   (void) request_len;
00820   /* we just got an ack for our establish-rendezvous. switch purposes. */
00821   if (circ->_base.purpose != CIRCUIT_PURPOSE_C_ESTABLISH_REND) {
00822     log_warn(LD_PROTOCOL,"Got a rendezvous ack when we weren't expecting one. "
00823              "Closing circ.");
00824     circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
00825     return -1;
00826   }
00827   log_info(LD_REND,"Got rendezvous ack. This circuit is now ready for "
00828            "rendezvous.");
00829   circuit_change_purpose(TO_CIRCUIT(circ), CIRCUIT_PURPOSE_C_REND_READY);
00830   /* Set timestamp_dirty, because circuit_expire_building expects it
00831    * to specify when a circuit entered the _C_REND_READY state. */
00832   circ->_base.timestamp_dirty = time(NULL);
00833   /* XXXX This is a pretty brute-force approach. It'd be better to
00834    * attach only the connections that are waiting on this circuit, rather
00835    * than trying to attach them all. See comments bug 743. */
00836   /* If we already have the introduction circuit built, make sure we send
00837    * the INTRODUCE cell _now_ */
00838   connection_ap_attach_pending();
00839   return 0;
00840 }
00841 
00843 int
00844 rend_client_receive_rendezvous(origin_circuit_t *circ, const uint8_t *request,
00845                                size_t request_len)
00846 {
00847   crypt_path_t *hop;
00848   char keys[DIGEST_LEN+CPATH_KEY_MATERIAL_LEN];
00849 
00850   if ((circ->_base.purpose != CIRCUIT_PURPOSE_C_REND_READY &&
00851        circ->_base.purpose != CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED)
00852       || !circ->build_state->pending_final_cpath) {
00853     log_warn(LD_PROTOCOL,"Got rendezvous2 cell from hidden service, but not "
00854              "expecting it. Closing.");
00855     circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
00856     return -1;
00857   }
00858 
00859   if (request_len != DH_KEY_LEN+DIGEST_LEN) {
00860     log_warn(LD_PROTOCOL,"Incorrect length (%d) on RENDEZVOUS2 cell.",
00861              (int)request_len);
00862     goto err;
00863   }
00864 
00865   log_info(LD_REND,"Got RENDEZVOUS2 cell from hidden service.");
00866 
00867   /* first DH_KEY_LEN bytes are g^y from bob. Finish the dh handshake...*/
00868   tor_assert(circ->build_state);
00869   tor_assert(circ->build_state->pending_final_cpath);
00870   hop = circ->build_state->pending_final_cpath;
00871   tor_assert(hop->dh_handshake_state);
00872   if (crypto_dh_compute_secret(LOG_PROTOCOL_WARN,
00873                                hop->dh_handshake_state, (char*)request,
00874                                DH_KEY_LEN,
00875                                keys, DIGEST_LEN+CPATH_KEY_MATERIAL_LEN)<0) {
00876     log_warn(LD_GENERAL, "Couldn't complete DH handshake.");
00877     goto err;
00878   }
00879   /* ... and set up cpath. */
00880   if (circuit_init_cpath_crypto(hop, keys+DIGEST_LEN, 0)<0)
00881     goto err;
00882 
00883   /* Check whether the digest is right... */
00884   if (tor_memneq(keys, request+DH_KEY_LEN, DIGEST_LEN)) {
00885     log_warn(LD_PROTOCOL, "Incorrect digest of key material.");
00886     goto err;
00887   }
00888 
00889   crypto_dh_free(hop->dh_handshake_state);
00890   hop->dh_handshake_state = NULL;
00891 
00892   /* All is well. Extend the circuit. */
00893   circuit_change_purpose(TO_CIRCUIT(circ), CIRCUIT_PURPOSE_C_REND_JOINED);
00894   hop->state = CPATH_STATE_OPEN;
00895   /* set the windows to default. these are the windows
00896    * that alice thinks bob has.
00897    */
00898   hop->package_window = circuit_initial_package_window();
00899   hop->deliver_window = CIRCWINDOW_START;
00900 
00901   /* Now that this circuit has finished connecting to its destination,
00902    * make sure circuit_get_open_circ_or_launch is willing to return it
00903    * so we can actually use it. */
00904   circ->hs_circ_has_timed_out = 0;
00905 
00906   onion_append_to_cpath(&circ->cpath, hop);
00907   circ->build_state->pending_final_cpath = NULL; /* prevent double-free */
00908 
00909   circuit_try_attaching_streams(circ);
00910 
00911   memset(keys, 0, sizeof(keys));
00912   return 0;
00913  err:
00914   memset(keys, 0, sizeof(keys));
00915   circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
00916   return -1;
00917 }
00918 
00922 void
00923 rend_client_desc_trynow(const char *query)
00924 {
00925   entry_connection_t *conn;
00926   rend_cache_entry_t *entry;
00927   const rend_data_t *rend_data;
00928   time_t now = time(NULL);
00929 
00930   smartlist_t *conns = get_connection_array();
00931   SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
00932     if (base_conn->type != CONN_TYPE_AP ||
00933         base_conn->state != AP_CONN_STATE_RENDDESC_WAIT ||
00934         base_conn->marked_for_close)
00935       continue;
00936     conn = TO_ENTRY_CONN(base_conn);
00937     rend_data = ENTRY_TO_EDGE_CONN(conn)->rend_data;
00938     if (!rend_data)
00939       continue;
00940     if (rend_cmp_service_ids(query, rend_data->onion_address))
00941       continue;
00942     assert_connection_ok(base_conn, now);
00943     if (rend_cache_lookup_entry(rend_data->onion_address, -1,
00944                                 &entry) == 1 &&
00945         rend_client_any_intro_points_usable(entry)) {
00946       /* either this fetch worked, or it failed but there was a
00947        * valid entry from before which we should reuse */
00948       log_info(LD_REND,"Rend desc is usable. Launching circuits.");
00949       base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
00950 
00951       /* restart their timeout values, so they get a fair shake at
00952        * connecting to the hidden service. */
00953       base_conn->timestamp_created = now;
00954       base_conn->timestamp_lastread = now;
00955       base_conn->timestamp_lastwritten = now;
00956 
00957       if (connection_ap_handshake_attach_circuit(conn) < 0) {
00958         /* it will never work */
00959         log_warn(LD_REND,"Rendezvous attempt failed. Closing.");
00960         if (!base_conn->marked_for_close)
00961           connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
00962       }
00963     } else { /* 404, or fetch didn't get that far */
00964       log_notice(LD_REND,"Closing stream for '%s.onion': hidden service is "
00965                  "unavailable (try again later).",
00966                  safe_str_client(query));
00967       connection_mark_unattached_ap(conn, END_STREAM_REASON_RESOLVEFAILED);
00968       rend_client_note_connection_attempt_ended(query);
00969     }
00970   } SMARTLIST_FOREACH_END(base_conn);
00971 }
00972 
00977 void
00978 rend_client_note_connection_attempt_ended(const char *onion_address)
00979 {
00980   rend_cache_entry_t *cache_entry = NULL;
00981   rend_cache_lookup_entry(onion_address, -1, &cache_entry);
00982 
00983   log_info(LD_REND, "Connection attempt for %s has ended; "
00984            "cleaning up temporary state.",
00985            safe_str_client(onion_address));
00986 
00987   /* Clear the timed_out flag on all remaining intro points for this HS. */
00988   if (cache_entry != NULL) {
00989     SMARTLIST_FOREACH(cache_entry->parsed->intro_nodes,
00990                       rend_intro_point_t *, ip,
00991                       ip->timed_out = 0; );
00992   }
00993 
00994   /* Remove the HS's entries in last_hid_serv_requests. */
00995   purge_hid_serv_from_last_hid_serv_requests(onion_address);
00996 }
00997 
01002 extend_info_t *
01003 rend_client_get_random_intro(const rend_data_t *rend_query)
01004 {
01005   extend_info_t *result;
01006   rend_cache_entry_t *entry;
01007 
01008   if (rend_cache_lookup_entry(rend_query->onion_address, -1, &entry) < 1) {
01009       log_warn(LD_REND,
01010                "Query '%s' didn't have valid rend desc in cache. Failing.",
01011                safe_str_client(rend_query->onion_address));
01012     return NULL;
01013   }
01014 
01015   /* See if we can get a node that complies with ExcludeNodes */
01016   if ((result = rend_client_get_random_intro_impl(entry, 1, 1)))
01017     return result;
01018   /* If not, and StrictNodes is not set, see if we can return any old node
01019    */
01020   if (!get_options()->StrictNodes)
01021     return rend_client_get_random_intro_impl(entry, 0, 1);
01022   return NULL;
01023 }
01024 
01029 static extend_info_t *
01030 rend_client_get_random_intro_impl(const rend_cache_entry_t *entry,
01031                                   const int strict,
01032                                   const int warnings)
01033 {
01034   int i;
01035 
01036   rend_intro_point_t *intro;
01037   const or_options_t *options = get_options();
01038   smartlist_t *usable_nodes;
01039   int n_excluded = 0;
01040 
01041   /* We'll keep a separate list of the usable nodes.  If this becomes empty,
01042    * no nodes are usable.  */
01043   usable_nodes = smartlist_new();
01044   smartlist_add_all(usable_nodes, entry->parsed->intro_nodes);
01045 
01046   /* Remove the intro points that have timed out during this HS
01047    * connection attempt from our list of usable nodes. */
01048   SMARTLIST_FOREACH(usable_nodes, rend_intro_point_t *, ip,
01049                     if (ip->timed_out) {
01050                       SMARTLIST_DEL_CURRENT(usable_nodes, ip);
01051                     });
01052 
01053  again:
01054   if (smartlist_len(usable_nodes) == 0) {
01055     if (n_excluded && get_options()->StrictNodes && warnings) {
01056       /* We only want to warn if StrictNodes is really set. Otherwise
01057        * we're just about to retry anyways.
01058        */
01059       log_warn(LD_REND, "All introduction points for hidden service are "
01060                "at excluded relays, and StrictNodes is set. Skipping.");
01061     }
01062     smartlist_free(usable_nodes);
01063     return NULL;
01064   }
01065 
01066   i = crypto_rand_int(smartlist_len(usable_nodes));
01067   intro = smartlist_get(usable_nodes, i);
01068   /* Do we need to look up the router or is the extend info complete? */
01069   if (!intro->extend_info->onion_key) {
01070     const node_t *node;
01071     extend_info_t *new_extend_info;
01072     if (tor_digest_is_zero(intro->extend_info->identity_digest))
01073       node = node_get_by_hex_id(intro->extend_info->nickname);
01074     else
01075       node = node_get_by_id(intro->extend_info->identity_digest);
01076     if (!node) {
01077       log_info(LD_REND, "Unknown router with nickname '%s'; trying another.",
01078                intro->extend_info->nickname);
01079       smartlist_del(usable_nodes, i);
01080       goto again;
01081     }
01082     new_extend_info = extend_info_from_node(node, 0);
01083     if (!new_extend_info) {
01084       log_info(LD_REND, "We don't have a descriptor for the intro-point relay "
01085                "'%s'; trying another.",
01086                extend_info_describe(intro->extend_info));
01087       smartlist_del(usable_nodes, i);
01088       goto again;
01089     } else {
01090       extend_info_free(intro->extend_info);
01091       intro->extend_info = new_extend_info;
01092     }
01093     tor_assert(intro->extend_info != NULL);
01094   }
01095   /* Check if we should refuse to talk to this router. */
01096   if (strict &&
01097       routerset_contains_extendinfo(options->ExcludeNodes,
01098                                     intro->extend_info)) {
01099     n_excluded++;
01100     smartlist_del(usable_nodes, i);
01101     goto again;
01102   }
01103 
01104   smartlist_free(usable_nodes);
01105   return extend_info_dup(intro->extend_info);
01106 }
01107 
01110 int
01111 rend_client_any_intro_points_usable(const rend_cache_entry_t *entry)
01112 {
01113   extend_info_t *extend_info =
01114     rend_client_get_random_intro_impl(entry, get_options()->StrictNodes, 0);
01115 
01116   int rv = (extend_info != NULL);
01117 
01118   extend_info_free(extend_info);
01119   return rv;
01120 }
01121 
01124 static strmap_t *auth_hid_servs = NULL;
01125 
01129 rend_service_authorization_t*
01130 rend_client_lookup_service_authorization(const char *onion_address)
01131 {
01132   tor_assert(onion_address);
01133   if (!auth_hid_servs) return NULL;
01134   return strmap_get(auth_hid_servs, onion_address);
01135 }
01136 
01138 static void
01139 rend_service_authorization_free(rend_service_authorization_t *auth)
01140 {
01141   tor_free(auth);
01142 }
01143 
01145 static void
01146 rend_service_authorization_strmap_item_free(void *service_auth)
01147 {
01148   rend_service_authorization_free(service_auth);
01149 }
01150 
01153 void
01154 rend_service_authorization_free_all(void)
01155 {
01156   if (!auth_hid_servs) {
01157     return;
01158   }
01159   strmap_free(auth_hid_servs, rend_service_authorization_strmap_item_free);
01160   auth_hid_servs = NULL;
01161 }
01162 
01166 int
01167 rend_parse_service_authorization(const or_options_t *options,
01168                                  int validate_only)
01169 {
01170   config_line_t *line;
01171   int res = -1;
01172   strmap_t *parsed = strmap_new();
01173   smartlist_t *sl = smartlist_new();
01174   rend_service_authorization_t *auth = NULL;
01175 
01176   for (line = options->HidServAuth; line; line = line->next) {
01177     char *onion_address, *descriptor_cookie;
01178     char descriptor_cookie_tmp[REND_DESC_COOKIE_LEN+2];
01179     char descriptor_cookie_base64ext[REND_DESC_COOKIE_LEN_BASE64+2+1];
01180     int auth_type_val = 0;
01181     auth = NULL;
01182     SMARTLIST_FOREACH(sl, char *, c, tor_free(c););
01183     smartlist_clear(sl);
01184     smartlist_split_string(sl, line->value, " ",
01185                            SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
01186     if (smartlist_len(sl) < 2) {
01187       log_warn(LD_CONFIG, "Configuration line does not consist of "
01188                "\"onion-address authorization-cookie [service-name]\": "
01189                "'%s'", line->value);
01190       goto err;
01191     }
01192     auth = tor_malloc_zero(sizeof(rend_service_authorization_t));
01193     /* Parse onion address. */
01194     onion_address = smartlist_get(sl, 0);
01195     if (strlen(onion_address) != REND_SERVICE_ADDRESS_LEN ||
01196         strcmpend(onion_address, ".onion")) {
01197       log_warn(LD_CONFIG, "Onion address has wrong format: '%s'",
01198                onion_address);
01199       goto err;
01200     }
01201     strlcpy(auth->onion_address, onion_address, REND_SERVICE_ID_LEN_BASE32+1);
01202     if (!rend_valid_service_id(auth->onion_address)) {
01203       log_warn(LD_CONFIG, "Onion address has wrong format: '%s'",
01204                onion_address);
01205       goto err;
01206     }
01207     /* Parse descriptor cookie. */
01208     descriptor_cookie = smartlist_get(sl, 1);
01209     if (strlen(descriptor_cookie) != REND_DESC_COOKIE_LEN_BASE64) {
01210       log_warn(LD_CONFIG, "Authorization cookie has wrong length: '%s'",
01211                descriptor_cookie);
01212       goto err;
01213     }
01214     /* Add trailing zero bytes (AA) to make base64-decoding happy. */
01215     tor_snprintf(descriptor_cookie_base64ext,
01216                  REND_DESC_COOKIE_LEN_BASE64+2+1,
01217                  "%sAA", descriptor_cookie);
01218     if (base64_decode(descriptor_cookie_tmp, sizeof(descriptor_cookie_tmp),
01219                       descriptor_cookie_base64ext,
01220                       strlen(descriptor_cookie_base64ext)) < 0) {
01221       log_warn(LD_CONFIG, "Decoding authorization cookie failed: '%s'",
01222                descriptor_cookie);
01223       goto err;
01224     }
01225     auth_type_val = (descriptor_cookie_tmp[16] >> 4) + 1;
01226     if (auth_type_val < 1 || auth_type_val > 2) {
01227       log_warn(LD_CONFIG, "Authorization cookie has unknown authorization "
01228                           "type encoded.");
01229       goto err;
01230     }
01231     auth->auth_type = auth_type_val == 1 ? REND_BASIC_AUTH : REND_STEALTH_AUTH;
01232     memcpy(auth->descriptor_cookie, descriptor_cookie_tmp,
01233            REND_DESC_COOKIE_LEN);
01234     if (strmap_get(parsed, auth->onion_address)) {
01235       log_warn(LD_CONFIG, "Duplicate authorization for the same hidden "
01236                           "service.");
01237       goto err;
01238     }
01239     strmap_set(parsed, auth->onion_address, auth);
01240     auth = NULL;
01241   }
01242   res = 0;
01243   goto done;
01244  err:
01245   res = -1;
01246  done:
01247   rend_service_authorization_free(auth);
01248   SMARTLIST_FOREACH(sl, char *, c, tor_free(c););
01249   smartlist_free(sl);
01250   if (!validate_only && res == 0) {
01251     rend_service_authorization_free_all();
01252     auth_hid_servs = parsed;
01253   } else {
01254     strmap_free(parsed, rend_service_authorization_strmap_item_free);
01255   }
01256   return res;
01257 }
01258