-towards enabling relative expiration times in namestore
[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 /**
191  * Continue shutdown
192  */
193 static void
194 on_resolver_cleanup(void)
195 {
196   GNUNET_NAMESTORE_disconnect(namestore_handle, 1);
197   
198 }
199
200 /**
201  * Task run during shutdown.
202  *
203  * @param cls unused
204  * @param tc unused
205  */
206 static void
207 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
208 {
209
210   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
211              "Shutting down!");
212   
213   
214   GNUNET_SERVER_notification_context_destroy (nc);
215   
216   gns_interceptor_stop();
217   gns_resolver_cleanup(&on_resolver_cleanup);
218   /* Kill zone task for it may make the scheduler hang */
219   if (zone_update_taskid != GNUNET_SCHEDULER_NO_TASK)
220     GNUNET_SCHEDULER_cancel(zone_update_taskid);
221   GNUNET_DHT_disconnect(dht_handle);
222 }
223
224
225 /**
226  * Method called periodicattluy that triggers
227  * iteration over root zone
228  *
229  * @param cls closure
230  * @param tc task context
231  */
232 static void
233 update_zone_dht_next(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
234 {
235   zone_update_taskid = GNUNET_SCHEDULER_NO_TASK;
236   GNUNET_NAMESTORE_zone_iterator_next(namestore_iter);
237 }
238
239 /**
240  * Continuation for DHT put
241  *
242  * @param cls closure
243  * @param success GNUNET_OK if the PUT was transmitted,
244  *                GNUNET_NO on timeout,
245  *                GNUNET_SYSERR on disconnect from service
246  *                after the PUT message was transmitted
247  *                (so we don't know if it was received or not)
248  */
249 static void
250 record_dht_put(void *cls, int success)
251 {
252   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "put request transmitted\n");
253 }
254
255 /* prototype */
256 static void
257 update_zone_dht_start(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
258
259 /**
260  * Function used to put all records successively into the DHT.
261  *
262  * @param cls the closure (NULL)
263  * @param key the public key of the authority (ours)
264  * @param expiration lifetime of the namestore entry
265  * @param name the name of the records
266  * @param rd_count the number of records in data
267  * @param rd the record data
268  * @param signature the signature for the record data
269  */
270 static void
271 put_gns_record(void *cls,
272                 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
273                 struct GNUNET_TIME_Absolute expiration,
274                 const char *name,
275                 unsigned int rd_count,
276                 const struct GNUNET_NAMESTORE_RecordData *rd,
277                 const struct GNUNET_CRYPTO_RsaSignature *signature)
278 {
279   
280   struct GNSNameRecordBlock *nrb;
281   struct GNUNET_CRYPTO_ShortHashCode name_hash;
282   struct GNUNET_CRYPTO_ShortHashCode zhash;
283   struct GNUNET_HashCode xor_hash;
284   struct GNUNET_HashCode name_hash_double;
285   struct GNUNET_HashCode zone_hash_double;
286   uint32_t rd_payload_length;
287   char* nrb_data = NULL;
288   size_t namelen;
289
290   /* we're done */
291   if (NULL == name)
292   {
293     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
294                "Zone iteration finished. Rescheduling put in %ds\n",
295                dht_max_update_interval);
296     zone_update_taskid = GNUNET_SCHEDULER_add_delayed (
297                                         GNUNET_TIME_relative_multiply(
298                                             GNUNET_TIME_UNIT_SECONDS,
299                                             dht_max_update_interval
300                                             ),
301                                             &update_zone_dht_start,
302                                             NULL);
303     return;
304   }
305   
306   namelen = strlen(name) + 1;
307   
308   if (signature == NULL)
309   {
310     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
311                "No signature for %s record data provided! Skipping...\n",
312                name);
313     zone_update_taskid = GNUNET_SCHEDULER_add_now (&update_zone_dht_next,
314                                                    NULL);
315     return;
316
317   }
318   
319   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
320              "Putting records for %s into the DHT\n", name);
321   
322   rd_payload_length = GNUNET_NAMESTORE_records_get_size (rd_count, rd);
323   
324   nrb = GNUNET_malloc(rd_payload_length + namelen
325                       + sizeof(struct GNSNameRecordBlock));
326   
327   nrb->signature = *signature;
328   
329   nrb->public_key = *key;
330
331   nrb->rd_count = htonl(rd_count);
332   
333   memcpy(&nrb[1], name, namelen);
334
335   nrb_data = (char*)&nrb[1];
336   nrb_data += namelen;
337
338   rd_payload_length += sizeof(struct GNSNameRecordBlock) + namelen;
339
340   if (-1 == GNUNET_NAMESTORE_records_serialize (rd_count,
341                                                 rd,
342                                                 rd_payload_length,
343                                                 nrb_data))
344   {
345     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
346                "Record serialization failed! Skipping...\n");
347     GNUNET_free(nrb);
348     zone_update_taskid = GNUNET_SCHEDULER_add_now (&update_zone_dht_next,
349                                                    NULL);
350     return;
351   }
352
353
354   /*
355    * calculate DHT key: H(name) xor H(pubkey)
356    */
357   GNUNET_CRYPTO_short_hash(key,
358                      sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
359                      &zhash);
360   GNUNET_CRYPTO_short_hash(name, strlen(name), &name_hash);
361   GNUNET_CRYPTO_short_hash_double (&name_hash, &name_hash_double);
362   GNUNET_CRYPTO_short_hash_double (&zhash, &zone_hash_double);
363   GNUNET_CRYPTO_hash_xor(&zone_hash_double, &name_hash_double, &xor_hash);
364
365   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
366              "zone identity: %s\n", GNUNET_h2s (&zone_hash_double));
367
368   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
369              "putting records for %s under key: %s with size %d\n",
370              name, GNUNET_h2s (&xor_hash), rd_payload_length);
371   
372   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
373              "DHT req to %d\n", DHT_OPERATION_TIMEOUT.rel_value);
374   /* FIXME: keep return value to possibly cancel? */
375   GNUNET_DHT_put (dht_handle, &xor_hash,
376                   DHT_GNS_REPLICATION_LEVEL,
377                   GNUNET_DHT_RO_NONE,
378                   GNUNET_BLOCK_TYPE_GNS_NAMERECORD,
379                   rd_payload_length,
380                   (char*)nrb,
381                   expiration,
382                   DHT_OPERATION_TIMEOUT,
383                   &record_dht_put,
384                   NULL); //cls for cont
385   
386   num_public_records++;
387
388   /**
389    * Reschedule periodic put
390    */
391   zone_update_taskid = GNUNET_SCHEDULER_add_delayed (record_put_interval,
392                                 &update_zone_dht_next,
393                                 NULL);
394
395   GNUNET_free(nrb);
396
397 }
398
399 /**
400  * Periodically iterate over our zone and store everything in dht
401  *
402  * @param cls NULL
403  * @param tc task context
404  */
405 static void
406 update_zone_dht_start(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
407 {
408   unsigned long long interval = 0;
409
410   zone_update_taskid = GNUNET_SCHEDULER_NO_TASK;
411
412   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Scheduling DHT zone update!\n");
413   if (0 == num_public_records)
414   {
415     /**
416      * If no records are known (startup) or none present
417      * we can safely set the interval to 1s
418      */
419     record_put_interval = GNUNET_TIME_relative_multiply(
420                                             GNUNET_TIME_UNIT_SECONDS,
421                                             1);
422     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
423                "No records in db. Adjusted record put interval to 1s\n");
424   }
425   else
426   {
427     interval = max_record_put_interval/num_public_records;
428     if (interval == 0)
429       interval = 1;
430     record_put_interval = GNUNET_TIME_relative_multiply(
431                                   GNUNET_TIME_UNIT_SECONDS,
432                                   interval);
433     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
434                "Adjusted DHT update interval to %ds!\n",
435                interval);
436   }
437
438   /* start counting again */
439   num_public_records = 0;
440   namestore_iter = GNUNET_NAMESTORE_zone_iteration_start (namestore_handle,
441                                                  NULL, //All zones
442                                                  GNUNET_NAMESTORE_RF_AUTHORITY,
443                                                  GNUNET_NAMESTORE_RF_PRIVATE,
444                                                  &put_gns_record,
445                                                  NULL);
446 }
447
448 /* END DHT ZONE PROPAGATION */
449
450 /**
451  * Send shorten response back to client
452  * 
453  * @param cls the closure containing a client shorten handle
454  * @param name the shortened name result or NULL if cannot be shortened
455  */
456 static void
457 send_shorten_response(void* cls, const char* name)
458 {
459   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message with %s\n",
460               "SHORTEN_RESULT", name);
461   struct GNUNET_GNS_ClientShortenResultMessage *rmsg;
462   struct ClientShortenHandle *csh = (struct ClientShortenHandle *)cls;
463   
464   if (name == NULL)
465   {
466     name = "";
467   }
468
469   rmsg = GNUNET_malloc(sizeof(struct GNUNET_GNS_ClientShortenResultMessage)
470                        + strlen(name) + 1);
471   
472   rmsg->id = csh->unique_id;
473   rmsg->header.type = htons(GNUNET_MESSAGE_TYPE_GNS_SHORTEN_RESULT);
474   rmsg->header.size = 
475     htons(sizeof(struct GNUNET_GNS_ClientShortenResultMessage) +
476           strlen(name) + 1);
477
478   strcpy((char*)&rmsg[1], name);
479
480   GNUNET_SERVER_notification_context_unicast (nc, csh->client,
481                               (const struct GNUNET_MessageHeader *) rmsg,
482                               GNUNET_NO);
483   GNUNET_SERVER_receive_done (csh->client, GNUNET_OK);
484   
485   GNUNET_free(rmsg);
486   GNUNET_free_non_null(csh->shorten_key);
487   GNUNET_free(csh);
488
489 }
490
491
492 static void
493 process_shorten_zone_shorten (void *cls,
494                       const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
495                       struct GNUNET_TIME_Absolute expiration,
496                       const char *name,
497                       unsigned int rd_count,
498                       const struct GNUNET_NAMESTORE_RecordData *rd,
499                       const struct GNUNET_CRYPTO_RsaSignature *signature)
500 {
501   struct ClientShortenHandle *csh = cls;
502   struct GNUNET_TIME_Relative remaining_time;
503   struct GNUNET_TIME_Absolute et;
504
505   remaining_time = GNUNET_TIME_absolute_get_remaining (expiration);
506
507   if ((rd_count == 1) &&
508       (remaining_time.rel_value != 0))
509   {
510     GNUNET_break (0 == (rd->flags & GNUNET_NAMESTORE_RF_RELATIVE_EXPIRATION));
511     et.abs_value = rd->expiration_time;
512     remaining_time = GNUNET_TIME_absolute_get_remaining (et);
513     if ((rd->record_type == GNUNET_GNS_RECORD_PKEY) &&
514         (remaining_time.rel_value != 0))
515     {
516       csh->shorten_zone = *((struct GNUNET_CRYPTO_ShortHashCode*)rd->data);
517     }
518   }
519   gns_resolver_shorten_name (&csh->root_zone,
520                              &csh->private_zone,
521                              &csh->shorten_zone,
522                              csh->name,
523                              private_zone_id,
524                              shorten_zone_id,
525                              &send_shorten_response, csh);
526
527 }
528
529
530 static void
531 process_private_zone_shorten (void *cls,
532                       const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
533                       struct GNUNET_TIME_Absolute expiration,
534                       const char *name,
535                       unsigned int rd_count,
536                       const struct GNUNET_NAMESTORE_RecordData *rd,
537                       const struct GNUNET_CRYPTO_RsaSignature *signature)
538 {
539   struct GNUNET_TIME_Relative remaining_time;
540   struct ClientShortenHandle *csh = cls;
541   struct GNUNET_TIME_Absolute et;
542
543   remaining_time = GNUNET_TIME_absolute_get_remaining (expiration);
544
545   if ((rd_count == 1) &&
546       (remaining_time.rel_value != 0))
547   {
548     GNUNET_break (0 == (rd->flags & GNUNET_NAMESTORE_RF_RELATIVE_EXPIRATION));
549     et.abs_value = rd->expiration_time;
550     remaining_time = GNUNET_TIME_absolute_get_remaining (et);
551     if ((rd->record_type == GNUNET_GNS_RECORD_PKEY) &&
552         (remaining_time.rel_value != 0))
553     {
554
555
556       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
557                   "Looking for shorten zone in private zone\n");
558       csh->private_zone = *((struct GNUNET_CRYPTO_ShortHashCode*)rd->data);
559       GNUNET_NAMESTORE_lookup_record (namestore_handle,
560                                       &csh->private_zone,
561                                       shorten_zone_id,
562                                       GNUNET_GNS_RECORD_ANY,
563                                       &process_shorten_zone_shorten,
564                                       cls);
565     }
566     return;
567   }
568
569   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
570               "No private zone found!\n");
571   gns_resolver_shorten_name (&csh->root_zone,
572                              &csh->private_zone,
573                              &csh->shorten_zone,
574                              csh->name,
575                              private_zone_id,
576                              shorten_zone_id,
577                              &send_shorten_response, csh);
578
579 }
580
581 /**
582  * Lookup the zone infos and shorten name
583  *
584  * @param csh the shorten handle
585  *
586  */
587 static void
588 start_shorten_name (struct ClientShortenHandle *csh)
589 {
590   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
591               "Looking for private zone in root zone\n");
592
593   GNUNET_NAMESTORE_lookup_record (namestore_handle,
594                                   &csh->root_zone,
595                                   private_zone_id,
596                                   GNUNET_GNS_RECORD_ANY,
597                                   &process_private_zone_shorten,
598                                   csh);
599 }
600
601
602 /**
603  * Handle a shorten message from the api
604  *
605  * @param cls the closure
606  * @param client the client
607  * @param message the message
608  */
609 static void handle_shorten (void *cls,
610                             struct GNUNET_SERVER_Client * client,
611                             const struct GNUNET_MessageHeader * message)
612 {
613   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "SHORTEN");
614
615   size_t msg_size = 0;
616   struct ClientShortenHandle *csh;
617   char name[MAX_DNS_NAME_LENGTH];
618   char* nameptr = name;
619
620   if (ntohs (message->size) < sizeof (struct GNUNET_GNS_ClientShortenMessage))
621   {
622     GNUNET_break_op (0);
623     GNUNET_SERVER_receive_done (client, GNUNET_OK);
624     return;
625   }
626
627
628   struct GNUNET_GNS_ClientShortenMessage *sh_msg =
629     (struct GNUNET_GNS_ClientShortenMessage *) message;
630   
631   msg_size = ntohs(message->size);
632
633   if (msg_size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
634   {
635     GNUNET_break_op (0);
636     GNUNET_SERVER_receive_done (client, GNUNET_OK);
637     return;
638   }
639
640   csh = GNUNET_malloc(sizeof(struct ClientShortenHandle));
641   csh->client = client;
642   csh->unique_id = sh_msg->id;
643   csh->shorten_key = NULL;
644   
645   GNUNET_STRINGS_utf8_tolower((char*)&sh_msg[1], &nameptr);
646
647   if (strlen (name) < strlen(GNUNET_GNS_TLD)) {
648     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
649                "SHORTEN: %s is too short", name);
650     send_shorten_response(csh, name);
651     return;
652   }
653
654   if (strlen (name) > MAX_DNS_NAME_LENGTH) {
655     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
656                "SHORTEN: %s is too long", name);
657     send_shorten_response(csh, name);
658     return;
659   }
660   
661   if (!is_gnunet_tld(name) && !is_zkey_tld(name))
662   {
663     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
664                 "%s is not our domain. Returning\n", name);
665     send_shorten_response(csh, name);
666     return;
667   }
668
669   strcpy (csh->name, name);
670   
671   GNUNET_SERVER_notification_context_add (nc, client);
672   
673   if (1 == ntohl(sh_msg->use_default_zone))
674     csh->root_zone = zone_hash; //Default zone
675   else
676     csh->root_zone = sh_msg->zone;
677
678   start_shorten_name (csh);
679   
680 }
681
682
683 /**
684  * Send get authority response back to client
685  * 
686  * @param cls the closure containing a client get auth handle
687  * @param name the shortened name result or NULL if cannot be shortened
688  */
689 static void
690 send_get_auth_response(void *cls, const char* name)
691 {
692   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message with %s\n",
693               "GET_AUTH_RESULT", name);
694   struct GNUNET_GNS_ClientGetAuthResultMessage *rmsg;
695   struct ClientGetAuthHandle *cah = (struct ClientGetAuthHandle *)cls;
696   
697   if (name == NULL)
698   {
699     name = "";
700   }
701
702   rmsg = GNUNET_malloc(sizeof(struct GNUNET_GNS_ClientGetAuthResultMessage)
703                        + strlen(name) + 1);
704   
705   rmsg->id = cah->unique_id;
706   rmsg->header.type = htons(GNUNET_MESSAGE_TYPE_GNS_GET_AUTH_RESULT);
707   rmsg->header.size = 
708     htons(sizeof(struct GNUNET_GNS_ClientGetAuthResultMessage) +
709           strlen(name) + 1);
710
711   strcpy((char*)&rmsg[1], name);
712
713   GNUNET_SERVER_notification_context_unicast (nc, cah->client,
714                               (const struct GNUNET_MessageHeader *) rmsg,
715                               GNUNET_NO);
716   GNUNET_SERVER_receive_done (cah->client, GNUNET_OK);
717   
718   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Cleaning up handles...\n");
719
720   GNUNET_free(rmsg);
721   GNUNET_free_non_null(cah->name);
722   GNUNET_free(cah);
723
724   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "done.\n");
725
726 }
727
728
729 /**
730  * Handle a get authority message from the api
731  *
732  * @param cls the closure
733  * @param client the client
734  * @param message the message
735  */
736 static void handle_get_authority(void *cls,
737                            struct GNUNET_SERVER_Client * client,
738                            const struct GNUNET_MessageHeader * message)
739 {
740   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "GET_AUTH");
741
742   size_t msg_size = 0;
743   struct ClientGetAuthHandle *cah;
744   char name[MAX_DNS_NAME_LENGTH];
745   char* nameptr = name;
746
747
748   if (ntohs (message->size) < sizeof (struct GNUNET_GNS_ClientGetAuthMessage))
749   {
750     GNUNET_break_op (0);
751     GNUNET_SERVER_receive_done (client, GNUNET_OK);
752     return;
753   }
754
755   GNUNET_SERVER_notification_context_add (nc, client);
756
757   struct GNUNET_GNS_ClientGetAuthMessage *sh_msg =
758     (struct GNUNET_GNS_ClientGetAuthMessage *) message;
759   
760   msg_size = ntohs(message->size);
761
762   if (msg_size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
763   {
764     GNUNET_break_op (0);
765     GNUNET_SERVER_receive_done (client, GNUNET_OK);
766     return;
767   }
768   
769   GNUNET_STRINGS_utf8_tolower((char*)&sh_msg[1], &nameptr);
770
771
772   cah = GNUNET_malloc(sizeof(struct ClientGetAuthHandle));
773   cah->client = client;
774   cah->unique_id = sh_msg->id;
775
776   if (strlen(name) < strlen(GNUNET_GNS_TLD))
777   {
778     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
779                 "GET_AUTH: %s is too short. Returning\n", name);
780     cah->name = NULL;
781     send_get_auth_response(cah, name);
782     return;
783   }
784   
785   if (strlen (name) > MAX_DNS_NAME_LENGTH) {
786     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
787                "GET_AUTH: %s is too long", name);
788     cah->name = NULL;
789     send_get_auth_response(cah, name);
790     return;
791   }
792   
793   if (strcmp(name+strlen(name)-strlen(GNUNET_GNS_TLD),
794              GNUNET_GNS_TLD) != 0)
795   {
796     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
797                 "GET_AUTH: %s is not our domain. Returning\n", name);
798     cah->name = NULL;
799     send_get_auth_response(cah, name);
800     return;
801   }
802
803   if (strcmp(name, GNUNET_GNS_TLD) == 0)
804   {
805     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
806                 "GET_AUTH: %s is us. Returning\n", name);
807     cah->name = NULL;
808     send_get_auth_response(cah, name);
809     return;
810   }
811   
812   cah->name = GNUNET_malloc(strlen(name)
813                             - strlen(GNUNET_GNS_TLD) + 1);
814   memset(cah->name, 0,
815          strlen(name)-strlen(GNUNET_GNS_TLD) + 1);
816   memcpy(cah->name, name,
817          strlen(name)-strlen(GNUNET_GNS_TLD));
818
819   /* Start delegation resolution in our namestore */
820   gns_resolver_get_authority(zone_hash, zone_hash, name, &send_get_auth_response, cah);
821 }
822
823
824
825 /**
826  * Reply to client with the result from our lookup.
827  *
828  * @param cls the closure (our client lookup handle)
829  * @param rd_count the number of records
830  * @param rd the record data
831  */
832 static void
833 send_lookup_response(void* cls,
834                      uint32_t rd_count,
835                      const struct GNUNET_NAMESTORE_RecordData *rd)
836 {
837   struct ClientLookupHandle* clh = (struct ClientLookupHandle*)cls;
838   struct GNUNET_GNS_ClientLookupResultMessage *rmsg;
839   size_t len;
840   
841   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message with %d results\n",
842               "LOOKUP_RESULT", rd_count);
843   
844   len = GNUNET_NAMESTORE_records_get_size (rd_count, rd);
845   rmsg = GNUNET_malloc(len+sizeof(struct GNUNET_GNS_ClientLookupResultMessage));
846   
847   rmsg->id = clh->unique_id;
848   rmsg->rd_count = htonl(rd_count);
849   rmsg->header.type = htons(GNUNET_MESSAGE_TYPE_GNS_LOOKUP_RESULT);
850   rmsg->header.size = 
851     htons(len+sizeof(struct GNUNET_GNS_ClientLookupResultMessage));
852
853   GNUNET_NAMESTORE_records_serialize (rd_count, rd, len, (char*)&rmsg[1]);
854   
855   GNUNET_SERVER_notification_context_unicast (nc, clh->client,
856                                 (const struct GNUNET_MessageHeader *) rmsg,
857                                 GNUNET_NO);
858   GNUNET_SERVER_receive_done (clh->client, GNUNET_OK);
859   
860   GNUNET_free(rmsg);
861   GNUNET_free(clh->name);
862   
863   if (NULL != clh->shorten_key)
864     GNUNET_free(clh->shorten_key);
865
866   GNUNET_free(clh);
867
868 }
869
870
871 /**
872  * Handle lookup requests from client
873  *
874  * @param cls the closure
875  * @param client the client
876  * @param message the message
877  */
878 static void
879 handle_lookup(void *cls,
880               struct GNUNET_SERVER_Client * client,
881               const struct GNUNET_MessageHeader * message)
882 {
883   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "LOOKUP");
884
885   size_t msg_size = 0;
886   size_t namelen;
887   char name[MAX_DNS_NAME_LENGTH];
888   struct ClientLookupHandle *clh;
889   char* nameptr = name;
890   int only_cached;
891   struct GNUNET_CRYPTO_RsaPrivateKey *key;
892   struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *pkey;
893   char* tmp_pkey;
894
895   if (ntohs (message->size) < sizeof (struct GNUNET_GNS_ClientLookupMessage))
896   {
897     GNUNET_break_op (0);
898     GNUNET_SERVER_receive_done (client, GNUNET_OK);
899     return;
900   }
901
902   GNUNET_SERVER_notification_context_add (nc, client);
903
904   struct GNUNET_GNS_ClientLookupMessage *sh_msg =
905     (struct GNUNET_GNS_ClientLookupMessage *) message;
906   
907   msg_size = ntohs(message->size);
908
909   if (msg_size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
910   {
911     GNUNET_break_op (0);
912     GNUNET_SERVER_receive_done (client, GNUNET_OK);
913     return;
914   }
915
916   if (1 == ntohl(sh_msg->have_key))
917   {
918     pkey = (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *)&sh_msg[1];
919     tmp_pkey = (char*)&sh_msg[1];
920     key = GNUNET_CRYPTO_rsa_decode_key (tmp_pkey, ntohs(pkey->len));
921     GNUNET_STRINGS_utf8_tolower(&tmp_pkey[ntohs(pkey->len)], &nameptr);
922   }
923   else
924   {
925     key = NULL;
926     GNUNET_STRINGS_utf8_tolower((char*)&sh_msg[1], &nameptr);
927   }
928   
929   namelen = strlen(name)+1;
930   clh = GNUNET_malloc(sizeof(struct ClientLookupHandle));
931   clh->client = client;
932   clh->name = GNUNET_malloc(namelen);
933   strcpy(clh->name, name);
934   clh->unique_id = sh_msg->id;
935   clh->type = ntohl(sh_msg->type);
936   clh->shorten_key = key;
937
938   only_cached = ntohl(sh_msg->only_cached);
939   
940   if (strlen (name) > MAX_DNS_NAME_LENGTH) {
941     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
942                "LOOKUP: %s is too long", name);
943     clh->name = NULL;
944     send_lookup_response(clh, 0, NULL);
945     return;
946   }
947
948   if (1 == ntohl(sh_msg->use_default_zone))
949     clh->zone = zone_hash; //Default zone
950   else
951     clh->zone = sh_msg->zone;
952   
953   if (GNUNET_YES == auto_import_pkey)
954   {
955     gns_resolver_lookup_record (clh->zone, clh->zone, clh->type, clh->name,
956                                 clh->shorten_key,
957                                 default_lookup_timeout,
958                                 clh->only_cached,
959                                 &send_lookup_response, clh);  
960   }
961   else
962   {
963     gns_resolver_lookup_record (clh->zone, clh->zone, clh->type, name,
964                                 NULL,
965                                 default_lookup_timeout,
966                                 only_cached,
967                                 &send_lookup_response, clh);
968   }
969 }
970
971
972
973 /**
974  * Process GNS requests.
975  *
976  * @param cls closure)
977  * @param server the initialized server
978  * @param c configuration to use
979  */
980 static void
981 run (void *cls, struct GNUNET_SERVER_Handle *server,
982      const struct GNUNET_CONFIGURATION_Handle *c)
983 {
984   
985   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Initializing GNS\n");
986   
987   char* keyfile;
988   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pkey;
989   unsigned long long max_parallel_bg_queries = 0;
990   unsigned long long default_lookup_timeout_secs = 0;
991   int ignore_pending = GNUNET_NO;
992
993   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
994     {&handle_shorten, NULL, GNUNET_MESSAGE_TYPE_GNS_SHORTEN, 0},
995     {&handle_lookup, NULL, GNUNET_MESSAGE_TYPE_GNS_LOOKUP, 0},
996     {&handle_get_authority, NULL, GNUNET_MESSAGE_TYPE_GNS_GET_AUTH, 0}
997   };
998
999   GNS_cfg = c;
1000
1001   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (c, "gns",
1002                                              "ZONEKEY", &keyfile))
1003   {
1004     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1005                 "No private key for root zone specified!\n");
1006     GNUNET_SCHEDULER_shutdown ();
1007     return;
1008   }
1009
1010   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1011              "Using keyfile %s for root zone.\n", keyfile);
1012
1013   zone_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
1014   GNUNET_CRYPTO_rsa_key_get_public (zone_key, &pkey);
1015
1016   GNUNET_CRYPTO_short_hash(&pkey,
1017                      sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1018                      &zone_hash);
1019   GNUNET_free(keyfile);
1020   
1021   /**
1022    * handle to our local namestore
1023    */
1024   namestore_handle = GNUNET_NAMESTORE_connect(c);
1025
1026   if (NULL == namestore_handle)
1027   {
1028     //FIXME do error handling;
1029     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1030                "Failed to connect to the namestore!\n");
1031     GNUNET_SCHEDULER_shutdown ();
1032     return;
1033   }
1034   
1035   
1036
1037   auto_import_pkey = GNUNET_NO;
1038
1039   if (GNUNET_YES ==
1040       GNUNET_CONFIGURATION_get_value_yesno (c, "gns",
1041                                             "AUTO_IMPORT_PKEY"))
1042   {
1043     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1044                "Automatic PKEY import is enabled.\n");
1045     auto_import_pkey = GNUNET_YES;
1046
1047   }
1048
1049   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (c, "gns",
1050                                                           "PRIVATE_ZONE",
1051                                                           &private_zone_id))
1052   {
1053     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1054                "Private zone id: %s\n", private_zone_id);
1055   }
1056
1057   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (c, "gns",
1058                                                           "SHORTEN_ZONE",
1059                                                           &shorten_zone_id))
1060   {
1061     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1062                "Shorten zone id: %s\n", shorten_zone_id);
1063   }
1064
1065   dht_max_update_interval = GNUNET_GNS_DHT_MAX_UPDATE_INTERVAL;
1066
1067   if (GNUNET_OK ==
1068       GNUNET_CONFIGURATION_get_value_number (c, "gns",
1069                                              "ZONE_PUT_INTERVAL",
1070                                              &dht_max_update_interval))
1071   {
1072     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1073                "DHT zone update interval: %d\n",
1074                dht_max_update_interval);
1075   }
1076   
1077   max_record_put_interval = 1;
1078
1079   if (GNUNET_OK ==
1080       GNUNET_CONFIGURATION_get_value_number (c, "gns",
1081                                              "RECORD_PUT_INTERVAL",
1082                                              &max_record_put_interval))
1083   {
1084     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1085                "Record put interval: %d\n",
1086                max_record_put_interval);
1087   }
1088   
1089   if (GNUNET_OK ==
1090       GNUNET_CONFIGURATION_get_value_number (c, "gns",
1091                                             "MAX_PARALLEL_BACKGROUND_QUERIES",
1092                                             &max_parallel_bg_queries))
1093   {
1094     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1095                "Number of allowed parallel background queries: %d\n",
1096                max_parallel_bg_queries);
1097   }
1098
1099   if (GNUNET_YES ==
1100       GNUNET_CONFIGURATION_get_value_yesno (c, "gns",
1101                                             "AUTO_IMPORT_CONFIRMATION_REQ"))
1102   {
1103     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1104                "Auto import requires user confirmation\n");
1105     ignore_pending = GNUNET_YES;
1106   }
1107
1108   if (GNUNET_OK ==
1109       GNUNET_CONFIGURATION_get_value_number(c, "gns",
1110                                             "DEFAULT_LOOKUP_TIMEOUT",
1111                                             &default_lookup_timeout_secs))
1112   {
1113     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1114                "Default lookup timeout: %ds\n", default_lookup_timeout_secs);
1115     default_lookup_timeout = GNUNET_TIME_relative_multiply(
1116                                             GNUNET_TIME_UNIT_SECONDS,
1117                                             default_lookup_timeout_secs);
1118   }
1119   
1120   /**
1121    * handle to the dht
1122    */
1123   dht_handle = GNUNET_DHT_connect(c,
1124                        //max_parallel_bg_queries); //FIXME get ht_len from cfg
1125                        1024);
1126
1127   if (NULL == dht_handle)
1128   {
1129     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Could not connect to DHT!\n");
1130   }
1131   
1132   if (gns_resolver_init(namestore_handle, dht_handle, zone_hash, c,
1133                         max_parallel_bg_queries,
1134                         ignore_pending)
1135       == GNUNET_SYSERR)
1136   {
1137     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1138                "Unable to initialize resolver!\n");
1139     GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
1140     return;
1141   }
1142
1143   if (GNUNET_YES ==
1144       GNUNET_CONFIGURATION_get_value_yesno (c, "gns", "HIJACK_DNS"))
1145   {
1146     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1147                "DNS hijacking enabled... connecting to service.\n");
1148
1149     if (gns_interceptor_init(zone_hash, zone_key, c) == GNUNET_SYSERR)
1150     {
1151       GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1152                "Failed to enable the dns interceptor!\n");
1153     }
1154   }
1155   
1156   /**
1157    * Schedule periodic put
1158    * for our records
1159    * We have roughly an hour for all records;
1160    */
1161   record_put_interval = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS,
1162                                                       1);
1163   zone_update_taskid = GNUNET_SCHEDULER_add_now (&update_zone_dht_start, NULL);
1164
1165   GNUNET_SERVER_add_handlers (server, handlers);
1166   
1167   //FIXME
1168   //GNUNET_SERVER_disconnect_notify (server,
1169   //                                 &client_disconnect_notification,
1170   //                                 NULL);
1171
1172   nc = GNUNET_SERVER_notification_context_create (server, 1);
1173
1174   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
1175                                 NULL);
1176 }
1177
1178
1179 /**
1180  * The main function for the GNS service.
1181  *
1182  * @param argc number of arguments from the command line
1183  * @param argv command line arguments
1184  * @return 0 ok, 1 on error
1185  */
1186 int
1187 main (int argc, char *const *argv)
1188 {
1189   int ret;
1190
1191   ret =
1192       (GNUNET_OK ==
1193        GNUNET_SERVICE_run (argc, argv, "gns", GNUNET_SERVICE_OPTION_NONE, &run,
1194                            NULL)) ? 0 : 1;
1195   return ret;
1196 }
1197
1198 /* end of gnunet-service-gns.c */