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