- sending and getting sessions
[oweals/gnunet.git] / src / transport / plugin_transport_udp_new.c
1 /*
2      This file is part of GNUnet
3      (C) 2010, 2011 Christian Grothoff (and other contributing authors)
4
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.
9
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.
14
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., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file transport/plugin_transport_udp.c
23  * @brief Implementation of the UDP transport protocol
24  * @author Christian Grothoff
25  * @author Nathan Evans
26  * @author Matthias Wachs
27  */
28 #include "platform.h"
29 #include "plugin_transport_udp_new.h"
30 #include "gnunet_hello_lib.h"
31 #include "gnunet_util_lib.h"
32 #include "gnunet_fragmentation_lib.h"
33 #include "gnunet_nat_lib.h"
34 #include "gnunet_protocols.h"
35 #include "gnunet_resolver_service.h"
36 #include "gnunet_signatures.h"
37 #include "gnunet_constants.h"
38 #include "gnunet_statistics_service.h"
39 #include "gnunet_transport_service.h"
40 #include "gnunet_transport_plugin.h"
41 #include "transport.h"
42
43 #define LOG(kind,...) GNUNET_log_from (kind, "transport-udp", __VA_ARGS__)
44
45
46 /**
47  * Closure for 'append_port'.
48  */
49 struct PrettyPrinterContext
50 {
51   /**
52    * Function to call with the result.
53    */
54   GNUNET_TRANSPORT_AddressStringCallback asc;
55
56   /**
57    * Clsoure for 'asc'.
58    */
59   void *asc_cls;
60
61   /**
62    * Port to add after the IP address.
63    */
64   uint16_t port;
65 };
66
67 struct Session
68 {
69   /**
70    * Which peer is this session for?
71    */
72   struct GNUNET_PeerIdentity target;
73
74   /**
75    * Address of the other peer
76    */
77   const struct sockaddr *sock_addr;
78
79   size_t addrlen;
80
81   /**
82    * Desired delay for next sending we received from other peer
83    */
84   struct GNUNET_TIME_Absolute flow_delay_from_other_peer;
85 };
86
87
88 struct SessionCompareContext
89 {
90   struct Session *res;
91   const struct GNUNET_HELLO_Address *addr;
92 };
93
94
95 /**
96  * Closure for 'process_inbound_tokenized_messages'
97  */
98 struct SourceInformation
99 {
100   /**
101    * Sender identity.
102    */
103   struct GNUNET_PeerIdentity sender;
104
105   /**
106    * Source address.
107    */
108   const void *arg;
109
110   /**
111    * Number of bytes in source address.
112    */
113   size_t args;
114
115   struct Session *session;
116 };
117
118
119 /**
120  * Function called for a quick conversion of the binary address to
121  * a numeric address.  Note that the caller must not free the
122  * address and that the next call to this function is allowed
123  * to override the address again.
124  *
125  * @param cls closure
126  * @param addr binary address
127  * @param addrlen length of the address
128  * @return string representing the same address
129  */
130 const char *
131 udp_address_to_string (void *cls, const void *addr, size_t addrlen)
132 {
133   static char rbuf[INET6_ADDRSTRLEN + 10];
134   char buf[INET6_ADDRSTRLEN];
135   const void *sb;
136   struct in_addr a4;
137   struct in6_addr a6;
138   const struct IPv4UdpAddress *t4;
139   const struct IPv6UdpAddress *t6;
140   int af;
141   uint16_t port;
142
143   if (addrlen == sizeof (struct IPv6UdpAddress))
144   {
145     t6 = addr;
146     af = AF_INET6;
147     port = ntohs (t6->u6_port);
148     memcpy (&a6, &t6->ipv6_addr, sizeof (a6));
149     sb = &a6;
150   }
151   else if (addrlen == sizeof (struct IPv4UdpAddress))
152   {
153     t4 = addr;
154     af = AF_INET;
155     port = ntohs (t4->u4_port);
156     memcpy (&a4, &t4->ipv4_addr, sizeof (a4));
157     sb = &a4;
158   }
159   else
160   {
161     GNUNET_break_op (0);
162     return NULL;
163   }
164   inet_ntop (af, sb, buf, INET6_ADDRSTRLEN);
165   GNUNET_snprintf (rbuf, sizeof (rbuf), (af == AF_INET6) ? "[%s]:%u" : "%s:%u",
166                    buf, port);
167   return rbuf;
168 }
169
170
171 /**
172  * Append our port and forward the result.
173  *
174  * @param cls a 'struct PrettyPrinterContext'
175  * @param hostname result from DNS resolver
176  */
177 static void
178 append_port (void *cls, const char *hostname)
179 {
180   struct PrettyPrinterContext *ppc = cls;
181   char *ret;
182
183   if (hostname == NULL)
184   {
185     ppc->asc (ppc->asc_cls, NULL);
186     GNUNET_free (ppc);
187     return;
188   }
189   GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
190   ppc->asc (ppc->asc_cls, ret);
191   GNUNET_free (ret);
192 }
193
194
195 /**
196  * Convert the transports address to a nice, human-readable
197  * format.
198  *
199  * @param cls closure
200  * @param type name of the transport that generated the address
201  * @param addr one of the addresses of the host, NULL for the last address
202  *        the specific address format depends on the transport
203  * @param addrlen length of the address
204  * @param numeric should (IP) addresses be displayed in numeric form?
205  * @param timeout after how long should we give up?
206  * @param asc function to call on each string
207  * @param asc_cls closure for asc
208  */
209 static void
210 udp_plugin_address_pretty_printer (void *cls, const char *type,
211                                    const void *addr, size_t addrlen,
212                                    int numeric,
213                                    struct GNUNET_TIME_Relative timeout,
214                                    GNUNET_TRANSPORT_AddressStringCallback asc,
215                                    void *asc_cls)
216 {
217   struct PrettyPrinterContext *ppc;
218   const void *sb;
219   size_t sbs;
220   struct sockaddr_in a4;
221   struct sockaddr_in6 a6;
222   const struct IPv4UdpAddress *u4;
223   const struct IPv6UdpAddress *u6;
224   uint16_t port;
225
226   if (addrlen == sizeof (struct IPv6UdpAddress))
227   {
228     u6 = addr;
229     memset (&a6, 0, sizeof (a6));
230     a6.sin6_family = AF_INET6;
231 #if HAVE_SOCKADDR_IN_SIN_LEN
232     a6.sin6_len = sizeof (a6);
233 #endif
234     a6.sin6_port = u6->u6_port;
235     memcpy (&a6.sin6_addr, &u6->ipv6_addr, sizeof (struct in6_addr));
236     port = ntohs (u6->u6_port);
237     sb = &a6;
238     sbs = sizeof (a6);
239   }
240   else if (addrlen == sizeof (struct IPv4UdpAddress))
241   {
242     u4 = addr;
243     memset (&a4, 0, sizeof (a4));
244     a4.sin_family = AF_INET;
245 #if HAVE_SOCKADDR_IN_SIN_LEN
246     a4.sin_len = sizeof (a4);
247 #endif
248     a4.sin_port = u4->u4_port;
249     a4.sin_addr.s_addr = u4->ipv4_addr;
250     port = ntohs (u4->u4_port);
251     sb = &a4;
252     sbs = sizeof (a4);
253   }
254   else
255   {
256     /* invalid address */
257     GNUNET_break_op (0);
258     asc (asc_cls, NULL);
259     return;
260   }
261   ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
262   ppc->asc = asc;
263   ppc->asc_cls = asc_cls;
264   ppc->port = port;
265   GNUNET_RESOLVER_hostname_get (sb, sbs, !numeric, timeout, &append_port, ppc);
266 }
267
268
269 /**
270  * Check if the given port is plausible (must be either our listen
271  * port or our advertised port).  If it is neither, we return
272  * GNUNET_SYSERR.
273  *
274  * @param plugin global variables
275  * @param in_port port number to check
276  * @return GNUNET_OK if port is either open_port or adv_port
277  */
278 static int
279 check_port (struct Plugin *plugin, uint16_t in_port)
280 {
281   if ((in_port == plugin->port) || (in_port == plugin->aport))
282     return GNUNET_OK;
283   return GNUNET_SYSERR;
284 }
285
286
287
288 /**
289  * Function that will be called to check if a binary address for this
290  * plugin is well-formed and corresponds to an address for THIS peer
291  * (as per our configuration).  Naturally, if absolutely necessary,
292  * plugins can be a bit conservative in their answer, but in general
293  * plugins should make sure that the address does not redirect
294  * traffic to a 3rd party that might try to man-in-the-middle our
295  * traffic.
296  *
297  * @param cls closure, should be our handle to the Plugin
298  * @param addr pointer to the address
299  * @param addrlen length of addr
300  * @return GNUNET_OK if this is a plausible address for this peer
301  *         and transport, GNUNET_SYSERR if not
302  *
303  */
304 static int
305 udp_plugin_check_address (void *cls, const void *addr, size_t addrlen)
306 {
307   struct Plugin *plugin = cls;
308   struct IPv4UdpAddress *v4;
309   struct IPv6UdpAddress *v6;
310
311   if ((addrlen != sizeof (struct IPv4UdpAddress)) &&
312       (addrlen != sizeof (struct IPv6UdpAddress)))
313   {
314     GNUNET_break_op (0);
315     return GNUNET_SYSERR;
316   }
317   if (addrlen == sizeof (struct IPv4UdpAddress))
318   {
319     v4 = (struct IPv4UdpAddress *) addr;
320     if (GNUNET_OK != check_port (plugin, ntohs (v4->u4_port)))
321       return GNUNET_SYSERR;
322     if (GNUNET_OK !=
323         GNUNET_NAT_test_address (plugin->nat, &v4->ipv4_addr,
324                                  sizeof (struct in_addr)))
325       return GNUNET_SYSERR;
326   }
327   else
328   {
329     v6 = (struct IPv6UdpAddress *) addr;
330     if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
331     {
332       GNUNET_break_op (0);
333       return GNUNET_SYSERR;
334     }
335     if (GNUNET_OK != check_port (plugin, ntohs (v6->u6_port)))
336       return GNUNET_SYSERR;
337     if (GNUNET_OK !=
338         GNUNET_NAT_test_address (plugin->nat, &v6->ipv6_addr,
339                                  sizeof (struct in6_addr)))
340       return GNUNET_SYSERR;
341   }
342   return GNUNET_OK;
343 }
344
345
346 /**
347  * Destroy a session, plugin is being unloaded.
348  *
349  * @param cls unused
350  * @param key hash of public key of target peer
351  * @param value a 'struct PeerSession*' to clean up
352  * @return GNUNET_OK (continue to iterate)
353  */
354 static int
355 disconnect_and_free_it (void *cls, const GNUNET_HashCode * key, void *value)
356 {
357   struct Plugin *plugin = cls;
358   struct Session *s = value;
359
360 #if DEBUG_UDP
361   LOG (GNUNET_ERROR_TYPE_DEBUG,
362        "Session %p to peer `%s' address ended \n",
363          s,
364          GNUNET_i2s (&s->target),
365          GNUNET_a2s (s->sock_addr, s->addrlen));
366 #endif
367
368   plugin->env->session_end (plugin->env->cls, &s->target, s);
369
370   GNUNET_assert (GNUNET_YES ==
371                  GNUNET_CONTAINER_multihashmap_remove (plugin->sessions,
372                                                        &s->target.hashPubKey,
373                                                        s));
374
375   GNUNET_free (s);
376   return GNUNET_OK;
377 }
378
379
380 /**
381  * Disconnect from a remote node.  Clean up session if we have one for this peer
382  *
383  * @param cls closure for this call (should be handle to Plugin)
384  * @param target the peeridentity of the peer to disconnect
385  * @return GNUNET_OK on success, GNUNET_SYSERR if the operation failed
386  */
387 static void
388 udp_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
389 {
390   struct Plugin *plugin = cls;
391   GNUNET_assert (plugin != NULL);
392
393   GNUNET_assert (target != NULL);
394 #if DEBUG_UDP
395   LOG (GNUNET_ERROR_TYPE_DEBUG,
396        "Disconnecting from peer `%s'\n", GNUNET_i2s (target));
397 #endif
398   /* Clean up sessions */
399   GNUNET_CONTAINER_multihashmap_get_multiple (plugin->sessions, &target->hashPubKey, &disconnect_and_free_it, plugin);
400
401 }
402
403 static struct Session *
404 create_session (struct Plugin *plugin, const struct GNUNET_PeerIdentity *target,
405                 const void *addr, size_t addrlen,
406                 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
407 {
408   struct Session *s;
409   const struct IPv4UdpAddress *t4;
410   const struct IPv6UdpAddress *t6;
411   struct sockaddr_in *v4;
412   struct sockaddr_in6 *v6;
413   size_t len;
414   struct GNUNET_ATS_Information ats;
415
416   switch (addrlen)
417   {
418   case sizeof (struct IPv4UdpAddress):
419     if (NULL == plugin->sockv4)
420     {
421       return NULL;
422     }
423     t4 = addr;
424     s = GNUNET_malloc (sizeof (struct Session) + sizeof (struct sockaddr_in));
425     len = sizeof (struct sockaddr_in);
426     v4 = (struct sockaddr_in *) &s[1];
427     v4->sin_family = AF_INET;
428 #if HAVE_SOCKADDR_IN_SIN_LEN
429     v4->sin_len = sizeof (struct sockaddr_in);
430 #endif
431     v4->sin_port = t4->u4_port;
432     v4->sin_addr.s_addr = t4->ipv4_addr;
433     ats = plugin->env->get_address_type (plugin->env->cls, (const struct sockaddr *) v4, sizeof (struct sockaddr_in));
434     break;
435   case sizeof (struct IPv6UdpAddress):
436     if (NULL == plugin->sockv6)
437     {
438       return NULL;
439     }
440     t6 = addr;
441     s =
442         GNUNET_malloc (sizeof (struct Session) + sizeof (struct sockaddr_in6));
443     len = sizeof (struct sockaddr_in6);
444     v6 = (struct sockaddr_in6 *) &s[1];
445     v6->sin6_family = AF_INET6;
446 #if HAVE_SOCKADDR_IN_SIN_LEN
447     v6->sin6_len = sizeof (struct sockaddr_in6);
448 #endif
449     v6->sin6_port = t6->u6_port;
450     v6->sin6_addr = t6->ipv6_addr;
451     ats = plugin->env->get_address_type (plugin->env->cls, (const struct sockaddr *) v6, sizeof (struct sockaddr_in6));
452     break;
453   default:
454     /* Must have a valid address to send to */
455     GNUNET_break_op (0);
456     return NULL;
457   }
458
459   s->addrlen = len;
460   s->target = *target;
461   s->sock_addr = (const struct sockaddr *) &s[1];
462
463   return s;
464 }
465
466 static int session_cmp_it (void *cls,
467                            const GNUNET_HashCode * key,
468                            void *value)
469 {
470   struct SessionCompareContext * cctx = cls;
471   const struct GNUNET_HELLO_Address *address = cctx->addr;
472   struct Session *s = value;
473
474   socklen_t s_addrlen = s->addrlen;
475
476 #if VERBOSE
477   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Comparing  address %s <-> %s\n",
478       udp_address_to_string (NULL, (void *) address->address, address->address_length),
479       GNUNET_a2s (s->sock_addr, s->addrlen));
480 #endif
481
482   if ((address->address_length == sizeof (struct IPv4UdpAddress)) &&
483       (s_addrlen == sizeof (struct sockaddr_in)))
484   {
485     struct IPv4UdpAddress * u4 = NULL;
486     u4 = (struct IPv4UdpAddress *) address->address;
487     const struct sockaddr_in *s4 = (const struct sockaddr_in *) s->sock_addr;
488     if ((0 == memcmp ((const void *) &u4->ipv4_addr,(const void *) &s4->sin_addr, sizeof (struct in_addr))) &&
489         (u4->u4_port == s4->sin_port))
490     {
491       cctx->res = s;
492       return GNUNET_NO;
493     }
494
495   }
496   if ((address->address_length == sizeof (struct IPv6UdpAddress)) &&
497       (s_addrlen == sizeof (struct sockaddr_in6)))
498   {
499     struct IPv6UdpAddress * u6 = NULL;
500     u6 = (struct IPv6UdpAddress *) address->address;
501     const struct sockaddr_in6 *s6 = (const struct sockaddr_in6 *) s->sock_addr;
502     if ((0 == memcmp (&u6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr))) &&
503         (u6->u6_port == s6->sin6_port))
504     {
505       cctx->res = s;
506       return GNUNET_NO;
507     }
508   }
509
510
511   return GNUNET_YES;
512 }
513
514
515 /**
516  * Creates a new outbound session the transport service will use to send data to the
517  * peer
518  *
519  * @param cls the plugin
520  * @param address the address
521  * @return the session or NULL of max connections exceeded
522  */
523 static struct Session *
524 udp_plugin_get_session (void *cls,
525                   const struct GNUNET_HELLO_Address *address)
526 {
527   struct Session * s = NULL;
528   struct Plugin * plugin = cls;
529
530   GNUNET_assert (plugin != NULL);
531   GNUNET_assert (address != NULL);
532
533   if ((address->address == NULL) ||
534       ((address->address_length != sizeof (struct IPv4UdpAddress)) &&
535       (address->address_length != sizeof (struct IPv6UdpAddress))))
536   {
537     GNUNET_break (0);
538     return NULL;
539   }
540
541   /* check if session already exists */
542   struct SessionCompareContext cctx;
543   cctx.addr = address;
544   cctx.res = NULL;
545 #if DEBUG_UDP
546   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Looking for existing session for peer `%s' `%s' \n", GNUNET_i2s (&address->peer), udp_address_to_string(NULL, address->address, address->address_length));
547 #endif
548   GNUNET_CONTAINER_multihashmap_get_multiple(plugin->sessions, &address->peer.hashPubKey, session_cmp_it, &cctx);
549   if (cctx.res != NULL)
550   {
551 #if DEBUG_UDP
552     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Found existing session %p\n", cctx.res);
553 #endif
554     return cctx.res;
555   }
556
557   /* otherwise create new */
558   s = create_session (plugin,
559       &address->peer,
560       address->address,
561       address->address_length,
562       NULL, NULL);
563 #if DEBUG_UDP
564     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
565               "Creating new session %p for peer `%s' address `%s'\n",
566               s,
567               GNUNET_i2s(&address->peer),
568               udp_address_to_string(NULL,address->address,address->address_length));
569 #endif
570   GNUNET_assert (GNUNET_OK ==
571                  GNUNET_CONTAINER_multihashmap_put (plugin->sessions,
572                                                     &s->target.hashPubKey,
573                                                     s,
574                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
575
576   return s;
577 }
578
579
580 /**
581  * Function that can be used by the transport service to transmit
582  * a message using the plugin.   Note that in the case of a
583  * peer disconnecting, the continuation MUST be called
584  * prior to the disconnect notification itself.  This function
585  * will be called with this peer's HELLO message to initiate
586  * a fresh connection to another peer.
587  *
588  * @param cls closure
589  * @param session which session must be used
590  * @param msgbuf the message to transmit
591  * @param msgbuf_size number of bytes in 'msgbuf'
592  * @param priority how important is the message (most plugins will
593  *                 ignore message priority and just FIFO)
594  * @param to how long to wait at most for the transmission (does not
595  *                require plugins to discard the message after the timeout,
596  *                just advisory for the desired delay; most plugins will ignore
597  *                this as well)
598  * @param cont continuation to call once the message has
599  *        been transmitted (or if the transport is ready
600  *        for the next transmission call; or if the
601  *        peer disconnected...); can be NULL
602  * @param cont_cls closure for cont
603  * @return number of bytes used (on the physical network, with overheads);
604  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
605  *         and does NOT mean that the message was not transmitted (DV)
606  */
607 static ssize_t
608 udp_plugin_send (void *cls,
609                   struct Session *s,
610                   const char *msgbuf, size_t msgbuf_size,
611                   unsigned int priority,
612                   struct GNUNET_TIME_Relative to,
613                   GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
614 {
615   struct Plugin *plugin = cls;
616   size_t mlen = msgbuf_size + sizeof (struct UDPMessage);;
617
618   struct GNUNET_TIME_Relative delta;
619   struct UDPMessageWrapper * udpw;
620   struct UDPMessage *udp;
621
622   GNUNET_assert (plugin != NULL);
623   GNUNET_assert (s != NULL);
624
625   if (mlen >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
626   {
627     GNUNET_break (0);
628     return GNUNET_SYSERR;
629   }
630
631   LOG (GNUNET_ERROR_TYPE_DEBUG,
632        "UDP transmits %u-byte message to `%s' using address `%s'\n",
633          msgbuf_size,
634          GNUNET_i2s (&s->target),
635          GNUNET_a2s(s->sock_addr, s->addrlen));
636
637   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains_value(plugin->sessions, &s->target.hashPubKey, s))
638   {
639     GNUNET_break (0);
640     return GNUNET_SYSERR;
641   }
642
643   udpw = GNUNET_malloc (sizeof (struct UDPMessageWrapper) + sizeof (struct UDPMessage) + msgbuf_size);
644   udpw->session = s;
645   udp = (struct UDPMessage *) &udpw[1];
646   udpw->udp = udp;
647   udpw->msg_size = mlen;
648   udpw->cont = cont;
649   udpw->cont_cls = cont_cls;
650
651   udp->header.size = htons (mlen);
652   udp->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_MESSAGE);
653   udp->reserved = htonl (0);
654   udp->sender = *plugin->env->my_identity;
655   memcpy (&udp[1], msgbuf, msgbuf_size);
656
657   GNUNET_CONTAINER_DLL_insert(plugin->msg_head, plugin->msg_tail, udpw);
658
659   delta = GNUNET_TIME_absolute_get_remaining (s->flow_delay_from_other_peer);
660   return mlen;
661 }
662
663 static ssize_t udp_plugin_send_wrapper (void *cls,
664                                         const struct
665                                         GNUNET_PeerIdentity *
666                                         target,
667                                         const char *msgbuf,
668                                         size_t msgbuf_size,
669                                         uint32_t priority,
670                                         struct
671                                         GNUNET_TIME_Relative
672                                         timeout,
673                                         struct Session * session,
674                                         const void *addr,
675                                         size_t addrlen,
676                                         int force_address,
677                                         GNUNET_TRANSPORT_TransmitContinuation
678                                         cont, void *cont_cls)
679 {
680   int ret;
681   struct Session * s = NULL;
682   struct GNUNET_HELLO_Address * ha = NULL;
683
684   ha = GNUNET_HELLO_address_allocate(target, "", addr,addrlen);
685   GNUNET_assert (ha != NULL);
686   s = udp_plugin_get_session(cls, ha);
687   GNUNET_assert (s != NULL);
688   GNUNET_free (ha);
689   ret = udp_plugin_send (cls, s, msgbuf, msgbuf_size, priority, timeout, cont, cont_cls);
690
691   return ret;
692 }
693
694
695 /**
696  * Our external IP address/port mapping has changed.
697  *
698  * @param cls closure, the 'struct LocalAddrList'
699  * @param add_remove GNUNET_YES to mean the new public IP address, GNUNET_NO to mean
700  *     the previous (now invalid) one
701  * @param addr either the previous or the new public IP address
702  * @param addrlen actual lenght of the address
703  */
704 static void
705 udp_nat_port_map_callback (void *cls, int add_remove,
706                            const struct sockaddr *addr, socklen_t addrlen)
707 {
708   struct Plugin *plugin = cls;
709   struct IPv4UdpAddress u4;
710   struct IPv6UdpAddress u6;
711   void *arg;
712   size_t args;
713
714   /* convert 'addr' to our internal format */
715   switch (addr->sa_family)
716   {
717   case AF_INET:
718     GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
719     u4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
720     u4.u4_port = ((struct sockaddr_in *) addr)->sin_port;
721     arg = &u4;
722     args = sizeof (u4);
723     break;
724   case AF_INET6:
725     GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
726     memcpy (&u6.ipv6_addr, &((struct sockaddr_in6 *) addr)->sin6_addr,
727             sizeof (struct in6_addr));
728     u6.u6_port = ((struct sockaddr_in6 *) addr)->sin6_port;
729     arg = &u6;
730     args = sizeof (u6);
731     break;
732   default:
733     GNUNET_break (0);
734     return;
735   }
736   /* modify our published address list */
737   plugin->env->notify_address (plugin->env->cls, add_remove, arg, args);
738 }
739
740
741
742 /**
743  * Message tokenizer has broken up an incomming message. Pass it on
744  * to the service.
745  *
746  * @param cls the 'struct Plugin'
747  * @param client the 'struct SourceInformation'
748  * @param hdr the actual message
749  */
750 static void
751 process_inbound_tokenized_messages (void *cls, void *client,
752                                     const struct GNUNET_MessageHeader *hdr)
753 {
754   struct Plugin *plugin = cls;
755   struct SourceInformation *si = client;
756   struct GNUNET_ATS_Information ats[2];
757   struct GNUNET_TIME_Relative delay;
758
759   /* setup ATS */
760   ats[0].type = htonl (GNUNET_ATS_QUALITY_NET_DISTANCE);
761   ats[0].value = htonl (1);
762   ats[1].type = htonl (GNUNET_ATS_NETWORK_TYPE);
763   ats[1].value = htonl (GNUNET_ATS_COST_WAN);
764   //GNUNET_break (ntohl(si->session->ats_address_network_type) != GNUNET_ATS_NET_UNSPECIFIED);
765   delay = plugin->env->receive (plugin->env->cls,
766                 &si->sender,
767                 hdr,
768                 (const struct GNUNET_ATS_Information *) &ats, 2,
769                 NULL,
770                 si->arg,
771                 si->args);
772   //si->session->flow_delay_for_other_peer = delay;
773 }
774
775
776 /**
777  * We've received a UDP Message.  Process it (pass contents to main service).
778  *
779  * @param plugin plugin context
780  * @param msg the message
781  * @param sender_addr sender address
782  * @param sender_addr_len number of bytes in sender_addr
783  */
784 static void
785 process_udp_message (struct Plugin *plugin, const struct UDPMessage *msg,
786                      const struct sockaddr *sender_addr,
787                      socklen_t sender_addr_len)
788 {
789   struct SourceInformation si;
790   struct IPv4UdpAddress u4;
791   struct IPv6UdpAddress u6;
792   struct GNUNET_ATS_Information ats;
793   const void *arg;
794   size_t args;
795
796   if (0 != ntohl (msg->reserved))
797   {
798     GNUNET_break_op (0);
799     return;
800   }
801   if (ntohs (msg->header.size) <
802       sizeof (struct GNUNET_MessageHeader) + sizeof (struct UDPMessage))
803   {
804     GNUNET_break_op (0);
805     return;
806   }
807
808   ats.type = htonl (GNUNET_ATS_NETWORK_TYPE);
809   ats.value = htonl (GNUNET_ATS_NET_UNSPECIFIED);
810   /* convert address */
811   switch (sender_addr->sa_family)
812   {
813   case AF_INET:
814     GNUNET_assert (sender_addr_len == sizeof (struct sockaddr_in));
815     u4.ipv4_addr = ((struct sockaddr_in *) sender_addr)->sin_addr.s_addr;
816     u4.u4_port = ((struct sockaddr_in *) sender_addr)->sin_port;
817     arg = &u4;
818     args = sizeof (u4);
819     break;
820   case AF_INET6:
821     GNUNET_assert (sender_addr_len == sizeof (struct sockaddr_in6));
822     u6.ipv6_addr = ((struct sockaddr_in6 *) sender_addr)->sin6_addr;
823     u6.u6_port = ((struct sockaddr_in6 *) sender_addr)->sin6_port;
824     arg = &u6;
825     args = sizeof (u6);
826     break;
827   default:
828     GNUNET_break (0);
829     return;
830   }
831 #if DEBUG_UDP
832   LOG (GNUNET_ERROR_TYPE_DEBUG,
833        "Received message with %u bytes from peer `%s' at `%s'\n",
834        (unsigned int) ntohs (msg->header.size), GNUNET_i2s (&msg->sender),
835        GNUNET_a2s (sender_addr, sender_addr_len));
836 #endif
837
838   /* iterate over all embedded messages */
839   si.sender = msg->sender;
840   si.arg = arg;
841   si.args = args;
842
843   GNUNET_SERVER_mst_receive (plugin->mst, &si, (const char *) &msg[1],
844                              ntohs (msg->header.size) -
845                              sizeof (struct UDPMessage), GNUNET_YES, GNUNET_NO);
846 }
847
848
849 /**
850  * Read and process a message from the given socket.
851  *
852  * @param plugin the overall plugin
853  * @param rsock socket to read from
854  */
855 static void
856 udp_select_read (struct Plugin *plugin, struct GNUNET_NETWORK_Handle *rsock)
857 {
858   socklen_t fromlen;
859   char addr[32];
860   char buf[65536];
861   ssize_t size;
862   const struct GNUNET_MessageHeader *msg;
863   //const struct GNUNET_MessageHeader *ack;
864   //struct Session *peer_session;
865   //const struct UDP_ACK_Message *udp_ack;
866   //struct ReceiveContext *rc;
867   //struct GNUNET_TIME_Absolute now;
868   //struct FindReceiveContext frc;
869   //struct Session *s = NULL;
870   //struct GNUNET_TIME_Relative flow_delay;
871   //struct GNUNET_ATS_Information ats;
872
873   fromlen = sizeof (addr);
874   memset (&addr, 0, sizeof (addr));
875   size = GNUNET_NETWORK_socket_recvfrom (rsock, buf, sizeof (buf),
876                                       (struct sockaddr *) &addr, &fromlen);
877   if (size < sizeof (struct GNUNET_MessageHeader))
878   {
879     GNUNET_break_op (0);
880     return;
881   }
882   msg = (const struct GNUNET_MessageHeader *) buf;
883
884   LOG (GNUNET_ERROR_TYPE_DEBUG,
885        "UDP received %u-byte message from `%s' type %i\n", (unsigned int) size,
886        GNUNET_a2s ((const struct sockaddr *) addr, fromlen), ntohs (msg->type));
887
888   if (size != ntohs (msg->size))
889   {
890     GNUNET_break_op (0);
891     return;
892   }
893   switch (ntohs (msg->type))
894   {
895   case GNUNET_MESSAGE_TYPE_TRANSPORT_BROADCAST_BEACON:
896   {
897     udp_broadcast_receive(plugin, &buf, size, addr, fromlen);
898     return;
899   }
900   case GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_MESSAGE:
901     if (ntohs (msg->size) < sizeof (struct UDPMessage))
902     {
903       GNUNET_break_op (0);
904       return;
905     }
906
907     process_udp_message (plugin, (const struct UDPMessage *) msg,
908                          (const struct sockaddr *) addr, fromlen);
909
910     return;
911   default:
912     GNUNET_break_op (0);
913     return;
914   }
915 }
916
917 size_t
918 udp_select_send (struct Plugin *plugin)
919 {
920   ssize_t sent;
921   size_t slen;
922
923   struct UDPMessageWrapper *udpw = plugin->msg_head;
924   const struct sockaddr * sa = udpw->session->sock_addr;
925
926   switch (sa->sa_family)
927   {
928   case AF_INET:
929     if (NULL == plugin->sockv4)
930       return 0;
931     sent =
932         GNUNET_NETWORK_socket_sendto (plugin->sockv4, udpw->udp, udpw->msg_size,
933                                       sa, slen = sizeof (struct sockaddr_in));
934     break;
935   case AF_INET6:
936     if (NULL == plugin->sockv6)
937       return 0;
938     sent =
939         GNUNET_NETWORK_socket_sendto (plugin->sockv6, udpw->udp, udpw->msg_size,
940                                       sa, slen = sizeof (struct sockaddr_in6));
941     break;
942   default:
943     GNUNET_break (0);
944     return 0;
945   }
946   if (GNUNET_SYSERR == sent)
947   {
948     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "sendto");
949     LOG (GNUNET_ERROR_TYPE_ERROR,
950          "UDP transmitted %u-byte message to %s (%d: %s)\n",
951          (unsigned int) ntohs (udpw->msg_size), GNUNET_a2s (sa, slen), (int) sent,
952          (sent < 0) ? STRERROR (errno) : "ok");
953     if (udpw->cont != NULL)
954       udpw->cont (udpw->cont_cls, &udpw->session->target, GNUNET_SYSERR);
955   }
956   LOG (GNUNET_ERROR_TYPE_DEBUG,
957        "UDP transmitted %u-byte message to %s (%d: %s)\n",
958        (unsigned int) ntohs (udpw->msg_size), GNUNET_a2s (sa, slen), (int) sent,
959        (sent < 0) ? STRERROR (errno) : "ok");
960
961   if (udpw->cont != NULL)
962     udpw->cont (udpw->cont_cls, &udpw->session->target, GNUNET_OK);
963
964   GNUNET_CONTAINER_DLL_remove(plugin->msg_head, plugin->msg_tail, udpw);
965   GNUNET_free (udpw);
966
967   return sent;
968 }
969
970 /**
971  * We have been notified that our readset has something to read.  We don't
972  * know which socket needs to be read, so we have to check each one
973  * Then reschedule this function to be called again once more is available.
974  *
975  * @param cls the plugin handle
976  * @param tc the scheduling context (for rescheduling this function again)
977  */
978 static void
979 udp_plugin_select (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
980 {
981   struct Plugin *plugin = cls;
982
983   plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
984   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
985     return;
986
987   if ((tc->reason & GNUNET_SCHEDULER_REASON_READ_READY) != 0)
988   {
989     if ((NULL != plugin->sockv4) &&
990       (GNUNET_NETWORK_fdset_isset (tc->read_ready, plugin->sockv4)))
991         udp_select_read (plugin, plugin->sockv4);
992     if ((NULL != plugin->sockv6) &&
993       (GNUNET_NETWORK_fdset_isset (tc->read_ready, plugin->sockv6)))
994         udp_select_read (plugin, plugin->sockv6);
995   }
996
997   if ((tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY) != 0)
998   {
999     if (plugin->msg_head != NULL)
1000       udp_select_send (plugin);
1001   }
1002
1003   plugin->select_task = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1004                                    GNUNET_SCHEDULER_NO_TASK,
1005                                    GNUNET_TIME_UNIT_FOREVER_REL, plugin->rs,
1006                                    plugin->ws, &udp_plugin_select, plugin);
1007
1008 }
1009
1010
1011 static int
1012 setup_sockets (struct Plugin *plugin, struct sockaddr_in6 *serverAddrv6, struct sockaddr_in *serverAddrv4)
1013 {
1014   int tries;
1015   int sockets_created = 0;
1016   struct sockaddr *serverAddr;
1017   struct sockaddr *addrs[2];
1018   socklen_t addrlens[2];
1019   socklen_t addrlen;
1020
1021   /* Create IPv6 socket */
1022   if (plugin->enable_ipv6 == GNUNET_YES)
1023   {
1024     plugin->sockv6 = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_DGRAM, 0);
1025     if (NULL == plugin->sockv6)
1026     {
1027       GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "socket");
1028     }
1029     else
1030     {
1031 #if HAVE_SOCKADDR_IN_SIN_LEN
1032       serverAddrv6.sin6_len = sizeof (serverAddrv6);
1033 #endif
1034       serverAddrv6->sin6_family = AF_INET6;
1035       serverAddrv6->sin6_addr = in6addr_any;
1036       serverAddrv6->sin6_port = htons (plugin->port);
1037       addrlen = sizeof (struct sockaddr_in6);
1038       serverAddr = (struct sockaddr *) serverAddrv6;
1039 #if DEBUG_UDP
1040       LOG (GNUNET_ERROR_TYPE_DEBUG, "Binding to IPv6 port %d\n",
1041            ntohs (serverAddrv6->sin6_port));
1042 #endif
1043       tries = 0;
1044       while (GNUNET_NETWORK_socket_bind (plugin->sockv6, serverAddr, addrlen) !=
1045              GNUNET_OK)
1046       {
1047         serverAddrv6->sin6_port = htons (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, 33537) + 32000);        /* Find a good, non-root port */
1048 #if DEBUG_UDP
1049         LOG (GNUNET_ERROR_TYPE_DEBUG,
1050              "IPv6 Binding failed, trying new port %d\n",
1051              ntohs (serverAddrv6->sin6_port));
1052 #endif
1053         tries++;
1054         if (tries > 10)
1055         {
1056           GNUNET_NETWORK_socket_close (plugin->sockv6);
1057           plugin->sockv6 = NULL;
1058           break;
1059         }
1060       }
1061       if (plugin->sockv6 != NULL)
1062       {
1063 #if DEBUG_UDP
1064         LOG (GNUNET_ERROR_TYPE_DEBUG,
1065              "IPv6 socket created on port %d\n",
1066              ntohs (serverAddrv6->sin6_port));
1067 #endif
1068         addrs[sockets_created] = (struct sockaddr *) serverAddrv6;
1069         addrlens[sockets_created] = sizeof (struct sockaddr_in6);
1070         sockets_created++;
1071       }
1072     }
1073   }
1074
1075   /* Create IPv4 socket */
1076   plugin->sockv4 = GNUNET_NETWORK_socket_create (PF_INET, SOCK_DGRAM, 0);
1077   if (NULL == plugin->sockv4)
1078   {
1079     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "socket");
1080   }
1081   else
1082   {
1083 #if HAVE_SOCKADDR_IN_SIN_LEN
1084     serverAddrv4.sin_len = sizeof (serverAddrv4);
1085 #endif
1086     serverAddrv4->sin_family = AF_INET;
1087     serverAddrv4->sin_addr.s_addr = INADDR_ANY;
1088     serverAddrv4->sin_port = htons (plugin->port);
1089     addrlen = sizeof (struct sockaddr_in);
1090     serverAddr = (struct sockaddr *) serverAddrv4;
1091
1092 #if DEBUG_UDP
1093     LOG (GNUNET_ERROR_TYPE_DEBUG, "Binding to IPv4 port %d\n",
1094          ntohs (serverAddrv4->sin_port));
1095 #endif
1096     tries = 0;
1097     while (GNUNET_NETWORK_socket_bind (plugin->sockv4, serverAddr, addrlen) !=
1098            GNUNET_OK)
1099     {
1100       serverAddrv4->sin_port = htons (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, 33537) + 32000);   /* Find a good, non-root port */
1101 #if DEBUG_UDP
1102       LOG (GNUNET_ERROR_TYPE_DEBUG, "IPv4 Binding failed, trying new port %d\n",
1103            ntohs (serverAddrv4->sin_port));
1104 #endif
1105       tries++;
1106       if (tries > 10)
1107       {
1108         GNUNET_NETWORK_socket_close (plugin->sockv4);
1109         plugin->sockv4 = NULL;
1110         break;
1111       }
1112     }
1113     if (plugin->sockv4 != NULL)
1114     {
1115       addrs[sockets_created] = (struct sockaddr *) serverAddrv4;
1116       addrlens[sockets_created] = sizeof (struct sockaddr_in);
1117       sockets_created++;
1118     }
1119   }
1120
1121   /* Create file descriptors */
1122   plugin->rs = GNUNET_NETWORK_fdset_create ();
1123   plugin->ws = GNUNET_NETWORK_fdset_create ();
1124   GNUNET_NETWORK_fdset_zero (plugin->rs);
1125   GNUNET_NETWORK_fdset_zero (plugin->ws);
1126   if (NULL != plugin->sockv4)
1127   {
1128     GNUNET_NETWORK_fdset_set (plugin->rs, plugin->sockv4);
1129     GNUNET_NETWORK_fdset_set (plugin->ws, plugin->sockv4);
1130   }
1131   if (NULL != plugin->sockv6)
1132   {
1133     GNUNET_NETWORK_fdset_set (plugin->rs, plugin->sockv6);
1134     GNUNET_NETWORK_fdset_set (plugin->ws, plugin->sockv6);
1135   }
1136
1137   if (sockets_created == 0)
1138     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _("Failed to open UDP sockets\n"));
1139
1140   plugin->select_task =
1141       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1142                                    GNUNET_SCHEDULER_NO_TASK,
1143                                    GNUNET_TIME_UNIT_FOREVER_REL, plugin->rs,
1144                                    plugin->ws, &udp_plugin_select, plugin);
1145
1146   plugin->nat = GNUNET_NAT_register (plugin->env->cfg,
1147                            GNUNET_NO, plugin->port,
1148                            sockets_created,
1149                            (const struct sockaddr **) addrs, addrlens,
1150                            &udp_nat_port_map_callback, NULL, plugin);
1151
1152   return sockets_created;
1153 }
1154
1155
1156 /**
1157  * The exported method. Makes the core api available via a global and
1158  * returns the udp transport API.
1159  *
1160  * @param cls our 'struct GNUNET_TRANSPORT_PluginEnvironment'
1161  * @return our 'struct GNUNET_TRANSPORT_PluginFunctions'
1162  */
1163 void *
1164 libgnunet_plugin_transport_udp_init (void *cls)
1165 {
1166   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1167   struct GNUNET_TRANSPORT_PluginFunctions *api;
1168   struct Plugin *plugin;
1169
1170   unsigned long long port;
1171   unsigned long long aport;
1172   unsigned long long broadcast;
1173   unsigned long long udp_max_bps;
1174   unsigned long long enable_v6;
1175   char * bind4_address;
1176   char * bind6_address;
1177   struct GNUNET_TIME_Relative interval;
1178
1179   struct sockaddr_in serverAddrv4;
1180   struct sockaddr_in6 serverAddrv6;
1181
1182   int res;
1183
1184   /* Get port number */
1185   if (GNUNET_OK !=
1186       GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp", "PORT",
1187                                              &port))
1188     port = 2086;
1189   if (GNUNET_OK !=
1190       GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp",
1191                                              "ADVERTISED_PORT", &aport))
1192     aport = port;
1193   if (port > 65535)
1194   {
1195     LOG (GNUNET_ERROR_TYPE_WARNING,
1196          _("Given `%s' option is out of range: %llu > %u\n"), "PORT", port,
1197          65535);
1198     return NULL;
1199   }
1200
1201   /* Protocols */
1202   if ((GNUNET_YES ==
1203        GNUNET_CONFIGURATION_get_value_yesno (env->cfg, "nat",
1204                                              "DISABLEV6")))
1205   {
1206     enable_v6 = GNUNET_NO;
1207   }
1208   else
1209     enable_v6 = GNUNET_YES;
1210
1211
1212   /* Addresses */
1213   memset (&serverAddrv6, 0, sizeof (serverAddrv6));
1214   memset (&serverAddrv4, 0, sizeof (serverAddrv4));
1215
1216   if (GNUNET_YES ==
1217       GNUNET_CONFIGURATION_get_value_string (env->cfg, "transport-udp",
1218                                              "BINDTO", &bind4_address))
1219   {
1220     LOG (GNUNET_ERROR_TYPE_DEBUG,
1221          "Binding udp plugin to specific address: `%s'\n",
1222          bind4_address);
1223     if (1 != inet_pton (AF_INET, bind4_address, &serverAddrv4.sin_addr))
1224     {
1225       GNUNET_free (bind4_address);
1226       return NULL;
1227     }
1228   }
1229
1230   if (GNUNET_YES ==
1231       GNUNET_CONFIGURATION_get_value_string (env->cfg, "transport-udp",
1232                                              "BINDTO6", &bind6_address))
1233   {
1234     LOG (GNUNET_ERROR_TYPE_DEBUG,
1235          "Binding udp plugin to specific address: `%s'\n",
1236          bind6_address);
1237     if (1 !=
1238         inet_pton (AF_INET6, bind6_address, &serverAddrv6.sin6_addr))
1239     {
1240       LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid IPv6 address: `%s'\n"),
1241            bind6_address);
1242       GNUNET_free_non_null (bind4_address);
1243       GNUNET_free (bind6_address);
1244       return NULL;
1245     }
1246   }
1247
1248
1249   /* Enable neighbour discovery */
1250   broadcast = GNUNET_CONFIGURATION_get_value_yesno (env->cfg, "transport-udp",
1251                                             "BROADCAST");
1252   if (broadcast == GNUNET_SYSERR)
1253     broadcast = GNUNET_NO;
1254
1255   if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_time (env->cfg, "transport-udp",
1256                                            "BROADCAST_INTERVAL", &interval))
1257   {
1258     interval = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10);
1259   }
1260
1261   /* Maximum datarate */
1262   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp",
1263                                              "MAX_BPS", &udp_max_bps))
1264   {
1265     udp_max_bps = 1024 * 1024 * 50;     /* 50 MB/s == infinity for practical purposes */
1266   }
1267
1268   plugin = GNUNET_malloc (sizeof (struct Plugin));
1269   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1270
1271   GNUNET_BANDWIDTH_tracker_init (&plugin->tracker,
1272                                  GNUNET_BANDWIDTH_value_init ((uint32_t)udp_max_bps), 30);
1273
1274
1275   plugin->sessions = GNUNET_CONTAINER_multihashmap_create (10);
1276   plugin->mst = GNUNET_SERVER_mst_create (&process_inbound_tokenized_messages, plugin);
1277   plugin->port = port;
1278   plugin->aport = aport;
1279   plugin->last_expected_delay = GNUNET_TIME_UNIT_SECONDS;
1280   plugin->broadcast_interval = interval;
1281   plugin->enable_ipv6 = enable_v6;
1282   plugin->env = env;
1283
1284   api->cls = plugin;
1285   api->send = NULL;
1286   api->disconnect = &udp_disconnect;
1287   api->address_pretty_printer = &udp_plugin_address_pretty_printer;
1288   api->address_to_string = &udp_address_to_string;
1289   api->check_address = &udp_plugin_check_address;
1290   api->get_session = &udp_plugin_get_session;
1291   api->send = &udp_plugin_send_wrapper;
1292   api->send_with_session = &udp_plugin_send;
1293
1294   LOG (GNUNET_ERROR_TYPE_DEBUG, "Setting up sockets\n");
1295   res = setup_sockets (plugin, &serverAddrv6, &serverAddrv4);
1296   if ((res == 0) || ((plugin->sockv4 == NULL) && (plugin->sockv6 == NULL)))
1297   {
1298     LOG (GNUNET_ERROR_TYPE_ERROR, "Failed to create network sockets, plugin failed\n");
1299     GNUNET_free (plugin);
1300     GNUNET_free (api);
1301     return NULL;
1302   }
1303
1304   LOG (GNUNET_ERROR_TYPE_DEBUG, "Starting broadcasting\n");
1305   if (broadcast == GNUNET_YES)
1306     setup_broadcast (plugin, &serverAddrv6, &serverAddrv4);
1307
1308
1309   GNUNET_free_non_null (bind4_address);
1310   GNUNET_free_non_null (bind6_address);
1311   return api;
1312 }
1313
1314 /**
1315  * The exported method. Makes the core api available via a global and
1316  * returns the udp transport API.
1317  *
1318  * @param cls our 'struct GNUNET_TRANSPORT_PluginEnvironment'
1319  * @return our 'struct GNUNET_TRANSPORT_PluginFunctions'
1320  */
1321 void *
1322 libgnunet_plugin_transport_udp_done (void *cls)
1323 {
1324   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1325   struct Plugin *plugin = api->cls;
1326
1327   stop_broadcast (plugin);
1328
1329   if (plugin->select_task != GNUNET_SCHEDULER_NO_TASK)
1330   {
1331     GNUNET_SCHEDULER_cancel (plugin->select_task);
1332     plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
1333   }
1334
1335   /* Closing sockets */
1336   if (plugin->sockv4 != NULL)
1337   {
1338     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (plugin->sockv4));
1339     plugin->sockv4 = NULL;
1340   }
1341   if (plugin->sockv6 != NULL)
1342   {
1343     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (plugin->sockv6));
1344     plugin->sockv6 = NULL;
1345   }
1346   GNUNET_NETWORK_fdset_destroy (plugin->rs);
1347   GNUNET_NETWORK_fdset_destroy (plugin->ws);
1348   GNUNET_NAT_unregister (plugin->nat);
1349
1350   if (plugin->mst != NULL)
1351   {
1352     GNUNET_SERVER_mst_destroy(plugin->mst);
1353     plugin->mst = NULL;
1354   }
1355
1356   /* Clean up leftover messages */
1357   struct UDPMessageWrapper *udpw = plugin->msg_head;
1358   while (udpw != NULL)
1359   {
1360     struct UDPMessageWrapper *tmp = udpw->next;
1361     GNUNET_CONTAINER_DLL_remove(plugin->msg_head, plugin->msg_tail, udpw);
1362     if (udpw->cont != NULL)
1363       udpw->cont (udpw->cont_cls, &udpw->session->target, GNUNET_SYSERR);
1364     GNUNET_free (udpw);
1365     udpw = tmp;
1366   }
1367
1368   /* Clean up sessions */
1369 #if DEBUG_UDP
1370   LOG (GNUNET_ERROR_TYPE_DEBUG,
1371        "Cleaning up sessions\n");
1372 #endif
1373   GNUNET_CONTAINER_multihashmap_iterate (plugin->sessions, &disconnect_and_free_it, plugin);
1374   GNUNET_CONTAINER_multihashmap_destroy (plugin->sessions);
1375
1376   plugin->nat = NULL;
1377   GNUNET_free (plugin);
1378   GNUNET_free (api);
1379   return NULL;
1380 }
1381
1382
1383 /* end of plugin_transport_udp.c */