Commit rewrite before moving to GNUNET_NAT functions
[oweals/gnunet.git] / src / nat / test_stun.c
1 /*\r
2      This file is part of GNUnet.\r
3      Copyright (C) 2009, 2015 Christian Grothoff (and other contributing authors)\r
4 \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
9 \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
14 \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
19 */\r
20 \r
21 /**\r
22  * Testcase for STUN server resolution\r
23  *\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
28  *\r
29  */\r
30 \r
31 \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
37 \r
38 \r
39 #include "test_stun.h"\r
40 \r
41 #define LOG(kind,...) GNUNET_log_from (kind, "stun", __VA_ARGS__)\r
42 \r
43 /**\r
44  * The port the test service is running on (default 7895)\r
45  */\r
46 static unsigned long port = 7895;\r
47 static int ret = 1;\r
48 \r
49 static char *stun_server = STUN_SERVER;\r
50 static int stun_port = STUN_PORT;\r
51 \r
52 /**\r
53  * The listen socket of the service for IPv4\r
54  */\r
55 static struct GNUNET_NETWORK_Handle *lsock4;\r
56 \r
57 \r
58 /**\r
59  * The listen task ID for IPv4\r
60  */\r
61 static struct GNUNET_SCHEDULER_Task * ltask4;\r
62 \r
63 \r
64 \r
65 /**\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
69  */\r
70 struct GNUNET_NAT_StunRequestHandle {\r
71 \r
72     /**\r
73     * Handle to a pending DNS lookup request.\r
74     */\r
75     struct GNUNET_RESOLVER_RequestHandle *dns_active;\r
76 \r
77 \r
78     /**\r
79     * Handle to the listen socket\r
80     */\r
81     struct GNUNET_NETWORK_Handle * sock;\r
82 \r
83 };\r
84 \r
85 \r
86 \r
87 \r
88 /* here we store credentials extracted from a message */\r
89 struct StunState {\r
90     uint16_t attr;\r
91 };\r
92 \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
95 \r
96 \r
97 \r
98 /**\r
99  * Convert a message to a StunClass\r
100  *\r
101  * @param msg the received message\r
102  * @return the converted StunClass\r
103  */\r
104 static int decode_class(int msg)\r
105 {\r
106     return ((msg & 0x0010) >> 4) | ((msg & 0x0100) >> 7);\r
107 }\r
108 \r
109 /**\r
110  * Convert a message to a StunMethod\r
111  *\r
112  * @param msg the received message\r
113  * @return the converted StunMethod\r
114  */\r
115 static int decode_method(int msg)\r
116 {\r
117     return (msg & 0x000f) | ((msg & 0x00e0) >> 1) | ((msg & 0x3e00) >> 2);\r
118 }\r
119 \r
120 /**\r
121  * Encode a class and method to a compatible STUN format\r
122  *\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
126  */\r
127 static int encode_message(StunClasses msg_class, StunMethods method)\r
128 {\r
129     return ((msg_class & 1) << 4) | ((msg_class & 2) << 7) |\r
130             (method & 0x000f) | ((method & 0x0070) << 1) | ((method & 0x0f800) << 2);\r
131 }\r
132 \r
133 /* helper function to print message names */\r
134 static const char *stun_msg2str(int msg)\r
135 {\r
136 \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
142         { 0, NULL }\r
143     };\r
144 \r
145     const struct { enum StunMethods value; const char *name; } methods[] = {\r
146         { STUN_BINDING, "Binding" },\r
147         { 0, NULL }\r
148     };\r
149 \r
150     static char result[32];\r
151     const char *msg_class = NULL;\r
152     const char *method = NULL;\r
153     int i;\r
154     int value;\r
155 \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
160             break;\r
161     }\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
166             break;\r
167     }\r
168     snprintf(result, sizeof(result), "%s %s",\r
169              method ? : "Unknown Method",\r
170              msg_class ? : "Unknown Class Message");\r
171     return result;\r
172 }\r
173 \r
174 /* helper function to print attribute names */\r
175 static const char *stun_attr2str(int msg)\r
176 {\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
197         { 0, NULL }\r
198     };\r
199     int i;\r
200 \r
201     for (i = 0; attrs[i].name; i++) {\r
202         if (attrs[i].value == msg)\r
203             return attrs[i].name;\r
204     }\r
205     return "Unknown Attribute";\r
206 }\r
207 \r
208 \r
209 \r
210 static int stun_process_attr(struct StunState *state, struct stun_attr *attr)\r
211 {\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
215 \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
220             break;\r
221         default:\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
225             \r
226     }\r
227     return 0;\r
228 }\r
229 \r
230 \r
231 /* helper function to generate a random request id */\r
232 static void\r
233 generate_request_id(struct stun_header *req)\r
234 {\r
235     int x;\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
239                                                   UINT32_MAX);\r
240 }\r
241 \r
242 \r
243 /* handle an incoming STUN message.\r
244  *\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
250  */\r
251 static int\r
252 stun_handle_packet(const uint8_t *data, size_t len, stun_cb_f *stun_cb, void *arg)\r
253 {\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
258 \r
259     uint32_t advertised_message_size;\r
260     uint32_t message_magic_cookie;\r
261 \r
262 \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
266          */\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
271         return -1;\r
272     }\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
276 \r
277     /* len as advertised in the message */\r
278     advertised_message_size = ntohs(hdr->msglen);\r
279 \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
286         return -1;\r
287     }\r
288 \r
289 \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
291 \r
292 \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
296     } else {\r
297         len = advertised_message_size;\r
298     }\r
299     /* Zero the struct */\r
300     memset(&st,0, sizeof(st));\r
301 \r
302     while (len > 0) {\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
306             break;\r
307         }\r
308         attr = (struct stun_attr *)data;\r
309 \r
310         /* compute total attribute length */\r
311         advertised_message_size = ntohs(attr->len) + sizeof(struct stun_attr);\r
312 \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
317             break;\r
318         }\r
319 \r
320         if (stun_cb){\r
321             stun_cb(&st, attr, arg, hdr->magic);\r
322         }\r
323 \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
326             break;\r
327         }\r
328         /* Clear attribute id: in case previous entry was a string,\r
329                  * this will act as the terminator for the string.\r
330                  */\r
331         attr->attr = 0;\r
332         data += advertised_message_size;\r
333         len -= advertised_message_size;\r
334     }\r
335 \r
336     return ret;\r
337 }\r
338 \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
342  */\r
343 static int\r
344 stun_get_mapped(struct StunState *st, struct stun_attr *attr, void *arg, unsigned int magic)\r
345 {\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
349 \r
350     switch (type) {\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
354             return 1;\r
355         magic = 0;\r
356         break;\r
357     case STUN_MS_XOR_MAPPED_ADDRESS:\r
358         if (st->attr == STUN_XOR_MAPPED_ADDRESS)\r
359             return 1;\r
360         break;\r
361     case STUN_XOR_MAPPED_ADDRESS:\r
362         break;\r
363     default:\r
364         return 1;\r
365     }\r
366     if (ntohs(attr->len) < 8 && returned_addr->family != 1) {\r
367         return 1;\r
368     }\r
369 \r
370     st->attr = type;\r
371     sa->sin_port = returned_addr->port ^ htons(ntohl(magic) >> 16);\r
372     sa->sin_addr.s_addr = returned_addr->addr ^ magic;\r
373     return 0;\r
374 }\r
375 \r
376 \r
377 /**\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
380  *\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
384  */\r
385 static void\r
386 try_connect_using_address (void *cls,\r
387                            const struct sockaddr *addr,\r
388                            socklen_t addrlen) {\r
389 \r
390 \r
391     struct GNUNET_NAT_StunRequestHandle *request = cls;\r
392 \r
393     struct stun_header *req;\r
394     uint8_t reqdata[1024];\r
395     int reqlen;\r
396 \r
397     if(NULL == request) {\r
398         LOG (GNUNET_ERROR_TYPE_INFO, "Empty request\n");\r
399         return;\r
400     }\r
401 \r
402 \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
406         //BREAk op\r
407         return;\r
408     }\r
409 \r
410 \r
411 \r
412     struct sockaddr_in server;\r
413 \r
414 \r
415     memset(&server,0, sizeof(server));\r
416     server.sin_family = AF_INET;\r
417 \r
418     struct sockaddr_in *addr_in = (struct sockaddr_in *)addr;\r
419 \r
420     server.sin_addr = addr_in->sin_addr;\r
421     server.sin_port = htons(stun_port);\r
422 \r
423 \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
427     reqlen = 0;\r
428     req->msgtype = 0;\r
429     req->msglen = 0;\r
430 \r
431 \r
432     req->msglen = htons(reqlen);\r
433     req->msgtype = htons(encode_message(STUN_REQUEST, STUN_BINDING));\r
434 \r
435 \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
438     {\r
439         GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "Failt to sendto");\r
440     }\r
441 \r
442 }\r
443 \r
444 \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
449  \r
450  * \param s the socket used to send the request\r
451  * \return 0 on success, other values on error.\r
452  */\r
453 struct GNUNET_NAT_StunRequestHandle *\r
454 stun_request(struct GNUNET_NETWORK_Handle * sock)\r
455 {\r
456 \r
457 \r
458     struct GNUNET_NAT_StunRequestHandle *rh;\r
459 \r
460 \r
461     rh = GNUNET_malloc (sizeof (struct GNUNET_NAT_StunRequestHandle));\r
462 \r
463     rh->sock = sock;\r
464 \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
468 \r
469 \r
470 \r
471 \r
472     return rh;\r
473 }\r
474 \r
475 static void\r
476 print_answer(struct sockaddr_in* answer)\r
477 {\r
478         printf("External IP is: %s , with port %d\n", inet_ntoa(answer->sin_addr), ntohs(answer->sin_port));\r
479 }\r
480 \r
481 \r
482 /**\r
483  * Activity on our incoming socket.  Read data from the\r
484  * incoming connection.\r
485  *\r
486  * @param cls \r
487  * @param tc scheduler context\r
488  */\r
489 static void\r
490 do_udp_read (void *cls,\r
491              const struct GNUNET_SCHEDULER_TaskContext *tc)\r
492 {\r
493     //struct GNUNET_NAT_Test *tst = cls;\r
494         unsigned char reply_buf[1024];\r
495         ssize_t rlen;\r
496         struct sockaddr_in answer;\r
497 \r
498 \r
499     if ((0 != (tc->reason & GNUNET_SCHEDULER_REASON_READ_READY)) &&\r
500       (GNUNET_NETWORK_fdset_isset (tc->read_ready,\r
501                                    lsock4)))\r
502         {\r
503                 rlen = GNUNET_NETWORK_socket_recv (lsock4, reply_buf, sizeof (reply_buf));\r
504                 printf("Recivied something of size %d", rlen);\r
505                 \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
509                 //Print the anser\r
510                 //TODO: Delete the object\r
511                 ret = 0;\r
512                 print_answer(&answer);\r
513                 \r
514                 \r
515         }\r
516 }\r
517 \r
518 \r
519 /**\r
520  * Create an IPv4 listen socket bound to our port.\r
521  *\r
522  * @return NULL on error\r
523  */\r
524 static struct GNUNET_NETWORK_Handle *\r
525 bind_v4 ()\r
526 {\r
527     struct GNUNET_NETWORK_Handle *ls;\r
528     struct sockaddr_in sa4;\r
529     int eno;\r
530 \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
536 #endif \r
537     ls = GNUNET_NETWORK_socket_create (AF_INET,\r
538                                        SOCK_DGRAM,\r
539                                        0);\r
540     if (NULL == ls)\r
541         return NULL;\r
542     if (GNUNET_OK !=\r
543             GNUNET_NETWORK_socket_bind (ls, (const struct sockaddr *) &sa4,\r
544                                         sizeof (sa4)))\r
545     {\r
546         eno = errno;\r
547         GNUNET_NETWORK_socket_close (ls);\r
548         errno = eno;\r
549         return NULL;\r
550     }\r
551     return ls;\r
552 }\r
553 \r
554 \r
555 \r
556 /**\r
557  * Main function run with scheduler.\r
558  */\r
559 \r
560 \r
561 static void\r
562 run (void *cls, char *const *args, const char *cfgfile,\r
563      const struct GNUNET_CONFIGURATION_Handle *cfg)\r
564 {\r
565 \r
566 \r
567     //Lets create the socket\r
568     lsock4 = bind_v4 ();\r
569     if (NULL == lsock4)\r
570     {\r
571         GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");\r
572     }\r
573     else\r
574     {\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
579 \r
580     }\r
581     if(NULL == lsock4 )\r
582     {\r
583         GNUNET_SCHEDULER_shutdown ();\r
584         return;\r
585     }\r
586     GNUNET_log (GNUNET_ERROR_TYPE_INFO,\r
587                 "Service listens on port %u\n",\r
588                 port);\r
589         printf("Start main event\n");\r
590         stun_request(lsock4);\r
591     //Main event\r
592     //main_task = GNUNET_SCHEDULER_add_delayed (timeout, &do_timeout, nh);\r
593 \r
594 }\r
595 \r
596 \r
597 int\r
598 main (int argc, char *const argv[])\r
599 {\r
600     struct GNUNET_GETOPT_CommandLineOption options[] = {\r
601         GNUNET_GETOPT_OPTION_END\r
602     };\r
603 \r
604     char *const argv_prog[] = {\r
605         "test-stun",\r
606         NULL\r
607     };\r
608     GNUNET_log_setup ("test-stun",\r
609                       "WARNING",\r
610                       NULL);\r
611 \r
612     GNUNET_PROGRAM_run (1, argv_prog, "test-stun", "nohelp", options, &run, NULL);\r
613     \r
614         return ret;\r
615 }\r
616 \r
617 /* end of test_nat.c */\r