-bugfixes
[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
504   remaining_time = GNUNET_TIME_absolute_get_remaining (expiration);
505
506   if ((rd_count == 1) &&
507       (remaining_time.rel_value != 0))
508   {
509     remaining_time = GNUNET_TIME_absolute_get_remaining (rd->expiration);
510     if ((rd->record_type == GNUNET_GNS_RECORD_PKEY) &&
511         (remaining_time.rel_value != 0))
512     {
513       csh->shorten_zone = *((struct GNUNET_CRYPTO_ShortHashCode*)rd->data);
514     }
515   }
516   gns_resolver_shorten_name (&csh->root_zone,
517                              &csh->private_zone,
518                              &csh->shorten_zone,
519                              csh->name,
520                              private_zone_id,
521                              shorten_zone_id,
522                              &send_shorten_response, csh);
523
524 }
525
526 static void
527 process_private_zone_shorten (void *cls,
528                       const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
529                       struct GNUNET_TIME_Absolute expiration,
530                       const char *name,
531                       unsigned int rd_count,
532                       const struct GNUNET_NAMESTORE_RecordData *rd,
533                       const struct GNUNET_CRYPTO_RsaSignature *signature)
534 {
535   struct GNUNET_TIME_Relative remaining_time;
536   struct ClientShortenHandle *csh = cls;
537
538   remaining_time = GNUNET_TIME_absolute_get_remaining (expiration);
539
540   if ((rd_count == 1) &&
541       (remaining_time.rel_value != 0))
542   {
543     remaining_time = GNUNET_TIME_absolute_get_remaining (rd->expiration);
544     if ((rd->record_type == GNUNET_GNS_RECORD_PKEY) &&
545         (remaining_time.rel_value != 0))
546     {
547
548
549       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
550                   "Looking for shorten zone in private zone\n");
551       csh->private_zone = *((struct GNUNET_CRYPTO_ShortHashCode*)rd->data);
552       GNUNET_NAMESTORE_lookup_record (namestore_handle,
553                                       &csh->private_zone,
554                                       shorten_zone_id,
555                                       GNUNET_GNS_RECORD_ANY,
556                                       &process_shorten_zone_shorten,
557                                       cls);
558     }
559     return;
560   }
561
562   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
563               "No private zone found!\n");
564   gns_resolver_shorten_name (&csh->root_zone,
565                              &csh->private_zone,
566                              &csh->shorten_zone,
567                              csh->name,
568                              private_zone_id,
569                              shorten_zone_id,
570                              &send_shorten_response, csh);
571
572 }
573
574 /**
575  * Lookup the zone infos and shorten name
576  *
577  * @param csh the shorten handle
578  *
579  */
580 static void
581 start_shorten_name (struct ClientShortenHandle *csh)
582 {
583   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
584               "Looking for private zone in root zone\n");
585
586   GNUNET_NAMESTORE_lookup_record (namestore_handle,
587                                   &csh->root_zone,
588                                   private_zone_id,
589                                   GNUNET_GNS_RECORD_ANY,
590                                   &process_private_zone_shorten,
591                                   csh);
592 }
593
594
595 /**
596  * Handle a shorten message from the api
597  *
598  * @param cls the closure
599  * @param client the client
600  * @param message the message
601  */
602 static void handle_shorten (void *cls,
603                             struct GNUNET_SERVER_Client * client,
604                             const struct GNUNET_MessageHeader * message)
605 {
606   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "SHORTEN");
607
608   size_t msg_size = 0;
609   struct ClientShortenHandle *csh;
610   char name[MAX_DNS_NAME_LENGTH];
611   char* nameptr = name;
612
613   if (ntohs (message->size) < sizeof (struct GNUNET_GNS_ClientShortenMessage))
614   {
615     GNUNET_break_op (0);
616     GNUNET_SERVER_receive_done (client, GNUNET_OK);
617     return;
618   }
619
620
621   struct GNUNET_GNS_ClientShortenMessage *sh_msg =
622     (struct GNUNET_GNS_ClientShortenMessage *) message;
623   
624   msg_size = ntohs(message->size);
625
626   if (msg_size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
627   {
628     GNUNET_break_op (0);
629     GNUNET_SERVER_receive_done (client, GNUNET_OK);
630     return;
631   }
632
633   csh = GNUNET_malloc(sizeof(struct ClientShortenHandle));
634   csh->client = client;
635   csh->unique_id = sh_msg->id;
636   csh->shorten_key = NULL;
637   
638   GNUNET_STRINGS_utf8_tolower((char*)&sh_msg[1], &nameptr);
639
640   if (strlen (name) < strlen(GNUNET_GNS_TLD)) {
641     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
642                "SHORTEN: %s is too short", name);
643     send_shorten_response(csh, name);
644     return;
645   }
646
647   if (strlen (name) > MAX_DNS_NAME_LENGTH) {
648     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
649                "SHORTEN: %s is too long", name);
650     send_shorten_response(csh, name);
651     return;
652   }
653   
654   if (!is_gnunet_tld(name) && !is_zkey_tld(name))
655   {
656     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
657                 "%s is not our domain. Returning\n", name);
658     send_shorten_response(csh, name);
659     return;
660   }
661
662   strcpy (csh->name, name);
663   
664   GNUNET_SERVER_notification_context_add (nc, client);
665   
666   if (1 == ntohl(sh_msg->use_default_zone))
667     csh->root_zone = zone_hash; //Default zone
668   else
669     csh->root_zone = sh_msg->zone;
670
671   start_shorten_name (csh);
672   
673 }
674
675
676 /**
677  * Send get authority response back to client
678  * 
679  * @param cls the closure containing a client get auth handle
680  * @param name the shortened name result or NULL if cannot be shortened
681  */
682 static void
683 send_get_auth_response(void *cls, const char* name)
684 {
685   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message with %s\n",
686               "GET_AUTH_RESULT", name);
687   struct GNUNET_GNS_ClientGetAuthResultMessage *rmsg;
688   struct ClientGetAuthHandle *cah = (struct ClientGetAuthHandle *)cls;
689   
690   if (name == NULL)
691   {
692     name = "";
693   }
694
695   rmsg = GNUNET_malloc(sizeof(struct GNUNET_GNS_ClientGetAuthResultMessage)
696                        + strlen(name) + 1);
697   
698   rmsg->id = cah->unique_id;
699   rmsg->header.type = htons(GNUNET_MESSAGE_TYPE_GNS_GET_AUTH_RESULT);
700   rmsg->header.size = 
701     htons(sizeof(struct GNUNET_GNS_ClientGetAuthResultMessage) +
702           strlen(name) + 1);
703
704   strcpy((char*)&rmsg[1], name);
705
706   GNUNET_SERVER_notification_context_unicast (nc, cah->client,
707                               (const struct GNUNET_MessageHeader *) rmsg,
708                               GNUNET_NO);
709   GNUNET_SERVER_receive_done (cah->client, GNUNET_OK);
710   
711   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Cleaning up handles...\n");
712
713   GNUNET_free(rmsg);
714   GNUNET_free_non_null(cah->name);
715   GNUNET_free(cah);
716
717   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "done.\n");
718
719 }
720
721
722 /**
723  * Handle a get authority message from the api
724  *
725  * @param cls the closure
726  * @param client the client
727  * @param message the message
728  */
729 static void handle_get_authority(void *cls,
730                            struct GNUNET_SERVER_Client * client,
731                            const struct GNUNET_MessageHeader * message)
732 {
733   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "GET_AUTH");
734
735   size_t msg_size = 0;
736   struct ClientGetAuthHandle *cah;
737   char name[MAX_DNS_NAME_LENGTH];
738   char* nameptr = name;
739
740
741   if (ntohs (message->size) < sizeof (struct GNUNET_GNS_ClientGetAuthMessage))
742   {
743     GNUNET_break_op (0);
744     GNUNET_SERVER_receive_done (client, GNUNET_OK);
745     return;
746   }
747
748   GNUNET_SERVER_notification_context_add (nc, client);
749
750   struct GNUNET_GNS_ClientGetAuthMessage *sh_msg =
751     (struct GNUNET_GNS_ClientGetAuthMessage *) message;
752   
753   msg_size = ntohs(message->size);
754
755   if (msg_size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
756   {
757     GNUNET_break_op (0);
758     GNUNET_SERVER_receive_done (client, GNUNET_OK);
759     return;
760   }
761   
762   GNUNET_STRINGS_utf8_tolower((char*)&sh_msg[1], &nameptr);
763
764
765   cah = GNUNET_malloc(sizeof(struct ClientGetAuthHandle));
766   cah->client = client;
767   cah->unique_id = sh_msg->id;
768
769   if (strlen(name) < strlen(GNUNET_GNS_TLD))
770   {
771     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
772                 "GET_AUTH: %s is too short. Returning\n", name);
773     cah->name = NULL;
774     send_get_auth_response(cah, name);
775     return;
776   }
777   
778   if (strlen (name) > MAX_DNS_NAME_LENGTH) {
779     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
780                "GET_AUTH: %s is too long", name);
781     cah->name = NULL;
782     send_get_auth_response(cah, name);
783     return;
784   }
785   
786   if (strcmp(name+strlen(name)-strlen(GNUNET_GNS_TLD),
787              GNUNET_GNS_TLD) != 0)
788   {
789     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
790                 "GET_AUTH: %s is not our domain. Returning\n", name);
791     cah->name = NULL;
792     send_get_auth_response(cah, name);
793     return;
794   }
795
796   if (strcmp(name, GNUNET_GNS_TLD) == 0)
797   {
798     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
799                 "GET_AUTH: %s is us. Returning\n", name);
800     cah->name = NULL;
801     send_get_auth_response(cah, name);
802     return;
803   }
804   
805   cah->name = GNUNET_malloc(strlen(name)
806                             - strlen(GNUNET_GNS_TLD) + 1);
807   memset(cah->name, 0,
808          strlen(name)-strlen(GNUNET_GNS_TLD) + 1);
809   memcpy(cah->name, name,
810          strlen(name)-strlen(GNUNET_GNS_TLD));
811
812   /* Start delegation resolution in our namestore */
813   gns_resolver_get_authority(zone_hash, zone_hash, name, &send_get_auth_response, cah);
814 }
815
816
817
818 /**
819  * Reply to client with the result from our lookup.
820  *
821  * @param cls the closure (our client lookup handle)
822  * @param rd_count the number of records
823  * @param rd the record data
824  */
825 static void
826 send_lookup_response(void* cls,
827                      uint32_t rd_count,
828                      const struct GNUNET_NAMESTORE_RecordData *rd)
829 {
830   struct ClientLookupHandle* clh = (struct ClientLookupHandle*)cls;
831   struct GNUNET_GNS_ClientLookupResultMessage *rmsg;
832   size_t len;
833   
834   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message with %d results\n",
835               "LOOKUP_RESULT", rd_count);
836   
837   len = GNUNET_NAMESTORE_records_get_size (rd_count, rd);
838   rmsg = GNUNET_malloc(len+sizeof(struct GNUNET_GNS_ClientLookupResultMessage));
839   
840   rmsg->id = clh->unique_id;
841   rmsg->rd_count = htonl(rd_count);
842   rmsg->header.type = htons(GNUNET_MESSAGE_TYPE_GNS_LOOKUP_RESULT);
843   rmsg->header.size = 
844     htons(len+sizeof(struct GNUNET_GNS_ClientLookupResultMessage));
845
846   GNUNET_NAMESTORE_records_serialize (rd_count, rd, len, (char*)&rmsg[1]);
847   
848   GNUNET_SERVER_notification_context_unicast (nc, clh->client,
849                                 (const struct GNUNET_MessageHeader *) rmsg,
850                                 GNUNET_NO);
851   GNUNET_SERVER_receive_done (clh->client, GNUNET_OK);
852   
853   GNUNET_free(rmsg);
854   GNUNET_free(clh->name);
855   
856   if (NULL != clh->shorten_key)
857     GNUNET_free(clh->shorten_key);
858
859   GNUNET_free(clh);
860
861 }
862
863
864 /**
865  * Handle lookup requests from client
866  *
867  * @param cls the closure
868  * @param client the client
869  * @param message the message
870  */
871 static void
872 handle_lookup(void *cls,
873               struct GNUNET_SERVER_Client * client,
874               const struct GNUNET_MessageHeader * message)
875 {
876   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "LOOKUP");
877
878   size_t msg_size = 0;
879   size_t namelen;
880   char name[MAX_DNS_NAME_LENGTH];
881   struct ClientLookupHandle *clh;
882   char* nameptr = name;
883   int only_cached;
884   struct GNUNET_CRYPTO_RsaPrivateKey *key;
885   struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *pkey;
886   char* tmp_pkey;
887
888   if (ntohs (message->size) < sizeof (struct GNUNET_GNS_ClientLookupMessage))
889   {
890     GNUNET_break_op (0);
891     GNUNET_SERVER_receive_done (client, GNUNET_OK);
892     return;
893   }
894
895   GNUNET_SERVER_notification_context_add (nc, client);
896
897   struct GNUNET_GNS_ClientLookupMessage *sh_msg =
898     (struct GNUNET_GNS_ClientLookupMessage *) message;
899   
900   msg_size = ntohs(message->size);
901
902   if (msg_size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
903   {
904     GNUNET_break_op (0);
905     GNUNET_SERVER_receive_done (client, GNUNET_OK);
906     return;
907   }
908
909   if (1 == ntohl(sh_msg->have_key))
910   {
911     pkey = (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *)&sh_msg[1];
912     tmp_pkey = (char*)&sh_msg[1];
913     key = GNUNET_CRYPTO_rsa_decode_key (tmp_pkey, ntohs(pkey->len));
914     GNUNET_STRINGS_utf8_tolower(&tmp_pkey[ntohs(pkey->len)], &nameptr);
915   }
916   else
917   {
918     key = NULL;
919     GNUNET_STRINGS_utf8_tolower((char*)&sh_msg[1], &nameptr);
920   }
921   
922   namelen = strlen(name)+1;
923   clh = GNUNET_malloc(sizeof(struct ClientLookupHandle));
924   clh->client = client;
925   clh->name = GNUNET_malloc(namelen);
926   strcpy(clh->name, name);
927   clh->unique_id = sh_msg->id;
928   clh->type = ntohl(sh_msg->type);
929   clh->shorten_key = key;
930
931   only_cached = ntohl(sh_msg->only_cached);
932   
933   if (strlen (name) > MAX_DNS_NAME_LENGTH) {
934     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
935                "LOOKUP: %s is too long", name);
936     clh->name = NULL;
937     send_lookup_response(clh, 0, NULL);
938     return;
939   }
940
941   if (1 == ntohl(sh_msg->use_default_zone))
942     clh->zone = zone_hash; //Default zone
943   else
944     clh->zone = sh_msg->zone;
945   
946   if (GNUNET_YES == auto_import_pkey)
947   {
948     gns_resolver_lookup_record (clh->zone, clh->zone, clh->type, clh->name,
949                                 clh->shorten_key,
950                                 default_lookup_timeout,
951                                 clh->only_cached,
952                                 &send_lookup_response, clh);  
953   }
954   else
955   {
956     gns_resolver_lookup_record (clh->zone, clh->zone, clh->type, name,
957                                 NULL,
958                                 default_lookup_timeout,
959                                 only_cached,
960                                 &send_lookup_response, clh);
961   }
962 }
963
964
965
966 /**
967  * Process GNS requests.
968  *
969  * @param cls closure)
970  * @param server the initialized server
971  * @param c configuration to use
972  */
973 static void
974 run (void *cls, struct GNUNET_SERVER_Handle *server,
975      const struct GNUNET_CONFIGURATION_Handle *c)
976 {
977   
978   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Initializing GNS\n");
979   
980   char* keyfile;
981   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pkey;
982   unsigned long long max_parallel_bg_queries = 0;
983   unsigned long long default_lookup_timeout_secs = 0;
984   int ignore_pending = GNUNET_NO;
985
986   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
987     {&handle_shorten, NULL, GNUNET_MESSAGE_TYPE_GNS_SHORTEN, 0},
988     {&handle_lookup, NULL, GNUNET_MESSAGE_TYPE_GNS_LOOKUP, 0},
989     {&handle_get_authority, NULL, GNUNET_MESSAGE_TYPE_GNS_GET_AUTH, 0}
990   };
991
992   GNS_cfg = c;
993
994   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (c, "gns",
995                                              "ZONEKEY", &keyfile))
996   {
997     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
998                 "No private key for root zone specified!\n");
999     GNUNET_SCHEDULER_shutdown ();
1000     return;
1001   }
1002
1003   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1004              "Using keyfile %s for root zone.\n", keyfile);
1005
1006   zone_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
1007   GNUNET_CRYPTO_rsa_key_get_public (zone_key, &pkey);
1008
1009   GNUNET_CRYPTO_short_hash(&pkey,
1010                      sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1011                      &zone_hash);
1012   GNUNET_free(keyfile);
1013   
1014   /**
1015    * handle to our local namestore
1016    */
1017   namestore_handle = GNUNET_NAMESTORE_connect(c);
1018
1019   if (NULL == namestore_handle)
1020   {
1021     //FIXME do error handling;
1022     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1023                "Failed to connect to the namestore!\n");
1024     GNUNET_SCHEDULER_shutdown ();
1025     return;
1026   }
1027   
1028   
1029
1030   auto_import_pkey = GNUNET_NO;
1031
1032   if (GNUNET_YES ==
1033       GNUNET_CONFIGURATION_get_value_yesno (c, "gns",
1034                                             "AUTO_IMPORT_PKEY"))
1035   {
1036     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1037                "Automatic PKEY import is enabled.\n");
1038     auto_import_pkey = GNUNET_YES;
1039
1040   }
1041
1042   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (c, "gns",
1043                                                           "PRIVATE_ZONE",
1044                                                           &private_zone_id))
1045   {
1046     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1047                "Private zone id: %s\n", private_zone_id);
1048   }
1049
1050   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (c, "gns",
1051                                                           "SHORTEN_ZONE",
1052                                                           &shorten_zone_id))
1053   {
1054     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1055                "Shorten zone id: %s\n", shorten_zone_id);
1056   }
1057
1058   dht_max_update_interval = GNUNET_GNS_DHT_MAX_UPDATE_INTERVAL;
1059
1060   if (GNUNET_OK ==
1061       GNUNET_CONFIGURATION_get_value_number (c, "gns",
1062                                              "ZONE_PUT_INTERVAL",
1063                                              &dht_max_update_interval))
1064   {
1065     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1066                "DHT zone update interval: %d\n",
1067                dht_max_update_interval);
1068   }
1069   
1070   max_record_put_interval = 1;
1071
1072   if (GNUNET_OK ==
1073       GNUNET_CONFIGURATION_get_value_number (c, "gns",
1074                                              "RECORD_PUT_INTERVAL",
1075                                              &max_record_put_interval))
1076   {
1077     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1078                "Record put interval: %d\n",
1079                max_record_put_interval);
1080   }
1081   
1082   if (GNUNET_OK ==
1083       GNUNET_CONFIGURATION_get_value_number (c, "gns",
1084                                             "MAX_PARALLEL_BACKGROUND_QUERIES",
1085                                             &max_parallel_bg_queries))
1086   {
1087     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1088                "Number of allowed parallel background queries: %d\n",
1089                max_parallel_bg_queries);
1090   }
1091
1092   if (GNUNET_YES ==
1093       GNUNET_CONFIGURATION_get_value_yesno (c, "gns",
1094                                             "AUTO_IMPORT_CONFIRMATION_REQ"))
1095   {
1096     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1097                "Auto import requires user confirmation\n");
1098     ignore_pending = GNUNET_YES;
1099   }
1100
1101   if (GNUNET_OK ==
1102       GNUNET_CONFIGURATION_get_value_number(c, "gns",
1103                                             "DEFAULT_LOOKUP_TIMEOUT",
1104                                             &default_lookup_timeout_secs))
1105   {
1106     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1107                "Default lookup timeout: %ds\n", default_lookup_timeout_secs);
1108     default_lookup_timeout = GNUNET_TIME_relative_multiply(
1109                                             GNUNET_TIME_UNIT_SECONDS,
1110                                             default_lookup_timeout_secs);
1111   }
1112   
1113   /**
1114    * handle to the dht
1115    */
1116   dht_handle = GNUNET_DHT_connect(c,
1117                        //max_parallel_bg_queries); //FIXME get ht_len from cfg
1118                        1024);
1119
1120   if (NULL == dht_handle)
1121   {
1122     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Could not connect to DHT!\n");
1123   }
1124   
1125   if (gns_resolver_init(namestore_handle, dht_handle, zone_hash, c,
1126                         max_parallel_bg_queries,
1127                         ignore_pending)
1128       == GNUNET_SYSERR)
1129   {
1130     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1131                "Unable to initialize resolver!\n");
1132     GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
1133     return;
1134   }
1135
1136   if (GNUNET_YES ==
1137       GNUNET_CONFIGURATION_get_value_yesno (c, "gns", "HIJACK_DNS"))
1138   {
1139     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1140                "DNS hijacking enabled... connecting to service.\n");
1141
1142     if (gns_interceptor_init(zone_hash, zone_key, c) == GNUNET_SYSERR)
1143     {
1144       GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1145                "Failed to enable the dns interceptor!\n");
1146     }
1147   }
1148   
1149   /**
1150    * Schedule periodic put
1151    * for our records
1152    * We have roughly an hour for all records;
1153    */
1154   record_put_interval = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS,
1155                                                       1);
1156   zone_update_taskid = GNUNET_SCHEDULER_add_now (&update_zone_dht_start, NULL);
1157
1158   GNUNET_SERVER_add_handlers (server, handlers);
1159   
1160   //FIXME
1161   //GNUNET_SERVER_disconnect_notify (server,
1162   //                                 &client_disconnect_notification,
1163   //                                 NULL);
1164
1165   nc = GNUNET_SERVER_notification_context_create (server, 1);
1166
1167   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
1168                                 NULL);
1169 }
1170
1171
1172 /**
1173  * The main function for the GNS service.
1174  *
1175  * @param argc number of arguments from the command line
1176  * @param argv command line arguments
1177  * @return 0 ok, 1 on error
1178  */
1179 int
1180 main (int argc, char *const *argv)
1181 {
1182   int ret;
1183
1184   ret =
1185       (GNUNET_OK ==
1186        GNUNET_SERVICE_run (argc, argv, "gns", GNUNET_SERVICE_OPTION_NONE, &run,
1187                            NULL)) ? 0 : 1;
1188   return ret;
1189 }
1190
1191 /* end of gnunet-service-gns.c */