Merge branch 'master' of gnunet.org:gnunet
[oweals/gnunet.git] / src / dns / gnunet-dns-monitor.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2011 GNUnet e.V.
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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20
21 /**
22  * @file src/dns/gnunet-dns-monitor.c
23  * @brief Tool to monitor DNS queries
24  * @author Christian Grothoff
25  */
26
27 #include "platform.h"
28 #include "gnunet_util_lib.h"
29 #include "gnunet_dns_service.h"
30 #include "gnunet_dnsparser_lib.h"
31
32 /**
33  * Handle to transport service.
34  */
35 static struct GNUNET_DNS_Handle *handle;
36
37 /**
38  * Option -i.
39  */
40 static int inbound_only;
41
42 /**
43  * Option -o.
44  */
45 static int outbound_only;
46
47 /**
48  * Global return value (0 success).
49  */
50 static int ret;
51
52 /**
53  * Selected level of verbosity.
54  */
55 static unsigned int verbosity;
56
57
58 /**
59  * Convert numeric DNS record type to a string.
60  *
61  * @param type type to convert
62  * @return type as string, only valid until the next call to this function
63  */
64 static const char *
65 get_type (uint16_t type)
66 {
67   static char buf[6];
68   switch (type)
69   {
70   case GNUNET_DNSPARSER_TYPE_A: return "A";
71   case GNUNET_DNSPARSER_TYPE_NS: return "NS";
72   case GNUNET_DNSPARSER_TYPE_CNAME: return "CNAME";
73   case GNUNET_DNSPARSER_TYPE_SOA: return "SOA";
74   case GNUNET_DNSPARSER_TYPE_PTR: return "PTR";
75   case GNUNET_DNSPARSER_TYPE_MX: return "MX";
76   case GNUNET_DNSPARSER_TYPE_TXT: return "TXT";
77   case GNUNET_DNSPARSER_TYPE_AAAA: return "AAAA";
78   case GNUNET_DNSPARSER_TYPE_SRV: return "SRV";
79   }
80   GNUNET_snprintf (buf, sizeof (buf), "%u", (unsigned int) type);
81   return buf;
82 }
83
84
85 /**
86  * Convert numeric DNS record class to a string.
87  *
88  * @param class class to convert
89  * @return class as string, only valid until the next call to this function
90  */
91 static const char *
92 get_class (uint16_t class)
93 {
94   static char buf[6];
95   switch (class)
96   {
97   case GNUNET_TUN_DNS_CLASS_INTERNET: return "IN";
98   case GNUNET_TUN_DNS_CLASS_CHAOS: return "CHAOS";
99   case GNUNET_TUN_DNS_CLASS_HESIOD: return "HESIOD";
100   }
101   GNUNET_snprintf (buf, sizeof (buf), "%u", (unsigned int) class);
102   return buf;
103 }
104
105
106 /**
107  * Output the given DNS query to stdout.
108  *
109  * @param query query to display.
110  */
111 static void
112 display_query (const struct GNUNET_DNSPARSER_Query *query)
113 {
114   fprintf (stdout,
115            "\t\t%s %s: %s\n",
116            get_class (query->dns_traffic_class),
117            get_type (query->type),
118            query->name);
119 }
120
121
122 /**
123  * Output the given DNS record to stdout.
124  *
125  * @param record record to display.
126  */
127 static void
128 display_record (const struct GNUNET_DNSPARSER_Record *record)
129 {
130   const char *format;
131   char buf[INET6_ADDRSTRLEN];
132   char *tmp;
133
134   tmp = NULL;
135   switch (record->type)
136   {
137   case GNUNET_DNSPARSER_TYPE_A:
138     if (record->data.raw.data_len != sizeof (struct in_addr))
139       format = "<invalid>";
140     else
141       format = inet_ntop (AF_INET, record->data.raw.data, buf, sizeof (buf));
142     break;
143   case GNUNET_DNSPARSER_TYPE_AAAA:
144     if (record->data.raw.data_len != sizeof (struct in6_addr))
145       format = "<invalid>";
146     else
147       format = inet_ntop (AF_INET6, record->data.raw.data, buf, sizeof (buf));
148     break;
149   case GNUNET_DNSPARSER_TYPE_NS:
150   case GNUNET_DNSPARSER_TYPE_CNAME:
151   case GNUNET_DNSPARSER_TYPE_PTR:
152     format = record->data.hostname;
153     break;
154   case GNUNET_DNSPARSER_TYPE_SOA:
155     if (NULL == record->data.soa)
156       format = "<invalid>";
157     else
158     {
159       GNUNET_asprintf (&tmp,
160                        "origin: %s, mail: %s, serial = %u, refresh = %u s, retry = %u s, expire = %u s, minimum = %u s",
161                        record->data.soa->mname,
162                        record->data.soa->rname,
163                        (unsigned int) record->data.soa->serial,
164                        (unsigned int) record->data.soa->refresh,
165                        (unsigned int) record->data.soa->retry,
166                        (unsigned int) record->data.soa->expire,
167                        (unsigned int) record->data.soa->minimum_ttl);
168       format = tmp;
169     }
170     break;
171   case GNUNET_DNSPARSER_TYPE_MX:
172     if (record->data.mx == NULL)
173       format = "<invalid>";
174     else
175     {
176       GNUNET_asprintf (&tmp,
177                        "%u: %s",
178                        record->data.mx->preference,
179                        record->data.mx->mxhost);
180       format = tmp;
181     }
182     break;
183   case GNUNET_DNSPARSER_TYPE_SRV:
184     if (NULL == record->data.srv)
185       format = "<invalid>";
186     else
187     {
188       GNUNET_asprintf (&tmp,
189                        "priority %u, weight = %s, port = %u, target = %s",
190                        (unsigned int) record->data.srv->priority,
191                        (unsigned int) record->data.srv->weight,
192                        (unsigned int) record->data.srv->port,
193                        record->data.srv->target);
194       format = tmp;
195     }
196     break;
197   case GNUNET_DNSPARSER_TYPE_TXT:
198     GNUNET_asprintf (&tmp,
199                      "%.*s",
200                      (unsigned int) record->data.raw.data_len,
201                      record->data.raw.data);
202     format = tmp;
203     break;
204   default:
205     format = "<payload>";
206     break;
207   }
208   fprintf (stdout,
209            "\t\t%s %s: %s = %s (%u s)\n",
210            get_class (record->dns_traffic_class),
211            get_type (record->type),
212            record->name,
213            format,
214            (unsigned int) (GNUNET_TIME_absolute_get_remaining (record->expiration_time).rel_value_us / 1000LL / 1000LL));
215   GNUNET_free_non_null (tmp);
216 }
217
218
219 /**
220  * Signature of a function that is called whenever the DNS service
221  * encounters a DNS request and needs to do something with it.  The
222  * function has then the chance to generate or modify the response by
223  * calling one of the three "GNUNET_DNS_request_*" continuations.
224  *
225  * When a request is intercepted, this function is called first to
226  * give the client a chance to do the complete address resolution;
227  * "rdata" will be NULL for this first call for a DNS request, unless
228  * some other client has already filled in a response.
229  *
230  * If multiple clients exist, all of them are called before the global
231  * DNS.  The global DNS is only called if all of the clients'
232  * functions call GNUNET_DNS_request_forward.  Functions that call
233  * GNUNET_DNS_request_forward will be called again before a final
234  * response is returned to the application.  If any of the clients'
235  * functions call GNUNET_DNS_request_drop, the response is dropped.
236  *
237  * @param cls closure
238  * @param rh request handle to user for reply
239  * @param request_length number of bytes in request
240  * @param request udp payload of the DNS request
241  */
242 static void
243 display_request (void *cls,
244                  struct GNUNET_DNS_RequestHandle *rh,
245                  size_t request_length,
246                  const char *request)
247 {
248   static const char *return_codes[] =
249     {
250       "No error", "Format error", "Server failure", "Name error",
251       "Not implemented", "Refused", "YXDomain", "YXRRset",
252       "NXRRset", "NOT AUTH", "NOT ZONE", "<invalid>",
253       "<invalid>", "<invalid>", "<invalid>", "<invalid>"
254     };
255   static const char *op_codes[] =
256     {
257       "Query", "Inverse query", "Status", "<invalid>",
258       "<invalid>", "<invalid>", "<invalid>", "<invalid>",
259       "<invalid>", "<invalid>", "<invalid>", "<invalid>",
260       "<invalid>", "<invalid>", "<invalid>", "<invalid>"
261     };
262   struct GNUNET_DNSPARSER_Packet *p;
263   unsigned int i;
264
265   p = GNUNET_DNSPARSER_parse (request, request_length);
266   if (NULL == p)
267   {
268     fprintf (stderr, "Received malformed DNS packet!\n");
269     // FIXME: drop instead?
270     GNUNET_DNS_request_forward (rh);
271     return;
272   }
273   fprintf (stdout,
274            "%s with ID: %5u Flags: %s%s%s%s%s%s, Return Code: %s, Opcode: %s\n",
275            p->flags.query_or_response ? "Response" : "Query",
276            p->id,
277            p->flags.recursion_desired ? "RD " : "",
278            p->flags.message_truncated ? "MT " : "",
279            p->flags.authoritative_answer ? "AA " : "",
280            p->flags.checking_disabled ? "CD " : "",
281            p->flags.authenticated_data ? "AD " : "",
282            p->flags.recursion_available ? "RA " : "",
283            return_codes[p->flags.return_code & 15],
284            op_codes[p->flags.opcode & 15]);
285   if (p->num_queries > 0)
286     fprintf (stdout,
287              "\tQueries:\n");
288   for (i=0;i<p->num_queries;i++)
289     display_query (&p->queries[i]);
290
291   if (p->num_answers > 0)
292     fprintf (stdout,
293              "\tAnswers:\n");
294   for (i=0;i<p->num_answers;i++)
295     display_record (&p->answers[i]);
296   fprintf (stdout, "\n");
297   GNUNET_DNSPARSER_free_packet (p);
298   GNUNET_DNS_request_forward (rh);
299 }
300
301
302 /**
303  * Shutdown.
304  */
305 static void
306 do_disconnect (void *cls)
307 {
308   if (NULL != handle)
309   {
310     GNUNET_DNS_disconnect (handle);
311     handle = NULL;
312   }
313 }
314
315
316 /**
317  * Main function that will be run by the scheduler.
318  *
319  * @param cls closure
320  * @param args remaining command-line arguments
321  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
322  * @param cfg configuration
323  */
324 static void
325 run (void *cls, char *const *args, const char *cfgfile,
326      const struct GNUNET_CONFIGURATION_Handle *cfg)
327 {
328   enum GNUNET_DNS_Flags flags;
329
330   flags = GNUNET_DNS_FLAG_REQUEST_MONITOR | GNUNET_DNS_FLAG_RESPONSE_MONITOR;
331   if (inbound_only | outbound_only)
332     flags = 0;
333   if (inbound_only)
334     flags |= GNUNET_DNS_FLAG_REQUEST_MONITOR;
335   if (outbound_only)
336     flags |= GNUNET_DNS_FLAG_RESPONSE_MONITOR;
337   handle =
338     GNUNET_DNS_connect (cfg,
339                         flags,
340                         &display_request,
341                         NULL);
342   GNUNET_SCHEDULER_add_shutdown (&do_disconnect, NULL);
343 }
344
345
346 int
347 main (int argc, char *const *argv)
348 {
349   struct GNUNET_GETOPT_CommandLineOption options[] = {
350
351     GNUNET_GETOPT_option_flag ('i',
352                                   "inbound-only",
353                                   gettext_noop ("only monitor DNS queries"),
354                                   &inbound_only),
355
356     GNUNET_GETOPT_option_flag ('o',
357                                   "outbound-only",
358                                   gettext_noop ("only monitor DNS queries"),
359                                   &outbound_only),
360
361     GNUNET_GETOPT_option_verbose (&verbosity),
362     GNUNET_GETOPT_OPTION_END
363   };
364
365   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
366     return 2;
367   ret = (GNUNET_OK ==
368          GNUNET_PROGRAM_run (argc, argv, "gnunet-dns-monitor",
369                              gettext_noop
370                              ("Monitor DNS queries."), options,
371                              &run, NULL)) ? ret : 1;
372   GNUNET_free ((void*) argv);
373   return ret;
374 }
375
376
377 /* end of gnunet-dns-monitor.c */