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