initialize response_code, always
[oweals/gnunet.git] / src / nat / nat_api_stun.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2009, 2015, 2016 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  * This code provides some support for doing STUN transactions.
22  * We send simplest possible packet ia REQUEST with BIND to a STUN server.
23  *
24  * All STUN packets start with a simple header made of a type,
25  * length (excluding the header) and a 16-byte random transaction id.
26  * Following the header we may have zero or more attributes, each
27  * structured as a type, length and a value (whose format depends
28  * on the type, but often contains addresses).
29  * Of course all fields are in network format.
30  *
31  * This code was based on ministun.c.
32  *
33  * @file nat/nat_api_stun.c
34  * @brief Functions for STUN functionality
35  * @author Bruno Souza Cabral
36  */
37
38 #include "platform.h"
39 #include "gnunet_util_lib.h"
40 #include "gnunet_resolver_service.h"
41 #include "gnunet_nat_service.h"
42
43
44 #include "nat_stun.h"
45
46 #define LOG(kind,...) GNUNET_log_from (kind, "stun", __VA_ARGS__)
47
48 #define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15)
49
50
51 /**
52  * Handle to a request given to the resolver.  Can be used to cancel
53  * the request prior to the timeout or successful execution.  Also
54  * used to track our internal state for the request.
55  */
56 struct GNUNET_NAT_STUN_Handle
57 {
58
59   /**
60    * Handle to a pending DNS lookup request.
61    */
62   struct GNUNET_RESOLVER_RequestHandle *dns_active;
63
64   /**
65    * Handle to the listen socket
66    */
67   struct GNUNET_NETWORK_Handle *sock;
68
69   /**
70    * Stun server address
71    */
72   char *stun_server;
73
74   /**
75    * Function to call when a error occours
76    */
77   GNUNET_NAT_TestCallback cb;
78
79   /**
80    * Closure for @e cb.
81    */
82   void *cb_cls;
83
84   /**
85    * Do we got a DNS resolution successfully?
86    */
87   int dns_success;
88
89   /**
90    * STUN port
91    */
92   uint16_t stun_port;
93
94 };
95
96
97 /**
98  * Encode a class and method to a compatible STUN format
99  *
100  * @param msg_class class to be converted
101  * @param method method to be converted
102  * @return message in a STUN compatible format
103  */
104 static int
105 encode_message (enum StunClasses msg_class,
106                 enum StunMethods method)
107 {
108   return ((msg_class & 1) << 4) | ((msg_class & 2) << 7) |
109     (method & 0x000f) | ((method & 0x0070) << 1) | ((method & 0x0f800) << 2);
110 }
111
112
113 /**
114  * Fill the stun_header with a random request_id
115  *
116  * @param req, stun header to be filled
117  */
118 static void
119 generate_request_id (struct stun_header *req)
120 {
121   req->magic = htonl(STUN_MAGIC_COOKIE);
122   for (unsigned int x = 0; x < 3; x++)
123     req->id.id[x] = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
124                                               UINT32_MAX);
125 }
126
127
128 /**
129  * Try to establish a connection given the specified address.
130  *
131  * @param cls our `struct GNUNET_NAT_STUN_Handle *`
132  * @param addr address to try, NULL for "last call"
133  * @param addrlen length of @a addr
134  */
135 static void
136 stun_dns_callback (void *cls,
137                    const struct sockaddr *addr,
138                    socklen_t addrlen)
139 {
140   struct GNUNET_NAT_STUN_Handle *rh = cls;
141   struct stun_header req;
142   struct sockaddr_in server;
143
144   if (NULL == addr)
145   {
146     rh->dns_active = NULL;
147     if (GNUNET_NO == rh->dns_success)
148     {
149       LOG (GNUNET_ERROR_TYPE_INFO,
150            "Error resolving host %s\n",
151            rh->stun_server);
152       rh->cb (rh->cb_cls,
153               GNUNET_NAT_ERROR_NOT_ONLINE);
154     }
155     else if (GNUNET_SYSERR == rh->dns_success)
156     {
157       rh->cb (rh->cb_cls,
158               GNUNET_NAT_ERROR_INTERNAL_NETWORK_ERROR);
159     }
160     else
161     {
162       rh->cb (rh->cb_cls,
163               GNUNET_NAT_ERROR_SUCCESS);
164     }
165     GNUNET_NAT_stun_make_request_cancel (rh);
166     return;
167   }
168
169   rh->dns_success = GNUNET_YES;
170   memset (&server, 0, sizeof(server));
171   server.sin_family = AF_INET;
172   server.sin_addr = ((struct sockaddr_in *)addr)->sin_addr;
173   server.sin_port = htons (rh->stun_port);
174 #if HAVE_SOCKADDR_IN_SIN_LEN
175   server.sin_len = (u_char) sizeof (struct sockaddr_in);
176 #endif
177
178   /* Craft the simplest possible STUN packet. A request binding */
179   generate_request_id (&req);
180   req.msglen = htons (0);
181   req.msgtype = htons (encode_message (STUN_REQUEST,
182                                        STUN_BINDING));
183
184   /* Send the packet */
185   if (-1 ==
186       GNUNET_NETWORK_socket_sendto (rh->sock,
187                                     &req,
188                                     sizeof (req),
189                                     (const struct sockaddr *) &server,
190                                     sizeof (server)))
191   {
192     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
193                          "sendto");
194     rh->dns_success = GNUNET_SYSERR;
195     return;
196   }
197 }
198
199
200 /**
201  * Make Generic STUN request. Sends a generic stun request to the
202  * server specified using the specified socket.
203  *
204  * @param server the address of the stun server
205  * @param port port of the stun server, in host byte order
206  * @param sock the socket used to send the request
207  * @param cb callback in case of error
208  * @param cb_cls closure for @a cb
209  * @return NULL on error
210  */
211 struct GNUNET_NAT_STUN_Handle *
212 GNUNET_NAT_stun_make_request (const char *server,
213                               uint16_t port,
214                               struct GNUNET_NETWORK_Handle *sock,
215                               GNUNET_NAT_TestCallback cb,
216                               void *cb_cls)
217 {
218   struct GNUNET_NAT_STUN_Handle *rh;
219
220   rh = GNUNET_new (struct GNUNET_NAT_STUN_Handle);
221   rh->sock = sock;
222   rh->cb = cb;
223   rh->cb_cls = cb_cls;
224   rh->stun_server = GNUNET_strdup (server);
225   rh->stun_port = port;
226   rh->dns_success = GNUNET_NO;
227   rh->dns_active = GNUNET_RESOLVER_ip_get (rh->stun_server,
228                                            AF_INET,
229                                            TIMEOUT,
230                                            &stun_dns_callback,
231                                            rh);
232   if (NULL == rh->dns_active)
233   {
234     GNUNET_NAT_stun_make_request_cancel (rh);
235     return NULL;
236   }
237   return rh;
238 }
239
240
241 /**
242  * Cancel active STUN request. Frees associated resources
243  * and ensures that the callback is no longer invoked.
244  *
245  * @param rh request to cancel
246  */
247 void
248 GNUNET_NAT_stun_make_request_cancel (struct GNUNET_NAT_STUN_Handle *rh)
249 {
250   if (NULL != rh->dns_active)
251   {
252     GNUNET_RESOLVER_request_cancel (rh->dns_active);
253     rh->dns_active = NULL;
254   }
255   GNUNET_free (rh->stun_server);
256   GNUNET_free (rh);
257 }
258
259
260 /* end of nat_stun.c */