-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   /* 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 tc task context
216  */
217 static void
218 record_dht_put(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
219 {
220   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "put request transmitted\n");
221 }
222
223 /* prototype */
224 static void
225 update_zone_dht_start(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
226
227 /**
228  * Function used to put all records successively into the DHT.
229  *
230  * @param cls the closure (NULL)
231  * @param key the public key of the authority (ours)
232  * @param expiration lifetime of the namestore entry
233  * @param name the name of the records
234  * @param rd_count the number of records in data
235  * @param rd the record data
236  * @param signature the signature for the record data
237  */
238 static void
239 put_gns_record(void *cls,
240                 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
241                 struct GNUNET_TIME_Absolute expiration,
242                 const char *name,
243                 unsigned int rd_count,
244                 const struct GNUNET_NAMESTORE_RecordData *rd,
245                 const struct GNUNET_CRYPTO_RsaSignature *signature)
246 {
247   
248   struct GNSNameRecordBlock *nrb;
249   struct GNUNET_CRYPTO_ShortHashCode name_hash;
250   GNUNET_HashCode xor_hash;
251   GNUNET_HashCode name_hash_double;
252   GNUNET_HashCode zone_hash_double;
253   struct GNUNET_CRYPTO_HashAsciiEncoded xor_hash_string;
254   uint32_t rd_payload_length;
255   char* nrb_data = NULL;
256   size_t namelen;
257
258   /* we're done */
259   if (NULL == name)
260   {
261     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
262                "Zone iteration finished. Rescheduling put in %ds\n",
263                dht_max_update_interval);
264     zone_update_taskid = GNUNET_SCHEDULER_add_delayed (
265                                         GNUNET_TIME_relative_multiply(
266                                             GNUNET_TIME_UNIT_SECONDS,
267                                             dht_max_update_interval
268                                             ),
269                                             &update_zone_dht_start,
270                                             NULL);
271     return;
272   }
273   
274   namelen = strlen(name) + 1;
275   
276   if (signature == NULL)
277   {
278     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
279                "No signature for %s record data provided! Skipping...\n",
280                name);
281     zone_update_taskid = GNUNET_SCHEDULER_add_now (&update_zone_dht_next,
282                                                    NULL);
283     return;
284
285   }
286   
287   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
288              "Putting records for %s into the DHT\n", name);
289   
290   rd_payload_length = GNUNET_NAMESTORE_records_get_size (rd_count, rd);
291   
292   nrb = GNUNET_malloc(rd_payload_length + namelen
293                       + sizeof(struct GNSNameRecordBlock));
294   
295   nrb->signature = *signature;
296   
297   nrb->public_key = *key;
298
299   nrb->rd_count = htonl(rd_count);
300   
301   memcpy(&nrb[1], name, namelen);
302
303   nrb_data = (char*)&nrb[1];
304   nrb_data += namelen;
305
306   rd_payload_length += sizeof(struct GNSNameRecordBlock) + namelen;
307
308   if (-1 == GNUNET_NAMESTORE_records_serialize (rd_count,
309                                                 rd,
310                                                 rd_payload_length,
311                                                 nrb_data))
312   {
313     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
314                "Record serialization failed! Skipping...\n");
315     GNUNET_free(nrb);
316     zone_update_taskid = GNUNET_SCHEDULER_add_now (&update_zone_dht_next,
317                                                    NULL);
318     return;
319   }
320
321
322   /*
323    * calculate DHT key: H(name) xor H(pubkey)
324    */
325   GNUNET_CRYPTO_short_hash(name, strlen(name), &name_hash);
326   GNUNET_CRYPTO_short_hash_double (&name_hash, &name_hash_double);
327   GNUNET_CRYPTO_short_hash_double (&zone_hash, &zone_hash_double);
328   GNUNET_CRYPTO_hash_xor(&zone_hash_double, &name_hash_double, &xor_hash);
329   GNUNET_CRYPTO_hash_to_enc (&xor_hash, &xor_hash_string);
330
331   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
332              "putting records for %s under key: %s with size %d\n",
333              name, (char*)&xor_hash_string, rd_payload_length);
334   
335   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
336              "DHT req to %d\n", DHT_OPERATION_TIMEOUT.rel_value);
337
338   GNUNET_DHT_put (dht_handle, &xor_hash,
339                   DHT_GNS_REPLICATION_LEVEL,
340                   GNUNET_DHT_RO_NONE,
341                   GNUNET_BLOCK_TYPE_GNS_NAMERECORD,
342                   rd_payload_length,
343                   (char*)nrb,
344                   expiration,
345                   DHT_OPERATION_TIMEOUT,
346                   &record_dht_put,
347                   NULL); //cls for cont
348   
349   num_public_records++;
350
351   /**
352    * Reschedule periodic put
353    */
354   zone_update_taskid = GNUNET_SCHEDULER_add_delayed (record_put_interval,
355                                 &update_zone_dht_next,
356                                 NULL);
357
358   GNUNET_free(nrb);
359
360 }
361
362 /**
363  * Periodically iterate over our zone and store everything in dht
364  *
365  * @param cls NULL
366  * @param tc task context
367  */
368 static void
369 update_zone_dht_start(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
370 {
371   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Scheduling DHT zone update!\n");
372   
373   unsigned long long int interval = 0;
374
375   if (0 == num_public_records)
376   {
377     /**
378      * If no records are known (startup) or none present
379      * we can safely set the interval to 1s
380      */
381     record_put_interval = GNUNET_TIME_relative_multiply(
382                                             GNUNET_TIME_UNIT_SECONDS,
383                                             1);
384     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
385                "No records in db. Adjusted record put interval to 1s\n");
386   }
387   else
388   {
389     interval = max_record_put_interval/num_public_records;
390     if (interval == 0)
391       interval = 1;
392     record_put_interval = GNUNET_TIME_relative_multiply(
393                                   GNUNET_TIME_UNIT_SECONDS,
394                                   interval);
395     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
396                "Adjusted DHT update interval to %ds!\n",
397                interval);
398   }
399
400   /* start counting again */
401   num_public_records = 0;
402   namestore_iter = GNUNET_NAMESTORE_zone_iteration_start (namestore_handle,
403                                                  &zone_hash,
404                                                  GNUNET_NAMESTORE_RF_AUTHORITY,
405                                                  GNUNET_NAMESTORE_RF_PRIVATE,
406                                                  &put_gns_record,
407                                                  NULL);
408 }
409
410
411 /* END DHT ZONE PROPAGATION */
412
413 /**
414  * Send shorten response back to client
415  * 
416  * @param cls the closure containing a client shorten handle
417  * @param name the shortened name result or NULL if cannot be shortened
418  */
419 static void
420 send_shorten_response(void* cls, const char* name)
421 {
422   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message with %s\n",
423               "SHORTEN_RESULT", name);
424   struct GNUNET_GNS_ClientShortenResultMessage *rmsg;
425   struct ClientShortenHandle *csh = (struct ClientShortenHandle *)cls;
426   
427   if (name == NULL)
428   {
429     name = "";
430   }
431
432   rmsg = GNUNET_malloc(sizeof(struct GNUNET_GNS_ClientShortenResultMessage)
433                        + strlen(name) + 1);
434   
435   rmsg->id = csh->unique_id;
436   rmsg->header.type = htons(GNUNET_MESSAGE_TYPE_GNS_SHORTEN_RESULT);
437   rmsg->header.size = 
438     htons(sizeof(struct GNUNET_GNS_ClientShortenResultMessage) +
439           strlen(name) + 1);
440
441   strcpy((char*)&rmsg[1], name);
442
443   GNUNET_SERVER_notification_context_unicast (nc, csh->client,
444                               (const struct GNUNET_MessageHeader *) rmsg,
445                               GNUNET_NO);
446   GNUNET_SERVER_receive_done (csh->client, GNUNET_OK);
447   
448   GNUNET_free(rmsg);
449   GNUNET_free_non_null(csh->name);
450   GNUNET_free(csh);
451
452 }
453
454 /**
455  * Handle a shorten message from the api
456  *
457  * @param cls the closure
458  * @param client the client
459  * @param message the message
460  */
461 static void handle_shorten(void *cls,
462                            struct GNUNET_SERVER_Client * client,
463                            const struct GNUNET_MessageHeader * message)
464 {
465   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "SHORTEN");
466
467   size_t msg_size = 0;
468   struct ClientShortenHandle *csh;
469   char name[MAX_DNS_NAME_LENGTH];
470   char* nameptr = name;
471
472   if (ntohs (message->size) < sizeof (struct GNUNET_GNS_ClientShortenMessage))
473   {
474     GNUNET_break_op (0);
475     GNUNET_SERVER_receive_done (client, GNUNET_OK);
476     return;
477   }
478
479
480   struct GNUNET_GNS_ClientShortenMessage *sh_msg =
481     (struct GNUNET_GNS_ClientShortenMessage *) message;
482   
483   msg_size = ntohs(message->size);
484
485   if (msg_size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
486   {
487     GNUNET_break_op (0);
488     GNUNET_SERVER_receive_done (client, GNUNET_OK);
489     return;
490   }
491
492   csh = GNUNET_malloc(sizeof(struct ClientShortenHandle));
493   csh->client = client;
494   csh->unique_id = sh_msg->id;
495   
496   GNUNET_STRINGS_utf8_tolower((char*)&sh_msg[1], &nameptr);
497
498   if (strlen (name) < strlen(GNUNET_GNS_TLD)) {
499     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
500                "SHORTEN: %s is too short", name);
501     csh->name = NULL;
502     send_shorten_response(csh, name);
503     return;
504   }
505
506   if (strlen (name) > MAX_DNS_NAME_LENGTH) {
507     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
508                "SHORTEN: %s is too long", name);
509     csh->name = NULL;
510     send_shorten_response(csh, name);
511     return;
512   }
513   
514   if (!is_gnunet_tld(name) && !is_zkey_tld(name))
515   {
516     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
517                 "%s is not our domain. Returning\n", name);
518     csh->name = NULL;
519     send_shorten_response(csh, name);
520     return;
521   }
522   
523   GNUNET_SERVER_notification_context_add (nc, client);
524   
525   /* Start shortening */
526   if (GNUNET_YES == auto_import_pkey)
527     gns_resolver_shorten_name(zone_hash, name, zone_key,
528                               &send_shorten_response, csh);
529   else
530     gns_resolver_shorten_name(zone_hash, name, NULL,
531                               &send_shorten_response, csh);
532 }
533
534
535 /**
536  * Send get authority response back to client
537  * 
538  * @param cls the closure containing a client get auth handle
539  * @param name the shortened name result or NULL if cannot be shortened
540  */
541 static void
542 send_get_auth_response(void *cls, const char* name)
543 {
544   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message with %s\n",
545               "GET_AUTH_RESULT", name);
546   struct GNUNET_GNS_ClientGetAuthResultMessage *rmsg;
547   struct ClientGetAuthHandle *cah = (struct ClientGetAuthHandle *)cls;
548   
549   if (name == NULL)
550   {
551     name = "";
552   }
553
554   rmsg = GNUNET_malloc(sizeof(struct GNUNET_GNS_ClientGetAuthResultMessage)
555                        + strlen(name) + 1);
556   
557   rmsg->id = cah->unique_id;
558   rmsg->header.type = htons(GNUNET_MESSAGE_TYPE_GNS_GET_AUTH_RESULT);
559   rmsg->header.size = 
560     htons(sizeof(struct GNUNET_GNS_ClientGetAuthResultMessage) +
561           strlen(name) + 1);
562
563   strcpy((char*)&rmsg[1], name);
564
565   GNUNET_SERVER_notification_context_unicast (nc, cah->client,
566                               (const struct GNUNET_MessageHeader *) rmsg,
567                               GNUNET_NO);
568   GNUNET_SERVER_receive_done (cah->client, GNUNET_OK);
569   
570   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Cleaning up handles...\n");
571
572   GNUNET_free(rmsg);
573   GNUNET_free_non_null(cah->name);
574   GNUNET_free(cah);
575
576   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "done.\n");
577
578 }
579
580
581 /**
582  * Handle a get authority message from the api
583  *
584  * @param cls the closure
585  * @param client the client
586  * @param message the message
587  */
588 static void handle_get_authority(void *cls,
589                            struct GNUNET_SERVER_Client * client,
590                            const struct GNUNET_MessageHeader * message)
591 {
592   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "GET_AUTH");
593
594   size_t msg_size = 0;
595   struct ClientGetAuthHandle *cah;
596   char name[MAX_DNS_NAME_LENGTH];
597   char* nameptr = name;
598
599
600   if (ntohs (message->size) < sizeof (struct GNUNET_GNS_ClientGetAuthMessage))
601   {
602     GNUNET_break_op (0);
603     GNUNET_SERVER_receive_done (client, GNUNET_OK);
604     return;
605   }
606
607   GNUNET_SERVER_notification_context_add (nc, client);
608
609   struct GNUNET_GNS_ClientGetAuthMessage *sh_msg =
610     (struct GNUNET_GNS_ClientGetAuthMessage *) message;
611   
612   msg_size = ntohs(message->size);
613
614   if (msg_size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
615   {
616     GNUNET_break_op (0);
617     GNUNET_SERVER_receive_done (client, GNUNET_OK);
618     return;
619   }
620   
621   GNUNET_STRINGS_utf8_tolower((char*)&sh_msg[1], &nameptr);
622
623
624   cah = GNUNET_malloc(sizeof(struct ClientGetAuthHandle));
625   cah->client = client;
626   cah->unique_id = sh_msg->id;
627
628   if (strlen(name) < strlen(GNUNET_GNS_TLD))
629   {
630     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
631                 "GET_AUTH: %s is too short. Returning\n", name);
632     cah->name = NULL;
633     send_get_auth_response(cah, name);
634     return;
635   }
636   
637   if (strlen (name) > MAX_DNS_NAME_LENGTH) {
638     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
639                "GET_AUTH: %s is too long", name);
640     cah->name = NULL;
641     send_get_auth_response(cah, name);
642     return;
643   }
644   
645   if (strcmp(name+strlen(name)-strlen(GNUNET_GNS_TLD),
646              GNUNET_GNS_TLD) != 0)
647   {
648     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
649                 "GET_AUTH: %s is not our domain. Returning\n", name);
650     cah->name = NULL;
651     send_get_auth_response(cah, name);
652     return;
653   }
654
655   if (strcmp(name, GNUNET_GNS_TLD) == 0)
656   {
657     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
658                 "GET_AUTH: %s is us. Returning\n", name);
659     cah->name = NULL;
660     send_get_auth_response(cah, name);
661     return;
662   }
663   
664   cah->name = GNUNET_malloc(strlen(name)
665                             - strlen(GNUNET_GNS_TLD) + 1);
666   memset(cah->name, 0,
667          strlen(name)-strlen(GNUNET_GNS_TLD) + 1);
668   memcpy(cah->name, name,
669          strlen(name)-strlen(GNUNET_GNS_TLD));
670
671   /* Start delegation resolution in our namestore */
672   gns_resolver_get_authority(zone_hash, name, &send_get_auth_response, cah);
673 }
674
675
676 /**
677  * Reply to client with the result from our lookup.
678  *
679  * @param cls the closure (our client lookup handle)
680  * @param rd_count the number of records
681  * @param rd the record data
682  */
683 static void
684 send_lookup_response(void* cls,
685                      uint32_t rd_count,
686                      const struct GNUNET_NAMESTORE_RecordData *rd)
687 {
688   struct ClientLookupHandle* clh = (struct ClientLookupHandle*)cls;
689   struct GNUNET_GNS_ClientLookupResultMessage *rmsg;
690   size_t len;
691   
692   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message with %d results\n",
693               "LOOKUP_RESULT", rd_count);
694   
695   len = GNUNET_NAMESTORE_records_get_size (rd_count, rd);
696   rmsg = GNUNET_malloc(len+sizeof(struct GNUNET_GNS_ClientLookupResultMessage));
697   
698   rmsg->id = clh->unique_id;
699   rmsg->rd_count = htonl(rd_count);
700   rmsg->header.type = htons(GNUNET_MESSAGE_TYPE_GNS_LOOKUP_RESULT);
701   rmsg->header.size = 
702     htons(len+sizeof(struct GNUNET_GNS_ClientLookupResultMessage));
703
704   GNUNET_NAMESTORE_records_serialize (rd_count, rd, len, (char*)&rmsg[1]);
705   
706   GNUNET_SERVER_notification_context_unicast (nc, clh->client,
707                                 (const struct GNUNET_MessageHeader *) rmsg,
708                                 GNUNET_NO);
709   GNUNET_SERVER_receive_done (clh->client, GNUNET_OK);
710   
711   GNUNET_free(rmsg);
712   GNUNET_free(clh->name);
713   GNUNET_free(clh);
714
715 }
716
717
718 /**
719  * Handle lookup requests from client
720  *
721  * @param cls the closure
722  * @param client the client
723  * @param message the message
724  */
725 static void
726 handle_lookup(void *cls,
727               struct GNUNET_SERVER_Client * client,
728               const struct GNUNET_MessageHeader * message)
729 {
730   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "LOOKUP");
731
732   size_t msg_size = 0;
733   size_t namelen;
734   char name[MAX_DNS_NAME_LENGTH];
735   struct ClientLookupHandle *clh;
736   char* nameptr = name;
737
738   if (ntohs (message->size) < sizeof (struct GNUNET_GNS_ClientLookupMessage))
739   {
740     GNUNET_break_op (0);
741     GNUNET_SERVER_receive_done (client, GNUNET_OK);
742     return;
743   }
744
745   GNUNET_SERVER_notification_context_add (nc, client);
746
747   struct GNUNET_GNS_ClientLookupMessage *sh_msg =
748     (struct GNUNET_GNS_ClientLookupMessage *) message;
749   
750   msg_size = ntohs(message->size);
751
752   if (msg_size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
753   {
754     GNUNET_break_op (0);
755     GNUNET_SERVER_receive_done (client, GNUNET_OK);
756     return;
757   }
758   
759   GNUNET_STRINGS_utf8_tolower((char*)&sh_msg[1], &nameptr);
760   namelen = strlen(name)+1;
761   clh = GNUNET_malloc(sizeof(struct ClientLookupHandle));
762   clh->client = client;
763   clh->name = GNUNET_malloc(namelen);
764   strcpy(clh->name, name);
765   clh->unique_id = sh_msg->id;
766   clh->type = ntohl(sh_msg->type);
767   
768   if (strlen (name) > MAX_DNS_NAME_LENGTH) {
769     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
770                "LOOKUP: %s is too long", name);
771     clh->name = NULL;
772     send_lookup_response(clh, 0, NULL);
773     return;
774   }
775   
776   if (GNUNET_YES == auto_import_pkey)
777   {
778     gns_resolver_lookup_record(zone_hash, clh->type, name,
779                                zone_key,
780                                default_lookup_timeout,
781                                &send_lookup_response, clh);
782   }
783   else
784   {
785     gns_resolver_lookup_record(zone_hash, clh->type, name,
786                                NULL,
787                                default_lookup_timeout,
788                                &send_lookup_response, clh);
789   }
790 }
791
792
793
794 /**
795  * Process GNS requests.
796  *
797  * @param cls closure)
798  * @param server the initialized server
799  * @param c configuration to use
800  */
801 static void
802 run (void *cls, struct GNUNET_SERVER_Handle *server,
803      const struct GNUNET_CONFIGURATION_Handle *c)
804 {
805   
806   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Initializing GNS\n");
807   
808   char* keyfile;
809   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pkey;
810   unsigned long long max_parallel_bg_queries = 0;
811   unsigned long long default_lookup_timeout_secs = 0;
812   int ignore_pending = GNUNET_NO;
813
814   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
815     {&handle_shorten, NULL, GNUNET_MESSAGE_TYPE_GNS_SHORTEN, 0},
816     {&handle_lookup, NULL, GNUNET_MESSAGE_TYPE_GNS_LOOKUP, 0},
817     {&handle_get_authority, NULL, GNUNET_MESSAGE_TYPE_GNS_GET_AUTH, 0}
818   };
819
820   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (c, "gns",
821                                              "ZONEKEY", &keyfile))
822   {
823     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
824                 "No private key for root zone specified!\n");
825     GNUNET_SCHEDULER_shutdown(0);
826     return;
827   }
828
829   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
830              "Using keyfile %s for root zone.\n", keyfile);
831
832   zone_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
833   GNUNET_CRYPTO_rsa_key_get_public (zone_key, &pkey);
834
835   GNUNET_CRYPTO_short_hash(&pkey,
836                      sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
837                      &zone_hash);
838   GNUNET_free(keyfile);
839   
840   /**
841    * handle to our local namestore
842    */
843   namestore_handle = GNUNET_NAMESTORE_connect(c);
844
845   if (NULL == namestore_handle)
846   {
847     //FIXME do error handling;
848     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
849                "Failed to connect to the namestore!\n");
850     GNUNET_SCHEDULER_shutdown(0);
851     return;
852   }
853   
854   
855
856   auto_import_pkey = GNUNET_NO;
857
858   if (GNUNET_YES ==
859       GNUNET_CONFIGURATION_get_value_yesno (c, "gns",
860                                             "AUTO_IMPORT_PKEY"))
861   {
862     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
863                "Automatic PKEY import is enabled.\n");
864     auto_import_pkey = GNUNET_YES;
865
866   }
867
868   dht_max_update_interval = GNUNET_GNS_DHT_MAX_UPDATE_INTERVAL;
869
870   if (GNUNET_OK ==
871       GNUNET_CONFIGURATION_get_value_number (c, "gns",
872                                              "ZONE_PUT_INTERVAL",
873                                              &dht_max_update_interval))
874   {
875     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
876                "DHT zone update interval: %d\n",
877                dht_max_update_interval);
878   }
879   
880   max_record_put_interval = 1;
881
882   if (GNUNET_OK ==
883       GNUNET_CONFIGURATION_get_value_number (c, "gns",
884                                              "RECORD_PUT_INTERVAL",
885                                              &max_record_put_interval))
886   {
887     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
888                "Record put interval: %d\n",
889                max_record_put_interval);
890   }
891   
892   if (GNUNET_OK ==
893       GNUNET_CONFIGURATION_get_value_number (c, "gns",
894                                             "MAX_PARALLEL_BACKGROUND_QUERIES",
895                                             &max_parallel_bg_queries))
896   {
897     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
898                "Number of allowed parallel background queries: %d\n",
899                max_parallel_bg_queries);
900   }
901
902   if (GNUNET_YES ==
903       GNUNET_CONFIGURATION_get_value_yesno (c, "gns",
904                                             "AUTO_IMPORT_CONFIRMATION_REQ"))
905   {
906     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
907                "Auto import requires user confirmation\n");
908     ignore_pending = GNUNET_YES;
909   }
910
911   if (GNUNET_OK ==
912       GNUNET_CONFIGURATION_get_value_number(c, "gns",
913                                             "DEFAULT_LOOKUP_TIMEOUT",
914                                             &default_lookup_timeout_secs))
915   {
916     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
917                "Default lookup timeout: %ds\n", default_lookup_timeout_secs);
918     default_lookup_timeout = GNUNET_TIME_relative_multiply(
919                                             GNUNET_TIME_UNIT_SECONDS,
920                                             default_lookup_timeout_secs);
921   }
922   
923   /**
924    * handle to the dht
925    */
926   dht_handle = GNUNET_DHT_connect(c,
927                        //max_parallel_bg_queries); //FIXME get ht_len from cfg
928                        1024);
929
930   if (NULL == dht_handle)
931   {
932     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Could not connect to DHT!\n");
933   }
934   
935   if (gns_resolver_init(namestore_handle, dht_handle, zone_hash,
936                         max_parallel_bg_queries,
937                         ignore_pending)
938       == GNUNET_SYSERR)
939   {
940     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
941                "Unable to initialize resolver!\n");
942     GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
943     return;
944   }
945
946   if (GNUNET_YES ==
947       GNUNET_CONFIGURATION_get_value_yesno (c, "gns", "HIJACK_DNS"))
948   {
949     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
950                "DNS hijacking enabled... connecting to service.\n");
951
952     if (gns_interceptor_init(zone_hash, zone_key, c) == GNUNET_SYSERR)
953     {
954       GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
955                "Failed to enable the dns interceptor!\n");
956     }
957   }
958   
959   /**
960    * Schedule periodic put
961    * for our records
962    * We have roughly an hour for all records;
963    */
964   record_put_interval = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS,
965                                                       1);
966   zone_update_taskid = GNUNET_SCHEDULER_add_now (&update_zone_dht_start, NULL);
967
968   GNUNET_SERVER_add_handlers (server, handlers);
969   
970   //FIXME
971   //GNUNET_SERVER_disconnect_notify (server,
972   //                                 &client_disconnect_notification,
973   //                                 NULL);
974
975   nc = GNUNET_SERVER_notification_context_create (server, 1);
976
977   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
978                                 NULL);
979 }
980
981
982 /**
983  * The main function for the GNS service.
984  *
985  * @param argc number of arguments from the command line
986  * @param argv command line arguments
987  * @return 0 ok, 1 on error
988  */
989 int
990 main (int argc, char *const *argv)
991 {
992   int ret;
993
994   ret =
995       (GNUNET_OK ==
996        GNUNET_SERVICE_run (argc, argv, "gns", GNUNET_SERVICE_OPTION_NONE, &run,
997                            NULL)) ? 0 : 1;
998   return ret;
999 }
1000
1001 /* end of gnunet-service-gns.c */