- some tests did not clean up
[oweals/gnunet.git] / src / dns / gnunet-dns-monitor.c
1 /*
2      This file is part of GNUnet.
3      (C) 2011 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @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 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_DNSPARSER_CLASS_INTERNET: return "IN";
98   case GNUNET_DNSPARSER_CLASS_CHAOS: return "CHAOS";
99   case GNUNET_DNSPARSER_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->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                        "service: %s, protocol: %s, domain_name = %s, priority %u, weight = %s, port = %u, target = %s",
190                        record->data.srv->service,
191                        record->data.srv->proto,
192                        record->data.srv->domain_name,
193                        (unsigned int) record->data.srv->priority,
194                        (unsigned int) record->data.srv->weight,
195                        (unsigned int) record->data.srv->port,
196                        record->data.srv->target);
197       format = tmp;
198     }
199     break;
200   case GNUNET_DNSPARSER_TYPE_TXT:
201     GNUNET_asprintf (&tmp,
202                      "%.*s",
203                      (unsigned int) record->data.raw.data_len,
204                      record->data.raw.data);
205     format = tmp;
206     break;
207   default:
208     format = "<payload>";
209     break;
210   }
211   fprintf (stdout,
212            "\t\t%s %s: %s = %s (%u s)\n",
213            get_class (record->class),
214            get_type (record->type),
215            record->name,
216            format,
217            (unsigned int) (GNUNET_TIME_absolute_get_remaining (record->expiration_time).rel_value / 1000));
218   GNUNET_free_non_null (tmp);
219 }
220
221
222 /**
223  * Signature of a function that is called whenever the DNS service
224  * encounters a DNS request and needs to do something with it.  The
225  * function has then the chance to generate or modify the response by
226  * calling one of the three "GNUNET_DNS_request_*" continuations.
227  *
228  * When a request is intercepted, this function is called first to
229  * give the client a chance to do the complete address resolution;
230  * "rdata" will be NULL for this first call for a DNS request, unless
231  * some other client has already filled in a response.
232  *
233  * If multiple clients exist, all of them are called before the global
234  * DNS.  The global DNS is only called if all of the clients'
235  * functions call GNUNET_DNS_request_forward.  Functions that call
236  * GNUNET_DNS_request_forward will be called again before a final
237  * response is returned to the application.  If any of the clients'
238  * functions call GNUNET_DNS_request_drop, the response is dropped.
239  *
240  * @param cls closure
241  * @param rh request handle to user for reply
242  * @param request_length number of bytes in request
243  * @param request udp payload of the DNS request
244  */
245 static void 
246 display_request (void *cls,
247                  struct GNUNET_DNS_RequestHandle *rh,
248                  size_t request_length,
249                  const char *request)
250 {
251   static const char *return_codes[] =
252     {
253       "No error", "Format error", "Server failure", "Name error",
254       "Not implemented", "Refused", "YXDomain", "YXRRset",
255       "NXRRset", "NOT AUTH", "NOT ZONE", "<invalid>",
256       "<invalid>", "<invalid>", "<invalid>", "<invalid>"
257     };
258   static const char *op_codes[] =
259     {
260       "Query", "Inverse query", "Status", "<invalid>",
261       "<invalid>", "<invalid>", "<invalid>", "<invalid>",
262       "<invalid>", "<invalid>", "<invalid>", "<invalid>",
263       "<invalid>", "<invalid>", "<invalid>", "<invalid>"
264     };
265   struct GNUNET_DNSPARSER_Packet *p;
266   unsigned int i;
267
268   p = GNUNET_DNSPARSER_parse (request, request_length);
269   if (NULL == p)
270   {
271     fprintf (stderr, "Received malformed DNS packet!\n");
272     // FIXME: drop instead?
273     GNUNET_DNS_request_forward (rh);
274     return;
275   }
276   fprintf (stdout,
277            "%s with ID: %5u Flags: %s%s%s%s%s%s, Return Code: %s, Opcode: %s\n",
278            p->flags.query_or_response ? "Response" : "Query",
279            p->id,
280            p->flags.recursion_desired ? "RD " : "",
281            p->flags.message_truncated ? "MT " : "",
282            p->flags.authoritative_answer ? "AA " : "",
283            p->flags.checking_disabled ? "CD " : "",
284            p->flags.authenticated_data ? "AD " : "",
285            p->flags.recursion_available ? "RA " : "",
286            return_codes[p->flags.return_code & 15],
287            op_codes[p->flags.opcode & 15]);  
288   if (p->num_queries > 0)
289     fprintf (stdout,
290              "\tQueries:\n");
291   for (i=0;i<p->num_queries;i++)
292     display_query (&p->queries[i]);
293   
294   if (p->num_answers > 0)
295     fprintf (stdout,
296              "\tAnswers:\n");
297   for (i=0;i<p->num_answers;i++)
298     display_record (&p->answers[i]);
299   fprintf (stdout, "\n");
300   GNUNET_DNSPARSER_free_packet (p);
301   GNUNET_DNS_request_forward (rh);
302 }
303
304
305 /**
306  * Shutdown.
307  */
308 static void
309 do_disconnect (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
310 {
311   if (NULL != handle)
312   {
313     GNUNET_DNS_disconnect (handle);
314     handle = NULL;
315   }
316 }
317
318
319 /**
320  * Main function that will be run by the scheduler.
321  *
322  * @param cls closure
323  * @param args remaining command-line arguments
324  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
325  * @param cfg configuration
326  */
327 static void
328 run (void *cls, char *const *args, const char *cfgfile,
329      const struct GNUNET_CONFIGURATION_Handle *cfg)
330 {
331   enum GNUNET_DNS_Flags flags;
332
333   flags = GNUNET_DNS_FLAG_REQUEST_MONITOR | GNUNET_DNS_FLAG_RESPONSE_MONITOR;
334   if (inbound_only | outbound_only)
335     flags = 0;
336   if (inbound_only)
337     flags |= GNUNET_DNS_FLAG_REQUEST_MONITOR;
338   if (outbound_only)
339     flags |= GNUNET_DNS_FLAG_RESPONSE_MONITOR;
340   handle =
341     GNUNET_DNS_connect (cfg, 
342                         flags,
343                         &display_request,
344                         NULL);
345   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
346                                 &do_disconnect, NULL);
347 }
348
349
350 int
351 main (int argc, char *const *argv)
352 {
353   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
354     {'i', "inbound-only", NULL,
355      gettext_noop ("only monitor DNS queries"),
356      0, &GNUNET_GETOPT_set_one, &inbound_only},
357     {'o', "outbound-only", NULL,
358      gettext_noop ("only monitor DNS replies"),
359      0, &GNUNET_GETOPT_set_one, &outbound_only},
360     GNUNET_GETOPT_OPTION_VERBOSE (&verbosity),
361     GNUNET_GETOPT_OPTION_END
362   };
363
364   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
365     return 2;
366
367   return (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 }
373
374
375 /* end of gnunet-dns-monitor.c */