2 This file is part of GNUnet.
3 Copyright (C) 2007-2016 GNUnet e.V.
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
22 * @author Christian Grothoff
23 * @author Milan Bouchet-Valat
26 * Service for handling UPnP and NAT-PMP port forwarding
27 * and external IP address retrieval
30 #include "gnunet_nat_service.h"
36 * Entry in DLL of addresses of this peer.
44 struct AddrEntry *next;
49 struct AddrEntry *prev;
52 * Address class of the address.
54 enum GNUNET_NAT_AddressClass ac;
57 * Number of bytes that follow.
64 * Handle for active NAT registrations.
66 struct GNUNET_NAT_Handle
70 * Configuration we use.
72 const struct GNUNET_CONFIGURATION_Handle *cfg;
75 * Message queue for communicating with the NAT service.
77 struct GNUNET_MQ_Handle *mq;
80 * Our registration message.
82 struct GNUNET_MessageHeader *reg;
85 * Head of address DLL.
87 struct AddrEntry *ae_head;
90 * Tail of address DLL.
92 struct AddrEntry *ae_tail;
95 * Function to call when our addresses change.
97 GNUNET_NAT_AddressCallback address_callback;
100 * Function to call when another peer requests connection reversal.
102 GNUNET_NAT_ReversalCallback reversal_callback;
105 * Closure for the various callbacks.
110 * Task scheduled to reconnect to the service.
112 struct GNUNET_SCHEDULER_Task *reconnect_task;
115 * How long to wait until we reconnect.
117 struct GNUNET_TIME_Relative reconnect_delay;
122 * Task to connect to the NAT service.
124 * @param cls our `struct GNUNET_NAT_Handle *`
127 do_connect (void *cls);
131 * Task to connect to the NAT service.
133 * @param nh handle to reconnect
136 reconnect (struct GNUNET_NAT_Handle *nh)
138 struct AddrEntry *ae;
142 GNUNET_MQ_destroy (nh->mq);
145 while (NULL != (ae = nh->ae_head))
147 GNUNET_CONTAINER_DLL_remove (nh->ae_head,
150 nh->address_callback (nh->callback_cls,
153 (const struct sockaddr *) &ae[1],
158 = GNUNET_TIME_STD_BACKOFF (nh->reconnect_delay);
160 = GNUNET_SCHEDULER_add_delayed (nh->reconnect_delay,
167 * Check connection reversal request.
169 * @param cls our `struct GNUNET_NAT_Handle`
170 * @param crm the message
171 * @return #GNUNET_OK if @a crm is well-formed
174 check_connection_reversal_request (void *cls,
175 const struct GNUNET_NAT_ConnectionReversalRequestedMessage *crm)
177 if (ntohs (crm->header.size) !=
179 sizeof (struct sockaddr_in) )
182 return GNUNET_SYSERR;
189 * Handle connection reversal request.
191 * @param cls our `struct GNUNET_NAT_Handle`
192 * @param crm the message
195 handle_connection_reversal_request (void *cls,
196 const struct GNUNET_NAT_ConnectionReversalRequestedMessage *crm)
198 struct GNUNET_NAT_Handle *nh = cls;
200 nh->reversal_callback (nh->callback_cls,
201 (const struct sockaddr *) &crm[1],
202 sizeof (struct sockaddr_in));
207 * Check address change notification.
209 * @param cls our `struct GNUNET_NAT_Handle`
210 * @param acn the message
211 * @return #GNUNET_OK if @a crm is well-formed
214 check_address_change_notification (void *cls,
215 const struct GNUNET_NAT_AddressChangeNotificationMessage *acn)
217 size_t alen = ntohs (acn->header.size) - sizeof (*acn);
221 case sizeof (struct sockaddr_in):
223 const struct sockaddr_in *s4
224 = (const struct sockaddr_in *) &acn[1];
225 if (AF_INET != s4->sin_family)
228 return GNUNET_SYSERR;
232 case sizeof (struct sockaddr_in6):
234 const struct sockaddr_in6 *s6
235 = (const struct sockaddr_in6 *) &acn[1];
236 if (AF_INET6 != s6->sin6_family)
239 return GNUNET_SYSERR;
245 return GNUNET_SYSERR;
252 * Handle connection reversal request.
254 * @param cls our `struct GNUNET_NAT_Handle`
255 * @param acn the message
258 handle_address_change_notification (void *cls,
259 const struct GNUNET_NAT_AddressChangeNotificationMessage *acn)
261 struct GNUNET_NAT_Handle *nh = cls;
262 size_t alen = ntohs (acn->header.size) - sizeof (*acn);
263 const struct sockaddr *sa = (const struct sockaddr *) &acn[1];
264 enum GNUNET_NAT_AddressClass ac;
265 struct AddrEntry *ae;
267 ac = (enum GNUNET_NAT_AddressClass) ntohl (acn->addr_class);
268 if (GNUNET_YES == ntohl (acn->add_remove))
270 ae = GNUNET_malloc (sizeof (*ae) + alen);
273 GNUNET_memcpy (&ae[1],
276 GNUNET_CONTAINER_DLL_insert (nh->ae_head,
282 for (ae = nh->ae_head; NULL != ae; ae = ae->next)
283 if ( (ae->addrlen == alen) &&
284 (0 == memcmp (&ae[1],
294 GNUNET_CONTAINER_DLL_remove (nh->ae_head,
299 nh->address_callback (nh->callback_cls,
300 ntohl (acn->add_remove),
308 * Handle queue errors by reconnecting to NAT.
310 * @param cls the `struct GNUNET_NAT_Handle *`
311 * @param error details about the error
314 mq_error_handler (void *cls,
315 enum GNUNET_MQ_Error error)
317 struct GNUNET_NAT_Handle *nh = cls;
324 * Task to connect to the NAT service.
326 * @param cls our `struct GNUNET_NAT_Handle *`
329 do_connect (void *cls)
331 struct GNUNET_NAT_Handle *nh = cls;
332 struct GNUNET_MQ_MessageHandler handlers[] = {
333 GNUNET_MQ_hd_var_size (connection_reversal_request,
334 GNUNET_MESSAGE_TYPE_NAT_CONNECTION_REVERSAL_REQUESTED,
335 struct GNUNET_NAT_ConnectionReversalRequestedMessage,
337 GNUNET_MQ_hd_var_size (address_change_notification,
338 GNUNET_MESSAGE_TYPE_NAT_ADDRESS_CHANGE,
339 struct GNUNET_NAT_AddressChangeNotificationMessage,
341 GNUNET_MQ_handler_end ()
343 struct GNUNET_MQ_Envelope *env;
345 nh->reconnect_task = NULL;
346 nh->mq = GNUNET_CLIENT_connecT (nh->cfg,
356 env = GNUNET_MQ_msg_copy (nh->reg);
357 GNUNET_MQ_send (nh->mq,
363 * Attempt to enable port redirection and detect public IP address
364 * contacting UPnP or NAT-PMP routers on the local network. Use @a
365 * addr to specify to which of the local host's addresses should the
366 * external port be mapped. The port is taken from the corresponding
367 * sockaddr_in[6] field. The NAT module should call the given @a
368 * address_callback for any 'plausible' external address.
370 * @param cfg configuration to use
371 * @param proto protocol this is about, IPPROTO_TCP or IPPROTO_UDP
372 * @param adv_port advertised port (port we are either bound to or that our OS
373 * locally performs redirection from to our bound port).
374 * @param num_addrs number of addresses in @a addrs
375 * @param addrs list of local addresses packets should be redirected to
376 * @param addrlens actual lengths of the addresses in @a addrs
377 * @param address_callback function to call everytime the public IP address changes
378 * @param reversal_callback function to call if someone wants connection reversal from us,
379 * NULL if connection reversal is not supported
380 * @param callback_cls closure for callbacks
381 * @return NULL on error, otherwise handle that can be used to unregister
383 struct GNUNET_NAT_Handle *
384 GNUNET_NAT_register (const struct GNUNET_CONFIGURATION_Handle *cfg,
387 unsigned int num_addrs,
388 const struct sockaddr **addrs,
389 const socklen_t *addrlens,
390 GNUNET_NAT_AddressCallback address_callback,
391 GNUNET_NAT_ReversalCallback reversal_callback,
394 struct GNUNET_NAT_Handle *nh;
395 struct GNUNET_NAT_RegisterMessage *rm;
400 for (unsigned int i=0;i<num_addrs;i++)
402 if ( (len > GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (*rm)) ||
403 (num_addrs > UINT16_MAX) )
408 rm = GNUNET_malloc (sizeof (*rm) + len);
409 rm->header.size = htons (sizeof (*rm) + len);
410 rm->header.type = htons (GNUNET_MESSAGE_TYPE_NAT_REGISTER);
411 rm->flags = GNUNET_NAT_RF_NONE;
412 if (NULL != address_callback)
413 rm->flags |= GNUNET_NAT_RF_ADDRESSES;
414 if (NULL != reversal_callback)
415 rm->flags |= GNUNET_NAT_RF_REVERSAL;
417 rm->adv_port = htons (adv_port);
418 rm->num_addrs = htons ((uint16_t) num_addrs);
419 off = (char *) &rm[1];
420 for (unsigned int i=0;i<num_addrs;i++)
422 switch (addrs[i]->sa_family)
425 if (sizeof (struct sockaddr_in) != addrlens[i])
432 if (sizeof (struct sockaddr_in6) != addrlens[i])
440 if (sizeof (struct sockaddr_un) != addrlens[i])
457 nh = GNUNET_new (struct GNUNET_NAT_Handle);
458 nh->reg = &rm->header;
460 nh->address_callback = address_callback;
461 nh->reversal_callback = reversal_callback;
462 nh->callback_cls = callback_cls;
469 * Check if an incoming message is a STUN message.
471 * @param data the packet
472 * @param len the length of the packet in @a data
473 * @return #GNUNET_YES if @a data is a STUN packet,
474 * #GNUNET_NO if the packet is invalid (not a stun packet)
477 test_stun_packet (const void *data,
480 const struct stun_header *hdr;
481 const struct stun_attr *attr;
482 uint32_t advertised_message_size;
483 uint32_t message_magic_cookie;
485 /* On entry, 'len' is the length of the UDP payload. After the
486 * initial checks it becomes the size of unprocessed options,
487 * while 'data' is advanced accordingly.
489 if (len < sizeof(struct stun_header))
491 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
492 "STUN packet too short (only %d, wanting at least %d)\n",
494 (int) sizeof (struct stun_header));
497 hdr = (const struct stun_header *) data;
498 /* Skip header as it is already in hdr */
499 len -= sizeof (struct stun_header);
500 data += sizeof (struct stun_header);
502 /* len as advertised in the message */
503 advertised_message_size = ntohs (hdr->msglen);
505 message_magic_cookie = ntohl (hdr->magic);
506 /* Compare if the cookie match */
507 if (STUN_MAGIC_COOKIE != message_magic_cookie)
509 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
510 "Invalid magic cookie for STUN\n");
514 if (advertised_message_size > len)
516 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
517 "Scrambled STUN packet length (got %d, expecting %d)\n",
518 advertised_message_size,
522 len = advertised_message_size;
525 if (len < sizeof (struct stun_attr))
527 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
528 "Attribute too short in STUN packet (got %d, expecting %d)\n",
530 (int) sizeof(struct stun_attr));
533 attr = (const struct stun_attr *) data;
535 /* compute total attribute length */
536 advertised_message_size = ntohs (attr->len) + sizeof(struct stun_attr);
538 /* Check if we still have space in our buffer */
539 if (advertised_message_size > len)
541 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
542 "Inconsistent Attribute (length %d exceeds remaining msg len %d)\n",
543 advertised_message_size,
547 data += advertised_message_size;
548 len -= advertised_message_size;
550 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
551 "STUN Packet, msg %04x, length: %d\n",
552 ntohs (hdr->msgtype),
553 advertised_message_size);
559 * Handle an incoming STUN message. This function is useful as
560 * some GNUnet service may be listening on a UDP port and might
561 * thus receive STUN messages while trying to receive other data.
562 * In this case, this function can be used to process replies
565 * The function does some basic sanity checks on packet size and
566 * content, try to extract a bit of information.
568 * At the moment this only processes BIND requests, and returns the
569 * externally visible address of the request to the rest of the
572 * @param nh handle to the NAT service
573 * @param sender_addr address from which we got @a data
574 * @param sender_addr_len number of bytes in @a sender_addr
575 * @param data the packet
576 * @param data_size number of bytes in @a data
577 * @return #GNUNET_OK on success
578 * #GNUNET_NO if the packet is not a STUN packet
579 * #GNUNET_SYSERR on internal error handling the packet
582 GNUNET_NAT_stun_handle_packet (struct GNUNET_NAT_Handle *nh,
583 const struct sockaddr *sender_addr,
584 size_t sender_addr_len,
588 struct GNUNET_MQ_Envelope *env;
589 struct GNUNET_NAT_HandleStunMessage *hsn;
593 test_stun_packet (data,
597 return GNUNET_SYSERR;
598 env = GNUNET_MQ_msg_extra (hsn,
599 data_size + sender_addr_len,
600 GNUNET_MESSAGE_TYPE_NAT_HANDLE_STUN);
601 hsn->sender_addr_size = htons ((uint16_t) sender_addr_len);
602 hsn->payload_size = htons ((uint16_t) data_size);
603 buf = (char *) &hsn[1];
607 buf += sender_addr_len;
611 GNUNET_MQ_send (nh->mq,
618 * Test if the given address is (currently) a plausible IP address for
619 * this peer. Mostly a convenience function so that clients do not
620 * have to explicitly track all IPs that the #GNUNET_NAT_AddressCallback
621 * has returned so far.
623 * @param nh the handle returned by register
624 * @param addr IP address to test (IPv4 or IPv6)
625 * @param addrlen number of bytes in @a addr
626 * @return #GNUNET_YES if the address is plausible,
627 * #GNUNET_NO if the address is not plausible,
628 * #GNUNET_SYSERR if the address is malformed
631 GNUNET_NAT_test_address (struct GNUNET_NAT_Handle *nh,
635 struct AddrEntry *ae;
637 if ( (addrlen != sizeof (struct sockaddr_in)) &&
638 (addrlen != sizeof (struct sockaddr_in6)) )
641 return GNUNET_SYSERR;
643 for (ae = nh->ae_head; NULL != ae; ae = ae->next)
644 if ( (addrlen == ae->addrlen) &&
654 * We learned about a peer (possibly behind NAT) so run the
655 * gnunet-nat-client to send dummy ICMP responses to cause
656 * that peer to connect to us (connection reversal).
658 * @param nh handle (used for configuration)
659 * @param local_sa our local address of the peer (IPv4-only)
660 * @param remote_sa the remote address of the peer (IPv4-only)
661 * @return #GNUNET_SYSERR on error,
662 * #GNUNET_NO if connection reversal is unavailable,
663 * #GNUNET_OK otherwise (presumably in progress)
666 GNUNET_NAT_request_reversal (struct GNUNET_NAT_Handle *nh,
667 const struct sockaddr_in *local_sa,
668 const struct sockaddr_in *remote_sa)
670 struct GNUNET_MQ_Envelope *env;
671 struct GNUNET_NAT_RequestConnectionReversalMessage *req;
675 return GNUNET_SYSERR;
676 env = GNUNET_MQ_msg_extra (req,
677 2 * sizeof (struct sockaddr_in),
678 GNUNET_MESSAGE_TYPE_NAT_REQUEST_CONNECTION_REVERSAL);
679 req->local_addr_size = htons (sizeof (struct sockaddr_in));
680 req->remote_addr_size = htons (sizeof (struct sockaddr_in));
681 buf = (char *) &req[1];
684 sizeof (struct sockaddr_in));
685 buf += sizeof (struct sockaddr_in);
688 sizeof (struct sockaddr_in));
689 GNUNET_MQ_send (nh->mq,
696 * Stop port redirection and public IP address detection for the given
697 * handle. This frees the handle, after having sent the needed
698 * commands to close open ports.
700 * @param nh the handle to stop
703 GNUNET_NAT_unregister (struct GNUNET_NAT_Handle *nh)
705 GNUNET_MQ_destroy (nh->mq);
706 GNUNET_free (nh->reg);
713 * Handle to auto-configuration in progress.
715 struct GNUNET_NAT_AutoHandle
719 * Configuration we use.
721 const struct GNUNET_CONFIGURATION_Handle *cfg;
724 * Message queue for communicating with the NAT service.
726 struct GNUNET_MQ_Handle *mq;
729 * Function called with the result from the autoconfiguration.
731 GNUNET_NAT_AutoResultCallback arc;
734 * Closure for @e arc.
742 * Converts `enum GNUNET_NAT_StatusCode` to string
744 * @param err error code to resolve to a string
745 * @return point to a static string containing the error code
748 GNUNET_NAT_status2string (enum GNUNET_NAT_StatusCode err)
752 case GNUNET_NAT_ERROR_SUCCESS:
753 return _ ("Operation Successful");
754 case GNUNET_NAT_ERROR_IPC_FAILURE:
755 return _ ("IPC failure");
756 case GNUNET_NAT_ERROR_INTERNAL_NETWORK_ERROR:
757 return _ ("Failure in network subsystem, check permissions.");
758 case GNUNET_NAT_ERROR_TIMEOUT:
759 return _ ("Encountered timeout while performing operation");
760 case GNUNET_NAT_ERROR_NOT_ONLINE:
761 return _ ("detected that we are offline");
762 case GNUNET_NAT_ERROR_UPNPC_NOT_FOUND:
763 return _ ("`upnpc` command not found");
764 case GNUNET_NAT_ERROR_UPNPC_FAILED:
765 return _ ("Failed to run `upnpc` command");
766 case GNUNET_NAT_ERROR_UPNPC_TIMEOUT:
767 return _ ("`upnpc' command took too long, process killed");
768 case GNUNET_NAT_ERROR_UPNPC_PORTMAP_FAILED:
769 return _ ("`upnpc' command failed to establish port mapping");
770 case GNUNET_NAT_ERROR_EXTERNAL_IP_UTILITY_NOT_FOUND:
771 return _ ("`external-ip' command not found");
772 case GNUNET_NAT_ERROR_EXTERNAL_IP_UTILITY_FAILED:
773 return _ ("Failed to run `external-ip` command");
774 case GNUNET_NAT_ERROR_EXTERNAL_IP_UTILITY_OUTPUT_INVALID:
775 return _ ("`external-ip' command output invalid");
776 case GNUNET_NAT_ERROR_EXTERNAL_IP_ADDRESS_INVALID:
777 return _ ("no valid address was returned by `external-ip'");
778 case GNUNET_NAT_ERROR_NO_VALID_IF_IP_COMBO:
779 return _ ("Could not determine interface with internal/local network address");
780 case GNUNET_NAT_ERROR_HELPER_NAT_SERVER_NOT_FOUND:
781 return _ ("No functioning gnunet-helper-nat-server installation found");
782 case GNUNET_NAT_ERROR_NAT_TEST_START_FAILED:
783 return _ ("NAT test could not be initialized");
784 case GNUNET_NAT_ERROR_NAT_TEST_TIMEOUT:
785 return _ ("NAT test timeout reached");
786 case GNUNET_NAT_ERROR_NAT_REGISTER_FAILED:
787 return _ ("could not register NAT");
788 case GNUNET_NAT_ERROR_HELPER_NAT_CLIENT_NOT_FOUND:
789 return _ ("No working gnunet-helper-nat-client installation found");
791 return "unknown status code";
797 * Check result from autoconfiguration attempt.
799 * @param cls the `struct GNUNET_NAT_AutoHandle`
800 * @param res the result
801 * @return #GNUNET_OK if @a res is well-formed (always for now)
804 check_auto_result (void *cls,
805 const struct GNUNET_NAT_AutoconfigResultMessage *res)
812 * Handle result from autoconfiguration attempt.
814 * @param cls the `struct GNUNET_NAT_AutoHandle`
815 * @param res the result
818 handle_auto_result (void *cls,
819 const struct GNUNET_NAT_AutoconfigResultMessage *res)
821 struct GNUNET_NAT_AutoHandle *ah = cls;
823 struct GNUNET_CONFIGURATION_Handle *cfg;
824 enum GNUNET_NAT_Type type
825 = (enum GNUNET_NAT_Type) ntohl (res->type);
826 enum GNUNET_NAT_StatusCode status
827 = (enum GNUNET_NAT_StatusCode) ntohl (res->status_code);
829 left = ntohs (res->header.size) - sizeof (*res);
830 cfg = GNUNET_CONFIGURATION_create ();
832 GNUNET_CONFIGURATION_deserialize (cfg,
833 (const char *) &res[1],
838 ah->arc (ah->arc_cls,
840 GNUNET_NAT_ERROR_IPC_FAILURE,
845 ah->arc (ah->arc_cls,
850 GNUNET_CONFIGURATION_destroy (cfg);
851 GNUNET_NAT_autoconfig_cancel (ah);
856 * Handle queue errors by reporting autoconfiguration failure.
858 * @param cls the `struct GNUNET_NAT_AutoHandle *`
859 * @param error details about the error
862 ah_error_handler (void *cls,
863 enum GNUNET_MQ_Error error)
865 struct GNUNET_NAT_AutoHandle *ah = cls;
867 ah->arc (ah->arc_cls,
869 GNUNET_NAT_ERROR_IPC_FAILURE,
870 GNUNET_NAT_TYPE_UNKNOWN);
871 GNUNET_NAT_autoconfig_cancel (ah);
876 * Start auto-configuration routine. The transport adapters should
877 * be stopped while this function is called.
879 * @param cfg initial configuration
880 * @param cb function to call with autoconfiguration result
881 * @param cb_cls closure for @a cb
882 * @return handle to cancel operation
884 struct GNUNET_NAT_AutoHandle *
885 GNUNET_NAT_autoconfig_start (const struct GNUNET_CONFIGURATION_Handle *cfg,
886 GNUNET_NAT_AutoResultCallback cb,
889 struct GNUNET_NAT_AutoHandle *ah = GNUNET_new (struct GNUNET_NAT_AutoHandle);
890 struct GNUNET_MQ_MessageHandler handlers[] = {
891 GNUNET_MQ_hd_var_size (auto_result,
892 GNUNET_MESSAGE_TYPE_NAT_AUTO_CFG_RESULT,
893 struct GNUNET_NAT_AutoconfigResultMessage,
895 GNUNET_MQ_handler_end ()
897 struct GNUNET_MQ_Envelope *env;
898 struct GNUNET_NAT_AutoconfigRequestMessage *req;
902 buf = GNUNET_CONFIGURATION_serialize (cfg,
904 if (size > GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (*req))
912 ah->arc_cls = cb_cls;
913 ah->mq = GNUNET_CLIENT_connecT (cfg,
925 env = GNUNET_MQ_msg_extra (req,
927 GNUNET_MESSAGE_TYPE_NAT_REQUEST_AUTO_CFG);
928 GNUNET_memcpy (&req[1],
932 GNUNET_MQ_send (ah->mq,
939 * Abort autoconfiguration.
941 * @param ah handle for operation to abort
944 GNUNET_NAT_autoconfig_cancel (struct GNUNET_NAT_AutoHandle *ah)
946 GNUNET_MQ_destroy (ah->mq);
950 /* end of nat_api.c */