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