33a71f7782dcca6828148f8982df81f7591da49b
[oweals/gnunet.git] / src / gns / nss / nss_gns_query.c
1 /*
2      This file is part of GNUnet.
3      (C) 2012 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 #include <string.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include "nss_gns_query.h"
24 #include <arpa/inet.h>
25
26
27 /**
28  * Wrapper function that uses gnunet-gns cli tool to resolve
29  * an IPv4/6 address.
30  *
31  * @param af address family
32  * @param name the name to resolve
33  * @param u the userdata (result struct)
34  * @return -1 on error else 0
35  */
36 int 
37 gns_resolve_name (int af,
38                   const char *name, 
39                   struct userdata *u)
40 {
41   FILE *p;
42   char *cmd;
43   char line[128];
44
45   if (AF_INET6 == af)
46   {
47     if (-1 == asprintf (&cmd, 
48                         "%s -t AAAA -u %s\n", 
49                         "gnunet-gns -r", name))
50       return -1;
51   }
52   else
53   {
54     if (-1 == asprintf (&cmd, 
55                         "%s %s\n", 
56                         "gnunet-gns -r -u", name))
57       return -1;
58   }
59   if (NULL == (p = popen (cmd, "r")))
60   {
61     free (cmd);
62     return -1;
63   }
64   while (NULL != fgets (line, sizeof(line), p))
65   {
66     if (u->count >= MAX_ENTRIES)
67       break;
68     if (line[strlen(line)-1] == '\n')
69     {
70       line[strlen(line)-1] = '\0';
71       if (AF_INET == af)
72       {
73         if (inet_pton(af, line, &(u->data.ipv4[u->count])))
74         {
75           u->count++;
76           u->data_len += sizeof(ipv4_address_t);
77         }
78         else
79         {
80           pclose (p);
81           free (cmd);
82           return -1;
83         }
84       }
85       else if (AF_INET6 == af)
86       {
87         if (inet_pton(af, line, &(u->data.ipv6[u->count])))
88         {
89           u->count++;
90           u->data_len += sizeof(ipv6_address_t);
91         }
92         else
93         {
94           pclose (p);
95           free (cmd);
96           return -1;
97         }
98       }
99     }
100   }
101   pclose (p);
102   free (cmd);
103   return 0;
104 }
105
106 /* end of nss_gns_query.c */