-more shortening
[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
1567   
1568   rh->proc(cls, rh, rd_len, rd);
1569 }
1570
1571
1572 /**
1573  * Start DHT lookup for a PSEUdonym record in
1574  * rh->authority's zone
1575  *
1576  * @param rh the pending gns query
1577  * @param name the name of the PKEY record
1578  */
1579 static void
1580 resolve_pseu_from_dht(struct GNUNET_GNS_ResolverHandle *rh)
1581 {
1582   uint32_t xquery;
1583   GNUNET_HashCode name_hash;
1584   GNUNET_HashCode lookup_key;
1585
1586   //Empty string
1587   GNUNET_CRYPTO_hash("",
1588                      1,
1589                      &name_hash);
1590
1591   GNUNET_CRYPTO_hash_xor(&name_hash, &rh->authority, &lookup_key);
1592
1593   rh->dht_timeout_task = GNUNET_SCHEDULER_add_delayed (DHT_LOOKUP_TIMEOUT,
1594                                                   &dht_lookup_timeout,
1595                                                        rh);
1596
1597   xquery = htonl(GNUNET_GNS_RECORD_PSEU);
1598   
1599   rh->get_handle = GNUNET_DHT_get_start(dht_handle,
1600                        DHT_OPERATION_TIMEOUT,
1601                        GNUNET_BLOCK_TYPE_GNS_NAMERECORD,
1602                        &lookup_key,
1603                        DHT_GNS_REPLICATION_LEVEL,
1604                        GNUNET_DHT_RO_NONE,
1605                        &xquery,
1606                        sizeof(xquery),
1607                        &process_authority_dht_result,
1608                        rh);
1609
1610 }
1611
1612 //Prototype
1613 static void
1614 handle_shorten_pseu_ns_result(void* cls,
1615                               struct GNUNET_GNS_ResolverHandle *rh,
1616                               uint32_t rd_count,
1617                               const struct GNUNET_NAMESTORE_RecordData *rd);
1618
1619 static void
1620 handle_shorten_zone_to_name(void *cls,
1621                  const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *zone_key,
1622                  struct GNUNET_TIME_Absolute expire,
1623                  const char *name,
1624                  unsigned int rd_len,
1625                  const struct GNUNET_NAMESTORE_RecordData *rd,
1626                  const struct GNUNET_CRYPTO_RsaSignature *signature)
1627 {
1628   struct GNUNET_GNS_ResolverHandle *rh = 
1629     (struct GNUNET_GNS_ResolverHandle *)cls;
1630   struct ClientShortenHandle* csh = (struct ClientShortenHandle*) rh->proc_cls;
1631
1632   char* result;
1633   
1634   /* we found a match in our own zone */
1635   if (rd_len != 0)
1636   {
1637     result = GNUNET_malloc(strlen(rh->name) + strlen(name) + 1);
1638     memset(result, 0, strlen(rh->name) + strlen(name) + 1);
1639     memcpy(result, rh->name, strlen(rh->name));
1640     memcpy(result+strlen(rh->name)+1, name, strlen(name));
1641
1642     send_shorten_response(result, csh);
1643
1644     GNUNET_free(result);
1645   }
1646   else
1647   {
1648     /**
1649      * Nothing in our zone
1650      * check PSEU for this authority in namestore
1651      */
1652     rh->proc = &handle_shorten_pseu_ns_result;
1653     GNUNET_NAMESTORE_lookup_record(namestore_handle,
1654                                    &rh->authority_chain_head->zone,
1655                                    "",
1656                                    GNUNET_GNS_RECORD_PSEU,
1657                                    &process_shorten_pseu_lookup_ns,
1658                                    rh);
1659   }
1660 }
1661
1662 /**
1663  * Process result from namestore delegation lookup
1664  * for shorten operation
1665  *
1666  * @param cls the client shorten handle
1667  * @param rh the resolver handle
1668  * @param rd_count number of results (0)
1669  * @param rd data (NULL)
1670  */
1671 void
1672 handle_shorten_pseu_dht_result(void* cls,
1673                       struct GNUNET_GNS_ResolverHandle *rh,
1674                       uint32_t rd_len,
1675                       const struct GNUNET_NAMESTORE_RecordData *rd)
1676 {
1677   struct ClientShortenHandle* csh = (struct ClientShortenHandle*) cls;
1678   struct AuthorityChain *auth_chain;
1679   char* pseu;
1680   char* result;
1681   char* new_name;
1682   int i;
1683   
1684   /**
1685    * PSEU found
1686    */
1687   if (rd_len != 0)
1688   {
1689     for (i=0; i < rd_len; i++)
1690     {
1691       if (rd[i].record_type == GNUNET_GNS_RECORD_PSEU)
1692         break;
1693     }
1694     
1695     pseu = (char*) rd[i].data;
1696     result = GNUNET_malloc(strlen(rh->name) + strlen(pseu) + 1);
1697     memset(result, 0, strlen(rh->name) + strlen(pseu) + 1);
1698     memcpy(result, rh->name, strlen(rh->name));
1699     memcpy(result+strlen(rh->name)+1, pseu, strlen(pseu));
1700
1701     send_shorten_response(result, csh);
1702
1703     GNUNET_free(result);
1704     return;
1705   }
1706   
1707   /**
1708    * No PSEU found.
1709    * continue with next authority
1710    * backtrack
1711    */
1712   auth_chain = rh->authority_chain_head;
1713
1714   if ((auth_chain->next->next == NULL) &&
1715       GNUNET_CRYPTO_hash_cmp(&auth_chain->next->zone, &zone_hash) == 0)
1716   {
1717     /**
1718      * Our zone is next
1719      */
1720     result = GNUNET_malloc(strlen(rh->name) + strlen(auth_chain->name) + 2);
1721     memset(result, 0, strlen(rh->name) + strlen(auth_chain->name) + 2);
1722     strcpy(result, rh->name);
1723     strcpy(result+strlen(rh->name)+1, ".");
1724     strcpy(result+strlen(rh->name)+2, auth_chain->name);
1725     send_shorten_response(result, csh);
1726
1727     return;
1728   }
1729
1730   /**
1731    * Continue with next authority
1732    */
1733   new_name = GNUNET_malloc(strlen(rh->name)+
1734                            strlen(auth_chain->name) + 2);
1735   memset(new_name, 0, strlen(rh->name)+
1736                       strlen(auth_chain->name) + 2);
1737   strcpy(new_name, rh->name);
1738   strcpy(new_name+strlen(rh->name)+1, ".");
1739   strcpy(new_name+strlen(rh->name)+2, auth_chain->name);
1740   GNUNET_CONTAINER_DLL_remove(rh->authority_chain_head,
1741                               rh->authority_chain_tail,
1742                               auth_chain);
1743
1744   GNUNET_NAMESTORE_zone_to_name (namestore_handle,
1745                                  &zone_hash,
1746                                  &rh->authority_chain_head->zone,
1747                                  &handle_shorten_zone_to_name,
1748                                  rh);
1749
1750 }
1751
1752
1753
1754 /**
1755  * Process result from namestore PSEU lookup
1756  * for shorten operation
1757  * FIXME do we need to check for own zone here?
1758  *
1759  * @param cls the client shorten handle
1760  * @param rh the resolver handle
1761  * @param rd_count number of results (0 if none found)
1762  * @param rd data (NULL if none found)
1763  */
1764 static void
1765 handle_shorten_pseu_ns_result(void* cls,
1766                       struct GNUNET_GNS_ResolverHandle *rh,
1767                       uint32_t rd_len,
1768                       const struct GNUNET_NAMESTORE_RecordData *rd)
1769 {
1770   struct ClientShortenHandle* csh = (struct ClientShortenHandle*) cls;
1771   struct AuthorityChain *auth_chain;
1772   char* pseu;
1773   char* result;
1774   char* new_name;
1775   int i;
1776   
1777   /**
1778    * PSEU found
1779    */
1780   if (rd_len != 0)
1781   {
1782     for (i=0; i < rd_len; i++)
1783     {
1784       if (rd[i].record_type == GNUNET_GNS_RECORD_PSEU)
1785         break;
1786     }
1787     
1788     pseu = (char*) rd[i].data;
1789     result = GNUNET_malloc(strlen(rh->name) + strlen(pseu) + 1);
1790     memset(result, 0, strlen(rh->name) + strlen(pseu) + 1);
1791     memcpy(result, rh->name, strlen(rh->name));
1792     memcpy(result+strlen(rh->name)+1, pseu, strlen(pseu));
1793
1794     send_shorten_response(result, csh);
1795
1796     GNUNET_free(result);
1797     return;
1798   }
1799   
1800   /**
1801    * No PSEU found. Ask DHT if expired.
1802    * Else contunue with next authority
1803    */
1804   if (rh->status & (EXISTS | !EXPIRED))
1805   {
1806     /**
1807      * backtrack
1808      */
1809     auth_chain = rh->authority_chain_head;
1810     new_name = GNUNET_malloc(strlen(rh->name)+
1811                              strlen(auth_chain->name) + 2);
1812     memset(new_name, 0, strlen(rh->name)+
1813                         strlen(auth_chain->name) + 2);
1814     strcpy(new_name, rh->name);
1815     strcpy(new_name+strlen(rh->name)+1, ".");
1816     strcpy(new_name+strlen(rh->name)+2, auth_chain->name);
1817
1818     GNUNET_CONTAINER_DLL_remove(rh->authority_chain_head,
1819                                 rh->authority_chain_tail,
1820                                 auth_chain);
1821
1822     GNUNET_NAMESTORE_zone_to_name (namestore_handle,
1823                                    &zone_hash,
1824                                    &rh->authority_chain_head->zone,
1825                                    &handle_shorten_zone_to_name,
1826                                    rh);
1827     return;
1828   }
1829
1830   /**
1831    * Ask DHT
1832    */
1833   rh->authority = rh->authority_chain_head->zone;
1834   rh->proc = &handle_shorten_pseu_dht_result;
1835   resolve_pseu_from_dht(rh);
1836
1837 }
1838
1839
1840
1841 /**
1842  * Process result from namestore delegation lookup
1843  * for shorten operation
1844  *
1845  * @param cls the client shorten handle
1846  * @param rh the resolver handle
1847  * @param rd_count number of results (0)
1848  * @param rd data (NULL)
1849  */
1850 void
1851 handle_shorten_delegation_result(void* cls,
1852                       struct GNUNET_GNS_ResolverHandle *rh,
1853                       uint32_t rd_count,
1854                       const struct GNUNET_NAMESTORE_RecordData *rd)
1855 {
1856   struct ClientShortenHandle* csh = (struct ClientShortenHandle*) cls;
1857   struct AuthorityChain *auth_chain;
1858   
1859   /**
1860    * At this point rh->name contains the part of the name
1861    * that we do not have a PKEY in our namestore to resolve.
1862    * The authority chain in the resolver handle is now
1863    * useful to backtrack if needed
1864    */
1865   
1866   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1867              "PKEY resolved as far as possible in ns up to %s!\n", rh->name);
1868
1869   if (GNUNET_CRYPTO_hash_cmp(&rh->authority_chain_head->zone,
1870                              &zone_hash) == 0)
1871   {
1872     /**
1873      * This is our zone append .gnunet unless name is empty
1874      * (it shouldn't be, usually FIXME what happens if we
1875      * shorten to our zone to a "" record??)
1876      **/
1877     send_shorten_response(rh->name, csh); //FIXME +.gnunet!
1878     //FIXME free
1879     return;
1880   }
1881   csh->offset++; //FIXME needed?
1882   auth_chain = rh->authority_chain_head;
1883   /* backtrack authorities for pseu */
1884   GNUNET_NAMESTORE_zone_to_name (namestore_handle,
1885                                  &zone_hash, //ours
1886                                  &auth_chain->zone,
1887                                  &handle_shorten_zone_to_name,
1888                                  rh);
1889
1890 }
1891
1892 typedef void (*ShortenResponseProc) (void* cls, const char* name);
1893
1894 /**
1895  * Shorten a given name
1896  *
1897  * @param name the name to shorten
1898  * @param proc the processor to call when finished
1899  * @praram cls the closure to the processor
1900  */
1901 static void
1902 shorten_name(char* name, struct ClientShortenHandle* csh)
1903 {
1904
1905   struct GNUNET_GNS_ResolverHandle *rh;
1906   
1907   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1908               "Starting resolution for %s (type=%d)!\n",
1909               name, GNUNET_GNS_RECORD_PKEY);
1910   
1911   rh = GNUNET_malloc(sizeof (struct GNUNET_GNS_ResolverHandle));
1912   rh->authority = zone_hash;
1913   
1914   rh->name = GNUNET_malloc(strlen(name)
1915                               - strlen(gnunet_tld) + 1);
1916   memset(rh->name, 0,
1917          strlen(name)-strlen(gnunet_tld) + 1);
1918   memcpy(rh->name, name,
1919          strlen(name)-strlen(gnunet_tld));
1920
1921   csh->name = GNUNET_malloc(strlen(name)
1922                             - strlen(gnunet_tld) + 1);
1923   memset(rh->name, 0,
1924          strlen(name)-strlen(gnunet_tld) + 1);
1925   memcpy(rh->name, name,
1926          strlen(name)-strlen(gnunet_tld));
1927
1928   rh->authority_name = GNUNET_malloc(sizeof(char)*MAX_DNS_LABEL_LENGTH);
1929
1930   rh->authority_chain_head = GNUNET_malloc(sizeof(struct AuthorityChain));
1931   rh->authority_chain_tail = rh->authority_chain_head;
1932   rh->authority_chain_head->zone = zone_hash;
1933   rh->proc = &handle_shorten_delegation_result;
1934   rh->proc_cls = (void*)csh;
1935
1936   /* Start delegation resolution in our namestore */
1937   resolve_delegation_from_ns(rh);
1938
1939 }
1940
1941 /**
1942  * Send shorten response back to client
1943  * FIXME this is without .gnunet!
1944  * 
1945  * @param cls the client handle in closure
1946  * @param name the shortened name result or NULL if cannot be shortened
1947  */
1948 static void
1949 send_shorten_response(const char* name, struct ClientShortenHandle *csh)
1950 {
1951   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message\n",
1952               "SHORTEN_RESULT");
1953   struct GNUNET_GNS_ClientShortenResultMessage *rmsg;
1954   
1955   if (name == NULL)
1956   {
1957     name = '\0';
1958   }
1959
1960   rmsg = GNUNET_malloc(sizeof(struct GNUNET_GNS_ClientShortenResultMessage *)
1961                        + strlen(name));
1962   
1963   rmsg->unique_id = csh->unique_id;
1964   rmsg->key = csh->key;
1965   rmsg->header.type = htons(GNUNET_MESSAGE_TYPE_GNS_SHORTEN_RESULT);
1966   rmsg->header.size = 
1967     htons(sizeof(struct GNUNET_GNS_ClientShortenResultMessage *) +
1968           strlen(name));
1969
1970   strcpy((char*)&rmsg[1], name);
1971
1972   GNUNET_SERVER_notification_context_unicast (nc, csh->client,
1973                               (const struct GNUNET_MessageHeader *) &rmsg,
1974                               GNUNET_NO);
1975
1976   GNUNET_SERVER_receive_done (csh->client, GNUNET_OK);
1977   
1978   GNUNET_free(csh);
1979   GNUNET_free(rmsg);
1980
1981 }
1982
1983 /**
1984  * Handle a shorten message from the api
1985  *
1986  * @param cls the closure
1987  * @param client the client
1988  * @param message the message
1989  */
1990 static void handle_shorten(void *cls,
1991                            struct GNUNET_SERVER_Client * client,
1992                            const struct GNUNET_MessageHeader * message)
1993 {
1994   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "SHORTEN");
1995
1996   size_t msg_size = 0;
1997   struct ClientShortenHandle *csh;
1998
1999   if (ntohs (message->size) != sizeof (struct GNUNET_GNS_ClientShortenMessage))
2000   {
2001     GNUNET_break_op (0);
2002     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2003     return;
2004   }
2005
2006   struct GNUNET_GNS_ClientShortenMessage *sh_msg =
2007     (struct GNUNET_GNS_ClientShortenMessage *) message;
2008   
2009   msg_size = ntohs(message->size);
2010
2011   if (msg_size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
2012   {
2013     GNUNET_break_op (0);
2014     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2015     return;
2016   }
2017
2018   csh = GNUNET_malloc(sizeof(struct ClientShortenHandle));
2019   csh->client = client;
2020   csh->unique_id = sh_msg->unique_id;
2021   csh->key = sh_msg->key;
2022   
2023   //Offset in original name
2024   csh->offset = 0;
2025   
2026
2027   shorten_name((char*)&sh_msg[1], csh);
2028
2029 }
2030
2031 /**
2032  * TODO
2033  */
2034 static void
2035 handle_lookup(void *cls,
2036               struct GNUNET_SERVER_Client * client,
2037               const struct GNUNET_MessageHeader * message)
2038 {
2039 }
2040
2041 /**
2042  * Process GNS requests.
2043  *
2044  * @param cls closure)
2045  * @param server the initialized server
2046  * @param c configuration to use
2047  */
2048 static void
2049 run (void *cls, struct GNUNET_SERVER_Handle *server,
2050      const struct GNUNET_CONFIGURATION_Handle *c)
2051 {
2052   
2053   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Initializing GNS\n");
2054
2055   char* keyfile;
2056   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pkey;
2057
2058   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
2059     {&handle_shorten, NULL, GNUNET_MESSAGE_TYPE_GNS_SHORTEN, 0},
2060     {&handle_lookup, NULL, GNUNET_MESSAGE_TYPE_GNS_LOOKUP, 0}
2061   };
2062
2063   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (c, "gns",
2064                                              "ZONEKEY", &keyfile))
2065   {
2066     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2067                 "No private key for root zone specified%s!\n", keyfile);
2068     GNUNET_SCHEDULER_shutdown(0);
2069     return;
2070   }
2071
2072   zone_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
2073   GNUNET_CRYPTO_rsa_key_get_public (zone_key, &pkey);
2074
2075   GNUNET_CRYPTO_hash(&pkey, sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2076                      &zone_hash);
2077   
2078
2079   if (GNUNET_YES ==
2080       GNUNET_CONFIGURATION_get_value_yesno (c, "gns",
2081                                             "HIJACK_DNS"))
2082   {
2083     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
2084                "DNS hijacking enabled... connecting to service.\n");
2085     /**
2086      * Do gnunet dns init here
2087      */
2088     dns_handle = GNUNET_DNS_connect(c,
2089                                     GNUNET_DNS_FLAG_PRE_RESOLUTION,
2090                                     &handle_dns_request, /* rh */
2091                                     NULL); /* Closure */
2092     if (NULL == dns_handle)
2093     {
2094       GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
2095                "Failed to connect to the dnsservice!\n");
2096     }
2097   }
2098
2099   
2100
2101   /**
2102    * handle to our local namestore
2103    */
2104   namestore_handle = GNUNET_NAMESTORE_connect(c);
2105
2106   if (NULL == namestore_handle)
2107   {
2108     //FIXME do error handling;
2109     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
2110                "Failed to connect to the namestore!\n");
2111     GNUNET_SCHEDULER_shutdown(0);
2112     return;
2113   }
2114   
2115   /**
2116    * handle to the dht
2117    */
2118   dht_handle = GNUNET_DHT_connect(c, 1); //FIXME get ht_len from cfg
2119
2120   if (NULL == dht_handle)
2121   {
2122     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Could not connect to DHT!\n");
2123   }
2124
2125   //put_some_records(); //FIXME for testing
2126   
2127   /**
2128    * Schedule periodic put
2129    * for our records
2130    * We have roughly an hour for all records;
2131    */
2132   dht_update_interval = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS,
2133                                                       1);
2134   //zone_update_taskid = GNUNET_SCHEDULER_add_now (&update_zone_dht_start, NULL);
2135
2136   GNUNET_SERVER_add_handlers (server, handlers);
2137   
2138   //FIXME
2139   //GNUNET_SERVER_disconnect_notify (server,
2140   //                                 &client_disconnect_notification,
2141   //                                 NULL);
2142
2143   nc = GNUNET_SERVER_notification_context_create (server, 1);
2144
2145   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
2146                                 NULL);
2147 }
2148
2149
2150 /**
2151  * The main function for the GNS service.
2152  *
2153  * @param argc number of arguments from the command line
2154  * @param argv command line arguments
2155  * @return 0 ok, 1 on error
2156  */
2157 int
2158 main (int argc, char *const *argv)
2159 {
2160   int ret;
2161
2162   ret =
2163       (GNUNET_OK ==
2164        GNUNET_SERVICE_run (argc, argv, "gns", GNUNET_SERVICE_OPTION_NONE, &run,
2165                            NULL)) ? 0 : 1;
2166   return ret;
2167 }
2168
2169 /* end of gnunet-service-gns.c */