2 This file is part of GNUnet.
\r
3 Copyright (C) 2009, 2015 Christian Grothoff (and other contributing authors)
\r
5 GNUnet is free software; you can redistribute it and/or modify
\r
6 it under the terms of the GNU General Public License as published
\r
7 by the Free Software Foundation; either version 3, or (at your
\r
8 option) any later version.
\r
10 GNUnet is distributed in the hope that it will be useful, but
\r
11 WITHOUT ANY WARRANTY; without even the implied warranty of
\r
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
\r
13 General Public License for more details.
\r
15 You should have received a copy of the GNU General Public License
\r
16 along with GNUnet; see the file COPYING. If not, write to the
\r
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
\r
18 Boston, MA 02111-1307, USA.
\r
22 * Testcase for STUN server resolution
\r
24 * @file nat/test_stun.c
\r
25 * @brief Testcase for STUN library
\r
26 * @author Bruno Souza Cabral - Major rewrite.
\r
27 * @autor Mark Spencer (Original code - borrowed from Asterisk)
\r
32 #include "platform.h"
\r
33 #include "gnunet_util_lib.h"
\r
34 #include "gnunet_program_lib.h"
\r
35 #include "gnunet_scheduler_lib.h"
\r
36 #include "gnunet_nat_lib.h"
\r
39 #include "test_stun.h"
\r
41 #define LOG(kind,...) GNUNET_log_from (kind, "stun", __VA_ARGS__)
\r
44 * The port the test service is running on (default 7895)
\r
46 static unsigned long port = 7895;
\r
49 static char *stun_server = STUN_SERVER;
\r
50 static int stun_port = STUN_PORT;
\r
53 * The listen socket of the service for IPv4
\r
55 static struct GNUNET_NETWORK_Handle *lsock4;
\r
59 * The listen task ID for IPv4
\r
61 static struct GNUNET_SCHEDULER_Task * ltask4;
\r
66 * Handle to a request given to the resolver. Can be used to cancel
\r
67 * the request prior to the timeout or successful execution. Also
\r
68 * used to track our internal state for the request.
\r
70 struct GNUNET_NAT_StunRequestHandle {
\r
73 * Handle to a pending DNS lookup request.
\r
75 struct GNUNET_RESOLVER_RequestHandle *dns_active;
\r
79 * Handle to the listen socket
\r
81 struct GNUNET_NETWORK_Handle * sock;
\r
88 /* here we store credentials extracted from a message */
\r
93 /* callback type to be invoked on stun responses. */
\r
94 typedef int (stun_cb_f)(struct StunState *st, struct stun_attr *attr, void *arg, unsigned int magic);
\r
99 * Convert a message to a StunClass
\r
101 * @param msg the received message
\r
102 * @return the converted StunClass
\r
104 static int decode_class(int msg)
\r
106 return ((msg & 0x0010) >> 4) | ((msg & 0x0100) >> 7);
\r
110 * Convert a message to a StunMethod
\r
112 * @param msg the received message
\r
113 * @return the converted StunMethod
\r
115 static int decode_method(int msg)
\r
117 return (msg & 0x000f) | ((msg & 0x00e0) >> 1) | ((msg & 0x3e00) >> 2);
\r
121 * Encode a class and method to a compatible STUN format
\r
123 * @param msg_class class to be converted
\r
124 * @param method method to be converted
\r
125 * @return message in a STUN compatible format
\r
127 static int encode_message(StunClasses msg_class, StunMethods method)
\r
129 return ((msg_class & 1) << 4) | ((msg_class & 2) << 7) |
\r
130 (method & 0x000f) | ((method & 0x0070) << 1) | ((method & 0x0f800) << 2);
\r
133 /* helper function to print message names */
\r
134 static const char *stun_msg2str(int msg)
\r
137 const struct { enum StunClasses value; const char *name; } classes[] = {
\r
138 { STUN_REQUEST, "Request" },
\r
139 { STUN_INDICATION, "Indication" },
\r
140 { STUN_RESPONSE, "Response" },
\r
141 { STUN_ERROR_RESPONSE, "Error Response" },
\r
145 const struct { enum StunMethods value; const char *name; } methods[] = {
\r
146 { STUN_BINDING, "Binding" },
\r
150 static char result[32];
\r
151 const char *msg_class = NULL;
\r
152 const char *method = NULL;
\r
156 value = decode_class(msg);
\r
157 for (i = 0; classes[i].name; i++) {
\r
158 msg_class = classes[i].name;
\r
159 if (classes[i].value == value)
\r
162 value = decode_method(msg);
\r
163 for (i = 0; methods[i].name; i++) {
\r
164 method = methods[i].name;
\r
165 if (methods[i].value == value)
\r
168 snprintf(result, sizeof(result), "%s %s",
\r
169 method ? : "Unknown Method",
\r
170 msg_class ? : "Unknown Class Message");
\r
174 /* helper function to print attribute names */
\r
175 static const char *stun_attr2str(int msg)
\r
177 const struct { enum StunAttributes value; const char *name; } attrs[] = {
\r
178 { STUN_MAPPED_ADDRESS, "Mapped Address" },
\r
179 { STUN_RESPONSE_ADDRESS, "Response Address" },
\r
180 { STUN_CHANGE_ADDRESS, "Change Address" },
\r
181 { STUN_SOURCE_ADDRESS, "Source Address" },
\r
182 { STUN_CHANGED_ADDRESS, "Changed Address" },
\r
183 { STUN_USERNAME, "Username" },
\r
184 { STUN_PASSWORD, "Password" },
\r
185 { STUN_MESSAGE_INTEGRITY, "Message Integrity" },
\r
186 { STUN_ERROR_CODE, "Error Code" },
\r
187 { STUN_UNKNOWN_ATTRIBUTES, "Unknown Attributes" },
\r
188 { STUN_REFLECTED_FROM, "Reflected From" },
\r
189 { STUN_REALM, "Realm" },
\r
190 { STUN_NONCE, "Nonce" },
\r
191 { STUN_XOR_MAPPED_ADDRESS, "XOR Mapped Address" },
\r
192 { STUN_MS_VERSION, "MS Version" },
\r
193 { STUN_MS_XOR_MAPPED_ADDRESS, "MS XOR Mapped Address" },
\r
194 { STUN_SOFTWARE, "Software" },
\r
195 { STUN_ALTERNATE_SERVER, "Alternate Server" },
\r
196 { STUN_FINGERPRINT, "Fingerprint" },
\r
201 for (i = 0; attrs[i].name; i++) {
\r
202 if (attrs[i].value == msg)
\r
203 return attrs[i].name;
\r
205 return "Unknown Attribute";
\r
210 static int stun_process_attr(struct StunState *state, struct stun_attr *attr)
\r
212 LOG (GNUNET_ERROR_TYPE_INFO,
\r
213 "Found STUN Attribute %s (%04x), length %d\n",
\r
214 stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
\r
216 switch (ntohs(attr->attr)) {
\r
217 case STUN_MAPPED_ADDRESS:
\r
218 case STUN_XOR_MAPPED_ADDRESS:
\r
219 case STUN_MS_XOR_MAPPED_ADDRESS:
\r
222 LOG (GNUNET_ERROR_TYPE_INFO,
\r
223 "Ignoring STUN Attribute %s (%04x), length %d\n",
\r
224 stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
\r
231 /* helper function to generate a random request id */
\r
233 generate_request_id(struct stun_header *req)
\r
236 req->magic = htonl(STUN_MAGIC_COOKIE);
\r
237 for (x = 0; x < 3; x++)
\r
238 req->id.id[x] = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
\r
243 /* handle an incoming STUN message.
\r
245 * Do some basic sanity checks on packet size and content,
\r
246 * try to extract a bit of information, and possibly reply.
\r
247 * At the moment this only processes BIND requests, and returns
\r
248 * the externally visible address of the request.
\r
249 * If a callback is specified, invoke it with the attribute.
\r
252 stun_handle_packet(const uint8_t *data, size_t len, stun_cb_f *stun_cb, void *arg)
\r
254 struct stun_header *hdr = (struct stun_header *)data;
\r
255 struct stun_attr *attr;
\r
256 struct StunState st;
\r
257 int ret = STUN_IGNORE;
\r
259 uint32_t advertised_message_size;
\r
260 uint32_t message_magic_cookie;
\r
263 /* On entry, 'len' is the length of the udp payload. After the
\r
264 * initial checks it becomes the size of unprocessed options,
\r
265 * while 'data' is advanced accordingly.
\r
267 if (len < sizeof(struct stun_header)) {
\r
268 LOG (GNUNET_ERROR_TYPE_INFO,
\r
269 "STUN packet too short (only %d, wanting at least %d)\n", (int) len, (int) sizeof(struct stun_header));
\r
270 GNUNET_break_op (0);
\r
273 /* Skip header as it is already in hdr */
\r
274 len -= sizeof(struct stun_header);
\r
275 data += sizeof(struct stun_header);
\r
277 /* len as advertised in the message */
\r
278 advertised_message_size = ntohs(hdr->msglen);
\r
280 message_magic_cookie = ntohl(hdr->magic);
\r
281 /* Compare if the cookie match */
\r
282 if(STUN_MAGIC_COOKIE != message_magic_cookie){
\r
283 LOG (GNUNET_ERROR_TYPE_INFO,
\r
284 "Invalid magic cookie \n");
\r
285 GNUNET_break_op (0);
\r
290 LOG (GNUNET_ERROR_TYPE_INFO, "STUN Packet, msg %s (%04x), length: %d\n", stun_msg2str(ntohs(hdr->msgtype)), ntohs(hdr->msgtype), advertised_message_size);
\r
293 if (advertised_message_size > len) {
\r
294 LOG (GNUNET_ERROR_TYPE_INFO, "Scrambled STUN packet length (got %d, expecting %d)\n", advertised_message_size, (int)len);
\r
295 GNUNET_break_op (0);
\r
297 len = advertised_message_size;
\r
299 /* Zero the struct */
\r
300 memset(&st,0, sizeof(st));
\r
303 if (len < sizeof(struct stun_attr)) {
\r
304 LOG (GNUNET_ERROR_TYPE_INFO, "Attribute too short (got %d, expecting %d)\n", (int)len, (int) sizeof(struct stun_attr));
\r
305 GNUNET_break_op (0);
\r
308 attr = (struct stun_attr *)data;
\r
310 /* compute total attribute length */
\r
311 advertised_message_size = ntohs(attr->len) + sizeof(struct stun_attr);
\r
313 /* Check if we still have space in our buffer */
\r
314 if (advertised_message_size > len ) {
\r
315 LOG (GNUNET_ERROR_TYPE_INFO, "Inconsistent Attribute (length %d exceeds remaining msg len %d)\n", advertised_message_size, (int)len);
\r
316 GNUNET_break_op (0);
\r
321 stun_cb(&st, attr, arg, hdr->magic);
\r
324 if (stun_process_attr(&st, attr)) {
\r
325 LOG (GNUNET_ERROR_TYPE_INFO, "Failed to handle attribute %s (%04x)\n", stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr));
\r
328 /* Clear attribute id: in case previous entry was a string,
\r
329 * this will act as the terminator for the string.
\r
332 data += advertised_message_size;
\r
333 len -= advertised_message_size;
\r
339 /* Extract the STUN_MAPPED_ADDRESS from the stun response.
\r
340 * This is used as a callback for stun_handle_response
\r
341 * when called from stun_request.
\r
344 stun_get_mapped(struct StunState *st, struct stun_attr *attr, void *arg, unsigned int magic)
\r
346 struct stun_addr *returned_addr = (struct stun_addr *)(attr + 1);
\r
347 struct sockaddr_in *sa = (struct sockaddr_in *)arg;
\r
348 unsigned short type = ntohs(attr->attr);
\r
351 case STUN_MAPPED_ADDRESS:
\r
352 if (st->attr == STUN_XOR_MAPPED_ADDRESS ||
\r
353 st->attr == STUN_MS_XOR_MAPPED_ADDRESS)
\r
357 case STUN_MS_XOR_MAPPED_ADDRESS:
\r
358 if (st->attr == STUN_XOR_MAPPED_ADDRESS)
\r
361 case STUN_XOR_MAPPED_ADDRESS:
\r
366 if (ntohs(attr->len) < 8 && returned_addr->family != 1) {
\r
371 sa->sin_port = returned_addr->port ^ htons(ntohl(magic) >> 16);
\r
372 sa->sin_addr.s_addr = returned_addr->addr ^ magic;
\r
378 * Try to establish a connection given the specified address.
\r
379 * This function is called by the resolver once we have a DNS reply.
\r
381 * @param cls our `struct GNUNET_CONNECTION_Handle *`
\r
382 * @param addr address to try, NULL for "last call"
\r
383 * @param addrlen length of @a addr
\r
386 try_connect_using_address (void *cls,
\r
387 const struct sockaddr *addr,
\r
388 socklen_t addrlen) {
\r
391 struct GNUNET_NAT_StunRequestHandle *request = cls;
\r
393 struct stun_header *req;
\r
394 uint8_t reqdata[1024];
\r
397 if(NULL == request) {
\r
398 LOG (GNUNET_ERROR_TYPE_INFO, "Empty request\n");
\r
403 if (NULL == addr) {
\r
404 request->dns_active = NULL;
\r
405 LOG (GNUNET_ERROR_TYPE_INFO, "Error resolving host %s\n", stun_server);
\r
412 struct sockaddr_in server;
\r
415 memset(&server,0, sizeof(server));
\r
416 server.sin_family = AF_INET;
\r
418 struct sockaddr_in *addr_in = (struct sockaddr_in *)addr;
\r
420 server.sin_addr = addr_in->sin_addr;
\r
421 server.sin_port = htons(stun_port);
\r
424 /*Craft the simplest possible STUN packet. A request binding*/
\r
425 req = (struct stun_header *)reqdata;
\r
426 generate_request_id(req);
\r
432 req->msglen = htons(reqlen);
\r
433 req->msgtype = htons(encode_message(STUN_REQUEST, STUN_BINDING));
\r
436 if (-1 == GNUNET_NETWORK_socket_sendto (request->sock, req, ntohs(req->msglen) + sizeof(*req),
\r
437 (const struct sockaddr *) &server, sizeof (server)))
\r
439 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "Failt to sendto");
\r
445 /* Generic STUN request
\r
446 * Send a generic stun request to the server specified,
\r
447 * possibly waiting for a reply and filling the 'reply' field with
\r
448 * the externally visible address.
\r
450 * \param s the socket used to send the request
\r
451 * \return 0 on success, other values on error.
\r
453 struct GNUNET_NAT_StunRequestHandle *
\r
454 stun_request(struct GNUNET_NETWORK_Handle * sock)
\r
458 struct GNUNET_NAT_StunRequestHandle *rh;
\r
461 rh = GNUNET_malloc (sizeof (struct GNUNET_NAT_StunRequestHandle));
\r
465 rh->dns_active = GNUNET_RESOLVER_ip_get (stun_server, AF_INET,
\r
466 GNUNET_CONNECTION_CONNECT_RETRY_TIMEOUT,
\r
467 &try_connect_using_address, rh);
\r
476 print_answer(struct sockaddr_in* answer)
\r
478 printf("External IP is: %s , with port %d\n", inet_ntoa(answer->sin_addr), ntohs(answer->sin_port));
\r
483 * Activity on our incoming socket. Read data from the
\r
484 * incoming connection.
\r
487 * @param tc scheduler context
\r
490 do_udp_read (void *cls,
\r
491 const struct GNUNET_SCHEDULER_TaskContext *tc)
\r
493 //struct GNUNET_NAT_Test *tst = cls;
\r
494 unsigned char reply_buf[1024];
\r
496 struct sockaddr_in answer;
\r
499 if ((0 != (tc->reason & GNUNET_SCHEDULER_REASON_READ_READY)) &&
\r
500 (GNUNET_NETWORK_fdset_isset (tc->read_ready,
\r
503 rlen = GNUNET_NETWORK_socket_recv (lsock4, reply_buf, sizeof (reply_buf));
\r
504 printf("Recivied something of size %d", rlen);
\r
506 //Lets handle the packet
\r
507 memset(&answer, 0, sizeof(struct sockaddr_in));
\r
508 stun_handle_packet(reply_buf, rlen, stun_get_mapped, &answer);
\r
510 //TODO: Delete the object
\r
512 print_answer(&answer);
\r
520 * Create an IPv4 listen socket bound to our port.
\r
522 * @return NULL on error
\r
524 static struct GNUNET_NETWORK_Handle *
\r
527 struct GNUNET_NETWORK_Handle *ls;
\r
528 struct sockaddr_in sa4;
\r
531 memset (&sa4, 0, sizeof (sa4));
\r
532 sa4.sin_family = AF_INET;
\r
533 sa4.sin_port = htons (port);
\r
534 #if HAVE_SOCKADDR_IN_SIN_LEN
\r
535 sa4.sin_len = sizeof (sa4);
\r
537 ls = GNUNET_NETWORK_socket_create (AF_INET,
\r
543 GNUNET_NETWORK_socket_bind (ls, (const struct sockaddr *) &sa4,
\r
547 GNUNET_NETWORK_socket_close (ls);
\r
557 * Main function run with scheduler.
\r
562 run (void *cls, char *const *args, const char *cfgfile,
\r
563 const struct GNUNET_CONFIGURATION_Handle *cfg)
\r
567 //Lets create the socket
\r
568 lsock4 = bind_v4 ();
\r
569 if (NULL == lsock4)
\r
571 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
\r
575 printf("Binded, now will call add_read\n");
\r
576 //Lets call our function now when it accepts
\r
577 ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
\r
578 lsock4, &do_udp_read, NULL);
\r
581 if(NULL == lsock4 )
\r
583 GNUNET_SCHEDULER_shutdown ();
\r
586 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
\r
587 "Service listens on port %u\n",
\r
589 printf("Start main event\n");
\r
590 stun_request(lsock4);
\r
592 //main_task = GNUNET_SCHEDULER_add_delayed (timeout, &do_timeout, nh);
\r
598 main (int argc, char *const argv[])
\r
600 struct GNUNET_GETOPT_CommandLineOption options[] = {
\r
601 GNUNET_GETOPT_OPTION_END
\r
604 char *const argv_prog[] = {
\r
608 GNUNET_log_setup ("test-stun",
\r
612 GNUNET_PROGRAM_run (1, argv_prog, "test-stun", "nohelp", options, &run, NULL);
\r
617 /* end of test_nat.c */
\r