-do not leave PPT timeout tasks behind
[oweals/gnunet.git] / src / transport / plugin_transport_unix.c
1 /*
2      This file is part of GNUnet
3      Copyright (C) 2010-2014 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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, 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 #include "platform.h"
30 #include "gnunet_util_lib.h"
31 #include "gnunet_hello_lib.h"
32 #include "gnunet_protocols.h"
33 #include "gnunet_statistics_service.h"
34 #include "gnunet_transport_service.h"
35 #include "gnunet_transport_plugin.h"
36 #include "transport.h"
37
38
39 /**
40  * Return code we give on 'send' if we failed to send right now
41  * but it makes sense to retry later. (Note: we might want to
42  * move this to the plugin API!?).
43  */
44 #define RETRY 0
45
46 /**
47  * Name of the plugin.
48  */
49 #define PLUGIN_NAME "unix"
50
51 /**
52  * Options for UNIX Domain addresses.
53  */
54 enum UNIX_ADDRESS_OPTIONS
55 {
56   /**
57    * No special options.
58    */
59   UNIX_OPTIONS_NONE = 0,
60
61   /**
62    * Linux abstract domain sockets should be used.
63    */
64   UNIX_OPTIONS_USE_ABSTRACT_SOCKETS = 1
65 };
66
67
68 /**
69  * How long until we give up on transmitting the welcome message?
70  */
71 #define HOSTNAME_RESOLVE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
72
73 #define LOG(kind,...) GNUNET_log_from (kind, "transport-unix",__VA_ARGS__)
74
75
76 GNUNET_NETWORK_STRUCT_BEGIN
77
78 /**
79  * Binary format for an UNIX Domain Socket address in GNUnet.
80  */
81 struct UnixAddress
82 {
83   /**
84    * Options to use for the address, in NBO
85    */
86   uint32_t options GNUNET_PACKED;
87
88   /**
89    * Length of the address (path length), in NBO
90    */
91   uint32_t addrlen GNUNET_PACKED;
92
93   /* followed by actual path */
94 };
95
96
97 /**
98  * UNIX Message-Packet header.
99  */
100 struct UNIXMessage
101 {
102   /**
103    * Message header.
104    */
105   struct GNUNET_MessageHeader header;
106
107   /**
108    * What is the identity of the sender (GNUNET_hash of public key)
109    */
110   struct GNUNET_PeerIdentity sender;
111
112 };
113
114 GNUNET_NETWORK_STRUCT_END
115
116
117 /**
118  * Information we track for a message awaiting transmission.
119  */
120 struct UNIXMessageWrapper
121 {
122   /**
123    * We keep messages in a doubly linked list.
124    */
125   struct UNIXMessageWrapper *next;
126
127   /**
128    * We keep messages in a doubly linked list.
129    */
130   struct UNIXMessageWrapper *prev;
131
132   /**
133    * The actual payload (allocated separately right now).
134    */
135   struct UNIXMessage *msg;
136
137   /**
138    * Session this message belongs to.
139    */
140   struct Session *session;
141
142   /**
143    * Function to call upon transmission.
144    */
145   GNUNET_TRANSPORT_TransmitContinuation cont;
146
147   /**
148    * Closure for @e cont.
149    */
150   void *cont_cls;
151
152   /**
153    * Timeout for this message.
154    */
155   struct GNUNET_TIME_Absolute timeout;
156
157   /**
158    * Number of bytes in @e msg.
159    */
160   size_t msgsize;
161
162   /**
163    * Number of bytes of payload encapsulated in @e msg.
164    */
165   size_t payload;
166
167   /**
168    * Priority of the message (ignored, just dragged along in UNIX).
169    */
170   unsigned int priority;
171 };
172
173
174 /**
175  * Handle for a session.
176  */
177 struct Session
178 {
179
180   /**
181    * Sessions with pending messages (!) are kept in a DLL.
182    */
183   struct Session *next;
184
185   /**
186    * Sessions with pending messages (!) are kept in a DLL.
187    */
188   struct Session *prev;
189
190   /**
191    * To whom are we talking to (set to our identity
192    * if we are still waiting for the welcome message).
193    *
194    * FIXME: information duplicated with 'peer' in address!
195    */
196   struct GNUNET_PeerIdentity target;
197
198   /**
199    * Pointer to the global plugin struct.
200    */
201   struct Plugin *plugin;
202
203   /**
204    * Address of the other peer.
205    */
206   struct GNUNET_HELLO_Address *address;
207
208   /**
209    * Number of bytes we currently have in our write queue.
210    */
211   unsigned long long bytes_in_queue;
212
213   /**
214    * Timeout for this session.
215    */
216   struct GNUNET_TIME_Absolute timeout;
217
218   /**
219    * Session timeout task.
220    */
221   struct GNUNET_SCHEDULER_Task * timeout_task;
222
223   /**
224    * Number of messages we currently have in our write queue.
225    */
226   unsigned int msgs_in_queue;
227
228 };
229
230
231 /**
232  * Encapsulation of all of the state of the plugin.
233  */
234 struct Plugin;
235
236
237 /**
238  * Information we keep for each of our listen sockets.
239  */
240 struct UNIX_Sock_Info
241 {
242   /**
243    * The network handle
244    */
245   struct GNUNET_NETWORK_Handle *desc;
246 };
247
248
249 /**
250  * Encapsulation of all of the state of the plugin.
251  */
252 struct Plugin
253 {
254
255   /**
256    * ID of task used to update our addresses when one expires.
257    */
258   struct GNUNET_SCHEDULER_Task * address_update_task;
259
260   /**
261    * ID of read task
262    */
263   struct GNUNET_SCHEDULER_Task * read_task;
264
265   /**
266    * ID of write task
267    */
268   struct GNUNET_SCHEDULER_Task * write_task;
269
270   /**
271    * Number of bytes we currently have in our write queues.
272    */
273   unsigned long long bytes_in_queue;
274
275   /**
276    * Our environment.
277    */
278   struct GNUNET_TRANSPORT_PluginEnvironment *env;
279
280   /**
281    * Sessions (map from peer identity to `struct Session`)
282    */
283   struct GNUNET_CONTAINER_MultiPeerMap *session_map;
284
285   /**
286    * Head of queue of messages to transmit.
287    */
288   struct UNIXMessageWrapper *msg_head;
289
290   /**
291    * Tail of queue of messages to transmit.
292    */
293   struct UNIXMessageWrapper *msg_tail;
294
295   /**
296    * Path of our unix domain socket (/tmp/unix-plugin)
297    */
298   char *unix_socket_path;
299
300   /**
301    * Function to call about session status changes.
302    */
303   GNUNET_TRANSPORT_SessionInfoCallback sic;
304
305   /**
306    * Closure for @e sic.
307    */
308   void *sic_cls;
309
310   /**
311    * socket that we transmit all data with
312    */
313   struct UNIX_Sock_Info unix_sock;
314
315   /**
316    * Address options in HBO
317    */
318   uint32_t myoptions;
319
320   /**
321    * Are we using an abstract UNIX domain socket?
322    */
323   int is_abstract;
324
325 };
326
327
328 /**
329  * If a session monitor is attached, notify it about the new
330  * session state.
331  *
332  * @param plugin our plugin
333  * @param session session that changed state
334  * @param state new state of the session
335  */
336 static void
337 notify_session_monitor (struct Plugin *plugin,
338                         struct Session *session,
339                         enum GNUNET_TRANSPORT_SessionState state)
340 {
341   struct GNUNET_TRANSPORT_SessionInfo info;
342
343   if (NULL == plugin->sic)
344     return;
345   memset (&info, 0, sizeof (info));
346   info.state = state;
347   info.is_inbound = GNUNET_SYSERR; /* hard to say */
348   info.num_msg_pending = session->msgs_in_queue;
349   info.num_bytes_pending = session->bytes_in_queue;
350   /* info.receive_delay remains zero as this is not supported by UNIX
351      (cannot selectively not receive from 'some' peer while continuing
352      to receive from others) */
353   info.session_timeout = session->timeout;
354   info.address = session->address;
355   plugin->sic (plugin->sic_cls,
356                session,
357                &info);
358 }
359
360
361 /**
362  * Function called for a quick conversion of the binary address to
363  * a numeric address.  Note that the caller must not free the
364  * address and that the next call to this function is allowed
365  * to override the address again.
366  *
367  * @param cls closure
368  * @param addr binary address
369  * @param addrlen length of the @a addr
370  * @return string representing the same address
371  */
372 static const char *
373 unix_plugin_address_to_string (void *cls,
374                                const void *addr,
375                                size_t addrlen)
376 {
377   static char rbuf[1024];
378   struct UnixAddress *ua = (struct UnixAddress *) addr;
379   char *addrstr;
380   size_t addr_str_len;
381   unsigned int off;
382
383   if ((NULL == addr) || (sizeof (struct UnixAddress) > addrlen))
384   {
385     GNUNET_break(0);
386     return NULL;
387   }
388   addrstr = (char *) &ua[1];
389   addr_str_len = ntohl (ua->addrlen);
390
391   if (addr_str_len != addrlen - sizeof(struct UnixAddress))
392   {
393     GNUNET_break(0);
394     return NULL;
395   }
396   if ('\0' != addrstr[addr_str_len - 1])
397   {
398     GNUNET_break(0);
399     return NULL;
400   }
401   if (strlen (addrstr) + 1 != addr_str_len)
402   {
403     GNUNET_break(0);
404     return NULL;
405   }
406
407   off = 0;
408   if ('\0' == addrstr[0])
409     off++;
410   memset (rbuf, 0, sizeof (rbuf));
411   GNUNET_snprintf (rbuf,
412                    sizeof (rbuf) - 1,
413                    "%s.%u.%s%.*s",
414                    PLUGIN_NAME,
415                    ntohl (ua->options),
416                    (off == 1) ? "@" : "",
417                    (int) (addr_str_len - off),
418                    &addrstr[off]);
419   return rbuf;
420 }
421
422
423 /**
424  * Functions with this signature are called whenever we need
425  * to close a session due to a disconnect or failure to
426  * establish a connection.
427  *
428  * @param cls closure with the `struct Plugin *`
429  * @param session session to close down
430  * @return #GNUNET_OK on success
431  */
432 static int
433 unix_plugin_session_disconnect (void *cls,
434                                 struct Session *session)
435 {
436   struct Plugin *plugin = cls;
437   struct UNIXMessageWrapper *msgw;
438   struct UNIXMessageWrapper *next;
439
440   LOG (GNUNET_ERROR_TYPE_DEBUG,
441        "Disconnecting session for peer `%s' `%s'\n",
442        GNUNET_i2s (&session->target),
443        unix_plugin_address_to_string (NULL,
444                                       session->address->address,
445                                       session->address->address_length));
446   plugin->env->session_end (plugin->env->cls,
447                             session->address,
448                             session);
449   next = plugin->msg_head;
450   while (NULL != next)
451   {
452     msgw = next;
453     next = msgw->next;
454     if (msgw->session != session)
455       continue;
456     GNUNET_CONTAINER_DLL_remove (plugin->msg_head,
457                                  plugin->msg_tail,
458                                  msgw);
459     session->msgs_in_queue--;
460     GNUNET_assert (session->bytes_in_queue >= msgw->msgsize);
461     session->bytes_in_queue -= msgw->msgsize;
462     GNUNET_assert (plugin->bytes_in_queue >= msgw->msgsize);
463     plugin->bytes_in_queue -= msgw->msgsize;
464     if (NULL != msgw->cont)
465       msgw->cont (msgw->cont_cls,
466                   &msgw->session->target,
467                   GNUNET_SYSERR,
468                   msgw->payload, 0);
469     GNUNET_free (msgw->msg);
470     GNUNET_free (msgw);
471   }
472   GNUNET_assert (GNUNET_YES ==
473                  GNUNET_CONTAINER_multipeermap_remove (plugin->session_map,
474                                                        &session->target,
475                                                        session));
476   GNUNET_STATISTICS_set (plugin->env->stats,
477                          "# UNIX sessions active",
478                          GNUNET_CONTAINER_multipeermap_size (plugin->session_map),
479                          GNUNET_NO);
480   if (NULL != session->timeout_task)
481   {
482     GNUNET_SCHEDULER_cancel (session->timeout_task);
483     session->timeout_task = NULL;
484     session->timeout = GNUNET_TIME_UNIT_ZERO_ABS;
485   }
486   notify_session_monitor (plugin,
487                           session,
488                           GNUNET_TRANSPORT_SS_DONE);
489   GNUNET_HELLO_address_free (session->address);
490   GNUNET_break (0 == session->bytes_in_queue);
491   GNUNET_break (0 == session->msgs_in_queue);
492   GNUNET_free (session);
493   return GNUNET_OK;
494 }
495
496
497 /**
498  * Session was idle for too long, so disconnect it
499  *
500  * @param cls the `struct Session *` to disconnect
501  * @param tc scheduler context
502  */
503 static void
504 session_timeout (void *cls,
505                  const struct GNUNET_SCHEDULER_TaskContext *tc)
506 {
507   struct Session *session = cls;
508   struct GNUNET_TIME_Relative left;
509
510   session->timeout_task = NULL;
511   left = GNUNET_TIME_absolute_get_remaining (session->timeout);
512   if (0 != left.rel_value_us)
513   {
514     /* not actually our turn yet, but let's at least update
515        the monitor, it may think we're about to die ... */
516     notify_session_monitor (session->plugin,
517                             session,
518                             GNUNET_TRANSPORT_SS_UPDATE);
519     session->timeout_task = GNUNET_SCHEDULER_add_delayed (left,
520                                                           &session_timeout,
521                                                           session);
522     return;
523   }
524   LOG (GNUNET_ERROR_TYPE_DEBUG,
525        "Session %p was idle for %s, disconnecting\n",
526        session,
527        GNUNET_STRINGS_relative_time_to_string (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
528                                                GNUNET_YES));
529   unix_plugin_session_disconnect (session->plugin, session);
530 }
531
532
533 /**
534  * Increment session timeout due to activity.  We do not immediately
535  * notify the monitor here as that might generate excessive
536  * signalling.
537  *
538  * @param session session for which the timeout should be rescheduled
539  */
540 static void
541 reschedule_session_timeout (struct Session *session)
542 {
543   GNUNET_assert (NULL != session->timeout_task);
544   session->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
545 }
546
547
548 /**
549  * Convert unix path to a `struct sockaddr_un *`
550  *
551  * @param unixpath path to convert
552  * @param[out] sock_len set to the length of the address
553  * @return converted unix path
554  */
555 static struct sockaddr_un *
556 unix_address_to_sockaddr (const char *unixpath,
557                           socklen_t *sock_len)
558 {
559   struct sockaddr_un *un;
560   size_t slen;
561
562   GNUNET_assert (0 < strlen (unixpath));        /* sanity check */
563   un = GNUNET_new (struct sockaddr_un);
564   un->sun_family = AF_UNIX;
565   slen = strlen (unixpath);
566   if (slen >= sizeof (un->sun_path))
567     slen = sizeof (un->sun_path) - 1;
568   memcpy (un->sun_path, unixpath, slen);
569   un->sun_path[slen] = '\0';
570   slen = sizeof (struct sockaddr_un);
571 #if HAVE_SOCKADDR_IN_SIN_LEN
572   un->sun_len = (u_char) slen;
573 #endif
574   (*sock_len) = slen;
575   return un;
576 }
577
578
579 /**
580  * Closure to #lookup_session_it().
581  */
582 struct LookupCtx
583 {
584   /**
585    * Location to store the session, if found.
586    */
587   struct Session *res;
588
589   /**
590    * Address we are looking for.
591    */
592   const struct GNUNET_HELLO_Address *address;
593 };
594
595
596 /**
597  * Function called to find a session by address.
598  *
599  * @param cls the `struct LookupCtx *`
600  * @param key peer we are looking for (unused)
601  * @param value a session
602  * @return #GNUNET_YES if not found (continue looking), #GNUNET_NO on success
603  */
604 static int
605 lookup_session_it (void *cls,
606                    const struct GNUNET_PeerIdentity * key,
607                    void *value)
608 {
609   struct LookupCtx *lctx = cls;
610   struct Session *session = value;
611
612   if (0 == GNUNET_HELLO_address_cmp (lctx->address,
613                                      session->address))
614   {
615     lctx->res = session;
616     return GNUNET_NO;
617   }
618   return GNUNET_YES;
619 }
620
621
622 /**
623  * Find an existing session by address.
624  *
625  * @param plugin the plugin
626  * @param address the address to find
627  * @return NULL if session was not found
628  */
629 static struct Session *
630 lookup_session (struct Plugin *plugin,
631                 const struct GNUNET_HELLO_Address *address)
632 {
633   struct LookupCtx lctx;
634
635   lctx.address = address;
636   lctx.res = NULL;
637   GNUNET_CONTAINER_multipeermap_get_multiple (plugin->session_map,
638                                               &address->peer,
639                                               &lookup_session_it, &lctx);
640   return lctx.res;
641 }
642
643
644 /**
645  * Function that is called to get the keepalive factor.
646  * #GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT is divided by this number to
647  * calculate the interval between keepalive packets.
648  *
649  * @param cls closure with the `struct Plugin`
650  * @return keepalive factor
651  */
652 static unsigned int
653 unix_plugin_query_keepalive_factor (void *cls)
654 {
655   return 3;
656 }
657
658
659 /**
660  * Actually send out the message, assume we've got the address and
661  * send_handle squared away!
662  *
663  * @param cls closure
664  * @param send_handle which handle to send message on
665  * @param target who should receive this message (ignored by UNIX)
666  * @param msgbuf one or more GNUNET_MessageHeader(s) strung together
667  * @param msgbuf_size the size of the @a msgbuf to send
668  * @param priority how important is the message (ignored by UNIX)
669  * @param timeout when should we time out (give up) if we can not transmit?
670  * @param addr the addr to send the message to, needs to be a sockaddr for us
671  * @param addrlen the len of @a addr
672  * @param payload bytes payload to send
673  * @param cont continuation to call once the message has
674  *        been transmitted (or if the transport is ready
675  *        for the next transmission call; or if the
676  *        peer disconnected...)
677  * @param cont_cls closure for @a cont
678  * @return on success the number of bytes written, RETRY for retry, -1 on errors
679  */
680 static ssize_t
681 unix_real_send (void *cls,
682                 struct GNUNET_NETWORK_Handle *send_handle,
683                 const struct GNUNET_PeerIdentity *target,
684                 const char *msgbuf,
685                 size_t msgbuf_size,
686                 unsigned int priority,
687                 struct GNUNET_TIME_Absolute timeout,
688                 const struct UnixAddress *addr,
689                 size_t addrlen,
690                 size_t payload,
691                 GNUNET_TRANSPORT_TransmitContinuation cont,
692                 void *cont_cls)
693 {
694   struct Plugin *plugin = cls;
695   ssize_t sent;
696   struct sockaddr_un *un;
697   socklen_t un_len;
698   const char *unixpath;
699
700   if (NULL == send_handle)
701   {
702     GNUNET_break (0); /* We do not have a send handle */
703     return GNUNET_SYSERR;
704   }
705   if ((NULL == addr) || (0 == addrlen))
706   {
707     GNUNET_break (0); /* Can never send if we don't have an address */
708     return GNUNET_SYSERR;
709   }
710
711   /* Prepare address */
712   unixpath = (const char *)  &addr[1];
713   if (NULL == (un = unix_address_to_sockaddr (unixpath,
714                                               &un_len)))
715   {
716     GNUNET_break (0);
717     return -1;
718   }
719
720   if ((GNUNET_YES == plugin->is_abstract) &&
721       (0 != (UNIX_OPTIONS_USE_ABSTRACT_SOCKETS & ntohl(addr->options) )) )
722   {
723     un->sun_path[0] = '\0';
724   }
725 resend:
726   /* Send the data */
727   sent = GNUNET_NETWORK_socket_sendto (send_handle,
728                                        msgbuf,
729                                        msgbuf_size,
730                                        (const struct sockaddr *) un,
731                                        un_len);
732   if (GNUNET_SYSERR == sent)
733   {
734     if ( (EAGAIN == errno) ||
735          (ENOBUFS == errno) )
736     {
737       GNUNET_free (un);
738       return RETRY; /* We have to retry later  */
739     }
740     if (EMSGSIZE == errno)
741     {
742       socklen_t size = 0;
743       socklen_t len = sizeof (size);
744
745       GNUNET_NETWORK_socket_getsockopt ((struct GNUNET_NETWORK_Handle *)
746                                         send_handle, SOL_SOCKET, SO_SNDBUF, &size,
747                                         &len);
748       if (size < msgbuf_size)
749       {
750         LOG (GNUNET_ERROR_TYPE_DEBUG,
751              "Trying to increase socket buffer size from %u to %u for message size %u\n",
752              (unsigned int) size,
753              (unsigned int) ((msgbuf_size / 1000) + 2) * 1000,
754              (unsigned int) msgbuf_size);
755         size = ((msgbuf_size / 1000) + 2) * 1000;
756         if (GNUNET_OK ==
757             GNUNET_NETWORK_socket_setsockopt ((struct GNUNET_NETWORK_Handle *) send_handle,
758                                               SOL_SOCKET, SO_SNDBUF,
759                                               &size, sizeof (size)))
760           goto resend; /* Increased buffer size, retry sending */
761         else
762         {
763           /* Could not increase buffer size: error, no retry */
764           GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "setsockopt");
765           GNUNET_free (un);
766           return GNUNET_SYSERR;
767         }
768       }
769       else
770       {
771         /* Buffer is bigger than message:  error, no retry
772          * This should never happen!*/
773         GNUNET_break (0);
774         GNUNET_free (un);
775         return GNUNET_SYSERR;
776       }
777     }
778   }
779
780   LOG (GNUNET_ERROR_TYPE_DEBUG,
781        "UNIX transmitted %u-byte message to %s (%d: %s)\n",
782        (unsigned int) msgbuf_size,
783        GNUNET_a2s ((const struct sockaddr *)un, un_len),
784        (int) sent,
785        (sent < 0) ? STRERROR (errno) : "ok");
786   GNUNET_free (un);
787   return sent;
788 }
789
790
791 /**
792  * Function obtain the network type for a session
793  *
794  * @param cls closure ('struct Plugin*')
795  * @param session the session
796  * @return the network type in HBO or #GNUNET_SYSERR
797  */
798 static enum GNUNET_ATS_Network_Type
799 unix_plugin_get_network (void *cls,
800                          struct Session *session)
801 {
802   GNUNET_assert (NULL != session);
803   return GNUNET_ATS_NET_LOOPBACK;
804 }
805
806
807 /**
808  * Creates a new outbound session the transport service will use to send data to the
809  * peer
810  *
811  * @param cls the plugin
812  * @param address the address
813  * @return the session or NULL of max connections exceeded
814  */
815 static struct Session *
816 unix_plugin_get_session (void *cls,
817                          const struct GNUNET_HELLO_Address *address)
818 {
819   struct Plugin *plugin = cls;
820   struct Session *session;
821   struct UnixAddress *ua;
822   char * addrstr;
823   uint32_t addr_str_len;
824   uint32_t addr_option;
825
826   ua = (struct UnixAddress *) address->address;
827   if ((NULL == address->address) || (0 == address->address_length) ||
828                 (sizeof (struct UnixAddress) > address->address_length))
829   {
830     GNUNET_break (0);
831     return NULL;
832   }
833   addrstr = (char *) &ua[1];
834   addr_str_len = ntohl (ua->addrlen);
835   addr_option = ntohl (ua->options);
836
837   if ( (0 != (UNIX_OPTIONS_USE_ABSTRACT_SOCKETS & addr_option)) &&
838     (GNUNET_NO == plugin->is_abstract))
839   {
840     return NULL;
841   }
842
843   if (addr_str_len != address->address_length - sizeof (struct UnixAddress))
844   {
845     return NULL; /* This can be a legacy address */
846   }
847
848   if ('\0' != addrstr[addr_str_len - 1])
849   {
850     GNUNET_break (0);
851     return NULL;
852   }
853   if (strlen (addrstr) + 1 != addr_str_len)
854   {
855     GNUNET_break (0);
856     return NULL;
857   }
858
859   /* Check if a session for this address already exists */
860   if (NULL != (session = lookup_session (plugin,
861                                          address)))
862     {
863     LOG (GNUNET_ERROR_TYPE_DEBUG,
864          "Found existing session %p for address `%s'\n",
865          session,
866          unix_plugin_address_to_string (NULL,
867                                         address->address,
868                                         address->address_length));
869     return session;
870   }
871
872   /* create a new session */
873   session = GNUNET_new (struct Session);
874   session->target = address->peer;
875   session->address = GNUNET_HELLO_address_copy (address);
876   session->plugin = plugin;
877   session->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
878   session->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
879                                                         &session_timeout,
880                                                         session);
881   LOG (GNUNET_ERROR_TYPE_DEBUG,
882        "Creating a new session %p for address `%s'\n",
883        session,
884        unix_plugin_address_to_string (NULL,
885                                       address->address,
886                                       address->address_length));
887   (void) GNUNET_CONTAINER_multipeermap_put (plugin->session_map,
888                                             &address->peer, session,
889                                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
890   GNUNET_STATISTICS_set (plugin->env->stats,
891                          "# UNIX sessions active",
892                          GNUNET_CONTAINER_multipeermap_size (plugin->session_map),
893                          GNUNET_NO);
894   notify_session_monitor (plugin,
895                           session,
896                           GNUNET_TRANSPORT_SS_INIT);
897   notify_session_monitor (plugin,
898                           session,
899                           GNUNET_TRANSPORT_SS_UP);
900   return session;
901 }
902
903
904 /**
905  * Function that will be called whenever the transport service wants
906  * to notify the plugin that a session is still active and in use and
907  * therefore the session timeout for this session has to be updated
908  *
909  * @param cls closure with the `struct Plugin *`
910  * @param peer which peer was the session for
911  * @param session which session is being updated
912  */
913 static void
914 unix_plugin_update_session_timeout (void *cls,
915                                     const struct GNUNET_PeerIdentity *peer,
916                                     struct Session *session)
917 {
918   struct Plugin *plugin = cls;
919
920   if (GNUNET_OK !=
921       GNUNET_CONTAINER_multipeermap_contains_value (plugin->session_map,
922                                                     &session->target,
923                                                     session))
924   {
925     GNUNET_break (0);
926     return;
927   }
928   reschedule_session_timeout (session);
929 }
930
931
932 /**
933  * Demultiplexer for UNIX messages
934  *
935  * @param plugin the main plugin for this transport
936  * @param sender from which peer the message was received
937  * @param currhdr pointer to the header of the message
938  * @param ua address to look for
939  * @param ua_len length of the address @a ua
940  */
941 static void
942 unix_demultiplexer (struct Plugin *plugin,
943                     struct GNUNET_PeerIdentity *sender,
944                     const struct GNUNET_MessageHeader *currhdr,
945                     const struct UnixAddress *ua,
946                     size_t ua_len)
947 {
948   struct Session *session;
949   struct GNUNET_HELLO_Address *address;
950
951   GNUNET_assert (ua_len >= sizeof (struct UnixAddress));
952   LOG (GNUNET_ERROR_TYPE_DEBUG,
953        "Received message from %s\n",
954        unix_plugin_address_to_string (NULL, ua, ua_len));
955   GNUNET_STATISTICS_update (plugin->env->stats,
956                             "# bytes received via UNIX",
957                             ntohs (currhdr->size),
958                             GNUNET_NO);
959
960   /* Look for existing session */
961   address = GNUNET_HELLO_address_allocate (sender,
962                                            PLUGIN_NAME,
963                                            ua, ua_len,
964                                            GNUNET_HELLO_ADDRESS_INFO_NONE); /* UNIX does not have "inbound" sessions */
965   session = lookup_session (plugin, address);
966   if (NULL == session)
967   {
968     session = unix_plugin_get_session (plugin, address);
969     /* Notify transport and ATS about new inbound session */
970     plugin->env->session_start (NULL,
971                                 session->address,
972                                 session,
973                                 GNUNET_ATS_NET_LOOPBACK);
974   }
975   else
976   {
977     reschedule_session_timeout (session);
978   }
979   GNUNET_HELLO_address_free (address);
980   plugin->env->receive (plugin->env->cls,
981                         session->address,
982                         session,
983                         currhdr);
984 }
985
986
987 /**
988  * Read from UNIX domain socket (it is ready).
989  *
990  * @param plugin the plugin
991  */
992 static void
993 unix_plugin_do_read (struct Plugin *plugin)
994 {
995   char buf[65536] GNUNET_ALIGN;
996   struct UnixAddress *ua;
997   struct UNIXMessage *msg;
998   struct GNUNET_PeerIdentity sender;
999   struct sockaddr_un un;
1000   socklen_t addrlen;
1001   ssize_t ret;
1002   int offset;
1003   int tsize;
1004   int is_abstract;
1005   char *msgbuf;
1006   const struct GNUNET_MessageHeader *currhdr;
1007   uint16_t csize;
1008   size_t ua_len;
1009
1010   addrlen = sizeof (un);
1011   memset (&un, 0, sizeof (un));
1012   ret = GNUNET_NETWORK_socket_recvfrom (plugin->unix_sock.desc,
1013                                         buf, sizeof (buf),
1014                                         (struct sockaddr *) &un,
1015                                         &addrlen);
1016   if ((GNUNET_SYSERR == ret) && ((errno == EAGAIN) || (errno == ENOBUFS)))
1017     return;
1018   if (GNUNET_SYSERR == ret)
1019   {
1020     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
1021                          "recvfrom");
1022     return;
1023   }
1024   else
1025   {
1026     LOG (GNUNET_ERROR_TYPE_DEBUG,
1027          "Read %d bytes from socket %s\n",
1028          (int) ret,
1029          un.sun_path);
1030   }
1031
1032   GNUNET_assert (AF_UNIX == (un.sun_family));
1033   is_abstract = GNUNET_NO;
1034   if ('\0' == un.sun_path[0])
1035   {
1036     un.sun_path[0] = '@';
1037     is_abstract = GNUNET_YES;
1038   }
1039
1040   ua_len = sizeof (struct UnixAddress) + strlen (un.sun_path) + 1;
1041   ua = GNUNET_malloc (ua_len);
1042   ua->addrlen = htonl (strlen (&un.sun_path[0]) +1);
1043   memcpy (&ua[1], &un.sun_path[0], strlen (un.sun_path) + 1);
1044   if (is_abstract)
1045     ua->options = htonl(UNIX_OPTIONS_USE_ABSTRACT_SOCKETS);
1046   else
1047     ua->options = htonl(UNIX_OPTIONS_NONE);
1048
1049   msg = (struct UNIXMessage *) buf;
1050   csize = ntohs (msg->header.size);
1051   if ((csize < sizeof (struct UNIXMessage)) || (csize > ret))
1052   {
1053     GNUNET_break_op (0);
1054     GNUNET_free (ua);
1055     return;
1056   }
1057   msgbuf = (char *) &msg[1];
1058   memcpy (&sender,
1059           &msg->sender,
1060           sizeof (struct GNUNET_PeerIdentity));
1061   offset = 0;
1062   tsize = csize - sizeof (struct UNIXMessage);
1063   while (offset + sizeof (struct GNUNET_MessageHeader) <= tsize)
1064   {
1065     currhdr = (struct GNUNET_MessageHeader *) &msgbuf[offset];
1066     csize = ntohs (currhdr->size);
1067     if ((csize < sizeof (struct GNUNET_MessageHeader)) ||
1068         (csize > tsize - offset))
1069     {
1070       GNUNET_break_op (0);
1071       break;
1072     }
1073     unix_demultiplexer (plugin, &sender, currhdr, ua, ua_len);
1074     offset += csize;
1075   }
1076   GNUNET_free (ua);
1077 }
1078
1079
1080 /**
1081  * Write to UNIX domain socket (it is ready).
1082  *
1083  * @param plugin handle to the plugin
1084  */
1085 static void
1086 unix_plugin_do_write (struct Plugin *plugin)
1087 {
1088   ssize_t sent = 0;
1089   struct UNIXMessageWrapper *msgw;
1090   struct Session *session;
1091   int did_delete;
1092
1093   session = NULL;
1094   did_delete = GNUNET_NO;
1095   while (NULL != (msgw = plugin->msg_head))
1096   {
1097     if (GNUNET_TIME_absolute_get_remaining (msgw->timeout).rel_value_us > 0)
1098       break; /* Message is ready for sending */
1099     /* Message has a timeout */
1100     did_delete = GNUNET_YES;
1101     LOG (GNUNET_ERROR_TYPE_DEBUG,
1102          "Timeout for message with %u bytes \n",
1103          (unsigned int) msgw->msgsize);
1104     GNUNET_CONTAINER_DLL_remove (plugin->msg_head,
1105                                  plugin->msg_tail,
1106                                  msgw);
1107     session = msgw->session;
1108     session->msgs_in_queue--;
1109     GNUNET_assert (session->bytes_in_queue >= msgw->msgsize);
1110     session->bytes_in_queue -= msgw->msgsize;
1111     GNUNET_assert (plugin->bytes_in_queue >= msgw->msgsize);
1112     plugin->bytes_in_queue -= msgw->msgsize;
1113     GNUNET_STATISTICS_set (plugin->env->stats,
1114                            "# bytes currently in UNIX buffers",
1115                            plugin->bytes_in_queue,
1116                            GNUNET_NO);
1117     GNUNET_STATISTICS_update (plugin->env->stats,
1118                               "# UNIX bytes discarded",
1119                               msgw->msgsize,
1120                               GNUNET_NO);
1121     if (NULL != msgw->cont)
1122       msgw->cont (msgw->cont_cls,
1123                   &msgw->session->target,
1124                   GNUNET_SYSERR,
1125                   msgw->payload,
1126                   0);
1127     GNUNET_free (msgw->msg);
1128     GNUNET_free (msgw);
1129   }
1130   if (NULL == msgw)
1131   {
1132     if (GNUNET_YES == did_delete)
1133       notify_session_monitor (plugin,
1134                               session,
1135                               GNUNET_TRANSPORT_SS_UPDATE);
1136     return; /* Nothing to send at the moment */
1137   }
1138   session = msgw->session;
1139   sent = unix_real_send (plugin,
1140                          plugin->unix_sock.desc,
1141                          &session->target,
1142                          (const char *) msgw->msg,
1143                          msgw->msgsize,
1144                          msgw->priority,
1145                          msgw->timeout,
1146                          msgw->session->address->address,
1147                          msgw->session->address->address_length,
1148                          msgw->payload,
1149                          msgw->cont, msgw->cont_cls);
1150   if (RETRY == sent)
1151   {
1152     GNUNET_STATISTICS_update (plugin->env->stats,
1153                               "# UNIX retry attempts",
1154                               1, GNUNET_NO);
1155     notify_session_monitor (plugin,
1156                             session,
1157                             GNUNET_TRANSPORT_SS_UPDATE);
1158     return;
1159   }
1160   GNUNET_CONTAINER_DLL_remove (plugin->msg_head,
1161                                plugin->msg_tail,
1162                                msgw);
1163   session->msgs_in_queue--;
1164   GNUNET_assert (session->bytes_in_queue >= msgw->msgsize);
1165   session->bytes_in_queue -= msgw->msgsize;
1166   GNUNET_assert (plugin->bytes_in_queue >= msgw->msgsize);
1167   plugin->bytes_in_queue -= msgw->msgsize;
1168   GNUNET_STATISTICS_set (plugin->env->stats,
1169                          "# bytes currently in UNIX buffers",
1170                          plugin->bytes_in_queue, GNUNET_NO);
1171   notify_session_monitor (plugin,
1172                           session,
1173                           GNUNET_TRANSPORT_SS_UPDATE);
1174   if (GNUNET_SYSERR == sent)
1175   {
1176     /* failed and no retry */
1177     if (NULL != msgw->cont)
1178       msgw->cont (msgw->cont_cls,
1179                   &msgw->session->target,
1180                   GNUNET_SYSERR,
1181                   msgw->payload, 0);
1182     GNUNET_STATISTICS_update (plugin->env->stats,
1183                               "# UNIX bytes discarded",
1184                               msgw->msgsize,
1185                               GNUNET_NO);
1186     GNUNET_free (msgw->msg);
1187     GNUNET_free (msgw);
1188     return;
1189   }
1190   /* successfully sent bytes */
1191   GNUNET_break (sent > 0);
1192   GNUNET_STATISTICS_update (plugin->env->stats,
1193                             "# bytes transmitted via UNIX",
1194                             msgw->msgsize,
1195                             GNUNET_NO);
1196   if (NULL != msgw->cont)
1197     msgw->cont (msgw->cont_cls,
1198                 &msgw->session->target,
1199                 GNUNET_OK,
1200                 msgw->payload,
1201                 msgw->msgsize);
1202   GNUNET_free (msgw->msg);
1203   GNUNET_free (msgw);
1204 }
1205
1206
1207 /**
1208  * We have been notified that our socket has something to read.
1209  * Then reschedule this function to be called again once more is available.
1210  *
1211  * @param cls the plugin handle
1212  * @param tc the scheduling context
1213  */
1214 static void
1215 unix_plugin_select_read (void *cls,
1216                          const struct GNUNET_SCHEDULER_TaskContext *tc)
1217 {
1218   struct Plugin *plugin = cls;
1219
1220   plugin->read_task = NULL;
1221   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1222     return;
1223   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_READ_READY))
1224     unix_plugin_do_read (plugin);
1225   plugin->read_task =
1226     GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
1227                                    plugin->unix_sock.desc,
1228                                    &unix_plugin_select_read, plugin);
1229 }
1230
1231
1232 /**
1233  * We have been notified that our socket is ready to write.
1234  * Then reschedule this function to be called again once more is available.
1235  *
1236  * @param cls the plugin handle
1237  * @param tc the scheduling context
1238  */
1239 static void
1240 unix_plugin_select_write (void *cls,
1241                          const struct GNUNET_SCHEDULER_TaskContext *tc)
1242 {
1243   struct Plugin *plugin = cls;
1244
1245   plugin->write_task = NULL;
1246   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1247     return;
1248   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY))
1249     unix_plugin_do_write (plugin);
1250   if (NULL == plugin->msg_head)
1251     return; /* write queue empty */
1252   plugin->write_task =
1253     GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
1254                                     plugin->unix_sock.desc,
1255                                     &unix_plugin_select_write, plugin);
1256 }
1257
1258
1259 /**
1260  * Function that can be used by the transport service to transmit
1261  * a message using the plugin.   Note that in the case of a
1262  * peer disconnecting, the continuation MUST be called
1263  * prior to the disconnect notification itself.  This function
1264  * will be called with this peer's HELLO message to initiate
1265  * a fresh connection to another peer.
1266  *
1267  * @param cls closure
1268  * @param session which session must be used
1269  * @param msgbuf the message to transmit
1270  * @param msgbuf_size number of bytes in @a msgbuf
1271  * @param priority how important is the message (most plugins will
1272  *                 ignore message priority and just FIFO)
1273  * @param to how long to wait at most for the transmission (does not
1274  *                require plugins to discard the message after the timeout,
1275  *                just advisory for the desired delay; most plugins will ignore
1276  *                this as well)
1277  * @param cont continuation to call once the message has
1278  *        been transmitted (or if the transport is ready
1279  *        for the next transmission call; or if the
1280  *        peer disconnected...); can be NULL
1281  * @param cont_cls closure for @a cont
1282  * @return number of bytes used (on the physical network, with overheads);
1283  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
1284  *         and does NOT mean that the message was not transmitted (DV)
1285  */
1286 static ssize_t
1287 unix_plugin_send (void *cls,
1288                   struct Session *session,
1289                   const char *msgbuf,
1290                   size_t msgbuf_size,
1291                   unsigned int priority,
1292                   struct GNUNET_TIME_Relative to,
1293                   GNUNET_TRANSPORT_TransmitContinuation cont,
1294                   void *cont_cls)
1295 {
1296   struct Plugin *plugin = cls;
1297   struct UNIXMessageWrapper *wrapper;
1298   struct UNIXMessage *message;
1299   int ssize;
1300
1301   if (GNUNET_OK !=
1302       GNUNET_CONTAINER_multipeermap_contains_value (plugin->session_map,
1303                                                     &session->target,
1304                                                     session))
1305   {
1306     LOG (GNUNET_ERROR_TYPE_ERROR,
1307          "Invalid session for peer `%s' `%s'\n",
1308          GNUNET_i2s (&session->target),
1309          unix_plugin_address_to_string (NULL,
1310                                         session->address->address,
1311                                         session->address->address_length));
1312     GNUNET_break (0);
1313     return GNUNET_SYSERR;
1314   }
1315   LOG (GNUNET_ERROR_TYPE_DEBUG,
1316        "Sending %u bytes with session for peer `%s' `%s'\n",
1317        msgbuf_size,
1318        GNUNET_i2s (&session->target),
1319        unix_plugin_address_to_string (NULL,
1320                                       session->address->address,
1321                                       session->address->address_length));
1322   ssize = sizeof (struct UNIXMessage) + msgbuf_size;
1323   message = GNUNET_malloc (sizeof (struct UNIXMessage) + msgbuf_size);
1324   message->header.size = htons (ssize);
1325   message->header.type = htons (0);
1326   memcpy (&message->sender, plugin->env->my_identity,
1327           sizeof (struct GNUNET_PeerIdentity));
1328   memcpy (&message[1], msgbuf, msgbuf_size);
1329   wrapper = GNUNET_new (struct UNIXMessageWrapper);
1330   wrapper->msg = message;
1331   wrapper->msgsize = ssize;
1332   wrapper->payload = msgbuf_size;
1333   wrapper->priority = priority;
1334   wrapper->timeout = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (),
1335                                                to);
1336   wrapper->cont = cont;
1337   wrapper->cont_cls = cont_cls;
1338   wrapper->session = session;
1339   GNUNET_CONTAINER_DLL_insert_tail (plugin->msg_head,
1340                                     plugin->msg_tail,
1341                                     wrapper);
1342   plugin->bytes_in_queue += ssize;
1343   session->bytes_in_queue += ssize;
1344   session->msgs_in_queue++;
1345   GNUNET_STATISTICS_set (plugin->env->stats,
1346                          "# bytes currently in UNIX buffers",
1347                          plugin->bytes_in_queue,
1348                          GNUNET_NO);
1349   notify_session_monitor (plugin,
1350                           session,
1351                           GNUNET_TRANSPORT_SS_UPDATE);
1352   if (NULL == plugin->write_task)
1353     plugin->write_task =
1354       GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
1355                                       plugin->unix_sock.desc,
1356                                       &unix_plugin_select_write, plugin);
1357   return ssize;
1358 }
1359
1360
1361 /**
1362  * Create a slew of UNIX sockets.  If possible, use IPv6 and IPv4.
1363  *
1364  * @param cls closure for server start, should be a `struct Plugin *`
1365  * @return number of sockets created or #GNUNET_SYSERR on error
1366  */
1367 static int
1368 unix_transport_server_start (void *cls)
1369 {
1370   struct Plugin *plugin = cls;
1371   struct sockaddr_un *un;
1372   socklen_t un_len;
1373
1374   un = unix_address_to_sockaddr (plugin->unix_socket_path,
1375                                  &un_len);
1376   if (GNUNET_YES == plugin->is_abstract)
1377   {
1378     plugin->unix_socket_path[0] = '@';
1379     un->sun_path[0] = '\0';
1380   }
1381   plugin->unix_sock.desc =
1382       GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_DGRAM, 0);
1383   if (NULL == plugin->unix_sock.desc)
1384   {
1385     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
1386     GNUNET_free (un);
1387     return GNUNET_SYSERR;
1388   }
1389   if ('\0' != un->sun_path[0])
1390   {
1391     if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (un->sun_path))
1392     {
1393       LOG (GNUNET_ERROR_TYPE_ERROR, _("Cannot create path to `%s'\n"),
1394           un->sun_path);
1395       GNUNET_NETWORK_socket_close (plugin->unix_sock.desc);
1396       plugin->unix_sock.desc = NULL;
1397       GNUNET_free (un);
1398       return GNUNET_SYSERR;
1399     }
1400   }
1401   if (GNUNET_OK !=
1402       GNUNET_NETWORK_socket_bind (plugin->unix_sock.desc,
1403                                   (const struct sockaddr *) un, un_len))
1404   {
1405     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
1406     LOG (GNUNET_ERROR_TYPE_ERROR, _("Cannot bind to `%s'\n"),
1407         un->sun_path);
1408     GNUNET_NETWORK_socket_close (plugin->unix_sock.desc);
1409     plugin->unix_sock.desc = NULL;
1410     GNUNET_free (un);
1411     return GNUNET_SYSERR;
1412   }
1413   LOG (GNUNET_ERROR_TYPE_DEBUG,
1414        "Bound to `%s'\n",
1415        plugin->unix_socket_path);
1416   plugin->read_task =
1417     GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
1418                                    plugin->unix_sock.desc,
1419                                    &unix_plugin_select_read, plugin);
1420   GNUNET_free (un);
1421   return 1;
1422 }
1423
1424
1425 /**
1426  * Function that will be called to check if a binary address for this
1427  * plugin is well-formed and corresponds to an address for THIS peer
1428  * (as per our configuration).  Naturally, if absolutely necessary,
1429  * plugins can be a bit conservative in their answer, but in general
1430  * plugins should make sure that the address does not redirect
1431  * traffic to a 3rd party that might try to man-in-the-middle our
1432  * traffic.
1433  *
1434  * @param cls closure, should be our handle to the Plugin
1435  * @param addr pointer to the address
1436  * @param addrlen length of @a addr
1437  * @return #GNUNET_OK if this is a plausible address for this peer
1438  *         and transport, #GNUNET_SYSERR if not
1439  *
1440  */
1441 static int
1442 unix_plugin_check_address (void *cls,
1443                            const void *addr,
1444                            size_t addrlen)
1445 {
1446   struct Plugin* plugin = cls;
1447   const struct UnixAddress *ua = addr;
1448   char *addrstr;
1449   size_t addr_str_len;
1450
1451   if ( (NULL == addr) ||
1452        (0 == addrlen) ||
1453        (sizeof (struct UnixAddress) > addrlen) )
1454   {
1455     GNUNET_break (0);
1456     return GNUNET_SYSERR;
1457   }
1458   addrstr = (char *) &ua[1];
1459   addr_str_len = ntohl (ua->addrlen);
1460   if ('\0' != addrstr[addr_str_len - 1])
1461   {
1462     GNUNET_break (0);
1463     return GNUNET_SYSERR;
1464   }
1465   if (strlen (addrstr) + 1 != addr_str_len)
1466   {
1467     GNUNET_break (0);
1468     return GNUNET_SYSERR;
1469   }
1470
1471   if (0 == strcmp (plugin->unix_socket_path, addrstr))
1472         return GNUNET_OK;
1473   return GNUNET_SYSERR;
1474 }
1475
1476
1477 /**
1478  * Convert the transports address to a nice, human-readable
1479  * format.
1480  *
1481  * @param cls closure
1482  * @param type name of the transport that generated the address
1483  * @param addr one of the addresses of the host, NULL for the last address
1484  *        the specific address format depends on the transport
1485  * @param addrlen length of the @a addr
1486  * @param numeric should (IP) addresses be displayed in numeric form?
1487  * @param timeout after how long should we give up?
1488  * @param asc function to call on each string
1489  * @param asc_cls closure for @a asc
1490  */
1491 static void
1492 unix_plugin_address_pretty_printer (void *cls, const char *type,
1493                                     const void *addr,
1494                                     size_t addrlen,
1495                                     int numeric,
1496                                     struct GNUNET_TIME_Relative timeout,
1497                                     GNUNET_TRANSPORT_AddressStringCallback asc,
1498                                     void *asc_cls)
1499 {
1500   const char *ret;
1501
1502   if ( (NULL != addr) && (addrlen > 0))
1503     ret = unix_plugin_address_to_string (NULL,
1504                                          addr,
1505                                          addrlen);
1506   else
1507     ret = NULL;
1508   asc (asc_cls,
1509        ret,
1510        (NULL == ret) ? GNUNET_SYSERR : GNUNET_OK);
1511   asc (asc_cls, NULL, GNUNET_OK);
1512 }
1513
1514
1515 /**
1516  * Function called to convert a string address to
1517  * a binary address.
1518  *
1519  * @param cls closure (`struct Plugin *`)
1520  * @param addr string address
1521  * @param addrlen length of the @a addr (strlen(addr) + '\0')
1522  * @param buf location to store the buffer
1523  *        If the function returns #GNUNET_SYSERR, its contents are undefined.
1524  * @param added length of created address
1525  * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
1526  */
1527 static int
1528 unix_plugin_string_to_address (void *cls,
1529                                const char *addr,
1530                                uint16_t addrlen,
1531                                void **buf, size_t *added)
1532 {
1533   struct UnixAddress *ua;
1534   char *address;
1535   char *plugin;
1536   char *optionstr;
1537   uint32_t options;
1538   size_t ua_size;
1539
1540   /* Format unix.options.address */
1541   address = NULL;
1542   plugin = NULL;
1543   optionstr = NULL;
1544
1545   if ((NULL == addr) || (addrlen == 0))
1546   {
1547     GNUNET_break (0);
1548     return GNUNET_SYSERR;
1549   }
1550   if ('\0' != addr[addrlen - 1])
1551   {
1552     GNUNET_break (0);
1553     return GNUNET_SYSERR;
1554   }
1555   if (strlen (addr) != addrlen - 1)
1556   {
1557     GNUNET_break (0);
1558     return GNUNET_SYSERR;
1559   }
1560   plugin = GNUNET_strdup (addr);
1561   optionstr = strchr (plugin, '.');
1562   if (NULL == optionstr)
1563   {
1564     GNUNET_break (0);
1565     GNUNET_free (plugin);
1566     return GNUNET_SYSERR;
1567   }
1568   optionstr[0] = '\0';
1569   optionstr++;
1570   options = atol (optionstr);
1571   address = strchr (optionstr, '.');
1572   if (NULL == address)
1573   {
1574     GNUNET_break (0);
1575     GNUNET_free (plugin);
1576     return GNUNET_SYSERR;
1577   }
1578   address[0] = '\0';
1579   address++;
1580   if (0 != strcmp(plugin, PLUGIN_NAME))
1581   {
1582     GNUNET_break (0);
1583     GNUNET_free (plugin);
1584     return GNUNET_SYSERR;
1585   }
1586
1587   ua_size = sizeof (struct UnixAddress) + strlen (address) + 1;
1588   ua = GNUNET_malloc (ua_size);
1589   ua->options = htonl (options);
1590   ua->addrlen = htonl (strlen (address) + 1);
1591   memcpy (&ua[1], address, strlen (address) + 1);
1592   GNUNET_free (plugin);
1593
1594   (*buf) = ua;
1595   (*added) = ua_size;
1596   return GNUNET_OK;
1597 }
1598
1599
1600 /**
1601  * Notify transport service about address
1602  *
1603  * @param cls the plugin
1604  * @param tc unused
1605  */
1606 static void
1607 address_notification (void *cls,
1608                       const struct GNUNET_SCHEDULER_TaskContext *tc)
1609 {
1610   struct Plugin *plugin = cls;
1611   struct GNUNET_HELLO_Address *address;
1612   size_t len;
1613   struct UnixAddress *ua;
1614   char *unix_path;
1615
1616   len = sizeof (struct UnixAddress) + strlen (plugin->unix_socket_path) + 1;
1617   ua = GNUNET_malloc (len);
1618   ua->options = htonl (plugin->myoptions);
1619   ua->addrlen = htonl(strlen (plugin->unix_socket_path) + 1);
1620   unix_path = (char *) &ua[1];
1621   memcpy (unix_path, plugin->unix_socket_path, strlen (plugin->unix_socket_path) + 1);
1622
1623   plugin->address_update_task = NULL;
1624   address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
1625                                            PLUGIN_NAME,
1626                                            ua,
1627                                            len,
1628                                            GNUNET_HELLO_ADDRESS_INFO_NONE);
1629   plugin->env->notify_address (plugin->env->cls,
1630                                GNUNET_YES,
1631                                address);
1632   GNUNET_free (ua);
1633   GNUNET_free (address);
1634 }
1635
1636
1637 /**
1638  * Function called on sessions to disconnect
1639  *
1640  * @param cls the plugin
1641  * @param key peer identity (unused)
1642  * @param value the `struct Session *` to disconnect
1643  * @return #GNUNET_YES (always, continue to iterate)
1644  */
1645 static int
1646 get_session_delete_it (void *cls,
1647                        const struct GNUNET_PeerIdentity *key,
1648                        void *value)
1649 {
1650   struct Plugin *plugin = cls;
1651   struct Session *session = value;
1652
1653   unix_plugin_session_disconnect (plugin, session);
1654   return GNUNET_YES;
1655 }
1656
1657
1658 /**
1659  * Disconnect from a remote node.  Clean up session if we have one for this peer
1660  *
1661  * @param cls closure for this call (should be handle to Plugin)
1662  * @param target the peeridentity of the peer to disconnect
1663  * @return #GNUNET_OK on success, #GNUNET_SYSERR if the operation failed
1664  */
1665 static void
1666 unix_plugin_peer_disconnect (void *cls,
1667                              const struct GNUNET_PeerIdentity *target)
1668 {
1669   struct Plugin *plugin = cls;
1670
1671   GNUNET_CONTAINER_multipeermap_get_multiple (plugin->session_map,
1672                                               target,
1673                                               &get_session_delete_it, plugin);
1674 }
1675
1676
1677 /**
1678  * Return information about the given session to the
1679  * monitor callback.
1680  *
1681  * @param cls the `struct Plugin` with the monitor callback (`sic`)
1682  * @param peer peer we send information about
1683  * @param value our `struct Session` to send information about
1684  * @return #GNUNET_OK (continue to iterate)
1685  */
1686 static int
1687 send_session_info_iter (void *cls,
1688                         const struct GNUNET_PeerIdentity *peer,
1689                         void *value)
1690 {
1691   struct Plugin *plugin = cls;
1692   struct Session *session = value;
1693
1694   notify_session_monitor (plugin,
1695                           session,
1696                           GNUNET_TRANSPORT_SS_INIT);
1697   notify_session_monitor (plugin,
1698                           session,
1699                           GNUNET_TRANSPORT_SS_UP);
1700   return GNUNET_OK;
1701 }
1702
1703
1704 /**
1705  * Begin monitoring sessions of a plugin.  There can only
1706  * be one active monitor per plugin (i.e. if there are
1707  * multiple monitors, the transport service needs to
1708  * multiplex the generated events over all of them).
1709  *
1710  * @param cls closure of the plugin
1711  * @param sic callback to invoke, NULL to disable monitor;
1712  *            plugin will being by iterating over all active
1713  *            sessions immediately and then enter monitor mode
1714  * @param sic_cls closure for @a sic
1715  */
1716 static void
1717 unix_plugin_setup_monitor (void *cls,
1718                            GNUNET_TRANSPORT_SessionInfoCallback sic,
1719                            void *sic_cls)
1720 {
1721   struct Plugin *plugin = cls;
1722
1723   plugin->sic = sic;
1724   plugin->sic_cls = sic_cls;
1725   if (NULL != sic)
1726   {
1727     GNUNET_CONTAINER_multipeermap_iterate (plugin->session_map,
1728                                            &send_session_info_iter,
1729                                            plugin);
1730     /* signal end of first iteration */
1731     sic (sic_cls, NULL, NULL);
1732   }
1733 }
1734
1735
1736 /**
1737  * The exported method.  Initializes the plugin and returns a
1738  * struct with the callbacks.
1739  *
1740  * @param cls the plugin's execution environment
1741  * @return NULL on error, plugin functions otherwise
1742  */
1743 void *
1744 libgnunet_plugin_transport_unix_init (void *cls)
1745 {
1746   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1747   struct GNUNET_TRANSPORT_PluginFunctions *api;
1748   struct Plugin *plugin;
1749   int sockets_created;
1750
1751   if (NULL == env->receive)
1752   {
1753     /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
1754        initialze the plugin or the API */
1755     api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
1756     api->cls = NULL;
1757     api->address_pretty_printer = &unix_plugin_address_pretty_printer;
1758     api->address_to_string = &unix_plugin_address_to_string;
1759     api->string_to_address = &unix_plugin_string_to_address;
1760     return api;
1761   }
1762
1763   plugin = GNUNET_new (struct Plugin);
1764   if (GNUNET_OK !=
1765       GNUNET_CONFIGURATION_get_value_filename (env->cfg,
1766                                                "transport-unix",
1767                                                "UNIXPATH",
1768                                                &plugin->unix_socket_path))
1769   {
1770     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
1771                                "transport-unix",
1772                                "UNIXPATH");
1773     GNUNET_free (plugin);
1774     return NULL;
1775   }
1776
1777   plugin->env = env;
1778
1779   /* Initialize my flags */
1780 #ifdef LINUX
1781   plugin->is_abstract = GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg,
1782                                                               "testing",
1783                                                               "USE_ABSTRACT_SOCKETS");
1784 #endif
1785   plugin->myoptions = UNIX_OPTIONS_NONE;
1786   if (GNUNET_YES == plugin->is_abstract)
1787     plugin->myoptions = UNIX_OPTIONS_USE_ABSTRACT_SOCKETS;
1788
1789   api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
1790   api->cls = plugin;
1791   api->get_session = &unix_plugin_get_session;
1792   api->send = &unix_plugin_send;
1793   api->disconnect_peer = &unix_plugin_peer_disconnect;
1794   api->disconnect_session = &unix_plugin_session_disconnect;
1795   api->query_keepalive_factor = &unix_plugin_query_keepalive_factor;
1796   api->address_pretty_printer = &unix_plugin_address_pretty_printer;
1797   api->address_to_string = &unix_plugin_address_to_string;
1798   api->check_address = &unix_plugin_check_address;
1799   api->string_to_address = &unix_plugin_string_to_address;
1800   api->get_network = &unix_plugin_get_network;
1801   api->update_session_timeout = &unix_plugin_update_session_timeout;
1802   api->setup_monitor = &unix_plugin_setup_monitor;
1803   sockets_created = unix_transport_server_start (plugin);
1804   if ((0 == sockets_created) || (GNUNET_SYSERR == sockets_created))
1805   {
1806     LOG (GNUNET_ERROR_TYPE_WARNING,
1807          _("Failed to open UNIX listen socket\n"));
1808     GNUNET_free (api);
1809     GNUNET_free (plugin->unix_socket_path);
1810     GNUNET_free (plugin);
1811     return NULL;
1812   }
1813   plugin->session_map = GNUNET_CONTAINER_multipeermap_create (10, GNUNET_NO);
1814   plugin->address_update_task = GNUNET_SCHEDULER_add_now (&address_notification,
1815                                                           plugin);
1816   return api;
1817 }
1818
1819
1820 /**
1821  * Shutdown the plugin.
1822  *
1823  * @param cls the plugin API returned from the initialization function
1824  * @return NULL (always)
1825  */
1826 void *
1827 libgnunet_plugin_transport_unix_done (void *cls)
1828 {
1829   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1830   struct Plugin *plugin = api->cls;
1831   struct GNUNET_HELLO_Address *address;
1832   struct UNIXMessageWrapper * msgw;
1833   struct UnixAddress *ua;
1834   size_t len;
1835   struct Session *session;
1836
1837   if (NULL == plugin)
1838   {
1839     GNUNET_free (api);
1840     return NULL;
1841   }
1842   len = sizeof (struct UnixAddress) + strlen (plugin->unix_socket_path) + 1;
1843   ua = GNUNET_malloc (len);
1844   ua->options = htonl (plugin->myoptions);
1845   ua->addrlen = htonl(strlen (plugin->unix_socket_path) + 1);
1846   memcpy (&ua[1],
1847           plugin->unix_socket_path,
1848           strlen (plugin->unix_socket_path) + 1);
1849   address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
1850                                            PLUGIN_NAME,
1851                                            ua, len,
1852                                            GNUNET_HELLO_ADDRESS_INFO_NONE);
1853   plugin->env->notify_address (plugin->env->cls,
1854                                GNUNET_NO,
1855                                address);
1856
1857   GNUNET_free (address);
1858   GNUNET_free (ua);
1859
1860   while (NULL != (msgw = plugin->msg_head))
1861   {
1862     GNUNET_CONTAINER_DLL_remove (plugin->msg_head,
1863                                  plugin->msg_tail,
1864                                  msgw);
1865     session = msgw->session;
1866     session->msgs_in_queue--;
1867     GNUNET_assert (session->bytes_in_queue >= msgw->msgsize);
1868     session->bytes_in_queue -= msgw->msgsize;
1869     GNUNET_assert (plugin->bytes_in_queue >= msgw->msgsize);
1870     plugin->bytes_in_queue -= msgw->msgsize;
1871     if (NULL != msgw->cont)
1872       msgw->cont (msgw->cont_cls,
1873                   &msgw->session->target,
1874                   GNUNET_SYSERR,
1875                   msgw->payload, 0);
1876     GNUNET_free (msgw->msg);
1877     GNUNET_free (msgw);
1878   }
1879
1880   if (NULL != plugin->read_task)
1881   {
1882     GNUNET_SCHEDULER_cancel (plugin->read_task);
1883     plugin->read_task = NULL;
1884   }
1885   if (NULL != plugin->write_task)
1886   {
1887     GNUNET_SCHEDULER_cancel (plugin->write_task);
1888     plugin->write_task = NULL;
1889   }
1890   if (NULL != plugin->address_update_task)
1891   {
1892     GNUNET_SCHEDULER_cancel (plugin->address_update_task);
1893     plugin->address_update_task = NULL;
1894   }
1895   if (NULL != plugin->unix_sock.desc)
1896   {
1897     GNUNET_break (GNUNET_OK ==
1898                   GNUNET_NETWORK_socket_close (plugin->unix_sock.desc));
1899     plugin->unix_sock.desc = NULL;
1900   }
1901   GNUNET_CONTAINER_multipeermap_iterate (plugin->session_map,
1902                                          &get_session_delete_it,
1903                                          plugin);
1904   GNUNET_CONTAINER_multipeermap_destroy (plugin->session_map);
1905   GNUNET_break (0 == plugin->bytes_in_queue);
1906   GNUNET_free (plugin->unix_socket_path);
1907   GNUNET_free (plugin);
1908   GNUNET_free (api);
1909   return NULL;
1910 }
1911
1912 /* end of plugin_transport_unix.c */