-fix cname, more ns/vpn delegation
[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   /* Kill zone task for it may make the scheduler hang */
213   if (zone_update_taskid != GNUNET_SCHEDULER_NO_TASK)
214     GNUNET_SCHEDULER_cancel(zone_update_taskid);
215   
216   GNUNET_SERVER_notification_context_destroy (nc);
217   
218   gns_interceptor_stop();
219   gns_resolver_cleanup(&on_resolver_cleanup);
220
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
503   remaining_time = GNUNET_TIME_absolute_get_remaining (expiration);
504
505   if ((rd_count == 1) &&
506       (remaining_time.rel_value != 0))
507   {
508     remaining_time = GNUNET_TIME_absolute_get_remaining (rd->expiration);
509     if ((rd->record_type == GNUNET_GNS_RECORD_PKEY) &&
510         (remaining_time.rel_value != 0))
511     {
512       csh->shorten_zone = *((struct GNUNET_CRYPTO_ShortHashCode*)rd->data);
513     }
514   }
515   gns_resolver_shorten_name (&csh->root_zone,
516                              &csh->private_zone,
517                              &csh->shorten_zone,
518                              csh->name,
519                              private_zone_id,
520                              shorten_zone_id,
521                              &send_shorten_response, csh);
522
523 }
524
525 static void
526 process_private_zone_shorten (void *cls,
527                       const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
528                       struct GNUNET_TIME_Absolute expiration,
529                       const char *name,
530                       unsigned int rd_count,
531                       const struct GNUNET_NAMESTORE_RecordData *rd,
532                       const struct GNUNET_CRYPTO_RsaSignature *signature)
533 {
534   struct GNUNET_TIME_Relative remaining_time;
535   struct ClientShortenHandle *csh = cls;
536
537   remaining_time = GNUNET_TIME_absolute_get_remaining (expiration);
538
539   if ((rd_count == 1) &&
540       (remaining_time.rel_value != 0))
541   {
542     remaining_time = GNUNET_TIME_absolute_get_remaining (rd->expiration);
543     if ((rd->record_type == GNUNET_GNS_RECORD_PKEY) &&
544         (remaining_time.rel_value != 0))
545     {
546
547
548       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
549                   "Looking for shorten zone in private zone\n");
550       csh->private_zone = *((struct GNUNET_CRYPTO_ShortHashCode*)rd->data);
551       GNUNET_NAMESTORE_lookup_record (namestore_handle,
552                                       &csh->private_zone,
553                                       shorten_zone_id,
554                                       GNUNET_GNS_RECORD_ANY,
555                                       &process_shorten_zone_shorten,
556                                       cls);
557     }
558     return;
559   }
560
561   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
562               "No private zone found!\n");
563   gns_resolver_shorten_name (&csh->root_zone,
564                              &csh->private_zone,
565                              &csh->shorten_zone,
566                              csh->name,
567                              private_zone_id,
568                              shorten_zone_id,
569                              &send_shorten_response, csh);
570
571 }
572
573 /**
574  * Lookup the zone infos and shorten name
575  *
576  * @param csh the shorten handle
577  *
578  */
579 static void
580 start_shorten_name (struct ClientShortenHandle *csh)
581 {
582   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
583               "Looking for private zone in root zone\n");
584
585   GNUNET_NAMESTORE_lookup_record (namestore_handle,
586                                   &csh->root_zone,
587                                   private_zone_id,
588                                   GNUNET_GNS_RECORD_ANY,
589                                   &process_private_zone_shorten,
590                                   csh);
591 }
592
593
594 /**
595  * Handle a shorten message from the api
596  *
597  * @param cls the closure
598  * @param client the client
599  * @param message the message
600  */
601 static void handle_shorten (void *cls,
602                             struct GNUNET_SERVER_Client * client,
603                             const struct GNUNET_MessageHeader * message)
604 {
605   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "SHORTEN");
606
607   size_t msg_size = 0;
608   struct ClientShortenHandle *csh;
609   char name[MAX_DNS_NAME_LENGTH];
610   char* nameptr = name;
611
612   if (ntohs (message->size) < sizeof (struct GNUNET_GNS_ClientShortenMessage))
613   {
614     GNUNET_break_op (0);
615     GNUNET_SERVER_receive_done (client, GNUNET_OK);
616     return;
617   }
618
619
620   struct GNUNET_GNS_ClientShortenMessage *sh_msg =
621     (struct GNUNET_GNS_ClientShortenMessage *) message;
622   
623   msg_size = ntohs(message->size);
624
625   if (msg_size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
626   {
627     GNUNET_break_op (0);
628     GNUNET_SERVER_receive_done (client, GNUNET_OK);
629     return;
630   }
631
632   csh = GNUNET_malloc(sizeof(struct ClientShortenHandle));
633   csh->client = client;
634   csh->unique_id = sh_msg->id;
635   csh->shorten_key = NULL;
636   
637   GNUNET_STRINGS_utf8_tolower((char*)&sh_msg[1], &nameptr);
638
639   if (strlen (name) < strlen(GNUNET_GNS_TLD)) {
640     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
641                "SHORTEN: %s is too short", name);
642     send_shorten_response(csh, name);
643     return;
644   }
645
646   if (strlen (name) > MAX_DNS_NAME_LENGTH) {
647     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
648                "SHORTEN: %s is too long", name);
649     send_shorten_response(csh, name);
650     return;
651   }
652   
653   if (!is_gnunet_tld(name) && !is_zkey_tld(name))
654   {
655     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
656                 "%s is not our domain. Returning\n", name);
657     send_shorten_response(csh, name);
658     return;
659   }
660
661   strcpy (csh->name, name);
662   
663   GNUNET_SERVER_notification_context_add (nc, client);
664   
665   if (1 == ntohl(sh_msg->use_default_zone))
666     csh->root_zone = zone_hash; //Default zone
667   else
668     csh->root_zone = sh_msg->zone;
669
670   start_shorten_name (csh);
671   
672 }
673
674
675 /**
676  * Send get authority response back to client
677  * 
678  * @param cls the closure containing a client get auth handle
679  * @param name the shortened name result or NULL if cannot be shortened
680  */
681 static void
682 send_get_auth_response(void *cls, const char* name)
683 {
684   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message with %s\n",
685               "GET_AUTH_RESULT", name);
686   struct GNUNET_GNS_ClientGetAuthResultMessage *rmsg;
687   struct ClientGetAuthHandle *cah = (struct ClientGetAuthHandle *)cls;
688   
689   if (name == NULL)
690   {
691     name = "";
692   }
693
694   rmsg = GNUNET_malloc(sizeof(struct GNUNET_GNS_ClientGetAuthResultMessage)
695                        + strlen(name) + 1);
696   
697   rmsg->id = cah->unique_id;
698   rmsg->header.type = htons(GNUNET_MESSAGE_TYPE_GNS_GET_AUTH_RESULT);
699   rmsg->header.size = 
700     htons(sizeof(struct GNUNET_GNS_ClientGetAuthResultMessage) +
701           strlen(name) + 1);
702
703   strcpy((char*)&rmsg[1], name);
704
705   GNUNET_SERVER_notification_context_unicast (nc, cah->client,
706                               (const struct GNUNET_MessageHeader *) rmsg,
707                               GNUNET_NO);
708   GNUNET_SERVER_receive_done (cah->client, GNUNET_OK);
709   
710   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Cleaning up handles...\n");
711
712   GNUNET_free(rmsg);
713   GNUNET_free_non_null(cah->name);
714   GNUNET_free(cah);
715
716   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "done.\n");
717
718 }
719
720
721 /**
722  * Handle a get authority message from the api
723  *
724  * @param cls the closure
725  * @param client the client
726  * @param message the message
727  */
728 static void handle_get_authority(void *cls,
729                            struct GNUNET_SERVER_Client * client,
730                            const struct GNUNET_MessageHeader * message)
731 {
732   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "GET_AUTH");
733
734   size_t msg_size = 0;
735   struct ClientGetAuthHandle *cah;
736   char name[MAX_DNS_NAME_LENGTH];
737   char* nameptr = name;
738
739
740   if (ntohs (message->size) < sizeof (struct GNUNET_GNS_ClientGetAuthMessage))
741   {
742     GNUNET_break_op (0);
743     GNUNET_SERVER_receive_done (client, GNUNET_OK);
744     return;
745   }
746
747   GNUNET_SERVER_notification_context_add (nc, client);
748
749   struct GNUNET_GNS_ClientGetAuthMessage *sh_msg =
750     (struct GNUNET_GNS_ClientGetAuthMessage *) message;
751   
752   msg_size = ntohs(message->size);
753
754   if (msg_size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
755   {
756     GNUNET_break_op (0);
757     GNUNET_SERVER_receive_done (client, GNUNET_OK);
758     return;
759   }
760   
761   GNUNET_STRINGS_utf8_tolower((char*)&sh_msg[1], &nameptr);
762
763
764   cah = GNUNET_malloc(sizeof(struct ClientGetAuthHandle));
765   cah->client = client;
766   cah->unique_id = sh_msg->id;
767
768   if (strlen(name) < strlen(GNUNET_GNS_TLD))
769   {
770     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
771                 "GET_AUTH: %s is too short. Returning\n", name);
772     cah->name = NULL;
773     send_get_auth_response(cah, name);
774     return;
775   }
776   
777   if (strlen (name) > MAX_DNS_NAME_LENGTH) {
778     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
779                "GET_AUTH: %s is too long", name);
780     cah->name = NULL;
781     send_get_auth_response(cah, name);
782     return;
783   }
784   
785   if (strcmp(name+strlen(name)-strlen(GNUNET_GNS_TLD),
786              GNUNET_GNS_TLD) != 0)
787   {
788     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
789                 "GET_AUTH: %s is not our domain. Returning\n", name);
790     cah->name = NULL;
791     send_get_auth_response(cah, name);
792     return;
793   }
794
795   if (strcmp(name, GNUNET_GNS_TLD) == 0)
796   {
797     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
798                 "GET_AUTH: %s is us. Returning\n", name);
799     cah->name = NULL;
800     send_get_auth_response(cah, name);
801     return;
802   }
803   
804   cah->name = GNUNET_malloc(strlen(name)
805                             - strlen(GNUNET_GNS_TLD) + 1);
806   memset(cah->name, 0,
807          strlen(name)-strlen(GNUNET_GNS_TLD) + 1);
808   memcpy(cah->name, name,
809          strlen(name)-strlen(GNUNET_GNS_TLD));
810
811   /* Start delegation resolution in our namestore */
812   gns_resolver_get_authority(zone_hash, zone_hash, name, &send_get_auth_response, cah);
813 }
814
815
816
817 /**
818  * Reply to client with the result from our lookup.
819  *
820  * @param cls the closure (our client lookup handle)
821  * @param rd_count the number of records
822  * @param rd the record data
823  */
824 static void
825 send_lookup_response(void* cls,
826                      uint32_t rd_count,
827                      const struct GNUNET_NAMESTORE_RecordData *rd)
828 {
829   struct ClientLookupHandle* clh = (struct ClientLookupHandle*)cls;
830   struct GNUNET_GNS_ClientLookupResultMessage *rmsg;
831   size_t len;
832   
833   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message with %d results\n",
834               "LOOKUP_RESULT", rd_count);
835   
836   len = GNUNET_NAMESTORE_records_get_size (rd_count, rd);
837   rmsg = GNUNET_malloc(len+sizeof(struct GNUNET_GNS_ClientLookupResultMessage));
838   
839   rmsg->id = clh->unique_id;
840   rmsg->rd_count = htonl(rd_count);
841   rmsg->header.type = htons(GNUNET_MESSAGE_TYPE_GNS_LOOKUP_RESULT);
842   rmsg->header.size = 
843     htons(len+sizeof(struct GNUNET_GNS_ClientLookupResultMessage));
844
845   GNUNET_NAMESTORE_records_serialize (rd_count, rd, len, (char*)&rmsg[1]);
846   
847   GNUNET_SERVER_notification_context_unicast (nc, clh->client,
848                                 (const struct GNUNET_MessageHeader *) rmsg,
849                                 GNUNET_NO);
850   GNUNET_SERVER_receive_done (clh->client, GNUNET_OK);
851   
852   GNUNET_free(rmsg);
853   GNUNET_free(clh->name);
854   
855   if (NULL != clh->shorten_key)
856     GNUNET_free(clh->shorten_key);
857
858   GNUNET_free(clh);
859
860 }
861
862
863 /**
864  * Handle lookup requests from client
865  *
866  * @param cls the closure
867  * @param client the client
868  * @param message the message
869  */
870 static void
871 handle_lookup(void *cls,
872               struct GNUNET_SERVER_Client * client,
873               const struct GNUNET_MessageHeader * message)
874 {
875   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "LOOKUP");
876
877   size_t msg_size = 0;
878   size_t namelen;
879   char name[MAX_DNS_NAME_LENGTH];
880   struct ClientLookupHandle *clh;
881   char* nameptr = name;
882   int only_cached;
883   struct GNUNET_CRYPTO_RsaPrivateKey *key;
884   struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *pkey;
885   char* tmp_pkey;
886
887   if (ntohs (message->size) < sizeof (struct GNUNET_GNS_ClientLookupMessage))
888   {
889     GNUNET_break_op (0);
890     GNUNET_SERVER_receive_done (client, GNUNET_OK);
891     return;
892   }
893
894   GNUNET_SERVER_notification_context_add (nc, client);
895
896   struct GNUNET_GNS_ClientLookupMessage *sh_msg =
897     (struct GNUNET_GNS_ClientLookupMessage *) message;
898   
899   msg_size = ntohs(message->size);
900
901   if (msg_size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
902   {
903     GNUNET_break_op (0);
904     GNUNET_SERVER_receive_done (client, GNUNET_OK);
905     return;
906   }
907
908   if (1 == ntohl(sh_msg->have_key))
909   {
910     pkey = (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *)&sh_msg[1];
911     tmp_pkey = (char*)&sh_msg[1];
912     key = GNUNET_CRYPTO_rsa_decode_key (tmp_pkey, ntohs(pkey->len));
913     GNUNET_STRINGS_utf8_tolower(&tmp_pkey[ntohs(pkey->len)], &nameptr);
914   }
915   else
916   {
917     key = NULL;
918     GNUNET_STRINGS_utf8_tolower((char*)&sh_msg[1], &nameptr);
919   }
920   
921   namelen = strlen(name)+1;
922   clh = GNUNET_malloc(sizeof(struct ClientLookupHandle));
923   clh->client = client;
924   clh->name = GNUNET_malloc(namelen);
925   strcpy(clh->name, name);
926   clh->unique_id = sh_msg->id;
927   clh->type = ntohl(sh_msg->type);
928   clh->shorten_key = key;
929
930   only_cached = ntohl(sh_msg->only_cached);
931   
932   if (strlen (name) > MAX_DNS_NAME_LENGTH) {
933     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
934                "LOOKUP: %s is too long", name);
935     clh->name = NULL;
936     send_lookup_response(clh, 0, NULL);
937     return;
938   }
939
940   if (1 == ntohl(sh_msg->use_default_zone))
941     clh->zone = zone_hash; //Default zone
942   else
943     clh->zone = sh_msg->zone;
944   
945   if (GNUNET_YES == auto_import_pkey)
946   {
947     gns_resolver_lookup_record (clh->zone, clh->zone, clh->type, clh->name,
948                                 clh->shorten_key,
949                                 default_lookup_timeout,
950                                 clh->only_cached,
951                                 &send_lookup_response, clh);  
952   }
953   else
954   {
955     gns_resolver_lookup_record (clh->zone, clh->zone, clh->type, name,
956                                 NULL,
957                                 default_lookup_timeout,
958                                 only_cached,
959                                 &send_lookup_response, clh);
960   }
961 }
962
963
964
965 /**
966  * Process GNS requests.
967  *
968  * @param cls closure)
969  * @param server the initialized server
970  * @param c configuration to use
971  */
972 static void
973 run (void *cls, struct GNUNET_SERVER_Handle *server,
974      const struct GNUNET_CONFIGURATION_Handle *c)
975 {
976   
977   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Initializing GNS\n");
978   
979   char* keyfile;
980   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pkey;
981   unsigned long long max_parallel_bg_queries = 0;
982   unsigned long long default_lookup_timeout_secs = 0;
983   int ignore_pending = GNUNET_NO;
984
985   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
986     {&handle_shorten, NULL, GNUNET_MESSAGE_TYPE_GNS_SHORTEN, 0},
987     {&handle_lookup, NULL, GNUNET_MESSAGE_TYPE_GNS_LOOKUP, 0},
988     {&handle_get_authority, NULL, GNUNET_MESSAGE_TYPE_GNS_GET_AUTH, 0}
989   };
990
991   GNS_cfg = c;
992
993   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (c, "gns",
994                                              "ZONEKEY", &keyfile))
995   {
996     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
997                 "No private key for root zone specified!\n");
998     GNUNET_SCHEDULER_shutdown ();
999     return;
1000   }
1001
1002   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1003              "Using keyfile %s for root zone.\n", keyfile);
1004
1005   zone_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
1006   GNUNET_CRYPTO_rsa_key_get_public (zone_key, &pkey);
1007
1008   GNUNET_CRYPTO_short_hash(&pkey,
1009                      sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1010                      &zone_hash);
1011   GNUNET_free(keyfile);
1012   
1013   /**
1014    * handle to our local namestore
1015    */
1016   namestore_handle = GNUNET_NAMESTORE_connect(c);
1017
1018   if (NULL == namestore_handle)
1019   {
1020     //FIXME do error handling;
1021     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1022                "Failed to connect to the namestore!\n");
1023     GNUNET_SCHEDULER_shutdown ();
1024     return;
1025   }
1026   
1027   
1028
1029   auto_import_pkey = GNUNET_NO;
1030
1031   if (GNUNET_YES ==
1032       GNUNET_CONFIGURATION_get_value_yesno (c, "gns",
1033                                             "AUTO_IMPORT_PKEY"))
1034   {
1035     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1036                "Automatic PKEY import is enabled.\n");
1037     auto_import_pkey = GNUNET_YES;
1038
1039   }
1040
1041   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (c, "gns",
1042                                                           "PRIVATE_ZONE",
1043                                                           &private_zone_id))
1044   {
1045     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1046                "Private zone id: %s\n", private_zone_id);
1047   }
1048
1049   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (c, "gns",
1050                                                           "SHORTEN_ZONE",
1051                                                           &shorten_zone_id))
1052   {
1053     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1054                "Shorten zone id: %s\n", shorten_zone_id);
1055   }
1056
1057   dht_max_update_interval = GNUNET_GNS_DHT_MAX_UPDATE_INTERVAL;
1058
1059   if (GNUNET_OK ==
1060       GNUNET_CONFIGURATION_get_value_number (c, "gns",
1061                                              "ZONE_PUT_INTERVAL",
1062                                              &dht_max_update_interval))
1063   {
1064     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1065                "DHT zone update interval: %d\n",
1066                dht_max_update_interval);
1067   }
1068   
1069   max_record_put_interval = 1;
1070
1071   if (GNUNET_OK ==
1072       GNUNET_CONFIGURATION_get_value_number (c, "gns",
1073                                              "RECORD_PUT_INTERVAL",
1074                                              &max_record_put_interval))
1075   {
1076     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1077                "Record put interval: %d\n",
1078                max_record_put_interval);
1079   }
1080   
1081   if (GNUNET_OK ==
1082       GNUNET_CONFIGURATION_get_value_number (c, "gns",
1083                                             "MAX_PARALLEL_BACKGROUND_QUERIES",
1084                                             &max_parallel_bg_queries))
1085   {
1086     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1087                "Number of allowed parallel background queries: %d\n",
1088                max_parallel_bg_queries);
1089   }
1090
1091   if (GNUNET_YES ==
1092       GNUNET_CONFIGURATION_get_value_yesno (c, "gns",
1093                                             "AUTO_IMPORT_CONFIRMATION_REQ"))
1094   {
1095     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1096                "Auto import requires user confirmation\n");
1097     ignore_pending = GNUNET_YES;
1098   }
1099
1100   if (GNUNET_OK ==
1101       GNUNET_CONFIGURATION_get_value_number(c, "gns",
1102                                             "DEFAULT_LOOKUP_TIMEOUT",
1103                                             &default_lookup_timeout_secs))
1104   {
1105     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1106                "Default lookup timeout: %ds\n", default_lookup_timeout_secs);
1107     default_lookup_timeout = GNUNET_TIME_relative_multiply(
1108                                             GNUNET_TIME_UNIT_SECONDS,
1109                                             default_lookup_timeout_secs);
1110   }
1111   
1112   /**
1113    * handle to the dht
1114    */
1115   dht_handle = GNUNET_DHT_connect(c,
1116                        //max_parallel_bg_queries); //FIXME get ht_len from cfg
1117                        1024);
1118
1119   if (NULL == dht_handle)
1120   {
1121     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Could not connect to DHT!\n");
1122   }
1123   
1124   if (gns_resolver_init(namestore_handle, dht_handle, zone_hash, c,
1125                         max_parallel_bg_queries,
1126                         ignore_pending)
1127       == GNUNET_SYSERR)
1128   {
1129     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1130                "Unable to initialize resolver!\n");
1131     GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
1132     return;
1133   }
1134
1135   if (GNUNET_YES ==
1136       GNUNET_CONFIGURATION_get_value_yesno (c, "gns", "HIJACK_DNS"))
1137   {
1138     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1139                "DNS hijacking enabled... connecting to service.\n");
1140
1141     if (gns_interceptor_init(zone_hash, zone_key, c) == GNUNET_SYSERR)
1142     {
1143       GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1144                "Failed to enable the dns interceptor!\n");
1145     }
1146   }
1147   
1148   /**
1149    * Schedule periodic put
1150    * for our records
1151    * We have roughly an hour for all records;
1152    */
1153   record_put_interval = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS,
1154                                                       1);
1155   zone_update_taskid = GNUNET_SCHEDULER_add_now (&update_zone_dht_start, NULL);
1156
1157   GNUNET_SERVER_add_handlers (server, handlers);
1158   
1159   //FIXME
1160   //GNUNET_SERVER_disconnect_notify (server,
1161   //                                 &client_disconnect_notification,
1162   //                                 NULL);
1163
1164   nc = GNUNET_SERVER_notification_context_create (server, 1);
1165
1166   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
1167                                 NULL);
1168 }
1169
1170
1171 /**
1172  * The main function for the GNS service.
1173  *
1174  * @param argc number of arguments from the command line
1175  * @param argv command line arguments
1176  * @return 0 ok, 1 on error
1177  */
1178 int
1179 main (int argc, char *const *argv)
1180 {
1181   int ret;
1182
1183   ret =
1184       (GNUNET_OK ==
1185        GNUNET_SERVICE_run (argc, argv, "gns", GNUNET_SERVICE_OPTION_NONE, &run,
1186                            NULL)) ? 0 : 1;
1187   return ret;
1188 }
1189
1190 /* end of gnunet-service-gns.c */