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