-removing spectacular dead code
[oweals/gnunet.git] / src / nat / nat_stun.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2009, 2015 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., 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_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_lib.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_STUN_ErrorCallback 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  * here we store credentials extracted from a message
99 */
100 struct StunState
101 {
102     uint16_t attr;
103 };
104
105
106 /**
107  * Convert a message to a StunClass
108  *
109  * @param msg the received message
110  * @return the converted StunClass
111  */
112 static int
113 decode_class(int msg)
114 {
115   /* Sorry for the magic, but this maps the class according to rfc5245 */
116   return ((msg & 0x0010) >> 4) | ((msg & 0x0100) >> 7);
117 }
118
119 /**
120  * Convert a message to a StunMethod
121  *
122  * @param msg the received message
123  * @return the converted StunMethod
124  */
125 static int
126 decode_method(int msg)
127 {
128   return (msg & 0x000f) | ((msg & 0x00e0) >> 1) | ((msg & 0x3e00) >> 2);
129 }
130
131
132 /**
133  * Encode a class and method to a compatible STUN format
134  *
135  * @param msg_class class to be converted
136  * @param method method to be converted
137  * @return message in a STUN compatible format
138  */
139 static int
140 encode_message (enum StunClasses msg_class,
141                 enum StunMethods method)
142 {
143   return ((msg_class & 1) << 4) | ((msg_class & 2) << 7) |
144     (method & 0x000f) | ((method & 0x0070) << 1) | ((method & 0x0f800) << 2);
145 }
146
147
148 /**
149  * Print a class and method from a STUN message
150  *
151  * @param msg
152  * @return string with the message class and method
153  */
154 static const char *
155 stun_msg2str(int msg)
156 {
157   static const struct { enum StunClasses value; const char *name; } classes[] = {
158     { STUN_REQUEST, "Request" },
159     { STUN_INDICATION, "Indication" },
160     { STUN_RESPONSE, "Response" },
161     { STUN_ERROR_RESPONSE, "Error Response" },
162     { 0, NULL }
163   };
164   static const struct { enum StunMethods value; const char *name; } methods[] = {
165     { STUN_BINDING, "Binding" },
166     { 0, NULL }
167   };
168   static char result[32];
169   const char *msg_class = NULL;
170   const char *method = NULL;
171   int i;
172   int value;
173
174   value = decode_class(msg);
175   for (i = 0; classes[i].name; i++)
176   {
177     msg_class = classes[i].name;
178     if (classes[i].value == value)
179       break;
180   }
181   value = decode_method(msg);
182   for (i = 0; methods[i].name; i++)
183   {
184     method = methods[i].name;
185     if (methods[i].value == value)
186       break;
187   }
188   GNUNET_snprintf (result,
189                    sizeof(result),
190                    "%s %s",
191                    method ? : "Unknown Method",
192                    msg_class ? : "Unknown Class Message");
193   return result;
194 }
195
196
197 /**
198  * Print attribute name
199  *
200  * @param msg with a attribute type
201  * @return string with the attribute name
202  */
203 static const char *
204 stun_attr2str(int msg)
205 {
206   const struct { enum StunAttributes value; const char *name; } attrs[] = {
207     { STUN_MAPPED_ADDRESS, "Mapped Address" },
208     { STUN_RESPONSE_ADDRESS, "Response Address" },
209     { STUN_CHANGE_ADDRESS, "Change Address" },
210     { STUN_SOURCE_ADDRESS, "Source Address" },
211     { STUN_CHANGED_ADDRESS, "Changed Address" },
212     { STUN_USERNAME, "Username" },
213     { STUN_PASSWORD, "Password" },
214     { STUN_MESSAGE_INTEGRITY, "Message Integrity" },
215     { STUN_ERROR_CODE, "Error Code" },
216     { STUN_UNKNOWN_ATTRIBUTES, "Unknown Attributes" },
217     { STUN_REFLECTED_FROM, "Reflected From" },
218     { STUN_REALM, "Realm" },
219     { STUN_NONCE, "Nonce" },
220     { STUN_XOR_MAPPED_ADDRESS, "XOR Mapped Address" },
221     { STUN_MS_VERSION, "MS Version" },
222     { STUN_MS_XOR_MAPPED_ADDRESS, "MS XOR Mapped Address" },
223     { STUN_SOFTWARE, "Software" },
224     { STUN_ALTERNATE_SERVER, "Alternate Server" },
225     { STUN_FINGERPRINT, "Fingerprint" },
226     { 0, NULL }
227   };
228   unsigned int i;
229
230   for (i = 0; attrs[i].name; i++)
231   {
232     if (attrs[i].value == msg)
233       return attrs[i].name;
234   }
235   return "Unknown Attribute";
236 }
237
238
239 /**
240  * Fill the stun_header with a random request_id
241  *
242  * @param req, stun header to be filled
243  */
244 static void
245 generate_request_id(struct stun_header *req)
246 {
247   unsigned int x;
248
249   req->magic = htonl(STUN_MAGIC_COOKIE);
250   for (x = 0; x < 3; x++)
251     req->id.id[x] = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
252                                               UINT32_MAX);
253 }
254
255
256 /**
257  * Extract the STUN_MAPPED_ADDRESS from the stun response.
258  * This is used as a callback for stun_handle_response
259  * when called from stun_request.
260  *
261  * @param st, pointer where we will set the type
262  * @param attr , received stun attribute
263  * @param arg , pointer to a sockaddr_in where we will set the reported IP and port
264  * @param magic , Magic cookie
265  *
266  * @return 0 on success, other value otherwise
267  */
268 static int
269 stun_get_mapped (struct StunState *st,
270                  struct stun_attr *attr,
271                  struct sockaddr_in *arg,
272                  unsigned int magic)
273 {
274   struct stun_addr *returned_addr = (struct stun_addr *)(attr + 1);
275   struct sockaddr_in *sa = (struct sockaddr_in *)arg;
276   unsigned short type = ntohs(attr->attr);
277
278   switch (type)
279   {
280   case STUN_MAPPED_ADDRESS:
281     if (st->attr == STUN_XOR_MAPPED_ADDRESS ||
282         st->attr == STUN_MS_XOR_MAPPED_ADDRESS)
283       return 1;
284     magic = 0;
285     break;
286   case STUN_MS_XOR_MAPPED_ADDRESS:
287     if (st->attr == STUN_XOR_MAPPED_ADDRESS)
288       return 1;
289     break;
290   case STUN_XOR_MAPPED_ADDRESS:
291     break;
292   default:
293     return 1;
294   }
295   if (ntohs(attr->len) < 8 && returned_addr->family != 1)
296   {
297     return 1;
298   }
299   st->attr = type;
300   sa->sin_family = AF_INET;
301   sa->sin_port = returned_addr->port ^ htons(ntohl(magic) >> 16);
302   sa->sin_addr.s_addr = returned_addr->addr ^ magic;
303   return 0;
304 }
305
306
307 /**
308  * Handle an incoming STUN message, Do some basic sanity checks on packet size and content,
309  * try to extract a bit of information, and possibly reply.
310  * At the moment this only processes BIND requests, and returns
311  * the externally visible address of the request.
312  * If a callback is specified, invoke it with the attribute.
313  *
314  * @param data the packet
315  * @param len the length of the packet
316  * @param arg sockaddr_in where we will set our discovered packet
317  *
318  * @return, #GNUNET_OK on OK, #GNUNET_NO if the packet is invalid (not a stun packet)
319  */
320 int
321 GNUNET_NAT_stun_handle_packet (const void *data,
322                                size_t len,
323                                struct sockaddr_in *arg)
324 {
325   const struct stun_header *hdr = (const struct stun_header *)data;
326   struct stun_attr *attr;
327   struct StunState st;
328   int ret = GNUNET_OK;
329   uint32_t advertised_message_size;
330   uint32_t message_magic_cookie;
331
332   /* On entry, 'len' is the length of the udp payload. After the
333    * initial checks it becomes the size of unprocessed options,
334    * while 'data' is advanced accordingly.
335    */
336   if (len < sizeof(struct stun_header))
337   {
338     LOG (GNUNET_ERROR_TYPE_INFO,
339          "STUN packet too short (only %d, wanting at least %d)\n",
340          (int) len,
341          (int) sizeof(struct stun_header));
342     GNUNET_break_op (0);
343     return GNUNET_NO;
344   }
345   /* Skip header as it is already in hdr */
346   len -= sizeof(struct stun_header);
347   data += sizeof(struct stun_header);
348
349   /* len as advertised in the message */
350   advertised_message_size = ntohs(hdr->msglen);
351
352   message_magic_cookie = ntohl(hdr->magic);
353   /* Compare if the cookie match */
354   if(STUN_MAGIC_COOKIE != message_magic_cookie)
355   {
356     LOG (GNUNET_ERROR_TYPE_INFO,
357          "Invalid magic cookie \n");
358     return GNUNET_NO;
359   }
360
361   LOG (GNUNET_ERROR_TYPE_INFO,
362        "STUN Packet, msg %s (%04x), length: %d\n",
363        stun_msg2str(ntohs(hdr->msgtype)),
364        ntohs(hdr->msgtype),
365        advertised_message_size);
366   if (advertised_message_size > len)
367   {
368     LOG (GNUNET_ERROR_TYPE_INFO,
369          "Scrambled STUN packet length (got %d, expecting %d)\n",
370          advertised_message_size,
371          (int)len);
372     return GNUNET_NO;
373   }
374   else
375   {
376     len = advertised_message_size;
377   }
378   memset (&st,0, sizeof(st));
379
380   while (len > 0)
381   {
382     if (len < sizeof(struct stun_attr))
383     {
384       LOG (GNUNET_ERROR_TYPE_INFO,
385            "Attribute too short (got %d, expecting %d)\n",
386            (int)len,
387            (int) sizeof(struct stun_attr));
388       break;
389     }
390     attr = (struct stun_attr *)data;
391
392     /* compute total attribute length */
393     advertised_message_size = ntohs(attr->len) + sizeof(struct stun_attr);
394
395     /* Check if we still have space in our buffer */
396     if (advertised_message_size > len )
397     {
398       LOG (GNUNET_ERROR_TYPE_INFO,
399            "Inconsistent Attribute (length %d exceeds remaining msg len %d)\n",
400            advertised_message_size,
401            (int)len);
402       break;
403     }
404     stun_get_mapped (&st, attr, arg, hdr->magic);
405     /* Clear attribute id: in case previous entry was a string,
406      * this will act as the terminator for the string.
407      */
408     attr->attr = 0;
409     data += advertised_message_size;
410     len -= advertised_message_size;
411     ret = GNUNET_OK;
412   }
413   return ret;
414 }
415
416
417 /**
418  * Clean-up used memory
419  *
420  * @param handle handle to release memory for
421  */
422 static void
423 clean (struct GNUNET_NAT_STUN_Handle *handle)
424 {
425   GNUNET_free (handle->stun_server);
426   GNUNET_free (handle);
427 }
428
429
430 /**
431  * Try to establish a connection given the specified address.
432  *
433  * @param cls our `struct GNUNET_NAT_STUN_Handle *`
434  * @param addr address to try, NULL for "last call"
435  * @param addrlen length of @a addr
436  */
437 static void
438 stun_dns_callback (void *cls,
439                    const struct sockaddr *addr,
440                    socklen_t addrlen)
441 {
442   struct GNUNET_NAT_STUN_Handle *request = cls;
443   struct stun_header *req;
444   uint8_t reqdata[1024];
445   int reqlen;
446   struct sockaddr_in server;
447
448   if (NULL == addr)
449   {
450     request->dns_active = NULL;
451     if (GNUNET_NO == request->dns_success)
452     {
453       LOG (GNUNET_ERROR_TYPE_INFO,
454            "Error resolving host %s\n",
455            request->stun_server);
456       request->cb (request->cb_cls,
457                    GNUNET_NAT_ERROR_NOT_ONLINE);
458       clean (request);
459     }
460     return;
461   }
462
463   request->dns_success= GNUNET_YES;
464   memset(&server,0, sizeof(server));
465   server.sin_family = AF_INET;
466   server.sin_addr = ((struct sockaddr_in *)addr)->sin_addr;
467   server.sin_port = htons(request->stun_port);
468
469   /*Craft the simplest possible STUN packet. A request binding*/
470   req = (struct stun_header *)reqdata;
471   generate_request_id(req);
472   reqlen = 0;
473   req->msgtype = 0;
474   req->msglen = 0;
475   req->msglen = htons(reqlen);
476   req->msgtype = htons(encode_message(STUN_REQUEST, STUN_BINDING));
477
478   /* Send the packet */
479   if (-1 == GNUNET_NETWORK_socket_sendto (request->sock,
480                                           req,
481                                           ntohs(req->msglen) + sizeof(*req),
482                                           (const struct sockaddr *) &server,
483                                           sizeof (server)))
484   {
485     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
486                          "Fail to sendto");
487     request->cb (request->cb_cls,
488                  GNUNET_NAT_ERROR_INTERNAL_NETWORK_ERROR);
489     clean (request);
490     return;
491   }
492 }
493
494
495 /**
496  * Make Generic STUN request. Sends a generic stun request to the
497  * server specified using the specified socket, possibly waiting for
498  * a reply and filling the 'reply' field with the externally visible
499  * address.
500  *
501  * @param server the address of the stun server
502  * @param port port of the stun server
503  * @param sock the socket used to send the request
504  * @param cb callback in case of error
505  * @param cb_cls closure for @a cb
506  * @return #GNUNET_OK success, #GNUNET_NO on error.
507  */
508 int
509 GNUNET_NAT_stun_make_request (const char *server,
510                               uint16_t port,
511                               struct GNUNET_NETWORK_Handle *sock,
512                               GNUNET_NAT_STUN_ErrorCallback cb,
513                               void *cb_cls)
514 {
515   struct GNUNET_NAT_STUN_Handle *rh;
516
517   rh = GNUNET_new (struct GNUNET_NAT_STUN_Handle);
518   rh->sock = sock;
519   rh->cb = cb;
520   rh->cb_cls = cb_cls;
521   rh->stun_server = GNUNET_strdup (server);
522   rh->stun_port = port;
523   rh->dns_success = GNUNET_NO;
524   rh->dns_active = GNUNET_RESOLVER_ip_get (rh->stun_server,
525                                            AF_INET,
526                                            TIMEOUT,
527                                            &stun_dns_callback, rh);
528   if (NULL == rh->dns_active)
529   {
530     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
531                          "Failed DNS");
532     clean (rh);
533     return GNUNET_NO;
534   }
535   return GNUNET_OK;
536 }