2 This file is part of GNUnet.
3 Copyright (C) 2009, 2015 GNUnet e.V.
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 {
158 enum StunClasses value;
161 { STUN_REQUEST, "Request" },
162 { STUN_INDICATION, "Indication" },
163 { STUN_RESPONSE, "Response" },
164 { STUN_ERROR_RESPONSE, "Error Response" },
167 static const struct {
168 enum StunMethods value;
171 { STUN_BINDING, "Binding" },
174 static char result[32];
175 const char *msg_class = NULL;
176 const char *method = NULL;
180 value = decode_class(msg);
181 for (i = 0; classes[i].name; i++)
183 msg_class = classes[i].name;
184 if (classes[i].value == value)
187 value = decode_method(msg);
188 for (i = 0; methods[i].name; i++)
190 method = methods[i].name;
191 if (methods[i].value == value)
194 GNUNET_snprintf (result,
197 method ? : "Unknown Method",
198 msg_class ? : "Unknown Class Message");
204 * Print attribute name
206 * @param msg with a attribute type
207 * @return string with the attribute name
210 stun_attr2str (int msg)
212 static const struct {
213 enum StunAttributes value;
216 { STUN_MAPPED_ADDRESS, "Mapped Address" },
217 { STUN_RESPONSE_ADDRESS, "Response Address" },
218 { STUN_CHANGE_ADDRESS, "Change Address" },
219 { STUN_SOURCE_ADDRESS, "Source Address" },
220 { STUN_CHANGED_ADDRESS, "Changed Address" },
221 { STUN_USERNAME, "Username" },
222 { STUN_PASSWORD, "Password" },
223 { STUN_MESSAGE_INTEGRITY, "Message Integrity" },
224 { STUN_ERROR_CODE, "Error Code" },
225 { STUN_UNKNOWN_ATTRIBUTES, "Unknown Attributes" },
226 { STUN_REFLECTED_FROM, "Reflected From" },
227 { STUN_REALM, "Realm" },
228 { STUN_NONCE, "Nonce" },
229 { STUN_XOR_MAPPED_ADDRESS, "XOR Mapped Address" },
230 { STUN_MS_VERSION, "MS Version" },
231 { STUN_MS_XOR_MAPPED_ADDRESS, "MS XOR Mapped Address" },
232 { STUN_SOFTWARE, "Software" },
233 { STUN_ALTERNATE_SERVER, "Alternate Server" },
234 { STUN_FINGERPRINT, "Fingerprint" },
239 for (i = 0; attrs[i].name; i++)
241 if (attrs[i].value == msg)
242 return attrs[i].name;
244 return "Unknown Attribute";
249 * Fill the stun_header with a random request_id
251 * @param req, stun header to be filled
254 generate_request_id (struct stun_header *req)
258 req->magic = htonl(STUN_MAGIC_COOKIE);
259 for (x = 0; x < 3; x++)
260 req->id.id[x] = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
266 * Extract the STUN_MAPPED_ADDRESS from the stun response.
267 * This is used as a callback for stun_handle_response
268 * when called from stun_request.
270 * @param st, pointer where we will set the type
271 * @param attr , received stun attribute
272 * @param arg , pointer to a sockaddr_in where we will set the reported IP and port
273 * @param magic , Magic cookie
275 * @return 0 on success, other value otherwise
278 stun_get_mapped (struct StunState *st,
279 struct stun_attr *attr,
280 struct sockaddr_in *arg,
283 struct stun_addr *returned_addr = (struct stun_addr *)(attr + 1);
284 struct sockaddr_in *sa = (struct sockaddr_in *)arg;
285 unsigned short type = ntohs(attr->attr);
289 case STUN_MAPPED_ADDRESS:
290 if (st->attr == STUN_XOR_MAPPED_ADDRESS ||
291 st->attr == STUN_MS_XOR_MAPPED_ADDRESS)
295 case STUN_MS_XOR_MAPPED_ADDRESS:
296 if (st->attr == STUN_XOR_MAPPED_ADDRESS)
299 case STUN_XOR_MAPPED_ADDRESS:
304 if ( (ntohs(attr->len) < 8) &&
305 (returned_addr->family != 1) )
310 sa->sin_family = AF_INET;
311 sa->sin_port = returned_addr->port ^ htons(ntohl(magic) >> 16);
312 sa->sin_addr.s_addr = returned_addr->addr ^ magic;
318 * Handle an incoming STUN message, Do some basic sanity checks on packet size and content,
319 * try to extract a bit of information, and possibly reply.
320 * At the moment this only processes BIND requests, and returns
321 * the externally visible address of the request.
322 * If a callback is specified, invoke it with the attribute.
324 * @param data the packet
325 * @param len the length of the packet in @a data
326 * @param[out] arg sockaddr_in where we will set our discovered address
328 * @return, #GNUNET_OK on OK, #GNUNET_NO if the packet is invalid (not a stun packet)
331 GNUNET_NAT_stun_handle_packet (const void *data,
333 struct sockaddr_in *arg)
335 const struct stun_header *hdr = (const struct stun_header *)data;
336 struct stun_attr *attr;
339 uint32_t advertised_message_size;
340 uint32_t message_magic_cookie;
342 /* On entry, 'len' is the length of the udp payload. After the
343 * initial checks it becomes the size of unprocessed options,
344 * while 'data' is advanced accordingly.
346 if (len < sizeof(struct stun_header))
348 LOG (GNUNET_ERROR_TYPE_INFO,
349 "STUN packet too short (only %d, wanting at least %d)\n",
351 (int) sizeof(struct stun_header));
355 /* Skip header as it is already in hdr */
356 len -= sizeof(struct stun_header);
357 data += sizeof(struct stun_header);
359 /* len as advertised in the message */
360 advertised_message_size = ntohs(hdr->msglen);
362 message_magic_cookie = ntohl(hdr->magic);
363 /* Compare if the cookie match */
364 if (STUN_MAGIC_COOKIE != message_magic_cookie)
366 LOG (GNUNET_ERROR_TYPE_INFO,
367 "Invalid magic cookie \n");
371 LOG (GNUNET_ERROR_TYPE_INFO,
372 "STUN Packet, msg %s (%04x), length: %d\n",
373 stun_msg2str(ntohs(hdr->msgtype)),
375 advertised_message_size);
376 if (advertised_message_size > len)
378 LOG (GNUNET_ERROR_TYPE_INFO,
379 "Scrambled STUN packet length (got %d, expecting %d)\n",
380 advertised_message_size,
384 len = advertised_message_size;
385 memset (&st, 0, sizeof(st));
389 if (len < sizeof(struct stun_attr))
391 LOG (GNUNET_ERROR_TYPE_INFO,
392 "Attribute too short (got %d, expecting %d)\n",
394 (int) sizeof(struct stun_attr));
397 attr = (struct stun_attr *)data;
399 /* compute total attribute length */
400 advertised_message_size = ntohs(attr->len) + sizeof(struct stun_attr);
402 /* Check if we still have space in our buffer */
403 if (advertised_message_size > len )
405 LOG (GNUNET_ERROR_TYPE_INFO,
406 "Inconsistent Attribute (length %d exceeds remaining msg len %d)\n",
407 advertised_message_size,
411 stun_get_mapped (&st,
415 /* Clear attribute id: in case previous entry was a string,
416 * this will act as the terminator for the string.
419 data += advertised_message_size;
420 len -= advertised_message_size;
428 * Cancel active STUN request. Frees associated resources
429 * and ensures that the callback is no longer invoked.
431 * @param rh request to cancel
434 GNUNET_NAT_stun_make_request_cancel (struct GNUNET_NAT_STUN_Handle *rh)
436 if (NULL != rh->dns_active)
438 GNUNET_RESOLVER_request_cancel (rh->dns_active);
439 rh->dns_active = NULL;
441 GNUNET_free (rh->stun_server);
447 * Try to establish a connection given the specified address.
449 * @param cls our `struct GNUNET_NAT_STUN_Handle *`
450 * @param addr address to try, NULL for "last call"
451 * @param addrlen length of @a addr
454 stun_dns_callback (void *cls,
455 const struct sockaddr *addr,
458 struct GNUNET_NAT_STUN_Handle *rh = cls;
459 struct stun_header *req;
460 uint8_t reqdata[1024];
462 struct sockaddr_in server;
464 rh->dns_active = NULL;
467 if (GNUNET_NO == rh->dns_success)
469 LOG (GNUNET_ERROR_TYPE_INFO,
470 "Error resolving host %s\n",
473 GNUNET_NAT_ERROR_NOT_ONLINE);
474 GNUNET_NAT_stun_make_request_cancel (rh);
479 rh->dns_success = GNUNET_YES;
480 memset (&server,0, sizeof(server));
481 server.sin_family = AF_INET;
482 server.sin_addr = ((struct sockaddr_in *)addr)->sin_addr;
483 server.sin_port = htons(rh->stun_port);
484 #if HAVE_SOCKADDR_IN_SIN_LEN
485 server.sin_len = (u_char) sizeof (struct sockaddr_in);
488 /*Craft the simplest possible STUN packet. A request binding*/
489 req = (struct stun_header *)reqdata;
490 generate_request_id(req);
494 req->msglen = htons(reqlen);
495 req->msgtype = htons(encode_message(STUN_REQUEST, STUN_BINDING));
497 /* Send the packet */
498 if (-1 == GNUNET_NETWORK_socket_sendto (rh->sock,
500 ntohs(req->msglen) + sizeof(*req),
501 (const struct sockaddr *) &server,
504 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
507 GNUNET_NAT_ERROR_INTERNAL_NETWORK_ERROR);
508 GNUNET_NAT_stun_make_request_cancel (rh);
511 /* sending STUN request done, let's wait for replies... */
513 GNUNET_NAT_ERROR_SUCCESS);
514 GNUNET_NAT_stun_make_request_cancel (rh);
519 * Make Generic STUN request. Sends a generic stun request to the
520 * server specified using the specified socket, possibly waiting for
521 * a reply and filling the 'reply' field with the externally visible
524 * @param server the address of the stun server
525 * @param port port of the stun server
526 * @param sock the socket used to send the request
527 * @param cb callback in case of error
528 * @param cb_cls closure for @a cb
529 * @return NULL on error
531 struct GNUNET_NAT_STUN_Handle *
532 GNUNET_NAT_stun_make_request (const char *server,
534 struct GNUNET_NETWORK_Handle *sock,
535 GNUNET_NAT_STUN_ErrorCallback cb,
538 struct GNUNET_NAT_STUN_Handle *rh;
540 rh = GNUNET_new (struct GNUNET_NAT_STUN_Handle);
544 rh->stun_server = GNUNET_strdup (server);
545 rh->stun_port = port;
546 rh->dns_success = GNUNET_NO;
547 rh->dns_active = GNUNET_RESOLVER_ip_get (rh->stun_server,
550 &stun_dns_callback, rh);
551 if (NULL == rh->dns_active)
553 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
555 GNUNET_NAT_stun_make_request_cancel (rh);
561 /* end of nat_stun.c */