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