-big commit, make new ns and valgrind happy
[oweals/gnunet.git] / src / gns / gnunet-service-gns.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009, 2010, 2011 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  *
23  * @file gns/gnunet-service-gns.c
24  * @brief GNUnet GNS service
25  * @author Martin Schanzenbach
26  */
27 #include "platform.h"
28 #include "gnunet_util_lib.h"
29 #include "gnunet_transport_service.h"
30 #include "gnunet_dns_service.h"
31 #include "gnunet_dnsparser_lib.h"
32 #include "gnunet_dht_service.h"
33 #include "gnunet_namestore_service.h"
34 #include "gnunet_gns_service.h"
35 #include "block_gns.h"
36 #include "gns.h"
37 #include "gnunet-service-gns_resolver.h"
38 #include "gnunet-service-gns_interceptor.h"
39
40 /* FIXME move to proper header in include */
41 #define GNUNET_MESSAGE_TYPE_GNS_LOOKUP 23
42 #define GNUNET_MESSAGE_TYPE_GNS_LOOKUP_RESULT 24
43 #define GNUNET_MESSAGE_TYPE_GNS_SHORTEN 25
44 #define GNUNET_MESSAGE_TYPE_GNS_SHORTEN_RESULT 26
45 #define GNUNET_MESSAGE_TYPE_GNS_GET_AUTH 27
46 #define GNUNET_MESSAGE_TYPE_GNS_GET_AUTH_RESULT 28
47
48
49 /**
50  * Handle to a shorten operation from api
51  */
52 struct ClientShortenHandle
53 {
54   /* the requesting client that */
55   struct GNUNET_SERVER_Client *client;
56
57   /* request id */
58   uint64_t unique_id;
59
60   /* request type */
61   enum GNUNET_GNS_RecordType type;
62
63   /* optional zone private key used for shorten */
64   struct GNUNET_CRYPTO_RsaPrivateKey *shorten_key;
65   
66   /* name to shorten */
67   char name[MAX_DNS_NAME_LENGTH];
68
69   /* root zone */
70   struct GNUNET_CRYPTO_ShortHashCode root_zone;
71
72   /* private zone */
73   struct GNUNET_CRYPTO_ShortHashCode private_zone;
74   
75   /* shorten zone */
76   struct GNUNET_CRYPTO_ShortHashCode shorten_zone;
77 };
78
79
80 /**
81  * Handle to a get auhtority operation from api
82  */
83 struct ClientGetAuthHandle
84 {
85   /* the requesting client that */
86   struct GNUNET_SERVER_Client *client;
87
88   /* request id */
89   uint64_t unique_id;
90
91   /* name to lookup authority */
92   char* name;
93
94 };
95
96
97 /**
98  * Handle to a lookup operation from api
99  */
100 struct ClientLookupHandle
101 {
102   /* the requesting client that */
103   struct GNUNET_SERVER_Client *client;
104
105   /* The zone we look up in */
106   struct GNUNET_CRYPTO_ShortHashCode zone;
107
108   /* Do we only want to lookup from local cache? */
109   int only_cached;
110
111   /* request id */
112   uint64_t unique_id;
113
114   /* request type */
115   enum GNUNET_GNS_RecordType type;
116
117   /* optional zone private key used for shorten */
118   struct GNUNET_CRYPTO_RsaPrivateKey *shorten_key;
119
120   /* the name to look up */
121   char* name; //Needed?
122 };
123
124 /**
125  * Our handle to the DHT
126  */
127 static struct GNUNET_DHT_Handle *dht_handle;
128
129 /**
130  * Our zone's private key
131  */
132 struct GNUNET_CRYPTO_RsaPrivateKey *zone_key;
133
134 /**
135  * Our handle to the namestore service
136  * FIXME maybe need a second handle for iteration
137  */
138 struct GNUNET_NAMESTORE_Handle *namestore_handle;
139
140 /**
141  * Handle to iterate over our authoritative zone in namestore
142  */
143 struct GNUNET_NAMESTORE_ZoneIterator *namestore_iter;
144
145 /**
146  * The configuration the GNS service is running with
147  */
148 const struct GNUNET_CONFIGURATION_Handle *GNS_cfg;
149
150 /**
151  * Our notification context.
152  */
153 static struct GNUNET_SERVER_NotificationContext *nc;
154
155 /**
156  * Our zone hash
157  */
158 struct GNUNET_CRYPTO_ShortHashCode zone_hash;
159
160 /**
161  * Useful for zone update for DHT put
162  */
163 static int num_public_records;
164
165 /**
166  * update interval in seconds
167  */
168 static unsigned long long max_record_put_interval;
169
170 static unsigned long long dht_max_update_interval;
171
172 /* dht update interval FIXME define? */
173 static struct GNUNET_TIME_Relative record_put_interval;
174
175 /* zone update task */
176 GNUNET_SCHEDULER_TaskIdentifier zone_update_taskid = GNUNET_SCHEDULER_NO_TASK;
177
178 /* automatic pkey import for name shortening */
179 static int auto_import_pkey;
180
181 /* lookup timeout */
182 static struct GNUNET_TIME_Relative default_lookup_timeout;
183
184 /* name of the private zone */
185 static char *private_zone_id;
186
187 /* name of the public zone */
188 static char *shorten_zone_id;
189
190 /* ipv6 support */
191 static int v6_enabled;
192
193 /* ipv4 support */
194 static int v4_enabled;
195
196 /**
197  * Continue shutdown
198  */
199 static void
200 on_resolver_cleanup(void)
201 {
202   if (NULL != namestore_iter)
203     GNUNET_NAMESTORE_zone_iteration_stop (namestore_iter);
204   GNUNET_NAMESTORE_disconnect(namestore_handle);
205   GNUNET_DHT_disconnect(dht_handle);
206 }
207
208 /**
209  * Task run during shutdown.
210  *
211  * @param cls unused
212  * @param tc unused
213  */
214 static void
215 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
216 {
217
218   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
219              "Shutting down!");
220   
221   
222   GNUNET_SERVER_notification_context_destroy (nc);
223   
224   gns_interceptor_stop();
225   gns_resolver_cleanup(&on_resolver_cleanup);
226   /* Kill zone task for it may make the scheduler hang */
227   if (zone_update_taskid != GNUNET_SCHEDULER_NO_TASK)
228     GNUNET_SCHEDULER_cancel(zone_update_taskid);
229 }
230
231
232 /**
233  * Method called periodicattluy that triggers
234  * iteration over root zone
235  *
236  * @param cls closure
237  * @param tc task context
238  */
239 static void
240 update_zone_dht_next(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
241 {
242   zone_update_taskid = GNUNET_SCHEDULER_NO_TASK;
243   GNUNET_NAMESTORE_zone_iterator_next (namestore_iter);
244 }
245
246 /**
247  * Continuation for DHT put
248  *
249  * @param cls closure
250  * @param success GNUNET_OK if the PUT was transmitted,
251  *                GNUNET_NO on timeout,
252  *                GNUNET_SYSERR on disconnect from service
253  *                after the PUT message was transmitted
254  *                (so we don't know if it was received or not)
255  */
256 static void
257 record_dht_put(void *cls, int success)
258 {
259   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "put request transmitted\n");
260 }
261
262 /* prototype */
263 static void
264 update_zone_dht_start(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
265
266 /**
267  * Function used to put all records successively into the DHT.
268  *
269  * @param cls the closure (NULL)
270  * @param key the public key of the authority (ours)
271  * @param expiration lifetime of the namestore entry
272  * @param name the name of the records
273  * @param rd_count the number of records in data
274  * @param rd the record data
275  * @param signature the signature for the record data
276  */
277 static void
278 put_gns_record(void *cls,
279                 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
280                 struct GNUNET_TIME_Absolute expiration,
281                 const char *name,
282                 unsigned int rd_count,
283                 const struct GNUNET_NAMESTORE_RecordData *rd,
284                 const struct GNUNET_CRYPTO_RsaSignature *signature)
285 {
286   
287   struct GNSNameRecordBlock *nrb;
288   struct GNUNET_CRYPTO_ShortHashCode name_hash;
289   struct GNUNET_CRYPTO_ShortHashCode zhash;
290   struct GNUNET_HashCode xor_hash;
291   struct GNUNET_HashCode name_hash_double;
292   struct GNUNET_HashCode zone_hash_double;
293   uint32_t rd_payload_length;
294   char* nrb_data = NULL;
295   size_t namelen;
296
297   /* we're done */
298   if (NULL == name)
299   {
300     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
301                "Zone iteration finished. Rescheduling put in %ds\n",
302                dht_max_update_interval);
303     namestore_iter = NULL;
304     zone_update_taskid = GNUNET_SCHEDULER_add_delayed (
305                                         GNUNET_TIME_relative_multiply(
306                                             GNUNET_TIME_UNIT_SECONDS,
307                                             dht_max_update_interval
308                                             ),
309                                             &update_zone_dht_start,
310                                             NULL);
311     return;
312   }
313   
314   namelen = strlen(name) + 1;
315   
316   if (signature == NULL)
317   {
318     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
319                "No signature for %s record data provided! Skipping...\n",
320                name);
321     zone_update_taskid = GNUNET_SCHEDULER_add_now (&update_zone_dht_next,
322                                                    NULL);
323     return;
324
325   }
326   
327   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
328              "Putting records for %s into the DHT\n", name);
329   
330   rd_payload_length = GNUNET_NAMESTORE_records_get_size (rd_count, rd);
331   
332   nrb = GNUNET_malloc(rd_payload_length + namelen
333                       + sizeof(struct GNSNameRecordBlock));
334   
335   nrb->signature = *signature;
336   
337   nrb->public_key = *key;
338
339   nrb->rd_count = htonl(rd_count);
340   
341   memcpy(&nrb[1], name, namelen);
342
343   nrb_data = (char*)&nrb[1];
344   nrb_data += namelen;
345
346   rd_payload_length += sizeof(struct GNSNameRecordBlock) + namelen;
347
348   if (-1 == GNUNET_NAMESTORE_records_serialize (rd_count,
349                                                 rd,
350                                                 rd_payload_length,
351                                                 nrb_data))
352   {
353     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
354                "Record serialization failed! Skipping...\n");
355     GNUNET_free(nrb);
356     zone_update_taskid = GNUNET_SCHEDULER_add_now (&update_zone_dht_next,
357                                                    NULL);
358     return;
359   }
360
361
362   /*
363    * calculate DHT key: H(name) xor H(pubkey)
364    */
365   GNUNET_CRYPTO_short_hash(key,
366                      sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
367                      &zhash);
368   GNUNET_CRYPTO_short_hash(name, strlen(name), &name_hash);
369   GNUNET_CRYPTO_short_hash_double (&name_hash, &name_hash_double);
370   GNUNET_CRYPTO_short_hash_double (&zhash, &zone_hash_double);
371   GNUNET_CRYPTO_hash_xor(&zone_hash_double, &name_hash_double, &xor_hash);
372
373   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
374              "zone identity: %s\n", GNUNET_h2s (&zone_hash_double));
375
376   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
377              "putting records for %s under key: %s with size %d\n",
378              name, GNUNET_h2s (&xor_hash), rd_payload_length);
379   
380   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
381              "DHT req to %d\n", DHT_OPERATION_TIMEOUT.rel_value);
382   /* FIXME: keep return value to possibly cancel? */
383   GNUNET_DHT_put (dht_handle, &xor_hash,
384                   DHT_GNS_REPLICATION_LEVEL,
385                   GNUNET_DHT_RO_NONE,
386                   GNUNET_BLOCK_TYPE_GNS_NAMERECORD,
387                   rd_payload_length,
388                   (char*)nrb,
389                   expiration,
390                   DHT_OPERATION_TIMEOUT,
391                   &record_dht_put,
392                   NULL); //cls for cont
393   
394   num_public_records++;
395
396   /**
397    * Reschedule periodic put
398    */
399   zone_update_taskid = GNUNET_SCHEDULER_add_delayed (record_put_interval,
400                                 &update_zone_dht_next,
401                                 NULL);
402
403   GNUNET_free(nrb);
404
405 }
406
407 /**
408  * Periodically iterate over our zone and store everything in dht
409  *
410  * @param cls NULL
411  * @param tc task context
412  */
413 static void
414 update_zone_dht_start(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
415 {
416   unsigned long long interval = 0;
417
418   zone_update_taskid = GNUNET_SCHEDULER_NO_TASK;
419
420   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Scheduling DHT zone update!\n");
421   if (0 == num_public_records)
422   {
423     /**
424      * If no records are known (startup) or none present
425      * we can safely set the interval to 1s
426      */
427     record_put_interval = GNUNET_TIME_relative_multiply(
428                                             GNUNET_TIME_UNIT_SECONDS,
429                                             1);
430     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
431                "No records in db. Adjusted record put interval to 1s\n");
432   }
433   else
434   {
435     interval = max_record_put_interval/num_public_records;
436     if (interval == 0)
437       interval = 1;
438     record_put_interval = GNUNET_TIME_relative_multiply(
439                                   GNUNET_TIME_UNIT_SECONDS,
440                                   interval);
441     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
442                "Adjusted DHT update interval to %ds!\n",
443                interval);
444   }
445
446   /* start counting again */
447   num_public_records = 0;
448   namestore_iter = GNUNET_NAMESTORE_zone_iteration_start (namestore_handle,
449                                                  NULL, //All zones
450                                                  GNUNET_NAMESTORE_RF_AUTHORITY,
451                                                  GNUNET_NAMESTORE_RF_PRIVATE,
452                                                  &put_gns_record,
453                                                  NULL);
454 }
455
456 /* END DHT ZONE PROPAGATION */
457
458 /**
459  * Send shorten response back to client
460  * 
461  * @param cls the closure containing a client shorten handle
462  * @param name the shortened name result or NULL if cannot be shortened
463  */
464 static void
465 send_shorten_response(void* cls, const char* name)
466 {
467   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message with %s\n",
468               "SHORTEN_RESULT", name);
469   struct GNUNET_GNS_ClientShortenResultMessage *rmsg;
470   struct ClientShortenHandle *csh = (struct ClientShortenHandle *)cls;
471   
472   if (name == NULL)
473   {
474     name = "";
475   }
476
477   rmsg = GNUNET_malloc(sizeof(struct GNUNET_GNS_ClientShortenResultMessage)
478                        + strlen(name) + 1);
479   
480   rmsg->id = csh->unique_id;
481   rmsg->header.type = htons(GNUNET_MESSAGE_TYPE_GNS_SHORTEN_RESULT);
482   rmsg->header.size = 
483     htons(sizeof(struct GNUNET_GNS_ClientShortenResultMessage) +
484           strlen(name) + 1);
485
486   strcpy((char*)&rmsg[1], name);
487
488   GNUNET_SERVER_notification_context_unicast (nc, csh->client,
489                               (const struct GNUNET_MessageHeader *) rmsg,
490                               GNUNET_NO);
491   GNUNET_SERVER_receive_done (csh->client, GNUNET_OK);
492   
493   GNUNET_free(rmsg);
494   GNUNET_free_non_null(csh->shorten_key);
495   GNUNET_free(csh);
496
497 }
498
499
500 static void
501 process_shorten_zone_shorten (void *cls,
502                       const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
503                       struct GNUNET_TIME_Absolute expiration,
504                       const char *name,
505                       unsigned int rd_count,
506                       const struct GNUNET_NAMESTORE_RecordData *rd,
507                       const struct GNUNET_CRYPTO_RsaSignature *signature)
508 {
509   struct ClientShortenHandle *csh = cls;
510   struct GNUNET_TIME_Relative remaining_time;
511   struct GNUNET_TIME_Absolute et;
512
513   remaining_time = GNUNET_TIME_absolute_get_remaining (expiration);
514
515   if ((rd_count == 1) &&
516       (remaining_time.rel_value != 0))
517   {
518     GNUNET_break (0 == (rd->flags & GNUNET_NAMESTORE_RF_RELATIVE_EXPIRATION));
519     et.abs_value = rd->expiration_time;
520     remaining_time = GNUNET_TIME_absolute_get_remaining (et);
521     if ((rd->record_type == GNUNET_GNS_RECORD_PKEY) &&
522         (remaining_time.rel_value != 0))
523     {
524       csh->shorten_zone = *((struct GNUNET_CRYPTO_ShortHashCode*)rd->data);
525     }
526   }
527   gns_resolver_shorten_name (&csh->root_zone,
528                              &csh->private_zone,
529                              &csh->shorten_zone,
530                              csh->name,
531                              private_zone_id,
532                              shorten_zone_id,
533                              &send_shorten_response, csh);
534
535 }
536
537
538 static void
539 process_private_zone_shorten (void *cls,
540                       const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
541                       struct GNUNET_TIME_Absolute expiration,
542                       const char *name,
543                       unsigned int rd_count,
544                       const struct GNUNET_NAMESTORE_RecordData *rd,
545                       const struct GNUNET_CRYPTO_RsaSignature *signature)
546 {
547   struct GNUNET_TIME_Relative remaining_time;
548   struct ClientShortenHandle *csh = cls;
549   struct GNUNET_TIME_Absolute et;
550
551   remaining_time = GNUNET_TIME_absolute_get_remaining (expiration);
552
553   if ((rd_count == 1) &&
554       (remaining_time.rel_value != 0))
555   {
556     GNUNET_break (0 == (rd->flags & GNUNET_NAMESTORE_RF_RELATIVE_EXPIRATION));
557     et.abs_value = rd->expiration_time;
558     remaining_time = GNUNET_TIME_absolute_get_remaining (et);
559     if ((rd->record_type == GNUNET_GNS_RECORD_PKEY) &&
560         (remaining_time.rel_value != 0))
561     {
562
563
564       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
565                   "Looking for shorten zone in private zone\n");
566       csh->private_zone = *((struct GNUNET_CRYPTO_ShortHashCode*)rd->data);
567       GNUNET_NAMESTORE_lookup_record (namestore_handle,
568                                       &csh->private_zone,
569                                       shorten_zone_id,
570                                       GNUNET_GNS_RECORD_ANY,
571                                       &process_shorten_zone_shorten,
572                                       cls);
573     }
574     return;
575   }
576
577   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
578               "No private zone found!\n");
579   gns_resolver_shorten_name (&csh->root_zone,
580                              &csh->private_zone,
581                              &csh->shorten_zone,
582                              csh->name,
583                              private_zone_id,
584                              shorten_zone_id,
585                              &send_shorten_response, csh);
586
587 }
588
589 /**
590  * Lookup the zone infos and shorten name
591  *
592  * @param csh the shorten handle
593  *
594  */
595 static void
596 start_shorten_name (struct ClientShortenHandle *csh)
597 {
598   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
599               "Looking for private zone in root zone\n");
600
601   GNUNET_NAMESTORE_lookup_record (namestore_handle,
602                                   &csh->root_zone,
603                                   private_zone_id,
604                                   GNUNET_GNS_RECORD_ANY,
605                                   &process_private_zone_shorten,
606                                   csh);
607 }
608
609
610 /**
611  * Handle a shorten message from the api
612  *
613  * @param cls the closure
614  * @param client the client
615  * @param message the message
616  */
617 static void handle_shorten (void *cls,
618                             struct GNUNET_SERVER_Client * client,
619                             const struct GNUNET_MessageHeader * message)
620 {
621   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "SHORTEN");
622
623   size_t msg_size = 0;
624   struct ClientShortenHandle *csh;
625   char name[MAX_DNS_NAME_LENGTH];
626   char* nameptr = name;
627
628   if (ntohs (message->size) < sizeof (struct GNUNET_GNS_ClientShortenMessage))
629   {
630     GNUNET_break_op (0);
631     GNUNET_SERVER_receive_done (client, GNUNET_OK);
632     return;
633   }
634
635
636   struct GNUNET_GNS_ClientShortenMessage *sh_msg =
637     (struct GNUNET_GNS_ClientShortenMessage *) message;
638   
639   msg_size = ntohs(message->size);
640
641   if (msg_size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
642   {
643     GNUNET_break_op (0);
644     GNUNET_SERVER_receive_done (client, GNUNET_OK);
645     return;
646   }
647
648   csh = GNUNET_malloc(sizeof(struct ClientShortenHandle));
649   csh->client = client;
650   csh->unique_id = sh_msg->id;
651   csh->shorten_key = NULL;
652   
653   GNUNET_STRINGS_utf8_tolower((char*)&sh_msg[1], &nameptr);
654
655   if (strlen (name) < strlen(GNUNET_GNS_TLD)) {
656     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
657                "SHORTEN: %s is too short", name);
658     send_shorten_response(csh, name);
659     return;
660   }
661
662   if (strlen (name) > MAX_DNS_NAME_LENGTH) {
663     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
664                "SHORTEN: %s is too long", name);
665     send_shorten_response(csh, name);
666     return;
667   }
668   
669   if (!is_gnunet_tld(name) && !is_zkey_tld(name))
670   {
671     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
672                 "%s is not our domain. Returning\n", name);
673     send_shorten_response(csh, name);
674     return;
675   }
676
677   strcpy (csh->name, name);
678   
679   GNUNET_SERVER_notification_context_add (nc, client);
680   
681   if (1 == ntohl(sh_msg->use_default_zone))
682     csh->root_zone = zone_hash; //Default zone
683   else
684     csh->root_zone = sh_msg->zone;
685
686   start_shorten_name (csh);
687   
688 }
689
690
691 /**
692  * Send get authority response back to client
693  * 
694  * @param cls the closure containing a client get auth handle
695  * @param name the shortened name result or NULL if cannot be shortened
696  */
697 static void
698 send_get_auth_response(void *cls, const char* name)
699 {
700   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message with %s\n",
701               "GET_AUTH_RESULT", name);
702   struct GNUNET_GNS_ClientGetAuthResultMessage *rmsg;
703   struct ClientGetAuthHandle *cah = (struct ClientGetAuthHandle *)cls;
704   
705   if (name == NULL)
706   {
707     name = "";
708   }
709
710   rmsg = GNUNET_malloc(sizeof(struct GNUNET_GNS_ClientGetAuthResultMessage)
711                        + strlen(name) + 1);
712   
713   rmsg->id = cah->unique_id;
714   rmsg->header.type = htons(GNUNET_MESSAGE_TYPE_GNS_GET_AUTH_RESULT);
715   rmsg->header.size = 
716     htons(sizeof(struct GNUNET_GNS_ClientGetAuthResultMessage) +
717           strlen(name) + 1);
718
719   strcpy((char*)&rmsg[1], name);
720
721   GNUNET_SERVER_notification_context_unicast (nc, cah->client,
722                               (const struct GNUNET_MessageHeader *) rmsg,
723                               GNUNET_NO);
724   GNUNET_SERVER_receive_done (cah->client, GNUNET_OK);
725   
726   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Cleaning up handles...\n");
727
728   GNUNET_free(rmsg);
729   GNUNET_free_non_null(cah->name);
730   GNUNET_free(cah);
731
732   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "done.\n");
733
734 }
735
736
737 /**
738  * Handle a get authority message from the api
739  *
740  * @param cls the closure
741  * @param client the client
742  * @param message the message
743  */
744 static void handle_get_authority(void *cls,
745                            struct GNUNET_SERVER_Client * client,
746                            const struct GNUNET_MessageHeader * message)
747 {
748   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "GET_AUTH");
749
750   size_t msg_size = 0;
751   struct ClientGetAuthHandle *cah;
752   char name[MAX_DNS_NAME_LENGTH];
753   char* nameptr = name;
754
755
756   if (ntohs (message->size) < sizeof (struct GNUNET_GNS_ClientGetAuthMessage))
757   {
758     GNUNET_break_op (0);
759     GNUNET_SERVER_receive_done (client, GNUNET_OK);
760     return;
761   }
762
763   GNUNET_SERVER_notification_context_add (nc, client);
764
765   struct GNUNET_GNS_ClientGetAuthMessage *sh_msg =
766     (struct GNUNET_GNS_ClientGetAuthMessage *) message;
767   
768   msg_size = ntohs(message->size);
769
770   if (msg_size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
771   {
772     GNUNET_break_op (0);
773     GNUNET_SERVER_receive_done (client, GNUNET_OK);
774     return;
775   }
776   
777   GNUNET_STRINGS_utf8_tolower((char*)&sh_msg[1], &nameptr);
778
779
780   cah = GNUNET_malloc(sizeof(struct ClientGetAuthHandle));
781   cah->client = client;
782   cah->unique_id = sh_msg->id;
783
784   if (strlen(name) < strlen(GNUNET_GNS_TLD))
785   {
786     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
787                 "GET_AUTH: %s is too short. Returning\n", name);
788     cah->name = NULL;
789     send_get_auth_response(cah, name);
790     return;
791   }
792   
793   if (strlen (name) > MAX_DNS_NAME_LENGTH) {
794     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
795                "GET_AUTH: %s is too long", name);
796     cah->name = NULL;
797     send_get_auth_response(cah, name);
798     return;
799   }
800   
801   if (strcmp(name+strlen(name)-strlen(GNUNET_GNS_TLD),
802              GNUNET_GNS_TLD) != 0)
803   {
804     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
805                 "GET_AUTH: %s is not our domain. Returning\n", name);
806     cah->name = NULL;
807     send_get_auth_response(cah, name);
808     return;
809   }
810
811   if (strcmp(name, GNUNET_GNS_TLD) == 0)
812   {
813     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
814                 "GET_AUTH: %s is us. Returning\n", name);
815     cah->name = NULL;
816     send_get_auth_response(cah, name);
817     return;
818   }
819   
820   cah->name = GNUNET_malloc(strlen(name)
821                             - strlen(GNUNET_GNS_TLD) + 1);
822   memset(cah->name, 0,
823          strlen(name)-strlen(GNUNET_GNS_TLD) + 1);
824   memcpy(cah->name, name,
825          strlen(name)-strlen(GNUNET_GNS_TLD));
826
827   /* Start delegation resolution in our namestore */
828   gns_resolver_get_authority(zone_hash, zone_hash, name, &send_get_auth_response, cah);
829 }
830
831
832
833 /**
834  * Reply to client with the result from our lookup.
835  *
836  * @param cls the closure (our client lookup handle)
837  * @param rd_count the number of records
838  * @param rd the record data
839  */
840 static void
841 send_lookup_response(void* cls,
842                      uint32_t rd_count,
843                      const struct GNUNET_NAMESTORE_RecordData *rd)
844 {
845   struct ClientLookupHandle* clh = (struct ClientLookupHandle*)cls;
846   struct GNUNET_GNS_ClientLookupResultMessage *rmsg;
847   size_t len;
848   
849   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message with %d results\n",
850               "LOOKUP_RESULT", rd_count);
851   
852   len = GNUNET_NAMESTORE_records_get_size (rd_count, rd);
853   rmsg = GNUNET_malloc(len+sizeof(struct GNUNET_GNS_ClientLookupResultMessage));
854   
855   rmsg->id = clh->unique_id;
856   rmsg->rd_count = htonl(rd_count);
857   rmsg->header.type = htons(GNUNET_MESSAGE_TYPE_GNS_LOOKUP_RESULT);
858   rmsg->header.size = 
859     htons(len+sizeof(struct GNUNET_GNS_ClientLookupResultMessage));
860   
861   GNUNET_NAMESTORE_records_serialize (rd_count, rd, len, (char*)&rmsg[1]);
862   
863   GNUNET_SERVER_notification_context_unicast (nc, clh->client,
864                                 (const struct GNUNET_MessageHeader *) rmsg,
865                                 GNUNET_NO);
866   GNUNET_SERVER_receive_done (clh->client, GNUNET_OK);
867   
868   GNUNET_free(rmsg);
869   GNUNET_free(clh->name);
870   
871   if (NULL != clh->shorten_key)
872     GNUNET_free(clh->shorten_key);
873
874   GNUNET_free(clh);
875
876 }
877
878
879 /**
880  * Handle lookup requests from client
881  *
882  * @param cls the closure
883  * @param client the client
884  * @param message the message
885  */
886 static void
887 handle_lookup(void *cls,
888               struct GNUNET_SERVER_Client * client,
889               const struct GNUNET_MessageHeader * message)
890 {
891   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "LOOKUP");
892
893   size_t msg_size = 0;
894   size_t namelen;
895   char name[MAX_DNS_NAME_LENGTH];
896   struct ClientLookupHandle *clh;
897   char* nameptr = name;
898   int only_cached;
899   struct GNUNET_CRYPTO_RsaPrivateKey *key;
900   struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *pkey;
901   char* tmp_pkey;
902
903   if (ntohs (message->size) < sizeof (struct GNUNET_GNS_ClientLookupMessage))
904   {
905     GNUNET_break_op (0);
906     GNUNET_SERVER_receive_done (client, GNUNET_OK);
907     return;
908   }
909
910   GNUNET_SERVER_notification_context_add (nc, client);
911
912   struct GNUNET_GNS_ClientLookupMessage *sh_msg =
913     (struct GNUNET_GNS_ClientLookupMessage *) message;
914   
915   msg_size = ntohs(message->size);
916
917   if (msg_size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
918   {
919     GNUNET_break_op (0);
920     GNUNET_SERVER_receive_done (client, GNUNET_OK);
921     return;
922   }
923
924   if (1 == ntohl(sh_msg->have_key))
925   {
926     pkey = (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *)&sh_msg[1];
927     tmp_pkey = (char*)&sh_msg[1];
928     key = GNUNET_CRYPTO_rsa_decode_key (tmp_pkey, ntohs(pkey->len));
929     GNUNET_STRINGS_utf8_tolower(&tmp_pkey[ntohs(pkey->len)], &nameptr);
930   }
931   else
932   {
933     key = NULL;
934     GNUNET_STRINGS_utf8_tolower((char*)&sh_msg[1], &nameptr);
935   }
936   
937   namelen = strlen(name)+1;
938   clh = GNUNET_malloc (sizeof (struct ClientLookupHandle));
939   memset (clh, 0, sizeof (struct ClientLookupHandle));
940   clh->client = client;
941   clh->name = GNUNET_malloc(namelen);
942   strcpy(clh->name, name);
943   clh->unique_id = sh_msg->id;
944   clh->type = ntohl(sh_msg->type);
945   clh->shorten_key = key;
946
947   only_cached = ntohl(sh_msg->only_cached);
948   
949   if (strlen (name) > MAX_DNS_NAME_LENGTH) {
950     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
951                "LOOKUP: %s is too long", name);
952     clh->name = NULL;
953     send_lookup_response(clh, 0, NULL);
954     return;
955   }
956
957   if ((clh->type == GNUNET_GNS_RECORD_TYPE_A) &&
958       (GNUNET_OK != v4_enabled))
959   {
960     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
961                "LOOKUP: Query for A record but AF_INET not supported!");
962     clh->name = NULL;
963     send_lookup_response(clh, 0, NULL);
964     return;
965   }
966   
967   if ((clh->type == GNUNET_GNS_RECORD_AAAA) &&
968       (GNUNET_OK != v6_enabled))
969   {
970     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
971                "LOOKUP: Query for AAAA record but AF_INET6 not supported!");
972     clh->name = NULL;
973     send_lookup_response(clh, 0, NULL);
974     return;
975   }
976   
977   if (1 == ntohl(sh_msg->use_default_zone))
978     clh->zone = zone_hash; //Default zone
979   else
980     clh->zone = sh_msg->zone;
981   
982   if (GNUNET_YES == auto_import_pkey)
983   {
984     gns_resolver_lookup_record (clh->zone, clh->zone, clh->type, clh->name,
985                                 clh->shorten_key,
986                                 default_lookup_timeout,
987                                 clh->only_cached,
988                                 &send_lookup_response, clh);  
989   }
990   else
991   {
992     gns_resolver_lookup_record (clh->zone, clh->zone, clh->type, name,
993                                 NULL,
994                                 default_lookup_timeout,
995                                 only_cached,
996                                 &send_lookup_response, clh);
997   }
998 }
999
1000 /**
1001  * Test if the given AF is supported by this system.
1002  *
1003  * @param af to test
1004  * @return GNUNET_OK if the AF is supported
1005  */
1006 static int
1007 test_af (int af)
1008 {
1009   int s;
1010
1011   s = socket (af, SOCK_STREAM, 0);
1012   if (-1 == s)
1013   {
1014     if (EAFNOSUPPORT == errno)
1015       return GNUNET_NO;
1016     fprintf (stderr, "Failed to create test socket: %s\n", STRERROR (errno));
1017     return GNUNET_SYSERR;
1018   }
1019   close (s);
1020   return GNUNET_OK;
1021 }
1022
1023 /**
1024  * Process GNS requests.
1025  *
1026  * @param cls closure)
1027  * @param server the initialized server
1028  * @param c configuration to use
1029  */
1030 static void
1031 run (void *cls, struct GNUNET_SERVER_Handle *server,
1032      const struct GNUNET_CONFIGURATION_Handle *c)
1033 {
1034   
1035   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Initializing GNS\n");
1036   
1037   char* keyfile;
1038   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pkey;
1039   unsigned long long max_parallel_bg_queries = 0;
1040   unsigned long long default_lookup_timeout_secs = 0;
1041   int ignore_pending = GNUNET_NO;
1042
1043   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1044     {&handle_shorten, NULL, GNUNET_MESSAGE_TYPE_GNS_SHORTEN, 0},
1045     {&handle_lookup, NULL, GNUNET_MESSAGE_TYPE_GNS_LOOKUP, 0},
1046     {&handle_get_authority, NULL, GNUNET_MESSAGE_TYPE_GNS_GET_AUTH, 0}
1047   };
1048
1049   GNS_cfg = c;
1050
1051   v6_enabled = test_af (AF_INET6);
1052   v4_enabled = test_af (AF_INET);
1053
1054   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (c, "gns",
1055                                              "ZONEKEY", &keyfile))
1056   {
1057     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1058                 "No private key for root zone specified!\n");
1059     GNUNET_SCHEDULER_shutdown ();
1060     return;
1061   }
1062
1063   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1064              "Using keyfile %s for root zone.\n", keyfile);
1065
1066   zone_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
1067   GNUNET_CRYPTO_rsa_key_get_public (zone_key, &pkey);
1068
1069   GNUNET_CRYPTO_short_hash(&pkey,
1070                      sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1071                      &zone_hash);
1072   GNUNET_free(keyfile);
1073   
1074   /**
1075    * handle to our local namestore
1076    */
1077   namestore_handle = GNUNET_NAMESTORE_connect(c);
1078
1079   if (NULL == namestore_handle)
1080   {
1081     //FIXME do error handling;
1082     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1083                "Failed to connect to the namestore!\n");
1084     GNUNET_SCHEDULER_shutdown ();
1085     return;
1086   }
1087   
1088   
1089
1090   auto_import_pkey = GNUNET_NO;
1091
1092   if (GNUNET_YES ==
1093       GNUNET_CONFIGURATION_get_value_yesno (c, "gns",
1094                                             "AUTO_IMPORT_PKEY"))
1095   {
1096     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1097                "Automatic PKEY import is enabled.\n");
1098     auto_import_pkey = GNUNET_YES;
1099
1100   }
1101
1102   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (c, "gns",
1103                                                           "PRIVATE_ZONE",
1104                                                           &private_zone_id))
1105   {
1106     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1107                "Private zone id: %s\n", private_zone_id);
1108   }
1109
1110   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (c, "gns",
1111                                                           "SHORTEN_ZONE",
1112                                                           &shorten_zone_id))
1113   {
1114     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1115                "Shorten zone id: %s\n", shorten_zone_id);
1116   }
1117
1118   dht_max_update_interval = GNUNET_GNS_DHT_MAX_UPDATE_INTERVAL;
1119
1120   if (GNUNET_OK ==
1121       GNUNET_CONFIGURATION_get_value_number (c, "gns",
1122                                              "ZONE_PUT_INTERVAL",
1123                                              &dht_max_update_interval))
1124   {
1125     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1126                 "DHT zone update interval: %llu\n",
1127                 dht_max_update_interval);
1128   }
1129   
1130   max_record_put_interval = 1;
1131
1132   if (GNUNET_OK ==
1133       GNUNET_CONFIGURATION_get_value_number (c, "gns",
1134                                              "RECORD_PUT_INTERVAL",
1135                                              &max_record_put_interval))
1136   {
1137     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1138                "Record put interval: %llu\n",
1139                max_record_put_interval);
1140   }
1141   
1142   if (GNUNET_OK ==
1143       GNUNET_CONFIGURATION_get_value_number (c, "gns",
1144                                             "MAX_PARALLEL_BACKGROUND_QUERIES",
1145                                             &max_parallel_bg_queries))
1146   {
1147     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1148                "Number of allowed parallel background queries: %llu\n",
1149                max_parallel_bg_queries);
1150   }
1151
1152   if (GNUNET_YES ==
1153       GNUNET_CONFIGURATION_get_value_yesno (c, "gns",
1154                                             "AUTO_IMPORT_CONFIRMATION_REQ"))
1155   {
1156     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1157                "Auto import requires user confirmation\n");
1158     ignore_pending = GNUNET_YES;
1159   }
1160
1161   if (GNUNET_OK ==
1162       GNUNET_CONFIGURATION_get_value_number(c, "gns",
1163                                             "DEFAULT_LOOKUP_TIMEOUT",
1164                                             &default_lookup_timeout_secs))
1165   {
1166     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1167                "Default lookup timeout: %llus\n", default_lookup_timeout_secs);
1168     default_lookup_timeout = GNUNET_TIME_relative_multiply(
1169                                             GNUNET_TIME_UNIT_SECONDS,
1170                                             default_lookup_timeout_secs);
1171   }
1172   
1173   /**
1174    * handle to the dht
1175    */
1176   dht_handle = GNUNET_DHT_connect(c,
1177                        //max_parallel_bg_queries); //FIXME get ht_len from cfg
1178                        1024);
1179
1180   if (NULL == dht_handle)
1181   {
1182     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Could not connect to DHT!\n");
1183   }
1184   
1185   if (gns_resolver_init(namestore_handle, dht_handle, zone_hash, c,
1186                         max_parallel_bg_queries,
1187                         ignore_pending)
1188       == GNUNET_SYSERR)
1189   {
1190     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1191                "Unable to initialize resolver!\n");
1192     GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
1193     return;
1194   }
1195
1196   if (GNUNET_YES ==
1197       GNUNET_CONFIGURATION_get_value_yesno (c, "gns", "HIJACK_DNS"))
1198   {
1199     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1200                "DNS hijacking enabled... connecting to service.\n");
1201
1202     if (gns_interceptor_init(zone_hash, zone_key, c) == GNUNET_SYSERR)
1203     {
1204       GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1205                "Failed to enable the dns interceptor!\n");
1206     }
1207   }
1208   
1209   /**
1210    * Schedule periodic put
1211    * for our records
1212    * We have roughly an hour for all records;
1213    */
1214   record_put_interval = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS,
1215                                                       1);
1216   zone_update_taskid = GNUNET_SCHEDULER_add_now (&update_zone_dht_start, NULL);
1217
1218   GNUNET_SERVER_add_handlers (server, handlers);
1219   
1220   //FIXME
1221   //GNUNET_SERVER_disconnect_notify (server,
1222   //                                 &client_disconnect_notification,
1223   //                                 NULL);
1224
1225   nc = GNUNET_SERVER_notification_context_create (server, 1);
1226
1227   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
1228                                 NULL);
1229 }
1230
1231
1232 /**
1233  * The main function for the GNS service.
1234  *
1235  * @param argc number of arguments from the command line
1236  * @param argv command line arguments
1237  * @return 0 ok, 1 on error
1238  */
1239 int
1240 main (int argc, char *const *argv)
1241 {
1242   int ret;
1243
1244   ret =
1245       (GNUNET_OK ==
1246        GNUNET_SERVICE_run (argc, argv, "gns", GNUNET_SERVICE_OPTION_NONE, &run,
1247                            NULL)) ? 0 : 1;
1248   return ret;
1249 }
1250
1251 /* end of gnunet-service-gns.c */