still not really working... sending and receiving of messages a bit hinky
[oweals/gnunet.git] / src / transport / plugin_transport_udp.c
index c84b2bae7679b5439cd8fa3f32e1b941ac43972d..3df492a913213adc196b96a62acf12b3bf343224 100644 (file)
@@ -1,6 +1,6 @@
 /*
      This file is part of GNUnet
-     (C) 2001, 2002, 2003, 2004, 2005, 2008 Christian Grothoff (and other contributing authors)
+     (C) 2010 Christian Grothoff (and other contributing authors)
 
      GNUnet is free software; you can redistribute it and/or modify
      it under the terms of the GNU General Public License as published
 */
 
 /**
- * @file transports/udp.c
+ * @file transport/plugin_transport_udp.c
  * @brief Implementation of the UDP transport service
  * @author Christian Grothoff
+ * @author Nathan Evans
  */
 
 #include "platform.h"
-#include "gnunet_util.h"
+#include "gnunet_hello_lib.h"
+#include "gnunet_connection_lib.h"
+#include "gnunet_os_lib.h"
+#include "gnunet_peerinfo_service.h"
 #include "gnunet_protocols.h"
-#include "gnunet_transport.h"
-#include "gnunet_stats_service.h"
-#include "gnunet_upnp_service.h"
-#include "ip.h"
+#include "gnunet_resolver_service.h"
+#include "gnunet_server_lib.h"
+#include "gnunet_service_lib.h"
+#include "gnunet_signatures.h"
+#include "gnunet_statistics_service.h"
+#include "gnunet_transport_service.h"
+#include "plugin_transport.h"
+#include "transport.h"
 
 #define DEBUG_UDP GNUNET_YES
 
+/*
+ * Transport cost to peer, always 1 for UDP (direct connection)
+ */
+#define UDP_DIRECT_DISTANCE 1
+
 /**
- * The default maximum size of each outbound UDP message,
- * optimal value for Ethernet (10 or 100 MBit).
+ * Handle for request of hostname resolution, non-NULL if pending.
  */
-#define MESSAGE_SIZE 1472
+static struct GNUNET_RESOLVER_RequestHandle *hostname_dns;
+
+/**
+ * How long until we give up on transmitting the welcome message?
+ */
+#define HOSTNAME_RESOLVE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
+
 
 /**
  * Message-Packet header.
  */
-typedef struct
+struct UDPMessage
 {
   /**
    * size of the message, in bytes, including this header.
    */
-  GNUNET_MessageHeader header;
+  struct GNUNET_MessageHeader header;
 
   /**
    * What is the identity of the sender (GNUNET_hash of public key)
    */
-  GNUNET_PeerIdentity sender;
+  struct GNUNET_PeerIdentity sender;
 
-} UDPMessage;
+};
 
-#define MY_TRANSPORT_NAME "UDP"
-#include "common.c"
-
-/* *********** globals ************* */
+/* Forward definition */
+struct Plugin;
 
-static int stat_bytesReceived;
+struct PrettyPrinterContext
+{
+  GNUNET_TRANSPORT_AddressStringCallback asc;
+  void *asc_cls;
+  uint16_t port;
+};
 
-static int stat_bytesSent;
+/**
+ * Encapsulation of all of the state of the plugin.
+ */
+struct Plugin
+{
+  /**
+   * Our environment.
+   */
+  struct GNUNET_TRANSPORT_PluginEnvironment *env;
 
-static int stat_bytesDropped;
+  /**
+   * Handle for the statistics service.
+   */
+  struct GNUNET_STATISTICS_Handle *statistics;
 
-static int stat_udpConnected;
+  /**
+   * Handle to the network service.
+   */
+  struct GNUNET_SERVICE_Context *service;
 
-/**
- * thread that listens for inbound messages
- */
-static struct GNUNET_SelectHandle *selector;
+  /**
+   * Handle for request of hostname resolution, non-NULL if pending.
  */
+  struct GNUNET_RESOLVER_RequestHandle *hostname_dns;
 
-/**
- * the socket that we transmit all data with
- */
-static struct GNUNET_SocketHandle *udp_sock;
+  /**
+   * ID of task used to update our addresses when one expires.
  */
+  GNUNET_SCHEDULER_TaskIdentifier address_update_task;
 
-static struct GNUNET_LoadMonitor *load_monitor;
+  /**
+   * ID of select task
+   */
+  GNUNET_SCHEDULER_TaskIdentifier select_task;
 
+  /**
+   * Port that we are actually listening on.
+   */
+  uint16_t open_port;
 
-/**
- * The socket of session has data waiting, process!
- *
- * This function may only be called if the tcplock is
- * already held by the caller.
- */
-static int
-select_message_handler (void *mh_cls,
-                        struct GNUNET_SelectHandle *sh,
-                        struct GNUNET_SocketHandle *sock,
-                        void *sock_ctx, const GNUNET_MessageHeader * msg)
-{
-  unsigned int len;
-  GNUNET_TransportPacket *mp;
-  const UDPMessage *um;
+  /**
+   * Port that the user said we would have visible to the
+   * rest of the world.
+   */
+  uint16_t adv_port;
 
-  len = ntohs (msg->size);
-  if (len <= sizeof (UDPMessage))
-    {
-      GNUNET_GE_LOG (coreAPI->ectx,
-                     GNUNET_GE_WARNING | GNUNET_GE_USER | GNUNET_GE_BULK,
-                     _("Received malformed message via %s. Ignored.\n"),
-                     "UDP");
-      return GNUNET_SYSERR;
-    }
-  um = (const UDPMessage *) msg;
-  mp = GNUNET_malloc (sizeof (GNUNET_TransportPacket));
-  mp->msg = GNUNET_malloc (len - sizeof (UDPMessage));
-  memcpy (mp->msg, &um[1], len - sizeof (UDPMessage));
-  mp->sender = um->sender;
-  mp->size = len - sizeof (UDPMessage);
-  mp->tsession = NULL;
-  coreAPI->receive (mp);
-  if (stats != NULL)
-    stats->change (stat_bytesReceived, len);
-  return GNUNET_OK;
-}
+  /*
+   * FD Read set
+   */
+  struct GNUNET_NETWORK_FDSet *rs;
 
-static void *
-select_accept_handler (void *ah_cls,
-                       struct GNUNET_SelectHandle *sh,
-                       struct GNUNET_SocketHandle *sock,
-                       const void *addr, unsigned int addr_len)
-{
-  static int nonnullpointer;
+};
 
-  if (GNUNET_NO != is_rejected_tester (addr, addr_len))
-    return NULL;
-  return &nonnullpointer;
-}
+/* *********** globals ************* */
 
 /**
- * Select has been forced to close a connection.
- * Free the associated context.
+ * the socket that we transmit all data with
  */
-static void
-select_close_handler (void *ch_cls,
-                      struct GNUNET_SelectHandle *sh,
-                      struct GNUNET_SocketHandle *sock, void *sock_ctx)
-{
-  /* do nothing */
-}
+static struct GNUNET_NETWORK_Handle *udp_sock;
 
 /**
- * Establish a connection to a remote node.
+ * Disconnect from a remote node.
  *
- * @param hello the hello-Message for the target node
- * @param tsessionPtr the session handle that is to be set
+ * @param tsession the session that is closed
  * @return GNUNET_OK on success, GNUNET_SYSERR if the operation failed
  */
-static int
-udp_connect (const GNUNET_MessageHello * hello,
-             GNUNET_TSession ** tsessionPtr, int may_reuse)
+void
+udp_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
 {
-  GNUNET_TSession *tsession;
-
-  tsession = GNUNET_malloc (sizeof (GNUNET_TSession));
-  memset (tsession, 0, sizeof (GNUNET_TSession));
-  tsession->internal = GNUNET_malloc (GNUNET_sizeof_hello (hello));
-  memcpy (tsession->internal, hello, GNUNET_sizeof_hello (hello));
-  tsession->ttype = myAPI.protocol_number;
-  tsession->peer = hello->senderIdentity;
-  *tsessionPtr = tsession;
-  if (stats != NULL)
-    stats->change (stat_udpConnected, 1);
-  return GNUNET_OK;
+  return;
 }
 
 /**
- * A (core) Session is to be associated with a transport session. The
- * transport service may want to know in order to call back on the
- * core if the connection is being closed.
- *
- * @param tsession the session handle passed along
- *   from the call to receive that was made by the transport
- *   layer
- * @return GNUNET_OK if the session could be associated,
- *         GNUNET_SYSERR if not.
+ * Shutdown the server process (stop receiving inbound traffic). Maybe
+ * restarted later!
  */
-int
-udp_associate (GNUNET_TSession * tsession)
+static int
+udp_transport_server_stop (void *cls)
 {
-  return GNUNET_SYSERR;         /* UDP connections can never be associated */
+  struct Plugin *plugin = cls;
+  GNUNET_assert (udp_sock != NULL);
+  if (plugin->select_task != GNUNET_SCHEDULER_NO_TASK)
+    {
+      GNUNET_SCHEDULER_cancel (plugin->env->sched, plugin->select_task);
+      plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
+    }
+
+  GNUNET_NETWORK_socket_close (udp_sock);
+  udp_sock = NULL;
+  return GNUNET_OK;
 }
 
 /**
- * Disconnect from a remote node.
+ * Function that can be used by the transport service to transmit
+ * a message using the plugin.
  *
- * @param tsession the session that is closed
- * @return GNUNET_OK on success, GNUNET_SYSERR if the operation failed
+ * @param cls closure
+ * @param target who should receive this message (ignored by UDP)
+ * @param msgbuf one or more GNUNET_MessageHeader(s) strung together
+ * @param msgbufsize the size of the msgbuf to send
+ * @param priority how important is the message (ignored by UDP)
+ * @param timeout when should we time out (give up) if we can not transmit?
+ * @param addr the addr to send the message to, needs to be a sockaddr for us
+ * @param addrlen the len of addr
+ * @param force_address not used, we had better have an address to send to
+ *        because we are stateless!!
+ * @param cont continuation to call once the message has
+ *        been transmitted (or if the transport is ready
+ *        for the next transmission call; or if the
+ *        peer disconnected...)
+ * @param cont_cls closure for cont
+ *
+ * @return the number of bytes written
  */
-static int
-udp_disconnect (GNUNET_TSession * tsession)
+
+static ssize_t
+udp_plugin_send (void *cls,
+                 const struct GNUNET_PeerIdentity *target,
+                 char *msgbuf,
+                 size_t msgbuf_size,
+                 unsigned int priority,
+                 struct GNUNET_TIME_Relative timeout,
+                 const void *addr,
+                 size_t addrlen,
+                 int force_address,
+                 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
 {
-  if (tsession != NULL)
+  struct Plugin *plugin = cls;
+  struct UDPMessage *message;
+  int ssize;
+  ssize_t sent;
+
+  GNUNET_assert(udp_sock != NULL);
+
+  if ((addr == NULL) || (addrlen == 0))
     {
-      if (tsession->internal != NULL)
-        GNUNET_free (tsession->internal);
-      GNUNET_free (tsession);
-      if (stats != NULL)
-        stats->change (stat_udpConnected, -1);
+#if DEBUG_UDP
+  GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "udp", _
+                   ("udp_plugin_send called without address, returning!\n"));
+#endif
+      cont (cont_cls, target, GNUNET_OK);
+      return 0; /* Can never send if we don't have an address!! */
     }
-  return GNUNET_OK;
+
+  /* Build the message to be sent */
+  message = GNUNET_malloc (sizeof (struct UDPMessage) + msgbuf_size);
+  ssize = sizeof (struct UDPMessage) + msgbuf_size;
+
+#if DEBUG_UDP
+  GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "udp", _
+                   ("In udp_send, ssize is %d, sending message to %s\n"), ssize, GNUNET_a2s((const struct sockaddr *)addr, addrlen));
+#endif
+  message->header.size = htons (ssize);
+  message->header.type = htons (0);
+  memcpy (&message->sender, plugin->env->my_identity,
+          sizeof (struct GNUNET_PeerIdentity));
+  memcpy (&message[1], msgbuf, msgbuf_size);
+
+  /* Actually send the message */
+  sent =
+    GNUNET_NETWORK_socket_sendto (udp_sock, message, ssize,
+                                  addr,
+                                  addrlen);
+
+  if (cont != NULL)
+    {
+      if (sent == GNUNET_SYSERR)
+        cont (cont_cls, target, GNUNET_SYSERR);
+      else
+        {
+#if DEBUG_UDP
+  GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "udp", _
+                   ("Sucessfully sent message, calling transmit continuation!\n"));
+#endif
+          cont (cont_cls, target, GNUNET_OK);
+        }
+    }
+  GNUNET_free (message);
+  return sent;
 }
 
+
 /**
- * Shutdown the server process (stop receiving inbound traffic). Maybe
- * restarted later!
+ * Add the IP of our network interface to the list of
+ * our external IP addresses.
  */
 static int
-udp_transport_server_stop ()
+process_interfaces (void *cls,
+                    const char *name,
+                    int isDefault,
+                    const struct sockaddr *addr, socklen_t addrlen)
 {
-  GNUNET_GE_ASSERT (coreAPI->ectx, udp_sock != NULL);
-  if (selector != NULL)
+  struct Plugin *plugin = cls;
+  int af;
+  struct sockaddr_in *v4;
+  struct sockaddr_in6 *v6;
+
+  af = addr->sa_family;
+  if (af == AF_INET)
     {
-      GNUNET_select_destroy (selector);
-      selector = NULL;
+      v4 = (struct sockaddr_in *) addr;
+      v4->sin_port = htons (plugin->adv_port);
     }
-  GNUNET_socket_destroy (udp_sock);
-  udp_sock = NULL;
+  else
+    {
+      GNUNET_assert (af == AF_INET6);
+      v6 = (struct sockaddr_in6 *) addr;
+      v6->sin6_port = htons (plugin->adv_port);
+    }
+  GNUNET_log_from (GNUNET_ERROR_TYPE_INFO |
+                   GNUNET_ERROR_TYPE_BULK,
+                   "udp", _("Found address `%s' (%s)\n"),
+                   GNUNET_a2s (addr, addrlen), name);
+  plugin->env->notify_address (plugin->env->cls,
+                               "udp",
+                               addr, addrlen, GNUNET_TIME_UNIT_FOREVER_REL);
+
   return GNUNET_OK;
 }
 
+
 /**
- * Test if the transport would even try to send
- * a message of the given size and importance
- * for the given session.<br>
- * This function is used to check if the core should
- * even bother to construct (and encrypt) this kind
- * of message.
+ * Function called by the resolver for each address obtained from DNS
+ * for our own hostname.  Add the addresses to the list of our
+ * external IP addresses.
  *
- * @return GNUNET_YES if the transport would try (i.e. queue
- *         the message or call the OS to send),
- *         GNUNET_NO if the transport would just drop the message,
- *         GNUNET_SYSERR if the size/session is invalid
+ * @param cls closure
+ * @param addr one of the addresses of the host, NULL for the last address
+ * @param addrlen length of the address
  */
-static int
-udp_test_would_try (GNUNET_TSession * tsession, unsigned int size,
-                    int important)
+static void
+process_hostname_ips (void *cls,
+                      const struct sockaddr *addr, socklen_t addrlen)
 {
-  const GNUNET_MessageHello *hello;
+  struct Plugin *plugin = cls;
 
-  if (udp_sock == NULL)
-    return GNUNET_SYSERR;
-  if (size == 0)
+  if (addr == NULL)
     {
-      GNUNET_GE_BREAK (coreAPI->ectx, 0);
-      return GNUNET_SYSERR;
+      plugin->hostname_dns = NULL;
+      return;
     }
-  if (size > myAPI.mtu)
+  process_interfaces (plugin, "<hostname>", GNUNET_YES, addr, addrlen);
+}
+
+
+/*
+ * @param cls the plugin handle
+ * @param tc the scheduling context (for rescheduling this function again)
+ *
+ * We have been notified that our writeset has something to read.  Presumably
+ * select has been called already, so we can go ahead and start reading from
+ * the socket immediately.  Then we check if there is more to be read by
+ * calling select ourselves while there is stuff on the wire.  Then reschedule
+ * this function to be called again once more is available.
+ *
+ */
+static void
+udp_plugin_select (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
+{
+  struct Plugin *plugin = cls;
+  struct GNUNET_TIME_Relative timeout =
+    GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 500);
+  char *buf;
+  struct UDPMessage *msg;
+  const struct GNUNET_MessageHeader *hdr;
+  struct GNUNET_PeerIdentity *sender;
+  unsigned int buflen;
+  socklen_t fromlen;
+  struct sockaddr_storage addr;
+  ssize_t ret;
+  int offset;
+  int count;
+  int tsize;
+  char *msgbuf;
+  const struct GNUNET_MessageHeader *currhdr;
+
+  do
     {
-      GNUNET_GE_BREAK (coreAPI->ectx, 0);
-      return GNUNET_SYSERR;
+      buflen = GNUNET_NETWORK_socket_recvfrom_amount (udp_sock);
+
+#if DEBUG_UDP
+      GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "udp", _
+                       ("we expect to read %u bytes\n"), buflen);
+#endif
+
+      if (buflen == GNUNET_NO)
+        return;
+
+      buf = GNUNET_malloc (buflen);
+      fromlen = sizeof (addr);
+
+      memset (&addr, 0, fromlen);
+      ret =
+        GNUNET_NETWORK_socket_recvfrom (udp_sock, buf, buflen,
+                                        (struct sockaddr *) &addr, &fromlen);
+
+#if DEBUG_UDP
+      GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "udp", _
+                       ("socket_recv returned %u, src_addr_len is %u\n"), ret,
+                       fromlen);
+#endif
+
+      if (ret <= 0)
+        {
+          GNUNET_free (buf);
+          return;
+        }
+      msg = (struct UDPMessage *) buf;
+
+#if DEBUG_UDP
+      GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "udp", _
+                       ("header reports message size of %d\n"),
+                       ntohs (msg->header.size));
+
+      GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "udp", _
+                       ("header reports message type of %d\n"),
+                       ntohs (msg->header.type));
+#endif
+      if (ntohs (msg->header.size) < sizeof (struct UDPMessage))
+        {
+          GNUNET_free (buf);
+          GNUNET_NETWORK_fdset_zero (plugin->rs);
+          GNUNET_NETWORK_fdset_set (plugin->rs, udp_sock);
+          break;
+        }
+      hdr = (const struct GNUNET_MessageHeader *) &msg[1];
+      msgbuf = (char *)&msg[1];
+      sender = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity));
+      memcpy (sender, &msg->sender, sizeof (struct GNUNET_PeerIdentity));
+
+      offset = 0;
+      count = 0;
+      tsize = ntohs (msg->header.size) - sizeof(struct UDPMessage);
+      while (offset < tsize)
+        {
+          currhdr = (struct GNUNET_MessageHeader *)&msgbuf[offset];
+#if DEBUG_UDP
+      GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "udp", _
+                       ("processing msg %d: type %d, size %d at offset %d\n"),
+                       count, ntohs(currhdr->type), ntohs(currhdr->size), offset);
+#endif
+          plugin->env->receive (plugin->env->cls,
+              sender, currhdr, UDP_DIRECT_DISTANCE, (char *)&addr, fromlen);
+          offset += ntohs(currhdr->size);
+#if DEBUG_UDP
+      GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "udp", _
+                       ("offset now %d, tsize %d\n"),
+                       offset, tsize);
+#endif
+          count++;
+        }
+
+      GNUNET_free (sender);
+      GNUNET_free (buf);
+
     }
-  hello = (const GNUNET_MessageHello *) tsession->internal;
-  if (hello == NULL)
-    return GNUNET_SYSERR;
-  return GNUNET_YES;
+  while (GNUNET_NETWORK_socket_select (plugin->rs,
+                                       NULL,
+                                       NULL,
+                                       timeout) > 0
+         && GNUNET_NETWORK_fdset_isset (plugin->rs, udp_sock));
+
+  plugin->select_task =
+    GNUNET_SCHEDULER_add_select (plugin->env->sched,
+                                 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
+                                 GNUNET_SCHEDULER_NO_TASK,
+                                 GNUNET_TIME_UNIT_FOREVER_REL, plugin->rs,
+                                 NULL, &udp_plugin_select, plugin);
+
 }
 
 /**
  * Create a UDP socket.  If possible, use IPv6, otherwise
- * try IPv4.  Update available_protocols accordingly.
+ * try IPv4.
  */
-static struct GNUNET_NETWORK_Descriptor *
-udp_create_socket ()
+static struct GNUNET_NETWORK_Handle *
+udp_transport_server_start (void *cls)
 {
-  struct GNUNET_NETWORK_Descriptor *desc;
+  struct Plugin *plugin = cls;
+  struct GNUNET_NETWORK_Handle *desc;
+  struct sockaddr_in serverAddrv4;
+  struct sockaddr_in6 serverAddrv6;
+  struct sockaddr *serverAddr;
+  socklen_t addrlen;
 
-  available_protocols = VERSION_AVAILABLE_NONE;
   desc = NULL;
   if (GNUNET_YES !=
-      GNUNET_GC_get_configuration_value_yesno (cfg, "GNUNETD", "DISABLE-IPV6",
-                                               GNUNET_YES))
+      GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg, "GNUNETD",
+                                            "DISABLE-IPV6"))
     {
-      desc = GNUNET_net_socket (PF_INET6, SOCK_DGRAM, 17);
+      desc = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_DGRAM, 17);
+      if (desc != NULL)
+        {
+          memset (&serverAddrv6, 0, sizeof (serverAddrv6));
+#if HAVE_SOCKADDR_IN_SIN_LEN
+          serverAddrv6.sin6_len = sizeof (serverAddrv6);
+#endif
+          serverAddrv6.sin6_family = AF_INET6;
+          serverAddrv6.sin6_addr = in6addr_any;
+          serverAddrv6.sin6_port = htons (plugin->open_port);
+          addrlen = sizeof (serverAddrv6);
+          serverAddr = (struct sockaddr *) &serverAddrv6;
+        }
     }
   if (NULL == desc)
     {
-      desc = GNUNET_net_socket (PF_INET, SOCK_DGRAM, 17);
+      desc = GNUNET_NETWORK_socket_create (PF_INET, SOCK_DGRAM, 17);
       if (NULL == desc)
         {
-          GNUNET_GE_LOG_STRERROR (coreAPI->ectx,
-                                  GNUNET_GE_ERROR | GNUNET_GE_ADMIN |
-                                  GNUNET_GE_BULK, "socket");
-          return GNUNET_SYSERR;
+          GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "udp", "socket");
+          return NULL;
+        }
+      else
+        {
+          memset (&serverAddrv4, 0, sizeof (serverAddrv4));
+#if HAVE_SOCKADDR_IN_SIN_LEN
+          serverAddrv4.sin_len = sizeof (serverAddrv4);
+#endif
+          serverAddrv4.sin_family = AF_INET;
+          serverAddrv4.sin_addr.s_addr = INADDR_ANY;
+          serverAddrv4.sin_port = htons (plugin->open_port);
+          addrlen = sizeof (serverAddrv4);
+          serverAddr = (struct sockaddr *) &serverAddrv4;
         }
-      available_protocols = VERSION_AVAILABLE_IPV4;
     }
-  else
+
+  if (desc != NULL)
     {
-      available_protocols = VERSION_AVAILABLE_IPV6 | VERSION_AVAILABLE_IPV4;
+      GNUNET_assert (GNUNET_NETWORK_socket_bind (desc, serverAddr, addrlen) ==
+                     GNUNET_OK);
     }
+
+  plugin->rs = GNUNET_NETWORK_fdset_create ();
+
+  GNUNET_NETWORK_fdset_zero (plugin->rs);
+  GNUNET_NETWORK_fdset_set (plugin->rs, desc);
+
+  plugin->select_task =
+    GNUNET_SCHEDULER_add_select (plugin->env->sched,
+                                 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
+                                 GNUNET_SCHEDULER_NO_TASK,
+                                 GNUNET_TIME_UNIT_FOREVER_REL, plugin->rs,
+                                 NULL, &udp_plugin_select, plugin);
+
   return desc;
 }
 
+
+/**
+ * Check if the given port is plausible (must be either
+ * our listen port or our advertised port).  If it is
+ * neither, we return one of these two ports at random.
+ *
+ * @return either in_port or a more plausible port
+ */
+static uint16_t
+check_port (struct Plugin *plugin, uint16_t in_port)
+{
+  if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
+    return in_port;
+  return (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
+                                    2) == 0)
+    ? plugin->open_port : plugin->adv_port;
+}
+
+
 /**
- * Send a message to the specified remote node.
+ * Another peer has suggested an address for this peer and transport
+ * plugin.  Check that this could be a valid address.  This function
+ * is not expected to 'validate' the address in the sense of trying to
+ * connect to it but simply to see if the binary format is technically
+ * legal for establishing a connection.
+ *
+ * @param addr pointer to the address, may be modified (slightly)
+ * @param addrlen length of addr
+ * @return GNUNET_OK if this is a plausible address for this peer
+ *         and transport, GNUNET_SYSERR if not
  *
- * @param tsession the GNUNET_MessageHello identifying the remote node
- * @param message what to send
- * @param size the size of the message
- * @return GNUNET_SYSERR on error, GNUNET_OK on success
+ * TODO: perhaps make everything work with sockaddr_storage, it may
+ *       be a cleaner way to handle addresses in UDP
  */
 static int
-udp_send (GNUNET_TSession * tsession,
-          const void *message, const unsigned int size, int important)
+udp_check_address (void *cls, void *addr, size_t addrlen)
 {
-  const GNUNET_MessageHello *hello;
-  const HostAddress *haddr;
-  UDPMessage *mp;
-  struct sockaddr_in serverAddrv4;
-  struct sockaddr_in6 serverAddrv6;
-  struct sockaddr *serverAddr;
-  socklen_t addrlen;
-  unsigned short available;
-  int ok;
-  int ssize;
-  size_t sent;
+  struct Plugin *plugin = cls;
+  char buf[sizeof (struct sockaddr_in6)];
+
+  struct sockaddr_in *v4;
+  struct sockaddr_in6 *v6;
 
-  GNUNET_GE_ASSERT (NULL, tsession != NULL);
-  if (udp_sock == NULL)
-    return GNUNET_SYSERR;
-  if (size == 0)
+  if ((addrlen != sizeof (struct sockaddr_in)) &&
+      (addrlen != sizeof (struct sockaddr_in6)))
     {
-      GNUNET_GE_BREAK (coreAPI->ectx, 0);
+      GNUNET_break_op (0);
       return GNUNET_SYSERR;
     }
-  if (size > myAPI.mtu)
+  memcpy (buf, addr, sizeof (struct sockaddr_in6));
+  if (addrlen == sizeof (struct sockaddr_in))
     {
-      GNUNET_GE_BREAK (coreAPI->ectx, 0);
-      return GNUNET_SYSERR;
+      v4 = (struct sockaddr_in *) buf;
+      v4->sin_port = htons (check_port (plugin, ntohs (v4->sin_port)));
     }
-  hello = (const GNUNET_MessageHello *) tsession->internal;
-  if (hello == NULL)
-    return GNUNET_SYSERR;
-
-  haddr = (const HostAddress *) &hello[1];
-  available = ntohs (haddr->availability) & available_protocols;
-  if (available == VERSION_AVAILABLE_NONE)
-    return GNUNET_SYSERR;
-  if (available == (VERSION_AVAILABLE_IPV4 | VERSION_AVAILABLE_IPV6))
+  else
     {
-      if (GNUNET_random_u32 (GNUNET_RANDOM_QUALITY_WEAK, 2) == 0)
-        available = VERSION_AVAILABLE_IPV4;
-      else
-        available = VERSION_AVAILABLE_IPV6;
+      v6 = (struct sockaddr_in6 *) buf;
+      v6->sin6_port = htons (check_port (plugin, ntohs (v6->sin6_port)));
     }
-  ssize = size + sizeof (UDPMessage);
-  mp = GNUNET_malloc (ssize);
-  mp->header.size = htons (ssize);
-  mp->header.type = 0;
-  mp->sender = *(coreAPI->my_identity);
-  memcpy (&mp[1], message, size);
-  ok = GNUNET_SYSERR;
-
-  if ((available & VERSION_AVAILABLE_IPV4) > 0)
+#if DEBUG_UDP
+  GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
+                   "tcp",
+                   "Informing transport service about my address `%s'.\n",
+                   GNUNET_a2s (addr, addrlen));
+#endif
+  return GNUNET_OK;
+  return GNUNET_OK;
+}
+
+
+/**
+ * Append our port and forward the result.
+ */
+static void
+append_port (void *cls, const char *hostname)
+{
+  struct PrettyPrinterContext *ppc = cls;
+  char *ret;
+
+  if (hostname == NULL)
     {
-      memset (&serverAddrv4, 0, sizeof (serverAddrv4));
-      serverAddrv4.sin_family = AF_INET;
-      serverAddrv4.sin_port = haddr->port;
-      memcpy (&serverAddrv4.sin_addr, &haddr->ipv4, sizeof (struct in_addr));
-      addrlen = sizeof (serverAddrv4);
-      serverAddr = (struct sockaddr *) &serverAddrv4;
+      ppc->asc (ppc->asc_cls, NULL);
+      GNUNET_free (ppc);
+      return;
     }
-  else
+  GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
+  ppc->asc (ppc->asc_cls, ret);
+  GNUNET_free (ret);
+}
+
+
+/**
+ * Convert the transports address to a nice, human-readable
+ * format.
+ *
+ * @param cls closure
+ * @param type name of the transport that generated the address
+ * @param addr one of the addresses of the host, NULL for the last address
+ *        the specific address format depends on the transport
+ * @param addrlen length of the address
+ * @param numeric should (IP) addresses be displayed in numeric form?
+ * @param timeout after how long should we give up?
+ * @param asc function to call on each string
+ * @param asc_cls closure for asc
+ */
+static void
+udp_plugin_address_pretty_printer (void *cls,
+                                   const char *type,
+                                   const void *addr,
+                                   size_t addrlen,
+                                   int numeric,
+                                   struct GNUNET_TIME_Relative timeout,
+                                   GNUNET_TRANSPORT_AddressStringCallback asc,
+                                   void *asc_cls)
+{
+  struct Plugin *plugin = cls;
+  const struct sockaddr_in *v4;
+  const struct sockaddr_in6 *v6;
+  struct PrettyPrinterContext *ppc;
+
+  if ((addrlen != sizeof (struct sockaddr_in)) &&
+      (addrlen != sizeof (struct sockaddr_in6)))
     {
-      memset (&serverAddrv6, 0, sizeof (serverAddrv6));
-      serverAddrv6.sin6_family = AF_INET;
-      serverAddrv6.sin6_port = haddr->port;
-      memcpy (&serverAddrv6.sin6_addr, &haddr->ipv6,
-              sizeof (struct in6_addr));
-      addrlen = sizeof (serverAddrv6);
-      serverAddr = (struct sockaddr *) &serverAddrv6;
+      /* invalid address */
+      GNUNET_break_op (0);
+      asc (asc_cls, NULL);
+      return;
     }
-#ifndef MINGW
-  if (GNUNET_YES == GNUNET_socket_send_to (udp_sock,
-                                           GNUNET_NC_NONBLOCKING,
-                                           mp,
-                                           ssize, &sent,
-                                           (const char *) serverAddr,
-                                           addrlen))
-#else
-  sent =
-    win_ols_sendto (udp_sock, mp, ssize, (const char *) serverAddr, addrlen);
-  if (sent != SOCKET_ERROR)
-#endif
+  ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
+  ppc->asc = asc;
+  ppc->asc_cls = asc_cls;
+  if (addrlen == sizeof (struct sockaddr_in))
     {
-      ok = GNUNET_OK;
-      if (stats != NULL)
-        stats->change (stat_bytesSent, sent);
+      v4 = (const struct sockaddr_in *) addr;
+      ppc->port = ntohs (v4->sin_port);
     }
   else
     {
-      if (stats != NULL)
-        stats->change (stat_bytesDropped, ssize);
+      v6 = (const struct sockaddr_in6 *) addr;
+      ppc->port = ntohs (v6->sin6_port);
+
     }
-  GNUNET_free (mp);
-  return ok;
+  GNUNET_RESOLVER_hostname_get (plugin->env->sched,
+                                plugin->env->cfg,
+                                addr,
+                                addrlen,
+                                !numeric, timeout, &append_port, ppc);
 }
 
 /**
- * Start the server process to receive inbound traffic.
+ * Set a quota for receiving data from the given peer; this is a
+ * per-transport limit.  This call has no meaning for UDP, as if
+ * we don't receive data it still comes in.  UDP has no friendliness
+ * guarantees, and our buffers will fill at some level.
  *
- * @return GNUNET_OK on success, GNUNET_SYSERR if the operation failed
+ * @param cls closure
+ * @param target the peer for whom the quota is given
+ * @param quota_in quota for receiving/sending data in bytes per ms
  */
-static int
-udp_transport_server_start ()
+static void
+udp_plugin_set_receive_quota (void *cls,
+                              const struct GNUNET_PeerIdentity *target,
+                              uint32_t quota_in)
 {
-  struct sockaddr_in serverAddrv4;
-  struct sockaddr_in6 serverAddrv6;
-  struct sockaddr *serverAddr;
-  socklen_t addrlen;
-  GNUNET_NETWORK_Descriptor *desc;
-  const int on = 1;
-  unsigned short port;
-
-  GNUNET_GE_ASSERT (coreAPI->ectx, selector == NULL);
-  /* initialize UDP network */
-  port = get_port ();
-  if (port != 0)
-    {
-      desc = udp_create_socket ();
-      if (NULL == desc)
-        return GNUNET_SYSERR;
-      if (GNUNET_net_setsockopt (desc, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on)) < 0)
-        {
-          GNUNET_GE_DIE_STRERROR (coreAPI->ectx,
-                                  GNUNET_GE_FATAL | GNUNET_GE_ADMIN |
-                                  GNUNET_GE_IMMEDIATE, "setsockopt");
-          return GNUNET_SYSERR;
-        }
-      if (available_protocols == VERSION_AVAILABLE_IPV4)
-        {
-          memset (&serverAddrv4, 0, sizeof (serverAddrv4));
-          serverAddrv4.sin_family = AF_INET;
-          serverAddrv4.sin_addr.s_addr = INADDR_ANY;
-          serverAddrv4.sin_port = htons (port);
-          addrlen = sizeof (serverAddrv4);
-          serverAddr = (struct sockaddr *) &serverAddrv4;
-        }
-      else
-        {
-          memset (&serverAddrv6, 0, sizeof (serverAddrv6));
-          serverAddrv6.sin6_family = AF_INET6;
-          serverAddrv6.sin6_addr = in6addr_any;
-          serverAddrv6.sin6_port = htons (port);
-          addrlen = sizeof (serverAddrv6);
-          serverAddr = (struct sockaddr *) &serverAddrv6;
-        }
-      if (GNUNET_net_bind (desc, serverAddr, addrlen) < 0)
-        {
-          GNUNET_GE_LOG_STRERROR (coreAPI->ectx,
-                                  GNUNET_GE_FATAL | GNUNET_GE_ADMIN |
-                                  GNUNET_GE_IMMEDIATE, "bind");
-          GNUNET_GE_LOG (coreAPI->ectx,
-                         GNUNET_GE_FATAL | GNUNET_GE_ADMIN |
-                         GNUNET_GE_IMMEDIATE,
-                         _("Failed to bind to %s port %d.\n"),
-                         MY_TRANSPORT_NAME, port);
-          if (0 != GNUNET_net_close (&desc))
-            GNUNET_GE_LOG_STRERROR (coreAPI->ectx,
-                                    GNUNET_GE_ERROR | GNUNET_GE_USER |
-                                    GNUNET_GE_ADMIN | GNUNET_GE_BULK,
-                                    "close");
-          return GNUNET_SYSERR;
-        }
-      selector = GNUNET_select_create ("udp", GNUNET_YES, coreAPI->ectx, load_monitor, desc, addrlen, 0,        /* timeout */
-                                       &select_message_handler,
-                                       NULL,
-                                       &select_accept_handler,
-                                       NULL,
-                                       &select_close_handler,
-                                       NULL, 64 * 1024,
-                                       16 /* max sockets */ );
-      if (selector == NULL)
-        return GNUNET_SYSERR;
-    }
-  desc = udp_create_socket ();
-  if (NULL == desc)
-    {
-      GNUNET_GE_LOG_STRERROR (coreAPI->ectx,
-                              GNUNET_GE_ERROR | GNUNET_GE_ADMIN |
-                              GNUNET_GE_BULK, "socket");
-      GNUNET_select_destroy (selector);
-      selector = NULL;
-      return GNUNET_SYSERR;
-    }
-  udp_sock = GNUNET_socket_create (coreAPI->ectx, load_monitor, desc);
-  GNUNET_GE_ASSERT (coreAPI->ectx, udp_sock != NULL);
-  return GNUNET_OK;
+  return; /* Do nothing */
 }
 
 /**
  * The exported method. Makes the core api available via a global and
  * returns the udp transport API.
  */
-GNUNET_TransportAPI *
-inittransport_udp (GNUNET_CoreAPIForTransport * core)
+void *
+libgnunet_plugin_transport_udp_init (void *cls)
 {
   unsigned long long mtu;
 
-  cfg = core->cfg;
-  load_monitor = core->load_monitor;
-  GNUNET_GE_ASSERT (coreAPI->ectx, sizeof (UDPMessage) == 68);
-  GNUNET_GE_ASSERT (coreAPI->ectx, sizeof (HostAddress) == 24);
-  coreAPI = core;
-  if (-1 == GNUNET_GC_get_configuration_value_number (cfg,
-                                                      "UDP",
-                                                      "MTU",
-                                                      sizeof (UDPMessage)
-                                                      +
-                                                      GNUNET_P2P_MESSAGE_OVERHEAD
-                                                      +
-                                                      sizeof
-                                                      (GNUNET_MessageHeader) +
-                                                      32, 65500,
-                                                      MESSAGE_SIZE, &mtu))
+  struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
+  struct GNUNET_TRANSPORT_PluginFunctions *api;
+  struct Plugin *plugin;
+  struct GNUNET_SERVICE_Context *service;
+  unsigned long long aport;
+  unsigned long long bport;
+
+  service = GNUNET_SERVICE_start ("transport-udp", env->sched, env->cfg);
+  if (service == NULL)
     {
+      GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "udp", _
+                       ("Failed to start service for `%s' transport plugin.\n"),
+                       "udp");
       return NULL;
     }
-  if (mtu < 1200)
-    GNUNET_GE_LOG (coreAPI->ectx,
-                   GNUNET_GE_ERROR | GNUNET_GE_USER | GNUNET_GE_IMMEDIATE,
-                   _("MTU %llu for `%s' is probably too low!\n"), mtu, "UDP");
-  lock = GNUNET_mutex_create (GNUNET_NO);
-  if (0 !=
-      GNUNET_GC_attach_change_listener (cfg, &reload_configuration, NULL))
+  aport = 0;
+  if ((GNUNET_OK !=
+       GNUNET_CONFIGURATION_get_value_number (env->cfg,
+                                              "transport-udp",
+                                              "PORT",
+                                              &bport)) ||
+      (bport > 65535) ||
+      ((GNUNET_OK ==
+        GNUNET_CONFIGURATION_get_value_number (env->cfg,
+                                               "transport-udp",
+                                               "ADVERTISED-PORT",
+                                               &aport)) && (aport > 65535)))
     {
-      GNUNET_mutex_destroy (lock);
-      lock = NULL;
+      GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
+                       "udp",
+                       _
+                       ("Require valid port number for service `%s' in configuration!\n"),
+                       "transport-udp");
+      GNUNET_SERVICE_stop (service);
       return NULL;
     }
-  if (GNUNET_GC_get_configuration_value_yesno (cfg, "UDP", "UPNP", GNUNET_YES)
-      == GNUNET_YES)
-    {
-      upnp = coreAPI->service_request ("upnp");
-      if (upnp == NULL)
-        GNUNET_GE_LOG (coreAPI->ectx,
-                       GNUNET_GE_ERROR | GNUNET_GE_USER | GNUNET_GE_IMMEDIATE,
-                       "The UPnP service could not be loaded. To disable UPnP, set the "
-                       "configuration option \"UPNP\" in section \"%s\" to \"NO\"\n",
-                       "UDP");
-    }
-  stats = coreAPI->service_request ("stats");
-  if (stats != NULL)
-    {
-      stat_bytesReceived
-        = stats->create (gettext_noop ("# bytes received via UDP"));
-      stat_bytesSent = stats->create (gettext_noop ("# bytes sent via UDP"));
-      stat_bytesDropped
-        = stats->create (gettext_noop ("# bytes dropped by UDP (outgoing)"));
-      stat_udpConnected
-        = stats->create (gettext_noop ("# UDP connections (right now)"));
-    }
-  myAPI.protocol_number = GNUNET_TRANSPORT_PROTOCOL_NUMBER_UDP;
-  myAPI.mtu = mtu - sizeof (UDPMessage);
-  myAPI.cost = 20000;
-  myAPI.hello_verify = &verify_hello;
-  myAPI.hello_create = &create_hello;
-  myAPI.connect = &udp_connect;
-  myAPI.send = &udp_send;
-  myAPI.associate = &udp_associate;
-  myAPI.disconnect = &udp_disconnect;
-  myAPI.server_start = &udp_transport_server_start;
-  myAPI.server_stop = &udp_transport_server_stop;
-  myAPI.hello_to_address = &hello_to_address;
-  myAPI.send_now_test = &udp_test_would_try;
-
-  return &myAPI;
+  if (aport == 0)
+    aport = bport;
+
+  mtu = 1240;
+  if (mtu < 1200)
+    GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
+                     "udp",
+                     _("MTU %llu for `%s' is probably too low!\n"), mtu,
+                     "UDP");
+
+  plugin = GNUNET_malloc (sizeof (struct Plugin));
+  plugin->open_port = bport;
+  plugin->adv_port = aport;
+  plugin->env = env;
+  plugin->statistics = NULL;
+  api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
+  api->cls = plugin;
+
+  api->send = &udp_plugin_send;
+  api->disconnect = &udp_disconnect;
+  api->address_pretty_printer = &udp_plugin_address_pretty_printer;
+  api->set_receive_quota = &udp_plugin_set_receive_quota;
+  api->check_address = &udp_check_address;
+
+  plugin->service = service;
+
+  /* FIXME: do the two calls below periodically again and
+     not just once (since the info we get might change...) */
+  GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);
+  plugin->hostname_dns = GNUNET_RESOLVER_hostname_resolve (env->sched,
+                                                           env->cfg,
+                                                           AF_UNSPEC,
+                                                           HOSTNAME_RESOLVE_TIMEOUT,
+                                                           &process_hostname_ips,
+                                                           plugin);
+
+  udp_sock = udp_transport_server_start (plugin);
+
+  GNUNET_assert (udp_sock != NULL);
+
+  return api;
 }
 
-void
-donetransport_udp ()
+void *
+libgnunet_plugin_transport_udp_done (void *cls)
 {
-  do_shutdown ();
+  struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
+  struct Plugin *plugin = api->cls;
+
+  udp_transport_server_stop (plugin);
+  if (NULL != hostname_dns)
+    {
+      GNUNET_RESOLVER_request_cancel (hostname_dns);
+      hostname_dns = NULL;
+    }
+  GNUNET_SERVICE_stop (plugin->service);
+
+  GNUNET_NETWORK_fdset_destroy (plugin->rs);
+  GNUNET_free (plugin);
+  GNUNET_free (api);
+  return NULL;
 }
 
-/* end of udp.c */
+/* end of plugin_transport_udp.c */