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