From faf6cdf7e592414f041d486bf620967817485435 Mon Sep 17 00:00:00 2001 From: Bruno Cabral Date: Sat, 18 Jul 2015 19:15:51 +0000 Subject: Get STUN to work with UDP plugin --- src/include/gnunet_nat_lib.h | 50 ++- src/nat/gnunet-nat-server.c | 2 +- src/nat/nat.c | 301 ++++++++++++++- src/nat/nat.conf | 7 + src/nat/nat_stun.c | 553 +++++++++++++++------------ src/nat/nat_test.c | 4 +- src/nat/test_nat.c | 2 +- src/nat/test_stun.c | 94 ++++- src/transport/plugin_transport_http_server.c | 2 +- src/transport/plugin_transport_tcp.c | 5 +- src/transport/plugin_transport_udp.c | 14 +- src/transport/plugin_transport_udp.h | 5 + 12 files changed, 757 insertions(+), 282 deletions(-) (limited to 'src') diff --git a/src/include/gnunet_nat_lib.h b/src/include/gnunet_nat_lib.h index 7a8343d28..6c4362c90 100644 --- a/src/include/gnunet_nat_lib.h +++ b/src/include/gnunet_nat_lib.h @@ -170,6 +170,8 @@ enum GNUNET_NAT_StatusCode */ GNUNET_NAT_ERROR_HELPER_NAT_CLIENT_NOT_FOUND, + + /** * */ @@ -217,7 +219,8 @@ GNUNET_NAT_register (const struct GNUNET_CONFIGURATION_Handle *cfg, const socklen_t *addrlens, GNUNET_NAT_AddressCallback address_callback, GNUNET_NAT_ReversalCallback reversal_callback, - void *callback_cls); + void *callback_cls, + struct GNUNET_NETWORK_Handle* sock ); /** @@ -455,22 +458,43 @@ GNUNET_NAT_autoconfig_start (const struct GNUNET_CONFIGURATION_Handle *cfg, void GNUNET_NAT_autoconfig_cancel (struct GNUNET_NAT_AutoHandle *ah); +/** + * Handle for active STUN Requests. + */ +struct GNUNET_NAT_STUN_Handle; + + + + +/** + * Function called with the result from NAT request. + * + * @param cls closure + * @param diff minimal suggested changes to the original configuration + * to make it work (as best as we can) + * @param result #GNUNET_NAT_ERROR_SUCCESS on success, otherwise the specific error code + */ +typedef void +(*GNUNET_NAT_stun_RequestCallback)(void *cls, + enum GNUNET_NAT_StatusCode result); -struct GNUNET_NAT_StunRequestHandle; /** * Make Generic STUN request and * Send a generic stun request to the server specified using the specified socket. * possibly waiting for a reply and filling the 'reply' field with * the externally visible address. - *c + * + * @param server, the address of the stun server * @param port, port of the stun server * @param sock the socket used to send the request - * @return GNUNET_NAT_StunRequestHandle on success, NULL on error. + * @return GNUNET_NAT_STUN_Handle on success, NULL on error. */ -struct GNUNET_NAT_StunRequestHandle * -GNUNET_NAT_stun_make_request(char * server, int port, struct GNUNET_NETWORK_Handle * sock); +struct GNUNET_NAT_STUN_Handle * +GNUNET_NAT_stun_make_request(char * server, int port, + struct GNUNET_NETWORK_Handle * sock, GNUNET_NAT_stun_RequestCallback cb, + void *cb_cls); /** @@ -489,6 +513,20 @@ GNUNET_NAT_stun_make_request(char * server, int port, struct GNUNET_NETWORK_Hand int GNUNET_NAT_stun_handle_packet(const uint8_t *data, size_t len,struct sockaddr_in *arg); +/** + * CHECK if is a valid STUN packet sending to GNUNET_NAT_stun_handle_packet + * + * @param cls, NAT callback + * @param data, pointer where we will set the type + * @param len, pointer where we will set the type + * @param st, pointer where we will set the type + * + * @return, 0 on IGNORE, -1 if the packet is invalid ( not a stun packet) + */ +int +GNUNET_NAT_try_decode_stun_packet(void *cls, const uint8_t *data, size_t len); + + #endif diff --git a/src/nat/gnunet-nat-server.c b/src/nat/gnunet-nat-server.c index a5a5b4bed..66b5ee3da 100644 --- a/src/nat/gnunet-nat-server.c +++ b/src/nat/gnunet-nat-server.c @@ -58,7 +58,7 @@ try_anat (uint32_t dst_ipv4, uint16_t dport, int is_tcp) GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Asking for connection reversal with %x and code %u\n", (unsigned int) dst_ipv4, (unsigned int) dport); - h = GNUNET_NAT_register (cfg, is_tcp, dport, 0, NULL, NULL, NULL, NULL, NULL); + h = GNUNET_NAT_register (cfg, is_tcp, dport, 0, NULL, NULL, NULL, NULL, NULL, NULL); memset (&sa, 0, sizeof (sa)); sa.sin_family = AF_INET; #if HAVE_SOCKADDR_IN_SIN_LEN diff --git a/src/nat/nat.c b/src/nat/nat.c index 9eb7e7e7b..f5b1123c6 100644 --- a/src/nat/nat.c +++ b/src/nat/nat.c @@ -56,6 +56,12 @@ #define HOSTNAME_RESOLVE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1) +/** + * How often do we check a STUN server ? + */ +#define STUN_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 2) + + /** * Where did the given local address originate from? * To be used for debugging as well as in the future @@ -170,6 +176,35 @@ struct MiniList }; +/** + * List of STUN servers + */ +struct StunServerList +{ + + /** + * Doubly-linked list. + */ + struct StunServerList *next; + + /** + * Doubly-linked list. + */ + struct StunServerList *prev; + + /** + * Address + */ + char * address; + + /** + * Server Port + */ + uint16_t port; + +}; + + /** * Handle for active NAT registrations. */ @@ -366,6 +401,46 @@ struct GNUNET_NAT_Handle */ uint16_t adv_port; + /** + * Should we use STUN ? + */ + int use_stun; + + /** + * How often should se check STUN ? + */ + struct GNUNET_TIME_Relative stun_frequency; + + /** + * STUN socket + */ + struct GNUNET_NETWORK_Handle* socket; + + /* + * Am I waiting for a STUN response ? + */ + int waiting_stun; + + /** + * STUN request task + */ + struct GNUNET_SCHEDULER_Task * stun_task; + + /** + * Head of List of STUN servers + */ + struct StunServerList *stun_servers_head; + + /** + * Tail of List of STUN servers + */ + struct StunServerList *stun_servers_tail; + + /** + * Actual STUN Server + */ + struct StunServerList *actual_stun_server; + }; @@ -379,6 +454,20 @@ static void start_gnunet_nat_server (struct GNUNET_NAT_Handle *h); + + +/** + * Call task to process STUN + * + * @param cls handle to NAT + * @param tc TaskContext + */ + +static void +process_stun (void *cls, + const struct GNUNET_SCHEDULER_TaskContext *tc); + + /** * Remove all addresses from the list of 'local' addresses * that originated from the given source. @@ -1013,6 +1102,113 @@ list_interfaces (void *cls, } + +/** + * Callback if the STun request have a error + * + * @param cls the NAT handle + * @param result , the status + */ +static void stun_request_callback(void *cls, + enum GNUNET_NAT_StatusCode result) +{ + + struct GNUNET_NAT_Handle *h = cls; + + h->waiting_stun = GNUNET_NO; + LOG (GNUNET_ERROR_TYPE_WARNING, + "Error processing a STUN request"); + +}; + +/** + * Check if STUN can decode the packet + * + * @param cls the NAT handle + * @param data, packet + * @param len, packet lenght + * + * @return GNUNET_NO if it can't decode, GNUNET_YES if is a packet + */ +int +GNUNET_NAT_try_decode_stun_packet(void *cls, const uint8_t *data, size_t len) +{ + struct GNUNET_NAT_Handle *h = cls; + struct sockaddr_in answer; + + /* We are not expecting a STUN message*/ + if(!h->waiting_stun) + return GNUNET_NO; + + /* Empty the answer structure */ + memset(&answer, 0, sizeof(struct sockaddr_in)); + + /*Lets handle the packet*/ + int valid = GNUNET_NAT_stun_handle_packet(data,len, &answer); + if(valid) + { + LOG (GNUNET_ERROR_TYPE_DEBUG, + "Stun server returned IP %s , with port %d \n", inet_ntoa(answer.sin_addr), ntohs(answer.sin_port)); + /* ADD IP AS VALID*/ + add_to_address_list (h, LAL_EXTERNAL_IP, (const struct sockaddr *) &answer, + sizeof (struct sockaddr_in)); + h->waiting_stun = GNUNET_NO; + return GNUNET_YES; + } + else + { + return GNUNET_NO; + } + + + +} + +/** + * Task to do a STUN request + * + * @param cls the NAT handle + * @param tc scheduler context + */ +static void +process_stun (void *cls, + const struct GNUNET_SCHEDULER_TaskContext *tc) +{ + struct GNUNET_NAT_Handle *h = cls; + + LOG (GNUNET_ERROR_TYPE_DEBUG, + "I will do a STUN request\n"); + + + h->stun_task = NULL; + h->waiting_stun = GNUNET_YES; + + struct StunServerList* elem = h->actual_stun_server; + + /* Make the request */ + LOG (GNUNET_ERROR_TYPE_DEBUG, + "I will request the stun server %s:%i !\n", elem->address, elem->port); + + GNUNET_NAT_stun_make_request(elem->address, elem->port, h->socket, &stun_request_callback, NULL); + + h->stun_task = + GNUNET_SCHEDULER_add_delayed (h->stun_frequency, + &process_stun, h); + + /* Set actual Server*/ + if(elem->next) + { + h->actual_stun_server = elem->next; + } + else + { + h->actual_stun_server = h->stun_servers_head; + } + +} + + + /** * Task to do a lookup on our hostname for IP addresses. * @@ -1242,6 +1438,7 @@ add_from_bind (struct GNUNET_NAT_Handle *h) * @param address_callback function to call everytime the public IP address changes * @param reversal_callback function to call if someone wants connection reversal from us * @param callback_cls closure for callbacks + * @param sock used socket * @return NULL on error, otherwise handle that can be used to unregister */ struct GNUNET_NAT_Handle * @@ -1253,7 +1450,8 @@ GNUNET_NAT_register (const struct GNUNET_CONFIGURATION_Handle *cfg, const socklen_t *addrlens, GNUNET_NAT_AddressCallback address_callback, GNUNET_NAT_ReversalCallback reversal_callback, - void *callback_cls) + void *callback_cls, + struct GNUNET_NETWORK_Handle* sock ) { struct GNUNET_NAT_Handle *h; struct in_addr in_addr; @@ -1355,6 +1553,17 @@ GNUNET_NAT_register (const struct GNUNET_CONFIGURATION_Handle *cfg, h->enable_upnp = GNUNET_NO; } + /* STUN */ + h->use_stun = + GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat", + "USE_STUN"); + + if (GNUNET_OK != + GNUNET_CONFIGURATION_get_value_time (cfg, "nat", "STUN_FREQUENCY", + &h->stun_frequency)) + h->stun_frequency = STUN_FREQUENCY; + + /* Check if NAT was hole-punched */ if ((NULL != h->address_callback) && (NULL != h->external_address) && @@ -1363,6 +1572,7 @@ GNUNET_NAT_register (const struct GNUNET_CONFIGURATION_Handle *cfg, h->dns_task = GNUNET_SCHEDULER_add_now (&resolve_dns, h); h->enable_nat_server = GNUNET_NO; h->enable_upnp = GNUNET_NO; + h->use_stun = GNUNET_NO; } else { @@ -1370,6 +1580,95 @@ GNUNET_NAT_register (const struct GNUNET_CONFIGURATION_Handle *cfg, "No external IP address given to add to our list of addresses\n"); } + /* ENABLE STUN ONLY ON UDP*/ + if(!is_tcp && (NULL != sock) && h->use_stun ) { + h->socket = sock; + h->actual_stun_server = NULL; + + /* Lets process the servers*/ + char *stun_servers; + + size_t urls; + int pos; + size_t pos_port; + + if (GNUNET_OK != + GNUNET_CONFIGURATION_get_value_string (cfg, "nat", "STUN_SERVERS", + &stun_servers)) + { + GNUNET_log_config_missing (GNUNET_ERROR_TYPE_WARNING, + "nat", "STUN_SERVERS"); + } + + urls = 0; + h->stun_servers_head = NULL; + h->stun_servers_tail = NULL; + h->actual_stun_server = NULL; + if (strlen (stun_servers) > 0) + { + pos = strlen (stun_servers) - 1; + pos_port = 0; + while (pos >= 0) + { + if (stun_servers[pos] == ':') + { + pos_port = pos + 1; + } + if ((stun_servers[pos] == ' ') || (0 == pos)) + { + + /*Check if we do have a port*/ + if((0 == pos_port) || (pos_port <= pos)) + { + LOG (GNUNET_ERROR_TYPE_WARNING, + "STUN server format mistake\n"); + break; + } + + urls++; + + struct StunServerList* ml = GNUNET_new (struct StunServerList); + + ml->next = NULL; + ml->prev = NULL; + + ml->port = atoi(&stun_servers[pos_port]); + stun_servers[pos_port-1] = '\0'; + + /* Remove trailing space */ + if(stun_servers[pos] == ' ') + ml->address = GNUNET_strdup (&stun_servers[pos + 1]); + else + ml->address = GNUNET_strdup (&stun_servers[pos]); + + LOG (GNUNET_ERROR_TYPE_DEBUG, + "Found STUN server %s port %i !!!\n", ml->address, ml->port); + + GNUNET_CONTAINER_DLL_insert (h->stun_servers_head, h->stun_servers_tail, ml); + /* Make sure that we STOP if is the last one*/ + if(0== pos) + break; + } + + pos--; + } + } + if (urls == 0) + { + GNUNET_log_config_missing (GNUNET_ERROR_TYPE_WARNING, + "nat", "STUN_SERVERS"); + } + else + { + /* Set the actual STUN server*/ + h->actual_stun_server = h->stun_servers_head; + } + + h->stun_task = GNUNET_SCHEDULER_add_now(&process_stun, + h); + } + + /* Test for SUID binaries */ binary = GNUNET_OS_get_libexec_binary_path ("gnunet-helper-nat-server"); if ((h->behind_nat == GNUNET_YES) && (GNUNET_YES == h->enable_nat_server) && diff --git a/src/nat/nat.conf b/src/nat/nat.conf index 86522d994..9afa0aad0 100644 --- a/src/nat/nat.conf +++ b/src/nat/nat.conf @@ -48,6 +48,13 @@ IFC_SCAN_FREQUENCY = 15 min # for our hostname (to get our own IP) DYNDNS_FREQUENCY = 7 min +# SHOULD USE STUN ? +USE_STUN = YES +STUN_FREQUENCY = 2 min +# Default list of stun servers +STUN_SERVERS = stun.services.mozilla.com:3478 stun2.l.google.com:19302 + + [gnunet-nat-server] HOSTNAME = gnunet.org PORT = 5724 diff --git a/src/nat/nat_stun.c b/src/nat/nat_stun.c index 9419074a7..5e502c29e 100644 --- a/src/nat/nat_stun.c +++ b/src/nat/nat_stun.c @@ -48,6 +48,7 @@ #define LOG(kind,...) GNUNET_log_from (kind, "stun", __VA_ARGS__) +#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15) /** @@ -55,28 +56,44 @@ * the request prior to the timeout or successful execution. Also * used to track our internal state for the request. */ -struct GNUNET_NAT_StunRequestHandle { +struct GNUNET_NAT_STUN_Handle { - /** - * Handle to a pending DNS lookup request. - */ - struct GNUNET_RESOLVER_RequestHandle *dns_active; + /** + * Handle to a pending DNS lookup request. + */ + struct GNUNET_RESOLVER_RequestHandle *dns_active; - /** - * Handle to the listen socket - */ - struct GNUNET_NETWORK_Handle * sock; + /** + * Handle to the listen socket + */ + struct GNUNET_NETWORK_Handle * sock; + + /** + * Stun server address + */ + char *stun_server ; + + /** + * STUN port + */ + int stun_port; - /** - * Stun server address + /** + * Function to call when a error occours + */ + GNUNET_NAT_stun_RequestCallback cb; + + /** + * Closure for @e cb. */ - char *stun_server ; + void *cb_cls; - /** - * STUN port + /** + * Do we got a DNS resolution successfully ? */ - int stun_port; + int dns_success; + }; @@ -84,7 +101,7 @@ struct GNUNET_NAT_StunRequestHandle { /* here we store credentials extracted from a message */ struct StunState { - uint16_t attr; + uint16_t attr; }; @@ -96,7 +113,7 @@ struct StunState { */ static int decode_class(int msg) { - return ((msg & 0x0010) >> 4) | ((msg & 0x0100) >> 7); + return ((msg & 0x0010) >> 4) | ((msg & 0x0100) >> 7); } /** @@ -107,7 +124,7 @@ static int decode_class(int msg) */ static int decode_method(int msg) { - return (msg & 0x000f) | ((msg & 0x00e0) >> 1) | ((msg & 0x3e00) >> 2); + return (msg & 0x000f) | ((msg & 0x00e0) >> 1) | ((msg & 0x3e00) >> 2); } /** @@ -119,8 +136,8 @@ static int decode_method(int msg) */ static int encode_message(StunClasses msg_class, StunMethods method) { - return ((msg_class & 1) << 4) | ((msg_class & 2) << 7) | - (method & 0x000f) | ((method & 0x0070) << 1) | ((method & 0x0f800) << 2); + return ((msg_class & 1) << 4) | ((msg_class & 2) << 7) | + (method & 0x000f) | ((method & 0x0070) << 1) | ((method & 0x0f800) << 2); } /** @@ -132,41 +149,41 @@ static int encode_message(StunClasses msg_class, StunMethods method) static const char *stun_msg2str(int msg) { - const struct { enum StunClasses value; const char *name; } classes[] = { - { STUN_REQUEST, "Request" }, - { STUN_INDICATION, "Indication" }, - { STUN_RESPONSE, "Response" }, - { STUN_ERROR_RESPONSE, "Error Response" }, - { 0, NULL } - }; - - const struct { enum StunMethods value; const char *name; } methods[] = { - { STUN_BINDING, "Binding" }, - { 0, NULL } - }; - - static char result[32]; - const char *msg_class = NULL; - const char *method = NULL; - int i; - int value; - - value = decode_class(msg); - for (i = 0; classes[i].name; i++) { - msg_class = classes[i].name; - if (classes[i].value == value) - break; - } - value = decode_method(msg); - for (i = 0; methods[i].name; i++) { - method = methods[i].name; - if (methods[i].value == value) - break; - } - snprintf(result, sizeof(result), "%s %s", - method ? : "Unknown Method", - msg_class ? : "Unknown Class Message"); - return result; + const struct { enum StunClasses value; const char *name; } classes[] = { + { STUN_REQUEST, "Request" }, + { STUN_INDICATION, "Indication" }, + { STUN_RESPONSE, "Response" }, + { STUN_ERROR_RESPONSE, "Error Response" }, + { 0, NULL } + }; + + const struct { enum StunMethods value; const char *name; } methods[] = { + { STUN_BINDING, "Binding" }, + { 0, NULL } + }; + + static char result[32]; + const char *msg_class = NULL; + const char *method = NULL; + int i; + int value; + + value = decode_class(msg); + for (i = 0; classes[i].name; i++) { + msg_class = classes[i].name; + if (classes[i].value == value) + break; + } + value = decode_method(msg); + for (i = 0; methods[i].name; i++) { + method = methods[i].name; + if (methods[i].value == value) + break; + } + snprintf(result, sizeof(result), "%s %s", + method ? : "Unknown Method", + msg_class ? : "Unknown Class Message"); + return result; } /** @@ -177,35 +194,35 @@ static const char *stun_msg2str(int msg) */ static const char *stun_attr2str(int msg) { - const struct { enum StunAttributes value; const char *name; } attrs[] = { - { STUN_MAPPED_ADDRESS, "Mapped Address" }, - { STUN_RESPONSE_ADDRESS, "Response Address" }, - { STUN_CHANGE_ADDRESS, "Change Address" }, - { STUN_SOURCE_ADDRESS, "Source Address" }, - { STUN_CHANGED_ADDRESS, "Changed Address" }, - { STUN_USERNAME, "Username" }, - { STUN_PASSWORD, "Password" }, - { STUN_MESSAGE_INTEGRITY, "Message Integrity" }, - { STUN_ERROR_CODE, "Error Code" }, - { STUN_UNKNOWN_ATTRIBUTES, "Unknown Attributes" }, - { STUN_REFLECTED_FROM, "Reflected From" }, - { STUN_REALM, "Realm" }, - { STUN_NONCE, "Nonce" }, - { STUN_XOR_MAPPED_ADDRESS, "XOR Mapped Address" }, - { STUN_MS_VERSION, "MS Version" }, - { STUN_MS_XOR_MAPPED_ADDRESS, "MS XOR Mapped Address" }, - { STUN_SOFTWARE, "Software" }, - { STUN_ALTERNATE_SERVER, "Alternate Server" }, - { STUN_FINGERPRINT, "Fingerprint" }, - { 0, NULL } - }; - int i; - - for (i = 0; attrs[i].name; i++) { - if (attrs[i].value == msg) - return attrs[i].name; - } - return "Unknown Attribute"; + const struct { enum StunAttributes value; const char *name; } attrs[] = { + { STUN_MAPPED_ADDRESS, "Mapped Address" }, + { STUN_RESPONSE_ADDRESS, "Response Address" }, + { STUN_CHANGE_ADDRESS, "Change Address" }, + { STUN_SOURCE_ADDRESS, "Source Address" }, + { STUN_CHANGED_ADDRESS, "Changed Address" }, + { STUN_USERNAME, "Username" }, + { STUN_PASSWORD, "Password" }, + { STUN_MESSAGE_INTEGRITY, "Message Integrity" }, + { STUN_ERROR_CODE, "Error Code" }, + { STUN_UNKNOWN_ATTRIBUTES, "Unknown Attributes" }, + { STUN_REFLECTED_FROM, "Reflected From" }, + { STUN_REALM, "Realm" }, + { STUN_NONCE, "Nonce" }, + { STUN_XOR_MAPPED_ADDRESS, "XOR Mapped Address" }, + { STUN_MS_VERSION, "MS Version" }, + { STUN_MS_XOR_MAPPED_ADDRESS, "MS XOR Mapped Address" }, + { STUN_SOFTWARE, "Software" }, + { STUN_ALTERNATE_SERVER, "Alternate Server" }, + { STUN_FINGERPRINT, "Fingerprint" }, + { 0, NULL } + }; + int i; + + for (i = 0; attrs[i].name; i++) { + if (attrs[i].value == msg) + return attrs[i].name; + } + return "Unknown Attribute"; } @@ -219,22 +236,22 @@ static const char *stun_attr2str(int msg) */ static int stun_process_attr(struct StunState *state, struct stun_attr *attr) { - LOG (GNUNET_ERROR_TYPE_INFO, - "Found STUN Attribute %s (%04x), length %d\n", - stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len)); - - switch (ntohs(attr->attr)) { - case STUN_MAPPED_ADDRESS: - case STUN_XOR_MAPPED_ADDRESS: - case STUN_MS_XOR_MAPPED_ADDRESS: - break; - default: - LOG (GNUNET_ERROR_TYPE_INFO, - "Ignoring STUN Attribute %s (%04x), length %d\n", - stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len)); - - } - return 0; + LOG (GNUNET_ERROR_TYPE_INFO, + "Found STUN Attribute %s (%04x), length %d\n", + stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len)); + + switch (ntohs(attr->attr)) { + case STUN_MAPPED_ADDRESS: + case STUN_XOR_MAPPED_ADDRESS: + case STUN_MS_XOR_MAPPED_ADDRESS: + break; + default: + LOG (GNUNET_ERROR_TYPE_INFO, + "Ignoring STUN Attribute %s (%04x), length %d\n", + stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len)); + + } + return 0; } @@ -247,11 +264,11 @@ static int stun_process_attr(struct StunState *state, struct stun_attr *attr) static void generate_request_id(struct stun_header *req) { - int x; - req->magic = htonl(STUN_MAGIC_COOKIE); - for (x = 0; x < 3; x++) - req->id.id[x] = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, - UINT32_MAX); + int x; + req->magic = htonl(STUN_MAGIC_COOKIE); + for (x = 0; x < 3; x++) + req->id.id[x] = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, + UINT32_MAX); } @@ -295,6 +312,8 @@ stun_get_mapped(struct StunState *st, struct stun_attr *attr,struct sockaddr_in } st->attr = type; + /*TODO: Detect Family*/ + sa->sin_family = AF_INET; sa->sin_port = returned_addr->port ^ htons(ntohl(magic) >> 16); sa->sin_addr.s_addr = returned_addr->addr ^ magic; return 0; @@ -312,94 +331,109 @@ stun_get_mapped(struct StunState *st, struct stun_attr *attr,struct sockaddr_in * @param len, the length of the packet * @param arg, sockaddr_in where we will set our discovered packet * - * @return, 0 on OK, -1 if the packet is invalid ( not a stun packet) + * @return, GNUNET_OK on OK, GNUNET_NO if the packet is invalid ( not a stun packet) */ int GNUNET_NAT_stun_handle_packet(const uint8_t *data, size_t len,struct sockaddr_in *arg) { - struct stun_header *hdr = (struct stun_header *)data; - struct stun_attr *attr; - struct StunState st; - int ret = STUN_IGNORE; - - uint32_t advertised_message_size; - uint32_t message_magic_cookie; - - - /* On entry, 'len' is the length of the udp payload. After the - * initial checks it becomes the size of unprocessed options, - * while 'data' is advanced accordingly. - */ - if (len < sizeof(struct stun_header)) { - LOG (GNUNET_ERROR_TYPE_INFO, - "STUN packet too short (only %d, wanting at least %d)\n", (int) len, (int) sizeof(struct stun_header)); - GNUNET_break_op (0); - return -1; - } - /* Skip header as it is already in hdr */ - len -= sizeof(struct stun_header); - data += sizeof(struct stun_header); - - /* len as advertised in the message */ - advertised_message_size = ntohs(hdr->msglen); - - message_magic_cookie = ntohl(hdr->magic); - /* Compare if the cookie match */ - if(STUN_MAGIC_COOKIE != message_magic_cookie){ - LOG (GNUNET_ERROR_TYPE_INFO, - "Invalid magic cookie \n"); - GNUNET_break_op (0); - return -1; - } - - - LOG (GNUNET_ERROR_TYPE_INFO, "STUN Packet, msg %s (%04x), length: %d\n", stun_msg2str(ntohs(hdr->msgtype)), ntohs(hdr->msgtype), advertised_message_size); - - - if (advertised_message_size > len) { - LOG (GNUNET_ERROR_TYPE_INFO, "Scrambled STUN packet length (got %d, expecting %d)\n", advertised_message_size, (int)len); - GNUNET_break_op (0); - return -1; - } else { - len = advertised_message_size; - } - /* Zero the struct */ - memset(&st,0, sizeof(st)); - - while (len > 0) { - if (len < sizeof(struct stun_attr)) { - LOG (GNUNET_ERROR_TYPE_INFO, "Attribute too short (got %d, expecting %d)\n", (int)len, (int) sizeof(struct stun_attr)); - GNUNET_break_op (0); - break; - } - attr = (struct stun_attr *)data; - - /* compute total attribute length */ - advertised_message_size = ntohs(attr->len) + sizeof(struct stun_attr); - - /* Check if we still have space in our buffer */ - if (advertised_message_size > len ) { - LOG (GNUNET_ERROR_TYPE_INFO, "Inconsistent Attribute (length %d exceeds remaining msg len %d)\n", advertised_message_size, (int)len); - GNUNET_break_op (0); - break; - } - - - stun_get_mapped(&st, attr, arg, hdr->magic); - - if (stun_process_attr(&st, attr)) { - LOG (GNUNET_ERROR_TYPE_INFO, "Failed to handle attribute %s (%04x)\n", stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr)); - break; - } - /* Clear attribute id: in case previous entry was a string, - * this will act as the terminator for the string. - */ - attr->attr = 0; - data += advertised_message_size; - len -= advertised_message_size; - } - - return ret; + struct stun_header *hdr = (struct stun_header *)data; + struct stun_attr *attr; + struct StunState st; + int ret = GNUNET_OK; + + uint32_t advertised_message_size; + uint32_t message_magic_cookie; + + + /* On entry, 'len' is the length of the udp payload. After the + * initial checks it becomes the size of unprocessed options, + * while 'data' is advanced accordingly. + */ + if (len < sizeof(struct stun_header)) { + LOG (GNUNET_ERROR_TYPE_INFO, + "STUN packet too short (only %d, wanting at least %d)\n", (int) len, (int) sizeof(struct stun_header)); + GNUNET_break_op (0); + return GNUNET_NO; + } + /* Skip header as it is already in hdr */ + len -= sizeof(struct stun_header); + data += sizeof(struct stun_header); + + /* len as advertised in the message */ + advertised_message_size = ntohs(hdr->msglen); + + message_magic_cookie = ntohl(hdr->magic); + /* Compare if the cookie match */ + if(STUN_MAGIC_COOKIE != message_magic_cookie){ + LOG (GNUNET_ERROR_TYPE_INFO, + "Invalid magic cookie \n"); + GNUNET_break_op (0); + return GNUNET_NO; + } + + + LOG (GNUNET_ERROR_TYPE_INFO, "STUN Packet, msg %s (%04x), length: %d\n", stun_msg2str(ntohs(hdr->msgtype)), ntohs(hdr->msgtype), advertised_message_size); + + + if (advertised_message_size > len) { + LOG (GNUNET_ERROR_TYPE_INFO, "Scrambled STUN packet length (got %d, expecting %d)\n", advertised_message_size, (int)len); + GNUNET_break_op (0); + return GNUNET_NO; + } else { + len = advertised_message_size; + } + /* Zero the struct */ + memset(&st,0, sizeof(st)); + + while (len > 0) { + if (len < sizeof(struct stun_attr)) { + LOG (GNUNET_ERROR_TYPE_INFO, "Attribute too short (got %d, expecting %d)\n", (int)len, (int) sizeof(struct stun_attr)); + GNUNET_break_op (0); + break; + } + attr = (struct stun_attr *)data; + + /* compute total attribute length */ + advertised_message_size = ntohs(attr->len) + sizeof(struct stun_attr); + + /* Check if we still have space in our buffer */ + if (advertised_message_size > len ) { + LOG (GNUNET_ERROR_TYPE_INFO, "Inconsistent Attribute (length %d exceeds remaining msg len %d)\n", advertised_message_size, (int)len); + GNUNET_break_op (0); + break; + } + + + stun_get_mapped(&st, attr, arg, hdr->magic); + + if (stun_process_attr(&st, attr)) { + LOG (GNUNET_ERROR_TYPE_INFO, "Failed to handle attribute %s (%04x)\n", stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr)); + break; + } + /** Clear attribute id: in case previous entry was a string, + * this will act as the terminator for the string. + **/ + attr->attr = 0; + data += advertised_message_size; + len -= advertised_message_size; + ret = GNUNET_OK; + } + + return ret; +} + + + +/** + * Clean-up used memory + * + * @param cls our `struct GNUNET_NAT_STUN_Handle *` + */ +void clean(struct GNUNET_NAT_STUN_Handle * handle) +{ + GNUNET_free(handle->stun_server); + GNUNET_free(handle); + } @@ -407,97 +441,120 @@ GNUNET_NAT_stun_handle_packet(const uint8_t *data, size_t len,struct sockaddr_in /** * Try to establish a connection given the specified address. * - * @param cls our `struct GNUNET_NAT_StunRequestHandle *` + * @param cls our `struct GNUNET_NAT_STUN_Handle *` * @param addr address to try, NULL for "last call" * @param addrlen length of @a addr */ static void stun_dns_callback (void *cls, - const struct sockaddr *addr, - socklen_t addrlen) { + const struct sockaddr *addr, + socklen_t addrlen) { + + + struct GNUNET_NAT_STUN_Handle *request = cls; + struct stun_header *req; + uint8_t reqdata[1024]; + int reqlen; + struct sockaddr_in server; - struct GNUNET_NAT_StunRequestHandle *request = cls; - struct stun_header *req; - uint8_t reqdata[1024]; - int reqlen; - struct sockaddr_in server; + if(NULL == request) { - if(NULL == request) { - LOG (GNUNET_ERROR_TYPE_INFO, "Empty request\n"); - /* FIXME clean up ? */ - return; - } + if( GNUNET_NO == request->dns_success){ + LOG (GNUNET_ERROR_TYPE_INFO, "Empty request\n"); + clean(request); + request->cb(request->cb_cls, GNUNET_NAT_ERROR_INTERNAL_NETWORK_ERROR); + } + return; + } - if (NULL == addr) { - request->dns_active = NULL; - LOG (GNUNET_ERROR_TYPE_INFO, "Error resolving host %s\n", request->stun_server); - /* FIXME clean up? */ - return; - } + if (NULL == addr) { + request->dns_active = NULL; + if( GNUNET_NO == request->dns_success){ + LOG (GNUNET_ERROR_TYPE_INFO, "Error resolving host %s\n", request->stun_server); + clean(request); + request->cb(request->cb_cls, GNUNET_NAT_ERROR_INTERNAL_NETWORK_ERROR); + } - memset(&server,0, sizeof(server)); - server.sin_family = AF_INET; - server.sin_addr = ((struct sockaddr_in *)addr)->sin_addr; - server.sin_port = htons(request->stun_port); + return; + } - /*Craft the simplest possible STUN packet. A request binding*/ - req = (struct stun_header *)reqdata; - generate_request_id(req); - reqlen = 0; - req->msgtype = 0; - req->msglen = 0; - req->msglen = htons(reqlen); - req->msgtype = htons(encode_message(STUN_REQUEST, STUN_BINDING)); + request->dns_success= GNUNET_YES; + memset(&server,0, sizeof(server)); + server.sin_family = AF_INET; + server.sin_addr = ((struct sockaddr_in *)addr)->sin_addr; + server.sin_port = htons(request->stun_port); + + + /*Craft the simplest possible STUN packet. A request binding*/ + req = (struct stun_header *)reqdata; + generate_request_id(req); + reqlen = 0; + req->msgtype = 0; + req->msglen = 0; + req->msglen = htons(reqlen); + req->msgtype = htons(encode_message(STUN_REQUEST, STUN_BINDING)); + + /* Send the packet */ + if (-1 == GNUNET_NETWORK_socket_sendto (request->sock, req, ntohs(req->msglen) + sizeof(*req), + (const struct sockaddr *) &server, sizeof (server))) + { + GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "Fail to sendto"); + clean(request); + request->cb(request->cb_cls, GNUNET_NAT_ERROR_INTERNAL_NETWORK_ERROR); + return; + } - /* Send the packet */ - if (-1 == GNUNET_NETWORK_socket_sendto (request->sock, req, ntohs(req->msglen) + sizeof(*req), - (const struct sockaddr *) &server, sizeof (server))) - { - GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "Fail to sendto"); - } } + + + /** * Make Generic STUN request and * Send a generic stun request to the server specified using the specified socket. * possibly waiting for a reply and filling the 'reply' field with * the externally visible address. - *c + * * @param server, the address of the stun server * @param port, port of the stun server * @param sock the socket used to send the request - * @return GNUNET_NAT_StunRequestHandle on success, NULL on error. + * @return GNUNET_NAT_STUN_Handle on success, NULL on error. */ -struct GNUNET_NAT_StunRequestHandle * -GNUNET_NAT_stun_make_request(char * server, int port, struct GNUNET_NETWORK_Handle * sock) +struct GNUNET_NAT_STUN_Handle * +GNUNET_NAT_stun_make_request(char * server, int port, + struct GNUNET_NETWORK_Handle * sock,GNUNET_NAT_stun_RequestCallback cb, + void *cb_cls) { - struct GNUNET_NAT_StunRequestHandle *rh; + struct GNUNET_NAT_STUN_Handle *rh; + + rh = GNUNET_malloc (sizeof (struct GNUNET_NAT_STUN_Handle)); + rh->sock = sock; - rh = GNUNET_malloc (sizeof (struct GNUNET_NAT_StunRequestHandle)); - rh->sock = sock; + char * server_copy = GNUNET_strdup (server); - char * server_copy = GNUNET_malloc (1 + strlen (server)); - if (server_copy) { - strcpy (server_copy, server); - }else{ - GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "Failed to allocate string"); - /* FIXME: cleanup rh? */ - return NULL; - } + rh->cb = cb; + rh->cb_cls = cb_cls; + rh->stun_server = server_copy; + rh->stun_port = port; + rh->dns_success = GNUNET_NO; + + rh->dns_active = GNUNET_RESOLVER_ip_get (server_copy, AF_INET, + TIMEOUT, + &stun_dns_callback, rh); + + if(rh->dns_active == NULL) + { + GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "Failed DNS"); + return NULL; + } - rh->stun_server = server_copy; - rh->stun_port = port; - rh->dns_active = GNUNET_RESOLVER_ip_get (rh->stun_server, AF_INET, - GNUNET_CONNECTION_CONNECT_RETRY_TIMEOUT, - &stun_dns_callback, rh); - /* FIXME: error handling NULL==dns_active, callback function? */ - return rh; + return rh; } diff --git a/src/nat/nat_test.c b/src/nat/nat_test.c index eda969502..3ee80ecae 100644 --- a/src/nat/nat_test.c +++ b/src/nat/nat_test.c @@ -444,7 +444,7 @@ GNUNET_NAT_test_start (const struct GNUNET_CONFIGURATION_Handle *cfg, = GNUNET_NAT_register (cfg, is_tcp, 0, 0, NULL, NULL, &addr_cb, - &reversal_cb, nh); + &reversal_cb, nh, NULL); } else { @@ -490,7 +490,7 @@ GNUNET_NAT_test_start (const struct GNUNET_CONFIGURATION_Handle *cfg, (GNUNET_YES == is_tcp) ? "tcp" : "udp"); nh->nat = GNUNET_NAT_register (cfg, is_tcp, adv_port, 1, addrs, addrlens, - &addr_cb, NULL, nh); + &addr_cb, NULL, nh, NULL); if (NULL == nh->nat) { LOG (GNUNET_ERROR_TYPE_ERROR, diff --git a/src/nat/test_nat.c b/src/nat/test_nat.c index d62d156a2..b1d90ca31 100644 --- a/src/nat/test_nat.c +++ b/src/nat/test_nat.c @@ -143,7 +143,7 @@ run (void *cls, char *const *args, const char *cfgfile, nat = GNUNET_NAT_register (cfg, GNUNET_YES /* tcp */ , 2086, 1, (const struct sockaddr **) &addr, - &data.addrlen, &addr_callback, NULL, NULL); + &data.addrlen, &addr_callback, NULL, NULL, NULL); GNUNET_free (addr); GNUNET_SCHEDULER_add_delayed (TIMEOUT, &stop, nat); } diff --git a/src/nat/test_stun.c b/src/nat/test_stun.c index f0956d021..e75d55bd0 100644 --- a/src/nat/test_stun.c +++ b/src/nat/test_stun.c @@ -23,7 +23,7 @@ * * @file nat/test_stun.c * @brief Testcase for STUN library - * @author Bruno Souza Cabral - Major rewrite. + * @author Bruno Souza Cabral * */ @@ -39,14 +39,20 @@ #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 char *stun_server = "stun.ekiga.net"; -static int stun_port = 3478; +static char *stun_server = "stun2.l.google.com"; +static int stun_port = 19302; /** * The listen socket of the service for IPv4 @@ -85,23 +91,26 @@ do_udp_read (void *cls, ssize_t rlen; struct sockaddr_in answer; + printf("UDP READ\n"); + if ((0 != (tc->reason & GNUNET_SCHEDULER_REASON_READ_READY)) && (GNUNET_NETWORK_fdset_isset (tc->read_ready, lsock4))) { rlen = GNUNET_NETWORK_socket_recv (lsock4, reply_buf, sizeof (reply_buf)); - + //Lets handle the packet memset(&answer, 0, sizeof(struct sockaddr_in)); GNUNET_NAT_stun_handle_packet(reply_buf,rlen, &answer); //Print the answer - //TODO: Delete the object ret = 0; print_answer(&answer); - + + //Destroy the connection + GNUNET_NETWORK_socket_close(lsock4); } @@ -144,13 +153,38 @@ bind_v4 () return ls; } +/** + * Function that terminates the test. + */ +static void +stop () +{ + GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Stopping NAT and quitting...\n"); + + printf("Stopped !!\n"); + //Clean task + if(NULL != ltask4) + GNUNET_SCHEDULER_cancel (ltask4); + + //Clean socket + if(NULL != ltask4) + GNUNET_NETWORK_socket_close (lsock4); + +} + + +static void request_callback(void *cls, +enum GNUNET_NAT_StatusCode result) +{ + ret = result; + stop(); + printf("Called back\n"); +}; /** * Main function run with scheduler. */ - - static void run (void *cls, char *const *args, const char *cfgfile, const struct GNUNET_CONFIGURATION_Handle *cfg) @@ -162,29 +196,26 @@ run (void *cls, char *const *args, const char *cfgfile, if (NULL == lsock4) { GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind"); + GNUNET_SCHEDULER_shutdown (); + return; } else { - printf("Binded, now will call add_read\n"); //Lets call our function now when it accepts ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, lsock4, &do_udp_read, NULL); /* So you read once and what will happen if you get an irregular message? Repeat and add timeout */ } - if(NULL == lsock4 ) - { - /* FIXME: duplicate check */ - GNUNET_SCHEDULER_shutdown (); - return; - } + GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Service listens on port %u\n", port); printf("Start main event\n"); - GNUNET_NAT_stun_make_request(stun_server, stun_port, lsock4); - //Main event - //main_task = GNUNET_SCHEDULER_add_delayed (timeout, &do_timeout, nh); + GNUNET_NAT_stun_make_request(stun_server, stun_port, lsock4, &request_callback, NULL); + printf("Made the requeest\n"); + + //GNUNET_SCHEDULER_add_delayed (TIMEOUT, &stop, NULL); } @@ -198,13 +229,38 @@ main (int argc, char *const argv[]) char *const argv_prog[] = { "test-stun", + "-c", + "test_stun.conf", NULL }; GNUNET_log_setup ("test-stun", "WARNING", NULL); - GNUNET_PROGRAM_run (1, argv_prog, "test-stun", "nohelp", options, &run, NULL); + /* Lets start resolver */ + char *fn; + struct GNUNET_OS_Process *proc; + + 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); + GNUNET_assert (NULL != proc); + + 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; + return ret; } diff --git a/src/transport/plugin_transport_http_server.c b/src/transport/plugin_transport_http_server.c index b4130f945..0000a604d 100644 --- a/src/transport/plugin_transport_http_server.c +++ b/src/transport/plugin_transport_http_server.c @@ -2761,7 +2761,7 @@ server_start_report_addresses (struct HTTP_Server_Plugin *plugin) plugin->port, (unsigned int) res, (const struct sockaddr **) addrs, addrlens, - &server_nat_port_map_callback, NULL, plugin); + &server_nat_port_map_callback, NULL, plugin, NULL); while (res > 0) { res--; diff --git a/src/transport/plugin_transport_tcp.c b/src/transport/plugin_transport_tcp.c index ec66a4388..b4bcde60f 100644 --- a/src/transport/plugin_transport_tcp.c +++ b/src/transport/plugin_transport_tcp.c @@ -2960,7 +2960,7 @@ libgnunet_plugin_transport_tcp_init (void *cls) (const struct sockaddr **) addrs, addrlens, &tcp_nat_port_map_callback, &try_connection_reversal, - plugin); + plugin, NULL); for (ret = ret_s -1; ret >= 0; ret--) GNUNET_free (addrs[ret]); GNUNET_free_non_null (addrs); @@ -2976,7 +2976,8 @@ libgnunet_plugin_transport_tcp_init (void *cls) NULL, NULL, &try_connection_reversal, - plugin); + plugin, + NULL); } api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions); api->cls = plugin; diff --git a/src/transport/plugin_transport_udp.c b/src/transport/plugin_transport_udp.c index 91839bbff..d031e6008 100644 --- a/src/transport/plugin_transport_udp.c +++ b/src/transport/plugin_transport_udp.c @@ -2854,6 +2854,13 @@ udp_select_read (struct Plugin *plugin, /* Connection failure or something. Not a protocol violation. */ return; } + + + /* PROCESS STUN PACKET */ + if(GNUNET_NAT_try_decode_stun_packet(plugin->nat,(uint8_t *)buf, size )) + return; + + if (size < sizeof(struct GNUNET_MessageHeader)) { LOG (GNUNET_ERROR_TYPE_WARNING, @@ -2866,6 +2873,10 @@ udp_select_read (struct Plugin *plugin, GNUNET_break_op (0); return; } + + + + msg = (const struct GNUNET_MessageHeader *) buf; LOG (GNUNET_ERROR_TYPE_DEBUG, "UDP received %u-byte message from `%s' type %u\n", @@ -3533,7 +3544,8 @@ setup_sockets (struct Plugin *plugin, addrlens, &udp_nat_port_map_callback, NULL, - plugin); + plugin, + plugin->sockv4); return sockets_created; } diff --git a/src/transport/plugin_transport_udp.h b/src/transport/plugin_transport_udp.h index 603e13e1a..5f8366636 100644 --- a/src/transport/plugin_transport_udp.h +++ b/src/transport/plugin_transport_udp.h @@ -189,6 +189,11 @@ struct Plugin */ struct GNUNET_NAT_Handle *nat; + /** + * Handle to NAT traversal support. + */ + struct GNUNET_NAT_STUN_Handle *stun; + /** * The read socket for IPv4 */ -- cgit v1.2.3