fixing api related changes
[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  * Handle for request of hostname resolution, non-NULL if pending.
52  */
53 static struct GNUNET_RESOLVER_RequestHandle *hostname_dns;
54
55 /**
56  * Message-Packet header.
57  */
58 struct UDPMessage
59 {
60   /**
61    * size of the message, in bytes, including this header.
62    */
63   struct GNUNET_MessageHeader header;
64
65   /**
66    * What is the identity of the sender (GNUNET_hash of public key)
67    */
68   struct GNUNET_PeerIdentity sender;
69
70 };
71
72 /* Forward definition */
73 struct Plugin;
74
75 struct PrettyPrinterContext
76 {
77   GNUNET_TRANSPORT_AddressStringCallback asc;
78   void *asc_cls;
79   uint16_t port;
80 };
81
82 /**
83  * Encapsulation of all of the state of the plugin.
84  */
85 struct Plugin
86 {
87   /**
88    * Our environment.
89    */
90   struct GNUNET_TRANSPORT_PluginEnvironment *env;
91
92   /**
93    * Handle for the statistics service.
94    */
95   struct GNUNET_STATISTICS_Handle *statistics;
96
97   /**
98    * Handle to the network service.
99    */
100   struct GNUNET_SERVICE_Context *service;
101
102   /**
103    * ID of task used to update our addresses when one expires.
104    */
105   GNUNET_SCHEDULER_TaskIdentifier address_update_task;
106
107   /**
108    * ID of select task
109    */
110   GNUNET_SCHEDULER_TaskIdentifier select_task;
111
112   /**
113    * Port that we are actually listening on.
114    */
115   uint16_t open_port;
116
117   /**
118    * Port that the user said we would have visible to the
119    * rest of the world.
120    */
121   uint16_t adv_port;
122
123   /*
124    * FD Read set
125    */
126   struct GNUNET_NETWORK_FDSet *rs;
127
128 };
129
130 /* *********** globals ************* */
131
132 /**
133  * the socket that we transmit all data with
134  */
135 static struct GNUNET_NETWORK_Handle *udp_sock;
136
137 /**
138  * Disconnect from a remote node.
139  *
140  * @param tsession the session that is closed
141  * @return GNUNET_OK on success, GNUNET_SYSERR if the operation failed
142  */
143 void
144 udp_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
145 {
146   return;
147 }
148
149 /**
150  * Shutdown the server process (stop receiving inbound traffic). Maybe
151  * restarted later!
152  */
153 static int
154 udp_transport_server_stop (void *cls)
155 {
156   struct Plugin *plugin = cls;
157   GNUNET_assert (udp_sock != NULL);
158   if (plugin->select_task != GNUNET_SCHEDULER_NO_TASK)
159     {
160       GNUNET_SCHEDULER_cancel (plugin->env->sched, plugin->select_task);
161       plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
162     }
163
164   GNUNET_NETWORK_socket_close (udp_sock);
165   udp_sock = NULL;
166   return GNUNET_OK;
167 }
168
169 /**
170  * Function that can be used by the transport service to transmit
171  * a message using the plugin.
172  *
173  * @param cls closure
174  * @param target who should receive this message (ignored by UDP)
175  * @param msg the message to transmit
176  * @param priority how important is the message (ignored by UDP)
177  * @param timeout when should we time out (give up) if we can not transmit?
178  * @param addr the addr to send the message to, needs to be a sockaddr for us
179  * @param addrlen the len of addr
180  * @param force_address not used, we had better have an address to send to
181  *        because we are stateless!!
182  * @param cont continuation to call once the message has
183  *        been transmitted (or if the transport is ready
184  *        for the next transmission call; or if the
185  *        peer disconnected...)
186  * @param cont_cls closure for cont
187  *
188  * @return the number of bytes written
189  */
190
191 static ssize_t
192 udp_plugin_send (void *cls,
193                  const struct GNUNET_PeerIdentity *target,
194                  const struct GNUNET_MessageHeader *msg,
195                  unsigned int priority,
196                  struct GNUNET_TIME_Relative timeout,
197                  const void *addr,
198                  size_t addrlen,
199                  int force_address,
200                  GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
201 {
202   struct Plugin *plugin = cls;
203   struct UDPMessage *message;
204   int ssize;
205   ssize_t sent;
206
207   GNUNET_assert(udp_sock != NULL);
208   GNUNET_assert(addr != NULL);
209
210   /* Build the message to be sent */
211   message = GNUNET_malloc (sizeof (struct UDPMessage) + ntohs (msg->size));
212   ssize = sizeof (struct UDPMessage) + ntohs (msg->size);
213
214 #if DEBUG_UDP
215   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "udp", _
216                    ("In udp_send, ssize is %d\n"), ssize);
217 #endif
218   message->header.size = htons (ssize);
219   message->header.type = htons (0);
220   memcpy (&message->sender, plugin->env->my_identity,
221           sizeof (struct GNUNET_PeerIdentity));
222   memcpy (&message[1], msg, ntohs (msg->size));
223
224   /* Actually send the message */
225   sent =
226     GNUNET_NETWORK_socket_sendto (udp_sock, message, ssize,
227                                   addr,
228                                   addrlen);
229
230   if (cont != NULL)
231     {
232       if (sent == GNUNET_SYSERR)
233         cont (cont_cls, target, GNUNET_SYSERR);
234       else
235         cont (cont_cls, target, GNUNET_OK);
236     }
237   GNUNET_free (message);
238   return sent;
239 }
240
241
242 /*
243  * @param cls the plugin handle
244  * @param tc the scheduling context (for rescheduling this function again)
245  *
246  * We have been notified that our writeset has something to read.  Presumably
247  * select has been called already, so we can go ahead and start reading from
248  * the socket immediately.  Then we check if there is more to be read by
249  * calling select ourselves while there is stuff on the wire.  Then reschedule
250  * this function to be called again once more is available.
251  *
252  */
253 static void
254 udp_plugin_select (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
255 {
256   struct Plugin *plugin = cls;
257   struct GNUNET_TIME_Relative timeout =
258     GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 500);
259   char *buf;
260   struct UDPMessage *msg;
261   const struct GNUNET_MessageHeader *hdr;
262   struct GNUNET_PeerIdentity *sender;
263   unsigned int buflen;
264   socklen_t fromlen;
265   struct sockaddr_storage addr;
266   ssize_t ret;
267
268   do
269     {
270       buflen = GNUNET_NETWORK_socket_recvfrom_amount (udp_sock);
271
272 #if DEBUG_UDP
273       GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "udp", _
274                        ("we expect to read %u bytes\n"), buflen);
275 #endif
276
277       if (buflen == GNUNET_NO)
278         return;
279
280       buf = GNUNET_malloc (buflen);
281       fromlen = sizeof (addr);
282 #if DEBUG_UDP
283       GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "udp", _
284                        ("src_addr_len is %u\n"), fromlen);
285 #endif
286       memset (&addr, 0, fromlen);
287       ret =
288         GNUNET_NETWORK_socket_recvfrom (udp_sock, buf, buflen,
289                                         (struct sockaddr *) &addr, &fromlen);
290
291 #if DEBUG_UDP
292       GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "udp", _
293                        ("socket_recv returned %u, src_addr_len is %u\n"), ret,
294                        fromlen);
295 #endif
296
297       if (ret <= 0)
298         {
299           GNUNET_free (buf);
300           return;
301         }
302       msg = (struct UDPMessage *) buf;
303
304 #if DEBUG_UDP
305       GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "udp", _
306                        ("header reports message size of %d\n"),
307                        ntohs (msg->header.size));
308
309       GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "udp", _
310                        ("header reports message type of %d\n"),
311                        ntohs (msg->header.type));
312 #endif
313       if (ntohs (msg->header.size) < sizeof (struct UDPMessage))
314         {
315           GNUNET_free (buf);
316           GNUNET_NETWORK_fdset_zero (plugin->rs);
317           GNUNET_NETWORK_fdset_set (plugin->rs, udp_sock);
318           break;
319         }
320       hdr = (const struct GNUNET_MessageHeader *) &msg[1];
321       sender = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity));
322       memcpy (sender, &msg->sender, sizeof (struct GNUNET_PeerIdentity));
323
324 #if DEBUG_UDP
325       GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "udp", _
326                        ("msg reports message size of %d\n"),
327                        ntohs (hdr->size));
328
329       GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "udp", _
330                        ("msg reports message type of %d\n"),
331                        ntohs (hdr->type));
332 #endif
333
334       plugin->env->receive (plugin->env->cls, UDP_DIRECT_DISTANCE,(char *)&addr, fromlen, sender,
335                               &msg->header);
336
337       GNUNET_free (sender);
338       GNUNET_free (buf);
339
340     }
341   while (GNUNET_NETWORK_socket_select (plugin->rs,
342                                        NULL,
343                                        NULL,
344                                        timeout) > 0
345          && GNUNET_NETWORK_fdset_isset (plugin->rs, udp_sock));
346
347   plugin->select_task =
348     GNUNET_SCHEDULER_add_select (plugin->env->sched,
349                                  GNUNET_SCHEDULER_PRIORITY_DEFAULT,
350                                  GNUNET_SCHEDULER_NO_TASK,
351                                  GNUNET_TIME_UNIT_FOREVER_REL, plugin->rs,
352                                  NULL, &udp_plugin_select, plugin);
353
354 }
355
356 /**
357  * Create a UDP socket.  If possible, use IPv6, otherwise
358  * try IPv4.
359  */
360 static struct GNUNET_NETWORK_Handle *
361 udp_transport_server_start (void *cls)
362 {
363   struct Plugin *plugin = cls;
364   struct GNUNET_NETWORK_Handle *desc;
365   struct sockaddr_in serverAddrv4;
366   struct sockaddr_in6 serverAddrv6;
367   struct sockaddr *serverAddr;
368   socklen_t addrlen;
369
370   desc = NULL;
371   if (GNUNET_YES !=
372       GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg, "GNUNETD",
373                                             "DISABLE-IPV6"))
374     {
375       desc = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_DGRAM, 17);
376       if (desc != NULL)
377         {
378           memset (&serverAddrv6, 0, sizeof (serverAddrv6));
379 #if HAVE_SOCKADDR_IN_SIN_LEN
380           serverAddrv6.sin6_len = sizeof (serverAddrv6);
381 #endif
382           serverAddrv6.sin6_family = AF_INET6;
383           serverAddrv6.sin6_addr = in6addr_any;
384           serverAddrv6.sin6_port = htons (plugin->open_port);
385           addrlen = sizeof (serverAddrv6);
386           serverAddr = (struct sockaddr *) &serverAddrv6;
387         }
388     }
389   if (NULL == desc)
390     {
391       desc = GNUNET_NETWORK_socket_create (PF_INET, SOCK_DGRAM, 17);
392       if (NULL == desc)
393         {
394           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "udp", "socket");
395           return NULL;
396         }
397       else
398         {
399           memset (&serverAddrv4, 0, sizeof (serverAddrv4));
400 #if HAVE_SOCKADDR_IN_SIN_LEN
401           serverAddrv4.sin_len = sizeof (serverAddrv4);
402 #endif
403           serverAddrv4.sin_family = AF_INET;
404           serverAddrv4.sin_addr.s_addr = INADDR_ANY;
405           serverAddrv4.sin_port = htons (plugin->open_port);
406           addrlen = sizeof (serverAddrv4);
407           serverAddr = (struct sockaddr *) &serverAddrv4;
408         }
409     }
410
411   if (desc != NULL)
412     {
413       GNUNET_assert (GNUNET_NETWORK_socket_bind (desc, serverAddr, addrlen) ==
414                      GNUNET_OK);
415     }
416
417   plugin->rs = GNUNET_NETWORK_fdset_create ();
418
419   GNUNET_NETWORK_fdset_zero (plugin->rs);
420   GNUNET_NETWORK_fdset_set (plugin->rs, desc);
421
422   plugin->select_task =
423     GNUNET_SCHEDULER_add_select (plugin->env->sched,
424                                  GNUNET_SCHEDULER_PRIORITY_DEFAULT,
425                                  GNUNET_SCHEDULER_NO_TASK,
426                                  GNUNET_TIME_UNIT_FOREVER_REL, plugin->rs,
427                                  NULL, &udp_plugin_select, plugin);
428
429   return desc;
430 }
431
432
433 /**
434  * Check if the given port is plausible (must be either
435  * our listen port or our advertised port).  If it is
436  * neither, we return one of these two ports at random.
437  *
438  * @return either in_port or a more plausible port
439  */
440 static uint16_t
441 check_port (struct Plugin *plugin, uint16_t in_port)
442 {
443   if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
444     return in_port;
445   return (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
446                                     2) == 0)
447     ? plugin->open_port : plugin->adv_port;
448 }
449
450
451 /**
452  * Another peer has suggested an address for this peer and transport
453  * plugin.  Check that this could be a valid address.  This function
454  * is not expected to 'validate' the address in the sense of trying to
455  * connect to it but simply to see if the binary format is technically
456  * legal for establishing a connection.
457  *
458  * @param addr pointer to the address, may be modified (slightly)
459  * @param addrlen length of addr
460  * @return GNUNET_OK if this is a plausible address for this peer
461  *         and transport, GNUNET_SYSERR if not
462  *
463  * TODO: perhaps make everything work with sockaddr_storage, it may
464  *       be a cleaner way to handle addresses in UDP
465  */
466 static int
467 udp_check_address (void *cls, void *addr, size_t addrlen)
468 {
469   struct Plugin *plugin = cls;
470   char buf[sizeof (struct sockaddr_in6)];
471
472   struct sockaddr_in *v4;
473   struct sockaddr_in6 *v6;
474
475   if ((addrlen != sizeof (struct sockaddr_in)) &&
476       (addrlen != sizeof (struct sockaddr_in6)))
477     {
478       GNUNET_break_op (0);
479       return GNUNET_SYSERR;
480     }
481   memcpy (buf, addr, sizeof (struct sockaddr_in6));
482   if (addrlen == sizeof (struct sockaddr_in))
483     {
484       v4 = (struct sockaddr_in *) buf;
485       v4->sin_port = htons (check_port (plugin, ntohs (v4->sin_port)));
486     }
487   else
488     {
489       v6 = (struct sockaddr_in6 *) buf;
490       v6->sin6_port = htons (check_port (plugin, ntohs (v6->sin6_port)));
491     }
492 #if DEBUG_TCP
493   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
494                    "tcp",
495                    "Informing transport service about my address `%s'.\n",
496                    GNUNET_a2s (addr, addrlen));
497 #endif
498   return GNUNET_OK;
499   return GNUNET_OK;
500 }
501
502
503 /**
504  * Append our port and forward the result.
505  */
506 static void
507 append_port (void *cls, const char *hostname)
508 {
509   struct PrettyPrinterContext *ppc = cls;
510   char *ret;
511
512   if (hostname == NULL)
513     {
514       ppc->asc (ppc->asc_cls, NULL);
515       GNUNET_free (ppc);
516       return;
517     }
518   GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
519   ppc->asc (ppc->asc_cls, ret);
520   GNUNET_free (ret);
521 }
522
523
524 /**
525  * Convert the transports address to a nice, human-readable
526  * format.
527  *
528  * @param cls closure
529  * @param type name of the transport that generated the address
530  * @param addr one of the addresses of the host, NULL for the last address
531  *        the specific address format depends on the transport
532  * @param addrlen length of the address
533  * @param numeric should (IP) addresses be displayed in numeric form?
534  * @param timeout after how long should we give up?
535  * @param asc function to call on each string
536  * @param asc_cls closure for asc
537  */
538 static void
539 udp_plugin_address_pretty_printer (void *cls,
540                                    const char *type,
541                                    const void *addr,
542                                    size_t addrlen,
543                                    int numeric,
544                                    struct GNUNET_TIME_Relative timeout,
545                                    GNUNET_TRANSPORT_AddressStringCallback asc,
546                                    void *asc_cls)
547 {
548   struct Plugin *plugin = cls;
549   const struct sockaddr_in *v4;
550   const struct sockaddr_in6 *v6;
551   struct PrettyPrinterContext *ppc;
552
553   if ((addrlen != sizeof (struct sockaddr_in)) &&
554       (addrlen != sizeof (struct sockaddr_in6)))
555     {
556       /* invalid address */
557       GNUNET_break_op (0);
558       asc (asc_cls, NULL);
559       return;
560     }
561   ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
562   ppc->asc = asc;
563   ppc->asc_cls = asc_cls;
564   if (addrlen == sizeof (struct sockaddr_in))
565     {
566       v4 = (const struct sockaddr_in *) addr;
567       ppc->port = ntohs (v4->sin_port);
568     }
569   else
570     {
571       v6 = (const struct sockaddr_in6 *) addr;
572       ppc->port = ntohs (v6->sin6_port);
573
574     }
575   GNUNET_RESOLVER_hostname_get (plugin->env->sched,
576                                 plugin->env->cfg,
577                                 addr,
578                                 addrlen,
579                                 !numeric, timeout, &append_port, ppc);
580 }
581
582 /**
583  * Set a quota for receiving data from the given peer; this is a
584  * per-transport limit.  This call has no meaning for UDP, as if
585  * we don't receive data it still comes in.  UDP has no friendliness
586  * guarantees, and our buffers will fill at some level.
587  *
588  * @param cls closure
589  * @param target the peer for whom the quota is given
590  * @param quota_in quota for receiving/sending data in bytes per ms
591  */
592 static void
593 udp_plugin_set_receive_quota (void *cls,
594                               const struct GNUNET_PeerIdentity *target,
595                               uint32_t quota_in)
596 {
597   return; /* Do nothing */
598 }
599
600 /**
601  * The exported method. Makes the core api available via a global and
602  * returns the udp transport API.
603  */
604 void *
605 libgnunet_plugin_transport_udp_init (void *cls)
606 {
607   unsigned long long mtu;
608
609   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
610   struct GNUNET_TRANSPORT_PluginFunctions *api;
611   struct Plugin *plugin;
612   struct GNUNET_SERVICE_Context *service;
613   unsigned long long aport;
614   unsigned long long bport;
615
616   service = GNUNET_SERVICE_start ("transport-udp", env->sched, env->cfg);
617   if (service == NULL)
618     {
619       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "udp", _
620                        ("Failed to start service for `%s' transport plugin.\n"),
621                        "udp");
622       return NULL;
623     }
624   aport = 0;
625   if ((GNUNET_OK !=
626        GNUNET_CONFIGURATION_get_value_number (env->cfg,
627                                               "transport-udp",
628                                               "PORT",
629                                               &bport)) ||
630       (bport > 65535) ||
631       ((GNUNET_OK ==
632         GNUNET_CONFIGURATION_get_value_number (env->cfg,
633                                                "transport-udp",
634                                                "ADVERTISED-PORT",
635                                                &aport)) && (aport > 65535)))
636     {
637       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
638                        "udp",
639                        _
640                        ("Require valid port number for service `%s' in configuration!\n"),
641                        "transport-udp");
642       GNUNET_SERVICE_stop (service);
643       return NULL;
644     }
645   if (aport == 0)
646     aport = bport;
647
648   mtu = 1240;
649   if (mtu < 1200)
650     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
651                      "udp",
652                      _("MTU %llu for `%s' is probably too low!\n"), mtu,
653                      "UDP");
654
655   plugin = GNUNET_malloc (sizeof (struct Plugin));
656   plugin->open_port = bport;
657   plugin->adv_port = aport;
658   plugin->env = env;
659   plugin->statistics = NULL;
660   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
661   api->cls = plugin;
662
663   api->send = &udp_plugin_send;
664   api->disconnect = &udp_disconnect;
665   api->address_pretty_printer = &udp_plugin_address_pretty_printer;
666   api->set_receive_quota = &udp_plugin_set_receive_quota;
667   api->check_address = &udp_check_address;
668
669   plugin->service = service;
670
671   udp_sock = udp_transport_server_start (plugin);
672
673   GNUNET_assert (udp_sock != NULL);
674
675   return api;
676 }
677
678 void *
679 libgnunet_plugin_transport_udp_done (void *cls)
680 {
681   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
682   struct Plugin *plugin = api->cls;
683
684   udp_transport_server_stop (plugin);
685   if (NULL != hostname_dns)
686     {
687       GNUNET_RESOLVER_request_cancel (hostname_dns);
688       hostname_dns = NULL;
689     }
690   GNUNET_SERVICE_stop (plugin->service);
691
692   GNUNET_NETWORK_fdset_destroy (plugin->rs);
693   GNUNET_free (plugin);
694   GNUNET_free (api);
695   return NULL;
696 }
697
698 /* end of plugin_transport_udp.c */