2 This file is part of GNUnet.
3 Copyright (C) 2009, 2015 Christian Grothoff (and other contributing authors)
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.
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.
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.
21 * This code provides some support for doing STUN transactions.
22 * We send simplest possible packet ia REQUEST with BIND to a STUN server.
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.
31 * This code was based on ministun.c.
33 * @file nat/nat_stun.c
34 * @brief Functions for STUN functionality
35 * @author Bruno Souza Cabral
39 #include "gnunet_util_lib.h"
40 #include "gnunet_resolver_service.h"
41 #include "gnunet_nat_lib.h"
46 #define LOG(kind,...) GNUNET_log_from (kind, "stun", __VA_ARGS__)
48 #define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15)
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.
56 struct GNUNET_NAT_STUN_Handle
60 * Handle to a pending DNS lookup request.
62 struct GNUNET_RESOLVER_RequestHandle *dns_active;
65 * Handle to the listen socket
67 struct GNUNET_NETWORK_Handle *sock;
75 * Function to call when a error occours
77 GNUNET_NAT_STUN_ErrorCallback cb;
85 * Do we got a DNS resolution successfully?
98 * here we store credentials extracted from a message
107 * Convert a message to a StunClass
109 * @param msg the received message
110 * @return the converted StunClass
113 decode_class(int msg)
115 /* Sorry for the magic, but this maps the class according to rfc5245 */
116 return ((msg & 0x0010) >> 4) | ((msg & 0x0100) >> 7);
120 * Convert a message to a StunMethod
122 * @param msg the received message
123 * @return the converted StunMethod
126 decode_method(int msg)
128 return (msg & 0x000f) | ((msg & 0x00e0) >> 1) | ((msg & 0x3e00) >> 2);
133 * Encode a class and method to a compatible STUN format
135 * @param msg_class class to be converted
136 * @param method method to be converted
137 * @return message in a STUN compatible format
140 encode_message (enum StunClasses msg_class,
141 enum StunMethods method)
143 return ((msg_class & 1) << 4) | ((msg_class & 2) << 7) |
144 (method & 0x000f) | ((method & 0x0070) << 1) | ((method & 0x0f800) << 2);
149 * Print a class and method from a STUN message
152 * @return string with the message class and method
155 stun_msg2str(int msg)
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" },
164 static const struct { enum StunMethods value; const char *name; } methods[] = {
165 { STUN_BINDING, "Binding" },
168 static char result[32];
169 const char *msg_class = NULL;
170 const char *method = NULL;
174 value = decode_class(msg);
175 for (i = 0; classes[i].name; i++)
177 msg_class = classes[i].name;
178 if (classes[i].value == value)
181 value = decode_method(msg);
182 for (i = 0; methods[i].name; i++)
184 method = methods[i].name;
185 if (methods[i].value == value)
188 GNUNET_snprintf (result,
191 method ? : "Unknown Method",
192 msg_class ? : "Unknown Class Message");
198 * Print attribute name
200 * @param msg with a attribute type
201 * @return string with the attribute name
204 stun_attr2str(int msg)
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" },
230 for (i = 0; attrs[i].name; i++)
232 if (attrs[i].value == msg)
233 return attrs[i].name;
235 return "Unknown Attribute";
240 * Fill the stun_header with a random request_id
242 * @param req, stun header to be filled
245 generate_request_id(struct stun_header *req)
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,
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.
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
266 * @return 0 on success, other value otherwise
269 stun_get_mapped (struct StunState *st,
270 struct stun_attr *attr,
271 struct sockaddr_in *arg,
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);
280 case STUN_MAPPED_ADDRESS:
281 if (st->attr == STUN_XOR_MAPPED_ADDRESS ||
282 st->attr == STUN_MS_XOR_MAPPED_ADDRESS)
286 case STUN_MS_XOR_MAPPED_ADDRESS:
287 if (st->attr == STUN_XOR_MAPPED_ADDRESS)
290 case STUN_XOR_MAPPED_ADDRESS:
295 if (ntohs(attr->len) < 8 && returned_addr->family != 1)
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;
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.
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
318 * @return, #GNUNET_OK on OK, #GNUNET_NO if the packet is invalid (not a stun packet)
321 GNUNET_NAT_stun_handle_packet (const void *data,
323 struct sockaddr_in *arg)
325 const struct stun_header *hdr = (const struct stun_header *)data;
326 struct stun_attr *attr;
329 uint32_t advertised_message_size;
330 uint32_t message_magic_cookie;
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.
336 if (len < sizeof(struct stun_header))
338 LOG (GNUNET_ERROR_TYPE_INFO,
339 "STUN packet too short (only %d, wanting at least %d)\n",
341 (int) sizeof(struct stun_header));
345 /* Skip header as it is already in hdr */
346 len -= sizeof(struct stun_header);
347 data += sizeof(struct stun_header);
349 /* len as advertised in the message */
350 advertised_message_size = ntohs(hdr->msglen);
352 message_magic_cookie = ntohl(hdr->magic);
353 /* Compare if the cookie match */
354 if(STUN_MAGIC_COOKIE != message_magic_cookie)
356 LOG (GNUNET_ERROR_TYPE_INFO,
357 "Invalid magic cookie \n");
361 LOG (GNUNET_ERROR_TYPE_INFO,
362 "STUN Packet, msg %s (%04x), length: %d\n",
363 stun_msg2str(ntohs(hdr->msgtype)),
365 advertised_message_size);
366 if (advertised_message_size > len)
368 LOG (GNUNET_ERROR_TYPE_INFO,
369 "Scrambled STUN packet length (got %d, expecting %d)\n",
370 advertised_message_size,
376 len = advertised_message_size;
378 memset (&st,0, sizeof(st));
382 if (len < sizeof(struct stun_attr))
384 LOG (GNUNET_ERROR_TYPE_INFO,
385 "Attribute too short (got %d, expecting %d)\n",
387 (int) sizeof(struct stun_attr));
390 attr = (struct stun_attr *)data;
392 /* compute total attribute length */
393 advertised_message_size = ntohs(attr->len) + sizeof(struct stun_attr);
395 /* Check if we still have space in our buffer */
396 if (advertised_message_size > len )
398 LOG (GNUNET_ERROR_TYPE_INFO,
399 "Inconsistent Attribute (length %d exceeds remaining msg len %d)\n",
400 advertised_message_size,
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.
409 data += advertised_message_size;
410 len -= advertised_message_size;
418 * Clean-up used memory
420 * @param handle handle to release memory for
423 clean (struct GNUNET_NAT_STUN_Handle *handle)
425 GNUNET_free (handle->stun_server);
426 GNUNET_free (handle);
431 * Try to establish a connection given the specified address.
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
438 stun_dns_callback (void *cls,
439 const struct sockaddr *addr,
442 struct GNUNET_NAT_STUN_Handle *request = cls;
443 struct stun_header *req;
444 uint8_t reqdata[1024];
446 struct sockaddr_in server;
450 request->dns_active = NULL;
451 if (GNUNET_NO == request->dns_success)
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);
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);
469 /*Craft the simplest possible STUN packet. A request binding*/
470 req = (struct stun_header *)reqdata;
471 generate_request_id(req);
475 req->msglen = htons(reqlen);
476 req->msgtype = htons(encode_message(STUN_REQUEST, STUN_BINDING));
478 /* Send the packet */
479 if (-1 == GNUNET_NETWORK_socket_sendto (request->sock,
481 ntohs(req->msglen) + sizeof(*req),
482 (const struct sockaddr *) &server,
485 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
487 request->cb (request->cb_cls,
488 GNUNET_NAT_ERROR_INTERNAL_NETWORK_ERROR);
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
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.
509 GNUNET_NAT_stun_make_request (const char *server,
511 struct GNUNET_NETWORK_Handle *sock,
512 GNUNET_NAT_STUN_ErrorCallback cb,
515 struct GNUNET_NAT_STUN_Handle *rh;
517 rh = GNUNET_new (struct GNUNET_NAT_STUN_Handle);
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,
527 &stun_dns_callback, rh);
528 if (NULL == rh->dns_active)
530 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,