-ign
[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[MAX_DNS_NAME_LENGTH];
68
69   /* root zone */
70   struct GNUNET_CRYPTO_ShortHashCode root_zone;
71
72   /* private zone */
73   struct GNUNET_CRYPTO_ShortHashCode private_zone;
74   
75   /* shorten zone */
76   struct GNUNET_CRYPTO_ShortHashCode shorten_zone;
77 };
78
79
80 /**
81  * Handle to a get auhtority operation from api
82  */
83 struct ClientGetAuthHandle
84 {
85   /* the requesting client that */
86   struct GNUNET_SERVER_Client *client;
87
88   /* request id */
89   uint64_t unique_id;
90
91   /* name to lookup authority */
92   char* name;
93
94 };
95
96
97 /**
98  * Handle to a lookup operation from api
99  */
100 struct ClientLookupHandle
101 {
102   /* the requesting client that */
103   struct GNUNET_SERVER_Client *client;
104
105   /* The zone we look up in */
106   struct GNUNET_CRYPTO_ShortHashCode zone;
107
108   /* Do we only want to lookup from local cache? */
109   int only_cached;
110
111   /* request id */
112   uint64_t unique_id;
113
114   /* request type */
115   enum GNUNET_GNS_RecordType type;
116
117   /* optional zone private key used for shorten */
118   struct GNUNET_CRYPTO_RsaPrivateKey *shorten_key;
119
120   /* the name to look up */
121   char* name; //Needed?
122 };
123
124 /**
125  * Our handle to the DHT
126  */
127 static struct GNUNET_DHT_Handle *dht_handle;
128
129 /**
130  * Our zone's private key
131  */
132 struct GNUNET_CRYPTO_RsaPrivateKey *zone_key;
133
134 /**
135  * Our handle to the namestore service
136  * FIXME maybe need a second handle for iteration
137  */
138 struct GNUNET_NAMESTORE_Handle *namestore_handle;
139
140 /**
141  * Handle to iterate over our authoritative zone in namestore
142  */
143 struct GNUNET_NAMESTORE_ZoneIterator *namestore_iter;
144
145 /**
146  * The configuration the GNS service is running with
147  */
148 const struct GNUNET_CONFIGURATION_Handle *GNS_cfg;
149
150 /**
151  * Our notification context.
152  */
153 static struct GNUNET_SERVER_NotificationContext *nc;
154
155 /**
156  * Our zone hash
157  */
158 struct GNUNET_CRYPTO_ShortHashCode zone_hash;
159
160 /**
161  * Useful for zone update for DHT put
162  */
163 static int num_public_records;
164
165 /**
166  * update interval in seconds
167  */
168 static unsigned long long max_record_put_interval;
169
170 static unsigned long long dht_max_update_interval;
171
172 /* dht update interval FIXME define? */
173 static struct GNUNET_TIME_Relative record_put_interval;
174
175 /* zone update task */
176 GNUNET_SCHEDULER_TaskIdentifier zone_update_taskid = GNUNET_SCHEDULER_NO_TASK;
177
178 /* automatic pkey import for name shortening */
179 static int auto_import_pkey;
180
181 /* lookup timeout */
182 static struct GNUNET_TIME_Relative default_lookup_timeout;
183
184 /* name of the private zone */
185 static char *private_zone_id;
186
187 /* name of the public zone */
188 static char *shorten_zone_id;
189
190 /**
191  * Continue shutdown
192  */
193 static void
194 on_resolver_cleanup(void)
195 {
196   GNUNET_NAMESTORE_disconnect(namestore_handle, 1);
197   GNUNET_DHT_disconnect(dht_handle);
198 }
199
200 /**
201  * Task run during shutdown.
202  *
203  * @param cls unused
204  * @param tc unused
205  */
206 static void
207 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
208 {
209
210   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
211              "Shutting down!");
212   
213   
214   GNUNET_SERVER_notification_context_destroy (nc);
215   
216   gns_interceptor_stop();
217   gns_resolver_cleanup(&on_resolver_cleanup);
218   /* Kill zone task for it may make the scheduler hang */
219   if (zone_update_taskid != GNUNET_SCHEDULER_NO_TASK)
220     GNUNET_SCHEDULER_cancel(zone_update_taskid);
221 }
222
223
224 /**
225  * Method called periodicattluy that triggers
226  * iteration over root zone
227  *
228  * @param cls closure
229  * @param tc task context
230  */
231 static void
232 update_zone_dht_next(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
233 {
234   zone_update_taskid = GNUNET_SCHEDULER_NO_TASK;
235   GNUNET_NAMESTORE_zone_iterator_next(namestore_iter);
236 }
237
238 /**
239  * Continuation for DHT put
240  *
241  * @param cls closure
242  * @param success GNUNET_OK if the PUT was transmitted,
243  *                GNUNET_NO on timeout,
244  *                GNUNET_SYSERR on disconnect from service
245  *                after the PUT message was transmitted
246  *                (so we don't know if it was received or not)
247  */
248 static void
249 record_dht_put(void *cls, int success)
250 {
251   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "put request transmitted\n");
252 }
253
254 /* prototype */
255 static void
256 update_zone_dht_start(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
257
258 /**
259  * Function used to put all records successively into the DHT.
260  *
261  * @param cls the closure (NULL)
262  * @param key the public key of the authority (ours)
263  * @param expiration lifetime of the namestore entry
264  * @param name the name of the records
265  * @param rd_count the number of records in data
266  * @param rd the record data
267  * @param signature the signature for the record data
268  */
269 static void
270 put_gns_record(void *cls,
271                 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
272                 struct GNUNET_TIME_Absolute expiration,
273                 const char *name,
274                 unsigned int rd_count,
275                 const struct GNUNET_NAMESTORE_RecordData *rd,
276                 const struct GNUNET_CRYPTO_RsaSignature *signature)
277 {
278   
279   struct GNSNameRecordBlock *nrb;
280   struct GNUNET_CRYPTO_ShortHashCode name_hash;
281   struct GNUNET_CRYPTO_ShortHashCode zhash;
282   struct GNUNET_HashCode xor_hash;
283   struct GNUNET_HashCode name_hash_double;
284   struct GNUNET_HashCode zone_hash_double;
285   uint32_t rd_payload_length;
286   char* nrb_data = NULL;
287   size_t namelen;
288
289   /* we're done */
290   if (NULL == name)
291   {
292     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
293                "Zone iteration finished. Rescheduling put in %ds\n",
294                dht_max_update_interval);
295     zone_update_taskid = GNUNET_SCHEDULER_add_delayed (
296                                         GNUNET_TIME_relative_multiply(
297                                             GNUNET_TIME_UNIT_SECONDS,
298                                             dht_max_update_interval
299                                             ),
300                                             &update_zone_dht_start,
301                                             NULL);
302     return;
303   }
304   
305   namelen = strlen(name) + 1;
306   
307   if (signature == NULL)
308   {
309     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
310                "No signature for %s record data provided! Skipping...\n",
311                name);
312     zone_update_taskid = GNUNET_SCHEDULER_add_now (&update_zone_dht_next,
313                                                    NULL);
314     return;
315
316   }
317   
318   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
319              "Putting records for %s into the DHT\n", name);
320   
321   rd_payload_length = GNUNET_NAMESTORE_records_get_size (rd_count, rd);
322   
323   nrb = GNUNET_malloc(rd_payload_length + namelen
324                       + sizeof(struct GNSNameRecordBlock));
325   
326   nrb->signature = *signature;
327   
328   nrb->public_key = *key;
329
330   nrb->rd_count = htonl(rd_count);
331   
332   memcpy(&nrb[1], name, namelen);
333
334   nrb_data = (char*)&nrb[1];
335   nrb_data += namelen;
336
337   rd_payload_length += sizeof(struct GNSNameRecordBlock) + namelen;
338
339   if (-1 == GNUNET_NAMESTORE_records_serialize (rd_count,
340                                                 rd,
341                                                 rd_payload_length,
342                                                 nrb_data))
343   {
344     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
345                "Record serialization failed! Skipping...\n");
346     GNUNET_free(nrb);
347     zone_update_taskid = GNUNET_SCHEDULER_add_now (&update_zone_dht_next,
348                                                    NULL);
349     return;
350   }
351
352
353   /*
354    * calculate DHT key: H(name) xor H(pubkey)
355    */
356   GNUNET_CRYPTO_short_hash(key,
357                      sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
358                      &zhash);
359   GNUNET_CRYPTO_short_hash(name, strlen(name), &name_hash);
360   GNUNET_CRYPTO_short_hash_double (&name_hash, &name_hash_double);
361   GNUNET_CRYPTO_short_hash_double (&zhash, &zone_hash_double);
362   GNUNET_CRYPTO_hash_xor(&zone_hash_double, &name_hash_double, &xor_hash);
363
364   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
365              "zone identity: %s\n", GNUNET_h2s (&zone_hash_double));
366
367   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
368              "putting records for %s under key: %s with size %d\n",
369              name, GNUNET_h2s (&xor_hash), rd_payload_length);
370   
371   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
372              "DHT req to %d\n", DHT_OPERATION_TIMEOUT.rel_value);
373   /* FIXME: keep return value to possibly cancel? */
374   GNUNET_DHT_put (dht_handle, &xor_hash,
375                   DHT_GNS_REPLICATION_LEVEL,
376                   GNUNET_DHT_RO_NONE,
377                   GNUNET_BLOCK_TYPE_GNS_NAMERECORD,
378                   rd_payload_length,
379                   (char*)nrb,
380                   expiration,
381                   DHT_OPERATION_TIMEOUT,
382                   &record_dht_put,
383                   NULL); //cls for cont
384   
385   num_public_records++;
386
387   /**
388    * Reschedule periodic put
389    */
390   zone_update_taskid = GNUNET_SCHEDULER_add_delayed (record_put_interval,
391                                 &update_zone_dht_next,
392                                 NULL);
393
394   GNUNET_free(nrb);
395
396 }
397
398 /**
399  * Periodically iterate over our zone and store everything in dht
400  *
401  * @param cls NULL
402  * @param tc task context
403  */
404 static void
405 update_zone_dht_start(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
406 {
407   unsigned long long interval = 0;
408
409   zone_update_taskid = GNUNET_SCHEDULER_NO_TASK;
410
411   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Scheduling DHT zone update!\n");
412   if (0 == num_public_records)
413   {
414     /**
415      * If no records are known (startup) or none present
416      * we can safely set the interval to 1s
417      */
418     record_put_interval = GNUNET_TIME_relative_multiply(
419                                             GNUNET_TIME_UNIT_SECONDS,
420                                             1);
421     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
422                "No records in db. Adjusted record put interval to 1s\n");
423   }
424   else
425   {
426     interval = max_record_put_interval/num_public_records;
427     if (interval == 0)
428       interval = 1;
429     record_put_interval = GNUNET_TIME_relative_multiply(
430                                   GNUNET_TIME_UNIT_SECONDS,
431                                   interval);
432     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
433                "Adjusted DHT update interval to %ds!\n",
434                interval);
435   }
436
437   /* start counting again */
438   num_public_records = 0;
439   namestore_iter = GNUNET_NAMESTORE_zone_iteration_start (namestore_handle,
440                                                  NULL, //All zones
441                                                  GNUNET_NAMESTORE_RF_AUTHORITY,
442                                                  GNUNET_NAMESTORE_RF_PRIVATE,
443                                                  &put_gns_record,
444                                                  NULL);
445 }
446
447 /* END DHT ZONE PROPAGATION */
448
449 /**
450  * Send shorten response back to client
451  * 
452  * @param cls the closure containing a client shorten handle
453  * @param name the shortened name result or NULL if cannot be shortened
454  */
455 static void
456 send_shorten_response(void* cls, const char* name)
457 {
458   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message with %s\n",
459               "SHORTEN_RESULT", name);
460   struct GNUNET_GNS_ClientShortenResultMessage *rmsg;
461   struct ClientShortenHandle *csh = (struct ClientShortenHandle *)cls;
462   
463   if (name == NULL)
464   {
465     name = "";
466   }
467
468   rmsg = GNUNET_malloc(sizeof(struct GNUNET_GNS_ClientShortenResultMessage)
469                        + strlen(name) + 1);
470   
471   rmsg->id = csh->unique_id;
472   rmsg->header.type = htons(GNUNET_MESSAGE_TYPE_GNS_SHORTEN_RESULT);
473   rmsg->header.size = 
474     htons(sizeof(struct GNUNET_GNS_ClientShortenResultMessage) +
475           strlen(name) + 1);
476
477   strcpy((char*)&rmsg[1], name);
478
479   GNUNET_SERVER_notification_context_unicast (nc, csh->client,
480                               (const struct GNUNET_MessageHeader *) rmsg,
481                               GNUNET_NO);
482   GNUNET_SERVER_receive_done (csh->client, GNUNET_OK);
483   
484   GNUNET_free(rmsg);
485   GNUNET_free_non_null(csh->shorten_key);
486   GNUNET_free(csh);
487
488 }
489
490
491 static void
492 process_shorten_zone_shorten (void *cls,
493                       const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
494                       struct GNUNET_TIME_Absolute expiration,
495                       const char *name,
496                       unsigned int rd_count,
497                       const struct GNUNET_NAMESTORE_RecordData *rd,
498                       const struct GNUNET_CRYPTO_RsaSignature *signature)
499 {
500   struct ClientShortenHandle *csh = cls;
501   struct GNUNET_TIME_Relative remaining_time;
502   struct GNUNET_TIME_Absolute et;
503
504   remaining_time = GNUNET_TIME_absolute_get_remaining (expiration);
505
506   if ((rd_count == 1) &&
507       (remaining_time.rel_value != 0))
508   {
509     GNUNET_break (0 == (rd->flags & GNUNET_NAMESTORE_RF_RELATIVE_EXPIRATION));
510     et.abs_value = rd->expiration_time;
511     remaining_time = GNUNET_TIME_absolute_get_remaining (et);
512     if ((rd->record_type == GNUNET_GNS_RECORD_PKEY) &&
513         (remaining_time.rel_value != 0))
514     {
515       csh->shorten_zone = *((struct GNUNET_CRYPTO_ShortHashCode*)rd->data);
516     }
517   }
518   gns_resolver_shorten_name (&csh->root_zone,
519                              &csh->private_zone,
520                              &csh->shorten_zone,
521                              csh->name,
522                              private_zone_id,
523                              shorten_zone_id,
524                              &send_shorten_response, csh);
525
526 }
527
528
529 static void
530 process_private_zone_shorten (void *cls,
531                       const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
532                       struct GNUNET_TIME_Absolute expiration,
533                       const char *name,
534                       unsigned int rd_count,
535                       const struct GNUNET_NAMESTORE_RecordData *rd,
536                       const struct GNUNET_CRYPTO_RsaSignature *signature)
537 {
538   struct GNUNET_TIME_Relative remaining_time;
539   struct ClientShortenHandle *csh = cls;
540   struct GNUNET_TIME_Absolute et;
541
542   remaining_time = GNUNET_TIME_absolute_get_remaining (expiration);
543
544   if ((rd_count == 1) &&
545       (remaining_time.rel_value != 0))
546   {
547     GNUNET_break (0 == (rd->flags & GNUNET_NAMESTORE_RF_RELATIVE_EXPIRATION));
548     et.abs_value = rd->expiration_time;
549     remaining_time = GNUNET_TIME_absolute_get_remaining (et);
550     if ((rd->record_type == GNUNET_GNS_RECORD_PKEY) &&
551         (remaining_time.rel_value != 0))
552     {
553
554
555       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
556                   "Looking for shorten zone in private zone\n");
557       csh->private_zone = *((struct GNUNET_CRYPTO_ShortHashCode*)rd->data);
558       GNUNET_NAMESTORE_lookup_record (namestore_handle,
559                                       &csh->private_zone,
560                                       shorten_zone_id,
561                                       GNUNET_GNS_RECORD_ANY,
562                                       &process_shorten_zone_shorten,
563                                       cls);
564     }
565     return;
566   }
567
568   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
569               "No private zone found!\n");
570   gns_resolver_shorten_name (&csh->root_zone,
571                              &csh->private_zone,
572                              &csh->shorten_zone,
573                              csh->name,
574                              private_zone_id,
575                              shorten_zone_id,
576                              &send_shorten_response, csh);
577
578 }
579
580 /**
581  * Lookup the zone infos and shorten name
582  *
583  * @param csh the shorten handle
584  *
585  */
586 static void
587 start_shorten_name (struct ClientShortenHandle *csh)
588 {
589   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
590               "Looking for private zone in root zone\n");
591
592   GNUNET_NAMESTORE_lookup_record (namestore_handle,
593                                   &csh->root_zone,
594                                   private_zone_id,
595                                   GNUNET_GNS_RECORD_ANY,
596                                   &process_private_zone_shorten,
597                                   csh);
598 }
599
600
601 /**
602  * Handle a shorten message from the api
603  *
604  * @param cls the closure
605  * @param client the client
606  * @param message the message
607  */
608 static void handle_shorten (void *cls,
609                             struct GNUNET_SERVER_Client * client,
610                             const struct GNUNET_MessageHeader * message)
611 {
612   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "SHORTEN");
613
614   size_t msg_size = 0;
615   struct ClientShortenHandle *csh;
616   char name[MAX_DNS_NAME_LENGTH];
617   char* nameptr = name;
618
619   if (ntohs (message->size) < sizeof (struct GNUNET_GNS_ClientShortenMessage))
620   {
621     GNUNET_break_op (0);
622     GNUNET_SERVER_receive_done (client, GNUNET_OK);
623     return;
624   }
625
626
627   struct GNUNET_GNS_ClientShortenMessage *sh_msg =
628     (struct GNUNET_GNS_ClientShortenMessage *) message;
629   
630   msg_size = ntohs(message->size);
631
632   if (msg_size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
633   {
634     GNUNET_break_op (0);
635     GNUNET_SERVER_receive_done (client, GNUNET_OK);
636     return;
637   }
638
639   csh = GNUNET_malloc(sizeof(struct ClientShortenHandle));
640   csh->client = client;
641   csh->unique_id = sh_msg->id;
642   csh->shorten_key = NULL;
643   
644   GNUNET_STRINGS_utf8_tolower((char*)&sh_msg[1], &nameptr);
645
646   if (strlen (name) < strlen(GNUNET_GNS_TLD)) {
647     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
648                "SHORTEN: %s is too short", name);
649     send_shorten_response(csh, name);
650     return;
651   }
652
653   if (strlen (name) > MAX_DNS_NAME_LENGTH) {
654     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
655                "SHORTEN: %s is too long", name);
656     send_shorten_response(csh, name);
657     return;
658   }
659   
660   if (!is_gnunet_tld(name) && !is_zkey_tld(name))
661   {
662     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
663                 "%s is not our domain. Returning\n", name);
664     send_shorten_response(csh, name);
665     return;
666   }
667
668   strcpy (csh->name, name);
669   
670   GNUNET_SERVER_notification_context_add (nc, client);
671   
672   if (1 == ntohl(sh_msg->use_default_zone))
673     csh->root_zone = zone_hash; //Default zone
674   else
675     csh->root_zone = sh_msg->zone;
676
677   start_shorten_name (csh);
678   
679 }
680
681
682 /**
683  * Send get authority response back to client
684  * 
685  * @param cls the closure containing a client get auth handle
686  * @param name the shortened name result or NULL if cannot be shortened
687  */
688 static void
689 send_get_auth_response(void *cls, const char* name)
690 {
691   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message with %s\n",
692               "GET_AUTH_RESULT", name);
693   struct GNUNET_GNS_ClientGetAuthResultMessage *rmsg;
694   struct ClientGetAuthHandle *cah = (struct ClientGetAuthHandle *)cls;
695   
696   if (name == NULL)
697   {
698     name = "";
699   }
700
701   rmsg = GNUNET_malloc(sizeof(struct GNUNET_GNS_ClientGetAuthResultMessage)
702                        + strlen(name) + 1);
703   
704   rmsg->id = cah->unique_id;
705   rmsg->header.type = htons(GNUNET_MESSAGE_TYPE_GNS_GET_AUTH_RESULT);
706   rmsg->header.size = 
707     htons(sizeof(struct GNUNET_GNS_ClientGetAuthResultMessage) +
708           strlen(name) + 1);
709
710   strcpy((char*)&rmsg[1], name);
711
712   GNUNET_SERVER_notification_context_unicast (nc, cah->client,
713                               (const struct GNUNET_MessageHeader *) rmsg,
714                               GNUNET_NO);
715   GNUNET_SERVER_receive_done (cah->client, GNUNET_OK);
716   
717   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Cleaning up handles...\n");
718
719   GNUNET_free(rmsg);
720   GNUNET_free_non_null(cah->name);
721   GNUNET_free(cah);
722
723   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "done.\n");
724
725 }
726
727
728 /**
729  * Handle a get authority message from the api
730  *
731  * @param cls the closure
732  * @param client the client
733  * @param message the message
734  */
735 static void handle_get_authority(void *cls,
736                            struct GNUNET_SERVER_Client * client,
737                            const struct GNUNET_MessageHeader * message)
738 {
739   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "GET_AUTH");
740
741   size_t msg_size = 0;
742   struct ClientGetAuthHandle *cah;
743   char name[MAX_DNS_NAME_LENGTH];
744   char* nameptr = name;
745
746
747   if (ntohs (message->size) < sizeof (struct GNUNET_GNS_ClientGetAuthMessage))
748   {
749     GNUNET_break_op (0);
750     GNUNET_SERVER_receive_done (client, GNUNET_OK);
751     return;
752   }
753
754   GNUNET_SERVER_notification_context_add (nc, client);
755
756   struct GNUNET_GNS_ClientGetAuthMessage *sh_msg =
757     (struct GNUNET_GNS_ClientGetAuthMessage *) message;
758   
759   msg_size = ntohs(message->size);
760
761   if (msg_size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
762   {
763     GNUNET_break_op (0);
764     GNUNET_SERVER_receive_done (client, GNUNET_OK);
765     return;
766   }
767   
768   GNUNET_STRINGS_utf8_tolower((char*)&sh_msg[1], &nameptr);
769
770
771   cah = GNUNET_malloc(sizeof(struct ClientGetAuthHandle));
772   cah->client = client;
773   cah->unique_id = sh_msg->id;
774
775   if (strlen(name) < strlen(GNUNET_GNS_TLD))
776   {
777     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
778                 "GET_AUTH: %s is too short. Returning\n", name);
779     cah->name = NULL;
780     send_get_auth_response(cah, name);
781     return;
782   }
783   
784   if (strlen (name) > MAX_DNS_NAME_LENGTH) {
785     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
786                "GET_AUTH: %s is too long", name);
787     cah->name = NULL;
788     send_get_auth_response(cah, name);
789     return;
790   }
791   
792   if (strcmp(name+strlen(name)-strlen(GNUNET_GNS_TLD),
793              GNUNET_GNS_TLD) != 0)
794   {
795     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
796                 "GET_AUTH: %s is not our domain. Returning\n", name);
797     cah->name = NULL;
798     send_get_auth_response(cah, name);
799     return;
800   }
801
802   if (strcmp(name, GNUNET_GNS_TLD) == 0)
803   {
804     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
805                 "GET_AUTH: %s is us. Returning\n", name);
806     cah->name = NULL;
807     send_get_auth_response(cah, name);
808     return;
809   }
810   
811   cah->name = GNUNET_malloc(strlen(name)
812                             - strlen(GNUNET_GNS_TLD) + 1);
813   memset(cah->name, 0,
814          strlen(name)-strlen(GNUNET_GNS_TLD) + 1);
815   memcpy(cah->name, name,
816          strlen(name)-strlen(GNUNET_GNS_TLD));
817
818   /* Start delegation resolution in our namestore */
819   gns_resolver_get_authority(zone_hash, zone_hash, name, &send_get_auth_response, cah);
820 }
821
822
823
824 /**
825  * Reply to client with the result from our lookup.
826  *
827  * @param cls the closure (our client lookup handle)
828  * @param rd_count the number of records
829  * @param rd the record data
830  */
831 static void
832 send_lookup_response(void* cls,
833                      uint32_t rd_count,
834                      const struct GNUNET_NAMESTORE_RecordData *rd)
835 {
836   struct ClientLookupHandle* clh = (struct ClientLookupHandle*)cls;
837   struct GNUNET_GNS_ClientLookupResultMessage *rmsg;
838   size_t len;
839   
840   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message with %d results\n",
841               "LOOKUP_RESULT", rd_count);
842   
843   len = GNUNET_NAMESTORE_records_get_size (rd_count, rd);
844   rmsg = GNUNET_malloc(len+sizeof(struct GNUNET_GNS_ClientLookupResultMessage));
845   
846   rmsg->id = clh->unique_id;
847   rmsg->rd_count = htonl(rd_count);
848   rmsg->header.type = htons(GNUNET_MESSAGE_TYPE_GNS_LOOKUP_RESULT);
849   rmsg->header.size = 
850     htons(len+sizeof(struct GNUNET_GNS_ClientLookupResultMessage));
851
852   GNUNET_NAMESTORE_records_serialize (rd_count, rd, len, (char*)&rmsg[1]);
853   
854   GNUNET_SERVER_notification_context_unicast (nc, clh->client,
855                                 (const struct GNUNET_MessageHeader *) rmsg,
856                                 GNUNET_NO);
857   GNUNET_SERVER_receive_done (clh->client, GNUNET_OK);
858   
859   GNUNET_free(rmsg);
860   GNUNET_free(clh->name);
861   
862   if (NULL != clh->shorten_key)
863     GNUNET_free(clh->shorten_key);
864
865   GNUNET_free(clh);
866
867 }
868
869
870 /**
871  * Handle lookup requests from client
872  *
873  * @param cls the closure
874  * @param client the client
875  * @param message the message
876  */
877 static void
878 handle_lookup(void *cls,
879               struct GNUNET_SERVER_Client * client,
880               const struct GNUNET_MessageHeader * message)
881 {
882   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "LOOKUP");
883
884   size_t msg_size = 0;
885   size_t namelen;
886   char name[MAX_DNS_NAME_LENGTH];
887   struct ClientLookupHandle *clh;
888   char* nameptr = name;
889   int only_cached;
890   struct GNUNET_CRYPTO_RsaPrivateKey *key;
891   struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *pkey;
892   char* tmp_pkey;
893
894   if (ntohs (message->size) < sizeof (struct GNUNET_GNS_ClientLookupMessage))
895   {
896     GNUNET_break_op (0);
897     GNUNET_SERVER_receive_done (client, GNUNET_OK);
898     return;
899   }
900
901   GNUNET_SERVER_notification_context_add (nc, client);
902
903   struct GNUNET_GNS_ClientLookupMessage *sh_msg =
904     (struct GNUNET_GNS_ClientLookupMessage *) message;
905   
906   msg_size = ntohs(message->size);
907
908   if (msg_size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
909   {
910     GNUNET_break_op (0);
911     GNUNET_SERVER_receive_done (client, GNUNET_OK);
912     return;
913   }
914
915   if (1 == ntohl(sh_msg->have_key))
916   {
917     pkey = (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *)&sh_msg[1];
918     tmp_pkey = (char*)&sh_msg[1];
919     key = GNUNET_CRYPTO_rsa_decode_key (tmp_pkey, ntohs(pkey->len));
920     GNUNET_STRINGS_utf8_tolower(&tmp_pkey[ntohs(pkey->len)], &nameptr);
921   }
922   else
923   {
924     key = NULL;
925     GNUNET_STRINGS_utf8_tolower((char*)&sh_msg[1], &nameptr);
926   }
927   
928   namelen = strlen(name)+1;
929   clh = GNUNET_malloc(sizeof(struct ClientLookupHandle));
930   clh->client = client;
931   clh->name = GNUNET_malloc(namelen);
932   strcpy(clh->name, name);
933   clh->unique_id = sh_msg->id;
934   clh->type = ntohl(sh_msg->type);
935   clh->shorten_key = key;
936
937   only_cached = ntohl(sh_msg->only_cached);
938   
939   if (strlen (name) > MAX_DNS_NAME_LENGTH) {
940     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
941                "LOOKUP: %s is too long", name);
942     clh->name = NULL;
943     send_lookup_response(clh, 0, NULL);
944     return;
945   }
946
947   if (1 == ntohl(sh_msg->use_default_zone))
948     clh->zone = zone_hash; //Default zone
949   else
950     clh->zone = sh_msg->zone;
951   
952   if (GNUNET_YES == auto_import_pkey)
953   {
954     gns_resolver_lookup_record (clh->zone, clh->zone, clh->type, clh->name,
955                                 clh->shorten_key,
956                                 default_lookup_timeout,
957                                 clh->only_cached,
958                                 &send_lookup_response, clh);  
959   }
960   else
961   {
962     gns_resolver_lookup_record (clh->zone, clh->zone, clh->type, name,
963                                 NULL,
964                                 default_lookup_timeout,
965                                 only_cached,
966                                 &send_lookup_response, clh);
967   }
968 }
969
970
971
972 /**
973  * Process GNS requests.
974  *
975  * @param cls closure)
976  * @param server the initialized server
977  * @param c configuration to use
978  */
979 static void
980 run (void *cls, struct GNUNET_SERVER_Handle *server,
981      const struct GNUNET_CONFIGURATION_Handle *c)
982 {
983   
984   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Initializing GNS\n");
985   
986   char* keyfile;
987   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pkey;
988   unsigned long long max_parallel_bg_queries = 0;
989   unsigned long long default_lookup_timeout_secs = 0;
990   int ignore_pending = GNUNET_NO;
991
992   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
993     {&handle_shorten, NULL, GNUNET_MESSAGE_TYPE_GNS_SHORTEN, 0},
994     {&handle_lookup, NULL, GNUNET_MESSAGE_TYPE_GNS_LOOKUP, 0},
995     {&handle_get_authority, NULL, GNUNET_MESSAGE_TYPE_GNS_GET_AUTH, 0}
996   };
997
998   GNS_cfg = c;
999
1000   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (c, "gns",
1001                                              "ZONEKEY", &keyfile))
1002   {
1003     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1004                 "No private key for root zone specified!\n");
1005     GNUNET_SCHEDULER_shutdown ();
1006     return;
1007   }
1008
1009   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1010              "Using keyfile %s for root zone.\n", keyfile);
1011
1012   zone_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
1013   GNUNET_CRYPTO_rsa_key_get_public (zone_key, &pkey);
1014
1015   GNUNET_CRYPTO_short_hash(&pkey,
1016                      sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1017                      &zone_hash);
1018   GNUNET_free(keyfile);
1019   
1020   /**
1021    * handle to our local namestore
1022    */
1023   namestore_handle = GNUNET_NAMESTORE_connect(c);
1024
1025   if (NULL == namestore_handle)
1026   {
1027     //FIXME do error handling;
1028     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1029                "Failed to connect to the namestore!\n");
1030     GNUNET_SCHEDULER_shutdown ();
1031     return;
1032   }
1033   
1034   
1035
1036   auto_import_pkey = GNUNET_NO;
1037
1038   if (GNUNET_YES ==
1039       GNUNET_CONFIGURATION_get_value_yesno (c, "gns",
1040                                             "AUTO_IMPORT_PKEY"))
1041   {
1042     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1043                "Automatic PKEY import is enabled.\n");
1044     auto_import_pkey = GNUNET_YES;
1045
1046   }
1047
1048   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (c, "gns",
1049                                                           "PRIVATE_ZONE",
1050                                                           &private_zone_id))
1051   {
1052     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1053                "Private zone id: %s\n", private_zone_id);
1054   }
1055
1056   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (c, "gns",
1057                                                           "SHORTEN_ZONE",
1058                                                           &shorten_zone_id))
1059   {
1060     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1061                "Shorten zone id: %s\n", shorten_zone_id);
1062   }
1063
1064   dht_max_update_interval = GNUNET_GNS_DHT_MAX_UPDATE_INTERVAL;
1065
1066   if (GNUNET_OK ==
1067       GNUNET_CONFIGURATION_get_value_number (c, "gns",
1068                                              "ZONE_PUT_INTERVAL",
1069                                              &dht_max_update_interval))
1070   {
1071     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1072                "DHT zone update interval: %d\n",
1073                dht_max_update_interval);
1074   }
1075   
1076   max_record_put_interval = 1;
1077
1078   if (GNUNET_OK ==
1079       GNUNET_CONFIGURATION_get_value_number (c, "gns",
1080                                              "RECORD_PUT_INTERVAL",
1081                                              &max_record_put_interval))
1082   {
1083     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1084                "Record put interval: %d\n",
1085                max_record_put_interval);
1086   }
1087   
1088   if (GNUNET_OK ==
1089       GNUNET_CONFIGURATION_get_value_number (c, "gns",
1090                                             "MAX_PARALLEL_BACKGROUND_QUERIES",
1091                                             &max_parallel_bg_queries))
1092   {
1093     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1094                "Number of allowed parallel background queries: %d\n",
1095                max_parallel_bg_queries);
1096   }
1097
1098   if (GNUNET_YES ==
1099       GNUNET_CONFIGURATION_get_value_yesno (c, "gns",
1100                                             "AUTO_IMPORT_CONFIRMATION_REQ"))
1101   {
1102     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1103                "Auto import requires user confirmation\n");
1104     ignore_pending = GNUNET_YES;
1105   }
1106
1107   if (GNUNET_OK ==
1108       GNUNET_CONFIGURATION_get_value_number(c, "gns",
1109                                             "DEFAULT_LOOKUP_TIMEOUT",
1110                                             &default_lookup_timeout_secs))
1111   {
1112     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1113                "Default lookup timeout: %ds\n", default_lookup_timeout_secs);
1114     default_lookup_timeout = GNUNET_TIME_relative_multiply(
1115                                             GNUNET_TIME_UNIT_SECONDS,
1116                                             default_lookup_timeout_secs);
1117   }
1118   
1119   /**
1120    * handle to the dht
1121    */
1122   dht_handle = GNUNET_DHT_connect(c,
1123                        //max_parallel_bg_queries); //FIXME get ht_len from cfg
1124                        1024);
1125
1126   if (NULL == dht_handle)
1127   {
1128     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Could not connect to DHT!\n");
1129   }
1130   
1131   if (gns_resolver_init(namestore_handle, dht_handle, zone_hash, c,
1132                         max_parallel_bg_queries,
1133                         ignore_pending)
1134       == GNUNET_SYSERR)
1135   {
1136     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1137                "Unable to initialize resolver!\n");
1138     GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
1139     return;
1140   }
1141
1142   if (GNUNET_YES ==
1143       GNUNET_CONFIGURATION_get_value_yesno (c, "gns", "HIJACK_DNS"))
1144   {
1145     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1146                "DNS hijacking enabled... connecting to service.\n");
1147
1148     if (gns_interceptor_init(zone_hash, zone_key, c) == GNUNET_SYSERR)
1149     {
1150       GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1151                "Failed to enable the dns interceptor!\n");
1152     }
1153   }
1154   
1155   /**
1156    * Schedule periodic put
1157    * for our records
1158    * We have roughly an hour for all records;
1159    */
1160   record_put_interval = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS,
1161                                                       1);
1162   zone_update_taskid = GNUNET_SCHEDULER_add_now (&update_zone_dht_start, NULL);
1163
1164   GNUNET_SERVER_add_handlers (server, handlers);
1165   
1166   //FIXME
1167   //GNUNET_SERVER_disconnect_notify (server,
1168   //                                 &client_disconnect_notification,
1169   //                                 NULL);
1170
1171   nc = GNUNET_SERVER_notification_context_create (server, 1);
1172
1173   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
1174                                 NULL);
1175 }
1176
1177
1178 /**
1179  * The main function for the GNS service.
1180  *
1181  * @param argc number of arguments from the command line
1182  * @param argv command line arguments
1183  * @return 0 ok, 1 on error
1184  */
1185 int
1186 main (int argc, char *const *argv)
1187 {
1188   int ret;
1189
1190   ret =
1191       (GNUNET_OK ==
1192        GNUNET_SERVICE_run (argc, argv, "gns", GNUNET_SERVICE_OPTION_NONE, &run,
1193                            NULL)) ? 0 : 1;
1194   return ret;
1195 }
1196
1197 /* end of gnunet-service-gns.c */