doxygen
[oweals/gnunet.git] / src / transport / plugin_transport_udp.c
1 /*
2      This file is part of GNUnet
3      (C) 2010 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 2, 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 service
24  * @author Christian Grothoff
25  * @author Nathan Evans
26  */
27
28 #include "platform.h"
29 #include "gnunet_hello_lib.h"
30 #include "gnunet_connection_lib.h"
31 #include "gnunet_os_lib.h"
32 #include "gnunet_peerinfo_service.h"
33 #include "gnunet_protocols.h"
34 #include "gnunet_resolver_service.h"
35 #include "gnunet_server_lib.h"
36 #include "gnunet_service_lib.h"
37 #include "gnunet_signatures.h"
38 #include "gnunet_statistics_service.h"
39 #include "gnunet_transport_service.h"
40 #include "plugin_transport.h"
41 #include "transport.h"
42
43 #define DEBUG_UDP GNUNET_NO
44
45 /**
46  * Transport cost to peer, always 1 for UDP (direct connection)
47  */
48 #define UDP_DIRECT_DISTANCE 1
49
50 /**
51  * How long until we give up on transmitting the welcome message?
52  */
53 #define HOSTNAME_RESOLVE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
54
55
56 /**
57  * Message-Packet header.
58  */
59 struct UDPMessage
60 {
61   /**
62    * size of the message, in bytes, including this header.
63    */
64   struct GNUNET_MessageHeader header;
65
66   /**
67    * What is the identity of the sender (GNUNET_hash of public key)
68    */
69   struct GNUNET_PeerIdentity sender;
70
71 };
72
73
74 /**
75  * Network format for IPv4 addresses.
76  */
77 struct IPv4UdpAddress
78 {
79   /**
80    * IPv4 address, in network byte order.
81    */
82   uint32_t ipv4_addr;
83
84   /**
85    * Port number, in network byte order.
86    */
87   uint16_t u_port;
88
89 };
90
91
92 /**
93  * Network format for IPv6 addresses.
94  */
95 struct IPv6UdpAddress
96 {
97   /**
98    * IPv6 address.
99    */
100   unsigned char ipv6_addr[16];
101
102   /**
103    * Port number, in network byte order.
104    */
105   uint16_t u6_port;
106
107 };
108
109
110 /**
111  *
112  */
113 struct PrettyPrinterContext
114 {
115   /**
116    *
117    */
118   GNUNET_TRANSPORT_AddressStringCallback asc;
119
120   /**
121    * Closure for 'asc'.
122    */
123   void *asc_cls;
124
125   /**
126    *
127    */
128   uint16_t port;
129 };
130
131
132 /**
133  * Encapsulation of all of the state of the plugin.
134  */
135 struct Plugin
136 {
137   /**
138    * Our environment.
139    */
140   struct GNUNET_TRANSPORT_PluginEnvironment *env;
141
142   /**
143    * Handle for the statistics service.
144    */
145   struct GNUNET_STATISTICS_Handle *statistics;
146
147   /**
148    * Handle to the network service.
149    */
150   struct GNUNET_SERVICE_Context *service;
151
152   /**
153    * Handle for request of hostname resolution, non-NULL if pending.
154    */
155   struct GNUNET_RESOLVER_RequestHandle *hostname_dns;
156
157   /**
158    * FD Read set
159    */
160   struct GNUNET_NETWORK_FDSet *rs;
161
162   /**
163    * ID of task used to update our addresses when one expires.
164    */
165   GNUNET_SCHEDULER_TaskIdentifier address_update_task;
166
167   /**
168    * ID of select task
169    */
170   GNUNET_SCHEDULER_TaskIdentifier select_task;
171
172   /**
173    * Port that we are actually listening on.
174    */
175   uint16_t open_port;
176
177   /**
178    * Port that the user said we would have visible to the
179    * rest of the world.
180    */
181   uint16_t adv_port;
182
183 };
184
185 /* *********** globals ************* */
186
187 /**
188  * The socket that we transmit all data with
189  */
190 static struct GNUNET_NETWORK_Handle *udp_sock;
191
192 /**
193  * Disconnect from a remote node.
194  *
195  * @param cls closure ('struct Plugin'), unused
196  * @param target peer do disconnect
197  * @return GNUNET_OK on success, GNUNET_SYSERR if the operation failed
198  */
199 void
200 udp_disconnect (void *cls, 
201                 const struct GNUNET_PeerIdentity *target)
202 {
203   /* nothing to do, UDP is stateless */
204 }
205
206 /**
207  * Shutdown the server process (stop receiving inbound traffic). Maybe
208  * restarted later!
209  *
210  * @param cls closure, the 'struct Plugin*'
211  */
212 static int
213 udp_transport_server_stop (void *cls)
214 {
215   struct Plugin *plugin = cls;
216   int ret;
217
218   GNUNET_assert (udp_sock != NULL);
219   if (plugin->select_task != GNUNET_SCHEDULER_NO_TASK)
220     {
221       GNUNET_SCHEDULER_cancel (plugin->env->sched, plugin->select_task);
222       plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
223     }
224
225   ret = GNUNET_NETWORK_socket_close (udp_sock);
226   if (ret != GNUNET_SYSERR)
227     udp_sock = NULL;
228   return ret;
229 }
230
231 /**
232  * Function that can be used by the transport service to transmit
233  * a message using the plugin.
234  *
235  * @param cls closure, the 'struct Plugin*'
236  * @param target who should receive this message (ignored by UDP)
237  * @param msgbuf one or more GNUNET_MessageHeader(s) strung together
238  * @param msgbuf_size the size of the msgbuf to send
239  * @param priority how important is the message (ignored by UDP)
240  * @param timeout when should we time out (give up) if we can not transmit?
241  * @param session which session must be used (always NULL for UDP)
242  * @param addr the addr to send the message to, needs to be a sockaddr for us
243  * @param addrlen the len of addr
244  * @param force_address GNUNET_YES if the plugin MUST use the given address,
245  *                GNUNET_NO means the plugin may use any other address and
246  *                GNUNET_SYSERR means that only reliable existing
247  *                bi-directional connections should be used (regardless
248  *                of address)
249  * @param cont continuation to call once the message has
250  *        been transmitted (or if the transport is ready
251  *        for the next transmission call; or if the
252  *        peer disconnected...)
253  * @param cont_cls closure for cont
254  *
255  * @return the number of bytes written, -1 on error (in this case, cont is not called)
256  */
257 static ssize_t
258 udp_plugin_send (void *cls,
259                  const struct GNUNET_PeerIdentity *target,
260                  const char *msgbuf,
261                  size_t msgbuf_size,
262                  unsigned int priority,
263                  struct GNUNET_TIME_Relative timeout,
264                  struct Session *session,
265                  const void *addr,
266                  size_t addrlen,
267                  int force_address,
268                  GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
269 {
270   struct Plugin *plugin = cls;
271   struct UDPMessage *message;
272   int ssize;
273   ssize_t sent;
274   int af;
275   const void *sb;
276   size_t sbs;
277   struct sockaddr_in a4;
278   struct sockaddr_in6 a6;
279   const struct IPv4UdpAddress *t4;
280   const struct IPv6UdpAddress *t6;
281
282   GNUNET_assert (NULL == session);
283   GNUNET_assert(udp_sock != NULL);
284   if ( (addr == NULL) || (addrlen == 0) )
285     {
286 #if DEBUG_UDP
287   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "udp", _
288                    ("udp_plugin_send called without address, returning!\n"));
289 #endif
290       return -1; /* Can never send if we don't have an address!! */
291     }
292   if (force_address == GNUNET_SYSERR)
293     return -1; /* never reliable */
294
295   if (addrlen == sizeof (struct IPv6UdpAddress))
296     {
297       t6 = addr;
298       af = AF_INET6;
299       memset (&a6, 0, sizeof (a6));
300       a6.sin6_family = AF_INET6;
301       a6.sin6_port = t6->u6_port;
302       memcpy (a6.sin6_addr.s6_addr,
303               t6->ipv6_addr,
304               16);      
305       sb = &a6;
306       sbs = sizeof (a6);
307     }
308   else if (addrlen == sizeof (struct IPv4UdpAddress))
309     {
310       t4 = addr;
311       af = AF_INET;
312       memset (&a4, 0, sizeof (a4));
313       a4.sin_family = AF_INET;
314       a4.sin_port = t4->u_port;
315       a4.sin_addr.s_addr = t4->ipv4_addr;
316       sb = &a4;
317       sbs = sizeof (a4);
318     }
319   else
320     {
321       GNUNET_break_op (0);
322       return -1;
323     }
324
325   /* Build the message to be sent */
326   message = GNUNET_malloc (sizeof (struct UDPMessage) + msgbuf_size);
327   ssize = sizeof (struct UDPMessage) + msgbuf_size;
328
329 #if DEBUG_UDP
330   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "udp", 
331                    "In udp_send, ssize is %d, sending message to `%s'\n", 
332                    ssize, 
333                    GNUNET_a2s(sb, sbs));
334 #endif
335   message->header.size = htons (ssize);
336   message->header.type = htons (0);
337   memcpy (&message->sender, plugin->env->my_identity,
338           sizeof (struct GNUNET_PeerIdentity));
339   memcpy (&message[1], msgbuf, msgbuf_size);
340   sent =
341     GNUNET_NETWORK_socket_sendto (udp_sock, message, ssize,
342                                   sb, sbs);
343   if ( (cont != NULL) &&
344        (sent != -1) )
345     cont (cont_cls, target, GNUNET_OK);
346   GNUNET_free (message);
347   return sent;
348 }
349
350
351 /**
352  * Add the IP of our network interface to the list of
353  * our external IP addresses.
354  *
355  * @param cls closure (the 'struct Plugin*')
356  * @param name name of the interface (can be NULL for unknown)
357  * @param isDefault is this presumably the default interface
358  * @param addr address of this interface (can be NULL for unknown or unassigned)
359  * @param addrlen length of the address
360  * @return GNUNET_OK to continue iterating
361  */
362 static int
363 process_interfaces (void *cls,
364                     const char *name,
365                     int isDefault,
366                     const struct sockaddr *addr, socklen_t addrlen)
367 {
368   struct Plugin *plugin = cls;
369   int af;
370   struct IPv4UdpAddress t4;
371   struct IPv6UdpAddress t6;
372   void *arg;
373   uint16_t args;
374
375   af = addr->sa_family;
376   if (af == AF_INET)
377     {
378       t4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
379       t4.u_port = htons (plugin->adv_port);
380       arg = &t4;
381       args = sizeof (t4);
382     }
383   else if (af == AF_INET6)
384     {
385       memcpy (t6.ipv6_addr,
386               ((struct sockaddr_in6 *) addr)->sin6_addr.s6_addr,
387               16);
388       t6.u6_port = htons (plugin->adv_port);
389       arg = &t6;
390       args = sizeof (t6);
391     }
392   else
393     {
394       GNUNET_break (0);
395       return GNUNET_OK;
396     }
397   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO |
398                    GNUNET_ERROR_TYPE_BULK,
399                    "udp", 
400                    _("Found address `%s' (%s)\n"),
401                    GNUNET_a2s (addr, addrlen), 
402                    name);
403   plugin->env->notify_address (plugin->env->cls,
404                                "udp",
405                                arg, args, GNUNET_TIME_UNIT_FOREVER_REL);
406   return GNUNET_OK;
407 }
408
409
410 /**
411  * Function called by the resolver for each address obtained from DNS
412  * for our own hostname.  Add the addresses to the list of our
413  * external IP addresses.
414  *
415  * @param cls closure
416  * @param addr one of the addresses of the host, NULL for the last address
417  * @param addrlen length of the address
418  */
419 static void
420 process_hostname_ips (void *cls,
421                       const struct sockaddr *addr, socklen_t addrlen)
422 {
423   struct Plugin *plugin = cls;
424
425   if (addr == NULL)
426     {
427       plugin->hostname_dns = NULL;
428       return;
429     }
430   process_interfaces (plugin, "<hostname>", GNUNET_YES, addr, addrlen);
431 }
432
433
434 /*
435  * @param cls the plugin handle
436  * @param tc the scheduling context (for rescheduling this function again)
437  *
438  * We have been notified that our writeset has something to read.  Presumably
439  * select has been called already, so we can go ahead and start reading from
440  * the socket immediately.  Then we check if there is more to be read by
441  * calling select ourselves while there is stuff on the wire.  Then reschedule
442  * this function to be called again once more is available.
443  *
444  */
445 static void
446 udp_plugin_select (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
447 {
448   struct Plugin *plugin = cls;
449   char *buf;
450   struct UDPMessage *msg;
451   struct GNUNET_PeerIdentity *sender;
452   unsigned int buflen;
453   socklen_t fromlen;
454   struct sockaddr_storage addr;
455   ssize_t ret;
456   int offset;
457   int count;
458   int tsize;
459   char *msgbuf;
460   const struct GNUNET_MessageHeader *currhdr;
461   struct IPv4UdpAddress t4;
462   struct IPv6UdpAddress t6;
463   const struct sockaddr_in *s4;
464   const struct sockaddr_in6 *s6;
465   const void *ca;
466   size_t calen;
467
468 #if DEBUG_UDP
469       GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "udp", _
470                        ("entered select...\n"));
471 #endif
472
473       buflen = GNUNET_NETWORK_socket_recvfrom_amount (udp_sock);
474
475 #if DEBUG_UDP
476       GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "udp", _
477                        ("we expect to read %u bytes\n"), buflen);
478 #endif
479
480     if (buflen == GNUNET_NO)
481       return;
482
483     buf = GNUNET_malloc (buflen);
484     fromlen = sizeof (addr);
485
486     memset (&addr, 0, fromlen);
487     ret =
488       GNUNET_NETWORK_socket_recvfrom (udp_sock, buf, buflen,
489                                       (struct sockaddr *) &addr, &fromlen);
490
491 #if DEBUG_UDP
492     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "udp", _
493                      ("socket_recv returned %u, src_addr_len is %u\n"), ret,
494                      fromlen);
495 #endif
496
497     if (ret <= 0)
498       {
499         GNUNET_free (buf);
500         return;
501       }
502     msg = (struct UDPMessage *) buf;
503
504 #if DEBUG_UDP
505     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "udp", _
506                      ("header reports message size of %d\n"),
507                      ntohs (msg->header.size));
508
509     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "udp", _
510                      ("header reports message type of %d\n"),
511                      ntohs (msg->header.type));
512 #endif
513     if (ntohs (msg->header.size) < sizeof (struct UDPMessage))
514       {
515         GNUNET_free (buf);
516         GNUNET_NETWORK_fdset_zero (plugin->rs);
517         GNUNET_NETWORK_fdset_set (plugin->rs, udp_sock);
518         return;
519       }
520     msgbuf = (char *)&msg[1];
521     sender = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity));
522     memcpy (sender, &msg->sender, sizeof (struct GNUNET_PeerIdentity));
523
524     offset = 0;
525     count = 0;
526     tsize = ntohs (msg->header.size) - sizeof(struct UDPMessage);
527 #if DEBUG_UDP
528     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "UDP", _
529                      ("offset is %d, tsize is %d (UDPMessage size is %d)\n"),
530                      offset, tsize, sizeof(struct UDPMessage));
531 #endif
532
533     if (fromlen == sizeof (struct sockaddr_in))
534       {
535         s4 = (const struct sockaddr_in*) &addr;
536         t4.u_port = s4->sin_port;
537         t4.ipv4_addr = s4->sin_addr.s_addr;
538         ca = &t4;
539         calen = sizeof (struct IPv4UdpAddress);
540       }
541     else if (fromlen == sizeof (struct sockaddr_in6))
542       {
543         s6 = (const struct sockaddr_in6*) &addr;
544         t6.u6_port = s6->sin6_port;
545         memcpy (t6.ipv6_addr,
546                 s6->sin6_addr.s6_addr,
547                 16);
548         ca = &t6;
549         calen = sizeof (struct IPv6UdpAddress);
550       }
551     else
552       {
553         GNUNET_break (0);
554         ca = NULL;
555         calen = 0;
556       }
557     while (offset < tsize)
558       {
559         currhdr = (struct GNUNET_MessageHeader *)&msgbuf[offset];
560 #if DEBUG_UDP
561     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "udp", _
562                      ("processing msg %d: type %d, size %d at offset %d\n"),
563                      count, ntohs(currhdr->type), ntohs(currhdr->size), offset);
564 #endif
565         plugin->env->receive (plugin->env->cls,
566                               sender, currhdr, UDP_DIRECT_DISTANCE, 
567                               NULL, ca, calen);
568         offset += ntohs(currhdr->size);
569 #if DEBUG_UDP
570     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "udp", _
571                      ("offset now %d, tsize %d\n"),
572                      offset, tsize);
573 #endif
574         count++;
575       }
576
577     GNUNET_free (sender);
578     GNUNET_free (buf);
579
580   plugin->select_task =
581     GNUNET_SCHEDULER_add_select (plugin->env->sched,
582                                  GNUNET_SCHEDULER_PRIORITY_DEFAULT,
583                                  GNUNET_SCHEDULER_NO_TASK,
584                                  GNUNET_TIME_UNIT_FOREVER_REL, plugin->rs,
585                                  NULL, &udp_plugin_select, plugin);
586
587 }
588
589 /**
590  * Create a UDP socket.  If possible, use IPv6, otherwise
591  * try IPv4.
592  * @param cls closure, the 'struct Plugin*'
593  */
594 static struct GNUNET_NETWORK_Handle *
595 udp_transport_server_start (void *cls)
596 {
597   struct Plugin *plugin = cls;
598   struct GNUNET_NETWORK_Handle *desc;
599   struct sockaddr_in serverAddrv4;
600   struct sockaddr_in6 serverAddrv6;
601   struct sockaddr *serverAddr;
602   socklen_t addrlen;
603
604   desc = NULL;
605   if (GNUNET_YES !=
606       GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg, "GNUNETD",
607                                             "DISABLE-IPV6"))
608     {
609       desc = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_DGRAM, 17);
610       if (desc != NULL)
611         {
612           memset (&serverAddrv6, 0, sizeof (serverAddrv6));
613 #if HAVE_SOCKADDR_IN_SIN_LEN
614           serverAddrv6.sin6_len = sizeof (serverAddrv6);
615 #endif
616           serverAddrv6.sin6_family = AF_INET6;
617           serverAddrv6.sin6_addr = in6addr_any;
618           serverAddrv6.sin6_port = htons (plugin->open_port);
619           addrlen = sizeof (serverAddrv6);
620           serverAddr = (struct sockaddr *) &serverAddrv6;
621         }
622     }
623   if (NULL == desc)
624     {
625       desc = GNUNET_NETWORK_socket_create (PF_INET, SOCK_DGRAM, 17);
626       if (NULL == desc)
627         {
628           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "udp", "socket");
629           return NULL;
630         }
631       else
632         {
633           memset (&serverAddrv4, 0, sizeof (serverAddrv4));
634 #if HAVE_SOCKADDR_IN_SIN_LEN
635           serverAddrv4.sin_len = sizeof (serverAddrv4);
636 #endif
637           serverAddrv4.sin_family = AF_INET;
638           serverAddrv4.sin_addr.s_addr = INADDR_ANY;
639           serverAddrv4.sin_port = htons (plugin->open_port);
640           addrlen = sizeof (serverAddrv4);
641           serverAddr = (struct sockaddr *) &serverAddrv4;
642         }
643     }
644
645   if (desc != NULL)
646     {
647       GNUNET_assert (GNUNET_NETWORK_socket_bind (desc, serverAddr, addrlen) ==
648                      GNUNET_OK);
649     }
650
651   plugin->rs = GNUNET_NETWORK_fdset_create ();
652
653   GNUNET_NETWORK_fdset_zero (plugin->rs);
654   GNUNET_NETWORK_fdset_set (plugin->rs, desc);
655
656   plugin->select_task =
657     GNUNET_SCHEDULER_add_select (plugin->env->sched,
658                                  GNUNET_SCHEDULER_PRIORITY_DEFAULT,
659                                  GNUNET_SCHEDULER_NO_TASK,
660                                  GNUNET_TIME_UNIT_FOREVER_REL, plugin->rs,
661                                  NULL, &udp_plugin_select, plugin);
662
663   return desc;
664 }
665
666
667 /**
668  * Check if the given port is plausible (must be either
669  * our listen port or our advertised port).  If it is
670  * neither, we return one of these two ports at random.
671  *
672  * @return either in_port or a more plausible port
673  */
674 static uint16_t
675 check_port (struct Plugin *plugin, uint16_t in_port)
676 {
677   if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
678     return in_port;
679   return (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
680                                     2) == 0)
681     ? plugin->open_port : plugin->adv_port;
682 }
683
684
685 /**
686  * Another peer has suggested an address for this peer and transport
687  * plugin.  Check that this could be a valid address.  This function
688  * is not expected to 'validate' the address in the sense of trying to
689  * connect to it but simply to see if the binary format is technically
690  * legal for establishing a connection.
691  *
692  * @param cls handle to Plugin
693  * @param addr address to check
694  * @param addrlen length of addr
695  * @return GNUNET_OK if this is a plausible address for this peer
696  *         and transport, GNUNET_SYSERR if not
697  */
698 static int
699 udp_check_address (void *cls, void *addr, size_t addrlen)
700 {
701   struct Plugin *plugin = cls;
702   struct IPv4UdpAddress *v4;
703   struct IPv6UdpAddress *v6;
704
705   if ((addrlen != sizeof (struct IPv4UdpAddress)) &&
706       (addrlen != sizeof (struct IPv6UdpAddress)))
707     {
708       GNUNET_break_op (0);
709       return GNUNET_SYSERR;
710     }
711   if (addrlen == sizeof (struct IPv4UdpAddress))
712     {
713       v4 = (struct IPv4UdpAddress *) addr;
714       v4->u_port = htons (check_port (plugin, ntohs (v4->u_port)));
715     }
716   else
717     {
718       v6 = (struct IPv6UdpAddress *) addr;
719       v6->u6_port = htons (check_port (plugin, ntohs (v6->u6_port)));
720     }
721   return GNUNET_OK;
722 }
723
724
725 /**
726  * Append our port and forward the result.
727  */
728 static void
729 append_port (void *cls, const char *hostname)
730 {
731   struct PrettyPrinterContext *ppc = cls;
732   char *ret;
733
734   if (hostname == NULL)
735     {
736       ppc->asc (ppc->asc_cls, NULL);
737       GNUNET_free (ppc);
738       return;
739     }
740   GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
741   ppc->asc (ppc->asc_cls, ret);
742   GNUNET_free (ret);
743 }
744
745
746 /**
747  * Convert the transports address to a nice, human-readable
748  * format.
749  *
750  * @param cls closure
751  * @param type name of the transport that generated the address
752  * @param addr one of the addresses of the host, NULL for the last address
753  *        the specific address format depends on the transport
754  * @param addrlen length of the address
755  * @param numeric should (IP) addresses be displayed in numeric form?
756  * @param timeout after how long should we give up?
757  * @param asc function to call on each string
758  * @param asc_cls closure for asc
759  */
760 static void
761 udp_plugin_address_pretty_printer (void *cls,
762                                    const char *type,
763                                    const void *addr,
764                                    size_t addrlen,
765                                    int numeric,
766                                    struct GNUNET_TIME_Relative timeout,
767                                    GNUNET_TRANSPORT_AddressStringCallback asc,
768                                    void *asc_cls)
769 {
770   struct Plugin *plugin = cls;
771   struct PrettyPrinterContext *ppc;
772   const void *sb;
773   struct sockaddr_in a4;
774   struct sockaddr_in6 a6;
775   const struct IPv4UdpAddress *t4;
776   const struct IPv6UdpAddress *t6;
777   int af;
778   size_t sbs;
779   uint16_t port;
780
781   if (addrlen == sizeof (struct IPv6UdpAddress))
782     {
783       t6 = addr;
784       af = AF_INET6;
785       memset (&a6, 0, sizeof (a6));
786       a6.sin6_family = AF_INET6;
787       a6.sin6_port = t6->u6_port;
788       port = ntohs (t6->u6_port);
789       memcpy (a6.sin6_addr.s6_addr,
790               t6->ipv6_addr,
791               16);      
792       sb = &a6;
793       sbs = sizeof (a6);
794     }
795   else if (addrlen == sizeof (struct IPv4UdpAddress))
796     {
797       t4 = addr;
798       af = AF_INET;
799       memset (&a4, 0, sizeof (a4));
800       a4.sin_family = AF_INET;
801       a4.sin_port = t4->u_port;
802       a4.sin_addr.s_addr = t4->ipv4_addr;
803       port = ntohs (t4->u_port);
804       sb = &a4;
805       sbs = sizeof (a4);
806     }
807   else
808     {
809       /* invalid address */
810       GNUNET_break_op (0);
811       asc (asc_cls, NULL);
812       return;
813     }
814   ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
815   ppc->asc = asc;
816   ppc->asc_cls = asc_cls;
817   ppc->port = port;
818   GNUNET_RESOLVER_hostname_get (plugin->env->sched,
819                                 plugin->env->cfg,
820                                 sb,
821                                 sbs,
822                                 !numeric, timeout, &append_port, ppc);
823 }
824
825
826
827 /**
828  * Function called for a quick conversion of the binary address to
829  * a numeric address.  Note that the caller must not free the 
830  * address and that the next call to this function is allowed
831  * to override the address again.
832  *
833  * @param cls closure
834  * @param addr binary address
835  * @param addrlen length of the address
836  * @return string representing the same address 
837  */
838 static const char* 
839 udp_address_to_string (void *cls,
840                        const void *addr,
841                        size_t addrlen)
842 {
843   static char buf[INET6_ADDRSTRLEN];
844   const void *sb;
845   struct sockaddr_in a4;
846   struct sockaddr_in6 a6;
847   const struct IPv4UdpAddress *t4;
848   const struct IPv6UdpAddress *t6;
849   int af;
850
851   if (addrlen == sizeof (struct IPv6UdpAddress))
852     {
853       t6 = addr;
854       af = AF_INET6;
855       memset (&a6, 0, sizeof (a6));
856       a6.sin6_family = AF_INET6;
857       a6.sin6_port = t6->u6_port;
858       memcpy (a6.sin6_addr.s6_addr,
859               t6->ipv6_addr,
860               16);      
861       sb = &a6;
862     }
863   else if (addrlen == sizeof (struct IPv4UdpAddress))
864     {
865       t4 = addr;
866       af = AF_INET;
867       memset (&a4, 0, sizeof (a4));
868       a4.sin_family = AF_INET;
869       a4.sin_port = t4->u_port;
870       a4.sin_addr.s_addr = t4->ipv4_addr;
871       sb = &a4;
872     }
873   else
874     return NULL;
875   
876   return inet_ntop (af, sb, buf, INET6_ADDRSTRLEN);
877 }
878
879
880 /**
881  * The exported method. Makes the core api available via a global and
882  * returns the udp transport API.
883  *
884  * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
885  * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
886  */
887 void *
888 libgnunet_plugin_transport_udp_init (void *cls)
889 {
890   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
891   struct GNUNET_TRANSPORT_PluginFunctions *api;
892   struct Plugin *plugin;
893   struct GNUNET_SERVICE_Context *service;
894   unsigned long long aport;
895   unsigned long long bport;
896   unsigned long long mtu;
897
898   service = GNUNET_SERVICE_start ("transport-udp", env->sched, env->cfg);
899   if (service == NULL)
900     {
901       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "udp", _
902                        ("Failed to start service for `%s' transport plugin.\n"),
903                        "udp");
904       return NULL;
905     }
906   aport = 0;
907   if ((GNUNET_OK !=
908        GNUNET_CONFIGURATION_get_value_number (env->cfg,
909                                               "transport-udp",
910                                               "PORT",
911                                               &bport)) ||
912       (bport > 65535) ||
913       ((GNUNET_OK ==
914         GNUNET_CONFIGURATION_get_value_number (env->cfg,
915                                                "transport-udp",
916                                                "ADVERTISED-PORT",
917                                                &aport)) && (aport > 65535)))
918     {
919       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
920                        "udp",
921                        _
922                        ("Require valid port number for service `%s' in configuration!\n"),
923                        "transport-udp");
924       GNUNET_SERVICE_stop (service);
925       return NULL;
926     }
927   if (aport == 0)
928     aport = bport;
929
930   mtu = 1240;
931   if (mtu < 1200)
932     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
933                      "udp",
934                      _("MTU %llu for `%s' is probably too low!\n"), mtu,
935                      "UDP");
936
937   plugin = GNUNET_malloc (sizeof (struct Plugin));
938   plugin->open_port = bport;
939   plugin->adv_port = aport;
940   plugin->env = env;
941   plugin->statistics = NULL;
942   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
943   api->cls = plugin;
944
945   api->send = &udp_plugin_send;
946   api->disconnect = &udp_disconnect;
947   api->address_pretty_printer = &udp_plugin_address_pretty_printer;
948   api->check_address = &udp_check_address;
949   api->address_to_string = &udp_address_to_string;
950   plugin->service = service;
951
952   /* FIXME: do the two calls below periodically again and
953      not just once (since the info we get might change...) */
954   GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);
955   plugin->hostname_dns = GNUNET_RESOLVER_hostname_resolve (env->sched,
956                                                            env->cfg,
957                                                            AF_UNSPEC,
958                                                            HOSTNAME_RESOLVE_TIMEOUT,
959                                                            &process_hostname_ips,
960                                                            plugin);
961
962   udp_sock = udp_transport_server_start (plugin);
963
964   GNUNET_assert (udp_sock != NULL);
965
966   return api;
967 }
968
969 void *
970 libgnunet_plugin_transport_udp_done (void *cls)
971 {
972   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
973   struct Plugin *plugin = api->cls;
974
975   udp_transport_server_stop (plugin);
976   if (NULL != plugin->hostname_dns)
977     {
978       GNUNET_RESOLVER_request_cancel (plugin->hostname_dns);
979       plugin->hostname_dns = NULL;
980     }
981   GNUNET_SERVICE_stop (plugin->service);
982
983   GNUNET_NETWORK_fdset_destroy (plugin->rs);
984   GNUNET_free (plugin);
985   GNUNET_free (api);
986   return NULL;
987 }
988
989 /* end of plugin_transport_udp.c */