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