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 * Encode a class and method to a compatible STUN format
109 * @param msg_class class to be converted
110 * @param method method to be converted
111 * @return message in a STUN compatible format
114 encode_message (enum StunClasses msg_class,
115 enum StunMethods method)
117 return ((msg_class & 1) << 4) | ((msg_class & 2) << 7) |
118 (method & 0x000f) | ((method & 0x0070) << 1) | ((method & 0x0f800) << 2);
123 * Fill the stun_header with a random request_id
125 * @param req, stun header to be filled
128 generate_request_id (struct stun_header *req)
132 req->magic = htonl(STUN_MAGIC_COOKIE);
133 for (x = 0; x < 3; x++)
134 req->id.id[x] = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
140 * Extract the STUN_MAPPED_ADDRESS from the stun response.
141 * This is used as a callback for stun_handle_response
142 * when called from stun_request.
144 * @param st, pointer where we will set the type
145 * @param attr , received stun attribute
146 * @param arg , pointer to a sockaddr_in where we will set the reported IP and port
147 * @param magic , Magic cookie
149 * @return 0 on success, other value otherwise
152 stun_get_mapped (struct StunState *st,
153 struct stun_attr *attr,
154 struct sockaddr_in *arg,
157 struct stun_addr *returned_addr = (struct stun_addr *)(attr + 1);
158 struct sockaddr_in *sa = (struct sockaddr_in *)arg;
159 unsigned short type = ntohs(attr->attr);
163 case STUN_MAPPED_ADDRESS:
164 if (st->attr == STUN_XOR_MAPPED_ADDRESS ||
165 st->attr == STUN_MS_XOR_MAPPED_ADDRESS)
169 case STUN_MS_XOR_MAPPED_ADDRESS:
170 if (st->attr == STUN_XOR_MAPPED_ADDRESS)
173 case STUN_XOR_MAPPED_ADDRESS:
178 if ( (ntohs(attr->len) < 8) &&
179 (returned_addr->family != 1) )
184 sa->sin_family = AF_INET;
185 sa->sin_port = returned_addr->port ^ htons(ntohl(magic) >> 16);
186 sa->sin_addr.s_addr = returned_addr->addr ^ magic;
192 * Handle an incoming STUN message, Do some basic sanity checks on packet size and content,
193 * try to extract a bit of information, and possibly reply.
194 * At the moment this only processes BIND requests, and returns
195 * the externally visible address of the request.
196 * If a callback is specified, invoke it with the attribute.
198 * @param data the packet
199 * @param len the length of the packet in @a data
200 * @param[out] arg sockaddr_in where we will set our discovered address
202 * @return, #GNUNET_OK on OK, #GNUNET_NO if the packet is invalid (not a stun packet)
205 GNUNET_NAT_stun_handle_packet (const void *data,
207 struct sockaddr_in *arg)
209 const struct stun_header *hdr = (const struct stun_header *)data;
210 struct stun_attr *attr;
213 uint32_t advertised_message_size;
214 uint32_t message_magic_cookie;
216 /* On entry, 'len' is the length of the udp payload. After the
217 * initial checks it becomes the size of unprocessed options,
218 * while 'data' is advanced accordingly.
220 if (len < sizeof(struct stun_header))
222 LOG (GNUNET_ERROR_TYPE_INFO,
223 "STUN packet too short (only %d, wanting at least %d)\n",
225 (int) sizeof(struct stun_header));
229 /* Skip header as it is already in hdr */
230 len -= sizeof(struct stun_header);
231 data += sizeof(struct stun_header);
233 /* len as advertised in the message */
234 advertised_message_size = ntohs(hdr->msglen);
236 message_magic_cookie = ntohl(hdr->magic);
237 /* Compare if the cookie match */
238 if (STUN_MAGIC_COOKIE != message_magic_cookie)
240 LOG (GNUNET_ERROR_TYPE_INFO,
241 "Invalid magic cookie \n");
245 LOG (GNUNET_ERROR_TYPE_INFO,
246 "STUN Packet, msg %s (%04x), length: %d\n",
247 stun_msg2str(ntohs(hdr->msgtype)),
249 advertised_message_size);
250 if (advertised_message_size > len)
252 LOG (GNUNET_ERROR_TYPE_INFO,
253 "Scrambled STUN packet length (got %d, expecting %d)\n",
254 advertised_message_size,
258 len = advertised_message_size;
259 memset (&st, 0, sizeof(st));
263 if (len < sizeof(struct stun_attr))
265 LOG (GNUNET_ERROR_TYPE_INFO,
266 "Attribute too short (got %d, expecting %d)\n",
268 (int) sizeof(struct stun_attr));
271 attr = (struct stun_attr *)data;
273 /* compute total attribute length */
274 advertised_message_size = ntohs(attr->len) + sizeof(struct stun_attr);
276 /* Check if we still have space in our buffer */
277 if (advertised_message_size > len )
279 LOG (GNUNET_ERROR_TYPE_INFO,
280 "Inconsistent Attribute (length %d exceeds remaining msg len %d)\n",
281 advertised_message_size,
285 stun_get_mapped (&st,
289 /* Clear attribute id: in case previous entry was a string,
290 * this will act as the terminator for the string.
293 data += advertised_message_size;
294 len -= advertised_message_size;
302 * Cancel active STUN request. Frees associated resources
303 * and ensures that the callback is no longer invoked.
305 * @param rh request to cancel
308 GNUNET_NAT_stun_make_request_cancel (struct GNUNET_NAT_STUN_Handle *rh)
310 if (NULL != rh->dns_active)
312 GNUNET_RESOLVER_request_cancel (rh->dns_active);
313 rh->dns_active = NULL;
315 GNUNET_free (rh->stun_server);
321 * Try to establish a connection given the specified address.
323 * @param cls our `struct GNUNET_NAT_STUN_Handle *`
324 * @param addr address to try, NULL for "last call"
325 * @param addrlen length of @a addr
328 stun_dns_callback (void *cls,
329 const struct sockaddr *addr,
332 struct GNUNET_NAT_STUN_Handle *rh = cls;
333 struct stun_header *req;
334 uint8_t reqdata[1024];
336 struct sockaddr_in server;
340 rh->dns_active = NULL;
341 if (GNUNET_NO == rh->dns_success)
343 LOG (GNUNET_ERROR_TYPE_INFO,
344 "Error resolving host %s\n",
347 GNUNET_NAT_ERROR_NOT_ONLINE);
349 else if (GNUNET_SYSERR == rh->dns_success)
352 GNUNET_NAT_ERROR_INTERNAL_NETWORK_ERROR);
357 GNUNET_NAT_ERROR_SUCCESS);
359 GNUNET_NAT_stun_make_request_cancel (rh);
363 rh->dns_success = GNUNET_YES;
364 memset (&server,0, sizeof(server));
365 server.sin_family = AF_INET;
366 server.sin_addr = ((struct sockaddr_in *)addr)->sin_addr;
367 server.sin_port = htons(rh->stun_port);
368 #if HAVE_SOCKADDR_IN_SIN_LEN
369 server.sin_len = (u_char) sizeof (struct sockaddr_in);
372 /*Craft the simplest possible STUN packet. A request binding*/
373 req = (struct stun_header *)reqdata;
374 generate_request_id (req);
378 req->msglen = htons (reqlen);
379 req->msgtype = htons (encode_message (STUN_REQUEST,
382 /* Send the packet */
384 GNUNET_NETWORK_socket_sendto (rh->sock,
386 ntohs(req->msglen) + sizeof(*req),
387 (const struct sockaddr *) &server,
390 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
392 rh->dns_success = GNUNET_SYSERR;
399 * Make Generic STUN request. Sends a generic stun request to the
400 * server specified using the specified socket, possibly waiting for
401 * a reply and filling the 'reply' field with the externally visible
404 * @param server the address of the stun server
405 * @param port port of the stun server
406 * @param sock the socket used to send the request
407 * @param cb callback in case of error
408 * @param cb_cls closure for @a cb
409 * @return NULL on error
411 struct GNUNET_NAT_STUN_Handle *
412 GNUNET_NAT_stun_make_request (const char *server,
414 struct GNUNET_NETWORK_Handle *sock,
415 GNUNET_NAT_STUN_ErrorCallback cb,
418 struct GNUNET_NAT_STUN_Handle *rh;
420 rh = GNUNET_new (struct GNUNET_NAT_STUN_Handle);
424 rh->stun_server = GNUNET_strdup (server);
425 rh->stun_port = port;
426 rh->dns_success = GNUNET_NO;
427 rh->dns_active = GNUNET_RESOLVER_ip_get (rh->stun_server,
430 &stun_dns_callback, rh);
431 if (NULL == rh->dns_active)
433 GNUNET_NAT_stun_make_request_cancel (rh);
439 /* end of nat_stun.c */