-fix leak
[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   }
79   GNUNET_snprintf (buf, sizeof (buf), "%u", (unsigned int) type);
80   return buf;
81 }
82
83
84 /**
85  * Convert numeric DNS record class to a string.
86  *
87  * @param class class to convert
88  * @return class as string, only valid until the next call to this function
89  */
90 static const char *
91 get_class (uint16_t class)
92 {
93   static char buf[6];
94   switch (class)
95   {
96   case GNUNET_DNSPARSER_CLASS_INTERNET: return "IN";
97   case GNUNET_DNSPARSER_CLASS_CHAOS: return "CHAOS";
98   case GNUNET_DNSPARSER_CLASS_HESIOD: return "HESIOD";
99   }
100   GNUNET_snprintf (buf, sizeof (buf), "%u", (unsigned int) class);
101   return buf;
102 }
103
104
105 /**
106  * Output the given DNS query to stdout.
107  *
108  * @param query query to display.
109  */
110 static void
111 display_query (const struct GNUNET_DNSPARSER_Query *query)
112 {
113   fprintf (stdout,
114            "\t\t%s %s: %s\n",
115            get_class (query->class),
116            get_type (query->type),
117            query->name);
118 }
119
120
121 /**
122  * Output the given DNS record to stdout.
123  *
124  * @param record record to display.
125  */
126 static void
127 display_record (const struct GNUNET_DNSPARSER_Record *record)
128 {
129   const char *format;
130   char buf[INET6_ADDRSTRLEN];
131   char *tmp;
132   
133   tmp = NULL;
134   switch (record->type)
135   {
136   case GNUNET_DNSPARSER_TYPE_A:
137     if (record->data.raw.data_len != sizeof (struct in_addr))
138       format = "<invalid>";
139     else
140       format = inet_ntop (AF_INET, record->data.raw.data, buf, sizeof (buf));
141     break;
142   case GNUNET_DNSPARSER_TYPE_AAAA:
143     if (record->data.raw.data_len != sizeof (struct in6_addr))
144       format = "<invalid>";
145     else
146       format = inet_ntop (AF_INET6, record->data.raw.data, buf, sizeof (buf));
147     break;
148   case GNUNET_DNSPARSER_TYPE_NS:
149   case GNUNET_DNSPARSER_TYPE_CNAME:
150   case GNUNET_DNSPARSER_TYPE_PTR:
151     format = record->data.hostname;
152     break;
153   case GNUNET_DNSPARSER_TYPE_SOA:
154     if (record->data.soa == NULL)
155       format = "<invalid>";
156     else
157     {
158       GNUNET_asprintf (&tmp,
159                        "origin: %s, mail: %s, serial = %u, refresh = %u s, retry = %u s, expire = %u s, minimum = %u s",
160                        record->data.soa->mname,
161                        record->data.soa->rname,
162                        (unsigned int) record->data.soa->serial,
163                        (unsigned int) record->data.soa->refresh,
164                        (unsigned int) record->data.soa->retry,
165                        (unsigned int) record->data.soa->expire,
166                        (unsigned int) record->data.soa->minimum_ttl);          
167       format = tmp;
168     }
169     break;
170   case GNUNET_DNSPARSER_TYPE_MX:
171     if (record->data.mx == NULL)
172       format = "<invalid>";
173     else
174     {
175       GNUNET_asprintf (&tmp,
176                        "%u: %s",
177                        record->data.mx->preference,
178                        record->data.mx->mxhost);
179       format = tmp;
180     }
181     break;
182   case GNUNET_DNSPARSER_TYPE_TXT:
183     GNUNET_asprintf (&tmp,
184                      "%.*s",
185                      (unsigned int) record->data.raw.data_len,
186                      record->data.raw.data);
187     format = tmp;
188     break;
189   default:
190     format = "<payload>";
191     break;
192   }
193   fprintf (stdout,
194            "\t\t%s %s: %s = %s (%u s)\n",
195            get_class (record->class),
196            get_type (record->type),
197            record->name,
198            format,
199            (unsigned int) (GNUNET_TIME_absolute_get_remaining (record->expiration_time).rel_value / 1000));
200   GNUNET_free_non_null (tmp);
201 }
202
203
204 /**
205  * Signature of a function that is called whenever the DNS service
206  * encounters a DNS request and needs to do something with it.  The
207  * function has then the chance to generate or modify the response by
208  * calling one of the three "GNUNET_DNS_request_*" continuations.
209  *
210  * When a request is intercepted, this function is called first to
211  * give the client a chance to do the complete address resolution;
212  * "rdata" will be NULL for this first call for a DNS request, unless
213  * some other client has already filled in a response.
214  *
215  * If multiple clients exist, all of them are called before the global
216  * DNS.  The global DNS is only called if all of the clients'
217  * functions call GNUNET_DNS_request_forward.  Functions that call
218  * GNUNET_DNS_request_forward will be called again before a final
219  * response is returned to the application.  If any of the clients'
220  * functions call GNUNET_DNS_request_drop, the response is dropped.
221  *
222  * @param cls closure
223  * @param rh request handle to user for reply
224  * @param request_length number of bytes in request
225  * @param request udp payload of the DNS request
226  */
227 static void 
228 display_request (void *cls,
229                  struct GNUNET_DNS_RequestHandle *rh,
230                  size_t request_length,
231                  const char *request)
232 {
233   static const char *return_codes[] =
234     {
235       "No error", "Format error", "Server failure", "Name error",
236       "Not implemented", "Refused", "YXDomain", "YXRRset",
237       "NXRRset", "NOT AUTH", "NOT ZONE", "<invalid>",
238       "<invalid>", "<invalid>", "<invalid>", "<invalid>"
239     };
240   static const char *op_codes[] =
241     {
242       "Query", "Inverse query", "Status", "<invalid>",
243       "<invalid>", "<invalid>", "<invalid>", "<invalid>",
244       "<invalid>", "<invalid>", "<invalid>", "<invalid>",
245       "<invalid>", "<invalid>", "<invalid>", "<invalid>"
246     };
247   struct GNUNET_DNSPARSER_Packet *p;
248   unsigned int i;
249
250   p = GNUNET_DNSPARSER_parse (request, request_length);
251   if (NULL == p)
252   {
253     fprintf (stderr, "Received malformed DNS packet!\n");
254     // FIXME: drop instead?
255     GNUNET_DNS_request_forward (rh);
256     return;
257   }
258   fprintf (stdout,
259            "%s with ID: %5u Flags: %s%s%s%s%s%s, Return Code: %s, Opcode: %s\n",
260            p->flags.query_or_response ? "Response" : "Query",
261            p->id,
262            p->flags.recursion_desired ? "RD " : "",
263            p->flags.message_truncated ? "MT " : "",
264            p->flags.authoritative_answer ? "AA " : "",
265            p->flags.checking_disabled ? "CD " : "",
266            p->flags.authenticated_data ? "AD " : "",
267            p->flags.recursion_available ? "RA " : "",
268            return_codes[p->flags.return_code & 15],
269            op_codes[p->flags.opcode & 15]);  
270   if (p->num_queries > 0)
271     fprintf (stdout,
272              "\tQueries:\n");
273   for (i=0;i<p->num_queries;i++)
274     display_query (&p->queries[i]);
275   
276   if (p->num_answers > 0)
277     fprintf (stdout,
278              "\tAnswers:\n");
279   for (i=0;i<p->num_answers;i++)
280     display_record (&p->answers[i]);
281   fprintf (stdout, "\n");
282   GNUNET_DNSPARSER_free_packet (p);
283   GNUNET_DNS_request_forward (rh);
284 }
285
286
287 /**
288  * Shutdown.
289  */
290 static void
291 do_disconnect (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
292 {
293   if (NULL != handle)
294   {
295     GNUNET_DNS_disconnect (handle);
296     handle = NULL;
297   }
298 }
299
300
301 /**
302  * Main function that will be run by the scheduler.
303  *
304  * @param cls closure
305  * @param args remaining command-line arguments
306  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
307  * @param cfg configuration
308  */
309 static void
310 run (void *cls, char *const *args, const char *cfgfile,
311      const struct GNUNET_CONFIGURATION_Handle *cfg)
312 {
313   enum GNUNET_DNS_Flags flags;
314
315   flags = GNUNET_DNS_FLAG_REQUEST_MONITOR | GNUNET_DNS_FLAG_RESPONSE_MONITOR;
316   if (inbound_only | outbound_only)
317     flags = 0;
318   if (inbound_only)
319     flags |= GNUNET_DNS_FLAG_REQUEST_MONITOR;
320   if (outbound_only)
321     flags |= GNUNET_DNS_FLAG_RESPONSE_MONITOR;
322   handle =
323     GNUNET_DNS_connect (cfg, 
324                         flags,
325                         &display_request,
326                         NULL);
327   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
328                                 &do_disconnect, NULL);
329 }
330
331
332 int
333 main (int argc, char *const *argv)
334 {
335   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
336     {'i', "inbound-only", NULL,
337      gettext_noop ("only monitor DNS queries"),
338      0, &GNUNET_GETOPT_set_one, &inbound_only},
339     {'o', "outbound-only", NULL,
340      gettext_noop ("only monitor DNS replies"),
341      0, &GNUNET_GETOPT_set_one, &outbound_only},
342     GNUNET_GETOPT_OPTION_VERBOSE (&verbosity),
343     GNUNET_GETOPT_OPTION_END
344   };
345   return (GNUNET_OK ==
346           GNUNET_PROGRAM_run (argc, argv, "gnunet-dns-monitor",
347                               gettext_noop
348                               ("Monitor DNS queries."), options,
349                               &run, NULL)) ? ret : 1;
350 }
351
352
353 /* end of gnunet-dns-monitor.c */