-fix double free, linker issue
[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 gns_resolve_name(int af, const char *name, struct userdata *u)
37 {
38   FILE *p;
39   char *cmd;
40   char line[128];
41
42   if (af == AF_INET6)
43   {
44     if (-1 == asprintf(&cmd, "%s -t AAAA -u %s\n", "gnunet-gns -r", name))
45       return -1;
46   }
47   else
48   {
49     if (-1 == asprintf(&cmd, "%s %s\n", "gnunet-gns -r -u", name))
50       return -1;
51   }
52
53   p = popen(cmd,"r");
54
55   if (p != NULL )
56   {
57     while (fgets( line, sizeof(line), p ) != NULL)
58     {
59
60       if (u->count >= MAX_ENTRIES)
61         break;
62
63       if (line[strlen(line)-1] == '\n')
64       {
65         line[strlen(line)-1] = '\0';
66         if (af == AF_INET)
67         {
68           if (inet_pton(af, line, &(u->data.ipv4[u->count])))
69           {
70             u->count++;
71             u->data_len += sizeof(ipv4_address_t);
72           }
73           else
74           {
75             fclose (p);
76             free (cmd);
77             return -1;
78           }
79         }
80         else if ((af == AF_INET6))
81         {
82           if (inet_pton(af, line, &(u->data.ipv6[u->count])))
83           {
84             u->count++;
85             u->data_len += sizeof(ipv6_address_t);
86           }
87           else
88           {
89             fclose (p);
90             free (cmd);
91             return -1;
92           }
93         }
94       }
95     }
96     fclose (p);
97   }
98   free (cmd);
99
100   return 0;
101
102 }