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