-fix MX record parsing and serialization, others still to be fixed
[oweals/gnunet.git] / src / namestore / namestore_api_common.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009-2013 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  * @file namestore/namestore_api_common.c
23  * @brief API to access the NAMESTORE service
24  * @author Martin Schanzenbach
25  * @author Matthias Wachs
26  * @author Christian Grothoff
27  */
28 #include "platform.h"
29 #include "gnunet_util_lib.h"
30 #include "gnunet_constants.h"
31 #include "gnunet_signatures.h"
32 #include "gnunet_arm_service.h"
33 #include "gnunet_namestore_service.h"
34 #include "gnunet_dnsparser_lib.h"
35 #include "gnunet_tun_lib.h"
36 #include "namestore.h"
37
38
39 #define LOG(kind,...) GNUNET_log_from (kind, "gns-api",__VA_ARGS__)
40
41 GNUNET_NETWORK_STRUCT_BEGIN
42
43
44 /**
45  * Internal format of a record in the serialized form.
46  */
47 struct NetworkRecord
48 {
49
50   /**
51    * Expiration time for the DNS record; relative or absolute depends
52    * on 'flags', network byte order.
53    */
54   uint64_t expiration_time GNUNET_PACKED;
55
56   /**
57    * Number of bytes in 'data', network byte order.
58    */
59   uint32_t data_size GNUNET_PACKED;
60
61   /**
62    * Type of the GNS/DNS record, network byte order.
63    */
64   uint32_t record_type GNUNET_PACKED;
65
66   /**
67    * Flags for the record, network byte order.
68    */
69   uint32_t flags GNUNET_PACKED;
70   
71 };
72
73 GNUNET_NETWORK_STRUCT_END
74
75 /**
76  * Convert a UTF-8 string to UTF-8 lowercase
77  * @param src source string
78  * @return converted result
79  */
80 char *
81 GNUNET_NAMESTORE_normalize_string (const char *src)
82 {
83   GNUNET_assert (NULL != src);
84   char *res = strdup (src);
85   /* normalize */
86   GNUNET_STRINGS_utf8_tolower(src, &res);
87   return res;
88 }
89
90
91 /**
92  * Convert a zone key to a string (for printing debug messages).
93  * This is one of the very few calls in the entire API that is
94  * NOT reentrant!
95  *
96  * @param z the zone key
97  * @return string form; will be overwritten by next call to #GNUNET_NAMESTORE_z2s
98  */
99 const char *
100 GNUNET_NAMESTORE_z2s (const struct GNUNET_CRYPTO_EccPublicSignKey *z)
101 {
102   static char buf[sizeof (struct GNUNET_CRYPTO_EccPublicSignKey) * 8];
103   char *end;
104
105   end = GNUNET_STRINGS_data_to_string ((const unsigned char *) z, 
106                                        sizeof (struct GNUNET_CRYPTO_EccPublicSignKey),
107                                        buf, sizeof (buf));
108   if (NULL == end)
109   {
110     GNUNET_break (0);
111     return NULL;
112   }
113   *end = '\0';
114   return buf;
115 }
116
117
118 /**
119  * Calculate how many bytes we will need to serialize the given
120  * records.
121  *
122  * @param rd_count number of records in the rd array
123  * @param rd array of #GNUNET_NAMESTORE_RecordData with @a rd_count elements
124  * @return the required size to serialize
125  */
126 size_t
127 GNUNET_NAMESTORE_records_get_size (unsigned int rd_count,
128                                    const struct GNUNET_NAMESTORE_RecordData *rd)
129 {
130   unsigned int i;
131   size_t ret;
132
133   ret = sizeof (struct NetworkRecord) * rd_count;
134   for (i=0;i<rd_count;i++)
135   {
136     GNUNET_assert ((ret + rd[i].data_size) >= ret);
137     ret += rd[i].data_size;
138   }
139   return ret;  
140 }
141
142
143 /**
144  * Serialize the given records to the given destination buffer.
145  *
146  * @param rd_count number of records in the rd array
147  * @param rd array of #GNUNET_NAMESTORE_RecordData with @a rd_count elements
148  * @param dest_size size of the destination array
149  * @param dest where to write the result
150  * @return the size of serialized records, -1 if records do not fit
151  */
152 ssize_t
153 GNUNET_NAMESTORE_records_serialize (unsigned int rd_count,
154                                     const struct GNUNET_NAMESTORE_RecordData *rd,
155                                     size_t dest_size,
156                                     char *dest)
157 {
158   struct NetworkRecord rec;
159   unsigned int i;
160   size_t off;
161   
162   off = 0;
163   for (i=0;i<rd_count;i++)
164   {
165     rec.expiration_time = GNUNET_htonll (rd[i].expiration_time);
166     rec.data_size = htonl ((uint32_t) rd[i].data_size);
167     rec.record_type = htonl (rd[i].record_type);
168     rec.flags = htonl (rd[i].flags);
169     if (off + sizeof (rec) > dest_size)
170       return -1;
171     memcpy (&dest[off], &rec, sizeof (rec));
172     off += sizeof (rec);
173     if (off + rd[i].data_size > dest_size)
174       return -1;
175     memcpy (&dest[off], rd[i].data, rd[i].data_size);
176     off += rd[i].data_size;
177   }
178   return off;
179 }
180
181
182 /**
183  * Compares if two records are equal (ignoring flags such
184  * as authority, private and pending, but not relative vs.
185  * absolute expiration time).
186  *
187  * @param a record
188  * @param b record
189  * @return #GNUNET_YES if the records are equal or #GNUNET_NO if they are not
190  */
191 int
192 GNUNET_NAMESTORE_records_cmp (const struct GNUNET_NAMESTORE_RecordData *a,
193                               const struct GNUNET_NAMESTORE_RecordData *b)
194 {
195   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
196       "Comparing records\n");
197   if (a->record_type != b->record_type)
198   {
199     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
200         "Record type %lu != %lu\n", a->record_type, b->record_type);
201     return GNUNET_NO;
202   }
203   if ((a->expiration_time != b->expiration_time) &&
204       ((a->expiration_time != 0) && (b->expiration_time != 0)))
205   {
206     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
207         "Expiration time %llu != %llu\n", a->expiration_time, b->expiration_time);
208     return GNUNET_NO;
209   }
210   if ((a->flags & GNUNET_NAMESTORE_RF_RCMP_FLAGS) 
211        != (b->flags & GNUNET_NAMESTORE_RF_RCMP_FLAGS))
212   {
213     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
214         "Flags %lu (%lu) != %lu (%lu)\n", a->flags,
215         a->flags & GNUNET_NAMESTORE_RF_RCMP_FLAGS, b->flags,
216         b->flags & GNUNET_NAMESTORE_RF_RCMP_FLAGS);
217     return GNUNET_NO;
218   }
219   if (a->data_size != b->data_size)
220   {
221     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
222         "Data size %lu != %lu\n", a->data_size, b->data_size);
223     return GNUNET_NO;
224   }
225   if (0 != memcmp (a->data, b->data, a->data_size))
226   {
227     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
228         "Data contents do not match\n");
229     return GNUNET_NO;
230   }
231   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
232       "Records are equal\n");
233   return GNUNET_YES;
234 }
235
236
237 /**
238  * Deserialize the given records to the given destination.
239  *
240  * @param len size of the serialized record data
241  * @param src the serialized record data
242  * @param rd_count number of records in the rd array
243  * @param dest where to put the data
244  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
245  */
246 int
247 GNUNET_NAMESTORE_records_deserialize (size_t len,
248                                       const char *src,
249                                       unsigned int rd_count,
250                                       struct GNUNET_NAMESTORE_RecordData *dest)
251 {
252   struct NetworkRecord rec;
253   unsigned int i;
254   size_t off;
255   
256   off = 0;
257   for (i=0;i<rd_count;i++)
258   {
259     if (off + sizeof (rec) > len)
260       return GNUNET_SYSERR;
261     memcpy (&rec, &src[off], sizeof (rec));
262     dest[i].expiration_time = GNUNET_ntohll (rec.expiration_time);
263     dest[i].data_size = ntohl ((uint32_t) rec.data_size);
264     dest[i].record_type = ntohl (rec.record_type);
265     dest[i].flags = ntohl (rec.flags);
266     off += sizeof (rec);
267
268     if (off + dest[i].data_size > len)
269       return GNUNET_SYSERR;
270     dest[i].data = &src[off];
271     off += dest[i].data_size;
272   }
273   return GNUNET_OK; 
274 }
275
276
277 /**
278  * Returns the expiration time of the given block of records. The block
279  * expiration time is the expiration time of the block with smallest
280  * expiration time.
281  *
282  * @param rd_count number of records given in @a rd
283  * @param rd array of records
284  * @return absolute expiration time
285  */
286 struct GNUNET_TIME_Absolute
287 GNUNET_NAMESTORE_record_get_expiration_time (unsigned int rd_count, 
288                                              const struct GNUNET_NAMESTORE_RecordData *rd)
289 {
290   unsigned int c;
291   struct GNUNET_TIME_Absolute expire;
292   struct GNUNET_TIME_Absolute at;
293   struct GNUNET_TIME_Relative rt;
294
295   if (NULL == rd)
296     return GNUNET_TIME_UNIT_ZERO_ABS;
297   expire = GNUNET_TIME_UNIT_FOREVER_ABS;
298   for (c = 0; c < rd_count; c++)  
299   {
300     if (0 != (rd[c].flags & GNUNET_NAMESTORE_RF_RELATIVE_EXPIRATION))
301     {
302       rt.rel_value_us = rd[c].expiration_time;
303       at = GNUNET_TIME_relative_to_absolute (rt);
304     }
305     else
306     {
307       at.abs_value_us = rd[c].expiration_time;
308     }
309     expire = GNUNET_TIME_absolute_min (at, expire);  
310   }
311   return expire;
312 }
313
314
315 /**
316  * Derive session key and iv from label and public key.
317  *
318  * @param iv initialization vector to initialize
319  * @param skey session key to initialize
320  * @param label label to use for KDF
321  * @param pub public key to use for KDF
322  */
323 static void
324 derive_block_aes_key (struct GNUNET_CRYPTO_AesInitializationVector *iv,
325                       struct GNUNET_CRYPTO_AesSessionKey *skey,
326                       const char *label,
327                       const struct GNUNET_CRYPTO_EccPublicSignKey *pub)
328 {
329   static const char ctx_key[] = "gns-aes-ctx-key";
330   static const char ctx_iv[] = "gns-aes-ctx-iv";
331
332   GNUNET_CRYPTO_kdf (skey, sizeof (struct GNUNET_CRYPTO_AesSessionKey),
333                      pub, sizeof (struct GNUNET_CRYPTO_EccPublicSignKey),
334                      label, strlen (label),
335                      ctx_key, strlen (ctx_key),
336                      NULL, 0);
337   GNUNET_CRYPTO_kdf (iv, sizeof (struct GNUNET_CRYPTO_AesInitializationVector),
338                      pub, sizeof (struct GNUNET_CRYPTO_EccPublicSignKey),
339                      label, strlen (label),
340                      ctx_iv, strlen (ctx_iv),
341                      NULL, 0);
342 }
343
344
345 /**
346  * Sign name and records
347  *
348  * @param key the private key
349  * @param expire block expiration
350  * @param label the name for the records
351  * @param rd record data
352  * @param rd_count number of records
353  * @return NULL on error (block too large)
354  */
355 struct GNUNET_NAMESTORE_Block *
356 GNUNET_NAMESTORE_block_create (const struct GNUNET_CRYPTO_EccPrivateKey *key,
357                                struct GNUNET_TIME_Absolute expire,
358                                const char *label,
359                                const struct GNUNET_NAMESTORE_RecordData *rd,
360                                unsigned int rd_count)
361 {
362   size_t payload_len = GNUNET_NAMESTORE_records_get_size (rd_count, rd);
363   char payload[sizeof (uint32_t) + payload_len];
364   struct GNUNET_NAMESTORE_Block *block;
365   struct GNUNET_CRYPTO_EccPublicSignKey pkey;
366   struct GNUNET_CRYPTO_EccPrivateKey *dkey;
367   struct GNUNET_CRYPTO_AesInitializationVector iv;
368   struct GNUNET_CRYPTO_AesSessionKey skey;
369   uint32_t rd_count_nbo;
370
371   if (payload_len > GNUNET_NAMESTORE_MAX_VALUE_SIZE)
372     return NULL;
373   rd_count_nbo = htonl (rd_count);
374   memcpy (payload, &rd_count_nbo, sizeof (uint32_t));
375   GNUNET_assert (payload_len ==
376                  GNUNET_NAMESTORE_records_serialize (rd_count, rd,
377                                                      payload_len, &payload[sizeof (uint32_t)])); 
378   block = GNUNET_malloc (sizeof (struct GNUNET_NAMESTORE_Block) +
379                          sizeof (uint32_t) + payload_len);
380   block->purpose.size = htonl (sizeof (uint32_t) + payload_len + 
381                                sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
382                                sizeof (struct GNUNET_TIME_AbsoluteNBO));
383   block->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_GNS_RECORD_SIGN);
384   block->expiration_time = GNUNET_TIME_absolute_hton (expire);
385   dkey = GNUNET_CRYPTO_ecc_key_derive (key,
386                                        label,
387                                        "gns");
388   GNUNET_CRYPTO_ecc_key_get_public_for_signature (dkey,
389                                     &block->derived_key);
390   GNUNET_CRYPTO_ecc_key_get_public_for_signature (key,
391                                     &pkey);
392   derive_block_aes_key (&iv, &skey, label, &pkey);
393   GNUNET_break (payload_len + sizeof (uint32_t) ==
394                 GNUNET_CRYPTO_aes_encrypt (payload, payload_len + sizeof (uint32_t),
395                                            &skey, &iv,
396                                            &block[1]));
397   if (GNUNET_OK !=
398       GNUNET_CRYPTO_ecc_sign (dkey,
399                               &block->purpose,
400                               &block->signature))
401   {
402     GNUNET_break (0);
403     GNUNET_free (dkey);
404     GNUNET_free (block);
405     return NULL;
406   }
407   GNUNET_free (dkey);
408   return block;
409 }
410
411
412 /**
413  * Check if a signature is valid.  This API is used by the GNS Block
414  * to validate signatures received from the network.
415  *
416  * @param block block to verify
417  * @return #GNUNET_OK if the signature is valid
418  */
419 int
420 GNUNET_NAMESTORE_block_verify (const struct GNUNET_NAMESTORE_Block *block)
421 {  
422   return GNUNET_CRYPTO_ecc_verify (GNUNET_SIGNATURE_PURPOSE_GNS_RECORD_SIGN, 
423                                    &block->purpose,
424                                    &block->signature,
425                                    &block->derived_key);
426 }
427
428
429 /**
430  * Decrypt block.
431  *
432  * @param block block to decrypt
433  * @param zone_key public key of the zone
434  * @param label the name for the records
435  * @param proc function to call with the result
436  * @param proc_cls closure for proc
437  * @return #GNUNET_OK on success, #GNUNET_SYSERR if the block was 
438  *        not well-formed
439  */
440 int
441 GNUNET_NAMESTORE_block_decrypt (const struct GNUNET_NAMESTORE_Block *block,
442                                 const struct GNUNET_CRYPTO_EccPublicSignKey *zone_key,
443                                 const char *label,
444                                 GNUNET_NAMESTORE_RecordCallback proc,
445                                 void *proc_cls)
446 {
447   size_t payload_len = ntohl (block->purpose.size) -
448     sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) -
449     sizeof (struct GNUNET_TIME_AbsoluteNBO);
450   struct GNUNET_CRYPTO_AesInitializationVector iv;
451   struct GNUNET_CRYPTO_AesSessionKey skey;
452
453   if (ntohl (block->purpose.size) <      
454       sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
455       sizeof (struct GNUNET_TIME_AbsoluteNBO))
456   {
457     GNUNET_break_op (0);
458     return GNUNET_SYSERR;
459   }
460   derive_block_aes_key (&iv, &skey, label, zone_key);
461   {
462     char payload[payload_len];    
463     uint32_t rd_count;
464
465     GNUNET_break (payload_len ==
466                   GNUNET_CRYPTO_aes_decrypt (&block[1], payload_len,
467                                              &skey, &iv,
468                                              payload));
469     memcpy (&rd_count,
470             payload,
471             sizeof (uint32_t));
472     rd_count = ntohl (rd_count);
473     if (rd_count > 2048)
474     {
475       /* limit to sane value */
476       GNUNET_break_op (0);
477       return GNUNET_SYSERR;
478     }
479     {
480       struct GNUNET_NAMESTORE_RecordData rd[rd_count];
481       
482       if (GNUNET_OK !=
483           GNUNET_NAMESTORE_records_deserialize (payload_len - sizeof (uint32_t),
484                                                 &payload[sizeof (uint32_t)],
485                                                 rd_count,
486                                                 rd))
487       {
488         GNUNET_break_op (0);
489         return GNUNET_SYSERR;
490       }
491       if (NULL != proc)
492         proc (proc_cls, rd_count, (0 != rd_count) ? rd : NULL);
493     }
494   }
495   return GNUNET_OK;
496 }
497
498
499 /**
500  * Convert the 'value' of a record to a string.
501  *
502  * @param type type of the record
503  * @param data value in binary encoding
504  * @param data_size number of bytes in data
505  * @return NULL on error, otherwise human-readable representation of the value
506  */
507 char *
508 GNUNET_NAMESTORE_value_to_string (uint32_t type,
509                                   const void *data,
510                                   size_t data_size)
511 {
512   const struct GNUNET_TUN_DnsSoaRecord *soa;
513   const struct GNUNET_TUN_GnsVpnRecord *vpn;
514   const struct GNUNET_TUN_DnsSrvRecord *srv;
515   const struct GNUNET_TUN_DnsTlsaRecord *tlsa;
516   struct GNUNET_CRYPTO_HashAsciiEncoded s_peer;
517   const char *cdata;
518   char* vpn_str;
519   char* srv_str;
520   char* tlsa_str;
521   char* result;
522   const char* soa_rname;
523   const char* soa_mname;
524   char tmp[INET6_ADDRSTRLEN];
525
526   switch (type)
527   {
528   case 0:
529     return NULL;
530   case GNUNET_DNSPARSER_TYPE_A:
531     if (data_size != sizeof (struct in_addr))
532       return NULL;
533     if (NULL == inet_ntop (AF_INET, data, tmp, sizeof (tmp)))
534       return NULL;
535     return GNUNET_strdup (tmp);
536   case GNUNET_DNSPARSER_TYPE_NS:
537     return GNUNET_strndup (data, data_size);
538   case GNUNET_DNSPARSER_TYPE_CNAME:
539     return GNUNET_strndup (data, data_size);
540   case GNUNET_DNSPARSER_TYPE_SOA:
541     if (data_size <= sizeof (struct GNUNET_TUN_DnsSoaRecord))
542       return NULL;
543     soa = data;
544     soa_rname = (const char*) &soa[1];
545     soa_mname = memchr (soa_rname, 0, data_size - sizeof (struct GNUNET_TUN_DnsSoaRecord) - 1);
546     if (NULL == soa_mname)
547       return NULL;
548     soa_mname++;
549     if (NULL == memchr (soa_mname, 0, 
550                         data_size - (sizeof (struct GNUNET_TUN_DnsSoaRecord) + strlen (soa_rname) + 1)))
551       return NULL;
552     GNUNET_asprintf (&result, 
553                      "rname=%s mname=%s %lu,%lu,%lu,%lu,%lu",
554                      soa_rname, soa_mname,
555                      ntohl (soa->serial), 
556                      ntohl (soa->refresh),
557                      ntohl (soa->retry), 
558                      ntohl (soa->expire),
559                      ntohl (soa->minimum));
560     return result;
561   case GNUNET_DNSPARSER_TYPE_PTR:
562     return GNUNET_strndup (data, data_size);
563   case GNUNET_DNSPARSER_TYPE_MX:
564     {
565       struct GNUNET_DNSPARSER_MxRecord *mx;
566       size_t off;
567
568       off = 0;
569       mx = GNUNET_DNSPARSER_parse_mx (data,
570                                       data_size,
571                                       &off);
572       if ( (NULL == mx) ||
573            (off != data_size) )
574       {
575         GNUNET_break_op (0);
576         return NULL;
577       }
578       GNUNET_asprintf (&result, 
579                        "%hu,%s", 
580                        mx->preference,
581                        mx->mxhost);
582       GNUNET_DNSPARSER_free_mx (mx);
583       return result;
584     }
585   case GNUNET_DNSPARSER_TYPE_TXT:
586     return GNUNET_strndup (data, data_size);
587   case GNUNET_DNSPARSER_TYPE_AAAA:
588     if (data_size != sizeof (struct in6_addr))
589       return NULL;
590     if (NULL == inet_ntop (AF_INET6, data, tmp, sizeof (tmp)))
591       return NULL;
592     return GNUNET_strdup (tmp);
593   case GNUNET_NAMESTORE_TYPE_PKEY:
594     if (data_size != sizeof (struct GNUNET_CRYPTO_EccPublicSignKey))
595       return NULL;
596     return GNUNET_CRYPTO_ecc_public_sign_key_to_string (data);
597   case GNUNET_NAMESTORE_TYPE_PSEU:
598     return GNUNET_strndup (data, data_size);
599   case GNUNET_NAMESTORE_TYPE_LEHO:
600     return GNUNET_strndup (data, data_size);
601   case GNUNET_NAMESTORE_TYPE_VPN:
602     cdata = data;
603     if ( (data_size <= sizeof (struct GNUNET_TUN_GnsVpnRecord)) ||
604          ('\0' != cdata[data_size - 1]) )
605       return NULL; /* malformed */
606     vpn = data;
607     GNUNET_CRYPTO_hash_to_enc (&vpn->peer.hashPubKey, &s_peer);
608     if (0 == GNUNET_asprintf (&vpn_str, "%u %s %s",
609                               (unsigned int) ntohs (vpn->proto),
610                               (const char*) &s_peer,
611                               (const char*) &vpn[1]))
612     {
613       GNUNET_free (vpn_str);
614       return NULL;
615     }
616     return vpn_str;
617   case GNUNET_DNSPARSER_TYPE_SRV:
618     cdata = data;
619     if ( (data_size <= sizeof (struct GNUNET_TUN_DnsSrvRecord)) ||
620          ('\0' != cdata[data_size - 1]) )
621       return NULL; /* malformed */
622     srv = data;
623
624     if (0 == GNUNET_asprintf (&srv_str, 
625                               "%d %d %d %s",
626                               ntohs (srv->prio),
627                               ntohs (srv->weight),
628                               ntohs (srv->port),
629                               (const char *)&srv[1]))
630     {
631       GNUNET_free (srv_str);
632       return NULL;
633     }
634     return srv_str;
635   case GNUNET_DNSPARSER_TYPE_TLSA:
636     cdata = data;
637     if ( (data_size <= sizeof (struct GNUNET_TUN_DnsTlsaRecord)) ||
638          ('\0' != cdata[data_size - 1]) )
639       return NULL; /* malformed */
640     tlsa = data;
641     if (0 == GNUNET_asprintf (&tlsa_str, 
642                               "%c %c %c %s",
643                               tlsa->usage,
644                               tlsa->selector,
645                               tlsa->matching_type,
646                               (const char *) &tlsa[1]))
647     {
648       GNUNET_free (tlsa_str);
649       return NULL;
650     }
651     return tlsa_str;
652   default:
653     GNUNET_break (0);
654   }
655   GNUNET_break (0); // not implemented
656   return NULL;
657 }
658
659
660 /**
661  * Convert human-readable version of a 'value' of a record to the binary
662  * representation.
663  *
664  * @param type type of the record
665  * @param s human-readable string
666  * @param data set to value in binary encoding (will be allocated)
667  * @param data_size set to number of bytes in @a data
668  * @return #GNUNET_OK on success
669  */
670 int
671 GNUNET_NAMESTORE_string_to_value (uint32_t type,
672                                   const char *s,
673                                   void **data,
674                                   size_t *data_size)
675 {
676   struct in_addr value_a;
677   struct in6_addr value_aaaa;
678   struct GNUNET_CRYPTO_EccPublicSignKey pkey;
679   struct GNUNET_TUN_DnsSoaRecord *soa;
680   struct GNUNET_TUN_GnsVpnRecord *vpn;
681   struct GNUNET_TUN_DnsTlsaRecord *tlsa;
682   char soa_rname[253 + 1];
683   char soa_mname[253 + 1];
684   char s_peer[103 + 1];
685   char s_serv[253 + 1];
686   unsigned int soa_serial;
687   unsigned int soa_refresh;
688   unsigned int soa_retry;
689   unsigned int soa_expire;
690   unsigned int soa_min;
691   unsigned int proto;
692   
693   if (NULL == s)
694     return GNUNET_SYSERR;
695   switch (type)
696   {
697   case 0:
698     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
699                 _("Unsupported record type %d\n"),
700                 (int) type);
701     return GNUNET_SYSERR;
702   case GNUNET_DNSPARSER_TYPE_A:
703     if (1 != inet_pton (AF_INET, s, &value_a))
704     {
705       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
706                   _("Unable to parse IPv4 address `%s'\n"),
707                   s);
708       return GNUNET_SYSERR;
709     }
710     *data = GNUNET_malloc (sizeof (struct in_addr));
711     memcpy (*data, &value_a, sizeof (value_a));
712     *data_size = sizeof (value_a);
713     return GNUNET_OK;
714   case GNUNET_DNSPARSER_TYPE_NS:
715     *data = GNUNET_strdup (s);
716     *data_size = strlen (s) + 1;
717     return GNUNET_OK;
718   case GNUNET_DNSPARSER_TYPE_CNAME:
719     *data = GNUNET_strdup (s);
720     *data_size = strlen (s) + 1;
721     return GNUNET_OK;
722   case GNUNET_DNSPARSER_TYPE_SOA:
723     if (7 != SSCANF (s, 
724                      "rname=%253s mname=%253s %u,%u,%u,%u,%u",
725                      soa_rname, soa_mname,
726                      &soa_serial, &soa_refresh, &soa_retry, &soa_expire, &soa_min))
727     {
728       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
729                   _("Unable to parse SOA record `%s'\n"),
730                   s);
731       return GNUNET_SYSERR;
732     }
733     *data_size = sizeof (struct GNUNET_TUN_DnsSoaRecord) + strlen(soa_rname) + strlen(soa_mname) + 2;
734     *data = GNUNET_malloc (*data_size);
735     soa = (struct GNUNET_TUN_DnsSoaRecord*)*data;
736     soa->serial = htonl(soa_serial);
737     soa->refresh = htonl(soa_refresh);
738     soa->retry = htonl(soa_retry);
739     soa->expire = htonl(soa_expire);
740     soa->minimum = htonl(soa_min);
741     strcpy((char*)&soa[1], soa_rname);
742     strcpy((char*)&soa[1]+strlen(*data)+1, soa_mname);
743     return GNUNET_OK;
744   case GNUNET_DNSPARSER_TYPE_PTR:
745     *data = GNUNET_strdup (s);
746     *data_size = strlen (s);
747     return GNUNET_OK;
748   case GNUNET_DNSPARSER_TYPE_MX:
749     {
750       struct GNUNET_DNSPARSER_MxRecord mx;
751       char mxbuf[258];
752       char mxhost[253 + 1];
753       uint16_t mx_pref;
754       size_t off;
755
756       if (2 != SSCANF(s, "%hu,%253s", &mx_pref, mxhost))
757       {
758         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
759                     _("Unable to parse MX record `%s'\n"),
760                     s);
761       return GNUNET_SYSERR;
762       }
763       mx.preference = mx_pref;
764       mx.mxhost = mxhost;
765       off = 0;
766
767       if (GNUNET_OK !=
768           GNUNET_DNSPARSER_builder_add_mx (mxbuf,
769                                            sizeof (mxbuf),
770                                            &off,
771                                            &mx))
772       {
773         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
774                     _("Failed to serialize MX record with hostname `%s'\n"),
775                     mxhost);
776         return GNUNET_SYSERR;
777       }
778       *data_size = off;
779       *data = GNUNET_malloc (off);
780       memcpy (*data, mxbuf, off);
781       return GNUNET_OK;
782     }
783   case GNUNET_DNSPARSER_TYPE_TXT:
784     *data = GNUNET_strdup (s);
785     *data_size = strlen (s);
786     return GNUNET_OK;
787   case GNUNET_DNSPARSER_TYPE_AAAA:
788     if (1 != inet_pton (AF_INET6, s, &value_aaaa))    
789     {
790       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
791                   _("Unable to parse IPv6 address `%s'\n"),
792                   s);
793       return GNUNET_SYSERR;
794     }
795     *data = GNUNET_malloc (sizeof (struct in6_addr));
796     *data_size = sizeof (struct in6_addr);
797     memcpy (*data, &value_aaaa, sizeof (value_aaaa));
798     return GNUNET_OK;
799   case GNUNET_NAMESTORE_TYPE_PKEY:
800     if (GNUNET_OK !=
801         GNUNET_CRYPTO_ecc_public_sign_key_from_string (s, strlen (s), &pkey))
802     {
803       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
804                   _("Unable to parse PKEY record `%s'\n"),
805                   s);
806       return GNUNET_SYSERR;
807     }
808     *data = GNUNET_new (struct GNUNET_CRYPTO_EccPublicSignKey);
809     memcpy (*data, &pkey, sizeof (pkey));
810     *data_size = sizeof (struct GNUNET_CRYPTO_EccPublicSignKey);
811     return GNUNET_OK;
812   case GNUNET_NAMESTORE_TYPE_PSEU:
813     *data = GNUNET_strdup (s);
814     *data_size = strlen (s);
815     return GNUNET_OK;
816   case GNUNET_NAMESTORE_TYPE_LEHO:
817     *data = GNUNET_strdup (s);
818     *data_size = strlen (s);
819     return GNUNET_OK;
820   case GNUNET_NAMESTORE_TYPE_VPN:
821     if (3 != SSCANF (s,"%u %103s %253s",
822                      &proto, s_peer, s_serv))
823     {
824       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
825                   _("Unable to parse VPN record string `%s'\n"),
826                   s);
827       return GNUNET_SYSERR;
828     }
829     *data_size = sizeof (struct GNUNET_TUN_GnsVpnRecord) + strlen (s_serv) + 1;
830     *data = vpn = GNUNET_malloc (*data_size);
831     if (GNUNET_OK != GNUNET_CRYPTO_hash_from_string ((char*)&s_peer,
832                                                      &vpn->peer.hashPubKey))
833     {
834       GNUNET_free (vpn);
835       *data_size = 0;
836       return GNUNET_SYSERR;
837     }
838     vpn->proto = htons ((uint16_t) proto);
839     strcpy ((char*)&vpn[1], s_serv);
840     return GNUNET_OK;
841   case GNUNET_DNSPARSER_TYPE_TLSA:
842     *data_size = sizeof (struct GNUNET_TUN_DnsTlsaRecord) + strlen (s) - 6;
843     *data = tlsa = GNUNET_malloc (*data_size);
844     if (4 != SSCANF (s, "%c %c %c %s",
845                      &tlsa->usage,
846                      &tlsa->selector,
847                      &tlsa->matching_type,
848                      (char*)&tlsa[1]))
849     {
850       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
851                   _("Unable to parse TLSA record string `%s'\n"), 
852                   s);
853       *data_size = 0;
854       GNUNET_free (tlsa);
855       return GNUNET_SYSERR;
856     }
857     return GNUNET_OK;
858   default:
859     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
860                 _("Unsupported record type %d\n"),
861                 (int) type);
862     return GNUNET_SYSERR;
863   }
864 }
865
866
867 /**
868  * Mapping of record type numbers to human-readable
869  * record type names.
870  */
871 static struct { 
872   const char *name; 
873   uint32_t number; 
874 } name_map[] = {
875   { "A", GNUNET_DNSPARSER_TYPE_A },
876   { "NS", GNUNET_DNSPARSER_TYPE_NS },
877   { "CNAME", GNUNET_DNSPARSER_TYPE_CNAME },
878   { "SOA", GNUNET_DNSPARSER_TYPE_SOA },
879   { "PTR", GNUNET_DNSPARSER_TYPE_PTR },
880   { "MX", GNUNET_DNSPARSER_TYPE_MX },
881   { "TXT", GNUNET_DNSPARSER_TYPE_TXT },
882   { "AAAA", GNUNET_DNSPARSER_TYPE_AAAA },
883   { "PKEY",  GNUNET_NAMESTORE_TYPE_PKEY },
884   { "PSEU",  GNUNET_NAMESTORE_TYPE_PSEU },
885   { "LEHO",  GNUNET_NAMESTORE_TYPE_LEHO },
886   { "VPN", GNUNET_NAMESTORE_TYPE_VPN },
887   { "TLSA", GNUNET_DNSPARSER_TYPE_TLSA },
888   { NULL, UINT32_MAX }
889 };
890
891
892 /**
893  * Convert a type name (i.e. "AAAA") to the corresponding number.
894  *
895  * @param typename name to convert
896  * @return corresponding number, UINT32_MAX on error
897  */
898 uint32_t
899 GNUNET_NAMESTORE_typename_to_number (const char *typename)
900 {
901   unsigned int i;
902
903   i=0;
904   while ( (name_map[i].name != NULL) &&
905           (0 != strcasecmp (typename, name_map[i].name)) )
906     i++;
907   return name_map[i].number;  
908 }
909
910
911 /**
912  * Convert a type number (i.e. 1) to the corresponding type string (i.e. "A")
913  *
914  * @param type number of a type to convert
915  * @return corresponding typestring, NULL on error
916  */
917 const char *
918 GNUNET_NAMESTORE_number_to_typename (uint32_t type)
919 {
920   unsigned int i;
921
922   i=0;
923   while ( (name_map[i].name != NULL) &&
924           (type != name_map[i].number) )
925     i++;
926   return name_map[i].name;  
927 }
928
929
930 /**
931  * Test if a given record is expired.
932  * 
933  * @return #GNUNET_YES if the record is expired,
934  *         #GNUNET_NO if not
935  */
936 int
937 GNUNET_NAMESTORE_is_expired (const struct GNUNET_NAMESTORE_RecordData *rd)
938 {
939   struct GNUNET_TIME_Absolute at;
940
941   if (0 != (rd->flags & GNUNET_NAMESTORE_RF_RELATIVE_EXPIRATION))
942     return GNUNET_NO;
943   at.abs_value_us = rd->expiration_time;
944   return (0 == GNUNET_TIME_absolute_get_remaining (at).rel_value_us) ? GNUNET_YES : GNUNET_NO;
945 }
946
947
948 /**
949  * Calculate the DHT query for a given @a label in a given @a zone.
950  * 
951  * @param zone private key of the zone
952  * @param label label of the record
953  * @param query hash to use for the query
954  */
955 void
956 GNUNET_NAMESTORE_query_from_private_key (const struct GNUNET_CRYPTO_EccPrivateKey *zone,
957                                          const char *label,
958                                          struct GNUNET_HashCode *query)
959 {
960   struct GNUNET_CRYPTO_EccPublicSignKey pub;
961
962   GNUNET_CRYPTO_ecc_key_get_public_for_signature (zone, &pub);
963   GNUNET_NAMESTORE_query_from_public_key (&pub, label, query);
964 }
965
966
967 /**
968  * Calculate the DHT query for a given @a label in a given @a zone.
969  * 
970  * @param pub public key of the zone
971  * @param label label of the record
972  * @param query hash to use for the query
973  */
974 void
975 GNUNET_NAMESTORE_query_from_public_key (const struct GNUNET_CRYPTO_EccPublicSignKey *pub,
976                                         const char *label,
977                                         struct GNUNET_HashCode *query)
978 {
979   struct GNUNET_CRYPTO_EccPublicSignKey pd;
980
981   GNUNET_CRYPTO_ecc_public_key_derive (pub, label, "gns", &pd);
982   GNUNET_CRYPTO_hash (&pd, sizeof (pd), query);
983 }
984
985
986 /**
987  * Convert public key to the respective absolute domain name in the
988  * ".zkey" pTLD. 
989  * This is one of the very few calls in the entire API that is
990  * NOT reentrant!
991  * 
992  * @param pkey a public key with a point on the eliptic curve 
993  * @return string "X.zkey" where X is the public 
994  *         key in an encoding suitable for DNS labels.
995  */
996 const char *
997 GNUNET_NAMESTORE_pkey_to_zkey (const struct GNUNET_CRYPTO_EccPublicSignKey *pkey)
998 {
999   static char ret[128];
1000   char *pkeys;
1001
1002   pkeys = GNUNET_CRYPTO_ecc_public_sign_key_to_string (pkey);
1003   GNUNET_snprintf (ret,
1004                    sizeof (ret),
1005                    "%s.zkey",
1006                    pkeys);
1007   GNUNET_free (pkeys);
1008   return ret;
1009 }
1010
1011
1012 /**
1013  * Convert an absolute domain name in the ".zkey" pTLD to the
1014  * respective public key.
1015  * 
1016  * @param zkey string "X.zkey" where X is the coordinates of the public
1017  *         key in an encoding suitable for DNS labels.
1018  * @param pkey set to a public key on the eliptic curve 
1019  * @return #GNUNET_SYSERR if @a zkey has the wrong syntax
1020  */
1021 int
1022 GNUNET_NAMESTORE_zkey_to_pkey (const char *zkey,
1023                                struct GNUNET_CRYPTO_EccPublicSignKey *pkey)
1024 {
1025   char *cpy;
1026   char *dot;
1027   const char *x;
1028     
1029   cpy = GNUNET_strdup (zkey);
1030   x = cpy;
1031   if (NULL == (dot = strchr (x, (int) '.')))
1032     goto error;
1033   *dot = '\0';
1034   if (0 != strcasecmp (dot + 1, 
1035                        "zkey"))
1036     goto error;
1037
1038   if (GNUNET_OK !=
1039       GNUNET_CRYPTO_ecc_public_sign_key_from_string (x,
1040                                                 strlen (x),
1041                                                 pkey))
1042     goto error;
1043   GNUNET_free (cpy);
1044   return GNUNET_OK;
1045  error:
1046   GNUNET_free (cpy);
1047   return GNUNET_SYSERR;
1048 }
1049
1050
1051 /* end of namestore_common.c */