Remove an HS's last_hid_serv_requests entries when a conn. attempt ends
[tor.git] / src / or / rendclient.c
blobe66b2426f82811968cb6aead4602605f37a214dc
1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007-2011, The Tor Project, Inc. */
3 /* See LICENSE for licensing information */
5 /**
6 * \file rendclient.c
7 * \brief Client code to access location-hidden services.
8 **/
10 #include "or.h"
11 #include "circuitbuild.h"
12 #include "circuitlist.h"
13 #include "circuituse.h"
14 #include "config.h"
15 #include "connection.h"
16 #include "connection_edge.h"
17 #include "directory.h"
18 #include "main.h"
19 #include "relay.h"
20 #include "rendclient.h"
21 #include "rendcommon.h"
22 #include "rephist.h"
23 #include "router.h"
24 #include "routerlist.h"
26 static extend_info_t *rend_client_get_random_intro_impl(
27 const rend_cache_entry_t *rend_query,
28 const int strict, const int warnings);
30 /** Purge all potentially remotely-detectable state held in the hidden
31 * service client code. Called on SIGNAL NEWNYM. */
32 void
33 rend_client_purge_state(void)
35 rend_cache_purge();
36 rend_client_cancel_descriptor_fetches();
37 rend_client_purge_last_hid_serv_requests();
40 /** Called when we've established a circuit to an introduction point:
41 * send the introduction request. */
42 void
43 rend_client_introcirc_has_opened(origin_circuit_t *circ)
45 tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
46 tor_assert(circ->cpath);
48 log_info(LD_REND,"introcirc is open");
49 connection_ap_attach_pending();
52 /** Send the establish-rendezvous cell along a rendezvous circuit. if
53 * it fails, mark the circ for close and return -1. else return 0.
55 static int
56 rend_client_send_establish_rendezvous(origin_circuit_t *circ)
58 tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND);
59 tor_assert(circ->rend_data);
60 log_info(LD_REND, "Sending an ESTABLISH_RENDEZVOUS cell");
62 if (crypto_rand(circ->rend_data->rend_cookie, REND_COOKIE_LEN) < 0) {
63 log_warn(LD_BUG, "Internal error: Couldn't produce random cookie.");
64 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL);
65 return -1;
67 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
68 RELAY_COMMAND_ESTABLISH_RENDEZVOUS,
69 circ->rend_data->rend_cookie,
70 REND_COOKIE_LEN,
71 circ->cpath->prev)<0) {
72 /* circ is already marked for close */
73 log_warn(LD_GENERAL, "Couldn't send ESTABLISH_RENDEZVOUS cell");
74 return -1;
77 return 0;
80 /** Extend the introduction circuit <b>circ</b> to another valid
81 * introduction point for the hidden service it is trying to connect
82 * to, or mark it and launch a new circuit if we can't extend it.
83 * Return 0 on success. Return -1 and mark the introduction
84 * circuit on failure.
86 * On failure, the caller is responsible for marking the associated
87 * rendezvous circuit for close. */
88 static int
89 rend_client_reextend_intro_circuit(origin_circuit_t *circ)
91 extend_info_t *extend_info;
92 int result;
93 extend_info = rend_client_get_random_intro(circ->rend_data);
94 if (!extend_info) {
95 log_warn(LD_REND,
96 "No usable introduction points left for %s. Closing.",
97 safe_str_client(circ->rend_data->onion_address));
98 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL);
99 return -1;
101 if (circ->remaining_relay_early_cells) {
102 log_info(LD_REND,
103 "Re-extending circ %d, this time to %s.",
104 circ->_base.n_circ_id,
105 safe_str_client(extend_info_describe(extend_info)));
106 result = circuit_extend_to_new_exit(circ, extend_info);
107 } else {
108 log_info(LD_REND,
109 "Building a new introduction circuit, this time to %s.",
110 safe_str_client(extend_info_describe(extend_info)));
111 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
112 if (!circuit_launch_by_extend_info(CIRCUIT_PURPOSE_C_INTRODUCING,
113 extend_info,
114 CIRCLAUNCH_IS_INTERNAL)) {
115 log_warn(LD_REND, "Building introduction circuit failed.");
116 result = -1;
117 } else {
118 result = 0;
121 extend_info_free(extend_info);
122 return result;
125 /** Called when we're trying to connect an ap conn; sends an INTRODUCE1 cell
126 * down introcirc if possible.
129 rend_client_send_introduction(origin_circuit_t *introcirc,
130 origin_circuit_t *rendcirc)
132 size_t payload_len;
133 int r, v3_shift = 0;
134 char payload[RELAY_PAYLOAD_SIZE];
135 char tmp[RELAY_PAYLOAD_SIZE];
136 rend_cache_entry_t *entry;
137 crypt_path_t *cpath;
138 off_t dh_offset;
139 crypto_pk_env_t *intro_key = NULL;
141 tor_assert(introcirc->_base.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
142 tor_assert(rendcirc->_base.purpose == CIRCUIT_PURPOSE_C_REND_READY);
143 tor_assert(introcirc->rend_data);
144 tor_assert(rendcirc->rend_data);
145 tor_assert(!rend_cmp_service_ids(introcirc->rend_data->onion_address,
146 rendcirc->rend_data->onion_address));
148 if (rend_cache_lookup_entry(introcirc->rend_data->onion_address, -1,
149 &entry) < 1) {
150 log_info(LD_REND,
151 "query %s didn't have valid rend desc in cache. "
152 "Refetching descriptor.",
153 safe_str_client(introcirc->rend_data->onion_address));
154 rend_client_refetch_v2_renddesc(introcirc->rend_data);
156 connection_t *conn;
158 while ((conn = connection_get_by_type_state_rendquery(CONN_TYPE_AP,
159 AP_CONN_STATE_CIRCUIT_WAIT,
160 introcirc->rend_data->onion_address))) {
161 conn->state = AP_CONN_STATE_RENDDESC_WAIT;
165 return -1;
168 /* first 20 bytes of payload are the hash of Bob's pk */
169 intro_key = NULL;
170 SMARTLIST_FOREACH(entry->parsed->intro_nodes, rend_intro_point_t *,
171 intro, {
172 if (tor_memeq(introcirc->build_state->chosen_exit->identity_digest,
173 intro->extend_info->identity_digest, DIGEST_LEN)) {
174 intro_key = intro->intro_key;
175 break;
178 if (!intro_key) {
179 log_info(LD_REND, "Could not find intro key for %s at %s; we "
180 "have a v2 rend desc with %d intro points. "
181 "Trying a different intro point...",
182 safe_str_client(introcirc->rend_data->onion_address),
183 safe_str_client(extend_info_describe(
184 introcirc->build_state->chosen_exit)),
185 smartlist_len(entry->parsed->intro_nodes));
187 if (rend_client_reextend_intro_circuit(introcirc)) {
188 goto perm_err;
189 } else {
190 return -1;
193 if (crypto_pk_get_digest(intro_key, payload)<0) {
194 log_warn(LD_BUG, "Internal error: couldn't hash public key.");
195 goto perm_err;
198 /* Initialize the pending_final_cpath and start the DH handshake. */
199 cpath = rendcirc->build_state->pending_final_cpath;
200 if (!cpath) {
201 cpath = rendcirc->build_state->pending_final_cpath =
202 tor_malloc_zero(sizeof(crypt_path_t));
203 cpath->magic = CRYPT_PATH_MAGIC;
204 if (!(cpath->dh_handshake_state = crypto_dh_new(DH_TYPE_REND))) {
205 log_warn(LD_BUG, "Internal error: couldn't allocate DH.");
206 goto perm_err;
208 if (crypto_dh_generate_public(cpath->dh_handshake_state)<0) {
209 log_warn(LD_BUG, "Internal error: couldn't generate g^x.");
210 goto perm_err;
214 /* If version is 3, write (optional) auth data and timestamp. */
215 if (entry->parsed->protocols & (1<<3)) {
216 tmp[0] = 3; /* version 3 of the cell format */
217 tmp[1] = (uint8_t)introcirc->rend_data->auth_type; /* auth type, if any */
218 v3_shift = 1;
219 if (introcirc->rend_data->auth_type != REND_NO_AUTH) {
220 set_uint16(tmp+2, htons(REND_DESC_COOKIE_LEN));
221 memcpy(tmp+4, introcirc->rend_data->descriptor_cookie,
222 REND_DESC_COOKIE_LEN);
223 v3_shift += 2+REND_DESC_COOKIE_LEN;
225 set_uint32(tmp+v3_shift+1, htonl((uint32_t)time(NULL)));
226 v3_shift += 4;
227 } /* if version 2 only write version number */
228 else if (entry->parsed->protocols & (1<<2)) {
229 tmp[0] = 2; /* version 2 of the cell format */
232 /* write the remaining items into tmp */
233 if (entry->parsed->protocols & (1<<3) || entry->parsed->protocols & (1<<2)) {
234 /* version 2 format */
235 extend_info_t *extend_info = rendcirc->build_state->chosen_exit;
236 int klen;
237 /* nul pads */
238 set_uint32(tmp+v3_shift+1, tor_addr_to_ipv4h(&extend_info->addr));
239 set_uint16(tmp+v3_shift+5, htons(extend_info->port));
240 memcpy(tmp+v3_shift+7, extend_info->identity_digest, DIGEST_LEN);
241 klen = crypto_pk_asn1_encode(extend_info->onion_key,
242 tmp+v3_shift+7+DIGEST_LEN+2,
243 sizeof(tmp)-(v3_shift+7+DIGEST_LEN+2));
244 set_uint16(tmp+v3_shift+7+DIGEST_LEN, htons(klen));
245 memcpy(tmp+v3_shift+7+DIGEST_LEN+2+klen, rendcirc->rend_data->rend_cookie,
246 REND_COOKIE_LEN);
247 dh_offset = v3_shift+7+DIGEST_LEN+2+klen+REND_COOKIE_LEN;
248 } else {
249 /* Version 0. */
250 strncpy(tmp, rendcirc->build_state->chosen_exit->nickname,
251 (MAX_NICKNAME_LEN+1)); /* nul pads */
252 memcpy(tmp+MAX_NICKNAME_LEN+1, rendcirc->rend_data->rend_cookie,
253 REND_COOKIE_LEN);
254 dh_offset = MAX_NICKNAME_LEN+1+REND_COOKIE_LEN;
257 if (crypto_dh_get_public(cpath->dh_handshake_state, tmp+dh_offset,
258 DH_KEY_LEN)<0) {
259 log_warn(LD_BUG, "Internal error: couldn't extract g^x.");
260 goto perm_err;
263 note_crypto_pk_op(REND_CLIENT);
264 /*XXX maybe give crypto_pk_public_hybrid_encrypt a max_len arg,
265 * to avoid buffer overflows? */
266 r = crypto_pk_public_hybrid_encrypt(intro_key, payload+DIGEST_LEN,
267 sizeof(payload)-DIGEST_LEN,
268 tmp,
269 (int)(dh_offset+DH_KEY_LEN),
270 PK_PKCS1_OAEP_PADDING, 0);
271 if (r<0) {
272 log_warn(LD_BUG,"Internal error: hybrid pk encrypt failed.");
273 goto perm_err;
276 payload_len = DIGEST_LEN + r;
277 tor_assert(payload_len <= RELAY_PAYLOAD_SIZE); /* we overran something */
279 log_info(LD_REND, "Sending an INTRODUCE1 cell");
280 if (relay_send_command_from_edge(0, TO_CIRCUIT(introcirc),
281 RELAY_COMMAND_INTRODUCE1,
282 payload, payload_len,
283 introcirc->cpath->prev)<0) {
284 /* introcirc is already marked for close. leave rendcirc alone. */
285 log_warn(LD_BUG, "Couldn't send INTRODUCE1 cell");
286 return -2;
289 /* Now, we wait for an ACK or NAK on this circuit. */
290 introcirc->_base.purpose = CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT;
291 /* Set timestamp_dirty, because circuit_expire_building expects it
292 * to specify when a circuit entered the _C_INTRODUCE_ACK_WAIT
293 * state. */
294 introcirc->_base.timestamp_dirty = time(NULL);
296 return 0;
297 perm_err:
298 if (!introcirc->_base.marked_for_close)
299 circuit_mark_for_close(TO_CIRCUIT(introcirc), END_CIRC_REASON_INTERNAL);
300 circuit_mark_for_close(TO_CIRCUIT(rendcirc), END_CIRC_REASON_INTERNAL);
301 return -2;
304 /** Called when a rendezvous circuit is open; sends a establish
305 * rendezvous circuit as appropriate. */
306 void
307 rend_client_rendcirc_has_opened(origin_circuit_t *circ)
309 tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND);
311 log_info(LD_REND,"rendcirc is open");
313 /* generate a rendezvous cookie, store it in circ */
314 if (rend_client_send_establish_rendezvous(circ) < 0) {
315 return;
319 /** Called when get an ACK or a NAK for a REND_INTRODUCE1 cell.
322 rend_client_introduction_acked(origin_circuit_t *circ,
323 const uint8_t *request, size_t request_len)
325 origin_circuit_t *rendcirc;
326 (void) request; // XXXX Use this.
328 if (circ->_base.purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
329 log_warn(LD_PROTOCOL,
330 "Received REND_INTRODUCE_ACK on unexpected circuit %d.",
331 circ->_base.n_circ_id);
332 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
333 return -1;
336 tor_assert(circ->build_state->chosen_exit);
337 tor_assert(circ->rend_data);
339 if (request_len == 0) {
340 /* It's an ACK; the introduction point relayed our introduction request. */
341 /* Locate the rend circ which is waiting to hear about this ack,
342 * and tell it.
344 log_info(LD_REND,"Received ack. Telling rend circ...");
345 rendcirc = circuit_get_by_rend_query_and_purpose(
346 circ->rend_data->onion_address, CIRCUIT_PURPOSE_C_REND_READY);
347 if (rendcirc) { /* remember the ack */
348 rendcirc->_base.purpose = CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED;
349 /* Set timestamp_dirty, because circuit_expire_building expects
350 * it to specify when a circuit entered the
351 * _C_REND_READY_INTRO_ACKED state. */
352 rendcirc->_base.timestamp_dirty = time(NULL);
353 } else {
354 log_info(LD_REND,"...Found no rend circ. Dropping on the floor.");
356 /* close the circuit: we won't need it anymore. */
357 circ->_base.purpose = CIRCUIT_PURPOSE_C_INTRODUCE_ACKED;
358 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
359 } else {
360 /* It's a NAK; the introduction point didn't relay our request. */
361 circ->_base.purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
362 /* Remove this intro point from the set of viable introduction
363 * points. If any remain, extend to a new one and try again.
364 * If none remain, refetch the service descriptor.
366 log_info(LD_REND, "Got nack for %s from %s...",
367 safe_str_client(circ->rend_data->onion_address),
368 safe_str_client(extend_info_describe(circ->build_state->chosen_exit)));
369 if (rend_client_report_intro_point_failure(circ->build_state->chosen_exit,
370 circ->rend_data,
371 INTRO_POINT_FAILURE_GENERIC)>0){
372 /* There are introduction points left. Re-extend the circuit to
373 * another intro point and try again. */
374 int result = rend_client_reextend_intro_circuit(circ);
375 /* XXXX If that call failed, should we close the rend circuit,
376 * too? */
377 return result;
380 return 0;
383 /** The period for which a hidden service directory cannot be queried for
384 * the same descriptor ID again. */
385 #define REND_HID_SERV_DIR_REQUERY_PERIOD (15 * 60)
387 /** Contains the last request times to hidden service directories for
388 * certain queries; each key is a string consisting of the
389 * concatenation of a base32-encoded HS directory identity digest, a
390 * base32-encoded HS descriptor ID, and a hidden service address
391 * (without the ".onion" part); each value is a pointer to a time_t
392 * holding the time of the last request for that descriptor ID to that
393 * HS directory. */
394 static strmap_t *last_hid_serv_requests_ = NULL;
396 /** Returns last_hid_serv_requests_, initializing it to a new strmap if
397 * necessary. */
398 static strmap_t *
399 get_last_hid_serv_requests(void)
401 if (!last_hid_serv_requests_)
402 last_hid_serv_requests_ = strmap_new();
403 return last_hid_serv_requests_;
406 #define LAST_HID_SERV_REQUEST_KEY_LEN (REND_DESC_ID_V2_LEN_BASE32 + \
407 REND_DESC_ID_V2_LEN_BASE32 + \
408 REND_SERVICE_ID_LEN_BASE32)
410 /** Look up the last request time to hidden service directory <b>hs_dir</b>
411 * for descriptor ID <b>desc_id_base32</b> for the service specified in
412 * <b>rend_query</b>. If <b>set</b> is non-zero,
413 * assign the current time <b>now</b> and return that. Otherwise, return
414 * the most recent request time, or 0 if no such request has been sent
415 * before. */
416 static time_t
417 lookup_last_hid_serv_request(routerstatus_t *hs_dir,
418 const char *desc_id_base32,
419 const rend_data_t *rend_query,
420 time_t now, int set)
422 char hsdir_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
423 char hsdir_desc_comb_id[LAST_HID_SERV_REQUEST_KEY_LEN + 1];
424 time_t *last_request_ptr;
425 strmap_t *last_hid_serv_requests = get_last_hid_serv_requests();
426 base32_encode(hsdir_id_base32, sizeof(hsdir_id_base32),
427 hs_dir->identity_digest, DIGEST_LEN);
428 tor_snprintf(hsdir_desc_comb_id, sizeof(hsdir_desc_comb_id), "%s%s%s",
429 hsdir_id_base32,
430 desc_id_base32,
431 rend_query->onion_address);
432 /* XXX023 tor_assert(strlen(hsdir_desc_comb_id) ==
433 LAST_HID_SERV_REQUEST_KEY_LEN); */
434 if (set) {
435 time_t *oldptr;
436 last_request_ptr = tor_malloc_zero(sizeof(time_t));
437 *last_request_ptr = now;
438 oldptr = strmap_set(last_hid_serv_requests, hsdir_desc_comb_id,
439 last_request_ptr);
440 tor_free(oldptr);
441 } else
442 last_request_ptr = strmap_get_lc(last_hid_serv_requests,
443 hsdir_desc_comb_id);
444 return (last_request_ptr) ? *last_request_ptr : 0;
447 /** Clean the history of request times to hidden service directories, so that
448 * it does not contain requests older than REND_HID_SERV_DIR_REQUERY_PERIOD
449 * seconds any more. */
450 static void
451 directory_clean_last_hid_serv_requests(void)
453 strmap_iter_t *iter;
454 time_t cutoff = time(NULL) - REND_HID_SERV_DIR_REQUERY_PERIOD;
455 strmap_t *last_hid_serv_requests = get_last_hid_serv_requests();
456 for (iter = strmap_iter_init(last_hid_serv_requests);
457 !strmap_iter_done(iter); ) {
458 const char *key;
459 void *val;
460 time_t *ent;
461 strmap_iter_get(iter, &key, &val);
462 ent = (time_t *) val;
463 if (*ent < cutoff) {
464 iter = strmap_iter_next_rmv(last_hid_serv_requests, iter);
465 tor_free(ent);
466 } else {
467 iter = strmap_iter_next(last_hid_serv_requests, iter);
472 /** Remove all requests related to the hidden service named
473 * <b>onion_address</b> from the history of times of requests to
474 * hidden service directories. */
475 static void
476 purge_hid_serv_from_last_hid_serv_requests(const char *onion_address)
478 strmap_iter_t *iter;
479 strmap_t *last_hid_serv_requests = get_last_hid_serv_requests();
480 /* XXX023 tor_assert(strlen(onion_address) == REND_SERVICE_ID_LEN_BASE32); */
481 for (iter = strmap_iter_init(last_hid_serv_requests);
482 !strmap_iter_done(iter); ) {
483 const char *key;
484 void *val;
485 strmap_iter_get(iter, &key, &val);
486 /* XXX023 tor_assert(strlen(key) == LAST_HID_SERV_REQUEST_KEY_LEN); */
487 if (tor_memeq(key + LAST_HID_SERV_REQUEST_KEY_LEN -
488 REND_SERVICE_ID_LEN_BASE32,
489 onion_address,
490 REND_SERVICE_ID_LEN_BASE32)) {
491 iter = strmap_iter_next_rmv(last_hid_serv_requests, iter);
492 tor_free(val);
493 } else {
494 iter = strmap_iter_next(last_hid_serv_requests, iter);
499 /** Purge the history of request times to hidden service directories,
500 * so that future lookups of an HS descriptor will not fail because we
501 * accessed all of the HSDir relays responsible for the descriptor
502 * recently. */
503 void
504 rend_client_purge_last_hid_serv_requests(void)
506 /* Don't create the table if it doesn't exist yet (and it may very
507 * well not exist if the user hasn't accessed any HSes)... */
508 strmap_t *old_last_hid_serv_requests = last_hid_serv_requests_;
509 /* ... and let get_last_hid_serv_requests re-create it for us if
510 * necessary. */
511 last_hid_serv_requests_ = NULL;
513 if (old_last_hid_serv_requests != NULL) {
514 log_info(LD_REND, "Purging client last-HS-desc-request-time table");
515 strmap_free(old_last_hid_serv_requests, _tor_free);
519 /** Determine the responsible hidden service directories for <b>desc_id</b>
520 * and fetch the descriptor with that ID from one of them. Only
521 * send a request to a hidden service directory that we have not yet tried
522 * during this attempt to connect to this hidden service; on success, return 1,
523 * in the case that no hidden service directory is left to ask for the
524 * descriptor, return 0, and in case of a failure -1. */
525 static int
526 directory_get_from_hs_dir(const char *desc_id, const rend_data_t *rend_query)
528 smartlist_t *responsible_dirs = smartlist_create();
529 routerstatus_t *hs_dir;
530 char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
531 time_t now = time(NULL);
532 char descriptor_cookie_base64[3*REND_DESC_COOKIE_LEN_BASE64];
533 tor_assert(desc_id);
534 tor_assert(rend_query);
535 /* Determine responsible dirs. Even if we can't get all we want,
536 * work with the ones we have. If it's empty, we'll notice below. */
537 hid_serv_get_responsible_directories(responsible_dirs, desc_id);
539 base32_encode(desc_id_base32, sizeof(desc_id_base32),
540 desc_id, DIGEST_LEN);
542 /* Only select those hidden service directories to which we did not send
543 * a request recently and for which we have a router descriptor here. */
544 directory_clean_last_hid_serv_requests(); /* Clean request history first. */
546 SMARTLIST_FOREACH(responsible_dirs, routerstatus_t *, dir, {
547 if (lookup_last_hid_serv_request(dir, desc_id_base32, rend_query, 0, 0) +
548 REND_HID_SERV_DIR_REQUERY_PERIOD >= now ||
549 !router_get_by_digest(dir->identity_digest))
550 SMARTLIST_DEL_CURRENT(responsible_dirs, dir);
553 hs_dir = smartlist_choose(responsible_dirs);
554 smartlist_free(responsible_dirs);
555 if (!hs_dir) {
556 log_info(LD_REND, "Could not pick one of the responsible hidden "
557 "service directories, because we requested them all "
558 "recently without success.");
559 return 0;
562 /* Remember that we are requesting a descriptor from this hidden service
563 * directory now. */
564 lookup_last_hid_serv_request(hs_dir, desc_id_base32, rend_query, now, 1);
566 /* Encode descriptor cookie for logging purposes. */
567 if (rend_query->auth_type != REND_NO_AUTH) {
568 if (base64_encode(descriptor_cookie_base64,
569 sizeof(descriptor_cookie_base64),
570 rend_query->descriptor_cookie, REND_DESC_COOKIE_LEN)<0) {
571 log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
572 return 0;
574 /* Remove == signs and newline. */
575 descriptor_cookie_base64[strlen(descriptor_cookie_base64)-3] = '\0';
576 } else {
577 strlcpy(descriptor_cookie_base64, "(none)",
578 sizeof(descriptor_cookie_base64));
581 /* Send fetch request. (Pass query and possibly descriptor cookie so that
582 * they can be written to the directory connection and be referred to when
583 * the response arrives. */
584 directory_initiate_command_routerstatus_rend(hs_dir,
585 DIR_PURPOSE_FETCH_RENDDESC_V2,
586 ROUTER_PURPOSE_GENERAL,
587 1, desc_id_base32, NULL, 0, 0,
588 rend_query);
589 log_info(LD_REND, "Sending fetch request for v2 descriptor for "
590 "service '%s' with descriptor ID '%s', auth type %d, "
591 "and descriptor cookie '%s' to hidden service "
592 "directory %s",
593 rend_query->onion_address, desc_id_base32,
594 rend_query->auth_type,
595 (rend_query->auth_type == REND_NO_AUTH ? "[none]" :
596 escaped_safe_str_client(descriptor_cookie_base64)),
597 routerstatus_describe(hs_dir));
598 return 1;
601 /** Unless we already have a descriptor for <b>rend_query</b> with at least
602 * one (possibly) working introduction point in it, start a connection to a
603 * hidden service directory to fetch a v2 rendezvous service descriptor. */
604 void
605 rend_client_refetch_v2_renddesc(const rend_data_t *rend_query)
607 char descriptor_id[DIGEST_LEN];
608 int replicas_left_to_try[REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS];
609 int i, tries_left;
610 rend_cache_entry_t *e = NULL;
611 tor_assert(rend_query);
612 /* Are we configured to fetch descriptors? */
613 if (!get_options()->FetchHidServDescriptors) {
614 log_warn(LD_REND, "We received an onion address for a v2 rendezvous "
615 "service descriptor, but are not fetching service descriptors.");
616 return;
618 /* Before fetching, check if we already have a usable descriptor here. */
619 if (rend_cache_lookup_entry(rend_query->onion_address, -1, &e) > 0 &&
620 rend_client_any_intro_points_usable(e)) {
621 log_info(LD_REND, "We would fetch a v2 rendezvous descriptor, but we "
622 "already have a usable descriptor here. Not fetching.");
623 return;
625 log_debug(LD_REND, "Fetching v2 rendezvous descriptor for service %s",
626 safe_str_client(rend_query->onion_address));
627 /* Randomly iterate over the replicas until a descriptor can be fetched
628 * from one of the consecutive nodes, or no options are left. */
629 tries_left = REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS;
630 for (i = 0; i < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS; i++)
631 replicas_left_to_try[i] = i;
632 while (tries_left > 0) {
633 int rand = crypto_rand_int(tries_left);
634 int chosen_replica = replicas_left_to_try[rand];
635 replicas_left_to_try[rand] = replicas_left_to_try[--tries_left];
637 if (rend_compute_v2_desc_id(descriptor_id, rend_query->onion_address,
638 rend_query->auth_type == REND_STEALTH_AUTH ?
639 rend_query->descriptor_cookie : NULL,
640 time(NULL), chosen_replica) < 0) {
641 log_warn(LD_REND, "Internal error: Computing v2 rendezvous "
642 "descriptor ID did not succeed.");
643 return;
645 if (directory_get_from_hs_dir(descriptor_id, rend_query) != 0)
646 return; /* either success or failure, but we're done */
648 /* If we come here, there are no hidden service directories left. */
649 log_info(LD_REND, "Could not pick one of the responsible hidden "
650 "service directories to fetch descriptors, because "
651 "we already tried them all unsuccessfully.");
652 /* Close pending connections. */
653 rend_client_desc_trynow(rend_query->onion_address);
654 return;
657 /** Cancel all rendezvous descriptor fetches currently in progress.
659 void
660 rend_client_cancel_descriptor_fetches(void)
662 smartlist_t *connection_array = get_connection_array();
664 SMARTLIST_FOREACH_BEGIN(connection_array, connection_t *, conn) {
665 if (conn->type == CONN_TYPE_DIR &&
666 (conn->purpose == DIR_PURPOSE_FETCH_RENDDESC ||
667 conn->purpose == DIR_PURPOSE_FETCH_RENDDESC_V2)) {
668 /* It's a rendezvous descriptor fetch in progress -- cancel it
669 * by marking the connection for close.
671 * Even if this connection has already reached EOF, this is
672 * enough to make sure that if the descriptor hasn't been
673 * processed yet, it won't be. See the end of
674 * connection_handle_read; connection_reached_eof (indirectly)
675 * processes whatever response the connection received. */
677 const rend_data_t *rd = (TO_DIR_CONN(conn))->rend_data;
678 if (!rd) {
679 log_warn(LD_BUG | LD_REND,
680 "Marking for close dir conn fetching rendezvous "
681 "descriptor for unknown service!");
682 } else {
683 log_debug(LD_REND, "Marking for close dir conn fetching "
684 "rendezvous descriptor for service %s",
685 safe_str(rd->onion_address));
687 connection_mark_for_close(conn);
689 } SMARTLIST_FOREACH_END(conn);
692 /** Mark <b>failed_intro</b> as a failed introduction point for the
693 * hidden service specified by <b>rend_query</b>. If the HS now has no
694 * usable intro points, or we do not have an HS descriptor for it,
695 * then launch a new renddesc fetch.
697 * If <b>failure_type</b> is INTRO_POINT_FAILURE_GENERIC, remove the
698 * intro point from (our parsed copy of) the HS descriptor.
700 * If <b>failure_type</b> is INTRO_POINT_FAILURE_TIMEOUT, mark the
701 * intro point as 'timed out'; it will not be retried until the
702 * current hidden service connection attempt has ended or it has
703 * appeared in a newly fetched rendezvous descriptor.
705 * If <b>failure_type</b> is INTRO_POINT_FAILURE_UNREACHABLE,
706 * increment the intro point's reachability-failure count; if it has
707 * now failed MAX_INTRO_POINT_REACHABILITY_FAILURES or more times,
708 * remove the intro point from (our parsed copy of) the HS descriptor.
710 * Return -1 if error, 0 if no usable intro points remain or service
711 * unrecognized, 1 if recognized and some intro points remain.
714 rend_client_report_intro_point_failure(extend_info_t *failed_intro,
715 const rend_data_t *rend_query,
716 unsigned int failure_type)
718 int i, r;
719 rend_cache_entry_t *ent;
720 connection_t *conn;
722 r = rend_cache_lookup_entry(rend_query->onion_address, -1, &ent);
723 if (r<0) {
724 log_warn(LD_BUG, "Malformed service ID %s.",
725 escaped_safe_str_client(rend_query->onion_address));
726 return -1;
728 if (r==0) {
729 log_info(LD_REND, "Unknown service %s. Re-fetching descriptor.",
730 escaped_safe_str_client(rend_query->onion_address));
731 rend_client_refetch_v2_renddesc(rend_query);
732 return 0;
735 for (i = 0; i < smartlist_len(ent->parsed->intro_nodes); i++) {
736 rend_intro_point_t *intro = smartlist_get(ent->parsed->intro_nodes, i);
737 if (tor_memeq(failed_intro->identity_digest,
738 intro->extend_info->identity_digest, DIGEST_LEN)) {
739 switch (failure_type) {
740 default:
741 log_warn(LD_BUG, "Unknown failure type %u. Removing intro point.",
742 failure_type);
743 tor_fragile_assert();
744 /* fall through */
745 case INTRO_POINT_FAILURE_GENERIC:
746 rend_intro_point_free(intro);
747 smartlist_del(ent->parsed->intro_nodes, i);
748 break;
749 case INTRO_POINT_FAILURE_TIMEOUT:
750 intro->timed_out = 1;
751 break;
752 case INTRO_POINT_FAILURE_UNREACHABLE:
753 ++(intro->unreachable_count);
755 int zap_intro_point =
756 intro->unreachable_count >= MAX_INTRO_POINT_REACHABILITY_FAILURES;
757 log_info(LD_REND, "Failed to reach this intro point %u times.%s",
758 intro->unreachable_count,
759 zap_intro_point ? " Removing from descriptor.": "");
760 if (zap_intro_point) {
761 rend_intro_point_free(intro);
762 smartlist_del(ent->parsed->intro_nodes, i);
765 break;
767 break;
771 if (! rend_client_any_intro_points_usable(ent)) {
772 log_info(LD_REND,
773 "No more intro points remain for %s. Re-fetching descriptor.",
774 escaped_safe_str_client(rend_query->onion_address));
775 rend_client_refetch_v2_renddesc(rend_query);
777 /* move all pending streams back to renddesc_wait */
778 while ((conn = connection_get_by_type_state_rendquery(CONN_TYPE_AP,
779 AP_CONN_STATE_CIRCUIT_WAIT,
780 rend_query->onion_address))) {
781 conn->state = AP_CONN_STATE_RENDDESC_WAIT;
784 return 0;
786 log_info(LD_REND,"%d options left for %s.",
787 smartlist_len(ent->parsed->intro_nodes),
788 escaped_safe_str_client(rend_query->onion_address));
789 return 1;
792 /** Called when we receive a RENDEZVOUS_ESTABLISHED cell; changes the state of
793 * the circuit to C_REND_READY.
796 rend_client_rendezvous_acked(origin_circuit_t *circ, const uint8_t *request,
797 size_t request_len)
799 (void) request;
800 (void) request_len;
801 /* we just got an ack for our establish-rendezvous. switch purposes. */
802 if (circ->_base.purpose != CIRCUIT_PURPOSE_C_ESTABLISH_REND) {
803 log_warn(LD_PROTOCOL,"Got a rendezvous ack when we weren't expecting one. "
804 "Closing circ.");
805 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
806 return -1;
808 log_info(LD_REND,"Got rendezvous ack. This circuit is now ready for "
809 "rendezvous.");
810 circ->_base.purpose = CIRCUIT_PURPOSE_C_REND_READY;
811 /* Set timestamp_dirty, because circuit_expire_building expects it
812 * to specify when a circuit entered the _C_REND_READY state. */
813 circ->_base.timestamp_dirty = time(NULL);
814 /* XXXX023 This is a pretty brute-force approach. It'd be better to
815 * attach only the connections that are waiting on this circuit, rather
816 * than trying to attach them all. See comments bug 743. */
817 /* If we already have the introduction circuit built, make sure we send
818 * the INTRODUCE cell _now_ */
819 connection_ap_attach_pending();
820 return 0;
823 /** Bob sent us a rendezvous cell; join the circuits. */
825 rend_client_receive_rendezvous(origin_circuit_t *circ, const uint8_t *request,
826 size_t request_len)
828 crypt_path_t *hop;
829 char keys[DIGEST_LEN+CPATH_KEY_MATERIAL_LEN];
831 if ((circ->_base.purpose != CIRCUIT_PURPOSE_C_REND_READY &&
832 circ->_base.purpose != CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED)
833 || !circ->build_state->pending_final_cpath) {
834 log_warn(LD_PROTOCOL,"Got rendezvous2 cell from hidden service, but not "
835 "expecting it. Closing.");
836 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
837 return -1;
840 if (request_len != DH_KEY_LEN+DIGEST_LEN) {
841 log_warn(LD_PROTOCOL,"Incorrect length (%d) on RENDEZVOUS2 cell.",
842 (int)request_len);
843 goto err;
846 log_info(LD_REND,"Got RENDEZVOUS2 cell from hidden service.");
848 /* first DH_KEY_LEN bytes are g^y from bob. Finish the dh handshake...*/
849 tor_assert(circ->build_state);
850 tor_assert(circ->build_state->pending_final_cpath);
851 hop = circ->build_state->pending_final_cpath;
852 tor_assert(hop->dh_handshake_state);
853 if (crypto_dh_compute_secret(LOG_PROTOCOL_WARN,
854 hop->dh_handshake_state, (char*)request,
855 DH_KEY_LEN,
856 keys, DIGEST_LEN+CPATH_KEY_MATERIAL_LEN)<0) {
857 log_warn(LD_GENERAL, "Couldn't complete DH handshake.");
858 goto err;
860 /* ... and set up cpath. */
861 if (circuit_init_cpath_crypto(hop, keys+DIGEST_LEN, 0)<0)
862 goto err;
864 /* Check whether the digest is right... */
865 if (tor_memneq(keys, request+DH_KEY_LEN, DIGEST_LEN)) {
866 log_warn(LD_PROTOCOL, "Incorrect digest of key material.");
867 goto err;
870 crypto_dh_free(hop->dh_handshake_state);
871 hop->dh_handshake_state = NULL;
873 /* All is well. Extend the circuit. */
874 circ->_base.purpose = CIRCUIT_PURPOSE_C_REND_JOINED;
875 hop->state = CPATH_STATE_OPEN;
876 /* set the windows to default. these are the windows
877 * that alice thinks bob has.
879 hop->package_window = circuit_initial_package_window();
880 hop->deliver_window = CIRCWINDOW_START;
882 onion_append_to_cpath(&circ->cpath, hop);
883 circ->build_state->pending_final_cpath = NULL; /* prevent double-free */
884 /* XXXX023 This is a pretty brute-force approach. It'd be better to
885 * attach only the connections that are waiting on this circuit, rather
886 * than trying to attach them all. See comments bug 743. */
887 connection_ap_attach_pending();
888 memset(keys, 0, sizeof(keys));
889 return 0;
890 err:
891 memset(keys, 0, sizeof(keys));
892 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
893 return -1;
896 /** Find all the apconns in state AP_CONN_STATE_RENDDESC_WAIT that are
897 * waiting on <b>query</b>. If there's a working cache entry here with at
898 * least one intro point, move them to the next state. */
899 void
900 rend_client_desc_trynow(const char *query)
902 edge_connection_t *conn;
903 rend_cache_entry_t *entry;
904 time_t now = time(NULL);
906 smartlist_t *conns = get_connection_array();
907 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, _conn) {
908 if (_conn->type != CONN_TYPE_AP ||
909 _conn->state != AP_CONN_STATE_RENDDESC_WAIT ||
910 _conn->marked_for_close)
911 continue;
912 conn = TO_EDGE_CONN(_conn);
913 if (!conn->rend_data)
914 continue;
915 if (rend_cmp_service_ids(query, conn->rend_data->onion_address))
916 continue;
917 assert_connection_ok(TO_CONN(conn), now);
918 if (rend_cache_lookup_entry(conn->rend_data->onion_address, -1,
919 &entry) == 1 &&
920 rend_client_any_intro_points_usable(entry)) {
921 /* either this fetch worked, or it failed but there was a
922 * valid entry from before which we should reuse */
923 log_info(LD_REND,"Rend desc is usable. Launching circuits.");
924 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
926 /* restart their timeout values, so they get a fair shake at
927 * connecting to the hidden service. */
928 conn->_base.timestamp_created = now;
929 conn->_base.timestamp_lastread = now;
930 conn->_base.timestamp_lastwritten = now;
932 if (connection_ap_handshake_attach_circuit(conn) < 0) {
933 /* it will never work */
934 log_warn(LD_REND,"Rendezvous attempt failed. Closing.");
935 if (!conn->_base.marked_for_close)
936 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
938 } else { /* 404, or fetch didn't get that far */
939 log_notice(LD_REND,"Closing stream for '%s.onion': hidden service is "
940 "unavailable (try again later).",
941 safe_str_client(query));
942 connection_mark_unattached_ap(conn, END_STREAM_REASON_RESOLVEFAILED);
943 rend_client_note_connection_attempt_ended(query);
945 } SMARTLIST_FOREACH_END(_conn);
948 /** Clear temporary state used only during an attempt to connect to
949 * the hidden service named <b>onion_address</b>. Called when a
950 * connection attempt has ended; may be called occasionally at other
951 * times, and should be reasonably harmless. */
952 void
953 rend_client_note_connection_attempt_ended(const char *onion_address)
955 rend_cache_entry_t *cache_entry = NULL;
956 rend_cache_lookup_entry(onion_address, -1, &cache_entry);
958 log_info(LD_REND, "Connection attempt for %s has ended; "
959 "cleaning up temporary state.",
960 safe_str_client(onion_address));
962 /* Clear the timed_out flag on all remaining intro points for this HS. */
963 if (cache_entry != NULL) {
964 SMARTLIST_FOREACH(cache_entry->parsed->intro_nodes,
965 rend_intro_point_t *, ip,
966 ip->timed_out = 0; );
969 /* Remove the HS's entries in last_hid_serv_requests. */
970 purge_hid_serv_from_last_hid_serv_requests(onion_address);
973 /** Return a newly allocated extend_info_t* for a randomly chosen introduction
974 * point for the named hidden service. Return NULL if all introduction points
975 * have been tried and failed.
977 extend_info_t *
978 rend_client_get_random_intro(const rend_data_t *rend_query)
980 extend_info_t *result;
981 rend_cache_entry_t *entry;
983 if (rend_cache_lookup_entry(rend_query->onion_address, -1, &entry) < 1) {
984 log_warn(LD_REND,
985 "Query '%s' didn't have valid rend desc in cache. Failing.",
986 safe_str_client(rend_query->onion_address));
987 return NULL;
990 /* See if we can get a node that complies with ExcludeNodes */
991 if ((result = rend_client_get_random_intro_impl(entry, 1, 1)))
992 return result;
993 /* If not, and StrictNodes is not set, see if we can return any old node
995 if (!get_options()->StrictNodes)
996 return rend_client_get_random_intro_impl(entry, 0, 1);
997 return NULL;
1000 /** As rend_client_get_random_intro, except assume that StrictNodes is set
1001 * iff <b>strict</b> is true. If <b>warnings</b> is false, don't complain
1002 * to the user when we're out of nodes, even if StrictNodes is true.
1004 static extend_info_t *
1005 rend_client_get_random_intro_impl(const rend_cache_entry_t *entry,
1006 const int strict,
1007 const int warnings)
1009 int i;
1011 rend_intro_point_t *intro;
1012 routerinfo_t *router;
1013 or_options_t *options = get_options();
1014 smartlist_t *usable_nodes;
1015 int n_excluded = 0;
1017 /* We'll keep a separate list of the usable nodes. If this becomes empty,
1018 * no nodes are usable. */
1019 usable_nodes = smartlist_create();
1020 smartlist_add_all(usable_nodes, entry->parsed->intro_nodes);
1022 /* Remove the intro points that have timed out during this HS
1023 * connection attempt from our list of usable nodes. */
1024 SMARTLIST_FOREACH(usable_nodes, rend_intro_point_t *, ip,
1025 if (ip->timed_out) {
1026 SMARTLIST_DEL_CURRENT(usable_nodes, ip);
1029 again:
1030 if (smartlist_len(usable_nodes) == 0) {
1031 if (n_excluded && get_options()->StrictNodes && warnings) {
1032 /* We only want to warn if StrictNodes is really set. Otherwise
1033 * we're just about to retry anyways.
1035 log_warn(LD_REND, "All introduction points for hidden service are "
1036 "at excluded relays, and StrictNodes is set. Skipping.");
1038 smartlist_free(usable_nodes);
1039 return NULL;
1042 i = crypto_rand_int(smartlist_len(usable_nodes));
1043 intro = smartlist_get(usable_nodes, i);
1044 /* Do we need to look up the router or is the extend info complete? */
1045 if (!intro->extend_info->onion_key) {
1046 if (tor_digest_is_zero(intro->extend_info->identity_digest))
1047 router = router_get_by_hexdigest(intro->extend_info->nickname);
1048 else
1049 router = router_get_by_digest(intro->extend_info->identity_digest);
1050 if (!router) {
1051 log_info(LD_REND, "Unknown router with nickname '%s'; trying another.",
1052 intro->extend_info->nickname);
1053 smartlist_del(usable_nodes, i);
1054 goto again;
1056 extend_info_free(intro->extend_info);
1057 intro->extend_info = extend_info_from_router(router);
1059 /* Check if we should refuse to talk to this router. */
1060 if (options->ExcludeNodes && strict &&
1061 routerset_contains_extendinfo(options->ExcludeNodes,
1062 intro->extend_info)) {
1063 n_excluded++;
1064 smartlist_del(usable_nodes, i);
1065 goto again;
1068 smartlist_free(usable_nodes);
1069 return extend_info_dup(intro->extend_info);
1072 /** Return true iff any introduction points still listed in <b>entry</b> are
1073 * usable. */
1075 rend_client_any_intro_points_usable(const rend_cache_entry_t *entry)
1077 return rend_client_get_random_intro_impl(
1078 entry, get_options()->StrictNodes, 0) != NULL;
1081 /** Client-side authorizations for hidden services; map of onion address to
1082 * rend_service_authorization_t*. */
1083 static strmap_t *auth_hid_servs = NULL;
1085 /** Look up the client-side authorization for the hidden service with
1086 * <b>onion_address</b>. Return NULL if no authorization is available for
1087 * that address. */
1088 rend_service_authorization_t*
1089 rend_client_lookup_service_authorization(const char *onion_address)
1091 tor_assert(onion_address);
1092 if (!auth_hid_servs) return NULL;
1093 return strmap_get(auth_hid_servs, onion_address);
1096 /** Helper: Free storage held by rend_service_authorization_t. */
1097 static void
1098 rend_service_authorization_free(rend_service_authorization_t *auth)
1100 tor_free(auth);
1103 /** Helper for strmap_free. */
1104 static void
1105 rend_service_authorization_strmap_item_free(void *service_auth)
1107 rend_service_authorization_free(service_auth);
1110 /** Release all the storage held in auth_hid_servs.
1112 void
1113 rend_service_authorization_free_all(void)
1115 if (!auth_hid_servs) {
1116 return;
1118 strmap_free(auth_hid_servs, rend_service_authorization_strmap_item_free);
1119 auth_hid_servs = NULL;
1122 /** Parse <b>config_line</b> as a client-side authorization for a hidden
1123 * service and add it to the local map of hidden service authorizations.
1124 * Return 0 for success and -1 for failure. */
1126 rend_parse_service_authorization(or_options_t *options, int validate_only)
1128 config_line_t *line;
1129 int res = -1;
1130 strmap_t *parsed = strmap_new();
1131 smartlist_t *sl = smartlist_create();
1132 rend_service_authorization_t *auth = NULL;
1134 for (line = options->HidServAuth; line; line = line->next) {
1135 char *onion_address, *descriptor_cookie;
1136 char descriptor_cookie_tmp[REND_DESC_COOKIE_LEN+2];
1137 char descriptor_cookie_base64ext[REND_DESC_COOKIE_LEN_BASE64+2+1];
1138 int auth_type_val = 0;
1139 auth = NULL;
1140 SMARTLIST_FOREACH(sl, char *, c, tor_free(c););
1141 smartlist_clear(sl);
1142 smartlist_split_string(sl, line->value, " ",
1143 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
1144 if (smartlist_len(sl) < 2) {
1145 log_warn(LD_CONFIG, "Configuration line does not consist of "
1146 "\"onion-address authorization-cookie [service-name]\": "
1147 "'%s'", line->value);
1148 goto err;
1150 auth = tor_malloc_zero(sizeof(rend_service_authorization_t));
1151 /* Parse onion address. */
1152 onion_address = smartlist_get(sl, 0);
1153 if (strlen(onion_address) != REND_SERVICE_ADDRESS_LEN ||
1154 strcmpend(onion_address, ".onion")) {
1155 log_warn(LD_CONFIG, "Onion address has wrong format: '%s'",
1156 onion_address);
1157 goto err;
1159 strlcpy(auth->onion_address, onion_address, REND_SERVICE_ID_LEN_BASE32+1);
1160 if (!rend_valid_service_id(auth->onion_address)) {
1161 log_warn(LD_CONFIG, "Onion address has wrong format: '%s'",
1162 onion_address);
1163 goto err;
1165 /* Parse descriptor cookie. */
1166 descriptor_cookie = smartlist_get(sl, 1);
1167 if (strlen(descriptor_cookie) != REND_DESC_COOKIE_LEN_BASE64) {
1168 log_warn(LD_CONFIG, "Authorization cookie has wrong length: '%s'",
1169 descriptor_cookie);
1170 goto err;
1172 /* Add trailing zero bytes (AA) to make base64-decoding happy. */
1173 tor_snprintf(descriptor_cookie_base64ext,
1174 REND_DESC_COOKIE_LEN_BASE64+2+1,
1175 "%sAA", descriptor_cookie);
1176 if (base64_decode(descriptor_cookie_tmp, sizeof(descriptor_cookie_tmp),
1177 descriptor_cookie_base64ext,
1178 strlen(descriptor_cookie_base64ext)) < 0) {
1179 log_warn(LD_CONFIG, "Decoding authorization cookie failed: '%s'",
1180 descriptor_cookie);
1181 goto err;
1183 auth_type_val = (descriptor_cookie_tmp[16] >> 4) + 1;
1184 if (auth_type_val < 1 || auth_type_val > 2) {
1185 log_warn(LD_CONFIG, "Authorization cookie has unknown authorization "
1186 "type encoded.");
1187 goto err;
1189 auth->auth_type = auth_type_val == 1 ? REND_BASIC_AUTH : REND_STEALTH_AUTH;
1190 memcpy(auth->descriptor_cookie, descriptor_cookie_tmp,
1191 REND_DESC_COOKIE_LEN);
1192 if (strmap_get(parsed, auth->onion_address)) {
1193 log_warn(LD_CONFIG, "Duplicate authorization for the same hidden "
1194 "service.");
1195 goto err;
1197 strmap_set(parsed, auth->onion_address, auth);
1198 auth = NULL;
1200 res = 0;
1201 goto done;
1202 err:
1203 res = -1;
1204 done:
1205 rend_service_authorization_free(auth);
1206 SMARTLIST_FOREACH(sl, char *, c, tor_free(c););
1207 smartlist_free(sl);
1208 if (!validate_only && res == 0) {
1209 rend_service_authorization_free_all();
1210 auth_hid_servs = parsed;
1211 } else {
1212 strmap_free(parsed, rend_service_authorization_strmap_item_free);
1214 return res;