add support for /etc/hosts
[oweals/gnunet.git] / src / util / gnunet-service-resolver.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2007-2016 GNUnet e.V.
4
5      GNUnet is free software: you can redistribute it and/or modify it
6      under the terms of the GNU Affero General Public License as published
7      by the Free Software Foundation, either version 3 of the License,
8      or (at your 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      Affero General Public License for more details.
14
15      You should have received a copy of the GNU Affero General Public License
16      along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 /**
20  * @file util/gnunet-service-resolver.c
21  * @brief code to do DNS resolution
22  * @author Christian Grothoff
23  */
24 #include "platform.h"
25 #include "gnunet_util_lib.h"
26 #include "gnunet_protocols.h"
27 #include "gnunet_statistics_service.h"
28 #include "resolver.h"
29
30
31 /**
32  * How long do we wait for DNS answers?
33  */
34 #define DNS_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)
35
36 /**
37  * Maximum number of hostnames we cache results for.
38  */
39 #define MAX_CACHE 1024
40
41 /**
42  * Entry in list of cached DNS records for a hostname.
43  */
44 struct RecordListEntry
45 {
46   /**
47    * This is a doubly linked list.
48    */
49   struct RecordListEntry *next;
50
51   /**
52    * This is a doubly linked list.
53    */
54   struct RecordListEntry *prev;
55
56   /**
57    * Cached data.
58    */
59   struct GNUNET_DNSPARSER_Record *record;
60
61 };
62
63
64 /**
65  * A cached DNS lookup result.
66  */
67 struct ResolveCache
68 {
69   /**
70    * This is a doubly linked list.
71    */
72   struct ResolveCache *next;
73
74   /**
75    * This is a doubly linked list.
76    */
77   struct ResolveCache *prev;
78
79   /**
80    * Which hostname is this cache for?
81    */
82   char *hostname;
83
84   /**
85    * head of a double linked list containing the lookup results
86    */
87   struct RecordListEntry *records_head;
88
89   /**
90    * tail of a double linked list containing the lookup results
91    */
92   struct RecordListEntry *records_tail;
93
94 };
95
96
97 /**
98  * Information about pending lookups.
99  */
100 struct ActiveLookup
101 {
102   /**
103    * Stored in a DLL.
104    */
105   struct ActiveLookup *next;
106
107   /**
108    * Stored in a DLL.
109    */
110   struct ActiveLookup *prev;
111
112   /**
113    * The client that queried the records contained in this cache entry.
114    */
115   struct GNUNET_SERVICE_Client *client;
116
117   /**
118    * handle for cancelling a request
119    */
120   struct GNUNET_DNSSTUB_RequestSocket *resolve_handle;
121
122   /**
123    * handle for the resolution timeout task
124    */
125   struct GNUNET_SCHEDULER_Task *timeout_task;
126
127   /**
128    * Which hostname are we resolving?
129    */
130   char *hostname;
131
132   /**
133    * If @a record_type is #GNUNET_DNSPARSER_TYPE_ALL, did we go again
134    * for the AAAA records yet?
135    */
136   int did_aaaa;
137
138   /**
139    * type of queried DNS record
140    */
141   uint16_t record_type;
142
143   /**
144    * Unique request ID of a client if a query for this hostname/record_type
145    * is currently pending, undefined otherwise.
146    */
147   uint32_t client_request_id;
148
149   /**
150    * Unique DNS request ID of a client if a query for this hostname/record_type
151    * is currently pending, undefined otherwise.
152    */
153   uint16_t dns_id;
154
155 };
156
157
158 /**
159  * Start of the linked list of cached DNS lookup results.
160  */
161 static struct ResolveCache *cache_head;
162
163 /**
164  * Tail of the linked list of cached DNS lookup results.
165  */
166 static struct ResolveCache *cache_tail;
167
168 /**
169  * Head of the linked list of DNS lookup results from /etc/hosts.
170  */
171 static struct ResolveCache *hosts_head;
172
173 /**
174  * Tail of the linked list of DNS lookup results from /etc/hosts.
175  */
176 static struct ResolveCache *hosts_tail;
177
178 /**
179  * Start of the linked list of active DNS lookups.
180  */
181 static struct ActiveLookup *lookup_head;
182
183 /**
184  * Tail of the linked list of active DNS lookups.
185  */
186 static struct ActiveLookup *lookup_tail;
187
188 /**
189  * context of dnsstub library
190  */
191 static struct GNUNET_DNSSTUB_Context *dnsstub_ctx;
192
193 /**
194  * My domain, to be appended to the hostname to get a FQDN.
195  */
196 static char *my_domain;
197
198 /**
199  * How many entries do we have in #cache_head DLL?
200  */
201 static unsigned int cache_size;
202
203
204 /**
205  * Remove @a entry from cache.
206  *
207  * @param rc entry to free
208  */
209 static void
210 free_cache_entry (struct ResolveCache *rc)
211 {
212   struct RecordListEntry *pos;
213
214   while (NULL != (pos = rc->records_head))
215   {
216     GNUNET_CONTAINER_DLL_remove (rc->records_head,
217                                  rc->records_tail,
218                                  pos);
219     GNUNET_DNSPARSER_free_record (pos->record);
220     GNUNET_free (pos->record);
221     GNUNET_free (pos);
222   }
223   GNUNET_free_non_null (rc->hostname);
224   GNUNET_CONTAINER_DLL_remove (cache_head,
225                                cache_tail,
226                                rc);
227   cache_size--;
228   GNUNET_free (rc);
229 }
230
231
232 /**
233  * Remove @a entry from cache.
234  *
235  * @param rc entry to free
236  */
237 static void
238 free_hosts_entry (struct ResolveCache *rc)
239 {
240   struct RecordListEntry *pos;
241
242   while (NULL != (pos = rc->records_head))
243   {
244     GNUNET_CONTAINER_DLL_remove (rc->records_head,
245                                  rc->records_tail,
246                                  pos);
247     GNUNET_DNSPARSER_free_record (pos->record);
248     GNUNET_free (pos->record);
249     GNUNET_free (pos);
250   }
251   GNUNET_free_non_null (rc->hostname);
252   GNUNET_CONTAINER_DLL_remove (hosts_head,
253                                hosts_tail,
254                                rc);
255   cache_size--;
256   GNUNET_free (rc);
257 }
258
259
260 /**
261  * Release resources associated with @a al
262  *
263  * @param al an active lookup
264  */
265 static void
266 free_active_lookup (struct ActiveLookup *al)
267 {
268   GNUNET_CONTAINER_DLL_remove (lookup_head,
269                                lookup_tail,
270                                al);
271   if (NULL != al->resolve_handle)
272   {
273     GNUNET_DNSSTUB_resolve_cancel (al->resolve_handle);
274     al->resolve_handle = NULL;
275   }
276   if (NULL != al->timeout_task)
277   {
278     GNUNET_SCHEDULER_cancel (al->timeout_task);
279     al->timeout_task = NULL;
280   }
281   GNUNET_free_non_null (al->hostname);
282   GNUNET_free (al);
283 }
284
285
286
287 /**
288  * Find out if the configuration file line contains a string
289  * starting with "nameserver ", and if so, return a copy of
290  * the nameserver's IP.
291  *
292  * @param line line to parse
293  * @param line_len number of characters in @a line
294  * @return NULL if no nameserver is configured in this @a line
295  */
296 static char *
297 extract_dns_server (const char* line,
298                     size_t line_len)
299 {
300   if (0 == strncmp (line,
301                     "nameserver ",
302                     strlen ("nameserver ")))
303     return GNUNET_strndup (line + strlen ("nameserver "),
304                            line_len - strlen ("nameserver "));
305   return NULL;
306 }
307
308
309 /**
310  * Find out if the configuration file line contains a string
311  * starting with "search ", and if so, return a copy of
312  * the machine's search domain.
313  *
314  * @param line line to parse
315  * @param line_len number of characters in @a line
316  * @return NULL if no nameserver is configured in this @a line
317  */
318 static char *
319 extract_search_domain (const char* line,
320                        size_t line_len)
321 {
322   if (0 == strncmp (line,
323                     "search ",
324                     strlen ("search ")))
325     return GNUNET_strndup (line + strlen ("search "),
326                            line_len - strlen ("search "));
327   return NULL;
328 }
329
330
331 /**
332  * Reads the list of nameservers from /etc/resolve.conf
333  *
334  * @param server_addrs[out] a list of null-terminated server address strings
335  * @return the number of server addresses in @server_addrs, -1 on error
336  */
337 static int
338 lookup_dns_servers (char ***server_addrs)
339 {
340   struct GNUNET_DISK_FileHandle *fh;
341   struct GNUNET_DISK_MapHandle *mh;
342   off_t bytes_read;
343   const char *buf;
344   size_t read_offset;
345   unsigned int num_dns_servers;
346
347   fh = GNUNET_DISK_file_open ("/etc/resolv.conf",
348                               GNUNET_DISK_OPEN_READ,
349                               GNUNET_DISK_PERM_NONE);
350   if (NULL == fh)
351   {
352     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
353                 "Could not open /etc/resolv.conf. "
354                 "DNS resolution will not be possible.\n");
355     return -1;
356   }
357   if (GNUNET_OK !=
358       GNUNET_DISK_file_handle_size (fh,
359                                     &bytes_read))
360   {
361     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
362                 "Could not determine size of /etc/resolv.conf. "
363                 "DNS resolution will not be possible.\n");
364     GNUNET_DISK_file_close (fh);
365     return -1;
366   }
367   if (bytes_read > SIZE_MAX)
368   { 
369     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
370                 "/etc/resolv.conf file too large to mmap. "
371                 "DNS resolution will not be possible.\n");
372     GNUNET_DISK_file_close (fh);
373     return -1;   
374   }
375   buf = GNUNET_DISK_file_map (fh,
376                               &mh,
377                               GNUNET_DISK_MAP_TYPE_READ,
378                               (size_t) bytes_read);
379   *server_addrs = NULL;
380   read_offset = 0;
381   num_dns_servers = 0;
382   while (read_offset < bytes_read)
383   {
384     const char *newline;
385     size_t line_len;
386     char *dns_server;
387
388     newline = strchr (buf + read_offset,
389                       '\n');
390     if (NULL == newline)
391       break;
392     line_len = newline - buf - read_offset;
393     dns_server = extract_dns_server (buf + read_offset,
394                                      line_len);
395     if (NULL != dns_server)
396     {
397       GNUNET_array_append (*server_addrs,
398                            num_dns_servers,
399                            dns_server);
400     }
401     else if (NULL == my_domain)
402     {
403       my_domain = extract_search_domain (buf + read_offset,
404                                          line_len);
405     }
406     read_offset += line_len + 1;
407   }
408   GNUNET_DISK_file_unmap (mh);
409   GNUNET_DISK_file_close (fh);
410   return (int) num_dns_servers;
411 }
412
413
414 /**
415  * Compute name to use for DNS reverse lookups from @a ip.
416  *
417  * @param ip IP address to resolve, in binary format, network byte order
418  * @param af address family of @a ip, AF_INET or AF_INET6
419  */
420 static char *
421 make_reverse_hostname (const void *ip,
422                        int af)
423 {
424   char *buf = GNUNET_new_array (80,
425                                 char);
426   int pos = 0;
427
428   if (AF_INET == af)
429   {
430     struct in_addr *addr = (struct in_addr *)ip;
431     uint32_t ip_int = addr->s_addr;
432
433     for (int i = 3; i >= 0; i--)
434     {
435       int n = GNUNET_snprintf (buf + pos,
436                                80 - pos,
437                                "%u.",
438                                ((uint8_t *)&ip_int)[i]);
439       if (n < 0)
440       {
441         GNUNET_free (buf);
442         return NULL;
443       }
444       pos += n;
445     }
446     pos += GNUNET_snprintf (buf + pos,
447                             80 - pos,
448                             "in-addr.arpa");
449   }
450   else if (AF_INET6 == af)
451   {
452     struct in6_addr *addr = (struct in6_addr *)ip;
453     for (int i = 15; i >= 0; i--)
454     {
455       int n = GNUNET_snprintf (buf + pos,
456                                80 - pos,
457                                "%x.",
458                                addr->s6_addr[i] & 0xf);
459       if (n < 0)
460       {
461         GNUNET_free (buf);
462         return NULL;
463       }
464       pos += n;
465       n = GNUNET_snprintf (buf + pos,
466                            80 - pos,
467                            "%x.",
468                            addr->s6_addr[i] >> 4);
469       if (n < 0)
470       {
471         GNUNET_free (buf);
472         return NULL;
473       }
474       pos += n;
475     }
476     pos += GNUNET_snprintf (buf + pos,
477                             80 - pos,
478                             "ip6.arpa");
479   }
480   buf[pos] = '\0';
481   return buf;
482 }
483
484
485 /**
486  * Send DNS @a record back to our @a client.
487  *
488  * @param record information to transmit
489  * @param record_type requested record type from client
490  * @param client_request_id to which request are we responding
491  * @param client where to send @a record
492  * @return #GNUNET_YES if we sent a reply,
493  *         #GNUNET_NO if the record type is not understood or
494  *         does not match @a record_type
495  */
496 static int
497 send_reply (struct GNUNET_DNSPARSER_Record *record,
498             uint16_t record_type,
499             uint32_t client_request_id,
500             struct GNUNET_SERVICE_Client *client)
501 {
502   struct GNUNET_RESOLVER_ResponseMessage *msg;
503   struct GNUNET_MQ_Envelope *env;
504   const void *payload;
505   size_t payload_len;
506
507   switch (record->type)
508   {
509   case GNUNET_DNSPARSER_TYPE_CNAME:
510     if (GNUNET_DNSPARSER_TYPE_CNAME != record_type)
511       return GNUNET_NO;
512     payload = record->data.hostname;
513     payload_len = strlen (record->data.hostname) + 1;
514     break;
515   case GNUNET_DNSPARSER_TYPE_PTR:
516     if (GNUNET_DNSPARSER_TYPE_PTR != record_type)
517       return GNUNET_NO;
518     payload = record->data.hostname;
519     payload_len = strlen (record->data.hostname) + 1;
520     break;
521   case GNUNET_DNSPARSER_TYPE_A:
522     if ( (GNUNET_DNSPARSER_TYPE_A != record_type) &&
523          (GNUNET_DNSPARSER_TYPE_ALL != record_type) )
524       return GNUNET_NO;
525     payload = record->data.raw.data;
526     payload_len = record->data.raw.data_len;
527     break;
528   case GNUNET_DNSPARSER_TYPE_AAAA:
529     if ( (GNUNET_DNSPARSER_TYPE_AAAA != record_type) &&
530          (GNUNET_DNSPARSER_TYPE_ALL != record_type) )
531       return GNUNET_NO;
532     payload = record->data.raw.data;
533     payload_len = record->data.raw.data_len;
534     break;
535   default:
536     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
537                 "Cannot handle DNS response type %u: not supported here\n",
538                 record->type);
539     return GNUNET_NO;
540   }
541   env = GNUNET_MQ_msg_extra (msg,
542                              payload_len,
543                              GNUNET_MESSAGE_TYPE_RESOLVER_RESPONSE);
544   msg->client_id = client_request_id;
545   GNUNET_memcpy (&msg[1],
546                  payload,
547                  payload_len);
548   GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq (client),
549                   env);
550   return GNUNET_YES;
551 }
552
553
554 /**
555  * Send message to @a client that we transmitted all
556  * responses for @a client_request_id
557  *
558  * @param client_request_id to which request are we responding
559  * @param client where to send @a record
560  */
561 static void
562 send_end_msg (uint32_t client_request_id,
563               struct GNUNET_SERVICE_Client *client)
564 {
565   struct GNUNET_RESOLVER_ResponseMessage *msg;
566   struct GNUNET_MQ_Envelope *env;
567
568   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
569               "Sending END message\n");
570   env = GNUNET_MQ_msg (msg,
571                        GNUNET_MESSAGE_TYPE_RESOLVER_RESPONSE);
572   msg->client_id = client_request_id;
573   GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq (client),
574                   env);
575 }
576
577
578 /**
579  * Remove expired entries from @a rc
580  *
581  * @param rc entry in resolver cache
582  * @return #GNUNET_YES if @a rc was completely expired
583  *         #GNUNET_NO if some entries are left
584  */
585 static int
586 remove_expired (struct ResolveCache *rc)
587 {
588   struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get ();
589   struct RecordListEntry *n;
590
591   for (struct RecordListEntry *pos = rc->records_head;
592        NULL != pos;
593        pos = n)
594   {
595     n = pos->next;
596     if (now.abs_value_us > pos->record->expiration_time.abs_value_us)
597     {
598       GNUNET_CONTAINER_DLL_remove (rc->records_head,
599                                    rc->records_tail,
600                                    pos);
601       GNUNET_DNSPARSER_free_record (pos->record);
602       GNUNET_free (pos->record);
603       GNUNET_free (pos);      
604     }
605   }
606   if (NULL == rc->records_head)
607   {
608     free_cache_entry (rc);
609     return GNUNET_YES;
610   }
611   return GNUNET_NO;
612 }
613
614
615 /**
616  * Process DNS request for @a hostname with request ID @a request_id
617  * from @a client demanding records of type @a record_type.
618  *
619  * @param hostname DNS name to resolve
620  * @param record_type desired record type
621  * @param client_request_id client's request ID
622  * @param client who should get the result?
623  */
624 static void
625 process_get (const char *hostname,
626              uint16_t record_type,
627              uint32_t client_request_id,
628              struct GNUNET_SERVICE_Client *client);
629
630
631 /**
632  * Get an IP address as a string (works for both IPv4 and IPv6).  Note
633  * that the resolution happens asynchronously and that the first call
634  * may not immediately result in the FQN (but instead in a
635  * human-readable IP address).
636  *
637  * @param hostname what hostname was to be resolved
638  * @param record_type what type of record was requested
639  * @param client_request_id unique identification of the client's request
640  * @param client handle to the client making the request (for sending the reply)
641  */
642 static int
643 try_cache (const char *hostname,
644            uint16_t record_type,
645            uint32_t client_request_id,
646            struct GNUNET_SERVICE_Client *client)
647 {
648   struct ResolveCache *pos;
649   struct ResolveCache *next;
650   int found;
651
652   for (pos = hosts_head; NULL != pos; pos = pos->next)
653     if (0 == strcmp (pos->hostname,
654                      hostname))
655       break;
656   if (NULL == pos)
657   {
658     next = cache_head;
659     for (pos = next; NULL != pos; pos = next)
660     {
661       next = pos->next;
662       if (GNUNET_YES == remove_expired (pos))
663         continue;
664       if (0 == strcmp (pos->hostname,
665                        hostname))
666         break;
667     }
668   }
669   if (NULL == pos)
670   {
671     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
672                 "No cache entry for '%s'\n",
673                 hostname);
674     return GNUNET_NO;
675   }
676   if (cache_head != pos)
677   {
678     /* move result to head to achieve LRU for cache eviction */
679     GNUNET_CONTAINER_DLL_remove (cache_head,
680                                  cache_tail,
681                                  pos);
682     GNUNET_CONTAINER_DLL_insert (cache_head,
683                                  cache_tail,
684                                  pos);
685   }
686   found = GNUNET_NO;
687   for (struct RecordListEntry *rle = pos->records_head;
688        NULL != rle;
689        rle = rle->next)
690   {
691     const struct GNUNET_DNSPARSER_Record *record = rle->record;
692
693     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
694                 "Found cache entry for '%s', record type '%u'\n",
695                 hostname,
696                 record_type);
697     if ( (GNUNET_DNSPARSER_TYPE_CNAME == record->type) &&
698          (GNUNET_DNSPARSER_TYPE_CNAME != record_type) &&
699          (GNUNET_NO == found) )
700     {
701       const char *hostname = record->data.hostname;
702
703       process_get (hostname,
704                    record_type,
705                    client_request_id,
706                    client);
707       return GNUNET_YES; /* counts as a cache "hit" */
708     }
709     found |= send_reply (rle->record,
710                          record_type,
711                          client_request_id,
712                          client);
713   }
714   if (GNUNET_NO == found)
715     return GNUNET_NO; /* had records, but none matched! */
716   send_end_msg (client_request_id,
717                 client);
718   return GNUNET_YES;
719 }
720
721
722 /**
723  * Create DNS query for @a hostname of type @a type
724  * with DNS request ID @a dns_id.
725  *
726  * @param hostname DNS name to query
727  * @param type requested DNS record type
728  * @param dns_id what should be the DNS request ID
729  * @param packet_buf[out] where to write the request packet
730  * @param packet_size[out] set to size of @a packet_buf on success
731  * @return #GNUNET_OK on success
732  */
733 static int
734 pack (const char *hostname,
735       uint16_t type,
736       uint16_t dns_id,
737       char **packet_buf,
738       size_t *packet_size)
739 {
740   struct GNUNET_DNSPARSER_Query query;
741   struct GNUNET_DNSPARSER_Packet packet;
742
743   query.name = (char *)hostname;
744   query.type = type;
745   query.dns_traffic_class = GNUNET_TUN_DNS_CLASS_INTERNET;
746   memset (&packet,
747           0,
748           sizeof (packet));
749   packet.num_queries = 1;
750   packet.queries = &query;
751   packet.id = htons (dns_id);
752   packet.flags.recursion_desired = 1;
753   if (GNUNET_OK !=
754       GNUNET_DNSPARSER_pack (&packet,
755                              UINT16_MAX,
756                              packet_buf,
757                              packet_size))
758   {
759     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
760                 "Failed to pack query for hostname `%s'\n",
761                 hostname);
762     packet_buf = NULL;
763     return GNUNET_SYSERR;
764   }
765   return GNUNET_OK;
766 }
767
768
769 /**
770  * We got a result from DNS. Add it to the cache and
771  * see if we can make our client happy...
772  *
773  * @param cls the `struct ActiveLookup`
774  * @param dns the DNS response
775  * @param dns_len number of bytes in @a dns
776  */
777 static void
778 handle_resolve_result (void *cls,
779                        const struct GNUNET_TUN_DnsHeader *dns,
780                        size_t dns_len)
781 {
782   struct ActiveLookup *al = cls;
783   struct GNUNET_DNSPARSER_Packet *parsed;
784   struct ResolveCache *rc;
785
786   parsed = GNUNET_DNSPARSER_parse ((const char *)dns,
787                                    dns_len);
788   if (NULL == parsed)
789   {
790     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
791                 "Failed to parse DNS reply (hostname %s, request ID %u)\n",
792                 al->hostname,
793                 al->dns_id);
794     return;
795   }
796   if (al->dns_id != ntohs (parsed->id))
797   {
798     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
799                 "Request ID in DNS reply does not match\n");
800     GNUNET_DNSPARSER_free_packet (parsed);
801     return;
802   }
803   if (0 == parsed->num_answers + parsed->num_authority_records + parsed->num_additional_records)
804   {
805     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
806                 "DNS reply (hostname %s, request ID %u) contains no answers\n",
807                 al->hostname,
808                 (unsigned int) al->client_request_id);
809     GNUNET_DNSPARSER_free_packet (parsed);
810     send_end_msg (al->client_request_id,
811                   al->client);
812     free_active_lookup (al);
813     return;
814   }
815   /* LRU-based cache eviction: we remove from tail */
816   while (cache_size > MAX_CACHE)
817     free_cache_entry (cache_tail);
818
819   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
820               "Got reply for hostname %s and request ID %u\n",
821               al->hostname,
822               (unsigned int) al->client_request_id);
823   /* add to cache */
824   for (unsigned int i = 0; i != parsed->num_answers; i++)
825   {
826     struct GNUNET_DNSPARSER_Record *record = &parsed->answers[i];
827     struct RecordListEntry *rle;
828
829     for (rc = cache_head; NULL != rc; rc = rc->next)
830       if (0 == strcasecmp (rc->hostname,
831                            record->name))
832         break;
833     if (NULL == rc)
834     {
835       rc = GNUNET_new (struct ResolveCache);
836       rc->hostname = GNUNET_strdup (record->name);
837       GNUNET_CONTAINER_DLL_insert (cache_head,
838                                    cache_tail,
839                                    rc);
840       cache_size++;
841     }
842     /* TODO: ought to check first if we have this exact record
843        already in the cache! */
844     rle = GNUNET_new (struct RecordListEntry);
845     rle->record = GNUNET_DNSPARSER_duplicate_record (record);
846     GNUNET_CONTAINER_DLL_insert (rc->records_head,
847                                  rc->records_tail,
848                                  rle);
849   }
850   for (unsigned int i = 0; i != parsed->num_authority_records; i++)
851   {
852     struct GNUNET_DNSPARSER_Record *record = &parsed->authority_records[i];
853     struct RecordListEntry *rle;
854
855     for (rc = cache_head; NULL != rc; rc = rc->next)
856       if (0 == strcasecmp (rc->hostname,
857                            record->name))
858         break;
859     if (NULL == rc)
860     {
861       rc = GNUNET_new (struct ResolveCache);
862       rc->hostname = GNUNET_strdup (record->name);
863       GNUNET_CONTAINER_DLL_insert (cache_head,
864                                    cache_tail,
865                                    rc);
866       cache_size++;
867     }
868     /* TODO: ought to check first if we have this exact record
869        already in the cache! */
870     rle = GNUNET_new (struct RecordListEntry);
871     rle->record = GNUNET_DNSPARSER_duplicate_record (record);
872     GNUNET_CONTAINER_DLL_insert (rc->records_head,
873                                  rc->records_tail,
874                                  rle);
875   }
876   for (unsigned int i = 0; i != parsed->num_additional_records; i++)
877   {
878     struct GNUNET_DNSPARSER_Record *record = &parsed->additional_records[i];
879     struct RecordListEntry *rle;
880
881     for (rc = cache_head; NULL != rc; rc = rc->next)
882       if (0 == strcasecmp (rc->hostname,
883                            record->name))
884         break;
885     if (NULL == rc)
886     {
887       rc = GNUNET_new (struct ResolveCache);
888       rc->hostname = GNUNET_strdup (record->name);
889       GNUNET_CONTAINER_DLL_insert (cache_head,
890                                    cache_tail,
891                                    rc);
892       cache_size++;
893     }
894     /* TODO: ought to check first if we have this exact record
895        already in the cache! */
896     rle = GNUNET_new (struct RecordListEntry);
897     rle->record = GNUNET_DNSPARSER_duplicate_record (record);
898     GNUNET_CONTAINER_DLL_insert (rc->records_head,
899                                  rc->records_tail,
900                                  rle);
901   }
902   /* see if we need to do the 2nd request for AAAA records */
903   if ( (GNUNET_DNSPARSER_TYPE_ALL == al->record_type) &&
904        (GNUNET_NO == al->did_aaaa) )
905   {
906     char *packet_buf;
907     size_t packet_size;
908     uint16_t dns_id;
909
910     dns_id = (uint16_t) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
911                                                   UINT16_MAX);
912     if (GNUNET_OK ==
913         pack (al->hostname,
914               GNUNET_DNSPARSER_TYPE_AAAA,
915               dns_id,
916               &packet_buf,
917               &packet_size))
918     {
919       al->did_aaaa = GNUNET_YES;
920       al->dns_id = dns_id;
921       GNUNET_DNSSTUB_resolve_cancel (al->resolve_handle);
922       al->resolve_handle =
923         GNUNET_DNSSTUB_resolve (dnsstub_ctx,
924                                 packet_buf,
925                                 packet_size,
926                                 &handle_resolve_result,
927                                 al);
928       GNUNET_free (packet_buf);
929       GNUNET_DNSPARSER_free_packet (parsed);
930       return;
931     }
932   }
933
934   /* resume by trying again from cache */
935   if (GNUNET_NO ==
936       try_cache (al->hostname,
937                  al->record_type,
938                  al->client_request_id,
939                  al->client))
940     /* cache failed, tell client we could not get an answer */
941   {
942     send_end_msg (al->client_request_id,
943                   al->client);
944   }
945   free_active_lookup (al);
946   GNUNET_DNSPARSER_free_packet (parsed);
947 }
948
949
950 /**
951  * We encountered a timeout trying to perform a
952  * DNS lookup.
953  *
954  * @param cls a `struct ActiveLookup`
955  */
956 static void
957 handle_resolve_timeout (void *cls)
958 {
959   struct ActiveLookup *al = cls;
960
961   al->timeout_task = NULL;
962   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
963               "DNS lookup timeout!\n");
964   send_end_msg (al->client_request_id,
965                 al->client);
966   free_active_lookup (al);
967 }
968
969
970 /**
971  * Initiate an active lookup, then cache the result and
972  * try to then complete the resolution.
973  *
974  * @param hostname DNS name to resolve
975  * @param record_type record type to locate
976  * @param client_request_id client request ID
977  * @param client handle to the client
978  * @return #GNUNET_OK if the DNS query is now pending
979  */
980 static int
981 resolve_and_cache (const char* hostname,
982                    uint16_t record_type,
983                    uint32_t client_request_id,
984                    struct GNUNET_SERVICE_Client *client)
985 {
986   char *packet_buf;
987   size_t packet_size;
988   struct ActiveLookup *al;
989   uint16_t dns_id;
990   uint16_t type;
991
992   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
993               "resolve_and_cache `%s'\n",
994               hostname);
995   dns_id = (uint16_t) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
996                                                 UINT16_MAX);
997
998   if (GNUNET_DNSPARSER_TYPE_ALL == record_type)
999     type = GNUNET_DNSPARSER_TYPE_A;
1000   else
1001     type = record_type;
1002   if (GNUNET_OK !=
1003       pack (hostname,
1004             type,
1005             dns_id,
1006             &packet_buf,
1007             &packet_size))
1008   {
1009     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1010                 "Failed to pack query for hostname `%s'\n",
1011                 hostname);
1012     return GNUNET_SYSERR;
1013   }
1014
1015   al = GNUNET_new (struct ActiveLookup);
1016   al->hostname = GNUNET_strdup (hostname);
1017   al->record_type = record_type;
1018   al->client_request_id = client_request_id;
1019   al->dns_id = dns_id;
1020   al->client = client;
1021   al->timeout_task = GNUNET_SCHEDULER_add_delayed (DNS_TIMEOUT,
1022                                                    &handle_resolve_timeout,
1023                                                    al);
1024   al->resolve_handle =
1025     GNUNET_DNSSTUB_resolve (dnsstub_ctx,
1026                             packet_buf,
1027                             packet_size,
1028                             &handle_resolve_result,
1029                             al);
1030   GNUNET_free (packet_buf);
1031   GNUNET_CONTAINER_DLL_insert (lookup_head,
1032                                lookup_tail,
1033                                al);
1034   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1035               "Resolving %s, client_request_id = %u, dns_id = %u\n",
1036               hostname,
1037               (unsigned int) client_request_id,
1038               (unsigned int) dns_id);
1039   return GNUNET_OK;
1040 }
1041
1042
1043 /**
1044  * Process DNS request for @a hostname with request ID @a client_request_id
1045  * from @a client demanding records of type @a record_type.
1046  *
1047  * @param hostname DNS name to resolve
1048  * @param record_type desired record type
1049  * @param client_request_id client's request ID
1050  * @param client who should get the result?
1051  */
1052 static void
1053 process_get (const char *hostname,
1054              uint16_t record_type,
1055              uint32_t client_request_id,
1056              struct GNUNET_SERVICE_Client *client)
1057 {
1058   char fqdn[255];
1059   
1060   if (  (NULL != my_domain) &&
1061         (NULL == strchr (hostname,
1062                          (unsigned char) '.')) &&
1063         (strlen (hostname) + strlen (my_domain) <= 253) )
1064   {
1065     GNUNET_snprintf (fqdn,
1066                      sizeof (fqdn),
1067                      "%s.%s",
1068                      hostname,
1069                      my_domain);                     
1070   }
1071   else if (strlen (hostname) < 255)
1072   {
1073     GNUNET_snprintf (fqdn,
1074                      sizeof (fqdn),
1075                      "%s",
1076                      hostname);
1077   }
1078   else
1079   {
1080     GNUNET_break (0);
1081     GNUNET_SERVICE_client_drop (client);
1082     return;
1083   }
1084   if (GNUNET_NO ==
1085       try_cache (fqdn,
1086                  record_type,
1087                  client_request_id,
1088                  client))
1089   {
1090     if (GNUNET_OK !=
1091         resolve_and_cache (fqdn,
1092                            record_type,
1093                            client_request_id,
1094                            client))
1095     {
1096       send_end_msg (client_request_id,
1097                     client);
1098     }
1099   }
1100 }
1101
1102
1103 /**
1104  * Verify well-formedness of GET-message.
1105  *
1106  * @param cls closure, unused
1107  * @param get the actual message
1108  * @return #GNUNET_OK if @a get is well-formed
1109  */
1110 static int
1111 check_get (void *cls,
1112            const struct GNUNET_RESOLVER_GetMessage *get)
1113 {
1114   uint16_t size;
1115   int direction;
1116   int af;
1117
1118   (void) cls;
1119   size = ntohs (get->header.size) - sizeof (*get);
1120   direction = ntohl (get->direction);
1121   if (GNUNET_NO == direction)
1122   {
1123     /* IP from hostname */
1124     const char *hostname;
1125
1126     hostname = (const char *) &get[1];
1127     if (hostname[size - 1] != '\0')
1128     {
1129       GNUNET_break (0);
1130       return GNUNET_SYSERR;
1131     }
1132     return GNUNET_OK;
1133   }
1134   af = ntohl (get->af);
1135   switch (af)
1136   {
1137   case AF_INET:
1138     if (size != sizeof (struct in_addr))
1139     {
1140       GNUNET_break (0);
1141       return GNUNET_SYSERR;
1142     }
1143     break;
1144   case AF_INET6:
1145     if (size != sizeof (struct in6_addr))
1146     {
1147       GNUNET_break (0);
1148       return GNUNET_SYSERR;
1149     }
1150     break;
1151   default:
1152     GNUNET_break (0);
1153     return GNUNET_SYSERR;
1154   }
1155   return GNUNET_OK;
1156 }
1157
1158
1159 /**
1160  * Handle GET-message.
1161  *
1162  * @param cls identification of the client
1163  * @param msg the actual message
1164  */
1165 static void
1166 handle_get (void *cls,
1167             const struct GNUNET_RESOLVER_GetMessage *msg)
1168 {
1169   struct GNUNET_SERVICE_Client *client = cls;
1170   int direction;
1171   int af;
1172   uint32_t client_request_id;
1173   char *hostname;
1174
1175   direction = ntohl (msg->direction);
1176   af = ntohl (msg->af);
1177   client_request_id = msg->client_id;
1178   GNUNET_SERVICE_client_continue (client);
1179   if (GNUNET_NO == direction)
1180   {
1181     /* IP from hostname */
1182     hostname = GNUNET_strdup ((const char *) &msg[1]);
1183     switch (af)
1184     {
1185       case AF_UNSPEC:
1186       {
1187         process_get (hostname,
1188                      GNUNET_DNSPARSER_TYPE_ALL,
1189                      client_request_id,
1190                      client);
1191         break;
1192       }
1193       case AF_INET:
1194       {
1195         process_get (hostname,
1196                      GNUNET_DNSPARSER_TYPE_A,
1197                      client_request_id,
1198                      client);
1199         break;
1200       }
1201       case AF_INET6:
1202       {
1203         process_get (hostname,
1204                      GNUNET_DNSPARSER_TYPE_AAAA,
1205                      client_request_id,
1206                      client);
1207         break;
1208       }
1209       default:
1210       {
1211         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1212                     "got invalid af: %d\n",
1213                     af);
1214         GNUNET_assert (0);
1215       }
1216     }
1217   }
1218   else
1219   {
1220     /* hostname from IP */
1221     hostname = make_reverse_hostname (&msg[1],
1222                                       af);
1223     process_get (hostname,
1224                  GNUNET_DNSPARSER_TYPE_PTR,
1225                  client_request_id,
1226                  client);
1227   }
1228   GNUNET_free_non_null (hostname);
1229 }
1230
1231
1232 /**
1233  * Service is shutting down, clean up.
1234  *
1235  * @param cls NULL, unused
1236  */
1237 static void
1238 shutdown_task (void *cls)
1239 {
1240   (void) cls;
1241
1242   while (NULL != lookup_head)
1243     free_active_lookup (lookup_head);
1244   while (NULL != cache_head)
1245     free_cache_entry (cache_head);
1246   while (NULL != hosts_head)
1247     free_hosts_entry (hosts_head);
1248   GNUNET_DNSSTUB_stop (dnsstub_ctx);
1249   GNUNET_free (my_domain);
1250 }
1251
1252
1253 /**
1254  * Add information about a host from /etc/hosts 
1255  * to our cache.
1256  *
1257  * @param hostname the name of the host
1258  * @param rec_type DNS record type to use
1259  * @param data payload
1260  * @param data_size number of bytes in @a data
1261  */
1262 static void
1263 add_host (const char *hostname,
1264           uint16_t rec_type,
1265           const void *data,
1266           size_t data_size)
1267 {
1268   struct ResolveCache *rc;
1269   struct RecordListEntry *rle;
1270   struct GNUNET_DNSPARSER_Record *rec;
1271
1272   rec = GNUNET_malloc (sizeof (struct GNUNET_DNSPARSER_Record));
1273   rec->expiration_time = GNUNET_TIME_UNIT_FOREVER_ABS;
1274   rec->type = rec_type;
1275   rec->dns_traffic_class = GNUNET_TUN_DNS_CLASS_INTERNET;  
1276   rec->name = GNUNET_strdup (hostname);
1277   rec->data.raw.data = GNUNET_memdup (data,
1278                                       data_size);
1279   rec->data.raw.data_len = data_size;
1280   rle = GNUNET_new (struct RecordListEntry);
1281   rle->record = rec;
1282   rc = GNUNET_new (struct ResolveCache);
1283   rc->hostname = GNUNET_strdup (hostname);
1284   GNUNET_CONTAINER_DLL_insert (rc->records_head,
1285                                rc->records_tail,
1286                                rle);
1287   GNUNET_CONTAINER_DLL_insert (hosts_head,
1288                                hosts_tail,
1289                                rc);
1290 }
1291
1292
1293 /**
1294  * Extract host information from a line in /etc/hosts
1295  * 
1296  * @param line the line to parse
1297  * @param line_len number of bytes in @a line
1298  */
1299 static void
1300 extract_hosts (const char *line,
1301                size_t line_len)
1302 {
1303   const char *c;
1304   struct in_addr v4;
1305   struct in6_addr v6;
1306   char *tbuf;
1307   char *tok;
1308
1309   /* ignore everything after '#' */
1310   c = memrchr (line,
1311                (unsigned char) '#',
1312                line_len);
1313   if (NULL != c)
1314     line_len = c - line;
1315   /* ignore leading whitespace */
1316   while ( (0 > line_len) &&
1317           isspace ((unsigned char) *line) )
1318   {
1319     line++;
1320     line_len--;
1321   }
1322   tbuf = GNUNET_strndup (line,
1323                          line_len);
1324   tok = strtok (tbuf, " \t");
1325   if (NULL == tok)
1326   {
1327     GNUNET_free (tbuf);
1328     return;
1329   }
1330   if (1 == inet_pton (AF_INET,
1331                       tok,
1332                       &v4))
1333   {
1334     while (NULL != (tok = strtok (NULL, " \t")))
1335       add_host (tok,
1336                 GNUNET_DNSPARSER_TYPE_A,
1337                 &v4,
1338                 sizeof (struct in_addr));
1339   }
1340   else if (1 == inet_pton (AF_INET6,
1341                            tok,
1342                            &v6))
1343   {
1344     while (NULL != (tok = strtok (NULL, " \t")))
1345       add_host (tok,
1346                 GNUNET_DNSPARSER_TYPE_AAAA,
1347                 &v6,
1348                 sizeof (struct in6_addr));
1349   }
1350   GNUNET_free (tbuf);
1351 }
1352
1353
1354 /**
1355  * Reads the list of hosts from /etc/hosts.
1356  */
1357 static void
1358 load_etc_hosts (void)
1359 {
1360   struct GNUNET_DISK_FileHandle *fh;
1361   struct GNUNET_DISK_MapHandle *mh;
1362   off_t bytes_read;
1363   const char *buf;
1364   size_t read_offset;
1365
1366   fh = GNUNET_DISK_file_open ("/etc/hosts",
1367                               GNUNET_DISK_OPEN_READ,
1368                               GNUNET_DISK_PERM_NONE);
1369   if (NULL == fh)
1370   {
1371     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1372                 "Failed to open /etc/hosts");
1373     return;
1374   }
1375   if (GNUNET_OK !=
1376       GNUNET_DISK_file_handle_size (fh,
1377                                     &bytes_read))
1378   {
1379     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1380                 "Could not determin size of /etc/hosts. "
1381                 "DNS resolution will not be possible.\n");
1382     GNUNET_DISK_file_close (fh);
1383     return;
1384   }
1385   if (bytes_read > SIZE_MAX)
1386   { 
1387     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1388                 "/etc/hosts file too large to mmap. "
1389                 "DNS resolution will not be possible.\n");
1390     GNUNET_DISK_file_close (fh);
1391     return;   
1392   }
1393   buf = GNUNET_DISK_file_map (fh,
1394                               &mh,
1395                               GNUNET_DISK_MAP_TYPE_READ,
1396                               (size_t) bytes_read);
1397   read_offset = 0;
1398   while (read_offset < bytes_read)
1399   {
1400     const char *newline;
1401     size_t line_len;
1402
1403     newline = strchr (buf + read_offset,
1404                       '\n');
1405     if (NULL == newline)
1406       break;
1407     line_len = newline - buf - read_offset;
1408     extract_hosts (buf + read_offset,
1409                    line_len);
1410     read_offset += line_len + 1;
1411   }
1412   GNUNET_DISK_file_unmap (mh);
1413   GNUNET_DISK_file_close (fh);
1414 }
1415
1416
1417 /**
1418  * Service is starting, initialize everything.
1419  *
1420  * @param cls NULL, unused
1421  * @param cfg our configuration
1422  * @param sh service handle
1423  */
1424 static void
1425 init_cb (void *cls,
1426          const struct GNUNET_CONFIGURATION_Handle *cfg,
1427          struct GNUNET_SERVICE_Handle *sh)
1428 {
1429   char **dns_servers;
1430   int num_dns_servers;
1431
1432   (void) cfg;
1433   (void) sh;
1434   load_etc_hosts ();
1435   GNUNET_SCHEDULER_add_shutdown (&shutdown_task,
1436                                  cls);
1437   dnsstub_ctx = GNUNET_DNSSTUB_start (128);
1438   dns_servers = NULL;
1439   num_dns_servers = lookup_dns_servers (&dns_servers);
1440   if (0 >= num_dns_servers)
1441   {
1442     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1443                 _("No DNS server available. DNS resolution will not be possible.\n"));
1444     return;
1445   }
1446   for (int i = 0; i < num_dns_servers; i++)
1447   {
1448     int result = GNUNET_DNSSTUB_add_dns_ip (dnsstub_ctx, dns_servers[i]);
1449     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1450                 "Adding DNS server '%s': %s\n",
1451                 dns_servers[i],
1452                 GNUNET_OK == result ? "success" : "failure");
1453     GNUNET_free (dns_servers[i]);
1454   }
1455   GNUNET_free_non_null (dns_servers);
1456 }
1457
1458
1459 /**
1460  * Callback called when a client connects to the service.
1461  *
1462  * @param cls closure for the service, unused
1463  * @param c the new client that connected to the service
1464  * @param mq the message queue used to send messages to the client
1465  * @return @a c
1466  */
1467 static void *
1468 connect_cb (void *cls,
1469             struct GNUNET_SERVICE_Client *c,
1470             struct GNUNET_MQ_Handle *mq)
1471 {
1472   (void) cls;
1473   (void) mq;
1474
1475   return c;
1476 }
1477
1478
1479 /**
1480  * Callback called when a client disconnected from the service
1481  *
1482  * @param cls closure for the service
1483  * @param c the client that disconnected
1484  * @param internal_cls should be equal to @a c
1485  */
1486 static void
1487 disconnect_cb (void *cls,
1488                struct GNUNET_SERVICE_Client *c,
1489                void *internal_cls)
1490 {
1491   struct ActiveLookup *n;
1492   (void) cls;
1493
1494   GNUNET_assert (c == internal_cls);
1495   n = lookup_head;
1496   for (struct ActiveLookup *al = n;
1497        NULL != al;
1498        al = n)
1499   {
1500     n = al->next;
1501     if (al->client == c)
1502       free_active_lookup (al);
1503   }
1504 }
1505
1506
1507 /**
1508  * Define "main" method using service macro.
1509  */
1510 GNUNET_SERVICE_MAIN
1511 ("resolver",
1512  GNUNET_SERVICE_OPTION_NONE,
1513  &init_cb,
1514  &connect_cb,
1515  &disconnect_cb,
1516  NULL,
1517  GNUNET_MQ_hd_var_size (get,
1518                         GNUNET_MESSAGE_TYPE_RESOLVER_REQUEST,
1519                         struct GNUNET_RESOLVER_GetMessage,
1520                         NULL),
1521  GNUNET_MQ_handler_end ());
1522
1523
1524 #if defined(LINUX) && defined(__GLIBC__)
1525 #include <malloc.h>
1526
1527 /**
1528  * MINIMIZE heap size (way below 128k) since this process doesn't need much.
1529  */
1530 void __attribute__ ((constructor))
1531 GNUNET_RESOLVER_memory_init ()
1532 {
1533   mallopt (M_TRIM_THRESHOLD, 4 * 1024);
1534   mallopt (M_TOP_PAD, 1 * 1024);
1535   malloc_trim (0);
1536 }
1537 #endif
1538
1539
1540 /* end of gnunet-service-resolver.c */