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