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