Revert r13301 and part of r13304. I guess nick's svk messed up.
[tor.git] / src / or / rendservice.c
blob2894702ee9c128973253d5461305d9750f445996
1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007, The Tor Project, Inc. */
3 /* See LICENSE for licensing information */
4 /* $Id$ */
5 const char rendservice_c_id[] =
6 "$Id$";
8 /**
9 * \file rendservice.c
10 * \brief The hidden-service side of rendezvous functionality.
11 **/
13 #include "or.h"
15 static origin_circuit_t *find_intro_circuit(rend_intro_point_t *intro,
16 const char *pk_digest,
17 int desc_version);
19 /** Represents the mapping from a virtual port of a rendezvous service to
20 * a real port on some IP.
22 typedef struct rend_service_port_config_t {
23 uint16_t virtual_port;
24 uint16_t real_port;
25 uint32_t real_addr;
26 } rend_service_port_config_t;
28 /** Try to maintain this many intro points per service if possible. */
29 #define NUM_INTRO_POINTS 3
31 /** If we can't build our intro circuits, don't retry for this long. */
32 #define INTRO_CIRC_RETRY_PERIOD (60*5)
33 /** Don't try to build more than this many circuits before giving up
34 * for a while.*/
35 #define MAX_INTRO_CIRCS_PER_PERIOD 10
36 /** How many times will a hidden service operator attempt to connect to
37 * a requested rendezvous point before giving up? */
38 #define MAX_REND_FAILURES 30
39 /** How many seconds should we spend trying to connect to a requested
40 * rendezvous point before giving up? */
41 #define MAX_REND_TIMEOUT 30
43 /** Represents a single hidden service running at this OP. */
44 typedef struct rend_service_t {
45 /** Fields specified in config file */
46 char *directory; /**< where in the filesystem it stores it */
47 smartlist_t *ports; /**< List of rend_service_port_config_t */
48 char *intro_prefer_nodes; /**< comma-separated list of nicknames */
49 char *intro_exclude_nodes; /**< comma-separated list of nicknames */
50 /* Other fields */
51 crypto_pk_env_t *private_key;
52 char service_id[REND_SERVICE_ID_LEN_BASE32+1];
53 char pk_digest[DIGEST_LEN];
54 smartlist_t *intro_nodes; /**< List of rend_intro_point_t's we have,
55 * or are trying to establish. */
56 time_t intro_period_started;
57 int n_intro_circuits_launched; /**< count of intro circuits we have
58 * established in this period. */
59 /* DOCDOC undocumented versions */
60 rend_service_descriptor_t *desc;
61 time_t desc_is_dirty;
62 time_t next_upload_time;
63 int descriptor_version; /**< Rendezvous descriptor version that will be
64 * published. */
65 } rend_service_t;
67 /** A list of rend_service_t's for services run on this OP.
69 static smartlist_t *rend_service_list = NULL;
71 /** Return the number of rendezvous services we have configured. */
72 int
73 num_rend_services(void)
75 if (!rend_service_list)
76 return 0;
77 return smartlist_len(rend_service_list);
80 /** Release the storage held by <b>service</b>.
82 static void
83 rend_service_free(rend_service_t *service)
85 if (!service) return;
86 tor_free(service->directory);
87 SMARTLIST_FOREACH(service->ports, void*, p, tor_free(p));
88 smartlist_free(service->ports);
89 if (service->private_key)
90 crypto_free_pk_env(service->private_key);
91 if (service->intro_nodes) {
92 SMARTLIST_FOREACH(service->intro_nodes, rend_intro_point_t *, intro,
93 rend_intro_point_free(intro););
94 smartlist_free(service->intro_nodes);
96 tor_free(service->intro_prefer_nodes);
97 tor_free(service->intro_exclude_nodes);
98 if (service->desc)
99 rend_service_descriptor_free(service->desc);
100 tor_free(service);
103 /** Release all the storage held in rend_service_list.
105 void
106 rend_service_free_all(void)
108 if (!rend_service_list) {
109 return;
111 SMARTLIST_FOREACH(rend_service_list, rend_service_t*, ptr,
112 rend_service_free(ptr));
113 smartlist_free(rend_service_list);
114 rend_service_list = NULL;
117 /** Validate <b>service</b> and add it to rend_service_list if possible.
119 static void
120 rend_add_service(rend_service_t *service)
122 int i;
123 rend_service_port_config_t *p;
124 struct in_addr addr;
126 if (!service->intro_prefer_nodes)
127 service->intro_prefer_nodes = tor_strdup("");
128 if (!service->intro_exclude_nodes)
129 service->intro_exclude_nodes = tor_strdup("");
130 service->intro_nodes = smartlist_create();
132 /* If the service is configured to publish unversioned (v0) and versioned
133 * descriptors (v2 or higher), split it up into two separate services. */
134 if (service->descriptor_version == -1) {
135 rend_service_t *v0_service = tor_malloc_zero(sizeof(rend_service_t));
136 v0_service->directory = tor_strdup(service->directory);
137 v0_service->ports = smartlist_create();
138 SMARTLIST_FOREACH(service->ports, rend_service_port_config_t *, p, {
139 rend_service_port_config_t *copy =
140 tor_malloc_zero(sizeof(rend_service_port_config_t));
141 memcpy(copy, p, sizeof(rend_service_port_config_t));
142 smartlist_add(v0_service->ports, copy);
144 v0_service->intro_prefer_nodes = tor_strdup(service->intro_prefer_nodes);
145 v0_service->intro_exclude_nodes = tor_strdup(service->intro_exclude_nodes);
146 v0_service->intro_period_started = service->intro_period_started;
147 v0_service->descriptor_version = 0; /* Unversioned descriptor. */
148 rend_add_service(v0_service);
150 service->descriptor_version = 2; /* Versioned descriptor. */
153 if (!smartlist_len(service->ports)) {
154 log_warn(LD_CONFIG, "Hidden service with no ports configured; ignoring.");
155 rend_service_free(service);
156 } else {
157 smartlist_set_capacity(service->ports, -1);
158 smartlist_add(rend_service_list, service);
159 log_debug(LD_REND,"Configuring service with directory \"%s\"",
160 service->directory);
161 for (i = 0; i < smartlist_len(service->ports); ++i) {
162 char addrbuf[INET_NTOA_BUF_LEN];
163 p = smartlist_get(service->ports, i);
164 addr.s_addr = htonl(p->real_addr);
165 tor_inet_ntoa(&addr, addrbuf, sizeof(addrbuf));
166 log_debug(LD_REND,"Service maps port %d to %s:%d",
167 p->virtual_port, addrbuf, p->real_port);
172 /** Parses a real-port to virtual-port mapping and returns a new
173 * rend_service_port_config_t.
175 * The format is: VirtualPort (IP|RealPort|IP:RealPort)?
177 * IP defaults to 127.0.0.1; RealPort defaults to VirtualPort.
179 static rend_service_port_config_t *
180 parse_port_config(const char *string)
182 smartlist_t *sl;
183 int virtport;
184 int realport;
185 uint16_t p;
186 uint32_t addr;
187 const char *addrport;
188 rend_service_port_config_t *result = NULL;
190 sl = smartlist_create();
191 smartlist_split_string(sl, string, " ",
192 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
193 if (smartlist_len(sl) < 1 || smartlist_len(sl) > 2) {
194 log_warn(LD_CONFIG, "Bad syntax in hidden service port configuration.");
195 goto err;
198 virtport = atoi(smartlist_get(sl,0));
199 if (virtport < 1 || virtport > 65535) {
200 log_warn(LD_CONFIG, "Missing or invalid port in hidden service port "
201 "configuration.");
202 goto err;
205 if (smartlist_len(sl) == 1) {
206 /* No addr:port part; use default. */
207 realport = virtport;
208 addr = 0x7F000001u; /* 127.0.0.1 */
209 } else {
210 addrport = smartlist_get(sl,1);
211 if (strchr(addrport, ':') || strchr(addrport, '.')) {
212 if (parse_addr_port(LOG_WARN, addrport, NULL, &addr, &p)<0) {
213 log_warn(LD_CONFIG,"Unparseable address in hidden service port "
214 "configuration.");
215 goto err;
217 realport = p?p:virtport;
218 } else {
219 /* No addr:port, no addr -- must be port. */
220 realport = atoi(addrport);
221 if (realport < 1 || realport > 65535)
222 goto err;
223 addr = 0x7F000001u; /* Default to 127.0.0.1 */
227 result = tor_malloc(sizeof(rend_service_port_config_t));
228 result->virtual_port = virtport;
229 result->real_port = realport;
230 result->real_addr = addr;
231 err:
232 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
233 smartlist_free(sl);
234 return result;
237 /** Set up rend_service_list, based on the values of HiddenServiceDir and
238 * HiddenServicePort in <b>options</b>. Return 0 on success and -1 on
239 * failure. (If <b>validate_only</b> is set, parse, warn and return as
240 * normal, but don't actually change the configured services.)
243 rend_config_services(or_options_t *options, int validate_only)
245 config_line_t *line;
246 rend_service_t *service = NULL;
247 rend_service_port_config_t *portcfg;
249 if (!validate_only) {
250 rend_service_free_all();
251 rend_service_list = smartlist_create();
254 for (line = options->RendConfigLines; line; line = line->next) {
255 if (!strcasecmp(line->key, "HiddenServiceDir")) {
256 if (service) {
257 if (validate_only)
258 rend_service_free(service);
259 else
260 rend_add_service(service);
262 service = tor_malloc_zero(sizeof(rend_service_t));
263 service->directory = tor_strdup(line->value);
264 service->ports = smartlist_create();
265 service->intro_period_started = time(NULL);
266 service->descriptor_version = -1; /**< All descriptor versions. */
267 continue;
269 if (!service) {
270 log_warn(LD_CONFIG, "%s with no preceding HiddenServiceDir directive",
271 line->key);
272 rend_service_free(service);
273 return -1;
275 if (!strcasecmp(line->key, "HiddenServicePort")) {
276 portcfg = parse_port_config(line->value);
277 if (!portcfg) {
278 rend_service_free(service);
279 return -1;
281 smartlist_add(service->ports, portcfg);
282 } else if (!strcasecmp(line->key, "HiddenServiceNodes")) {
283 if (service->intro_prefer_nodes) {
284 log_warn(LD_CONFIG,
285 "Got multiple HiddenServiceNodes lines for a single "
286 "service.");
287 rend_service_free(service);
288 return -1;
290 service->intro_prefer_nodes = tor_strdup(line->value);
291 } else if (!strcasecmp(line->key, "HiddenServiceExcludeNodes")) {
292 if (service->intro_exclude_nodes) {
293 log_warn(LD_CONFIG,
294 "Got multiple HiddenServiceExcludedNodes lines for "
295 "a single service.");
296 rend_service_free(service);
297 return -1;
299 service->intro_exclude_nodes = tor_strdup(line->value);
300 } else {
301 smartlist_t *versions;
302 char *version_str;
303 int i, version, versions_bitmask = 0;
304 tor_assert(!strcasecmp(line->key, "HiddenServiceVersion"));
305 versions = smartlist_create();
306 smartlist_split_string(versions, line->value, ",",
307 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
308 for (i = 0; i < smartlist_len(versions); i++) {
309 version_str = smartlist_get(versions, i);
310 if (strlen(version_str) != 1 || strspn(version_str, "02") != 1) {
311 log_warn(LD_CONFIG,
312 "HiddenServiceVersion can only be 0 and/or 2.");
313 SMARTLIST_FOREACH(versions, char *, cp, tor_free(cp));
314 smartlist_free(versions);
315 rend_service_free(service);
316 return -1;
318 version = atoi(version_str);
319 versions_bitmask |= 1 << version;
321 /* If exactly one version is set, change descriptor_version to that
322 * value; otherwise leave it at -1. */
323 if (versions_bitmask == 1 << 0) service->descriptor_version = 0;
324 if (versions_bitmask == 1 << 2) service->descriptor_version = 2;
325 SMARTLIST_FOREACH(versions, char *, cp, tor_free(cp));
326 smartlist_free(versions);
329 if (service) {
330 if (validate_only)
331 rend_service_free(service);
332 else
333 rend_add_service(service);
336 return 0;
339 /** Replace the old value of <b>service</b>-\>desc with one that reflects
340 * the other fields in service.
342 static void
343 rend_service_update_descriptor(rend_service_t *service)
345 rend_service_descriptor_t *d;
346 origin_circuit_t *circ;
347 int i;
348 if (service->desc) {
349 rend_service_descriptor_free(service->desc);
350 service->desc = NULL;
352 d = service->desc = tor_malloc_zero(sizeof(rend_service_descriptor_t));
353 d->pk = crypto_pk_dup_key(service->private_key);
354 d->timestamp = time(NULL);
355 d->version = service->descriptor_version;
356 d->intro_nodes = smartlist_create();
357 /* Whoever understands descriptor version 2 also understands intro
358 * protocol 2. So we only support 2. */
359 d->protocols = 1 << 2;
361 for (i = 0; i < smartlist_len(service->intro_nodes); ++i) {
362 rend_intro_point_t *intro_svc = smartlist_get(service->intro_nodes, i);
363 rend_intro_point_t *intro_desc;
364 circ = find_intro_circuit(intro_svc, service->pk_digest, d->version);
365 if (!circ || circ->_base.purpose != CIRCUIT_PURPOSE_S_INTRO)
366 continue;
368 /* We have an entirely established intro circuit. */
369 intro_desc = tor_malloc_zero(sizeof(rend_intro_point_t));
370 intro_desc->extend_info = extend_info_dup(intro_svc->extend_info);
371 if (intro_svc->intro_key)
372 intro_desc->intro_key = crypto_pk_dup_key(intro_svc->intro_key);
373 smartlist_add(d->intro_nodes, intro_desc);
377 /** Load and/or generate private keys for all hidden services. Return 0 on
378 * success, -1 on failure.
381 rend_service_load_keys(void)
383 int i;
384 rend_service_t *s;
385 char fname[512];
386 char buf[128];
388 for (i=0; i < smartlist_len(rend_service_list); ++i) {
389 s = smartlist_get(rend_service_list,i);
390 if (s->private_key)
391 continue;
392 log_info(LD_REND, "Loading hidden-service keys from \"%s\"",
393 s->directory);
395 /* Check/create directory */
396 if (check_private_dir(s->directory, CPD_CREATE) < 0)
397 return -1;
399 /* Load key */
400 if (strlcpy(fname,s->directory,sizeof(fname)) >= sizeof(fname) ||
401 strlcat(fname,PATH_SEPARATOR"private_key",sizeof(fname))
402 >= sizeof(fname)) {
403 log_warn(LD_CONFIG, "Directory name too long to store key file: \"%s\".",
404 s->directory);
405 return -1;
407 s->private_key = init_key_from_file(fname, 1, LOG_ERR);
408 if (!s->private_key)
409 return -1;
411 /* Create service file */
412 if (rend_get_service_id(s->private_key, s->service_id)<0) {
413 log_warn(LD_BUG, "Internal error: couldn't encode service ID.");
414 return -1;
416 if (crypto_pk_get_digest(s->private_key, s->pk_digest)<0) {
417 log_warn(LD_BUG, "Couldn't compute hash of public key.");
418 return -1;
420 if (strlcpy(fname,s->directory,sizeof(fname)) >= sizeof(fname) ||
421 strlcat(fname,PATH_SEPARATOR"hostname",sizeof(fname))
422 >= sizeof(fname)) {
423 log_warn(LD_CONFIG, "Directory name too long to store hostname file:"
424 " \"%s\".", s->directory);
425 return -1;
427 tor_snprintf(buf, sizeof(buf),"%s.onion\n", s->service_id);
428 if (write_str_to_file(fname,buf,0)<0)
429 return -1;
431 return 0;
434 /** Return the service whose public key has a digest of <b>digest</b> and
435 * which publishes the given descriptor <b>version</b>. Return NULL if no
436 * such service exists.
438 static rend_service_t *
439 rend_service_get_by_pk_digest_and_version(const char* digest,
440 uint8_t version)
442 SMARTLIST_FOREACH(rend_service_list, rend_service_t*, s,
443 if (!memcmp(s->pk_digest,digest,DIGEST_LEN) &&
444 s->descriptor_version == version) return s);
445 return NULL;
448 /** Return 1 if any virtual port in <b>service</b> wants a circuit
449 * to have good uptime. Else return 0.
451 static int
452 rend_service_requires_uptime(rend_service_t *service)
454 int i;
455 rend_service_port_config_t *p;
457 for (i=0; i < smartlist_len(service->ports); ++i) {
458 p = smartlist_get(service->ports, i);
459 if (smartlist_string_num_isin(get_options()->LongLivedPorts,
460 p->virtual_port))
461 return 1;
463 return 0;
466 /******
467 * Handle cells
468 ******/
470 /** Respond to an INTRODUCE2 cell by launching a circuit to the chosen
471 * rendezvous point.
474 rend_service_introduce(origin_circuit_t *circuit, const char *request,
475 size_t request_len)
477 char *ptr, *r_cookie;
478 extend_info_t *extend_info = NULL;
479 char buf[RELAY_PAYLOAD_SIZE];
480 char keys[DIGEST_LEN+CPATH_KEY_MATERIAL_LEN]; /* Holds KH, Df, Db, Kf, Kb */
481 rend_service_t *service;
482 int r, i;
483 size_t len, keylen;
484 crypto_dh_env_t *dh = NULL;
485 origin_circuit_t *launched = NULL;
486 crypt_path_t *cpath = NULL;
487 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
488 char hexcookie[9];
489 int circ_needs_uptime;
490 int reason = END_CIRC_REASON_TORPROTOCOL;
491 crypto_pk_env_t *intro_key;
492 char intro_key_digest[DIGEST_LEN];
494 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
495 circuit->rend_pk_digest, REND_SERVICE_ID_LEN);
496 log_info(LD_REND, "Received INTRODUCE2 cell for service %s on circ %d.",
497 escaped(serviceid), circuit->_base.n_circ_id);
499 if (circuit->_base.purpose != CIRCUIT_PURPOSE_S_INTRO) {
500 log_warn(LD_PROTOCOL,
501 "Got an INTRODUCE2 over a non-introduction circuit %d.",
502 circuit->_base.n_circ_id);
503 return -1;
506 /* min key length plus digest length plus nickname length */
507 if (request_len < DIGEST_LEN+REND_COOKIE_LEN+(MAX_NICKNAME_LEN+1)+
508 DH_KEY_LEN+42) {
509 log_warn(LD_PROTOCOL, "Got a truncated INTRODUCE2 cell on circ %d.",
510 circuit->_base.n_circ_id);
511 return -1;
514 /* look up service depending on circuit. */
515 service = rend_service_get_by_pk_digest_and_version(
516 circuit->rend_pk_digest, circuit->rend_desc_version);
517 if (!service) {
518 log_warn(LD_REND, "Got an INTRODUCE2 cell for an unrecognized service %s.",
519 escaped(serviceid));
520 return -1;
523 /* if descriptor version is 2, use intro key instead of service key. */
524 if (circuit->rend_desc_version == 0) {
525 intro_key = service->private_key;
526 } else {
527 intro_key = circuit->intro_key;
530 /* first DIGEST_LEN bytes of request is intro or service pk digest */
531 crypto_pk_get_digest(intro_key, intro_key_digest);
532 if (memcmp(intro_key_digest, request, DIGEST_LEN)) {
533 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
534 request, REND_SERVICE_ID_LEN);
535 log_warn(LD_REND, "Got an INTRODUCE2 cell for the wrong service (%s).",
536 escaped(serviceid));
537 return -1;
540 keylen = crypto_pk_keysize(intro_key);
541 if (request_len < keylen+DIGEST_LEN) {
542 log_warn(LD_PROTOCOL,
543 "PK-encrypted portion of INTRODUCE2 cell was truncated.");
544 return -1;
546 /* Next N bytes is encrypted with service key */
547 note_crypto_pk_op(REND_SERVER);
548 r = crypto_pk_private_hybrid_decrypt(
549 intro_key,buf,request+DIGEST_LEN,request_len-DIGEST_LEN,
550 PK_PKCS1_OAEP_PADDING,1);
551 if (r<0) {
552 log_warn(LD_PROTOCOL, "Couldn't decrypt INTRODUCE2 cell.");
553 return -1;
555 len = r;
556 if (*buf == 2) {
557 /* Version 2 INTRODUCE2 cell. */
558 int klen;
559 extend_info = tor_malloc_zero(sizeof(extend_info_t));
560 extend_info->addr = ntohl(get_uint32(buf+1));
561 extend_info->port = ntohs(get_uint16(buf+5));
562 memcpy(extend_info->identity_digest, buf+7, DIGEST_LEN);
563 extend_info->nickname[0] = '$';
564 base16_encode(extend_info->nickname+1, sizeof(extend_info->nickname)-1,
565 extend_info->identity_digest, DIGEST_LEN);
567 klen = ntohs(get_uint16(buf+7+DIGEST_LEN));
568 if ((int)len != 7+DIGEST_LEN+2+klen+20+128) {
569 log_warn(LD_PROTOCOL, "Bad length %u for version 2 INTRODUCE2 cell.",
570 (int)len);
571 reason = END_CIRC_REASON_TORPROTOCOL;
572 goto err;
574 extend_info->onion_key = crypto_pk_asn1_decode(buf+7+DIGEST_LEN+2, klen);
575 if (!extend_info->onion_key) {
576 log_warn(LD_PROTOCOL,
577 "Error decoding onion key in version 2 INTRODUCE2 cell.");
578 reason = END_CIRC_REASON_TORPROTOCOL;
579 goto err;
581 ptr = buf+7+DIGEST_LEN+2+klen;
582 len -= 7+DIGEST_LEN+2+klen;
583 } else {
584 char *rp_nickname;
585 size_t nickname_field_len;
586 routerinfo_t *router;
587 int version;
588 if (*buf == 1) {
589 rp_nickname = buf+1;
590 nickname_field_len = MAX_HEX_NICKNAME_LEN+1;
591 version = 1;
592 } else {
593 nickname_field_len = MAX_NICKNAME_LEN+1;
594 rp_nickname = buf;
595 version = 0;
597 ptr=memchr(rp_nickname,0,nickname_field_len);
598 if (!ptr || ptr == rp_nickname) {
599 log_warn(LD_PROTOCOL,
600 "Couldn't find a nul-padded nickname in INTRODUCE2 cell.");
601 return -1;
603 if ((version == 0 && !is_legal_nickname(rp_nickname)) ||
604 (version == 1 && !is_legal_nickname_or_hexdigest(rp_nickname))) {
605 log_warn(LD_PROTOCOL, "Bad nickname in INTRODUCE2 cell.");
606 return -1;
608 /* Okay, now we know that a nickname is at the start of the buffer. */
609 ptr = rp_nickname+nickname_field_len;
610 len -= nickname_field_len;
611 len -= rp_nickname - buf; /* also remove header space used by version, if
612 * any */
613 router = router_get_by_nickname(rp_nickname, 0);
614 if (!router) {
615 log_info(LD_REND, "Couldn't find router %s named in introduce2 cell.",
616 escaped_safe_str(rp_nickname));
617 /* XXXX Add a no-such-router reason? */
618 reason = END_CIRC_REASON_TORPROTOCOL;
619 goto err;
622 extend_info = extend_info_from_router(router);
625 if (len != REND_COOKIE_LEN+DH_KEY_LEN) {
626 log_warn(LD_PROTOCOL, "Bad length %u for INTRODUCE2 cell.", (int)len);
627 reason = END_CIRC_REASON_TORPROTOCOL;
628 goto err;
631 r_cookie = ptr;
632 base16_encode(hexcookie,9,r_cookie,4);
634 /* Try DH handshake... */
635 dh = crypto_dh_new();
636 if (!dh || crypto_dh_generate_public(dh)<0) {
637 log_warn(LD_BUG,"Internal error: couldn't build DH state "
638 "or generate public key.");
639 reason = END_CIRC_REASON_INTERNAL;
640 goto err;
642 if (crypto_dh_compute_secret(dh, ptr+REND_COOKIE_LEN, DH_KEY_LEN, keys,
643 DIGEST_LEN+CPATH_KEY_MATERIAL_LEN)<0) {
644 log_warn(LD_BUG, "Internal error: couldn't complete DH handshake");
645 reason = END_CIRC_REASON_INTERNAL;
646 goto err;
649 circ_needs_uptime = rend_service_requires_uptime(service);
651 /* help predict this next time */
652 rep_hist_note_used_internal(time(NULL), circ_needs_uptime, 1);
654 /* Launch a circuit to alice's chosen rendezvous point.
656 for (i=0;i<MAX_REND_FAILURES;i++) {
657 int flags = CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_IS_INTERNAL;
658 if (circ_needs_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
659 launched = circuit_launch_by_extend_info(
660 CIRCUIT_PURPOSE_S_CONNECT_REND, extend_info, flags);
662 if (launched)
663 break;
665 if (!launched) { /* give up */
666 log_warn(LD_REND, "Giving up launching first hop of circuit to rendezvous "
667 "point %s for service %s.",
668 escaped_safe_str(extend_info->nickname), serviceid);
669 reason = END_CIRC_REASON_CONNECTFAILED;
670 goto err;
672 log_info(LD_REND,
673 "Accepted intro; launching circuit to %s "
674 "(cookie %s) for service %s.",
675 escaped_safe_str(extend_info->nickname), hexcookie, serviceid);
676 tor_assert(launched->build_state);
677 /* Fill in the circuit's state. */
678 memcpy(launched->rend_pk_digest, circuit->rend_pk_digest,
679 DIGEST_LEN);
680 memcpy(launched->rend_cookie, r_cookie, REND_COOKIE_LEN);
681 strlcpy(launched->rend_query, service->service_id,
682 sizeof(launched->rend_query));
683 launched->rend_desc_version = service->descriptor_version;
684 launched->build_state->pending_final_cpath = cpath =
685 tor_malloc_zero(sizeof(crypt_path_t));
686 cpath->magic = CRYPT_PATH_MAGIC;
687 launched->build_state->expiry_time = time(NULL) + MAX_REND_TIMEOUT;
689 cpath->dh_handshake_state = dh;
690 dh = NULL;
691 if (circuit_init_cpath_crypto(cpath,keys+DIGEST_LEN,1)<0)
692 goto err;
693 memcpy(cpath->handshake_digest, keys, DIGEST_LEN);
694 if (extend_info) extend_info_free(extend_info);
696 return 0;
697 err:
698 if (dh) crypto_dh_free(dh);
699 if (launched)
700 circuit_mark_for_close(TO_CIRCUIT(launched), reason);
701 if (extend_info) extend_info_free(extend_info);
702 return -1;
705 /** Called when we fail building a rendezvous circuit at some point other
706 * than the last hop: launches a new circuit to the same rendezvous point.
708 void
709 rend_service_relaunch_rendezvous(origin_circuit_t *oldcirc)
711 origin_circuit_t *newcirc;
712 cpath_build_state_t *newstate, *oldstate;
714 tor_assert(oldcirc->_base.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
716 if (!oldcirc->build_state ||
717 oldcirc->build_state->failure_count > MAX_REND_FAILURES ||
718 oldcirc->build_state->expiry_time < time(NULL)) {
719 log_info(LD_REND,
720 "Attempt to build circuit to %s for rendezvous has failed "
721 "too many times or expired; giving up.",
722 oldcirc->build_state ?
723 oldcirc->build_state->chosen_exit->nickname : "*unknown*");
724 return;
727 oldstate = oldcirc->build_state;
728 tor_assert(oldstate);
730 if (oldstate->pending_final_cpath == NULL) {
731 log_info(LD_REND,"Skipping relaunch of circ that failed on its first hop. "
732 "Initiator will retry.");
733 return;
736 log_info(LD_REND,"Reattempting rendezvous circuit to '%s'",
737 oldstate->chosen_exit->nickname);
739 newcirc = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_CONNECT_REND,
740 oldstate->chosen_exit,
741 CIRCLAUNCH_NEED_CAPACITY|CIRCLAUNCH_IS_INTERNAL);
743 if (!newcirc) {
744 log_warn(LD_REND,"Couldn't relaunch rendezvous circuit to '%s'.",
745 oldstate->chosen_exit->nickname);
746 return;
748 newstate = newcirc->build_state;
749 tor_assert(newstate);
750 newstate->failure_count = oldstate->failure_count+1;
751 newstate->expiry_time = oldstate->expiry_time;
752 newstate->pending_final_cpath = oldstate->pending_final_cpath;
753 oldstate->pending_final_cpath = NULL;
755 memcpy(newcirc->rend_query, oldcirc->rend_query,
756 REND_SERVICE_ID_LEN_BASE32+1);
757 memcpy(newcirc->rend_pk_digest, oldcirc->rend_pk_digest,
758 DIGEST_LEN);
759 memcpy(newcirc->rend_cookie, oldcirc->rend_cookie,
760 REND_COOKIE_LEN);
761 newcirc->rend_desc_version = oldcirc->rend_desc_version;
764 /** Launch a circuit to serve as an introduction point for the service
765 * <b>service</b> at the introduction point <b>nickname</b>
767 static int
768 rend_service_launch_establish_intro(rend_service_t *service,
769 rend_intro_point_t *intro)
771 origin_circuit_t *launched;
773 log_info(LD_REND,
774 "Launching circuit to introduction point %s for service %s",
775 escaped_safe_str(intro->extend_info->nickname),
776 service->service_id);
778 rep_hist_note_used_internal(time(NULL), 1, 0);
780 ++service->n_intro_circuits_launched;
781 launched = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_ESTABLISH_INTRO,
782 intro->extend_info,
783 CIRCLAUNCH_NEED_UPTIME|CIRCLAUNCH_IS_INTERNAL);
785 if (!launched) {
786 log_info(LD_REND,
787 "Can't launch circuit to establish introduction at %s.",
788 escaped_safe_str(intro->extend_info->nickname));
789 return -1;
791 strlcpy(launched->rend_query, service->service_id,
792 sizeof(launched->rend_query));
793 memcpy(launched->rend_pk_digest, service->pk_digest, DIGEST_LEN);
794 launched->rend_desc_version = service->descriptor_version;
795 if (service->descriptor_version == 2)
796 launched->intro_key = crypto_pk_dup_key(intro->intro_key);
797 if (launched->_base.state == CIRCUIT_STATE_OPEN)
798 rend_service_intro_has_opened(launched);
799 return 0;
802 /** Called when we're done building a circuit to an introduction point:
803 * sends a RELAY_ESTABLISH_INTRO cell.
805 void
806 rend_service_intro_has_opened(origin_circuit_t *circuit)
808 rend_service_t *service;
809 size_t len;
810 int r;
811 char buf[RELAY_PAYLOAD_SIZE];
812 char auth[DIGEST_LEN + 9];
813 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
814 int reason = END_CIRC_REASON_TORPROTOCOL;
815 crypto_pk_env_t *intro_key;
817 tor_assert(circuit->_base.purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO);
818 tor_assert(circuit->cpath);
820 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
821 circuit->rend_pk_digest, REND_SERVICE_ID_LEN);
823 service = rend_service_get_by_pk_digest_and_version(
824 circuit->rend_pk_digest, circuit->rend_desc_version);
825 if (!service) {
826 log_warn(LD_REND, "Unrecognized service ID %s on introduction circuit %d.",
827 serviceid, circuit->_base.n_circ_id);
828 reason = END_CIRC_REASON_NOSUCHSERVICE;
829 goto err;
832 log_info(LD_REND,
833 "Established circuit %d as introduction point for service %s",
834 circuit->_base.n_circ_id, serviceid);
836 /* If the introduction point will not be used in an unversioned
837 * descriptor, use the intro key instead of the service key in
838 * ESTABLISH_INTRO. */
839 if (service->descriptor_version == 0)
840 intro_key = service->private_key;
841 else
842 intro_key = circuit->intro_key;
843 /* Build the payload for a RELAY_ESTABLISH_INTRO cell. */
844 len = crypto_pk_asn1_encode(intro_key, buf+2,
845 RELAY_PAYLOAD_SIZE-2);
846 set_uint16(buf, htons((uint16_t)len));
847 len += 2;
848 memcpy(auth, circuit->cpath->prev->handshake_digest, DIGEST_LEN);
849 memcpy(auth+DIGEST_LEN, "INTRODUCE", 9);
850 if (crypto_digest(buf+len, auth, DIGEST_LEN+9))
851 goto err;
852 len += 20;
853 note_crypto_pk_op(REND_SERVER);
854 r = crypto_pk_private_sign_digest(intro_key, buf+len, buf, len);
855 if (r<0) {
856 log_warn(LD_BUG, "Internal error: couldn't sign introduction request.");
857 reason = END_CIRC_REASON_INTERNAL;
858 goto err;
860 len += r;
862 if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
863 RELAY_COMMAND_ESTABLISH_INTRO,
864 buf, len, circuit->cpath->prev)<0) {
865 log_info(LD_GENERAL,
866 "Couldn't send introduction request for service %s on circuit %d",
867 serviceid, circuit->_base.n_circ_id);
868 reason = END_CIRC_REASON_INTERNAL;
869 goto err;
872 return;
873 err:
874 circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
877 /** Called when we get an INTRO_ESTABLISHED cell; mark the circuit as a
878 * live introduction point, and note that the service descriptor is
879 * now out-of-date.*/
881 rend_service_intro_established(origin_circuit_t *circuit, const char *request,
882 size_t request_len)
884 rend_service_t *service;
885 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
886 (void) request;
887 (void) request_len;
889 if (circuit->_base.purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO) {
890 log_warn(LD_PROTOCOL,
891 "received INTRO_ESTABLISHED cell on non-intro circuit.");
892 goto err;
894 service = rend_service_get_by_pk_digest_and_version(
895 circuit->rend_pk_digest, circuit->rend_desc_version);
896 if (!service) {
897 log_warn(LD_REND, "Unknown service on introduction circuit %d.",
898 circuit->_base.n_circ_id);
899 goto err;
901 service->desc_is_dirty = time(NULL);
902 circuit->_base.purpose = CIRCUIT_PURPOSE_S_INTRO;
904 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32 + 1,
905 circuit->rend_pk_digest, REND_SERVICE_ID_LEN);
906 log_info(LD_REND,
907 "Received INTRO_ESTABLISHED cell on circuit %d for service %s",
908 circuit->_base.n_circ_id, serviceid);
910 return 0;
911 err:
912 circuit_mark_for_close(TO_CIRCUIT(circuit), END_CIRC_REASON_TORPROTOCOL);
913 return -1;
916 /** Called once a circuit to a rendezvous point is established: sends a
917 * RELAY_COMMAND_RENDEZVOUS1 cell.
919 void
920 rend_service_rendezvous_has_opened(origin_circuit_t *circuit)
922 rend_service_t *service;
923 char buf[RELAY_PAYLOAD_SIZE];
924 crypt_path_t *hop;
925 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
926 char hexcookie[9];
927 int reason;
929 tor_assert(circuit->_base.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
930 tor_assert(circuit->cpath);
931 tor_assert(circuit->build_state);
932 hop = circuit->build_state->pending_final_cpath;
933 tor_assert(hop);
935 base16_encode(hexcookie,9,circuit->rend_cookie,4);
936 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
937 circuit->rend_pk_digest, REND_SERVICE_ID_LEN);
939 log_info(LD_REND,
940 "Done building circuit %d to rendezvous with "
941 "cookie %s for service %s",
942 circuit->_base.n_circ_id, hexcookie, serviceid);
944 service = rend_service_get_by_pk_digest_and_version(
945 circuit->rend_pk_digest, circuit->rend_desc_version);
946 if (!service) {
947 log_warn(LD_GENERAL, "Internal error: unrecognized service ID on "
948 "introduction circuit.");
949 reason = END_CIRC_REASON_INTERNAL;
950 goto err;
953 /* All we need to do is send a RELAY_RENDEZVOUS1 cell... */
954 memcpy(buf, circuit->rend_cookie, REND_COOKIE_LEN);
955 if (crypto_dh_get_public(hop->dh_handshake_state,
956 buf+REND_COOKIE_LEN, DH_KEY_LEN)<0) {
957 log_warn(LD_GENERAL,"Couldn't get DH public key.");
958 reason = END_CIRC_REASON_INTERNAL;
959 goto err;
961 memcpy(buf+REND_COOKIE_LEN+DH_KEY_LEN, hop->handshake_digest,
962 DIGEST_LEN);
964 /* Send the cell */
965 if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
966 RELAY_COMMAND_RENDEZVOUS1,
967 buf, REND_COOKIE_LEN+DH_KEY_LEN+DIGEST_LEN,
968 circuit->cpath->prev)<0) {
969 log_warn(LD_GENERAL, "Couldn't send RENDEZVOUS1 cell.");
970 reason = END_CIRC_REASON_INTERNAL;
971 goto err;
974 crypto_dh_free(hop->dh_handshake_state);
975 hop->dh_handshake_state = NULL;
977 /* Append the cpath entry. */
978 hop->state = CPATH_STATE_OPEN;
979 /* set the windows to default. these are the windows
980 * that bob thinks alice has.
982 hop->package_window = CIRCWINDOW_START;
983 hop->deliver_window = CIRCWINDOW_START;
985 onion_append_to_cpath(&circuit->cpath, hop);
986 circuit->build_state->pending_final_cpath = NULL; /* prevent double-free */
988 /* Change the circuit purpose. */
989 circuit->_base.purpose = CIRCUIT_PURPOSE_S_REND_JOINED;
991 return;
992 err:
993 circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
997 * Manage introduction points
1000 /** Return the (possibly non-open) introduction circuit ending at
1001 * <b>intro</b> for the service whose public key is <b>pk_digest</b> and
1002 * which publishes descriptor of version <b>desc_version</b>. Return
1003 * NULL if no such service is found.
1005 static origin_circuit_t *
1006 find_intro_circuit(rend_intro_point_t *intro, const char *pk_digest,
1007 int desc_version)
1009 origin_circuit_t *circ = NULL;
1011 tor_assert(intro);
1012 while ((circ = circuit_get_next_by_pk_and_purpose(circ,pk_digest,
1013 CIRCUIT_PURPOSE_S_INTRO))) {
1014 if (!strcasecmp(circ->build_state->chosen_exit->identity_digest,
1015 intro->extend_info->identity_digest) &&
1016 circ->rend_desc_version == desc_version) {
1017 return circ;
1021 circ = NULL;
1022 while ((circ = circuit_get_next_by_pk_and_purpose(circ,pk_digest,
1023 CIRCUIT_PURPOSE_S_ESTABLISH_INTRO))) {
1024 if (!strcasecmp(circ->build_state->chosen_exit->identity_digest,
1025 intro->extend_info->identity_digest) &&
1026 circ->rend_desc_version == desc_version) {
1027 return circ;
1030 return NULL;
1033 /** Determine the responsible hidden service directories for the
1034 * rend_encoded_v2_service_descriptor_t's in <b>descs</b> and upload them;
1035 * <b>service_id</b> and <b>seconds_valid</b> are only passed for logging
1036 * purposes. */
1037 static void
1038 directory_post_to_hs_dir(smartlist_t *descs, const char *service_id,
1039 int seconds_valid)
1041 int i, j;
1042 smartlist_t *responsible_dirs = smartlist_create();
1043 routerstatus_t *hs_dir;
1044 for (i = 0; i < smartlist_len(descs); i++) {
1045 rend_encoded_v2_service_descriptor_t *desc = smartlist_get(descs, i);
1046 /* Determine responsible dirs. */
1047 if (hid_serv_get_responsible_directories(responsible_dirs,
1048 desc->desc_id) < 0) {
1049 log_warn(LD_REND, "Could not determine the responsible hidden service "
1050 "directories to post descriptors to.");
1051 smartlist_free(responsible_dirs);
1052 return;
1054 for (j = 0; j < smartlist_len(responsible_dirs); j++) {
1055 char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
1056 hs_dir = smartlist_get(responsible_dirs, j);
1057 /* Send publish request. */
1058 directory_initiate_command_routerstatus(hs_dir,
1059 DIR_PURPOSE_UPLOAD_RENDDESC_V2,
1060 ROUTER_PURPOSE_GENERAL,
1061 1, NULL, desc->desc_str,
1062 strlen(desc->desc_str), 0);
1063 base32_encode(desc_id_base32, sizeof(desc_id_base32),
1064 desc->desc_id, DIGEST_LEN);
1065 log_info(LD_REND, "Sending publish request for v2 descriptor for "
1066 "service '%s' with descriptor ID '%s' with validity "
1067 "of %d seconds to hidden service directory '%s' on "
1068 "port %d.",
1069 service_id,
1070 desc_id_base32,
1071 seconds_valid,
1072 hs_dir->nickname,
1073 hs_dir->dir_port);
1075 smartlist_clear(responsible_dirs);
1077 smartlist_free(responsible_dirs);
1080 /** Encode and sign up-to-date v0 and/or v2 service descriptors for
1081 * <b>service</b>, and upload it/them to all the dirservers/to the
1082 * responsible hidden service directories.
1084 static void
1085 upload_service_descriptor(rend_service_t *service)
1087 time_t now = time(NULL);
1088 int rendpostperiod;
1089 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
1090 int uploaded = 0;
1092 /* Update the descriptor. */
1093 rend_service_update_descriptor(service);
1095 rendpostperiod = get_options()->RendPostPeriod;
1097 /* Upload unversioned (v0) descriptor? */
1098 if (service->descriptor_version == 0 &&
1099 get_options()->PublishHidServDescriptors) {
1100 char *desc;
1101 size_t desc_len;
1102 /* Encode the descriptor. */
1103 if (rend_encode_service_descriptor(service->desc,
1104 service->private_key,
1105 &desc, &desc_len)<0) {
1106 log_warn(LD_BUG, "Internal error: couldn't encode service descriptor; "
1107 "not uploading.");
1108 return;
1111 /* Post it to the dirservers */
1112 rend_get_service_id(service->desc->pk, serviceid);
1113 log_info(LD_REND, "Sending publish request for hidden service %s",
1114 serviceid);
1115 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_RENDDESC,
1116 ROUTER_PURPOSE_GENERAL,
1117 HIDSERV_AUTHORITY, desc, desc_len, 0);
1118 tor_free(desc);
1119 service->next_upload_time = now + rendpostperiod;
1120 uploaded = 1;
1123 /* Upload v2 descriptor? */
1124 if (service->descriptor_version == 2 &&
1125 get_options()->PublishHidServDescriptors) {
1126 networkstatus_vote_t *c = networkstatus_get_latest_consensus();
1127 if (c && smartlist_len(c->routerstatus_list) > 0) {
1128 int seconds_valid;
1129 smartlist_t *descs = smartlist_create();
1130 int i;
1131 /* Encode the current descriptor. */
1132 seconds_valid = rend_encode_v2_descriptors(descs, service->desc, now,
1133 NULL, 0);
1134 if (seconds_valid < 0) {
1135 log_warn(LD_BUG, "Internal error: couldn't encode service descriptor; "
1136 "not uploading.");
1137 smartlist_free(descs);
1138 return;
1140 /* Post the current descriptors to the hidden service directories. */
1141 rend_get_service_id(service->desc->pk, serviceid);
1142 log_info(LD_REND, "Sending publish request for hidden service %s",
1143 serviceid);
1144 directory_post_to_hs_dir(descs, serviceid, seconds_valid);
1145 /* Free memory for descriptors. */
1146 for (i = 0; i < smartlist_len(descs); i++)
1147 rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
1148 smartlist_clear(descs);
1149 /* Update next upload time. */
1150 if (seconds_valid - REND_TIME_PERIOD_OVERLAPPING_V2_DESCS
1151 > rendpostperiod)
1152 service->next_upload_time = now + rendpostperiod;
1153 else if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS)
1154 service->next_upload_time = now + seconds_valid + 1;
1155 else
1156 service->next_upload_time = now + seconds_valid -
1157 REND_TIME_PERIOD_OVERLAPPING_V2_DESCS + 1;
1158 /* Post also the next descriptors, if necessary. */
1159 if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS) {
1160 seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
1161 now, NULL, 1);
1162 if (seconds_valid < 0) {
1163 log_warn(LD_BUG, "Internal error: couldn't encode service "
1164 "descriptor; not uploading.");
1165 smartlist_free(descs);
1166 return;
1168 directory_post_to_hs_dir(descs, serviceid, seconds_valid);
1169 /* Free memory for descriptors. */
1170 for (i = 0; i < smartlist_len(descs); i++)
1171 rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
1173 smartlist_free(descs);
1174 uploaded = 1;
1175 log_info(LD_REND, "Successfully uploaded v2 rend descriptors!");
1179 /* If not uploaded, try again in one minute. */
1180 if (!uploaded)
1181 service->next_upload_time = now + 60;
1183 /* Unmark dirty flag of this service. */
1184 service->desc_is_dirty = 0;
1187 /** For every service, check how many intro points it currently has, and:
1188 * - Pick new intro points as necessary.
1189 * - Launch circuits to any new intro points.
1191 void
1192 rend_services_introduce(void)
1194 int i,j,r;
1195 routerinfo_t *router;
1196 rend_service_t *service;
1197 rend_intro_point_t *intro;
1198 int changed, prev_intro_nodes;
1199 smartlist_t *intro_routers, *exclude_routers;
1200 time_t now;
1202 intro_routers = smartlist_create();
1203 exclude_routers = smartlist_create();
1204 now = time(NULL);
1206 for (i=0; i < smartlist_len(rend_service_list); ++i) {
1207 smartlist_clear(intro_routers);
1208 service = smartlist_get(rend_service_list, i);
1210 tor_assert(service);
1211 changed = 0;
1212 if (now > service->intro_period_started+INTRO_CIRC_RETRY_PERIOD) {
1213 /* One period has elapsed; we can try building circuits again. */
1214 service->intro_period_started = now;
1215 service->n_intro_circuits_launched = 0;
1216 } else if (service->n_intro_circuits_launched >=
1217 MAX_INTRO_CIRCS_PER_PERIOD) {
1218 /* We have failed too many times in this period; wait for the next
1219 * one before we try again. */
1220 continue;
1223 /* Find out which introduction points we have in progress for this
1224 service. */
1225 for (j=0; j < smartlist_len(service->intro_nodes); ++j) {
1226 intro = smartlist_get(service->intro_nodes, j);
1227 router = router_get_by_digest(intro->extend_info->identity_digest);
1228 if (!router || !find_intro_circuit(intro, service->pk_digest,
1229 service->descriptor_version)) {
1230 log_info(LD_REND,"Giving up on %s as intro point for %s.",
1231 intro->extend_info->nickname, service->service_id);
1232 rend_intro_point_free(intro);
1233 smartlist_del(service->intro_nodes,j--);
1234 changed = 1;
1235 service->desc_is_dirty = now;
1237 smartlist_add(intro_routers, router);
1240 /* We have enough intro points, and the intro points we thought we had were
1241 * all connected.
1243 if (!changed && smartlist_len(service->intro_nodes) >= NUM_INTRO_POINTS) {
1244 /* We have all our intro points! Start a fresh period and reset the
1245 * circuit count. */
1246 service->intro_period_started = now;
1247 service->n_intro_circuits_launched = 0;
1248 continue;
1251 /* Remember how many introduction circuits we started with. */
1252 prev_intro_nodes = smartlist_len(service->intro_nodes);
1254 smartlist_add_all(exclude_routers, intro_routers);
1255 /* The directory is now here. Pick three ORs as intro points. */
1256 for (j=prev_intro_nodes; j < NUM_INTRO_POINTS; ++j) {
1257 router = router_choose_random_node(service->intro_prefer_nodes,
1258 service->intro_exclude_nodes, exclude_routers, 1, 0, 0,
1259 get_options()->_AllowInvalid & ALLOW_INVALID_INTRODUCTION,
1260 0, 0);
1261 if (!router) {
1262 log_warn(LD_REND,
1263 "Could only establish %d introduction points for %s.",
1264 smartlist_len(service->intro_nodes), service->service_id);
1265 break;
1267 changed = 1;
1268 smartlist_add(intro_routers, router);
1269 smartlist_add(exclude_routers, router);
1270 intro = tor_malloc_zero(sizeof(rend_intro_point_t));
1271 intro->extend_info = extend_info_from_router(router);
1272 if (service->descriptor_version == 2) {
1273 intro->intro_key = crypto_new_pk_env();
1274 tor_assert(!crypto_pk_generate_key(intro->intro_key));
1276 smartlist_add(service->intro_nodes, intro);
1277 log_info(LD_REND, "Picked router %s as an intro point for %s.",
1278 router->nickname, service->service_id);
1281 /* Reset exclude_routers, for the next time around the loop. */
1282 smartlist_clear(exclude_routers);
1284 /* If there's no need to launch new circuits, stop here. */
1285 if (!changed)
1286 continue;
1288 /* Establish new introduction points. */
1289 for (j=prev_intro_nodes; j < smartlist_len(service->intro_nodes); ++j) {
1290 intro = smartlist_get(service->intro_nodes, j);
1291 r = rend_service_launch_establish_intro(service, intro);
1292 if (r<0) {
1293 log_warn(LD_REND, "Error launching circuit to node %s for service %s.",
1294 intro->extend_info->nickname, service->service_id);
1298 smartlist_free(intro_routers);
1299 smartlist_free(exclude_routers);
1302 /** Regenerate and upload rendezvous service descriptors for all
1303 * services, if necessary. If the descriptor has been dirty enough
1304 * for long enough, definitely upload; else only upload when the
1305 * periodic timeout has expired.
1307 * For the first upload, pick a random time between now and two periods
1308 * from now, and pick it independently for each service.
1310 void
1311 rend_consider_services_upload(time_t now)
1313 int i;
1314 rend_service_t *service;
1315 int rendpostperiod = get_options()->RendPostPeriod;
1317 if (!get_options()->PublishHidServDescriptors)
1318 return;
1320 for (i=0; i < smartlist_len(rend_service_list); ++i) {
1321 service = smartlist_get(rend_service_list, i);
1322 if (!service->next_upload_time) { /* never been uploaded yet */
1323 service->next_upload_time =
1324 now + crypto_rand_int(2*rendpostperiod);
1326 if (service->next_upload_time < now ||
1327 (service->desc_is_dirty &&
1328 service->desc_is_dirty < now-30)) {
1329 /* if it's time, or if the directory servers have a wrong service
1330 * descriptor and ours has been stable for 30 seconds, upload a
1331 * new one of each format. */
1332 upload_service_descriptor(service);
1337 /** Log the status of introduction points for all rendezvous services
1338 * at log severity <b>severity</b>.
1340 void
1341 rend_service_dump_stats(int severity)
1343 int i,j;
1344 rend_service_t *service;
1345 rend_intro_point_t *intro;
1346 const char *safe_name;
1347 origin_circuit_t *circ;
1349 for (i=0; i < smartlist_len(rend_service_list); ++i) {
1350 service = smartlist_get(rend_service_list, i);
1351 log(severity, LD_GENERAL, "Service configured in \"%s\":",
1352 service->directory);
1353 for (j=0; j < smartlist_len(service->intro_nodes); ++j) {
1354 intro = smartlist_get(service->intro_nodes, j);
1355 safe_name = safe_str(intro->extend_info->nickname);
1357 circ = find_intro_circuit(intro, service->pk_digest,
1358 service->descriptor_version);
1359 if (!circ) {
1360 log(severity, LD_GENERAL, " Intro point %d at %s: no circuit",
1361 j, safe_name);
1362 continue;
1364 log(severity, LD_GENERAL, " Intro point %d at %s: circuit is %s",
1365 j, safe_name, circuit_state_to_string(circ->_base.state));
1370 /** Given <b>conn</b>, a rendezvous exit stream, look up the hidden service for
1371 * 'circ', and look up the port and address based on conn-\>port.
1372 * Assign the actual conn-\>addr and conn-\>port. Return -1 if failure,
1373 * or 0 for success.
1376 rend_service_set_connection_addr_port(edge_connection_t *conn,
1377 origin_circuit_t *circ)
1379 rend_service_t *service;
1380 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
1381 smartlist_t *matching_ports;
1382 rend_service_port_config_t *chosen_port;
1384 tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_S_REND_JOINED);
1385 log_debug(LD_REND,"beginning to hunt for addr/port");
1386 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
1387 circ->rend_pk_digest, REND_SERVICE_ID_LEN);
1388 service = rend_service_get_by_pk_digest_and_version(circ->rend_pk_digest,
1389 circ->rend_desc_version);
1390 if (!service) {
1391 log_warn(LD_REND, "Couldn't find any service associated with pk %s on "
1392 "rendezvous circuit %d; closing.",
1393 serviceid, circ->_base.n_circ_id);
1394 return -1;
1396 matching_ports = smartlist_create();
1397 SMARTLIST_FOREACH(service->ports, rend_service_port_config_t *, p,
1399 if (conn->_base.port == p->virtual_port) {
1400 smartlist_add(matching_ports, p);
1403 chosen_port = smartlist_choose(matching_ports);
1404 smartlist_free(matching_ports);
1405 if (chosen_port) {
1406 conn->_base.addr = chosen_port->real_addr;
1407 conn->_base.port = chosen_port->real_port;
1408 return 0;
1410 log_info(LD_REND, "No virtual port mapping exists for port %d on service %s",
1411 conn->_base.port,serviceid);
1412 return -1;