it compiles, but definitely doesn't work
[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       plugin->env->receive (plugin->env->cls,
334           &msg->header, sender, UDP_DIRECT_DISTANCE, (char *)&addr, fromlen);
335
336       GNUNET_free (sender);
337       GNUNET_free (buf);
338
339     }
340   while (GNUNET_NETWORK_socket_select (plugin->rs,
341                                        NULL,
342                                        NULL,
343                                        timeout) > 0
344          && GNUNET_NETWORK_fdset_isset (plugin->rs, udp_sock));
345
346   plugin->select_task =
347     GNUNET_SCHEDULER_add_select (plugin->env->sched,
348                                  GNUNET_SCHEDULER_PRIORITY_DEFAULT,
349                                  GNUNET_SCHEDULER_NO_TASK,
350                                  GNUNET_TIME_UNIT_FOREVER_REL, plugin->rs,
351                                  NULL, &udp_plugin_select, plugin);
352
353 }
354
355 /**
356  * Create a UDP socket.  If possible, use IPv6, otherwise
357  * try IPv4.
358  */
359 static struct GNUNET_NETWORK_Handle *
360 udp_transport_server_start (void *cls)
361 {
362   struct Plugin *plugin = cls;
363   struct GNUNET_NETWORK_Handle *desc;
364   struct sockaddr_in serverAddrv4;
365   struct sockaddr_in6 serverAddrv6;
366   struct sockaddr *serverAddr;
367   socklen_t addrlen;
368
369   desc = NULL;
370   if (GNUNET_YES !=
371       GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg, "GNUNETD",
372                                             "DISABLE-IPV6"))
373     {
374       desc = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_DGRAM, 17);
375       if (desc != NULL)
376         {
377           memset (&serverAddrv6, 0, sizeof (serverAddrv6));
378 #if HAVE_SOCKADDR_IN_SIN_LEN
379           serverAddrv6.sin6_len = sizeof (serverAddrv6);
380 #endif
381           serverAddrv6.sin6_family = AF_INET6;
382           serverAddrv6.sin6_addr = in6addr_any;
383           serverAddrv6.sin6_port = htons (plugin->open_port);
384           addrlen = sizeof (serverAddrv6);
385           serverAddr = (struct sockaddr *) &serverAddrv6;
386         }
387     }
388   if (NULL == desc)
389     {
390       desc = GNUNET_NETWORK_socket_create (PF_INET, SOCK_DGRAM, 17);
391       if (NULL == desc)
392         {
393           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "udp", "socket");
394           return NULL;
395         }
396       else
397         {
398           memset (&serverAddrv4, 0, sizeof (serverAddrv4));
399 #if HAVE_SOCKADDR_IN_SIN_LEN
400           serverAddrv4.sin_len = sizeof (serverAddrv4);
401 #endif
402           serverAddrv4.sin_family = AF_INET;
403           serverAddrv4.sin_addr.s_addr = INADDR_ANY;
404           serverAddrv4.sin_port = htons (plugin->open_port);
405           addrlen = sizeof (serverAddrv4);
406           serverAddr = (struct sockaddr *) &serverAddrv4;
407         }
408     }
409
410   if (desc != NULL)
411     {
412       GNUNET_assert (GNUNET_NETWORK_socket_bind (desc, serverAddr, addrlen) ==
413                      GNUNET_OK);
414     }
415
416   plugin->rs = GNUNET_NETWORK_fdset_create ();
417
418   GNUNET_NETWORK_fdset_zero (plugin->rs);
419   GNUNET_NETWORK_fdset_set (plugin->rs, desc);
420
421   plugin->select_task =
422     GNUNET_SCHEDULER_add_select (plugin->env->sched,
423                                  GNUNET_SCHEDULER_PRIORITY_DEFAULT,
424                                  GNUNET_SCHEDULER_NO_TASK,
425                                  GNUNET_TIME_UNIT_FOREVER_REL, plugin->rs,
426                                  NULL, &udp_plugin_select, plugin);
427
428   return desc;
429 }
430
431
432 /**
433  * Check if the given port is plausible (must be either
434  * our listen port or our advertised port).  If it is
435  * neither, we return one of these two ports at random.
436  *
437  * @return either in_port or a more plausible port
438  */
439 static uint16_t
440 check_port (struct Plugin *plugin, uint16_t in_port)
441 {
442   if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
443     return in_port;
444   return (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
445                                     2) == 0)
446     ? plugin->open_port : plugin->adv_port;
447 }
448
449
450 /**
451  * Another peer has suggested an address for this peer and transport
452  * plugin.  Check that this could be a valid address.  This function
453  * is not expected to 'validate' the address in the sense of trying to
454  * connect to it but simply to see if the binary format is technically
455  * legal for establishing a connection.
456  *
457  * @param addr pointer to the address, may be modified (slightly)
458  * @param addrlen length of addr
459  * @return GNUNET_OK if this is a plausible address for this peer
460  *         and transport, GNUNET_SYSERR if not
461  *
462  * TODO: perhaps make everything work with sockaddr_storage, it may
463  *       be a cleaner way to handle addresses in UDP
464  */
465 static int
466 udp_check_address (void *cls, void *addr, size_t addrlen)
467 {
468   struct Plugin *plugin = cls;
469   char buf[sizeof (struct sockaddr_in6)];
470
471   struct sockaddr_in *v4;
472   struct sockaddr_in6 *v6;
473
474   if ((addrlen != sizeof (struct sockaddr_in)) &&
475       (addrlen != sizeof (struct sockaddr_in6)))
476     {
477       GNUNET_break_op (0);
478       return GNUNET_SYSERR;
479     }
480   memcpy (buf, addr, sizeof (struct sockaddr_in6));
481   if (addrlen == sizeof (struct sockaddr_in))
482     {
483       v4 = (struct sockaddr_in *) buf;
484       v4->sin_port = htons (check_port (plugin, ntohs (v4->sin_port)));
485     }
486   else
487     {
488       v6 = (struct sockaddr_in6 *) buf;
489       v6->sin6_port = htons (check_port (plugin, ntohs (v6->sin6_port)));
490     }
491 #if DEBUG_TCP
492   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
493                    "tcp",
494                    "Informing transport service about my address `%s'.\n",
495                    GNUNET_a2s (addr, addrlen));
496 #endif
497   return GNUNET_OK;
498   return GNUNET_OK;
499 }
500
501
502 /**
503  * Append our port and forward the result.
504  */
505 static void
506 append_port (void *cls, const char *hostname)
507 {
508   struct PrettyPrinterContext *ppc = cls;
509   char *ret;
510
511   if (hostname == NULL)
512     {
513       ppc->asc (ppc->asc_cls, NULL);
514       GNUNET_free (ppc);
515       return;
516     }
517   GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
518   ppc->asc (ppc->asc_cls, ret);
519   GNUNET_free (ret);
520 }
521
522
523 /**
524  * Convert the transports address to a nice, human-readable
525  * format.
526  *
527  * @param cls closure
528  * @param type name of the transport that generated the address
529  * @param addr one of the addresses of the host, NULL for the last address
530  *        the specific address format depends on the transport
531  * @param addrlen length of the address
532  * @param numeric should (IP) addresses be displayed in numeric form?
533  * @param timeout after how long should we give up?
534  * @param asc function to call on each string
535  * @param asc_cls closure for asc
536  */
537 static void
538 udp_plugin_address_pretty_printer (void *cls,
539                                    const char *type,
540                                    const void *addr,
541                                    size_t addrlen,
542                                    int numeric,
543                                    struct GNUNET_TIME_Relative timeout,
544                                    GNUNET_TRANSPORT_AddressStringCallback asc,
545                                    void *asc_cls)
546 {
547   struct Plugin *plugin = cls;
548   const struct sockaddr_in *v4;
549   const struct sockaddr_in6 *v6;
550   struct PrettyPrinterContext *ppc;
551
552   if ((addrlen != sizeof (struct sockaddr_in)) &&
553       (addrlen != sizeof (struct sockaddr_in6)))
554     {
555       /* invalid address */
556       GNUNET_break_op (0);
557       asc (asc_cls, NULL);
558       return;
559     }
560   ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
561   ppc->asc = asc;
562   ppc->asc_cls = asc_cls;
563   if (addrlen == sizeof (struct sockaddr_in))
564     {
565       v4 = (const struct sockaddr_in *) addr;
566       ppc->port = ntohs (v4->sin_port);
567     }
568   else
569     {
570       v6 = (const struct sockaddr_in6 *) addr;
571       ppc->port = ntohs (v6->sin6_port);
572
573     }
574   GNUNET_RESOLVER_hostname_get (plugin->env->sched,
575                                 plugin->env->cfg,
576                                 addr,
577                                 addrlen,
578                                 !numeric, timeout, &append_port, ppc);
579 }
580
581 /**
582  * Set a quota for receiving data from the given peer; this is a
583  * per-transport limit.  This call has no meaning for UDP, as if
584  * we don't receive data it still comes in.  UDP has no friendliness
585  * guarantees, and our buffers will fill at some level.
586  *
587  * @param cls closure
588  * @param target the peer for whom the quota is given
589  * @param quota_in quota for receiving/sending data in bytes per ms
590  */
591 static void
592 udp_plugin_set_receive_quota (void *cls,
593                               const struct GNUNET_PeerIdentity *target,
594                               uint32_t quota_in)
595 {
596   return; /* Do nothing */
597 }
598
599 /**
600  * The exported method. Makes the core api available via a global and
601  * returns the udp transport API.
602  */
603 void *
604 libgnunet_plugin_transport_udp_init (void *cls)
605 {
606   unsigned long long mtu;
607
608   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
609   struct GNUNET_TRANSPORT_PluginFunctions *api;
610   struct Plugin *plugin;
611   struct GNUNET_SERVICE_Context *service;
612   unsigned long long aport;
613   unsigned long long bport;
614
615   service = GNUNET_SERVICE_start ("transport-udp", env->sched, env->cfg);
616   if (service == NULL)
617     {
618       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "udp", _
619                        ("Failed to start service for `%s' transport plugin.\n"),
620                        "udp");
621       return NULL;
622     }
623   aport = 0;
624   if ((GNUNET_OK !=
625        GNUNET_CONFIGURATION_get_value_number (env->cfg,
626                                               "transport-udp",
627                                               "PORT",
628                                               &bport)) ||
629       (bport > 65535) ||
630       ((GNUNET_OK ==
631         GNUNET_CONFIGURATION_get_value_number (env->cfg,
632                                                "transport-udp",
633                                                "ADVERTISED-PORT",
634                                                &aport)) && (aport > 65535)))
635     {
636       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
637                        "udp",
638                        _
639                        ("Require valid port number for service `%s' in configuration!\n"),
640                        "transport-udp");
641       GNUNET_SERVICE_stop (service);
642       return NULL;
643     }
644   if (aport == 0)
645     aport = bport;
646
647   mtu = 1240;
648   if (mtu < 1200)
649     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
650                      "udp",
651                      _("MTU %llu for `%s' is probably too low!\n"), mtu,
652                      "UDP");
653
654   plugin = GNUNET_malloc (sizeof (struct Plugin));
655   plugin->open_port = bport;
656   plugin->adv_port = aport;
657   plugin->env = env;
658   plugin->statistics = NULL;
659   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
660   api->cls = plugin;
661
662   api->send = &udp_plugin_send;
663   api->disconnect = &udp_disconnect;
664   api->address_pretty_printer = &udp_plugin_address_pretty_printer;
665   api->set_receive_quota = &udp_plugin_set_receive_quota;
666   api->check_address = &udp_check_address;
667
668   plugin->service = service;
669
670   udp_sock = udp_transport_server_start (plugin);
671
672   GNUNET_assert (udp_sock != NULL);
673
674   return api;
675 }
676
677 void *
678 libgnunet_plugin_transport_udp_done (void *cls)
679 {
680   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
681   struct Plugin *plugin = api->cls;
682
683   udp_transport_server_stop (plugin);
684   if (NULL != hostname_dns)
685     {
686       GNUNET_RESOLVER_request_cancel (hostname_dns);
687       hostname_dns = NULL;
688     }
689   GNUNET_SERVICE_stop (plugin->service);
690
691   GNUNET_NETWORK_fdset_destroy (plugin->rs);
692   GNUNET_free (plugin);
693   GNUNET_free (api);
694   return NULL;
695 }
696
697 /* end of plugin_transport_udp.c */