-doxy
[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 unsigned long long 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 %ds\n",
333                dht_max_update_interval);
334     namestore_iter = NULL;
335     zone_update_taskid = GNUNET_SCHEDULER_add_delayed (
336                                         GNUNET_TIME_relative_multiply(
337                                             GNUNET_TIME_UNIT_SECONDS,
338                                             dht_max_update_interval
339                                             ),
340                                             &update_zone_dht_start,
341                                             NULL);
342     return;
343   }
344   
345   namelen = strlen(name) + 1;
346   
347   if (signature == NULL)
348   {
349     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
350                "No signature for %s record data provided! Skipping...\n",
351                name);
352     zone_update_taskid = GNUNET_SCHEDULER_add_now (&update_zone_dht_next,
353                                                    NULL);
354     return;
355
356   }
357   
358   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
359              "Putting records for %s into the DHT\n", name);
360   
361   rd_payload_length = GNUNET_NAMESTORE_records_get_size (rd_count, rd);
362   
363   nrb = GNUNET_malloc(rd_payload_length + namelen
364                       + sizeof(struct GNSNameRecordBlock));
365   
366   nrb->signature = *signature;
367   
368   nrb->public_key = *key;
369
370   nrb->rd_count = htonl(rd_count);
371   
372   memcpy(&nrb[1], name, namelen);
373
374   nrb_data = (char*)&nrb[1];
375   nrb_data += namelen;
376
377   rd_payload_length += sizeof(struct GNSNameRecordBlock) + namelen;
378
379   if (-1 == GNUNET_NAMESTORE_records_serialize (rd_count,
380                                                 rd,
381                                                 rd_payload_length,
382                                                 nrb_data))
383   {
384     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
385                "Record serialization failed! Skipping...\n");
386     GNUNET_free(nrb);
387     zone_update_taskid = GNUNET_SCHEDULER_add_now (&update_zone_dht_next,
388                                                    NULL);
389     return;
390   }
391
392
393   /*
394    * calculate DHT key: H(name) xor H(pubkey)
395    */
396   GNUNET_CRYPTO_short_hash(key,
397                      sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
398                      &zhash);
399   GNUNET_CRYPTO_short_hash(name, strlen(name), &name_hash);
400   GNUNET_CRYPTO_short_hash_double (&name_hash, &name_hash_double);
401   GNUNET_CRYPTO_short_hash_double (&zhash, &zone_hash_double);
402   GNUNET_CRYPTO_hash_xor(&zone_hash_double, &name_hash_double, &xor_hash);
403
404   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
405              "zone identity: %s\n", GNUNET_h2s (&zone_hash_double));
406
407   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
408              "putting records for %s under key: %s with size %d\n",
409              name, GNUNET_h2s (&xor_hash), rd_payload_length);
410   
411   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
412              "DHT req to %d\n", DHT_OPERATION_TIMEOUT.rel_value);
413   /* FIXME: keep return value to possibly cancel? */
414   GNUNET_DHT_put (dht_handle, &xor_hash,
415                   DHT_GNS_REPLICATION_LEVEL,
416                   GNUNET_DHT_RO_NONE,
417                   GNUNET_BLOCK_TYPE_GNS_NAMERECORD,
418                   rd_payload_length,
419                   (char*)nrb,
420                   expiration,
421                   DHT_OPERATION_TIMEOUT,
422                   &record_dht_put,
423                   NULL); //cls for cont
424   
425   num_public_records++;
426
427   /**
428    * Reschedule periodic put
429    */
430   zone_update_taskid = GNUNET_SCHEDULER_add_delayed (record_put_interval,
431                                 &update_zone_dht_next,
432                                 NULL);
433
434   GNUNET_free(nrb);
435
436 }
437
438 /**
439  * Periodically iterate over our zone and store everything in dht
440  *
441  * @param cls NULL
442  * @param tc task context
443  */
444 static void
445 update_zone_dht_start(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
446 {
447   unsigned long long interval = 0;
448
449   zone_update_taskid = GNUNET_SCHEDULER_NO_TASK;
450
451   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Scheduling DHT zone update!\n");
452   if (0 == num_public_records)
453   {
454     /**
455      * If no records are known (startup) or none present
456      * we can safely set the interval to 1s
457      */
458     record_put_interval = GNUNET_TIME_relative_multiply(
459                                             GNUNET_TIME_UNIT_SECONDS,
460                                             1);
461     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
462                "No records in db. Adjusted record put interval to 1s\n");
463   }
464   else
465   {
466     interval = max_record_put_interval/num_public_records;
467     if (interval == 0)
468       interval = 1;
469     record_put_interval = GNUNET_TIME_relative_multiply(
470                                   GNUNET_TIME_UNIT_SECONDS,
471                                   interval);
472     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
473                "Adjusted DHT update interval to %ds!\n",
474                interval);
475   }
476
477   /* start counting again */
478   num_public_records = 0;
479   namestore_iter = GNUNET_NAMESTORE_zone_iteration_start (namestore_handle,
480                                                  NULL, //All zones
481                                                  GNUNET_NAMESTORE_RF_AUTHORITY,
482                                                  GNUNET_NAMESTORE_RF_PRIVATE,
483                                                  &put_gns_record,
484                                                  NULL);
485 }
486
487 /* END DHT ZONE PROPAGATION */
488
489 /**
490  * Send shorten response back to client
491  * 
492  * @param cls the closure containing a client shorten handle
493  * @param name the shortened name result or NULL if cannot be shortened
494  */
495 static void
496 send_shorten_response(void* cls, const char* name)
497 {
498   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message with %s\n",
499               "SHORTEN_RESULT", name);
500   struct GNUNET_GNS_ClientShortenResultMessage *rmsg;
501   struct ClientShortenHandle *csh = (struct ClientShortenHandle *)cls;
502   
503   if (name == NULL)
504   {
505     name = "";
506   }
507
508   rmsg = GNUNET_malloc(sizeof(struct GNUNET_GNS_ClientShortenResultMessage)
509                        + strlen(name) + 1);
510   
511   rmsg->id = csh->unique_id;
512   rmsg->header.type = htons(GNUNET_MESSAGE_TYPE_GNS_SHORTEN_RESULT);
513   rmsg->header.size = 
514     htons(sizeof(struct GNUNET_GNS_ClientShortenResultMessage) +
515           strlen(name) + 1);
516
517   strcpy((char*)&rmsg[1], name);
518
519   GNUNET_SERVER_notification_context_unicast (nc, csh->client,
520                               (const struct GNUNET_MessageHeader *) rmsg,
521                               GNUNET_NO);
522   GNUNET_SERVER_receive_done (csh->client, GNUNET_OK);
523
524   if (NULL != csh->namestore_task)
525     GNUNET_NAMESTORE_cancel (csh->namestore_task);
526   
527   GNUNET_free(rmsg);
528   GNUNET_free(csh);
529
530 }
531
532
533 /**
534  * Lookup the zone infos and shorten name
535  *
536  * @param cls the client shorten handle
537  * @param key key of the zone
538  * @param expiration expiration of record
539  * @param name name found or null if no result
540  * @param rd_count number of records found
541  * @param rd record data
542  * @param signature
543  *
544  */
545 static void
546 process_shorten_in_private_zone_lookup (void *cls,
547                       const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
548                       struct GNUNET_TIME_Absolute expiration,
549                       const char *name,
550                       unsigned int rd_count,
551                       const struct GNUNET_NAMESTORE_RecordData *rd,
552                       const struct GNUNET_CRYPTO_RsaSignature *signature)
553 {
554   struct ClientShortenHandle *csh = cls;
555   csh->namestore_task = NULL;
556   struct GNUNET_CRYPTO_ShortHashCode *szone = &csh->shorten_zone;
557   struct GNUNET_CRYPTO_ShortHashCode *pzone = &csh->private_zone;
558
559   if (0 == strcmp (csh->private_zone_id, ""))
560     pzone = NULL;
561   
562   if (rd_count == 0)
563   {
564     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
565                 "No shorten zone in private zone!\n");
566
567     strcpy (csh->shorten_zone_id, "");
568     szone = NULL;
569
570   }
571   else
572   {
573
574     GNUNET_assert (rd_count == 1);
575
576     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
577                 "Shorten zone %s found in private zone %s\n",
578                 name, csh->private_zone_id);
579
580     sprintf (csh->shorten_zone_id, "%s.%s", name, csh->private_zone_id);
581   }
582   
583   GNUNET_CONTAINER_DLL_remove (csh_head, csh_tail, csh);
584
585   gns_resolver_shorten_name (&csh->root_zone,
586                              pzone,
587                              szone,
588                              csh->name,
589                              csh->private_zone_id,
590                              csh->shorten_zone_id,
591                              &send_shorten_response, csh);
592
593 }
594
595
596 /**
597  * Lookup the zone infos and shorten name
598  *
599  * @param cls the shorten handle
600  * @param key key of the zone
601  * @param expiration expiration of record
602  * @param name name found or null if no result
603  * @param rd_count number of records found
604  * @param rd record data
605  * @param signature
606  *
607  */
608 static void
609 process_shorten_in_root_zone_lookup (void *cls,
610                       const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
611                       struct GNUNET_TIME_Absolute expiration,
612                       const char *name,
613                       unsigned int rd_count,
614                       const struct GNUNET_NAMESTORE_RecordData *rd,
615                       const struct GNUNET_CRYPTO_RsaSignature *signature)
616 {
617   struct ClientShortenHandle *csh = cls;
618   csh->namestore_task = NULL;
619   struct GNUNET_CRYPTO_ShortHashCode *szone = &csh->shorten_zone;
620   struct GNUNET_CRYPTO_ShortHashCode *pzone = &csh->private_zone;
621   
622   if (0 == strcmp (csh->private_zone_id, ""))
623     pzone = NULL;
624
625   if (rd_count == 0)
626   {
627     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
628                 "No shorten zone in zone and no private zone!\n");
629
630     strcpy (csh->shorten_zone_id, "");
631
632     GNUNET_CONTAINER_DLL_remove (csh_head, csh_tail, csh);
633     szone = NULL;
634
635     gns_resolver_shorten_name (&csh->root_zone,
636                                pzone,
637                                szone,
638                                csh->name,
639                                csh->private_zone_id,
640                                csh->shorten_zone_id,
641                                &send_shorten_response, csh);
642     return;
643   }
644
645   GNUNET_assert (rd_count == 1);
646
647   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
648               "Private zone %s found in root zone\n", name);
649
650   strcpy (csh->private_zone_id, name);
651
652   csh->namestore_task = GNUNET_NAMESTORE_zone_to_name (namestore_handle,
653                                   pzone,
654                                   szone,
655                                   &process_shorten_in_private_zone_lookup,
656                                   csh);
657 }
658
659
660 /**
661  * Lookup the zone infos and shorten name
662  *
663  * @param cls the shorten handle
664  * @param key key of the zone
665  * @param expiration expiration of record
666  * @param name name found or null if no result
667  * @param rd_count number of records found
668  * @param rd record data
669  * @param signature
670  *
671  */
672 static void
673 process_private_in_root_zone_lookup (void *cls,
674                       const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
675                       struct GNUNET_TIME_Absolute expiration,
676                       const char *name,
677                       unsigned int rd_count,
678                       const struct GNUNET_NAMESTORE_RecordData *rd,
679                       const struct GNUNET_CRYPTO_RsaSignature *signature)
680 {
681   struct ClientShortenHandle *csh = cls;
682   csh->namestore_task = NULL;
683
684   if (rd_count == 0)
685   {
686     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
687                 "No private zone in root zone\n");
688
689     strcpy (csh->private_zone_id, "");
690   
691     csh->namestore_task = GNUNET_NAMESTORE_zone_to_name (namestore_handle,
692                                   &csh->root_zone,
693                                   &csh->shorten_zone,
694                                   &process_shorten_in_root_zone_lookup,
695                                   csh);
696     return;
697   }
698
699   GNUNET_assert (rd_count == 1);
700
701   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
702               "Private zone %s found in root zone\n", name);
703
704   strcpy (csh->private_zone_id, name);
705
706   csh->namestore_task = GNUNET_NAMESTORE_zone_to_name (namestore_handle,
707                                   &csh->private_zone,
708                                   &csh->shorten_zone,
709                                   &process_shorten_in_private_zone_lookup,
710                                   csh);
711 }
712
713 /**
714  * Lookup the zone infos and shorten name
715  *
716  * @param csh the shorten handle
717  *
718  */
719 static void
720 start_shorten_name (struct ClientShortenHandle *csh)
721 {
722   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
723               "Looking for private zone name in root zone\n");
724
725   csh->namestore_task = GNUNET_NAMESTORE_zone_to_name (namestore_handle,
726                                   &csh->root_zone,
727                                   &csh->private_zone,
728                                   &process_private_in_root_zone_lookup,
729                                   csh);
730 }
731
732
733 /**
734  * Handle a shorten message from the api
735  *
736  * @param cls the closure
737  * @param client the client
738  * @param message the message
739  */
740 static void handle_shorten (void *cls,
741                             struct GNUNET_SERVER_Client * client,
742                             const struct GNUNET_MessageHeader * message)
743 {
744   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "SHORTEN");
745
746   size_t msg_size = 0;
747   struct ClientShortenHandle *csh;
748   char name[MAX_DNS_NAME_LENGTH];
749   char* nameptr = name;
750
751   if (ntohs (message->size) < sizeof (struct GNUNET_GNS_ClientShortenMessage))
752   {
753     GNUNET_break_op (0);
754     GNUNET_SERVER_receive_done (client, GNUNET_OK);
755     return;
756   }
757
758
759   struct GNUNET_GNS_ClientShortenMessage *sh_msg =
760     (struct GNUNET_GNS_ClientShortenMessage *) message;
761   
762   msg_size = ntohs(message->size);
763
764   if (msg_size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
765   {
766     GNUNET_break_op (0);
767     GNUNET_SERVER_receive_done (client, GNUNET_OK);
768     return;
769   }
770
771   csh = GNUNET_malloc(sizeof(struct ClientShortenHandle));
772   csh->client = client;
773   csh->unique_id = sh_msg->id;
774
775   GNUNET_CONTAINER_DLL_insert (csh_head, csh_tail, csh);
776   
777   GNUNET_STRINGS_utf8_tolower((char*)&sh_msg[1], &nameptr);
778
779   if (strlen (name) < strlen(GNUNET_GNS_TLD)) {
780     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
781                "SHORTEN: %s is too short", name);
782     send_shorten_response(csh, name);
783     return;
784   }
785
786   if (strlen (name) > MAX_DNS_NAME_LENGTH) {
787     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
788                "SHORTEN: %s is too long", name);
789     send_shorten_response(csh, name);
790     return;
791   }
792   
793   if (!is_gnunet_tld(name) && !is_zkey_tld(name))
794   {
795     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
796                 "%s is not our domain. Returning\n", name);
797     send_shorten_response(csh, name);
798     return;
799   }
800
801   csh->shorten_zone = sh_msg->shorten_zone;
802   csh->private_zone = sh_msg->private_zone;
803
804   strcpy (csh->name, name);
805   
806   GNUNET_SERVER_notification_context_add (nc, client);
807   
808   if (1 == ntohl(sh_msg->use_default_zone))
809     csh->root_zone = zone_hash; //Default zone
810   else
811     csh->root_zone = sh_msg->zone;
812
813   start_shorten_name (csh);
814   
815 }
816
817
818 /**
819  * Send get authority response back to client
820  * 
821  * @param cls the closure containing a client get auth handle
822  * @param name the shortened name result or NULL if cannot be shortened
823  */
824 static void
825 send_get_auth_response(void *cls, const char* name)
826 {
827   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message with %s\n",
828               "GET_AUTH_RESULT", name);
829   struct GNUNET_GNS_ClientGetAuthResultMessage *rmsg;
830   struct ClientGetAuthHandle *cah = (struct ClientGetAuthHandle *)cls;
831   
832   if (name == NULL)
833   {
834     name = "";
835   }
836
837   rmsg = GNUNET_malloc(sizeof(struct GNUNET_GNS_ClientGetAuthResultMessage)
838                        + strlen(name) + 1);
839   
840   rmsg->id = cah->unique_id;
841   rmsg->header.type = htons(GNUNET_MESSAGE_TYPE_GNS_GET_AUTH_RESULT);
842   rmsg->header.size = 
843     htons(sizeof(struct GNUNET_GNS_ClientGetAuthResultMessage) +
844           strlen(name) + 1);
845
846   strcpy((char*)&rmsg[1], name);
847
848   GNUNET_SERVER_notification_context_unicast (nc, cah->client,
849                               (const struct GNUNET_MessageHeader *) rmsg,
850                               GNUNET_NO);
851   GNUNET_SERVER_receive_done (cah->client, GNUNET_OK);
852   
853   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Cleaning up handles...\n");
854
855   GNUNET_free(rmsg);
856   GNUNET_free_non_null(cah->name);
857   GNUNET_free(cah);
858
859   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "done.\n");
860
861 }
862
863
864 /**
865  * Handle a get authority message from the api
866  *
867  * @param cls the closure
868  * @param client the client
869  * @param message the message
870  */
871 static void handle_get_authority(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", "GET_AUTH");
876
877   size_t msg_size = 0;
878   struct ClientGetAuthHandle *cah;
879   char name[MAX_DNS_NAME_LENGTH];
880   char* nameptr = name;
881
882
883   if (ntohs (message->size) < sizeof (struct GNUNET_GNS_ClientGetAuthMessage))
884   {
885     GNUNET_break_op (0);
886     GNUNET_SERVER_receive_done (client, GNUNET_OK);
887     return;
888   }
889
890   GNUNET_SERVER_notification_context_add (nc, client);
891
892   struct GNUNET_GNS_ClientGetAuthMessage *sh_msg =
893     (struct GNUNET_GNS_ClientGetAuthMessage *) message;
894   
895   msg_size = ntohs(message->size);
896
897   if (msg_size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
898   {
899     GNUNET_break_op (0);
900     GNUNET_SERVER_receive_done (client, GNUNET_OK);
901     return;
902   }
903   
904   GNUNET_STRINGS_utf8_tolower((char*)&sh_msg[1], &nameptr);
905
906
907   cah = GNUNET_malloc(sizeof(struct ClientGetAuthHandle));
908   cah->client = client;
909   cah->unique_id = sh_msg->id;
910
911   if (strlen(name) < strlen(GNUNET_GNS_TLD))
912   {
913     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
914                 "GET_AUTH: %s is too short. Returning\n", name);
915     cah->name = NULL;
916     send_get_auth_response(cah, name);
917     return;
918   }
919   
920   if (strlen (name) > MAX_DNS_NAME_LENGTH) {
921     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
922                "GET_AUTH: %s is too long", name);
923     cah->name = NULL;
924     send_get_auth_response(cah, name);
925     return;
926   }
927   
928   if (strcmp(name+strlen(name)-strlen(GNUNET_GNS_TLD),
929              GNUNET_GNS_TLD) != 0)
930   {
931     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
932                 "GET_AUTH: %s is not our domain. Returning\n", name);
933     cah->name = NULL;
934     send_get_auth_response(cah, name);
935     return;
936   }
937
938   if (strcmp(name, GNUNET_GNS_TLD) == 0)
939   {
940     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
941                 "GET_AUTH: %s is us. Returning\n", name);
942     cah->name = NULL;
943     send_get_auth_response(cah, name);
944     return;
945   }
946   
947   cah->name = GNUNET_malloc(strlen(name)
948                             - strlen(GNUNET_GNS_TLD) + 1);
949   memset(cah->name, 0,
950          strlen(name)-strlen(GNUNET_GNS_TLD) + 1);
951   memcpy(cah->name, name,
952          strlen(name)-strlen(GNUNET_GNS_TLD));
953
954   /* Start delegation resolution in our namestore */
955   gns_resolver_get_authority(zone_hash, zone_hash, name, &send_get_auth_response, cah);
956 }
957
958
959
960 /**
961  * Reply to client with the result from our lookup.
962  *
963  * @param cls the closure (our client lookup handle)
964  * @param rd_count the number of records
965  * @param rd the record data
966  */
967 static void
968 send_lookup_response(void* cls,
969                      uint32_t rd_count,
970                      const struct GNUNET_NAMESTORE_RecordData *rd)
971 {
972   struct ClientLookupHandle* clh = (struct ClientLookupHandle*)cls;
973   struct GNUNET_GNS_ClientLookupResultMessage *rmsg;
974   size_t len;
975   
976   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message with %d results\n",
977               "LOOKUP_RESULT", rd_count);
978   
979   len = GNUNET_NAMESTORE_records_get_size (rd_count, rd);
980   rmsg = GNUNET_malloc(len+sizeof(struct GNUNET_GNS_ClientLookupResultMessage));
981   
982   rmsg->id = clh->unique_id;
983   rmsg->rd_count = htonl(rd_count);
984   rmsg->header.type = htons(GNUNET_MESSAGE_TYPE_GNS_LOOKUP_RESULT);
985   rmsg->header.size = 
986     htons(len+sizeof(struct GNUNET_GNS_ClientLookupResultMessage));
987   
988   GNUNET_NAMESTORE_records_serialize (rd_count, rd, len, (char*)&rmsg[1]);
989   
990   GNUNET_SERVER_notification_context_unicast (nc, clh->client,
991                                 (const struct GNUNET_MessageHeader *) rmsg,
992                                 GNUNET_NO);
993   GNUNET_SERVER_receive_done (clh->client, GNUNET_OK);
994   
995   GNUNET_free(rmsg);
996   GNUNET_free(clh->name);
997   
998   if (NULL != clh->shorten_key)
999     GNUNET_free(clh->shorten_key);
1000
1001   GNUNET_free(clh);
1002
1003 }
1004
1005
1006 /**
1007  * Handle lookup requests from client
1008  *
1009  * @param cls the closure
1010  * @param client the client
1011  * @param message the message
1012  */
1013 static void
1014 handle_lookup(void *cls,
1015               struct GNUNET_SERVER_Client * client,
1016               const struct GNUNET_MessageHeader * message)
1017 {
1018   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "LOOKUP");
1019
1020   size_t msg_size = 0;
1021   size_t namelen;
1022   char name[MAX_DNS_NAME_LENGTH];
1023   struct ClientLookupHandle *clh;
1024   char* nameptr = name;
1025   int only_cached;
1026   struct GNUNET_CRYPTO_RsaPrivateKey *key;
1027   struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *pkey;
1028   char* tmp_pkey;
1029
1030   if (ntohs (message->size) < sizeof (struct GNUNET_GNS_ClientLookupMessage))
1031   {
1032     GNUNET_break_op (0);
1033     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1034     return;
1035   }
1036
1037   GNUNET_SERVER_notification_context_add (nc, client);
1038
1039   struct GNUNET_GNS_ClientLookupMessage *sh_msg =
1040     (struct GNUNET_GNS_ClientLookupMessage *) message;
1041   
1042   msg_size = ntohs(message->size);
1043
1044   if (msg_size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
1045   {
1046     GNUNET_break_op (0);
1047     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1048     return;
1049   }
1050
1051   if (1 == ntohl(sh_msg->have_key))
1052   {
1053     pkey = (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *)&sh_msg[1];
1054     tmp_pkey = (char*)&sh_msg[1];
1055     key = GNUNET_CRYPTO_rsa_decode_key (tmp_pkey, ntohs(pkey->len));
1056     GNUNET_STRINGS_utf8_tolower(&tmp_pkey[ntohs(pkey->len)], &nameptr);
1057   }
1058   else
1059   {
1060     key = NULL;
1061     GNUNET_STRINGS_utf8_tolower((char*)&sh_msg[1], &nameptr);
1062   }
1063   
1064   namelen = strlen(name)+1;
1065   clh = GNUNET_malloc (sizeof (struct ClientLookupHandle));
1066   memset (clh, 0, sizeof (struct ClientLookupHandle));
1067   clh->client = client;
1068   clh->name = GNUNET_malloc(namelen);
1069   strcpy(clh->name, name);
1070   clh->unique_id = sh_msg->id;
1071   clh->type = ntohl(sh_msg->type);
1072   clh->shorten_key = key;
1073
1074   only_cached = ntohl(sh_msg->only_cached);
1075   
1076   if (strlen (name) > MAX_DNS_NAME_LENGTH) {
1077     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1078                "LOOKUP: %s is too long", name);
1079     clh->name = NULL;
1080     send_lookup_response(clh, 0, NULL);
1081     return;
1082   }
1083
1084   if ((clh->type == GNUNET_GNS_RECORD_A) &&
1085       (GNUNET_OK != v4_enabled))
1086   {
1087     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1088                "LOOKUP: Query for A record but AF_INET not supported!");
1089     clh->name = NULL;
1090     send_lookup_response(clh, 0, NULL);
1091     return;
1092   }
1093   
1094   if ((clh->type == GNUNET_GNS_RECORD_AAAA) &&
1095       (GNUNET_OK != v6_enabled))
1096   {
1097     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1098                "LOOKUP: Query for AAAA record but AF_INET6 not supported!");
1099     clh->name = NULL;
1100     send_lookup_response(clh, 0, NULL);
1101     return;
1102   }
1103   
1104   if (1 == ntohl(sh_msg->use_default_zone))
1105     clh->zone = zone_hash; //Default zone
1106   else
1107     clh->zone = sh_msg->zone;
1108   
1109   if (GNUNET_YES == auto_import_pkey)
1110   {
1111     gns_resolver_lookup_record (clh->zone, clh->zone, clh->type, clh->name,
1112                                 clh->shorten_key,
1113                                 default_lookup_timeout,
1114                                 clh->only_cached,
1115                                 &send_lookup_response, clh);  
1116   }
1117   else
1118   {
1119     gns_resolver_lookup_record (clh->zone, clh->zone, clh->type, name,
1120                                 NULL,
1121                                 default_lookup_timeout,
1122                                 only_cached,
1123                                 &send_lookup_response, clh);
1124   }
1125 }
1126
1127 /**
1128  * Test if the given AF is supported by this system.
1129  *
1130  * @param af to test
1131  * @return GNUNET_OK if the AF is supported
1132  */
1133 static int
1134 test_af (int af)
1135 {
1136   int s;
1137
1138   s = socket (af, SOCK_STREAM, 0);
1139   if (-1 == s)
1140   {
1141     if (EAFNOSUPPORT == errno)
1142       return GNUNET_NO;
1143     fprintf (stderr, "Failed to create test socket: %s\n", STRERROR (errno));
1144     return GNUNET_SYSERR;
1145   }
1146   close (s);
1147   return GNUNET_OK;
1148 }
1149
1150 /**
1151  * Process GNS requests.
1152  *
1153  * @param cls closure)
1154  * @param server the initialized server
1155  * @param c configuration to use
1156  */
1157 static void
1158 run (void *cls, struct GNUNET_SERVER_Handle *server,
1159      const struct GNUNET_CONFIGURATION_Handle *c)
1160 {
1161   
1162   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Initializing GNS\n");
1163   
1164   char* keyfile;
1165   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pkey;
1166   unsigned long long max_parallel_bg_queries = 0;
1167   unsigned long long default_lookup_timeout_secs = 0;
1168   int ignore_pending = GNUNET_NO;
1169
1170   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1171     {&handle_shorten, NULL, GNUNET_MESSAGE_TYPE_GNS_SHORTEN, 0},
1172     {&handle_lookup, NULL, GNUNET_MESSAGE_TYPE_GNS_LOOKUP, 0},
1173     {&handle_get_authority, NULL, GNUNET_MESSAGE_TYPE_GNS_GET_AUTH, 0}
1174   };
1175
1176   GNS_cfg = c;
1177
1178   v6_enabled = test_af (AF_INET6);
1179   v4_enabled = test_af (AF_INET);
1180
1181   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (c, "gns",
1182                                              "ZONEKEY", &keyfile))
1183   {
1184     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1185                 "No private key for root zone specified!\n");
1186     GNUNET_SCHEDULER_shutdown ();
1187     return;
1188   }
1189
1190   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1191              "Using keyfile %s for root zone.\n", keyfile);
1192
1193   zone_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
1194   GNUNET_CRYPTO_rsa_key_get_public (zone_key, &pkey);
1195
1196   GNUNET_CRYPTO_short_hash(&pkey,
1197                      sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1198                      &zone_hash);
1199   GNUNET_free(keyfile);
1200   
1201   /**
1202    * handle to our local namestore
1203    */
1204   namestore_handle = GNUNET_NAMESTORE_connect(c);
1205
1206   if (NULL == namestore_handle)
1207   {
1208     //FIXME do error handling;
1209     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1210                "Failed to connect to the namestore!\n");
1211     GNUNET_SCHEDULER_shutdown ();
1212     return;
1213   }
1214   
1215   
1216
1217   auto_import_pkey = GNUNET_NO;
1218
1219   if (GNUNET_YES ==
1220       GNUNET_CONFIGURATION_get_value_yesno (c, "gns",
1221                                             "AUTO_IMPORT_PKEY"))
1222   {
1223     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1224                "Automatic PKEY import is enabled.\n");
1225     auto_import_pkey = GNUNET_YES;
1226
1227   }
1228
1229   dht_max_update_interval = GNUNET_GNS_DHT_MAX_UPDATE_INTERVAL;
1230
1231   if (GNUNET_OK ==
1232       GNUNET_CONFIGURATION_get_value_number (c, "gns",
1233                                              "ZONE_PUT_INTERVAL",
1234                                              &dht_max_update_interval))
1235   {
1236     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1237                 "DHT zone update interval: %llu\n",
1238                 dht_max_update_interval);
1239   }
1240   
1241   max_record_put_interval = 1;
1242
1243   if (GNUNET_OK ==
1244       GNUNET_CONFIGURATION_get_value_number (c, "gns",
1245                                              "RECORD_PUT_INTERVAL",
1246                                              &max_record_put_interval))
1247   {
1248     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1249                "Record put interval: %llu\n",
1250                max_record_put_interval);
1251   }
1252   
1253   if (GNUNET_OK ==
1254       GNUNET_CONFIGURATION_get_value_number (c, "gns",
1255                                             "MAX_PARALLEL_BACKGROUND_QUERIES",
1256                                             &max_parallel_bg_queries))
1257   {
1258     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1259                "Number of allowed parallel background queries: %llu\n",
1260                max_parallel_bg_queries);
1261   }
1262
1263   if (GNUNET_YES ==
1264       GNUNET_CONFIGURATION_get_value_yesno (c, "gns",
1265                                             "AUTO_IMPORT_CONFIRMATION_REQ"))
1266   {
1267     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1268                "Auto import requires user confirmation\n");
1269     ignore_pending = GNUNET_YES;
1270   }
1271
1272   if (GNUNET_OK ==
1273       GNUNET_CONFIGURATION_get_value_number(c, "gns",
1274                                             "DEFAULT_LOOKUP_TIMEOUT",
1275                                             &default_lookup_timeout_secs))
1276   {
1277     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1278                "Default lookup timeout: %llus\n", default_lookup_timeout_secs);
1279     default_lookup_timeout = GNUNET_TIME_relative_multiply(
1280                                             GNUNET_TIME_UNIT_SECONDS,
1281                                             default_lookup_timeout_secs);
1282   }
1283   
1284   /**
1285    * handle to the dht
1286    */
1287   dht_handle = GNUNET_DHT_connect(c,
1288                        //max_parallel_bg_queries); //FIXME get ht_len from cfg
1289                        1024);
1290
1291   if (NULL == dht_handle)
1292   {
1293     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Could not connect to DHT!\n");
1294   }
1295   
1296   if (gns_resolver_init(namestore_handle, dht_handle, zone_hash, c,
1297                         max_parallel_bg_queries,
1298                         ignore_pending)
1299       == GNUNET_SYSERR)
1300   {
1301     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1302                "Unable to initialize resolver!\n");
1303     GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
1304     return;
1305   }
1306
1307   if (GNUNET_YES ==
1308       GNUNET_CONFIGURATION_get_value_yesno (c, "gns", "HIJACK_DNS"))
1309   {
1310     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1311                "DNS hijacking enabled... connecting to service.\n");
1312
1313     if (gns_interceptor_init(zone_hash, zone_key, c) == GNUNET_SYSERR)
1314     {
1315       GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1316                "Failed to enable the dns interceptor!\n");
1317     }
1318   }
1319   
1320   /**
1321    * Schedule periodic put
1322    * for our records
1323    * We have roughly an hour for all records;
1324    */
1325   record_put_interval = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS,
1326                                                       1);
1327   zone_update_taskid = GNUNET_SCHEDULER_add_now (&update_zone_dht_start, NULL);
1328
1329   GNUNET_SERVER_add_handlers (server, handlers);
1330   
1331   //FIXME
1332   //GNUNET_SERVER_disconnect_notify (server,
1333   //                                 &client_disconnect_notification,
1334   //                                 NULL);
1335
1336   nc = GNUNET_SERVER_notification_context_create (server, 1);
1337
1338   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
1339                                 NULL);
1340 }
1341
1342
1343 /**
1344  * The main function for the GNS service.
1345  *
1346  * @param argc number of arguments from the command line
1347  * @param argv command line arguments
1348  * @return 0 ok, 1 on error
1349  */
1350 int
1351 main (int argc, char *const *argv)
1352 {
1353   int ret;
1354
1355   ret =
1356       (GNUNET_OK ==
1357        GNUNET_SERVICE_run (argc, argv, "gns", GNUNET_SERVICE_OPTION_NONE, &run,
1358                            NULL)) ? 0 : 1;
1359   return ret;
1360 }
1361
1362 /* end of gnunet-service-gns.c */