indentation
[oweals/gnunet.git] / src / transport / plugin_transport_unix.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 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file transport/plugin_transport_unix.c
23  * @brief Transport plugin using unix domain sockets (!)
24  *        Clearly, can only be used locally on Unix/Linux hosts...
25  *        ONLY INTENDED FOR TESTING!!!
26  * @author Christian Grothoff
27  * @author Nathan Evans
28  */
29
30 #include "platform.h"
31 #include "gnunet_hello_lib.h"
32 #include "gnunet_connection_lib.h"
33 #include "gnunet_container_lib.h"
34 #include "gnunet_os_lib.h"
35 #include "gnunet_peerinfo_service.h"
36 #include "gnunet_protocols.h"
37 #include "gnunet_resolver_service.h"
38 #include "gnunet_server_lib.h"
39 #include "gnunet_signatures.h"
40 #include "gnunet_statistics_service.h"
41 #include "gnunet_transport_service.h"
42 #include "gnunet_transport_plugin.h"
43 #include "transport.h"
44
45 #define DEBUG_UNIX GNUNET_NO
46 #define DETAILS GNUNET_NO
47
48 #define MAX_PROBES 20
49
50 /*
51  * Transport cost to peer, always 1 for UNIX (direct connection)
52  */
53 #define UNIX_DIRECT_DISTANCE 1
54
55 #define DEFAULT_NAT_PORT 0
56
57 /**
58  * How long until we give up on transmitting the welcome message?
59  */
60 #define HOSTNAME_RESOLVE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
61
62 /**
63  * Starting port for listening and sending, eventually a config value
64  */
65 #define UNIX_NAT_DEFAULT_PORT 22086
66
67 /**
68  * UNIX Message-Packet header.
69  */
70 struct UNIXMessage
71 {
72   /**
73    * Message header.
74    */
75   struct GNUNET_MessageHeader header;
76
77   /**
78    * What is the identity of the sender (GNUNET_hash of public key)
79    */
80   struct GNUNET_PeerIdentity sender;
81
82 };
83
84 struct RetryList
85 {
86   /**
87    * Pointer to next element.
88    */
89   struct RetryList *next;
90
91   /**
92    * Pointer to previous element.
93    */
94   struct RetryList *prev;
95
96   /**
97    * The actual retry context.
98    */
99   struct RetrySendContext *retry_ctx;
100 };
101
102 /**
103  * Network format for IPv4 addresses.
104  */
105 struct IPv4UdpAddress
106 {
107   /**
108    * IPv4 address, in network byte order.
109    */
110   uint32_t ipv4_addr GNUNET_PACKED;
111
112   /**
113    * Port number, in network byte order.
114    */
115   uint16_t u_port GNUNET_PACKED;
116 };
117
118
119 /**
120  * Network format for IPv6 addresses.
121  */
122 struct IPv6UdpAddress
123 {
124   /**
125    * IPv6 address.
126    */
127   struct in6_addr ipv6_addr GNUNET_PACKED;
128
129   /**
130    * Port number, in network byte order.
131    */
132   uint16_t u6_port GNUNET_PACKED;
133 };
134
135 /* Forward definition */
136 struct Plugin;
137
138 struct PrettyPrinterContext
139 {
140   GNUNET_TRANSPORT_AddressStringCallback asc;
141   void *asc_cls;
142   uint16_t port;
143 };
144
145 struct RetrySendContext
146 {
147
148   /**
149    * Main plugin handle.
150    */
151   struct Plugin *plugin;
152
153   /**
154    * Address of recipient.
155    */
156   char *addr;
157
158   /**
159    * Length of address.
160    */
161   ssize_t addrlen;
162
163   /**
164    * Message to send.
165    */
166   char *msg;
167
168   /**
169    * Size of the message.
170    */
171   int msg_size;
172
173   /**
174    * Handle to send message out on.
175    */
176   struct GNUNET_NETWORK_Handle *send_handle;
177
178   /**
179    * Continuation to call on success or
180    * timeout.
181    */
182   GNUNET_TRANSPORT_TransmitContinuation cont;
183
184   /**
185    * Closure for continuation.
186    */
187   void *cont_cls;
188
189   /**
190    * The peer the message is destined for.
191    */
192   struct GNUNET_PeerIdentity target;
193
194   /**
195    * How long before not retrying any longer.
196    */
197   struct GNUNET_TIME_Absolute timeout;
198
199   /**
200    * How long the last message was delayed.
201    */
202   struct GNUNET_TIME_Relative delay;
203
204   /**
205    * The actual retry task.
206    */
207   GNUNET_SCHEDULER_TaskIdentifier retry_task;
208
209   /**
210    * The priority of the message.
211    */
212   unsigned int priority;
213
214   /**
215    * Entry in the DLL of retry items.
216    */
217   struct RetryList *retry_list_entry;
218 };
219
220
221 /**
222  * UNIX NAT "Session"
223  */
224 struct PeerSession
225 {
226
227   /**
228    * Stored in a linked list.
229    */
230   struct PeerSession *next;
231
232   /**
233    * Pointer to the global plugin struct.
234    */
235   struct Plugin *plugin;
236
237   /**
238    * To whom are we talking to (set to our identity
239    * if we are still waiting for the welcome message)
240    */
241   struct GNUNET_PeerIdentity target;
242
243   /**
244    * Address of the other peer (either based on our 'connect'
245    * call or on our 'accept' call).
246    */
247   void *connect_addr;
248
249   /**
250    * Length of connect_addr.
251    */
252   size_t connect_alen;
253
254   /**
255    * Are we still expecting the welcome message? (GNUNET_YES/GNUNET_NO)
256    */
257   int expecting_welcome;
258
259   /**
260    * From which socket do we need to send to this peer?
261    */
262   struct GNUNET_NETWORK_Handle *sock;
263
264   /*
265    * Queue of messages for this peer, in the case that
266    * we have to await a connection...
267    */
268   struct MessageQueue *messages;
269
270 };
271
272 /**
273  * Information we keep for each of our listen sockets.
274  */
275 struct UNIX_Sock_Info
276 {
277   /**
278    * The network handle
279    */
280   struct GNUNET_NETWORK_Handle *desc;
281
282   /**
283    * The port we bound to
284    */
285   uint16_t port;
286 };
287
288
289 /**
290  * Encapsulation of all of the state of the plugin.
291  */
292 struct Plugin
293 {
294   /**
295    * Our environment.
296    */
297   struct GNUNET_TRANSPORT_PluginEnvironment *env;
298
299   /*
300    * Session of peers with whom we are currently connected
301    */
302   struct PeerSession *sessions;
303
304   /**
305    * ID of task used to update our addresses when one expires.
306    */
307   GNUNET_SCHEDULER_TaskIdentifier address_update_task;
308
309   /**
310    * ID of select task
311    */
312   GNUNET_SCHEDULER_TaskIdentifier select_task;
313
314   /**
315    * Integer to append to unix domain socket.
316    */
317   uint16_t port;
318
319   /**
320    * FD Read set
321    */
322   struct GNUNET_NETWORK_FDSet *rs;
323
324   /**
325    * socket that we transmit all data with
326    */
327   struct UNIX_Sock_Info unix_sock;
328
329   /**
330    * Path of our unix domain socket (/tmp/unix-plugin-PORT)
331    */
332   char *unix_socket_path;
333
334 };
335
336 /**
337  * Head of retry DLL.
338  */
339 static struct RetryList *retry_list_head;
340
341 /**
342  * Tail of retry DLL.
343  */
344 static struct RetryList *retry_list_tail;
345
346
347 /**
348  * Disconnect from a remote node.  Clean up session if we have one for this peer
349  *
350  * @param cls closure for this call (should be handle to Plugin)
351  * @param target the peeridentity of the peer to disconnect
352  * @return GNUNET_OK on success, GNUNET_SYSERR if the operation failed
353  */
354 void
355 unix_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
356 {
357   /** TODO: Implement! */
358   return;
359 }
360
361 /**
362  * Shutdown the server process (stop receiving inbound traffic). Maybe
363  * restarted later!
364  *
365  * @param cls Handle to the plugin for this transport
366  *
367  * @return returns the number of sockets successfully closed,
368  *         should equal the number of sockets successfully opened
369  */
370 static int
371 unix_transport_server_stop (void *cls)
372 {
373   struct Plugin *plugin = cls;
374   struct RetryList *pos;
375
376   pos = retry_list_head;
377
378   while (NULL != (pos = retry_list_head))
379   {
380     GNUNET_CONTAINER_DLL_remove (retry_list_head, retry_list_tail, pos);
381     if (GNUNET_SCHEDULER_NO_TASK != pos->retry_ctx->retry_task)
382     {
383       GNUNET_SCHEDULER_cancel (pos->retry_ctx->retry_task);
384     }
385     GNUNET_free (pos->retry_ctx->msg);
386     GNUNET_free (pos->retry_ctx->addr);
387     GNUNET_free (pos->retry_ctx);
388     GNUNET_free (pos);
389   }
390
391   if (plugin->select_task != GNUNET_SCHEDULER_NO_TASK)
392   {
393     GNUNET_SCHEDULER_cancel (plugin->select_task);
394     plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
395   }
396
397   GNUNET_break (GNUNET_OK ==
398                 GNUNET_NETWORK_socket_close (plugin->unix_sock.desc));
399   plugin->unix_sock.desc = NULL;
400
401   return GNUNET_OK;
402 }
403
404
405 struct PeerSession *
406 find_session (struct Plugin *plugin, const struct GNUNET_PeerIdentity *peer)
407 {
408   struct PeerSession *pos;
409
410   pos = plugin->sessions;
411   while (pos != NULL)
412   {
413     if (memcmp (&pos->target, peer, sizeof (struct GNUNET_PeerIdentity)) == 0)
414       return pos;
415     pos = pos->next;
416   }
417
418   return pos;
419 }
420
421 /* Forward Declaration */
422 static ssize_t
423 unix_real_send (void *cls,
424                 struct RetrySendContext *incoming_retry_context,
425                 struct GNUNET_NETWORK_Handle *send_handle,
426                 const struct GNUNET_PeerIdentity *target,
427                 const char *msgbuf,
428                 size_t msgbuf_size,
429                 unsigned int priority,
430                 struct GNUNET_TIME_Relative timeout,
431                 const void *addr,
432                 size_t addrlen,
433                 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls);
434
435 /**
436  * Retry sending a message.
437  *
438  * @param cls closure a struct RetrySendContext
439  * @param tc context information
440  */
441 void
442 retry_send_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
443 {
444   struct RetrySendContext *retry_ctx = cls;
445
446   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
447   {
448     GNUNET_free (retry_ctx->msg);
449     GNUNET_free (retry_ctx->addr);
450     GNUNET_free (retry_ctx);
451     return;
452   }
453
454   unix_real_send (retry_ctx->plugin,
455                   retry_ctx,
456                   retry_ctx->send_handle,
457                   &retry_ctx->target,
458                   retry_ctx->msg,
459                   retry_ctx->msg_size,
460                   retry_ctx->priority,
461                   GNUNET_TIME_absolute_get_remaining (retry_ctx->timeout),
462                   retry_ctx->addr,
463                   retry_ctx->addrlen, retry_ctx->cont, retry_ctx->cont_cls);
464   return;
465 }
466
467 /**
468  * Actually send out the message, assume we've got the address and
469  * send_handle squared away!
470  *
471  * @param cls closure
472  * @param incoming_retry_context the retry context to use
473  * @param send_handle which handle to send message on
474  * @param target who should receive this message (ignored by UNIX)
475  * @param msgbuf one or more GNUNET_MessageHeader(s) strung together
476  * @param msgbuf_size the size of the msgbuf to send
477  * @param priority how important is the message (ignored by UNIX)
478  * @param timeout when should we time out (give up) if we can not transmit?
479  * @param addr the addr to send the message to, needs to be a sockaddr for us
480  * @param addrlen the len of addr
481  * @param cont continuation to call once the message has
482  *        been transmitted (or if the transport is ready
483  *        for the next transmission call; or if the
484  *        peer disconnected...)
485  * @param cont_cls closure for cont
486  *
487  * @return the number of bytes written, -1 on errors
488  */
489 static ssize_t
490 unix_real_send (void *cls,
491                 struct RetrySendContext *incoming_retry_context,
492                 struct GNUNET_NETWORK_Handle *send_handle,
493                 const struct GNUNET_PeerIdentity *target,
494                 const char *msgbuf,
495                 size_t msgbuf_size,
496                 unsigned int priority,
497                 struct GNUNET_TIME_Relative timeout,
498                 const void *addr,
499                 size_t addrlen,
500                 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
501 {
502   struct Plugin *plugin = cls;
503   struct UNIXMessage *message;
504   struct RetrySendContext *retry_ctx;
505   int ssize;
506   ssize_t sent;
507   const void *sb;
508   size_t sbs;
509   struct sockaddr_un un;
510   size_t slen;
511   struct RetryList *retry_list_entry;
512   int retry;
513
514   if (send_handle == NULL)
515   {
516 #if DEBUG_UNIX
517     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
518                 "unix_real_send with send_handle NULL!\n");
519 #endif
520     /* failed to open send socket for AF */
521     if (cont != NULL)
522       cont (cont_cls, target, GNUNET_SYSERR);
523     return 0;
524   }
525   if ((addr == NULL) || (addrlen == 0))
526   {
527 #if DEBUG_UNIX
528     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
529                 "unix_real_send called without address, returning!\n");
530 #endif
531     if (cont != NULL)
532       cont (cont_cls, target, GNUNET_SYSERR);
533     return 0;                   /* Can never send if we don't have an address!! */
534   }
535
536   /* Build the message to be sent */
537   message = GNUNET_malloc (sizeof (struct UNIXMessage) + msgbuf_size);
538   ssize = sizeof (struct UNIXMessage) + msgbuf_size;
539
540   message->header.size = htons (ssize);
541   message->header.type = htons (0);
542   memcpy (&message->sender, plugin->env->my_identity,
543           sizeof (struct GNUNET_PeerIdentity));
544   memcpy (&message[1], msgbuf, msgbuf_size);
545
546   memset (&un, 0, sizeof (un));
547   un.sun_family = AF_UNIX;
548   slen = strlen (addr) + 1;
549   if (slen >= sizeof (un.sun_path))
550     slen = sizeof (un.sun_path) - 1;
551   sent = 0;
552   GNUNET_assert (slen < sizeof (un.sun_path));
553   memcpy (un.sun_path, addr, slen);
554   un.sun_path[slen] = '\0';
555   slen = sizeof (struct sockaddr_un);
556 #if LINUX
557   un.sun_path[0] = '\0';
558 #endif
559 #if HAVE_SOCKADDR_IN_SIN_LEN
560   un.sun_len = (u_char) slen;
561 #endif
562   sb = (struct sockaddr *) &un;
563   sbs = slen;
564   retry = GNUNET_NO;
565
566   sent = GNUNET_NETWORK_socket_sendto (send_handle, message, ssize, sb, sbs);
567
568   if ((GNUNET_SYSERR == sent) && (errno == EAGAIN))
569     retry = GNUNET_YES;
570
571   if ((GNUNET_SYSERR == sent) && (errno == EMSGSIZE))
572   {
573     socklen_t size = 0;
574     socklen_t len = sizeof (size);
575
576     GNUNET_NETWORK_socket_getsockopt ((struct GNUNET_NETWORK_Handle *)
577                                       send_handle, SOL_SOCKET, SO_SNDBUF, &size,
578                                       &len);
579
580     if (size < ssize)
581     {
582 #if DEBUG_UNIX
583       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
584                   "Trying to increase socket buffer size from %i to %i for message size %i\n",
585                   size, ((ssize / 1000) + 2) * 1000, ssize);
586 #endif
587       size = ((ssize / 1000) + 2) * 1000;
588       if (GNUNET_NETWORK_socket_setsockopt
589           ((struct GNUNET_NETWORK_Handle *) send_handle, SOL_SOCKET, SO_SNDBUF,
590            &size, sizeof (size)) == GNUNET_OK)
591         retry = GNUNET_YES;
592       else
593         GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "setsockopt");
594     }
595   }
596
597   if (retry == GNUNET_YES)
598   {
599     if (incoming_retry_context == NULL)
600     {
601       retry_list_entry = GNUNET_malloc (sizeof (struct RetryList));
602       retry_ctx = GNUNET_malloc (sizeof (struct RetrySendContext));
603       retry_ctx->addr = GNUNET_malloc (addrlen);
604       retry_ctx->msg = GNUNET_malloc (msgbuf_size);
605       retry_ctx->plugin = plugin;
606       memcpy (retry_ctx->addr, addr, addrlen);
607       memcpy (retry_ctx->msg, msgbuf, msgbuf_size);
608       retry_ctx->msg_size = msgbuf_size;
609       retry_ctx->addrlen = addrlen;
610       retry_ctx->send_handle = send_handle;
611       retry_ctx->cont = cont;
612       retry_ctx->cont_cls = cont_cls;
613       retry_ctx->priority = priority;
614       retry_ctx->timeout = GNUNET_TIME_relative_to_absolute (timeout);
615       memcpy (&retry_ctx->target, target, sizeof (struct GNUNET_PeerIdentity));
616       retry_ctx->delay = GNUNET_TIME_UNIT_MILLISECONDS;
617       retry_ctx->retry_list_entry = retry_list_entry;
618       retry_list_entry->retry_ctx = retry_ctx;
619       GNUNET_CONTAINER_DLL_insert (retry_list_head, retry_list_tail,
620                                    retry_list_entry);
621     }
622     else
623     {
624       retry_ctx = incoming_retry_context;
625       retry_ctx->delay = GNUNET_TIME_relative_multiply (retry_ctx->delay, 2);
626     }
627     retry_ctx->retry_task =
628         GNUNET_SCHEDULER_add_delayed (retry_ctx->delay, &retry_send_message,
629                                       retry_ctx);
630
631     //GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG, "send");
632     GNUNET_free (message);
633     return ssize;
634   }
635 #if DEBUG_UNIX
636   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
637               "UNIX transmit %u-byte message to %s (%d: %s)\n",
638               (unsigned int) ssize,
639               GNUNET_a2s (sb, sbs),
640               (int) sent, (sent < 0) ? STRERROR (errno) : "ok");
641 #endif
642   if (cont != NULL)
643   {
644     if (sent == GNUNET_SYSERR)
645       cont (cont_cls, target, GNUNET_SYSERR);
646     else
647     {
648       cont (cont_cls, target, GNUNET_OK);
649     }
650   }
651
652   if (incoming_retry_context != NULL)
653   {
654     GNUNET_CONTAINER_DLL_remove (retry_list_head, retry_list_tail,
655                                  incoming_retry_context->retry_list_entry);
656     GNUNET_free (incoming_retry_context->retry_list_entry);
657     GNUNET_free (incoming_retry_context->msg);
658     GNUNET_free (incoming_retry_context->addr);
659     GNUNET_free (incoming_retry_context);
660   }
661
662   GNUNET_free (message);
663   return sent;
664 }
665
666
667 /**
668  * Function that can be used by the transport service to transmit
669  * a message using the plugin.
670  *
671  * @param cls closure
672  * @param target who should receive this message (ignored by UNIX)
673  * @param msgbuf one or more GNUNET_MessageHeader(s) strung together
674  * @param msgbuf_size the size of the msgbuf to send
675  * @param priority how important is the message (ignored by UNIX)
676  * @param timeout when should we time out (give up) if we can not transmit?
677  * @param session identifier used for this session (can be NULL)
678  * @param addr the addr to send the message to, needs to be a sockaddr for us
679  * @param addrlen the len of addr
680  * @param force_address not used, we had better have an address to send to
681  *        because we are stateless!!
682  * @param cont continuation to call once the message has
683  *        been transmitted (or if the transport is ready
684  *        for the next transmission call; or if the
685  *        peer disconnected...)
686  * @param cont_cls closure for cont
687  *
688  * @return the number of bytes written (may return 0 and the message can
689  *         still be transmitted later!)
690  */
691 static ssize_t
692 unix_plugin_send (void *cls,
693                   const struct GNUNET_PeerIdentity *target,
694                   const char *msgbuf,
695                   size_t msgbuf_size,
696                   unsigned int priority,
697                   struct GNUNET_TIME_Relative timeout,
698                   struct Session *session,
699                   const void *addr,
700                   size_t addrlen,
701                   int force_address,
702                   GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
703 {
704   struct Plugin *plugin = cls;
705   ssize_t sent;
706
707   if (force_address == GNUNET_SYSERR)
708     return GNUNET_SYSERR;
709   GNUNET_assert (NULL == session);
710
711 #if DEBUG_UNIX
712   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Asked to send message to `%s'\n",
713               (char *) addr);
714 #endif
715   sent = unix_real_send (cls,
716                          NULL,
717                          plugin->unix_sock.desc,
718                          target,
719                          msgbuf, msgbuf_size,
720                          priority, timeout, addr, addrlen, cont, cont_cls);
721 #if DEBUG_UNIX
722   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sent %d bytes to `%s'\n", sent,
723               (char *) addr);
724 #endif
725   if (sent == GNUNET_SYSERR)
726     return 0;
727   return sent;
728 }
729
730
731 /**
732  * Demultiplexer for UNIX messages
733  *
734  * @param plugin the main plugin for this transport
735  * @param sender from which peer the message was received
736  * @param currhdr pointer to the header of the message
737  * @param un the address from which the message was received
738  * @param fromlen the length of the address
739  */
740 static void
741 unix_demultiplexer (struct Plugin *plugin,
742                     struct GNUNET_PeerIdentity *sender,
743                     const struct GNUNET_MessageHeader *currhdr,
744                     const struct sockaddr_un *un, size_t fromlen)
745 {
746   struct GNUNET_TRANSPORT_ATS_Information distance[2];
747
748   distance[0].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE);
749   distance[0].value = htonl (UNIX_DIRECT_DISTANCE);
750   distance[1].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
751   distance[1].value = htonl (0);
752
753   GNUNET_assert (fromlen >= sizeof (struct sockaddr_un));
754
755 #if DEBUG_UNIX
756   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received message from %s\n",
757               un->sun_path);
758 #endif
759   plugin->env->receive (plugin->env->cls, sender, currhdr,
760                         (const struct GNUNET_TRANSPORT_ATS_Information *)
761                         &distance, 2, NULL, un->sun_path,
762                         strlen (un->sun_path) + 1);
763 }
764
765
766 /*
767  * @param cls the plugin handle
768  * @param tc the scheduling context (for rescheduling this function again)
769  *
770  * We have been notified that our writeset has something to read.  We don't
771  * know which socket needs to be read, so we have to check each one
772  * Then reschedule this function to be called again once more is available.
773  *
774  */
775 static void
776 unix_plugin_select (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
777 {
778   struct Plugin *plugin = cls;
779   char buf[65536];
780   struct UNIXMessage *msg;
781   struct GNUNET_PeerIdentity sender;
782   struct sockaddr_un un;
783   socklen_t addrlen;
784   ssize_t ret;
785   int offset;
786   int tsize;
787   char *msgbuf;
788   const struct GNUNET_MessageHeader *currhdr;
789   uint16_t csize;
790
791   plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
792   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
793     return;
794
795   addrlen = sizeof (un);
796   memset (&un, 0, sizeof (un));
797   GNUNET_assert (GNUNET_NETWORK_fdset_isset
798                  (tc->read_ready, plugin->unix_sock.desc));
799   ret =
800       GNUNET_NETWORK_socket_recvfrom (plugin->unix_sock.desc, buf, sizeof (buf),
801                                       (struct sockaddr *) &un, &addrlen);
802
803   if (ret == GNUNET_SYSERR)
804   {
805     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "recvfrom");
806     plugin->select_task =
807         GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
808                                      GNUNET_SCHEDULER_NO_TASK,
809                                      GNUNET_TIME_UNIT_FOREVER_REL, plugin->rs,
810                                      NULL, &unix_plugin_select, plugin);
811     return;
812   }
813   else
814   {
815 #if LINUX
816     un.sun_path[0] = '/';
817 #endif
818 #if DEBUG_UNIX
819     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Read %d bytes from socket %s\n", ret,
820                 &un.sun_path[0]);
821 #endif
822   }
823
824   GNUNET_assert (AF_UNIX == (un.sun_family));
825
826   msg = (struct UNIXMessage *) buf;
827   csize = ntohs (msg->header.size);
828   if ((csize < sizeof (struct UNIXMessage)) || (csize > ret))
829   {
830     GNUNET_break_op (0);
831     plugin->select_task =
832         GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
833                                      GNUNET_SCHEDULER_NO_TASK,
834                                      GNUNET_TIME_UNIT_FOREVER_REL, plugin->rs,
835                                      NULL, &unix_plugin_select, plugin);
836     return;
837   }
838   msgbuf = (char *) &msg[1];
839   memcpy (&sender, &msg->sender, sizeof (struct GNUNET_PeerIdentity));
840   offset = 0;
841   tsize = csize - sizeof (struct UNIXMessage);
842   while (offset + sizeof (struct GNUNET_MessageHeader) <= tsize)
843   {
844     currhdr = (struct GNUNET_MessageHeader *) &msgbuf[offset];
845     csize = ntohs (currhdr->size);
846     if ((csize < sizeof (struct GNUNET_MessageHeader)) ||
847         (csize > tsize - offset))
848     {
849       GNUNET_break_op (0);
850       break;
851     }
852     unix_demultiplexer (plugin, &sender, currhdr, &un, sizeof (un));
853     offset += csize;
854   }
855   plugin->select_task =
856       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
857                                    GNUNET_SCHEDULER_NO_TASK,
858                                    GNUNET_TIME_UNIT_FOREVER_REL, plugin->rs,
859                                    NULL, &unix_plugin_select, plugin);
860 }
861
862 /**
863  * Create a slew of UNIX sockets.  If possible, use IPv6 and IPv4.
864  *
865  * @param cls closure for server start, should be a struct Plugin *
866  * @return number of sockets created or GNUNET_SYSERR on error
867 */
868 static int
869 unix_transport_server_start (void *cls)
870 {
871   struct Plugin *plugin = cls;
872   struct sockaddr *serverAddr;
873   socklen_t addrlen;
874   struct sockaddr_un un;
875   size_t slen;
876
877   memset (&un, 0, sizeof (un));
878   un.sun_family = AF_UNIX;
879   slen = strlen (plugin->unix_socket_path) + 1;
880   if (slen >= sizeof (un.sun_path))
881     slen = sizeof (un.sun_path) - 1;
882
883   memcpy (un.sun_path, plugin->unix_socket_path, slen);
884   un.sun_path[slen] = '\0';
885   slen = sizeof (struct sockaddr_un);
886 #if HAVE_SOCKADDR_IN_SIN_LEN
887   un.sun_len = (u_char) slen;
888 #endif
889
890   serverAddr = (struct sockaddr *) &un;
891   addrlen = slen;
892 #if LINUX
893   un.sun_path[0] = '\0';
894 #endif
895
896   plugin->unix_sock.desc =
897       GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_DGRAM, 0);
898   if (NULL == plugin->unix_sock.desc)
899   {
900     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
901     return GNUNET_SYSERR;
902   }
903   if (GNUNET_NETWORK_socket_bind (plugin->unix_sock.desc, serverAddr, addrlen)
904       != GNUNET_OK)
905   {
906     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
907     GNUNET_NETWORK_socket_close (plugin->unix_sock.desc);
908     plugin->unix_sock.desc = NULL;
909     return GNUNET_SYSERR;
910   }
911 #if DEBUG_UNIX
912   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
913                    "unix", "Bound to `%s'\n", &un.sun_path[0]);
914 #endif
915   plugin->rs = GNUNET_NETWORK_fdset_create ();
916   GNUNET_NETWORK_fdset_zero (plugin->rs);
917   GNUNET_NETWORK_fdset_set (plugin->rs, plugin->unix_sock.desc);
918
919   plugin->select_task =
920       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
921                                    GNUNET_SCHEDULER_NO_TASK,
922                                    GNUNET_TIME_UNIT_FOREVER_REL, plugin->rs,
923                                    NULL, &unix_plugin_select, plugin);
924   return 1;
925 }
926
927
928 /**
929  * Function that will be called to check if a binary address for this
930  * plugin is well-formed and corresponds to an address for THIS peer
931  * (as per our configuration).  Naturally, if absolutely necessary,
932  * plugins can be a bit conservative in their answer, but in general
933  * plugins should make sure that the address does not redirect
934  * traffic to a 3rd party that might try to man-in-the-middle our
935  * traffic.
936  *
937  * @param cls closure, should be our handle to the Plugin
938  * @param addr pointer to the address
939  * @param addrlen length of addr
940  * @return GNUNET_OK if this is a plausible address for this peer
941  *         and transport, GNUNET_SYSERR if not
942  *
943  */
944 static int
945 unix_check_address (void *cls, const void *addr, size_t addrlen)
946 {
947
948 #if DEBUG_UNIX
949   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
950               "Informing transport service about my address `%s'\n",
951               (char *) addr);
952 #endif
953   return GNUNET_OK;
954 }
955
956
957 /**
958  * Append our port and forward the result.
959  */
960 static void
961 append_port (void *cls, const char *hostname)
962 {
963   struct PrettyPrinterContext *ppc = cls;
964   char *ret;
965
966   if (hostname == NULL)
967   {
968     ppc->asc (ppc->asc_cls, NULL);
969     GNUNET_free (ppc);
970     return;
971   }
972   GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
973   ppc->asc (ppc->asc_cls, ret);
974   GNUNET_free (ret);
975 }
976
977
978 /**
979  * Convert the transports address to a nice, human-readable
980  * format.
981  *
982  * @param cls closure
983  * @param type name of the transport that generated the address
984  * @param addr one of the addresses of the host, NULL for the last address
985  *        the specific address format depends on the transport
986  * @param addrlen length of the address
987  * @param numeric should (IP) addresses be displayed in numeric form?
988  * @param timeout after how long should we give up?
989  * @param asc function to call on each string
990  * @param asc_cls closure for asc
991  */
992 static void
993 unix_plugin_address_pretty_printer (void *cls,
994                                     const char *type,
995                                     const void *addr,
996                                     size_t addrlen,
997                                     int numeric,
998                                     struct GNUNET_TIME_Relative timeout,
999                                     GNUNET_TRANSPORT_AddressStringCallback asc,
1000                                     void *asc_cls)
1001 {
1002   struct PrettyPrinterContext *ppc;
1003   const void *sb;
1004   size_t sbs;
1005   struct sockaddr_in a4;
1006   struct sockaddr_in6 a6;
1007   const struct IPv4UdpAddress *u4;
1008   const struct IPv6UdpAddress *u6;
1009   uint16_t port;
1010
1011   if (addrlen == sizeof (struct IPv6UdpAddress))
1012   {
1013     u6 = addr;
1014     memset (&a6, 0, sizeof (a6));
1015     a6.sin6_family = AF_INET6;
1016     a6.sin6_port = u6->u6_port;
1017     memcpy (&a6.sin6_addr, &u6->ipv6_addr, sizeof (struct in6_addr));
1018     port = ntohs (u6->u6_port);
1019     sb = &a6;
1020     sbs = sizeof (a6);
1021   }
1022   else if (addrlen == sizeof (struct IPv4UdpAddress))
1023   {
1024     u4 = addr;
1025     memset (&a4, 0, sizeof (a4));
1026     a4.sin_family = AF_INET;
1027     a4.sin_port = u4->u_port;
1028     a4.sin_addr.s_addr = u4->ipv4_addr;
1029     port = ntohs (u4->u_port);
1030     sb = &a4;
1031     sbs = sizeof (a4);
1032   }
1033   else
1034   {
1035     /* invalid address */
1036     GNUNET_break_op (0);
1037     asc (asc_cls, NULL);
1038     return;
1039   }
1040   ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1041   ppc->asc = asc;
1042   ppc->asc_cls = asc_cls;
1043   ppc->port = port;
1044   GNUNET_RESOLVER_hostname_get (sb, sbs, !numeric, timeout, &append_port, ppc);
1045 }
1046
1047 /**
1048  * Function called for a quick conversion of the binary address to
1049  * a numeric address.  Note that the caller must not free the
1050  * address and that the next call to this function is allowed
1051  * to override the address again.
1052  *
1053  * @param cls closure
1054  * @param addr binary address
1055  * @param addrlen length of the address
1056  * @return string representing the same address
1057  */
1058 static const char *
1059 unix_address_to_string (void *cls, const void *addr, size_t addrlen)
1060 {
1061   if ((addr != NULL) && (addrlen > 0))
1062     return (const char *) addr;
1063   else
1064     return NULL;
1065 }
1066
1067 /**
1068  * Notify transport service about address
1069  *
1070  * @param cls the plugin
1071  * @param tc unused
1072  */
1073 static void
1074 address_notification (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1075 {
1076   struct Plugin *plugin = cls;
1077
1078   plugin->env->notify_address (plugin->env->cls,
1079                                GNUNET_YES,
1080                                plugin->unix_socket_path,
1081                                strlen (plugin->unix_socket_path) + 1);
1082 }
1083
1084 /**
1085  * The exported method. Makes the core api available via a global and
1086  * returns the unix transport API.
1087  */
1088 void *
1089 libgnunet_plugin_transport_unix_init (void *cls)
1090 {
1091   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1092   unsigned long long port;
1093   struct GNUNET_TRANSPORT_PluginFunctions *api;
1094   struct Plugin *plugin;
1095   int sockets_created;
1096
1097   if (GNUNET_OK !=
1098       GNUNET_CONFIGURATION_get_value_number (env->cfg,
1099                                              "transport-unix", "PORT", &port))
1100     port = UNIX_NAT_DEFAULT_PORT;
1101   plugin = GNUNET_malloc (sizeof (struct Plugin));
1102   plugin->port = port;
1103   plugin->env = env;
1104   GNUNET_asprintf (&plugin->unix_socket_path,
1105                    "/tmp/unix-plugin-sock.%d", plugin->port);
1106
1107   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1108   api->cls = plugin;
1109
1110   api->send = &unix_plugin_send;
1111   api->disconnect = &unix_disconnect;
1112   api->address_pretty_printer = &unix_plugin_address_pretty_printer;
1113   api->address_to_string = &unix_address_to_string;
1114   api->check_address = &unix_check_address;
1115   sockets_created = unix_transport_server_start (plugin);
1116   if (sockets_created == 0)
1117     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _("Failed to open UNIX sockets\n"));
1118
1119   GNUNET_SCHEDULER_add_now (address_notification, plugin);
1120   return api;
1121 }
1122
1123 void *
1124 libgnunet_plugin_transport_unix_done (void *cls)
1125 {
1126   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1127   struct Plugin *plugin = api->cls;
1128
1129   unix_transport_server_stop (plugin);
1130
1131   GNUNET_NETWORK_fdset_destroy (plugin->rs);
1132   GNUNET_free (plugin->unix_socket_path);
1133   GNUNET_free (plugin);
1134   GNUNET_free (api);
1135   return NULL;
1136 }
1137
1138 /* end of plugin_transport_unix.c */