-disable tests for now
[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  * TODO:
24  *    - Write xquery and block plugin
25  *    - The smaller FIXME issues all around
26  *
27  * @file gns/gnunet-service-gns.c
28  * @brief GNUnet GNS service
29  * @author Martin Schanzenbach
30  */
31 #include "platform.h"
32 #include "gnunet_util_lib.h"
33 #include "gnunet_transport_service.h"
34 #include "gnunet_dns_service.h"
35 #include "gnunet_dnsparser_lib.h"
36 #include "gnunet_dht_service.h"
37 #include "gnunet_namestore_service.h"
38 #include "gnunet_gns_service.h"
39 #include "block_gns.h"
40 #include "gns.h"
41
42 #define DHT_OPERATION_TIMEOUT  GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 3)
43 #define DHT_LOOKUP_TIMEOUT DHT_OPERATION_TIMEOUT
44 #define DHT_GNS_REPLICATION_LEVEL 5
45 #define MAX_DNS_LABEL_LENGTH 63
46
47 /* Ignore for now not used anyway and probably never will */
48 #define GNUNET_MESSAGE_TYPE_GNS_LOOKUP 23
49 #define GNUNET_MESSAGE_TYPE_GNS_LOOKUP_RESULT 24
50 #define GNUNET_MESSAGE_TYPE_GNS_SHORTEN 25
51 #define GNUNET_MESSAGE_TYPE_GNS_SHORTEN_RESULT 26
52
53
54 struct AuthorityChain
55 {
56   struct AuthorityChain *prev;
57
58   struct AuthorityChain *next;
59
60   GNUNET_HashCode zone;
61
62   /* (local) name of the authority */
63   char* name;
64
65   /* was the ns entry fresh */
66   int fresh;
67 };
68
69 struct GNUNET_GNS_ResolverHandle;
70
71 typedef void (*ResolutionResultProcessor) (void *cls,
72                                   struct GNUNET_GNS_ResolverHandle *rh,
73                                   uint32_t rd_count,
74                                   const struct GNUNET_NAMESTORE_RecordData *rd);
75
76 enum ResolutionStatus
77 {
78   EXISTS = 1,
79   EXPIRED = 2
80 };
81
82 /**
83  * Handle to a currenty pending resolution
84  */
85 struct GNUNET_GNS_ResolverHandle
86 {
87   /* The name to resolve */
88   char *name;
89
90   /* the request handle to reply to */
91   struct GNUNET_DNS_RequestHandle *request_handle;
92   
93   /* the dns parser packet received */
94   struct GNUNET_DNSPARSER_Packet *packet;
95   
96   /* the query parsed from the packet */
97
98   struct GNUNET_DNSPARSER_Query *query;
99   
100   /* has this query been answered? how many matches */
101   int answered;
102
103   /* the authoritative zone to query */
104   GNUNET_HashCode authority;
105
106   /* the name of the authoritative zone to query */
107   char *authority_name;
108
109   /**
110    * we have an authority in namestore that
111    * may be able to resolve
112    */
113   int authority_found;
114
115   /* a handle for dht lookups. should be NULL if no lookups are in progress */
116   struct GNUNET_DHT_GetHandle *get_handle;
117
118   /* timeout task for dht lookups */
119   GNUNET_SCHEDULER_TaskIdentifier dht_timeout_task;
120
121   ResolutionResultProcessor proc;
122
123   void* proc_cls;
124
125   struct AuthorityChain *authority_chain_head;
126   struct AuthorityChain *authority_chain_tail;
127
128   enum ResolutionStatus status;
129
130 };
131
132 struct ClientShortenHandle
133 {
134   struct GNUNET_SERVER_Client *client;
135   uint64_t unique_id;
136   GNUNET_HashCode key;
137   char* name;
138   uint32_t offset;
139 };
140
141 /**
142  * Our handle to the DNS handler library
143  */
144 struct GNUNET_DNS_Handle *dns_handle;
145
146 /**
147  * Our handle to the DHT
148  */
149 struct GNUNET_DHT_Handle *dht_handle;
150
151 /**
152  * Our zone's private key
153  */
154 struct GNUNET_CRYPTO_RsaPrivateKey *zone_key;
155
156 /**
157  * Our handle to the namestore service
158  * FIXME maybe need a second handle for iteration
159  */
160 struct GNUNET_NAMESTORE_Handle *namestore_handle;
161
162 /**
163  * Handle to iterate over our authoritative zone in namestore
164  */
165 struct GNUNET_NAMESTORE_ZoneIterator *namestore_iter;
166
167 /**
168  * The configuration the GNS service is running with
169  */
170 const struct GNUNET_CONFIGURATION_Handle *GNS_cfg;
171
172 /**
173  * Our notification context.
174  */
175 static struct GNUNET_SERVER_NotificationContext *nc;
176
177 /**
178  * Our zone hash
179  */
180 GNUNET_HashCode zone_hash;
181
182 /**
183  * Our tld. Maybe get from config file
184  */
185 const char* gnunet_tld = ".gnunet";
186
187 /**
188  * Useful for zone update for DHT put
189  */
190 static int num_public_records =  3600;
191 struct GNUNET_TIME_Relative dht_update_interval;
192 GNUNET_SCHEDULER_TaskIdentifier zone_update_taskid = GNUNET_SCHEDULER_NO_TASK;
193
194 //static void resolve_name(struct GNUNET_GNS_ResolverHandle *rh);
195
196 /**
197  * Reply to client with the result from our lookup.
198  *
199  * @param rh the request handle of the lookup
200  * @param rd_count the number of records to return
201  * @param rd the record data
202  */
203 static void
204 reply_to_dns(void* cls, struct GNUNET_GNS_ResolverHandle *rh, uint32_t rd_count,
205              const struct GNUNET_NAMESTORE_RecordData *rd)
206 {
207   int i;
208   size_t len;
209   int ret;
210   char *buf;
211   struct GNUNET_DNSPARSER_Packet *packet = rh->packet;
212   struct GNUNET_DNSPARSER_Record answer_records[rh->answered];
213   struct GNUNET_DNSPARSER_Record additional_records[rd_count-(rh->answered)];
214   packet->answers = answer_records;
215   packet->additional_records = additional_records;
216   
217   /**
218    * Put records in the DNS packet and modify it
219    * to a response
220    */
221   len = sizeof(struct GNUNET_DNSPARSER_Record*);
222   for (i=0; i < rd_count; i++)
223   {
224     
225     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
226                "Adding type %d to DNS response\n", rd[i].record_type);
227     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Name: %s\n", rh->name);
228     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "QName: %s\n", rh->query->name);
229     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Record %d/%d\n", i+1, rd_count);
230     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Record len %d\n", rd[i].data_size);
231     
232     if (rd[i].record_type == rh->query->type)
233     {
234       answer_records[i].name = rh->query->name;
235       answer_records[i].type = rd[i].record_type;
236       answer_records[i].data.raw.data_len = rd[i].data_size;
237       answer_records[i].data.raw.data = (char*)rd[i].data;
238       answer_records[i].expiration_time = rd[i].expiration;
239       answer_records[i].class = GNUNET_DNSPARSER_CLASS_INTERNET;//hmmn
240     }
241     else
242     {
243       additional_records[i].name = rh->query->name;
244       additional_records[i].type = rd[i].record_type;
245       additional_records[i].data.raw.data_len = rd[i].data_size;
246       additional_records[i].data.raw.data = (char*)rd[i].data;
247       additional_records[i].expiration_time = rd[i].expiration;
248       additional_records[i].class = GNUNET_DNSPARSER_CLASS_INTERNET;//hmmn
249     }
250   }
251   
252   packet->num_answers = rh->answered;
253   packet->num_additional_records = rd_count-(rh->answered);
254   
255   if (0 == GNUNET_CRYPTO_hash_cmp(&rh->authority, &zone_hash))
256     packet->flags.authoritative_answer = 1;
257   else
258     packet->flags.authoritative_answer = 0;
259
260   if (rd == NULL)
261     packet->flags.return_code = GNUNET_DNSPARSER_RETURN_CODE_NAME_ERROR;
262   else
263     packet->flags.return_code = GNUNET_DNSPARSER_RETURN_CODE_NO_ERROR;
264   
265   packet->flags.query_or_response = 1;
266
267   
268   /**
269    * Reply to DNS
270    */
271   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
272              "Building DNS response\n");
273   ret = GNUNET_DNSPARSER_pack (packet,
274                                1024, /* FIXME magic from dns redirector */
275                                &buf,
276                                &len);
277   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
278              "Built DNS response! (ret=%d,len=%d)\n", ret, len);
279   if (ret == GNUNET_OK)
280   {
281     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
282                "Answering DNS request\n");
283     GNUNET_DNS_request_answer(rh->request_handle,
284                               len,
285                               buf);
286     //GNUNET_free(answer);
287     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Answered DNS request\n");
288   }
289   else
290   {
291     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
292                "Error building DNS response! (ret=%d)", ret);
293   }
294
295   GNUNET_free(rh->name);
296   GNUNET_free(rh);
297 }
298
299
300 /**
301  * Task run during shutdown.
302  *
303  * @param cls unused
304  * @param tc unused
305  */
306 static void
307 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
308 {
309   /* Kill zone task for it may make the scheduler hang */
310   if (zone_update_taskid)
311     GNUNET_SCHEDULER_cancel(zone_update_taskid);
312
313   GNUNET_DNS_disconnect(dns_handle);
314   GNUNET_NAMESTORE_disconnect(namestore_handle, 1);
315   GNUNET_DHT_disconnect(dht_handle);
316 }
317
318 /**
319  * Callback when record data is put into namestore
320  *
321  * @param cls the closure
322  * @param success GNUNET_OK on success
323  * @param emsg the error message. NULL if SUCCESS==GNUNET_OK
324  */
325 void
326 on_namestore_record_put_result(void *cls,
327                                int32_t success,
328                                const char *emsg)
329 {
330   if (GNUNET_NO == success)
331   {
332     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "records already in namestore\n");
333     return;
334   }
335   else if (GNUNET_YES == success)
336   {
337     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
338                "records successfully put in namestore\n");
339     return;
340   }
341
342   GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
343              "Error putting records into namestore: %s\n", emsg);
344 }
345
346 /**
347  * Handle timeout for DHT requests
348  *
349  * @param cls the request handle as closure
350  * @param tc the task context
351  */
352 static void
353 dht_lookup_timeout(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
354 {
355   struct GNUNET_GNS_ResolverHandle *rh = cls;
356
357   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
358              "dht lookup for query %s (type=%d) timed out.\n",
359              rh->name, rh->query->type);
360
361   GNUNET_DHT_get_stop (rh->get_handle);
362   rh->proc(rh->proc_cls, rh, 0, NULL);
363 }
364
365
366
367 /**
368  * Function called when we get a result from the dht
369  * for our query
370  *
371  * @param cls the request handle
372  * @param exp lifetime
373  * @param key the key the record was stored under
374  * @param get_path get path
375  * @param get_path_length get path length
376  * @param put_path put path
377  * @param put_path_length put path length
378  * @param type the block type
379  * @param size the size of the record
380  * @param data the record data
381  */
382 static void
383 process_record_dht_result(void* cls,
384                  struct GNUNET_TIME_Absolute exp,
385                  const GNUNET_HashCode * key,
386                  const struct GNUNET_PeerIdentity *get_path,
387                  unsigned int get_path_length,
388                  const struct GNUNET_PeerIdentity *put_path,
389                  unsigned int put_path_length,
390                  enum GNUNET_BLOCK_Type type,
391                  size_t size, const void *data)
392 {
393   struct GNUNET_GNS_ResolverHandle *rh;
394   struct GNSNameRecordBlock *nrb;
395   uint32_t num_records;
396   char* name = NULL;
397   char* rd_data = (char*)data;
398   int i;
399   int rd_size;
400   
401   GNUNET_HashCode zone, name_hash;
402   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "got dht result (size=%d)\n", size);
403   
404   if (data == NULL)
405     return;
406
407   //FIXME maybe check expiration here, check block type
408   
409   rh = (struct GNUNET_GNS_ResolverHandle *)cls;
410   nrb = (struct GNSNameRecordBlock*)data;
411   
412   /* stop lookup and timeout task */
413   GNUNET_DHT_get_stop (rh->get_handle);
414   GNUNET_SCHEDULER_cancel(rh->dht_timeout_task);
415   
416   rh->get_handle = NULL;
417   name = (char*)&nrb[1];
418   num_records = ntohl(nrb->rd_count);
419   {
420     struct GNUNET_NAMESTORE_RecordData rd[num_records];
421
422     rd_data += strlen(name) + 1 + sizeof(struct GNSNameRecordBlock);
423     rd_size = size - strlen(name) - 1 - sizeof(struct GNSNameRecordBlock);
424   
425     if (GNUNET_SYSERR == GNUNET_NAMESTORE_records_deserialize (rd_size,
426                                                                rd_data,
427                                                                num_records,
428                                                                rd))
429     {
430       GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Error deserializing data!\n");
431       return;
432     }
433
434     for (i=0; i<num_records; i++)
435     {
436       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
437                "Got name: %s (wanted %s)\n", name, rh->name);
438       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
439                "Got type: %d (wanted %d)\n",
440                rd[i].record_type, rh->query->type);
441       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
442                "Got data length: %d\n", rd[i].data_size);
443       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
444                "Got flag %d\n", rd[i].flags);
445     
446      if ((strcmp(name, rh->name) == 0) &&
447          (rd[i].record_type == rh->query->type))
448       {
449         rh->answered++;
450       }
451
452     }
453
454     GNUNET_CRYPTO_hash(name, strlen(name), &name_hash);
455     GNUNET_CRYPTO_hash_xor(key, &name_hash, &zone);
456   
457     /**
458      * FIXME check pubkey against existing key in namestore?
459      * https://gnunet.org/bugs/view.php?id=2179
460      */
461
462     /* Save to namestore */
463     GNUNET_NAMESTORE_record_put (namestore_handle,
464                                  &nrb->public_key,
465                                  name,
466                                  exp,
467                                  num_records,
468                                  rd,
469                                  &nrb->signature,
470                                  &on_namestore_record_put_result, //cont
471                                  NULL); //cls
472   
473     if (rh->answered)
474       rh->proc(rh->proc_cls, rh, num_records, rd);
475     else
476       rh->proc(rh->proc_cls, rh, 0, NULL);
477   }
478
479 }
480
481
482 /**
483  * Start DHT lookup for a (name -> query->record_type) record in
484  * rh->authority's zone
485  *
486  * @param rh the pending gns query context
487  * @param name the name to query record
488  */
489 static void
490 resolve_record_from_dht(struct GNUNET_GNS_ResolverHandle *rh)
491 {
492   uint32_t xquery;
493   GNUNET_HashCode name_hash;
494   GNUNET_HashCode lookup_key;
495   struct GNUNET_CRYPTO_HashAsciiEncoded lookup_key_string;
496
497   GNUNET_CRYPTO_hash(rh->name, strlen(rh->name), &name_hash);
498   GNUNET_CRYPTO_hash_xor(&name_hash, &rh->authority, &lookup_key);
499   GNUNET_CRYPTO_hash_to_enc (&lookup_key, &lookup_key_string);
500   
501   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
502              "starting dht lookup for %s with key: %s\n",
503              rh->name, (char*)&lookup_key_string);
504
505   rh->dht_timeout_task = GNUNET_SCHEDULER_add_delayed(DHT_LOOKUP_TIMEOUT,
506                                                       &dht_lookup_timeout, rh);
507
508   xquery = htonl(rh->query->type);
509   rh->get_handle = GNUNET_DHT_get_start(dht_handle, 
510                        DHT_OPERATION_TIMEOUT,
511                        GNUNET_BLOCK_TYPE_GNS_NAMERECORD,
512                        &lookup_key,
513                        DHT_GNS_REPLICATION_LEVEL,
514                        GNUNET_DHT_RO_NONE,
515                        &xquery, 
516                        sizeof(xquery),
517                        &process_record_dht_result,
518                        rh);
519
520 }
521
522
523 /**
524  * Namestore calls this function if we have record for this name.
525  * (or with rd_count=0 to indicate no matches)
526  *
527  * @param cls the pending query
528  * @param key the key of the zone we did the lookup
529  * @param expiration expiration date of the namestore entry
530  * @param name the name for which we need an authority
531  * @param rd_count the number of records with 'name'
532  * @param rd the record data
533  * @param signature the signature of the authority for the record data
534  */
535 static void
536 process_record_lookup_ns(void* cls,
537                   const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
538                   struct GNUNET_TIME_Absolute expiration,
539                   const char *name, unsigned int rd_count,
540                   const struct GNUNET_NAMESTORE_RecordData *rd,
541                   const struct GNUNET_CRYPTO_RsaSignature *signature)
542 {
543   struct GNUNET_GNS_ResolverHandle *rh;
544   struct GNUNET_TIME_Relative remaining_time;
545   GNUNET_HashCode zone;
546
547   rh = (struct GNUNET_GNS_ResolverHandle *) cls;
548   GNUNET_CRYPTO_hash(key,
549                      sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
550                      &zone);
551   remaining_time = GNUNET_TIME_absolute_get_remaining (expiration);
552
553   rh->status = 0;
554   
555   if (name != NULL)
556   {
557     rh->status |= EXISTS;
558   }
559   
560   if (remaining_time.rel_value == 0)
561   {
562     rh->status |= EXPIRED;
563   }
564   
565   if (rd_count == 0)
566   {
567     /**
568      * Lookup terminated and no results
569      */
570     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
571                "Namestore lookup for %s terminated without results\n", name);
572     
573     
574
575     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
576                "Record %s unknown in namestore\n",
577                rh->name);
578     /**
579      * Our zone and no result? Cannot resolve TT
580      */
581     rh->proc(rh->proc_cls, rh, 0, NULL);
582     return;
583
584   }
585   else
586   {
587     
588     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
589                "Processing additional result %s from namestore\n", name);
590     int i;
591     for (i=0; i<rd_count;i++)
592     {
593       
594       if (rd[i].record_type != rh->query->type)
595         continue;
596       
597       if ((GNUNET_TIME_absolute_get_remaining (rd[i].expiration)).rel_value
598           == 0)
599       {
600         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "This record is expired. Skipping\n");
601         continue;
602       }
603       
604       rh->answered++;
605       
606     }
607     
608     /**
609      * no answers found
610      */
611     if (rh->answered == 0)
612     {
613       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, 
614                  "No answers found. This is odd!\n");
615       rh->proc(rh->proc_cls, rh, 0, NULL);
616       return;
617     }
618     
619     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Found %d answer(s) to query!\n",
620                rh->answered);
621
622     rh->proc(rh->proc_cls, rh, rd_count, rd);
623   }
624 }
625
626 /**
627  * The final phase of resolution.
628  * This is a name that is canonical and we do not have a delegation.
629  *
630  * @param rh the pending lookup
631  */
632 static void
633 resolve_record_from_ns(struct GNUNET_GNS_ResolverHandle *rh)
634 {
635   
636   /**
637    * Try to resolve this record in our namestore.
638    * The name to resolve is now in rh->authority_name
639    * since we tried to resolve it to an authority
640    * and failed.
641    **/
642   GNUNET_NAMESTORE_lookup_record(namestore_handle,
643                                  &rh->authority,
644                                  rh->name,
645                                  rh->query->type,
646                                  &process_record_lookup_ns,
647                                  rh);
648
649 }
650
651
652 /**
653  * Handle timeout for DHT requests
654  *
655  * @param cls the request handle as closure
656  * @param tc the task context
657  */
658 static void
659 dht_authority_lookup_timeout(void *cls,
660                              const struct GNUNET_SCHEDULER_TaskContext *tc)
661 {
662   struct GNUNET_GNS_ResolverHandle *rh = cls;
663
664   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
665              "dht lookup for query %s (type=%d) timed out.\n",
666              rh->name, rh->query->type);
667
668   GNUNET_DHT_get_stop (rh->get_handle);
669   if (strcmp(rh->name, "") == 0)
670   {
671     /*
672      * promote authority back to name and try to resolve record
673      */
674     strcpy(rh->name, rh->authority_name);
675   }
676   rh->proc(rh->proc_cls, rh, 0, NULL);
677 }
678
679 // Prototype
680 static void resolve_delegation_from_dht(struct GNUNET_GNS_ResolverHandle *rh);
681
682 /**
683  * Function called when we get a result from the dht
684  * for our query. Recursively tries to resolve PKEYs
685  * for name in DHT.
686  *
687  * @param cls the request handle
688  * @param exp lifetime
689  * @param key the key the record was stored under
690  * @param get_path get path
691  * @param get_path_length get path length
692  * @param put_path put path
693  * @param put_path_length put path length
694  * @param type the block type
695  * @param size the size of the record
696  * @param data the record data
697  */
698 static void
699 process_authority_dht_result(void* cls,
700                  struct GNUNET_TIME_Absolute exp,
701                  const GNUNET_HashCode * key,
702                  const struct GNUNET_PeerIdentity *get_path,
703                  unsigned int get_path_length,
704                  const struct GNUNET_PeerIdentity *put_path,
705                  unsigned int put_path_length,
706                  enum GNUNET_BLOCK_Type type,
707                  size_t size, const void *data)
708 {
709   struct GNUNET_GNS_ResolverHandle *rh;
710   struct GNSNameRecordBlock *nrb;
711   uint32_t num_records;
712   char* name = NULL;
713   char* rd_data = (char*) data;
714   int i;
715   int rd_size;
716   GNUNET_HashCode zone, name_hash;
717   
718   if (data == NULL)
719     return;
720   
721   //FIXME check expiration?
722   
723   rh = (struct GNUNET_GNS_ResolverHandle *)cls;
724   nrb = (struct GNSNameRecordBlock*)data;
725   
726   /* stop dht lookup and timeout task */
727   GNUNET_DHT_get_stop (rh->get_handle);
728   GNUNET_SCHEDULER_cancel(rh->dht_timeout_task);
729
730   rh->get_handle = NULL;
731   num_records = ntohl(nrb->rd_count);
732   name = (char*)&nrb[1];
733   {
734     struct GNUNET_NAMESTORE_RecordData rd[num_records];
735     
736     rd_data += strlen(name) + 1 + sizeof(struct GNSNameRecordBlock);
737     rd_size = size - strlen(name) - 1 - sizeof(struct GNSNameRecordBlock);
738   
739     if (GNUNET_SYSERR == GNUNET_NAMESTORE_records_deserialize (rd_size,
740                                                                rd_data,
741                                                                num_records,
742                                                                rd))
743     {
744       GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Error deserializing data!\n");
745       return;
746     }
747
748     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
749                "Got name: %s (wanted %s)\n", name, rh->authority_name);
750     for (i=0; i<num_records; i++)
751     {
752     
753       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
754                 "Got name: %s (wanted %s)\n", name, rh->authority_name);
755       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
756                  "Got type: %d (wanted %d)\n",
757                  rd[i].record_type, GNUNET_GNS_RECORD_PKEY);
758       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
759                  "Got data length: %d\n", rd[i].data_size);
760       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
761                  "Got flag %d\n", rd[i].flags);
762
763       if ((strcmp(name, rh->authority_name) == 0) &&
764           (rd[i].record_type == GNUNET_GNS_RECORD_PKEY))
765       {
766         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Authority found in DHT\n");
767         rh->answered = 1;
768         memcpy(&rh->authority, rd[i].data, sizeof(GNUNET_HashCode));
769         struct AuthorityChain *auth =
770           GNUNET_malloc(sizeof(struct AuthorityChain));
771         auth->zone = rh->authority;
772         GNUNET_CONTAINER_DLL_insert (rh->authority_chain_head,
773                                      rh->authority_chain_tail,
774                                      auth);
775       }
776
777     }
778
779
780     GNUNET_CRYPTO_hash(name, strlen(name), &name_hash);
781     GNUNET_CRYPTO_hash_xor(key, &name_hash, &zone);
782
783     /* Save to namestore */
784     if (0 != GNUNET_CRYPTO_hash_cmp(&zone_hash, &zone))
785     {
786       GNUNET_NAMESTORE_record_put (namestore_handle,
787                                  &nrb->public_key,
788                                  name,
789                                  exp,
790                                  num_records,
791                                  rd,
792                                  &nrb->signature,
793                                  &on_namestore_record_put_result, //cont
794                                  NULL); //cls
795     }
796   }
797   
798   if (rh->answered)
799   {
800     rh->answered = 0;
801     /* delegate */
802     if (strcmp(rh->name, "") == 0)
803       rh->proc(rh->proc_cls, rh, 0, NULL);
804     else
805       resolve_delegation_from_dht(rh);
806     return;
807   }
808
809   /**
810    * should never get here unless false dht key/put
811    * block plugin should handle this
812    **/
813   
814   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "DHT authority lookup error!\n");
815   GNUNET_break(0);
816 }
817
818
819 /**
820  * Process DHT lookup result for record.
821  *
822  * @param cls the closure
823  * @param rh resolver handle
824  * @param rd_count number of results (always 0)
825  * @param rd record data (always NULL)
826  */
827 static void
828 process_record_result_dht(void* cls, struct GNUNET_GNS_ResolverHandle *rh,
829                        unsigned int rd_count,
830                        const struct GNUNET_NAMESTORE_RecordData *rd)
831 {
832   if (rd_count == 0)
833   {
834     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
835                "No records for %s found in DHT. Aborting\n",
836                rh->name);
837     /* give up, cannot resolve */
838     reply_to_dns(NULL, rh, 0, NULL);
839     return;
840   }
841
842   /* results found yay */
843   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
844              "Record resolved from namestore!");
845   reply_to_dns(NULL, rh, rd_count, rd);
846
847 }
848
849
850 /**
851  * Process namestore lookup result for record.
852  *
853  * @param cls the closure
854  * @param rh resolver handle
855  * @param rd_count number of results (always 0)
856  * @param rd record data (always NULL)
857  */
858 static void
859 process_record_result_ns(void* cls, struct GNUNET_GNS_ResolverHandle *rh,
860                        unsigned int rd_count,
861                        const struct GNUNET_NAMESTORE_RecordData *rd)
862 {
863   if (rd_count == 0)
864   {
865     /* ns entry expired. try dht */
866     if (rh->status & (EXPIRED | !EXISTS))
867     {
868       rh->proc = &process_record_result_dht;
869       resolve_record_from_dht(rh);
870       return;
871     }
872     /* give up, cannot resolve */
873     reply_to_dns(NULL, rh, 0, NULL);
874     return;
875   }
876
877   /* results found yay */
878   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
879              "Record resolved from namestore!");
880   reply_to_dns(NULL, rh, rd_count, rd);
881
882 }
883
884
885 /**
886  * Determine if this name is canonical.
887  * i.e.
888  * a.b.gnunet  = not canonical
889  * a           = canonical
890  *
891  * @param name the name to test
892  * @return 1 if canonical
893  */
894 static int
895 is_canonical(char* name)
896 {
897   uint32_t len = strlen(name);
898   int i;
899
900   for (i=0; i<len; i++)
901   {
902     if (*(name+i) == '.')
903       return 0;
904   }
905   return 1;
906 }
907
908 /**
909  * Move one level up in the domain hierarchy and return the
910  * passed top level domain.
911  *
912  * @param name the domain
913  * @param dest the destination where the tld will be put
914  */
915 void
916 pop_tld(char* name, char* dest)
917 {
918   uint32_t len;
919
920   if (is_canonical(name))
921   {
922     strcpy(dest, name);
923     strcpy(name, "");
924     return;
925   }
926
927   for (len = strlen(name); len > 0; len--)
928   {
929     if (*(name+len) == '.')
930       break;
931   }
932   
933   //Was canonical?
934   if (len == 0)
935     return;
936
937   name[len] = '\0';
938
939   strcpy(dest, (name+len+1));
940 }
941
942 /**
943  * DHT resolution for delegation finished. Processing result.
944  *
945  * @param cls the closure
946  * @param rh resolver handle
947  * @param rd_count number of results (always 0)
948  * @param rd record data (always NULL)
949  */
950 static void
951 process_dht_delegation_dns(void* cls, struct GNUNET_GNS_ResolverHandle *rh,
952                           unsigned int rd_count,
953                           const struct GNUNET_NAMESTORE_RecordData *rd)
954 {
955   if (strcmp(rh->name, "") == 0)
956   {
957     /* We resolved full name for delegation. resolving record */
958     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
959       "Resolved full name for delegation via DHT. resolving record '' in ns\n");
960     rh->proc = &process_record_result_ns;
961     resolve_record_from_ns(rh);
962     return;
963   }
964
965   /**
966    * we still have some left
967    **/
968   if (is_canonical(rh->name))
969   {
970     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
971                "Resolving canonical record %s in ns\n", rh->name);
972     rh->proc = &process_record_result_ns;
973     resolve_record_from_ns(rh);
974     return;
975   }
976   /* give up, cannot resolve */
977   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
978              "Cannot fully resolve delegation for %s via DHT!\n",
979              rh->name);
980   reply_to_dns(NULL, rh, 0, NULL);
981 }
982
983
984 /**
985  * Start DHT lookup for a name -> PKEY (compare NS) record in
986  * rh->authority's zone
987  *
988  * @param rh the pending gns query
989  * @param name the name of the PKEY record
990  */
991 static void
992 resolve_delegation_from_dht(struct GNUNET_GNS_ResolverHandle *rh)
993 {
994   uint32_t xquery;
995   GNUNET_HashCode name_hash;
996   GNUNET_HashCode lookup_key;
997
998   GNUNET_CRYPTO_hash(rh->authority_name,
999                      strlen(rh->authority_name),
1000                      &name_hash);
1001   GNUNET_CRYPTO_hash_xor(&name_hash, &rh->authority, &lookup_key);
1002
1003   rh->dht_timeout_task = GNUNET_SCHEDULER_add_delayed (DHT_LOOKUP_TIMEOUT,
1004                                                   &dht_authority_lookup_timeout,
1005                                                        rh);
1006
1007   xquery = htonl(GNUNET_GNS_RECORD_PKEY);
1008   
1009   rh->get_handle = GNUNET_DHT_get_start(dht_handle,
1010                        DHT_OPERATION_TIMEOUT,
1011                        GNUNET_BLOCK_TYPE_GNS_NAMERECORD,
1012                        &lookup_key,
1013                        DHT_GNS_REPLICATION_LEVEL,
1014                        GNUNET_DHT_RO_NONE,
1015                        &xquery,
1016                        sizeof(xquery),
1017                        &process_authority_dht_result,
1018                        rh);
1019
1020 }
1021
1022
1023 /**
1024  * Namestore resolution for delegation finished. Processing result.
1025  *
1026  * @param cls the closure
1027  * @param rh resolver handle
1028  * @param rd_count number of results (always 0)
1029  * @param rd record data (always NULL)
1030  */
1031 static void
1032 process_ns_delegation_dns(void* cls, struct GNUNET_GNS_ResolverHandle *rh,
1033                           unsigned int rd_count,
1034                           const struct GNUNET_NAMESTORE_RecordData *rd)
1035 {
1036   if (strcmp(rh->name, "") == 0)
1037   {
1038     /* We resolved full name for delegation. resolving record */
1039     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1040                "Resolved full name for delegation. resolving record ''\n");
1041     rh->proc = &process_record_result_ns;
1042     resolve_record_from_ns(rh);
1043     return;
1044   }
1045
1046   /**
1047    * we still have some left
1048    * check if ns entry is fresh
1049    **/
1050   if (rh->status & (EXISTS | !EXPIRED))
1051   {
1052     if (is_canonical(rh->name))
1053     {
1054       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1055                  "Resolving canonical record %s\n", rh->name);
1056       rh->proc = &process_record_result_ns;
1057       resolve_record_from_ns(rh);
1058     }
1059     else
1060     {
1061       /* give up, cannot resolve */
1062       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1063                  "Cannot fully resolve delegation for %s!\n",
1064                  rh->name);
1065       reply_to_dns(NULL, rh, 0, NULL);
1066     }
1067     return;
1068   }
1069   
1070   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1071              "Trying to resolve delegation for %s via DHT\n",
1072              rh->name);
1073   rh->proc = &process_dht_delegation_dns;
1074   resolve_delegation_from_dht(rh);
1075 }
1076
1077 //Prototype
1078 static void resolve_delegation_from_ns(struct GNUNET_GNS_ResolverHandle *rh);
1079
1080 /**
1081  * This is a callback function that should give us only PKEY
1082  * records. Used to query the namestore for the authority (PKEY)
1083  * for 'name'. It will recursively try to resolve the
1084  * authority for a given name from the namestore.
1085  *
1086  * @param cls the pending query
1087  * @param key the key of the zone we did the lookup
1088  * @param expiration expiration date of the record data set in the namestore
1089  * @param name the name for which we need an authority
1090  * @param rd_count the number of records with 'name'
1091  * @param rd the record data
1092  * @param signature the signature of the authority for the record data
1093  */
1094 static void
1095 process_authority_lookup_ns(void* cls,
1096                    const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
1097                    struct GNUNET_TIME_Absolute expiration,
1098                    const char *name,
1099                    unsigned int rd_count,
1100                    const struct GNUNET_NAMESTORE_RecordData *rd,
1101                    const struct GNUNET_CRYPTO_RsaSignature *signature)
1102 {
1103   struct GNUNET_GNS_ResolverHandle *rh;
1104   struct GNUNET_TIME_Relative remaining_time;
1105   GNUNET_HashCode zone;
1106   char* new_name;
1107   
1108   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Got %d records from authority lookup\n",
1109              rd_count);
1110
1111   rh = (struct GNUNET_GNS_ResolverHandle *)cls;
1112   GNUNET_CRYPTO_hash(key,
1113                      sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1114                      &zone);
1115   remaining_time = GNUNET_TIME_absolute_get_remaining (expiration);
1116   
1117   rh->status = 0;
1118   
1119   if (name != NULL)
1120   {
1121     rh->status |= EXISTS;
1122   }
1123   
1124   if (remaining_time.rel_value == 0)
1125   {
1126     rh->status |= EXPIRED;
1127   }
1128   
1129   /**
1130    * No authority found in namestore.
1131    */
1132   if (rd_count == 0)
1133   {
1134     /**
1135      * We did not find an authority in the namestore
1136      */
1137     
1138     /**
1139      * No PKEY in zone.
1140      * Promote this authority back to a name maybe it is
1141      * our record.
1142      */
1143     if (strcmp(rh->name, "") == 0)
1144     {
1145       /* simply promote back */
1146       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1147                  "Promoting %s back to name\n", rh->authority_name);
1148       strcpy(rh->name, rh->authority_name);
1149     }
1150     else
1151     {
1152       /* add back to existing name */
1153       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1154                  "Adding %s back to %s\n",
1155                  rh->authority_name, rh->name);
1156       new_name = GNUNET_malloc(strlen(rh->name)
1157                                + strlen(rh->authority_name) + 2);
1158       memset(new_name, 0, strlen(rh->name) + strlen(rh->authority_name) + 2);
1159       strcpy(new_name, rh->name);
1160       strcpy(new_name+strlen(new_name)+1, ".");
1161       strcpy(new_name+strlen(new_name)+2, rh->authority_name);
1162       GNUNET_free(rh->name);
1163       rh->name = new_name;
1164     }
1165     rh->proc(rh->proc_cls, rh, 0, NULL);
1166     return;
1167   }
1168
1169   //Note only 1 pkey should have been returned.. anything else would be strange
1170   /**
1171    * We found an authority that may be able to help us
1172    * move on with query
1173    */
1174   int i;
1175   for (i=0; i<rd_count;i++)
1176   {
1177   
1178     if (rd[i].record_type != GNUNET_GNS_RECORD_PKEY)
1179       continue;
1180     
1181     if ((GNUNET_TIME_absolute_get_remaining (rd[i].expiration)).rel_value
1182          == 0)
1183     {
1184       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "This pkey is expired.\n");
1185       if (remaining_time.rel_value == 0)
1186       {
1187         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1188                    "This dht entry is expired.\n");
1189         rh->authority_chain_head->fresh = 0;
1190         rh->proc(rh->proc_cls, rh, 0, NULL);
1191         return;
1192       }
1193
1194       continue;
1195     }
1196
1197     /**
1198      * Resolve rest of query with new authority
1199      */
1200     GNUNET_assert(rd[i].record_type == GNUNET_GNS_RECORD_PKEY);
1201     memcpy(&rh->authority, rd[i].data, sizeof(GNUNET_HashCode));
1202     struct AuthorityChain *auth = GNUNET_malloc(sizeof(struct AuthorityChain));
1203     auth->zone = rh->authority;
1204     GNUNET_CONTAINER_DLL_insert (rh->authority_chain_head,
1205                                  rh->authority_chain_tail,
1206                                  auth);
1207     
1208     /**
1209      * We are done with PKEY resolution if name is empty
1210      * else resolve again with new authority
1211      */
1212     if (strcmp(rh->name, "") == 0)
1213       rh->proc(rh->proc_cls, rh, 0, NULL);
1214     else
1215       resolve_delegation_from_ns(rh);
1216     return;
1217   }
1218     
1219   /**
1220    * no answers found
1221    */
1222   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1223              "Authority lookup successful but no PKEY... never get here\n");
1224   rh->proc(rh->proc_cls, rh, 0, NULL);
1225 }
1226
1227
1228 /**
1229  * Resolve the delegation chain for the request
1230  *
1231  * @param rh the resolver handle
1232  */
1233 static void
1234 resolve_delegation_from_ns(struct GNUNET_GNS_ResolverHandle *rh)
1235 {
1236   
1237   pop_tld(rh->name, rh->authority_name);
1238   GNUNET_NAMESTORE_lookup_record(namestore_handle,
1239                                  &rh->authority,
1240                                  rh->authority_name,
1241                                  GNUNET_GNS_RECORD_PKEY,
1242                                  &process_authority_lookup_ns,
1243                                  rh);
1244
1245 }
1246
1247 /**
1248  * Entry point for name resolution
1249  * Setup a new query and try to resolve
1250  *
1251  * @param request the request handle of the DNS request from a client
1252  * @param p the DNS query packet we received
1253  * @param q the DNS query we received parsed from p
1254  */
1255 static void
1256 start_resolution_from_dns(struct GNUNET_DNS_RequestHandle *request,
1257                           struct GNUNET_DNSPARSER_Packet *p,
1258                           struct GNUNET_DNSPARSER_Query *q)
1259 {
1260   struct GNUNET_GNS_ResolverHandle *rh;
1261   
1262   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1263               "Starting resolution for %s (type=%d)!\n",
1264               q->name, q->type);
1265   
1266   rh = GNUNET_malloc(sizeof (struct GNUNET_GNS_ResolverHandle));
1267   rh->packet = p;
1268   rh->query = q;
1269   rh->authority = zone_hash;
1270   
1271   
1272   rh->name = GNUNET_malloc(strlen(q->name)
1273                               - strlen(gnunet_tld) + 1);
1274   memset(rh->name, 0,
1275          strlen(q->name)-strlen(gnunet_tld) + 1);
1276   memcpy(rh->name, q->name,
1277          strlen(q->name)-strlen(gnunet_tld));
1278
1279   rh->authority_name = GNUNET_malloc(sizeof(char)*MAX_DNS_LABEL_LENGTH);
1280
1281   rh->request_handle = request;
1282
1283   rh->authority_chain_head = GNUNET_malloc(sizeof(struct AuthorityChain));
1284   rh->authority_chain_tail = rh->authority_chain_head;
1285   rh->authority_chain_head->zone = zone_hash;
1286
1287   /* Start resolution in our zone */
1288   rh->proc = &process_ns_delegation_dns;
1289   resolve_delegation_from_ns(rh);
1290 }
1291
1292 /**
1293  * The DNS request handler
1294  * Called for every incoming DNS request.
1295  *
1296  * @param cls closure
1297  * @param rh request handle to user for reply
1298  * @param request_length number of bytes in request
1299  * @param request udp payload of the DNS request
1300  */
1301 static void
1302 handle_dns_request(void *cls,
1303                    struct GNUNET_DNS_RequestHandle *rh,
1304                    size_t request_length,
1305                    const char *request)
1306 {
1307   struct GNUNET_DNSPARSER_Packet *p;
1308   char *tldoffset;
1309
1310   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Hijacked a DNS request...processing\n");
1311   p = GNUNET_DNSPARSER_parse (request, request_length);
1312   
1313   if (NULL == p)
1314   {
1315     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1316                 "Received malformed DNS packet, leaving it untouched\n");
1317     GNUNET_DNS_request_forward (rh);
1318     return;
1319   }
1320   
1321   /**
1322    * Check tld and decide if we or
1323    * legacy dns is responsible
1324    *
1325    * FIXME now in theory there could be more than 1 query in the request
1326    * but if this is case we get into trouble:
1327    * either we query the GNS or the DNS. We cannot do both!
1328    * So I suggest to either only allow a single query per request or
1329    * only allow GNS or DNS requests.
1330    * The way it is implemented here now is buggy and will lead to erratic
1331    * behaviour (if multiple queries are present).
1332    */
1333   if (p->num_queries == 0)
1334   {
1335     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1336                 "No Queries in DNS packet... forwarding\n");
1337     GNUNET_DNS_request_forward (rh);
1338   }
1339
1340   if (p->num_queries > 1)
1341   {
1342     /* Note: We could also look for .gnunet */
1343     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1344                 ">1 queriy in DNS packet... odd. We only process #1\n");
1345   }
1346
1347   
1348   /**
1349    * Check for .gnunet
1350    */
1351   tldoffset = p->queries[0].name + strlen(p->queries[0].name);
1352
1353   while ((*tldoffset) != '.')
1354     tldoffset--;
1355   
1356   if (0 == strcmp(tldoffset, gnunet_tld))
1357   {
1358     start_resolution_from_dns(rh, p, p->queries);
1359   }
1360   else
1361   {
1362     /**
1363      * This request does not concern us. Forward to real DNS.
1364      */
1365     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1366                "Request for %s is forwarded to DNS\n", p->queries[0].name);
1367     GNUNET_DNS_request_forward (rh);
1368   }
1369
1370 }
1371
1372 /**
1373  * Method called periodicattluy that triggers
1374  * iteration over root zone
1375  *
1376  * @param cls closure
1377  * @param tc task context
1378  */
1379 static void
1380 update_zone_dht_next(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1381 {
1382   GNUNET_NAMESTORE_zone_iterator_next(namestore_iter);
1383 }
1384
1385 /**
1386  * Continuation for DHT put
1387  *
1388  * @param cls closure
1389  * @param tc task context
1390  */
1391 static void
1392 record_dht_put(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1393 {
1394   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "put request transmitted\n");
1395 }
1396
1397 /* prototype */
1398 static void
1399 update_zone_dht_start(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1400
1401 /**
1402  * Function used to put all records successively into the DHT.
1403  *
1404  * @param cls the closure (NULL)
1405  * @param key the public key of the authority (ours)
1406  * @param expiration lifetime of the namestore entry
1407  * @param name the name of the records
1408  * @param rd_count the number of records in data
1409  * @param rd the record data
1410  * @param signature the signature for the record data
1411  */
1412 static void
1413 put_gns_record(void *cls,
1414                 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
1415                 struct GNUNET_TIME_Absolute expiration,
1416                 const char *name,
1417                 unsigned int rd_count,
1418                 const struct GNUNET_NAMESTORE_RecordData *rd,
1419                 const struct GNUNET_CRYPTO_RsaSignature *signature)
1420 {
1421   
1422   struct GNSNameRecordBlock *nrb;
1423   GNUNET_HashCode name_hash;
1424   GNUNET_HashCode xor_hash;
1425   struct GNUNET_CRYPTO_HashAsciiEncoded xor_hash_string;
1426   uint32_t rd_payload_length;
1427   char* nrb_data = NULL;
1428
1429   /* we're done */
1430   if (NULL == name)
1431   {
1432     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Zone iteration finished\n");
1433     GNUNET_NAMESTORE_zone_iteration_stop (namestore_iter);
1434     zone_update_taskid = GNUNET_SCHEDULER_add_now (&update_zone_dht_start,
1435                                                    NULL);
1436     return;
1437   }
1438   
1439   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1440              "Putting records for %s into the DHT\n", name);
1441   
1442   rd_payload_length = GNUNET_NAMESTORE_records_get_size (rd_count, rd);
1443   
1444   nrb = GNUNET_malloc(rd_payload_length + strlen(name) + 1 
1445                       + sizeof(struct GNSNameRecordBlock));
1446   
1447   if (signature != NULL)
1448     nrb->signature = *signature;
1449   
1450   nrb->public_key = *key;
1451
1452   nrb->rd_count = htonl(rd_count);
1453   
1454   memset(&nrb[1], 0, strlen(name) + 1);
1455   memcpy(&nrb[1], name, strlen(name));
1456
1457   nrb_data = (char*)&nrb[1];
1458   nrb_data += strlen(name) + 1;
1459
1460   rd_payload_length += sizeof(struct GNSNameRecordBlock) +
1461     strlen(name) + 1;
1462
1463   if (-1 == GNUNET_NAMESTORE_records_serialize (rd_count,
1464                                                 rd,
1465                                                 rd_payload_length,
1466                                                 nrb_data))
1467   {
1468     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Record serialization failed!\n");
1469     return;
1470     //FIXME what to do
1471   }
1472
1473
1474   /*
1475    * calculate DHT key: H(name) xor H(pubkey)
1476    */
1477   GNUNET_CRYPTO_hash(name, strlen(name), &name_hash);
1478   GNUNET_CRYPTO_hash_xor(&zone_hash, &name_hash, &xor_hash);
1479   GNUNET_CRYPTO_hash_to_enc (&xor_hash, &xor_hash_string);
1480   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1481              "putting records for %s under key: %s with size %d\n",
1482              name, (char*)&xor_hash_string, rd_payload_length);
1483
1484   GNUNET_DHT_put (dht_handle, &xor_hash,
1485                   DHT_GNS_REPLICATION_LEVEL,
1486                   GNUNET_DHT_RO_NONE,
1487                   GNUNET_BLOCK_TYPE_GNS_NAMERECORD,
1488                   rd_payload_length,
1489                   (char*)nrb,
1490                   expiration,
1491                   DHT_OPERATION_TIMEOUT,
1492                   &record_dht_put,
1493                   NULL); //cls for cont
1494   
1495   num_public_records++;
1496
1497   /**
1498    * Reschedule periodic put
1499    */
1500   zone_update_taskid = GNUNET_SCHEDULER_add_delayed (dht_update_interval,
1501                                 &update_zone_dht_next,
1502                                 NULL);
1503
1504 }
1505
1506 /**
1507  * Periodically iterate over our zone and store everything in dht
1508  *
1509  * @param cls NULL
1510  * @param tc task context
1511  */
1512 static void
1513 update_zone_dht_start(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1514 {
1515   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Starting DHT zone update!\n");
1516   if (0 == num_public_records)
1517   {
1518     dht_update_interval = GNUNET_TIME_relative_multiply(
1519                                                       GNUNET_TIME_UNIT_SECONDS,
1520                                                       1);
1521   }
1522   else
1523   {
1524     dht_update_interval = GNUNET_TIME_relative_multiply(
1525                                                       GNUNET_TIME_UNIT_SECONDS,
1526                                                      (3600/num_public_records));
1527   }
1528   num_public_records = 0; //start counting again
1529   namestore_iter = GNUNET_NAMESTORE_zone_iteration_start (namestore_handle,
1530                                                           &zone_hash,
1531                                                           GNUNET_NAMESTORE_RF_AUTHORITY,
1532                                                           GNUNET_NAMESTORE_RF_PRIVATE,
1533                                                           &put_gns_record,
1534                                                           NULL);
1535 }
1536
1537 //Prototype
1538 static void send_shorten_response(const char* name,
1539                                   struct ClientShortenHandle *csh);
1540 static void
1541 process_shorten_pseu_lookup_ns(void *cls,
1542                  const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *zone_key,
1543                  struct GNUNET_TIME_Absolute expire,
1544                  const char *name,
1545                  unsigned int rd_len,
1546                  const struct GNUNET_NAMESTORE_RecordData *rd,
1547                  const struct GNUNET_CRYPTO_RsaSignature *signature)
1548 {
1549   struct GNUNET_GNS_ResolverHandle *rh = 
1550     (struct GNUNET_GNS_ResolverHandle *)cls;
1551   struct GNUNET_TIME_Relative remaining_time;
1552
1553   
1554   rh->status = 0;
1555   
1556   if (name != NULL)
1557   {
1558     rh->status |= EXISTS;
1559   }
1560   
1561   if (remaining_time.rel_value == 0)
1562   {
1563     rh->status |= EXPIRED;
1564   }
1565
1566   rh->proc(cls, rh, rd_len, rd);
1567 }
1568
1569
1570 /**
1571  * Start DHT lookup for a PSEUdonym record in
1572  * rh->authority's zone
1573  *
1574  * @param rh the pending gns query
1575  * @param name the name of the PKEY record
1576  */
1577 static void
1578 resolve_pseu_from_dht(struct GNUNET_GNS_ResolverHandle *rh)
1579 {
1580   uint32_t xquery;
1581   GNUNET_HashCode name_hash;
1582   GNUNET_HashCode lookup_key;
1583
1584   //Empty string
1585   GNUNET_CRYPTO_hash("",
1586                      1,
1587                      &name_hash);
1588
1589   GNUNET_CRYPTO_hash_xor(&name_hash, &rh->authority, &lookup_key);
1590
1591   rh->dht_timeout_task = GNUNET_SCHEDULER_add_delayed (DHT_LOOKUP_TIMEOUT,
1592                                                   &dht_lookup_timeout,
1593                                                   rh);
1594
1595   xquery = htonl(GNUNET_GNS_RECORD_PSEU);
1596   
1597   rh->get_handle = GNUNET_DHT_get_start(dht_handle,
1598                        DHT_OPERATION_TIMEOUT,
1599                        GNUNET_BLOCK_TYPE_GNS_NAMERECORD,
1600                        &lookup_key,
1601                        DHT_GNS_REPLICATION_LEVEL,
1602                        GNUNET_DHT_RO_NONE,
1603                        &xquery,
1604                        sizeof(xquery),
1605                        &process_authority_dht_result,
1606                        rh);
1607
1608 }
1609
1610 //Prototype
1611 static void
1612 handle_shorten_pseu_ns_result(void* cls,
1613                               struct GNUNET_GNS_ResolverHandle *rh,
1614                               uint32_t rd_count,
1615                               const struct GNUNET_NAMESTORE_RecordData *rd);
1616
1617 static void
1618 handle_shorten_zone_to_name(void *cls,
1619                  const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *zone_key,
1620                  struct GNUNET_TIME_Absolute expire,
1621                  const char *name,
1622                  unsigned int rd_len,
1623                  const struct GNUNET_NAMESTORE_RecordData *rd,
1624                  const struct GNUNET_CRYPTO_RsaSignature *signature)
1625 {
1626   struct GNUNET_GNS_ResolverHandle *rh = 
1627     (struct GNUNET_GNS_ResolverHandle *)cls;
1628   struct ClientShortenHandle* csh = (struct ClientShortenHandle*) rh->proc_cls;
1629
1630   char* result;
1631   
1632   /* we found a match in our own zone */
1633   if (rd_len != 0)
1634   {
1635     result = GNUNET_malloc(strlen(rh->name) + strlen(name) + 1);
1636     memset(result, 0, strlen(rh->name) + strlen(name) + 1);
1637     memcpy(result, rh->name, strlen(rh->name));
1638     memcpy(result+strlen(rh->name)+1, name, strlen(name));
1639
1640     send_shorten_response(result, csh);
1641
1642     GNUNET_free(result);
1643   }
1644   else
1645   {
1646     /**
1647      * Nothing in our zone
1648      * check PSEU for this authority in namestore
1649      */
1650     rh->proc = &handle_shorten_pseu_ns_result;
1651     GNUNET_NAMESTORE_lookup_record(namestore_handle,
1652                                    &rh->authority_chain_head->zone,
1653                                    "",
1654                                    GNUNET_GNS_RECORD_PSEU,
1655                                    &process_shorten_pseu_lookup_ns,
1656                                    rh);
1657   }
1658 }
1659
1660 /**
1661  * Process result from namestore delegation lookup
1662  * for shorten operation
1663  *
1664  * @param cls the client shorten handle
1665  * @param rh the resolver handle
1666  * @param rd_count number of results (0)
1667  * @param rd data (NULL)
1668  */
1669 void
1670 handle_shorten_pseu_dht_result(void* cls,
1671                       struct GNUNET_GNS_ResolverHandle *rh,
1672                       uint32_t rd_len,
1673                       const struct GNUNET_NAMESTORE_RecordData *rd)
1674 {
1675   struct ClientShortenHandle* csh = (struct ClientShortenHandle*) cls;
1676   struct AuthorityChain *auth_chain;
1677   char* pseu;
1678   char* result;
1679   char* new_name;
1680   int i;
1681   
1682   /**
1683    * PSEU found
1684    */
1685   if (rd_len != 0)
1686   {
1687     for (i=0; i < rd_len; i++)
1688     {
1689       if (rd[i].record_type == GNUNET_GNS_RECORD_PSEU)
1690         break;
1691     }
1692     
1693     pseu = (char*) rd[i].data;
1694     result = GNUNET_malloc(strlen(rh->name) + strlen(pseu) + 1);
1695     memset(result, 0, strlen(rh->name) + strlen(pseu) + 1);
1696     memcpy(result, rh->name, strlen(rh->name));
1697     memcpy(result+strlen(rh->name)+1, pseu, strlen(pseu));
1698
1699     send_shorten_response(result, csh);
1700
1701     GNUNET_free(result);
1702     return;
1703   }
1704   
1705   /**
1706    * No PSEU found.
1707    * continue with next authority
1708    * backtrack
1709    */
1710   auth_chain = rh->authority_chain_head;
1711
1712   if ((auth_chain->next->next == NULL) &&
1713       GNUNET_CRYPTO_hash_cmp(&auth_chain->next->zone, &zone_hash) == 0)
1714   {
1715     /**
1716      * Our zone is next
1717      */
1718     result = GNUNET_malloc(strlen(rh->name) + strlen(auth_chain->name) + 2);
1719     memset(result, 0, strlen(rh->name) + strlen(auth_chain->name) + 2);
1720     strcpy(result, rh->name);
1721     strcpy(result+strlen(rh->name)+1, ".");
1722     strcpy(result+strlen(rh->name)+2, auth_chain->name);
1723     send_shorten_response(result, csh);
1724
1725     return;
1726   }
1727
1728   /**
1729    * Continue with next authority
1730    */
1731   new_name = GNUNET_malloc(strlen(rh->name)+
1732                            strlen(auth_chain->name) + 2);
1733   memset(new_name, 0, strlen(rh->name)+
1734                       strlen(auth_chain->name) + 2);
1735   strcpy(new_name, rh->name);
1736   strcpy(new_name+strlen(rh->name)+1, ".");
1737   strcpy(new_name+strlen(rh->name)+2, auth_chain->name);
1738   GNUNET_CONTAINER_DLL_remove(rh->authority_chain_head,
1739                               rh->authority_chain_tail,
1740                               auth_chain);
1741
1742   GNUNET_NAMESTORE_zone_to_name (namestore_handle,
1743                                  &zone_hash,
1744                                  &rh->authority_chain_head->zone,
1745                                  &handle_shorten_zone_to_name,
1746                                  rh);
1747
1748 }
1749
1750
1751
1752 /**
1753  * Process result from namestore PSEU lookup
1754  * for shorten operation
1755  * FIXME do we need to check for own zone here?
1756  *
1757  * @param cls the client shorten handle
1758  * @param rh the resolver handle
1759  * @param rd_count number of results (0 if none found)
1760  * @param rd data (NULL if none found)
1761  */
1762 static void
1763 handle_shorten_pseu_ns_result(void* cls,
1764                       struct GNUNET_GNS_ResolverHandle *rh,
1765                       uint32_t rd_len,
1766                       const struct GNUNET_NAMESTORE_RecordData *rd)
1767 {
1768   struct ClientShortenHandle* csh = (struct ClientShortenHandle*) cls;
1769   struct AuthorityChain *auth_chain;
1770   char* pseu;
1771   char* result;
1772   char* new_name;
1773   int i;
1774   
1775   /**
1776    * PSEU found
1777    */
1778   if (rd_len != 0)
1779   {
1780     for (i=0; i < rd_len; i++)
1781     {
1782       if (rd[i].record_type == GNUNET_GNS_RECORD_PSEU)
1783         break;
1784     }
1785     
1786     pseu = (char*) rd[i].data;
1787     result = GNUNET_malloc(strlen(rh->name) + strlen(pseu) + 1);
1788     memset(result, 0, strlen(rh->name) + strlen(pseu) + 1);
1789     memcpy(result, rh->name, strlen(rh->name));
1790     memcpy(result+strlen(rh->name)+1, pseu, strlen(pseu));
1791
1792     send_shorten_response(result, csh);
1793
1794     GNUNET_free(result);
1795     return;
1796   }
1797   
1798   /**
1799    * No PSEU found. Ask DHT if expired.
1800    * Else contunue with next authority
1801    */
1802   if (rh->status & (EXISTS | !EXPIRED))
1803   {
1804     /**
1805      * backtrack
1806      */
1807     auth_chain = rh->authority_chain_head;
1808     new_name = GNUNET_malloc(strlen(rh->name)+
1809                              strlen(auth_chain->name) + 2);
1810     memset(new_name, 0, strlen(rh->name)+
1811                         strlen(auth_chain->name) + 2);
1812     strcpy(new_name, rh->name);
1813     strcpy(new_name+strlen(rh->name)+1, ".");
1814     strcpy(new_name+strlen(rh->name)+2, auth_chain->name);
1815
1816     GNUNET_CONTAINER_DLL_remove(rh->authority_chain_head,
1817                                 rh->authority_chain_tail,
1818                                 auth_chain);
1819
1820     GNUNET_NAMESTORE_zone_to_name (namestore_handle,
1821                                    &zone_hash,
1822                                    &rh->authority_chain_head->zone,
1823                                    &handle_shorten_zone_to_name,
1824                                    rh);
1825     return;
1826   }
1827
1828   /**
1829    * Ask DHT
1830    */
1831   rh->authority = rh->authority_chain_head->zone;
1832   rh->proc = &handle_shorten_pseu_dht_result;
1833   resolve_pseu_from_dht(rh);
1834
1835 }
1836
1837
1838
1839 /**
1840  * Process result from namestore delegation lookup
1841  * for shorten operation
1842  *
1843  * @param cls the client shorten handle
1844  * @param rh the resolver handle
1845  * @param rd_count number of results (0)
1846  * @param rd data (NULL)
1847  */
1848 void
1849 handle_shorten_delegation_result(void* cls,
1850                       struct GNUNET_GNS_ResolverHandle *rh,
1851                       uint32_t rd_count,
1852                       const struct GNUNET_NAMESTORE_RecordData *rd)
1853 {
1854   struct ClientShortenHandle* csh = (struct ClientShortenHandle*) cls;
1855   struct AuthorityChain *auth_chain;
1856   
1857   /**
1858    * At this point rh->name contains the part of the name
1859    * that we do not have a PKEY in our namestore to resolve.
1860    * The authority chain in the resolver handle is now
1861    * useful to backtrack if needed
1862    */
1863   
1864   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1865              "PKEY resolved as far as possible in ns up to %s!\n", rh->name);
1866
1867   if (GNUNET_CRYPTO_hash_cmp(&rh->authority_chain_head->zone,
1868                              &zone_hash) == 0)
1869   {
1870     /**
1871      * This is our zone append .gnunet unless name is empty
1872      * (it shouldn't be, usually FIXME what happens if we
1873      * shorten to our zone to a "" record??)
1874      **/
1875     send_shorten_response(rh->name, csh); //FIXME +.gnunet!
1876     //FIXME free
1877     return;
1878   }
1879   csh->offset++; //FIXME needed?
1880   auth_chain = rh->authority_chain_head;
1881   /* backtrack authorities for pseu */
1882   GNUNET_NAMESTORE_zone_to_name (namestore_handle,
1883                                  &zone_hash, //ours
1884                                  &auth_chain->zone,
1885                                  &handle_shorten_zone_to_name,
1886                                  rh);
1887
1888 }
1889
1890 typedef void (*ShortenResponseProc) (void* cls, const char* name);
1891
1892 /**
1893  * Shorten a given name
1894  *
1895  * @param name the name to shorten
1896  * @param proc the processor to call when finished
1897  * @praram cls the closure to the processor
1898  */
1899 static void
1900 shorten_name(char* name, struct ClientShortenHandle* csh)
1901 {
1902
1903   struct GNUNET_GNS_ResolverHandle *rh;
1904   
1905   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1906               "Starting resolution for %s (type=%d)!\n",
1907               name, GNUNET_GNS_RECORD_PKEY);
1908   
1909   rh = GNUNET_malloc(sizeof (struct GNUNET_GNS_ResolverHandle));
1910   rh->authority = zone_hash;
1911   
1912   rh->name = GNUNET_malloc(strlen(name)
1913                               - strlen(gnunet_tld) + 1);
1914   memset(rh->name, 0,
1915          strlen(name)-strlen(gnunet_tld) + 1);
1916   memcpy(rh->name, name,
1917          strlen(name)-strlen(gnunet_tld));
1918
1919   csh->name = GNUNET_malloc(strlen(name)
1920                             - strlen(gnunet_tld) + 1);
1921   memset(rh->name, 0,
1922          strlen(name)-strlen(gnunet_tld) + 1);
1923   memcpy(rh->name, name,
1924          strlen(name)-strlen(gnunet_tld));
1925
1926   rh->authority_name = GNUNET_malloc(sizeof(char)*MAX_DNS_LABEL_LENGTH);
1927
1928   rh->authority_chain_head = GNUNET_malloc(sizeof(struct AuthorityChain));
1929   rh->authority_chain_tail = rh->authority_chain_head;
1930   rh->authority_chain_head->zone = zone_hash;
1931   rh->proc = &handle_shorten_delegation_result;
1932   rh->proc_cls = (void*)csh;
1933
1934   /* Start delegation resolution in our namestore */
1935   resolve_delegation_from_ns(rh);
1936
1937 }
1938
1939 /**
1940  * Send shorten response back to client
1941  * FIXME this is without .gnunet!
1942  * 
1943  * @param cls the client handle in closure
1944  * @param name the shortened name result or NULL if cannot be shortened
1945  */
1946 static void
1947 send_shorten_response(const char* name, struct ClientShortenHandle *csh)
1948 {
1949   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message\n",
1950               "SHORTEN_RESULT");
1951   struct GNUNET_GNS_ClientShortenResultMessage *rmsg;
1952   
1953   if (name == NULL)
1954   {
1955     name = '\0';
1956   }
1957
1958   rmsg = GNUNET_malloc(sizeof(struct GNUNET_GNS_ClientShortenResultMessage *)
1959                        + strlen(name));
1960   
1961   rmsg->unique_id = csh->unique_id;
1962   rmsg->key = csh->key;
1963   rmsg->header.type = htons(GNUNET_MESSAGE_TYPE_GNS_SHORTEN_RESULT);
1964   rmsg->header.size = 
1965     htons(sizeof(struct GNUNET_GNS_ClientShortenResultMessage *) +
1966           strlen(name));
1967
1968   strcpy((char*)&rmsg[1], name);
1969
1970   GNUNET_SERVER_notification_context_unicast (nc, csh->client,
1971                               (const struct GNUNET_MessageHeader *) &rmsg,
1972                               GNUNET_NO);
1973
1974   GNUNET_SERVER_receive_done (csh->client, GNUNET_OK);
1975   
1976   GNUNET_free(csh);
1977   GNUNET_free(rmsg);
1978
1979 }
1980
1981 /**
1982  * Handle a shorten message from the api
1983  *
1984  * @param cls the closure
1985  * @param client the client
1986  * @param message the message
1987  */
1988 static void handle_shorten(void *cls,
1989                            struct GNUNET_SERVER_Client * client,
1990                            const struct GNUNET_MessageHeader * message)
1991 {
1992   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "SHORTEN");
1993
1994   size_t msg_size = 0;
1995   struct ClientShortenHandle *csh;
1996
1997   if (ntohs (message->size) != sizeof (struct GNUNET_GNS_ClientShortenMessage))
1998   {
1999     GNUNET_break_op (0);
2000     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2001     return;
2002   }
2003
2004   struct GNUNET_GNS_ClientShortenMessage *sh_msg =
2005     (struct GNUNET_GNS_ClientShortenMessage *) message;
2006   
2007   msg_size = ntohs(message->size);
2008
2009   if (msg_size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
2010   {
2011     GNUNET_break_op (0);
2012     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2013     return;
2014   }
2015
2016   csh = GNUNET_malloc(sizeof(struct ClientShortenHandle));
2017   csh->client = client;
2018   csh->unique_id = sh_msg->unique_id;
2019   csh->key = sh_msg->key;
2020   
2021   //Offset in original name
2022   csh->offset = 0;
2023   
2024
2025   shorten_name((char*)&sh_msg[1], csh);
2026
2027 }
2028
2029 /**
2030  * TODO
2031  */
2032 static void
2033 handle_lookup(void *cls,
2034               struct GNUNET_SERVER_Client * client,
2035               const struct GNUNET_MessageHeader * message)
2036 {
2037 }
2038
2039 /**
2040  * Process GNS requests.
2041  *
2042  * @param cls closure)
2043  * @param server the initialized server
2044  * @param c configuration to use
2045  */
2046 static void
2047 run (void *cls, struct GNUNET_SERVER_Handle *server,
2048      const struct GNUNET_CONFIGURATION_Handle *c)
2049 {
2050   
2051   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Initializing GNS\n");
2052
2053   char* keyfile;
2054   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pkey;
2055
2056   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
2057     {&handle_shorten, NULL, GNUNET_MESSAGE_TYPE_GNS_SHORTEN, 0},
2058     {&handle_lookup, NULL, GNUNET_MESSAGE_TYPE_GNS_LOOKUP, 0}
2059   };
2060
2061   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (c, "gns",
2062                                              "ZONEKEY", &keyfile))
2063   {
2064     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2065                 "No private key for root zone specified%s!\n", keyfile);
2066     GNUNET_SCHEDULER_shutdown(0);
2067     return;
2068   }
2069
2070   zone_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
2071   GNUNET_CRYPTO_rsa_key_get_public (zone_key, &pkey);
2072
2073   GNUNET_CRYPTO_hash(&pkey, sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2074                      &zone_hash);
2075   
2076
2077   if (GNUNET_YES ==
2078       GNUNET_CONFIGURATION_get_value_yesno (c, "gns",
2079                                             "HIJACK_DNS"))
2080   {
2081     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
2082                "DNS hijacking enabled... connecting to service.\n");
2083     /**
2084      * Do gnunet dns init here
2085      */
2086     dns_handle = GNUNET_DNS_connect(c,
2087                                     GNUNET_DNS_FLAG_PRE_RESOLUTION,
2088                                     &handle_dns_request, /* rh */
2089                                     NULL); /* Closure */
2090     if (NULL == dns_handle)
2091     {
2092       GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
2093                "Failed to connect to the dnsservice!\n");
2094     }
2095   }
2096
2097   
2098
2099   /**
2100    * handle to our local namestore
2101    */
2102   namestore_handle = GNUNET_NAMESTORE_connect(c);
2103
2104   if (NULL == namestore_handle)
2105   {
2106     //FIXME do error handling;
2107     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
2108                "Failed to connect to the namestore!\n");
2109     GNUNET_SCHEDULER_shutdown(0);
2110     return;
2111   }
2112   
2113   /**
2114    * handle to the dht
2115    */
2116   dht_handle = GNUNET_DHT_connect(c, 1); //FIXME get ht_len from cfg
2117
2118   if (NULL == dht_handle)
2119   {
2120     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Could not connect to DHT!\n");
2121   }
2122
2123   //put_some_records(); //FIXME for testing
2124   
2125   /**
2126    * Schedule periodic put
2127    * for our records
2128    * We have roughly an hour for all records;
2129    */
2130   dht_update_interval = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS,
2131                                                       1);
2132   //zone_update_taskid = GNUNET_SCHEDULER_add_now (&update_zone_dht_start, NULL);
2133
2134   GNUNET_SERVER_add_handlers (server, handlers);
2135   
2136   //FIXME
2137   //GNUNET_SERVER_disconnect_notify (server,
2138   //                                 &client_disconnect_notification,
2139   //                                 NULL);
2140
2141   nc = GNUNET_SERVER_notification_context_create (server, 1);
2142
2143   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
2144                                 NULL);
2145 }
2146
2147
2148 /**
2149  * The main function for the GNS service.
2150  *
2151  * @param argc number of arguments from the command line
2152  * @param argv command line arguments
2153  * @return 0 ok, 1 on error
2154  */
2155 int
2156 main (int argc, char *const *argv)
2157 {
2158   int ret;
2159
2160   ret =
2161       (GNUNET_OK ==
2162        GNUNET_SERVICE_run (argc, argv, "gns", GNUNET_SERVICE_OPTION_NONE, &run,
2163                            NULL)) ? 0 : 1;
2164   return ret;
2165 }
2166
2167 /* end of gnunet-service-gns.c */