RECLAIM/OIDC: code cleanup
[oweals/gnunet.git] / src / nat / test_stun.c
index 086789f27ee71c5b74d3c350c5e0985c8d43af1b..ee2db35e5112dc9e2c6afa9bf898b7f8c2a966f2 100644 (file)
-/*\r
-     This file is part of GNUnet.\r
-     Copyright (C) 2009, 2015 Christian Grothoff (and other contributing authors)\r
-\r
-     GNUnet is free software; you can redistribute it and/or modify\r
-     it under the terms of the GNU General Public License as published\r
-     by the Free Software Foundation; either version 3, or (at your\r
-     option) any later version.\r
-\r
-     GNUnet is distributed in the hope that it will be useful, but\r
-     WITHOUT ANY WARRANTY; without even the implied warranty of\r
-     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r
-     General Public License for more details.\r
-\r
-     You should have received a copy of the GNU General Public License\r
-     along with GNUnet; see the file COPYING.  If not, write to the\r
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,\r
-     Boston, MA 02111-1307, USA.\r
-*/\r
-\r
-/**\r
- * Testcase for STUN server resolution\r
- *\r
- * @file nat/test_stun.c\r
- * @brief Testcase for STUN library\r
- * @author Bruno Souza Cabral - Major rewrite.\r
- * @autor Mark Spencer (Original code - borrowed from Asterisk)\r
- *\r
- */\r
-\r
-\r
-#include "platform.h"\r
-#include "gnunet_util_lib.h"\r
-#include "gnunet_program_lib.h"\r
-#include "gnunet_scheduler_lib.h"\r
-#include "gnunet_nat_lib.h"\r
-\r
-\r
-#include "test_stun.h"\r
-\r
-#define LOG(kind,...) GNUNET_log_from (kind, "stun", __VA_ARGS__)\r
-\r
-/**\r
- * The port the test service is running on (default 7895)\r
- */\r
-static unsigned long port = 7895;\r
-static int ret = 1;\r
-\r
-static char *stun_server = STUN_SERVER;\r
-static int stun_port = STUN_PORT;\r
-\r
-/**\r
- * The listen socket of the service for IPv4\r
- */\r
-static struct GNUNET_NETWORK_Handle *lsock4;\r
-\r
-\r
-/**\r
- * The listen task ID for IPv4\r
- */\r
-static struct GNUNET_SCHEDULER_Task * ltask4;\r
-\r
-\r
-\r
-/**\r
- * Handle to a request given to the resolver.  Can be used to cancel\r
- * the request prior to the timeout or successful execution.  Also\r
- * used to track our internal state for the request.\r
- */\r
-struct GNUNET_NAT_StunRequestHandle {\r
-\r
-    /**\r
-    * Handle to a pending DNS lookup request.\r
-    */\r
-    struct GNUNET_RESOLVER_RequestHandle *dns_active;\r
-\r
-\r
-    /**\r
-    * Handle to the listen socket\r
-    */\r
-    struct GNUNET_NETWORK_Handle * sock;\r
-\r
-};\r
-\r
-\r
-\r
-\r
-/* here we store credentials extracted from a message */\r
-struct StunState {\r
-    uint16_t attr;\r
-};\r
-\r
-/* callback type to be invoked on stun responses. */\r
-typedef int (stun_cb_f)(struct StunState *st, struct stun_attr *attr, void *arg, unsigned int magic);\r
-\r
-\r
-\r
-/**\r
- * Convert a message to a StunClass\r
- *\r
- * @param msg the received message\r
- * @return the converted StunClass\r
- */\r
-static int decode_class(int msg)\r
-{\r
-    return ((msg & 0x0010) >> 4) | ((msg & 0x0100) >> 7);\r
-}\r
-\r
-/**\r
- * Convert a message to a StunMethod\r
- *\r
- * @param msg the received message\r
- * @return the converted StunMethod\r
- */\r
-static int decode_method(int msg)\r
-{\r
-    return (msg & 0x000f) | ((msg & 0x00e0) >> 1) | ((msg & 0x3e00) >> 2);\r
-}\r
-\r
-/**\r
- * Encode a class and method to a compatible STUN format\r
- *\r
- * @param msg_class class to be converted\r
- * @param method method to be converted\r
- * @return message in a STUN compatible format\r
- */\r
-static int encode_message(StunClasses msg_class, StunMethods method)\r
-{\r
-    return ((msg_class & 1) << 4) | ((msg_class & 2) << 7) |\r
-            (method & 0x000f) | ((method & 0x0070) << 1) | ((method & 0x0f800) << 2);\r
-}\r
-\r
-/* helper function to print message names */\r
-static const char *stun_msg2str(int msg)\r
-{\r
-\r
-    const struct { enum StunClasses value; const char *name; } classes[] = {\r
-        { STUN_REQUEST, "Request" },\r
-        { STUN_INDICATION, "Indication" },\r
-        { STUN_RESPONSE, "Response" },\r
-        { STUN_ERROR_RESPONSE, "Error Response" },\r
-        { 0, NULL }\r
-    };\r
-\r
-    const struct { enum StunMethods value; const char *name; } methods[] = {\r
-        { STUN_BINDING, "Binding" },\r
-        { 0, NULL }\r
-    };\r
-\r
-    static char result[32];\r
-    const char *msg_class = NULL;\r
-    const char *method = NULL;\r
-    int i;\r
-    int value;\r
-\r
-    value = decode_class(msg);\r
-    for (i = 0; classes[i].name; i++) {\r
-        msg_class = classes[i].name;\r
-        if (classes[i].value == value)\r
-            break;\r
-    }\r
-    value = decode_method(msg);\r
-    for (i = 0; methods[i].name; i++) {\r
-        method = methods[i].name;\r
-        if (methods[i].value == value)\r
-            break;\r
-    }\r
-    snprintf(result, sizeof(result), "%s %s",\r
-             method ? : "Unknown Method",\r
-             msg_class ? : "Unknown Class Message");\r
-    return result;\r
-}\r
-\r
-/* helper function to print attribute names */\r
-static const char *stun_attr2str(int msg)\r
-{\r
-    const struct { enum StunAttributes value; const char *name; } attrs[] = {\r
-        { STUN_MAPPED_ADDRESS, "Mapped Address" },\r
-        { STUN_RESPONSE_ADDRESS, "Response Address" },\r
-        { STUN_CHANGE_ADDRESS, "Change Address" },\r
-        { STUN_SOURCE_ADDRESS, "Source Address" },\r
-        { STUN_CHANGED_ADDRESS, "Changed Address" },\r
-        { STUN_USERNAME, "Username" },\r
-        { STUN_PASSWORD, "Password" },\r
-        { STUN_MESSAGE_INTEGRITY, "Message Integrity" },\r
-        { STUN_ERROR_CODE, "Error Code" },\r
-        { STUN_UNKNOWN_ATTRIBUTES, "Unknown Attributes" },\r
-        { STUN_REFLECTED_FROM, "Reflected From" },\r
-        { STUN_REALM, "Realm" },\r
-        { STUN_NONCE, "Nonce" },\r
-        { STUN_XOR_MAPPED_ADDRESS, "XOR Mapped Address" },\r
-        { STUN_MS_VERSION, "MS Version" },\r
-        { STUN_MS_XOR_MAPPED_ADDRESS, "MS XOR Mapped Address" },\r
-        { STUN_SOFTWARE, "Software" },\r
-        { STUN_ALTERNATE_SERVER, "Alternate Server" },\r
-        { STUN_FINGERPRINT, "Fingerprint" },\r
-        { 0, NULL }\r
-    };\r
-    int i;\r
-\r
-    for (i = 0; attrs[i].name; i++) {\r
-        if (attrs[i].value == msg)\r
-            return attrs[i].name;\r
-    }\r
-    return "Unknown Attribute";\r
-}\r
-\r
-\r
-\r
-static int stun_process_attr(struct StunState *state, struct stun_attr *attr)\r
-{\r
-    LOG (GNUNET_ERROR_TYPE_INFO,\r
-         "Found STUN Attribute %s (%04x), length %d\n",\r
-         stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));\r
-\r
-    switch (ntohs(attr->attr)) {\r
-        case STUN_MAPPED_ADDRESS:\r
-        case STUN_XOR_MAPPED_ADDRESS:\r
-        case STUN_MS_XOR_MAPPED_ADDRESS:\r
-            break;\r
-        default:\r
-            LOG (GNUNET_ERROR_TYPE_INFO,\r
-                 "Ignoring STUN Attribute %s (%04x), length %d\n",\r
-                 stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));\r
-            \r
-    }\r
-    return 0;\r
-}\r
-\r
-\r
-/* helper function to generate a random request id */\r
-static void\r
-generate_request_id(struct stun_header *req)\r
-{\r
-    int x;\r
-    req->magic = htonl(STUN_MAGIC_COOKIE);\r
-    for (x = 0; x < 3; x++)\r
-        req->id.id[x] = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,\r
-                                                  UINT32_MAX);\r
-}\r
-\r
-\r
-/* handle an incoming STUN message.\r
- *\r
- * Do some basic sanity checks on packet size and content,\r
- * try to extract a bit of information, and possibly reply.\r
- * At the moment this only processes BIND requests, and returns\r
- * the externally visible address of the request.\r
- * If a callback is specified, invoke it with the attribute.\r
- */\r
-static int\r
-stun_handle_packet(const uint8_t *data, size_t len, stun_cb_f *stun_cb, void *arg)\r
-{\r
-    struct stun_header *hdr = (struct stun_header *)data;\r
-    struct stun_attr *attr;\r
-    struct StunState st;\r
-    int ret = STUN_IGNORE;\r
-\r
-    uint32_t advertised_message_size;\r
-    uint32_t message_magic_cookie;\r
-\r
-\r
-    /* On entry, 'len' is the length of the udp payload. After the\r
-         * initial checks it becomes the size of unprocessed options,\r
-         * while 'data' is advanced accordingly.\r
-         */\r
-    if (len < sizeof(struct stun_header)) {\r
-        LOG (GNUNET_ERROR_TYPE_INFO,\r
-             "STUN packet too short (only %d, wanting at least %d)\n", (int) len, (int) sizeof(struct stun_header));\r
-        GNUNET_break_op (0);\r
-        return -1;\r
-    }\r
-    /* Skip header as it is already in hdr */\r
-    len -= sizeof(struct stun_header);\r
-    data += sizeof(struct stun_header);\r
-\r
-    /* len as advertised in the message */\r
-    advertised_message_size = ntohs(hdr->msglen);\r
-\r
-    message_magic_cookie = ntohl(hdr->magic);\r
-    /* Compare if the cookie match */\r
-    if(STUN_MAGIC_COOKIE != message_magic_cookie){\r
-        LOG (GNUNET_ERROR_TYPE_INFO,\r
-             "Invalid magic cookie \n");\r
-        GNUNET_break_op (0);\r
-        return -1;\r
-    }\r
-\r
-\r
-    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
-\r
-\r
-    if (advertised_message_size > len) {\r
-        LOG (GNUNET_ERROR_TYPE_INFO, "Scrambled STUN packet length (got %d, expecting %d)\n", advertised_message_size, (int)len);\r
-        GNUNET_break_op (0);\r
-    } else {\r
-        len = advertised_message_size;\r
-    }\r
-    /* Zero the struct */\r
-    memset(&st,0, sizeof(st));\r
-\r
-    while (len > 0) {\r
-        if (len < sizeof(struct stun_attr)) {\r
-            LOG (GNUNET_ERROR_TYPE_INFO, "Attribute too short (got %d, expecting %d)\n", (int)len, (int) sizeof(struct stun_attr));\r
-            GNUNET_break_op (0);\r
-            break;\r
-        }\r
-        attr = (struct stun_attr *)data;\r
-\r
-        /* compute total attribute length */\r
-        advertised_message_size = ntohs(attr->len) + sizeof(struct stun_attr);\r
-\r
-        /* Check if we still have space in our buffer */\r
-        if (advertised_message_size > len ) {\r
-            LOG (GNUNET_ERROR_TYPE_INFO, "Inconsistent Attribute (length %d exceeds remaining msg len %d)\n", advertised_message_size, (int)len);\r
-            GNUNET_break_op (0);\r
-            break;\r
-        }\r
-\r
-        if (stun_cb){\r
-            stun_cb(&st, attr, arg, hdr->magic);\r
-        }\r
-\r
-        if (stun_process_attr(&st, attr)) {\r
-            LOG (GNUNET_ERROR_TYPE_INFO, "Failed to handle attribute %s (%04x)\n", stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr));\r
-            break;\r
-        }\r
-        /* Clear attribute id: in case previous entry was a string,\r
-                 * this will act as the terminator for the string.\r
-                 */\r
-        attr->attr = 0;\r
-        data += advertised_message_size;\r
-        len -= advertised_message_size;\r
-    }\r
-\r
-    return ret;\r
-}\r
-\r
-/* Extract the STUN_MAPPED_ADDRESS from the stun response.\r
- * This is used as a callback for stun_handle_response\r
- * when called from stun_request.\r
- */\r
-static int\r
-stun_get_mapped(struct StunState *st, struct stun_attr *attr, void *arg, unsigned int magic)\r
-{\r
-    struct stun_addr *returned_addr = (struct stun_addr *)(attr + 1);\r
-    struct sockaddr_in *sa = (struct sockaddr_in *)arg;\r
-    unsigned short type = ntohs(attr->attr);\r
-\r
-    switch (type) {\r
-    case STUN_MAPPED_ADDRESS:\r
-        if (st->attr == STUN_XOR_MAPPED_ADDRESS ||\r
-                st->attr == STUN_MS_XOR_MAPPED_ADDRESS)\r
-            return 1;\r
-        magic = 0;\r
-        break;\r
-    case STUN_MS_XOR_MAPPED_ADDRESS:\r
-        if (st->attr == STUN_XOR_MAPPED_ADDRESS)\r
-            return 1;\r
-        break;\r
-    case STUN_XOR_MAPPED_ADDRESS:\r
-        break;\r
-    default:\r
-        return 1;\r
-    }\r
-    if (ntohs(attr->len) < 8 && returned_addr->family != 1) {\r
-        return 1;\r
-    }\r
-\r
-    st->attr = type;\r
-    sa->sin_port = returned_addr->port ^ htons(ntohl(magic) >> 16);\r
-    sa->sin_addr.s_addr = returned_addr->addr ^ magic;\r
-    return 0;\r
-}\r
-\r
-\r
-/**\r
- * Try to establish a connection given the specified address.\r
- * This function is called by the resolver once we have a DNS reply.\r
- *\r
- * @param cls our `struct GNUNET_CONNECTION_Handle *`\r
- * @param addr address to try, NULL for "last call"\r
- * @param addrlen length of @a addr\r
- */\r
-static void\r
-try_connect_using_address (void *cls,\r
-                           const struct sockaddr *addr,\r
-                           socklen_t addrlen) {\r
-\r
-\r
-    struct GNUNET_NAT_StunRequestHandle *request = cls;\r
-\r
-    struct stun_header *req;\r
-    uint8_t reqdata[1024];\r
-    int reqlen;\r
-\r
-    if(NULL == request) {\r
-        LOG (GNUNET_ERROR_TYPE_INFO, "Empty request\n");\r
-        return;\r
-    }\r
-\r
-\r
-    if (NULL == addr) {\r
-        request->dns_active = NULL;\r
-        LOG (GNUNET_ERROR_TYPE_INFO, "Error resolving host %s\n", stun_server);\r
-        //BREAk op\r
-        return;\r
-    }\r
-\r
-\r
-\r
-    struct sockaddr_in server;\r
-\r
-\r
-    memset(&server,0, sizeof(server));\r
-    server.sin_family = AF_INET;\r
-\r
-    struct sockaddr_in *addr_in = (struct sockaddr_in *)addr;\r
-\r
-    server.sin_addr = addr_in->sin_addr;\r
-    server.sin_port = htons(stun_port);\r
-\r
-\r
-    /*Craft the simplest possible STUN packet. A request binding*/\r
-    req = (struct stun_header *)reqdata;\r
-    generate_request_id(req);\r
-    reqlen = 0;\r
-    req->msgtype = 0;\r
-    req->msglen = 0;\r
-\r
-\r
-    req->msglen = htons(reqlen);\r
-    req->msgtype = htons(encode_message(STUN_REQUEST, STUN_BINDING));\r
-\r
-\r
-    if (-1 == GNUNET_NETWORK_socket_sendto (request->sock, req, ntohs(req->msglen) + sizeof(*req),\r
-                                            (const struct sockaddr *) &server, sizeof (server)))\r
-    {\r
-        GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "Failt to sendto");\r
-    }\r
-\r
-}\r
-\r
-\r
-/* Generic STUN request\r
- * Send a generic stun request to the server specified,\r
- * possibly waiting for a reply and filling the 'reply' field with\r
- * the externally visible address. \r
\r
- * \param s the socket used to send the request\r
- * \return 0 on success, other values on error.\r
- */\r
-struct GNUNET_NAT_StunRequestHandle *\r
-stun_request(struct GNUNET_NETWORK_Handle * sock)\r
-{\r
-\r
-\r
-    struct GNUNET_NAT_StunRequestHandle *rh;\r
-\r
-\r
-    rh = GNUNET_malloc (sizeof (struct GNUNET_NAT_StunRequestHandle));\r
-\r
-    rh->sock = sock;\r
-\r
-    rh->dns_active = GNUNET_RESOLVER_ip_get (stun_server, AF_INET,\r
-                                 GNUNET_CONNECTION_CONNECT_RETRY_TIMEOUT,\r
-                                 &try_connect_using_address, rh);\r
-\r
-\r
-\r
-\r
-    return rh;\r
-}\r
-\r
-static void\r
-print_answer(struct sockaddr_in* answer)\r
-{\r
-       printf("External IP is: %s , with port %d\n", inet_ntoa(answer->sin_addr), ntohs(answer->sin_port));\r
-}\r
-\r
-\r
-/**\r
- * Activity on our incoming socket.  Read data from the\r
- * incoming connection.\r
- *\r
- * @param cls \r
- * @param tc scheduler context\r
- */\r
-static void\r
-do_udp_read (void *cls,\r
-             const struct GNUNET_SCHEDULER_TaskContext *tc)\r
-{\r
-    //struct GNUNET_NAT_Test *tst = cls;\r
-       unsigned char reply_buf[1024];\r
-       ssize_t rlen;\r
-       struct sockaddr_in answer;\r
-\r
-\r
-    if ((0 != (tc->reason & GNUNET_SCHEDULER_REASON_READ_READY)) &&\r
-      (GNUNET_NETWORK_fdset_isset (tc->read_ready,\r
-                                   lsock4)))\r
-       {\r
-               rlen = GNUNET_NETWORK_socket_recv (lsock4, reply_buf, sizeof (reply_buf));\r
-               printf("Recivied something of size %d", rlen);\r
-               \r
-               //Lets handle the packet\r
-               memset(&answer, 0, sizeof(struct sockaddr_in));\r
-        stun_handle_packet(reply_buf, rlen, stun_get_mapped, &answer);\r
-               //Print the anser\r
-               //TODO: Delete the object\r
-               ret = 0;\r
-               print_answer(&answer);\r
-               \r
-               \r
-       }\r
-}\r
-\r
-\r
-/**\r
- * Create an IPv4 listen socket bound to our port.\r
- *\r
- * @return NULL on error\r
- */\r
-static struct GNUNET_NETWORK_Handle *\r
-bind_v4 ()\r
-{\r
-    struct GNUNET_NETWORK_Handle *ls;\r
-    struct sockaddr_in sa4;\r
-    int eno;\r
-\r
-    memset (&sa4, 0, sizeof (sa4));\r
-    sa4.sin_family = AF_INET;\r
-    sa4.sin_port = htons (port);\r
-#if HAVE_SOCKADDR_IN_SIN_LEN\r
-    sa4.sin_len = sizeof (sa4);\r
-#endif \r
-    ls = GNUNET_NETWORK_socket_create (AF_INET,\r
-                                       SOCK_DGRAM,\r
-                                       0);\r
-    if (NULL == ls)\r
-        return NULL;\r
-    if (GNUNET_OK !=\r
-            GNUNET_NETWORK_socket_bind (ls, (const struct sockaddr *) &sa4,\r
-                                        sizeof (sa4)))\r
-    {\r
-        eno = errno;\r
-        GNUNET_NETWORK_socket_close (ls);\r
-        errno = eno;\r
-        return NULL;\r
-    }\r
-    return ls;\r
-}\r
-\r
-\r
-\r
-/**\r
- * Main function run with scheduler.\r
- */\r
-\r
-\r
-static void\r
-run (void *cls, char *const *args, const char *cfgfile,\r
-     const struct GNUNET_CONFIGURATION_Handle *cfg)\r
-{\r
-\r
-\r
-    //Lets create the socket\r
-    lsock4 = bind_v4 ();\r
-    if (NULL == lsock4)\r
-    {\r
-        GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");\r
-    }\r
-    else\r
-    {\r
-               printf("Binded, now will call add_read\n");\r
-        //Lets call our function now when it accepts\r
-        ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,\r
-                                                lsock4, &do_udp_read, NULL);\r
-\r
-    }\r
-    if(NULL == lsock4 )\r
-    {\r
-        GNUNET_SCHEDULER_shutdown ();\r
-        return;\r
-    }\r
-    GNUNET_log (GNUNET_ERROR_TYPE_INFO,\r
-                "Service listens on port %u\n",\r
-                port);\r
-       printf("Start main event\n");\r
-       stun_request(lsock4);\r
-    //Main event\r
-    //main_task = GNUNET_SCHEDULER_add_delayed (timeout, &do_timeout, nh);\r
-\r
-}\r
-\r
-\r
-int\r
-main (int argc, char *const argv[])\r
-{\r
-    struct GNUNET_GETOPT_CommandLineOption options[] = {\r
-        GNUNET_GETOPT_OPTION_END\r
-    };\r
-\r
-    char *const argv_prog[] = {\r
-        "test-stun",\r
-        NULL\r
-    };\r
-    GNUNET_log_setup ("test-stun",\r
-                      "WARNING",\r
-                      NULL);\r
-\r
-    GNUNET_PROGRAM_run (1, argv_prog, "test-stun", "nohelp", options, &run, NULL);\r
-    \r
-       return ret;\r
-}\r
-\r
-/* end of test_nat.c */\r
+/*
+     This file is part of GNUnet.
+     Copyright (C) 2009, 2015 GNUnet e.V.
+
+     GNUnet is free software: you can redistribute it and/or modify it
+     under the terms of the GNU Affero General Public License as published
+     by the Free Software Foundation, either version 3 of the License,
+     or (at your option) any later version.
+
+     GNUnet is distributed in the hope that it will be useful, but
+     WITHOUT ANY WARRANTY; without even the implied warranty of
+     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+     Affero General Public License for more details.
+    
+     You should have received a copy of the GNU Affero General Public License
+     along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+     SPDX-License-Identifier: AGPL3.0-or-later
+*/
+
+/**
+ * Testcase for STUN server resolution
+ *
+ * @file nat/test_stun.c
+ * @brief Testcase for STUN library
+ * @author Bruno Souza Cabral
+ * @author Christian Grothoff
+ */
+
+
+#include "platform.h"
+#include "gnunet_util_lib.h"
+#include "gnunet_program_lib.h"
+#include "gnunet_scheduler_lib.h"
+#include "gnunet_nat_lib.h"
+
+
+
+#define LOG(kind,...) GNUNET_log_from (kind, "test-stun", __VA_ARGS__)
+
+/**
+ * Time to wait before stopping NAT, in seconds
+ */
+#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
+
+
+/**
+ * The port the test service is running on (default 7895)
+ */
+static unsigned long port = 7895;
+
+static int ret = 1;
+
+static const char *stun_server = "stun.gnunet.org";
+
+static int stun_port = 3478;
+
+/**
+ * The listen socket of the service for IPv4
+ */
+static struct GNUNET_NETWORK_Handle *lsock4;
+
+/**
+ * The listen task ID for IPv4
+ */
+static struct GNUNET_SCHEDULER_Task *ltask4;
+
+/**
+ * Handle for the STUN request.
+ */
+static struct GNUNET_NAT_STUN_Handle *rh;
+
+
+static void
+print_answer(struct sockaddr_in* answer)
+{
+  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
+              "External IP is: %s , with port %d\n",
+              inet_ntoa (answer->sin_addr),
+              ntohs (answer->sin_port));
+}
+
+
+/**
+ * Function that terminates the test.
+ */
+static void
+stop ()
+{
+  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
+              "Stopping NAT and quitting...\n");
+  if (NULL != ltask4)
+  {
+    GNUNET_SCHEDULER_cancel (ltask4);
+    ltask4 = NULL;
+  }
+  if(NULL != lsock4)
+  {
+    GNUNET_NETWORK_socket_close(lsock4);
+    lsock4 = NULL;
+  }
+  if (NULL != rh)
+  {
+    GNUNET_NAT_stun_make_request_cancel (rh);
+    rh = NULL;
+  }
+}
+
+
+/**
+ * Activity on our incoming socket.  Read data from the
+ * incoming connection.
+ *
+ * @param cls
+ */
+static void
+do_udp_read (void *cls)
+{
+  //struct GNUNET_NAT_Test *tst = cls;
+  unsigned char reply_buf[1024];
+  ssize_t rlen;
+  struct sockaddr_in answer;
+  const struct GNUNET_SCHEDULER_TaskContext *tc;
+
+  ltask4 = NULL;
+  tc = GNUNET_SCHEDULER_get_task_context ();
+  if ( (0 == (tc->reason & GNUNET_SCHEDULER_REASON_READ_READY)) ||
+       (! GNUNET_NETWORK_fdset_isset (tc->read_ready,
+                                      lsock4)) )
+  {
+    fprintf (stderr,
+             "Timeout waiting for STUN response\n");
+    stop();
+  }
+  rlen = GNUNET_NETWORK_socket_recv (lsock4,
+                                     reply_buf,
+                                     sizeof (reply_buf));
+  memset (&answer,
+          0,
+          sizeof(struct sockaddr_in));
+  if (GNUNET_OK !=
+      GNUNET_NAT_stun_handle_packet (reply_buf,
+                                     rlen,
+                                     &answer))
+  {
+    fprintf (stderr,
+             "Unexpected UDP packet, trying to read more\n");
+    ltask4 = GNUNET_SCHEDULER_add_read_net (TIMEOUT,
+                                            lsock4,
+                                            &do_udp_read, NULL);
+    return;
+  }
+  ret = 0;
+  print_answer (&answer);
+  stop ();
+}
+
+
+/**
+ * Create an IPv4 listen socket bound to our port.
+ *
+ * @return NULL on error
+ */
+static struct GNUNET_NETWORK_Handle *
+bind_v4 ()
+{
+  struct GNUNET_NETWORK_Handle *ls;
+  struct sockaddr_in sa4;
+  int eno;
+
+  memset (&sa4, 0, sizeof (sa4));
+  sa4.sin_family = AF_INET;
+  sa4.sin_port = htons (port);
+#if HAVE_SOCKADDR_IN_SIN_LEN
+  sa4.sin_len = sizeof (sa4);
+#endif
+  ls = GNUNET_NETWORK_socket_create (AF_INET,
+                                     SOCK_DGRAM,
+                                     0);
+  if (NULL == ls)
+    return NULL;
+  if (GNUNET_OK !=
+      GNUNET_NETWORK_socket_bind (ls,
+                                  (const struct sockaddr *) &sa4,
+                                  sizeof (sa4)))
+  {
+    eno = errno;
+    GNUNET_NETWORK_socket_close (ls);
+    errno = eno;
+    return NULL;
+  }
+  return ls;
+}
+
+
+/**
+ * Function called with the result of the STUN request transmission attempt.
+ *
+ * @param cls unused
+ * @param error status code from STUN
+ */
+static void
+request_callback (void *cls,
+                  enum GNUNET_NAT_StatusCode error)
+{
+  rh = NULL;
+  if (GNUNET_NAT_ERROR_SUCCESS == error)
+  {
+    /* all good, start to receive */
+    ltask4 = GNUNET_SCHEDULER_add_read_net (TIMEOUT,
+                                            lsock4,
+                                            &do_udp_read,
+                                            NULL);
+    return;
+  }
+  if (error == GNUNET_NAT_ERROR_NOT_ONLINE)
+  {
+    ret = 77; /* report 'skip' */
+    fprintf (stderr,
+             "System is offline, cannot test STUN request.\n");
+  }
+  else
+  {
+    ret = error;
+  }
+  stop();
+}
+
+
+/**
+ * Main function run with scheduler.
+ */
+static void
+run (void *cls,
+     char *const *args,
+     const char *cfgfile,
+     const struct GNUNET_CONFIGURATION_Handle *cfg)
+{
+  //Lets create the socket
+  lsock4 = bind_v4 ();
+  if (NULL == lsock4)
+  {
+    GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
+                         "bind");
+    GNUNET_SCHEDULER_shutdown ();
+    return;
+  }
+  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
+              "Service listens on port %u\n",
+              (unsigned int) port);
+  rh = GNUNET_NAT_stun_make_request (stun_server,
+                                     stun_port,
+                                     lsock4,
+                                     &request_callback, NULL);
+  GNUNET_SCHEDULER_add_delayed (TIMEOUT,
+                                &stop, NULL);
+}
+
+
+int
+main (int argc, char *const argv[])
+{
+  struct GNUNET_GETOPT_CommandLineOption options[] = {
+      GNUNET_GETOPT_OPTION_END
+  };
+  char *const argv_prog[] = {
+      "test-stun",
+      "-c",
+      "test_stun.conf",
+      NULL
+  };
+  char *fn;
+  struct GNUNET_OS_Process *proc;
+
+  GNUNET_log_setup ("test-stun",
+                    "WARNING",
+                    NULL);
+
+  /* Lets start resolver */
+  fn = GNUNET_OS_get_libexec_binary_path ("gnunet-service-resolver");
+  proc = GNUNET_OS_start_process (GNUNET_YES,
+                                  GNUNET_OS_INHERIT_STD_OUT_AND_ERR,
+                                  NULL, NULL, NULL,
+                                  fn,
+                                  "gnunet-service-resolver",
+                                  "-c", "test_stun.conf", NULL);
+
+  if (NULL == proc)
+  {
+    GNUNET_log (GNUNET_ERROR_TYPE_INFO,
+                "This test was unable to start gnunet-service-resolver, and it is required to run ...\n");
+    exit(1);
+  }
+
+  GNUNET_PROGRAM_run (3, argv_prog,
+                      "test-stun", "nohelp",
+                      options,
+                      &run, NULL);
+
+  /* Now kill the resolver */
+  if (0 != GNUNET_OS_process_kill (proc, GNUNET_TERM_SIG))
+  {
+    GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill");
+  }
+  GNUNET_OS_process_wait (proc);
+  GNUNET_OS_process_destroy (proc);
+  proc = NULL;
+  GNUNET_free (fn);
+
+  return ret;
+}
+
+/* end of test_stun.c */