small API change: do no longer pass rarely needed GNUNET_SCHEDULER_TaskContext to...
[oweals/gnunet.git] / src / transport / plugin_transport_unix.c
1 /*
2      This file is part of GNUnet
3      Copyright (C) 2010-2014 GNUnet e.V.
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 GNUNET_ATS_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 GNUNET_ATS_Session
178 {
179
180   /**
181    * Sessions with pending messages (!) are kept in a DLL.
182    */
183   struct GNUNET_ATS_Session *next;
184
185   /**
186    * Sessions with pending messages (!) are kept in a DLL.
187    */
188   struct GNUNET_ATS_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 GNUNET_ATS_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 GNUNET_ATS_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 GNUNET_ATS_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 GNUNET_ATS_Session *` to disconnect
501  */
502 static void
503 session_timeout (void *cls)
504 {
505   struct GNUNET_ATS_Session *session = cls;
506   struct GNUNET_TIME_Relative left;
507
508   session->timeout_task = NULL;
509   left = GNUNET_TIME_absolute_get_remaining (session->timeout);
510   if (0 != left.rel_value_us)
511   {
512     /* not actually our turn yet, but let's at least update
513        the monitor, it may think we're about to die ... */
514     notify_session_monitor (session->plugin,
515                             session,
516                             GNUNET_TRANSPORT_SS_UPDATE);
517     session->timeout_task = GNUNET_SCHEDULER_add_delayed (left,
518                                                           &session_timeout,
519                                                           session);
520     return;
521   }
522   LOG (GNUNET_ERROR_TYPE_DEBUG,
523        "Session %p was idle for %s, disconnecting\n",
524        session,
525        GNUNET_STRINGS_relative_time_to_string (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
526                                                GNUNET_YES));
527   unix_plugin_session_disconnect (session->plugin, session);
528 }
529
530
531 /**
532  * Increment session timeout due to activity.  We do not immediately
533  * notify the monitor here as that might generate excessive
534  * signalling.
535  *
536  * @param session session for which the timeout should be rescheduled
537  */
538 static void
539 reschedule_session_timeout (struct GNUNET_ATS_Session *session)
540 {
541   GNUNET_assert (NULL != session->timeout_task);
542   session->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
543 }
544
545
546 /**
547  * Convert unix path to a `struct sockaddr_un *`
548  *
549  * @param unixpath path to convert
550  * @param[out] sock_len set to the length of the address
551  * @return converted unix path
552  */
553 static struct sockaddr_un *
554 unix_address_to_sockaddr (const char *unixpath,
555                           socklen_t *sock_len)
556 {
557   struct sockaddr_un *un;
558   size_t slen;
559
560   GNUNET_assert (0 < strlen (unixpath));        /* sanity check */
561   un = GNUNET_new (struct sockaddr_un);
562   un->sun_family = AF_UNIX;
563   slen = strlen (unixpath);
564   if (slen >= sizeof (un->sun_path))
565     slen = sizeof (un->sun_path) - 1;
566   memcpy (un->sun_path, unixpath, slen);
567   un->sun_path[slen] = '\0';
568   slen = sizeof (struct sockaddr_un);
569 #if HAVE_SOCKADDR_IN_SIN_LEN
570   un->sun_len = (u_char) slen;
571 #endif
572   (*sock_len) = slen;
573   return un;
574 }
575
576
577 /**
578  * Closure to #lookup_session_it().
579  */
580 struct LookupCtx
581 {
582   /**
583    * Location to store the session, if found.
584    */
585   struct GNUNET_ATS_Session *res;
586
587   /**
588    * Address we are looking for.
589    */
590   const struct GNUNET_HELLO_Address *address;
591 };
592
593
594 /**
595  * Function called to find a session by address.
596  *
597  * @param cls the `struct LookupCtx *`
598  * @param key peer we are looking for (unused)
599  * @param value a session
600  * @return #GNUNET_YES if not found (continue looking), #GNUNET_NO on success
601  */
602 static int
603 lookup_session_it (void *cls,
604                    const struct GNUNET_PeerIdentity * key,
605                    void *value)
606 {
607   struct LookupCtx *lctx = cls;
608   struct GNUNET_ATS_Session *session = value;
609
610   if (0 == GNUNET_HELLO_address_cmp (lctx->address,
611                                      session->address))
612   {
613     lctx->res = session;
614     return GNUNET_NO;
615   }
616   return GNUNET_YES;
617 }
618
619
620 /**
621  * Find an existing session by address.
622  *
623  * @param plugin the plugin
624  * @param address the address to find
625  * @return NULL if session was not found
626  */
627 static struct GNUNET_ATS_Session *
628 lookup_session (struct Plugin *plugin,
629                 const struct GNUNET_HELLO_Address *address)
630 {
631   struct LookupCtx lctx;
632
633   lctx.address = address;
634   lctx.res = NULL;
635   GNUNET_CONTAINER_multipeermap_get_multiple (plugin->session_map,
636                                               &address->peer,
637                                               &lookup_session_it, &lctx);
638   return lctx.res;
639 }
640
641
642 /**
643  * Function that is called to get the keepalive factor.
644  * #GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT is divided by this number to
645  * calculate the interval between keepalive packets.
646  *
647  * @param cls closure with the `struct Plugin`
648  * @return keepalive factor
649  */
650 static unsigned int
651 unix_plugin_query_keepalive_factor (void *cls)
652 {
653   return 3;
654 }
655
656
657 /**
658  * Actually send out the message, assume we've got the address and
659  * send_handle squared away!
660  *
661  * @param cls closure
662  * @param send_handle which handle to send message on
663  * @param target who should receive this message (ignored by UNIX)
664  * @param msgbuf one or more GNUNET_MessageHeader(s) strung together
665  * @param msgbuf_size the size of the @a msgbuf to send
666  * @param priority how important is the message (ignored by UNIX)
667  * @param timeout when should we time out (give up) if we can not transmit?
668  * @param addr the addr to send the message to, needs to be a sockaddr for us
669  * @param addrlen the len of @a addr
670  * @param payload bytes payload to send
671  * @param cont continuation to call once the message has
672  *        been transmitted (or if the transport is ready
673  *        for the next transmission call; or if the
674  *        peer disconnected...)
675  * @param cont_cls closure for @a cont
676  * @return on success the number of bytes written, RETRY for retry, -1 on errors
677  */
678 static ssize_t
679 unix_real_send (void *cls,
680                 struct GNUNET_NETWORK_Handle *send_handle,
681                 const struct GNUNET_PeerIdentity *target,
682                 const char *msgbuf,
683                 size_t msgbuf_size,
684                 unsigned int priority,
685                 struct GNUNET_TIME_Absolute timeout,
686                 const struct UnixAddress *addr,
687                 size_t addrlen,
688                 size_t payload,
689                 GNUNET_TRANSPORT_TransmitContinuation cont,
690                 void *cont_cls)
691 {
692   struct Plugin *plugin = cls;
693   ssize_t sent;
694   struct sockaddr_un *un;
695   socklen_t un_len;
696   const char *unixpath;
697
698   if (NULL == send_handle)
699   {
700     GNUNET_break (0); /* We do not have a send handle */
701     return GNUNET_SYSERR;
702   }
703   if ((NULL == addr) || (0 == addrlen))
704   {
705     GNUNET_break (0); /* Can never send if we don't have an address */
706     return GNUNET_SYSERR;
707   }
708
709   /* Prepare address */
710   unixpath = (const char *)  &addr[1];
711   if (NULL == (un = unix_address_to_sockaddr (unixpath,
712                                               &un_len)))
713   {
714     GNUNET_break (0);
715     return -1;
716   }
717
718   if ((GNUNET_YES == plugin->is_abstract) &&
719       (0 != (UNIX_OPTIONS_USE_ABSTRACT_SOCKETS & ntohl(addr->options) )) )
720   {
721     un->sun_path[0] = '\0';
722   }
723 resend:
724   /* Send the data */
725   sent = GNUNET_NETWORK_socket_sendto (send_handle,
726                                        msgbuf,
727                                        msgbuf_size,
728                                        (const struct sockaddr *) un,
729                                        un_len);
730   if (GNUNET_SYSERR == sent)
731   {
732     if ( (EAGAIN == errno) ||
733          (ENOBUFS == errno) )
734     {
735       GNUNET_free (un);
736       return RETRY; /* We have to retry later  */
737     }
738     if (EMSGSIZE == errno)
739     {
740       socklen_t size = 0;
741       socklen_t len = sizeof (size);
742
743       GNUNET_NETWORK_socket_getsockopt ((struct GNUNET_NETWORK_Handle *)
744                                         send_handle, SOL_SOCKET, SO_SNDBUF, &size,
745                                         &len);
746       if (size < msgbuf_size)
747       {
748         LOG (GNUNET_ERROR_TYPE_DEBUG,
749              "Trying to increase socket buffer size from %u to %u for message size %u\n",
750              (unsigned int) size,
751              (unsigned int) ((msgbuf_size / 1000) + 2) * 1000,
752              (unsigned int) msgbuf_size);
753         size = ((msgbuf_size / 1000) + 2) * 1000;
754         if (GNUNET_OK ==
755             GNUNET_NETWORK_socket_setsockopt ((struct GNUNET_NETWORK_Handle *) send_handle,
756                                               SOL_SOCKET, SO_SNDBUF,
757                                               &size, sizeof (size)))
758           goto resend; /* Increased buffer size, retry sending */
759         else
760         {
761           /* Could not increase buffer size: error, no retry */
762           GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "setsockopt");
763           GNUNET_free (un);
764           return GNUNET_SYSERR;
765         }
766       }
767       else
768       {
769         /* Buffer is bigger than message:  error, no retry
770          * This should never happen!*/
771         GNUNET_break (0);
772         GNUNET_free (un);
773         return GNUNET_SYSERR;
774       }
775     }
776   }
777
778   LOG (GNUNET_ERROR_TYPE_DEBUG,
779        "UNIX transmitted %u-byte message to %s (%d: %s)\n",
780        (unsigned int) msgbuf_size,
781        GNUNET_a2s ((const struct sockaddr *)un, un_len),
782        (int) sent,
783        (sent < 0) ? STRERROR (errno) : "ok");
784   GNUNET_free (un);
785   return sent;
786 }
787
788
789 /**
790  * Function obtain the network type for a session
791  *
792  * @param cls closure ('struct Plugin*')
793  * @param session the session
794  * @return the network type in HBO or #GNUNET_SYSERR
795  */
796 static enum GNUNET_ATS_Network_Type
797 unix_plugin_get_network (void *cls,
798                          struct GNUNET_ATS_Session *session)
799 {
800   GNUNET_assert (NULL != session);
801   return GNUNET_ATS_NET_LOOPBACK;
802 }
803
804
805 /**
806  * Function obtain the network type for a session
807  *
808  * @param cls closure (`struct Plugin *`)
809  * @param address the address
810  * @return the network type
811  */
812 static enum GNUNET_ATS_Network_Type
813 unix_plugin_get_network_for_address (void *cls,
814                                      const struct GNUNET_HELLO_Address *address)
815
816 {
817   return GNUNET_ATS_NET_LOOPBACK;
818 }
819
820
821 /**
822  * Creates a new outbound session the transport service will use to send data to the
823  * peer
824  *
825  * @param cls the plugin
826  * @param address the address
827  * @return the session or NULL of max connections exceeded
828  */
829 static struct GNUNET_ATS_Session *
830 unix_plugin_get_session (void *cls,
831                          const struct GNUNET_HELLO_Address *address)
832 {
833   struct Plugin *plugin = cls;
834   struct GNUNET_ATS_Session *session;
835   struct UnixAddress *ua;
836   char * addrstr;
837   uint32_t addr_str_len;
838   uint32_t addr_option;
839
840   ua = (struct UnixAddress *) address->address;
841   if ((NULL == address->address) || (0 == address->address_length) ||
842                 (sizeof (struct UnixAddress) > address->address_length))
843   {
844     GNUNET_break (0);
845     return NULL;
846   }
847   addrstr = (char *) &ua[1];
848   addr_str_len = ntohl (ua->addrlen);
849   addr_option = ntohl (ua->options);
850
851   if ( (0 != (UNIX_OPTIONS_USE_ABSTRACT_SOCKETS & addr_option)) &&
852     (GNUNET_NO == plugin->is_abstract))
853   {
854     return NULL;
855   }
856
857   if (addr_str_len != address->address_length - sizeof (struct UnixAddress))
858   {
859     return NULL; /* This can be a legacy address */
860   }
861
862   if ('\0' != addrstr[addr_str_len - 1])
863   {
864     GNUNET_break (0);
865     return NULL;
866   }
867   if (strlen (addrstr) + 1 != addr_str_len)
868   {
869     GNUNET_break (0);
870     return NULL;
871   }
872
873   /* Check if a session for this address already exists */
874   if (NULL != (session = lookup_session (plugin,
875                                          address)))
876     {
877     LOG (GNUNET_ERROR_TYPE_DEBUG,
878          "Found existing session %p for address `%s'\n",
879          session,
880          unix_plugin_address_to_string (NULL,
881                                         address->address,
882                                         address->address_length));
883     return session;
884   }
885
886   /* create a new session */
887   session = GNUNET_new (struct GNUNET_ATS_Session);
888   session->target = address->peer;
889   session->address = GNUNET_HELLO_address_copy (address);
890   session->plugin = plugin;
891   session->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
892   session->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
893                                                         &session_timeout,
894                                                         session);
895   LOG (GNUNET_ERROR_TYPE_DEBUG,
896        "Creating a new session %p for address `%s'\n",
897        session,
898        unix_plugin_address_to_string (NULL,
899                                       address->address,
900                                       address->address_length));
901   (void) GNUNET_CONTAINER_multipeermap_put (plugin->session_map,
902                                             &address->peer, session,
903                                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
904   GNUNET_STATISTICS_set (plugin->env->stats,
905                          "# UNIX sessions active",
906                          GNUNET_CONTAINER_multipeermap_size (plugin->session_map),
907                          GNUNET_NO);
908   notify_session_monitor (plugin,
909                           session,
910                           GNUNET_TRANSPORT_SS_INIT);
911   notify_session_monitor (plugin,
912                           session,
913                           GNUNET_TRANSPORT_SS_UP);
914   return session;
915 }
916
917
918 /**
919  * Function that will be called whenever the transport service wants
920  * to notify the plugin that a session is still active and in use and
921  * therefore the session timeout for this session has to be updated
922  *
923  * @param cls closure with the `struct Plugin *`
924  * @param peer which peer was the session for
925  * @param session which session is being updated
926  */
927 static void
928 unix_plugin_update_session_timeout (void *cls,
929                                     const struct GNUNET_PeerIdentity *peer,
930                                     struct GNUNET_ATS_Session *session)
931 {
932   struct Plugin *plugin = cls;
933
934   if (GNUNET_OK !=
935       GNUNET_CONTAINER_multipeermap_contains_value (plugin->session_map,
936                                                     &session->target,
937                                                     session))
938   {
939     GNUNET_break (0);
940     return;
941   }
942   reschedule_session_timeout (session);
943 }
944
945
946 /**
947  * Demultiplexer for UNIX messages
948  *
949  * @param plugin the main plugin for this transport
950  * @param sender from which peer the message was received
951  * @param currhdr pointer to the header of the message
952  * @param ua address to look for
953  * @param ua_len length of the address @a ua
954  */
955 static void
956 unix_demultiplexer (struct Plugin *plugin,
957                     struct GNUNET_PeerIdentity *sender,
958                     const struct GNUNET_MessageHeader *currhdr,
959                     const struct UnixAddress *ua,
960                     size_t ua_len)
961 {
962   struct GNUNET_ATS_Session *session;
963   struct GNUNET_HELLO_Address *address;
964
965   GNUNET_assert (ua_len >= sizeof (struct UnixAddress));
966   LOG (GNUNET_ERROR_TYPE_DEBUG,
967        "Received message from %s\n",
968        unix_plugin_address_to_string (NULL, ua, ua_len));
969   GNUNET_STATISTICS_update (plugin->env->stats,
970                             "# bytes received via UNIX",
971                             ntohs (currhdr->size),
972                             GNUNET_NO);
973
974   /* Look for existing session */
975   address = GNUNET_HELLO_address_allocate (sender,
976                                            PLUGIN_NAME,
977                                            ua, ua_len,
978                                            GNUNET_HELLO_ADDRESS_INFO_NONE); /* UNIX does not have "inbound" sessions */
979   session = lookup_session (plugin, address);
980   if (NULL == session)
981   {
982     session = unix_plugin_get_session (plugin, address);
983     /* Notify transport and ATS about new inbound session */
984     plugin->env->session_start (NULL,
985                                 session->address,
986                                 session,
987                                 GNUNET_ATS_NET_LOOPBACK);
988   }
989   else
990   {
991     reschedule_session_timeout (session);
992   }
993   GNUNET_HELLO_address_free (address);
994   plugin->env->receive (plugin->env->cls,
995                         session->address,
996                         session,
997                         currhdr);
998 }
999
1000
1001 /**
1002  * Read from UNIX domain socket (it is ready).
1003  *
1004  * @param plugin the plugin
1005  */
1006 static void
1007 unix_plugin_do_read (struct Plugin *plugin)
1008 {
1009   char buf[65536] GNUNET_ALIGN;
1010   struct UnixAddress *ua;
1011   struct UNIXMessage *msg;
1012   struct GNUNET_PeerIdentity sender;
1013   struct sockaddr_un un;
1014   socklen_t addrlen;
1015   ssize_t ret;
1016   int offset;
1017   int tsize;
1018   int is_abstract;
1019   char *msgbuf;
1020   const struct GNUNET_MessageHeader *currhdr;
1021   uint16_t csize;
1022   size_t ua_len;
1023
1024   addrlen = sizeof (un);
1025   memset (&un, 0, sizeof (un));
1026   ret = GNUNET_NETWORK_socket_recvfrom (plugin->unix_sock.desc,
1027                                         buf, sizeof (buf),
1028                                         (struct sockaddr *) &un,
1029                                         &addrlen);
1030   if ((GNUNET_SYSERR == ret) && ((errno == EAGAIN) || (errno == ENOBUFS)))
1031     return;
1032   if (GNUNET_SYSERR == ret)
1033   {
1034     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
1035                          "recvfrom");
1036     return;
1037   }
1038   else
1039   {
1040     LOG (GNUNET_ERROR_TYPE_DEBUG,
1041          "Read %d bytes from socket %s\n",
1042          (int) ret,
1043          un.sun_path);
1044   }
1045
1046   GNUNET_assert (AF_UNIX == (un.sun_family));
1047   is_abstract = GNUNET_NO;
1048   if ('\0' == un.sun_path[0])
1049   {
1050     un.sun_path[0] = '@';
1051     is_abstract = GNUNET_YES;
1052   }
1053
1054   ua_len = sizeof (struct UnixAddress) + strlen (un.sun_path) + 1;
1055   ua = GNUNET_malloc (ua_len);
1056   ua->addrlen = htonl (strlen (&un.sun_path[0]) +1);
1057   memcpy (&ua[1], &un.sun_path[0], strlen (un.sun_path) + 1);
1058   if (is_abstract)
1059     ua->options = htonl(UNIX_OPTIONS_USE_ABSTRACT_SOCKETS);
1060   else
1061     ua->options = htonl(UNIX_OPTIONS_NONE);
1062
1063   msg = (struct UNIXMessage *) buf;
1064   csize = ntohs (msg->header.size);
1065   if ((csize < sizeof (struct UNIXMessage)) || (csize > ret))
1066   {
1067     GNUNET_break_op (0);
1068     GNUNET_free (ua);
1069     return;
1070   }
1071   msgbuf = (char *) &msg[1];
1072   memcpy (&sender,
1073           &msg->sender,
1074           sizeof (struct GNUNET_PeerIdentity));
1075   offset = 0;
1076   tsize = csize - sizeof (struct UNIXMessage);
1077   while (offset + sizeof (struct GNUNET_MessageHeader) <= tsize)
1078   {
1079     currhdr = (struct GNUNET_MessageHeader *) &msgbuf[offset];
1080     csize = ntohs (currhdr->size);
1081     if ((csize < sizeof (struct GNUNET_MessageHeader)) ||
1082         (csize > tsize - offset))
1083     {
1084       GNUNET_break_op (0);
1085       break;
1086     }
1087     unix_demultiplexer (plugin, &sender, currhdr, ua, ua_len);
1088     offset += csize;
1089   }
1090   GNUNET_free (ua);
1091 }
1092
1093
1094 /**
1095  * Write to UNIX domain socket (it is ready).
1096  *
1097  * @param plugin handle to the plugin
1098  */
1099 static void
1100 unix_plugin_do_write (struct Plugin *plugin)
1101 {
1102   ssize_t sent = 0;
1103   struct UNIXMessageWrapper *msgw;
1104   struct GNUNET_ATS_Session *session;
1105   int did_delete;
1106
1107   session = NULL;
1108   did_delete = GNUNET_NO;
1109   while (NULL != (msgw = plugin->msg_head))
1110   {
1111     if (GNUNET_TIME_absolute_get_remaining (msgw->timeout).rel_value_us > 0)
1112       break; /* Message is ready for sending */
1113     /* Message has a timeout */
1114     did_delete = GNUNET_YES;
1115     LOG (GNUNET_ERROR_TYPE_DEBUG,
1116          "Timeout for message with %u bytes \n",
1117          (unsigned int) msgw->msgsize);
1118     GNUNET_CONTAINER_DLL_remove (plugin->msg_head,
1119                                  plugin->msg_tail,
1120                                  msgw);
1121     session = msgw->session;
1122     session->msgs_in_queue--;
1123     GNUNET_assert (session->bytes_in_queue >= msgw->msgsize);
1124     session->bytes_in_queue -= msgw->msgsize;
1125     GNUNET_assert (plugin->bytes_in_queue >= msgw->msgsize);
1126     plugin->bytes_in_queue -= msgw->msgsize;
1127     GNUNET_STATISTICS_set (plugin->env->stats,
1128                            "# bytes currently in UNIX buffers",
1129                            plugin->bytes_in_queue,
1130                            GNUNET_NO);
1131     GNUNET_STATISTICS_update (plugin->env->stats,
1132                               "# UNIX bytes discarded",
1133                               msgw->msgsize,
1134                               GNUNET_NO);
1135     if (NULL != msgw->cont)
1136       msgw->cont (msgw->cont_cls,
1137                   &msgw->session->target,
1138                   GNUNET_SYSERR,
1139                   msgw->payload,
1140                   0);
1141     GNUNET_free (msgw->msg);
1142     GNUNET_free (msgw);
1143   }
1144   if (NULL == msgw)
1145   {
1146     if (GNUNET_YES == did_delete)
1147       notify_session_monitor (plugin,
1148                               session,
1149                               GNUNET_TRANSPORT_SS_UPDATE);
1150     return; /* Nothing to send at the moment */
1151   }
1152   session = msgw->session;
1153   sent = unix_real_send (plugin,
1154                          plugin->unix_sock.desc,
1155                          &session->target,
1156                          (const char *) msgw->msg,
1157                          msgw->msgsize,
1158                          msgw->priority,
1159                          msgw->timeout,
1160                          msgw->session->address->address,
1161                          msgw->session->address->address_length,
1162                          msgw->payload,
1163                          msgw->cont, msgw->cont_cls);
1164   if (RETRY == sent)
1165   {
1166     GNUNET_STATISTICS_update (plugin->env->stats,
1167                               "# UNIX retry attempts",
1168                               1, GNUNET_NO);
1169     notify_session_monitor (plugin,
1170                             session,
1171                             GNUNET_TRANSPORT_SS_UPDATE);
1172     return;
1173   }
1174   GNUNET_CONTAINER_DLL_remove (plugin->msg_head,
1175                                plugin->msg_tail,
1176                                msgw);
1177   session->msgs_in_queue--;
1178   GNUNET_assert (session->bytes_in_queue >= msgw->msgsize);
1179   session->bytes_in_queue -= msgw->msgsize;
1180   GNUNET_assert (plugin->bytes_in_queue >= msgw->msgsize);
1181   plugin->bytes_in_queue -= msgw->msgsize;
1182   GNUNET_STATISTICS_set (plugin->env->stats,
1183                          "# bytes currently in UNIX buffers",
1184                          plugin->bytes_in_queue, GNUNET_NO);
1185   notify_session_monitor (plugin,
1186                           session,
1187                           GNUNET_TRANSPORT_SS_UPDATE);
1188   if (GNUNET_SYSERR == sent)
1189   {
1190     /* failed and no retry */
1191     if (NULL != msgw->cont)
1192       msgw->cont (msgw->cont_cls,
1193                   &msgw->session->target,
1194                   GNUNET_SYSERR,
1195                   msgw->payload, 0);
1196     GNUNET_STATISTICS_update (plugin->env->stats,
1197                               "# UNIX bytes discarded",
1198                               msgw->msgsize,
1199                               GNUNET_NO);
1200     GNUNET_free (msgw->msg);
1201     GNUNET_free (msgw);
1202     return;
1203   }
1204   /* successfully sent bytes */
1205   GNUNET_break (sent > 0);
1206   GNUNET_STATISTICS_update (plugin->env->stats,
1207                             "# bytes transmitted via UNIX",
1208                             msgw->msgsize,
1209                             GNUNET_NO);
1210   if (NULL != msgw->cont)
1211     msgw->cont (msgw->cont_cls,
1212                 &msgw->session->target,
1213                 GNUNET_OK,
1214                 msgw->payload,
1215                 msgw->msgsize);
1216   GNUNET_free (msgw->msg);
1217   GNUNET_free (msgw);
1218 }
1219
1220
1221 /**
1222  * We have been notified that our socket has something to read.
1223  * Then reschedule this function to be called again once more is available.
1224  *
1225  * @param cls the plugin handle
1226  */
1227 static void
1228 unix_plugin_select_read (void *cls)
1229 {
1230   struct Plugin *plugin = cls;
1231   const struct GNUNET_SCHEDULER_TaskContext *tc;
1232
1233   tc = GNUNET_SCHEDULER_get_task_context ();
1234   plugin->read_task = NULL;
1235   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1236     return;
1237   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_READ_READY))
1238     unix_plugin_do_read (plugin);
1239   plugin->read_task =
1240     GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
1241                                    plugin->unix_sock.desc,
1242                                    &unix_plugin_select_read, plugin);
1243 }
1244
1245
1246 /**
1247  * We have been notified that our socket is ready to write.
1248  * Then reschedule this function to be called again once more is available.
1249  *
1250  * @param cls the plugin handle
1251  */
1252 static void
1253 unix_plugin_select_write (void *cls)
1254 {
1255   struct Plugin *plugin = cls;
1256   const struct GNUNET_SCHEDULER_TaskContext *tc;
1257
1258   tc = GNUNET_SCHEDULER_get_task_context ();
1259   plugin->write_task = NULL;
1260   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1261     return;
1262   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY))
1263     unix_plugin_do_write (plugin);
1264   if (NULL == plugin->msg_head)
1265     return; /* write queue empty */
1266   plugin->write_task =
1267     GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
1268                                     plugin->unix_sock.desc,
1269                                     &unix_plugin_select_write, plugin);
1270 }
1271
1272
1273 /**
1274  * Function that can be used by the transport service to transmit
1275  * a message using the plugin.   Note that in the case of a
1276  * peer disconnecting, the continuation MUST be called
1277  * prior to the disconnect notification itself.  This function
1278  * will be called with this peer's HELLO message to initiate
1279  * a fresh connection to another peer.
1280  *
1281  * @param cls closure
1282  * @param session which session must be used
1283  * @param msgbuf the message to transmit
1284  * @param msgbuf_size number of bytes in @a msgbuf
1285  * @param priority how important is the message (most plugins will
1286  *                 ignore message priority and just FIFO)
1287  * @param to how long to wait at most for the transmission (does not
1288  *                require plugins to discard the message after the timeout,
1289  *                just advisory for the desired delay; most plugins will ignore
1290  *                this as well)
1291  * @param cont continuation to call once the message has
1292  *        been transmitted (or if the transport is ready
1293  *        for the next transmission call; or if the
1294  *        peer disconnected...); can be NULL
1295  * @param cont_cls closure for @a cont
1296  * @return number of bytes used (on the physical network, with overheads);
1297  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
1298  *         and does NOT mean that the message was not transmitted (DV)
1299  */
1300 static ssize_t
1301 unix_plugin_send (void *cls,
1302                   struct GNUNET_ATS_Session *session,
1303                   const char *msgbuf,
1304                   size_t msgbuf_size,
1305                   unsigned int priority,
1306                   struct GNUNET_TIME_Relative to,
1307                   GNUNET_TRANSPORT_TransmitContinuation cont,
1308                   void *cont_cls)
1309 {
1310   struct Plugin *plugin = cls;
1311   struct UNIXMessageWrapper *wrapper;
1312   struct UNIXMessage *message;
1313   int ssize;
1314
1315   if (GNUNET_OK !=
1316       GNUNET_CONTAINER_multipeermap_contains_value (plugin->session_map,
1317                                                     &session->target,
1318                                                     session))
1319   {
1320     LOG (GNUNET_ERROR_TYPE_ERROR,
1321          "Invalid session for peer `%s' `%s'\n",
1322          GNUNET_i2s (&session->target),
1323          unix_plugin_address_to_string (NULL,
1324                                         session->address->address,
1325                                         session->address->address_length));
1326     GNUNET_break (0);
1327     return GNUNET_SYSERR;
1328   }
1329   LOG (GNUNET_ERROR_TYPE_DEBUG,
1330        "Sending %u bytes with session for peer `%s' `%s'\n",
1331        msgbuf_size,
1332        GNUNET_i2s (&session->target),
1333        unix_plugin_address_to_string (NULL,
1334                                       session->address->address,
1335                                       session->address->address_length));
1336   ssize = sizeof (struct UNIXMessage) + msgbuf_size;
1337   message = GNUNET_malloc (sizeof (struct UNIXMessage) + msgbuf_size);
1338   message->header.size = htons (ssize);
1339   message->header.type = htons (0);
1340   memcpy (&message->sender, plugin->env->my_identity,
1341           sizeof (struct GNUNET_PeerIdentity));
1342   memcpy (&message[1], msgbuf, msgbuf_size);
1343   wrapper = GNUNET_new (struct UNIXMessageWrapper);
1344   wrapper->msg = message;
1345   wrapper->msgsize = ssize;
1346   wrapper->payload = msgbuf_size;
1347   wrapper->priority = priority;
1348   wrapper->timeout = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (),
1349                                                to);
1350   wrapper->cont = cont;
1351   wrapper->cont_cls = cont_cls;
1352   wrapper->session = session;
1353   GNUNET_CONTAINER_DLL_insert_tail (plugin->msg_head,
1354                                     plugin->msg_tail,
1355                                     wrapper);
1356   plugin->bytes_in_queue += ssize;
1357   session->bytes_in_queue += ssize;
1358   session->msgs_in_queue++;
1359   GNUNET_STATISTICS_set (plugin->env->stats,
1360                          "# bytes currently in UNIX buffers",
1361                          plugin->bytes_in_queue,
1362                          GNUNET_NO);
1363   notify_session_monitor (plugin,
1364                           session,
1365                           GNUNET_TRANSPORT_SS_UPDATE);
1366   if (NULL == plugin->write_task)
1367     plugin->write_task =
1368       GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
1369                                       plugin->unix_sock.desc,
1370                                       &unix_plugin_select_write, plugin);
1371   return ssize;
1372 }
1373
1374
1375 /**
1376  * Create a slew of UNIX sockets.  If possible, use IPv6 and IPv4.
1377  *
1378  * @param cls closure for server start, should be a `struct Plugin *`
1379  * @return number of sockets created or #GNUNET_SYSERR on error
1380  */
1381 static int
1382 unix_transport_server_start (void *cls)
1383 {
1384   struct Plugin *plugin = cls;
1385   struct sockaddr_un *un;
1386   socklen_t un_len;
1387
1388   un = unix_address_to_sockaddr (plugin->unix_socket_path,
1389                                  &un_len);
1390   if (GNUNET_YES == plugin->is_abstract)
1391   {
1392     plugin->unix_socket_path[0] = '@';
1393     un->sun_path[0] = '\0';
1394   }
1395   plugin->unix_sock.desc =
1396       GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_DGRAM, 0);
1397   if (NULL == plugin->unix_sock.desc)
1398   {
1399     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
1400     GNUNET_free (un);
1401     return GNUNET_SYSERR;
1402   }
1403   if ('\0' != un->sun_path[0])
1404   {
1405     if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (un->sun_path))
1406     {
1407       LOG (GNUNET_ERROR_TYPE_ERROR, _("Cannot create path to `%s'\n"),
1408           un->sun_path);
1409       GNUNET_NETWORK_socket_close (plugin->unix_sock.desc);
1410       plugin->unix_sock.desc = NULL;
1411       GNUNET_free (un);
1412       return GNUNET_SYSERR;
1413     }
1414   }
1415   if (GNUNET_OK !=
1416       GNUNET_NETWORK_socket_bind (plugin->unix_sock.desc,
1417                                   (const struct sockaddr *) un, un_len))
1418   {
1419     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
1420     LOG (GNUNET_ERROR_TYPE_ERROR, _("Cannot bind to `%s'\n"),
1421         un->sun_path);
1422     GNUNET_NETWORK_socket_close (plugin->unix_sock.desc);
1423     plugin->unix_sock.desc = NULL;
1424     GNUNET_free (un);
1425     return GNUNET_SYSERR;
1426   }
1427   LOG (GNUNET_ERROR_TYPE_DEBUG,
1428        "Bound to `%s'\n",
1429        plugin->unix_socket_path);
1430   plugin->read_task =
1431     GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
1432                                    plugin->unix_sock.desc,
1433                                    &unix_plugin_select_read, plugin);
1434   GNUNET_free (un);
1435   return 1;
1436 }
1437
1438
1439 /**
1440  * Function that will be called to check if a binary address for this
1441  * plugin is well-formed and corresponds to an address for THIS peer
1442  * (as per our configuration).  Naturally, if absolutely necessary,
1443  * plugins can be a bit conservative in their answer, but in general
1444  * plugins should make sure that the address does not redirect
1445  * traffic to a 3rd party that might try to man-in-the-middle our
1446  * traffic.
1447  *
1448  * @param cls closure, should be our handle to the Plugin
1449  * @param addr pointer to the address
1450  * @param addrlen length of @a addr
1451  * @return #GNUNET_OK if this is a plausible address for this peer
1452  *         and transport, #GNUNET_SYSERR if not
1453  *
1454  */
1455 static int
1456 unix_plugin_check_address (void *cls,
1457                            const void *addr,
1458                            size_t addrlen)
1459 {
1460   struct Plugin* plugin = cls;
1461   const struct UnixAddress *ua = addr;
1462   char *addrstr;
1463   size_t addr_str_len;
1464
1465   if ( (NULL == addr) ||
1466        (0 == addrlen) ||
1467        (sizeof (struct UnixAddress) > addrlen) )
1468   {
1469     GNUNET_break (0);
1470     return GNUNET_SYSERR;
1471   }
1472   addrstr = (char *) &ua[1];
1473   addr_str_len = ntohl (ua->addrlen);
1474   if ('\0' != addrstr[addr_str_len - 1])
1475   {
1476     GNUNET_break (0);
1477     return GNUNET_SYSERR;
1478   }
1479   if (strlen (addrstr) + 1 != addr_str_len)
1480   {
1481     GNUNET_break (0);
1482     return GNUNET_SYSERR;
1483   }
1484
1485   if (0 == strcmp (plugin->unix_socket_path, addrstr))
1486         return GNUNET_OK;
1487   return GNUNET_SYSERR;
1488 }
1489
1490
1491 /**
1492  * Convert the transports address to a nice, human-readable
1493  * format.
1494  *
1495  * @param cls closure
1496  * @param type name of the transport that generated the address
1497  * @param addr one of the addresses of the host, NULL for the last address
1498  *        the specific address format depends on the transport
1499  * @param addrlen length of the @a addr
1500  * @param numeric should (IP) addresses be displayed in numeric form?
1501  * @param timeout after how long should we give up?
1502  * @param asc function to call on each string
1503  * @param asc_cls closure for @a asc
1504  */
1505 static void
1506 unix_plugin_address_pretty_printer (void *cls, const char *type,
1507                                     const void *addr,
1508                                     size_t addrlen,
1509                                     int numeric,
1510                                     struct GNUNET_TIME_Relative timeout,
1511                                     GNUNET_TRANSPORT_AddressStringCallback asc,
1512                                     void *asc_cls)
1513 {
1514   const char *ret;
1515
1516   if ( (NULL != addr) && (addrlen > 0))
1517     ret = unix_plugin_address_to_string (NULL,
1518                                          addr,
1519                                          addrlen);
1520   else
1521     ret = NULL;
1522   asc (asc_cls,
1523        ret,
1524        (NULL == ret) ? GNUNET_SYSERR : GNUNET_OK);
1525   asc (asc_cls, NULL, GNUNET_OK);
1526 }
1527
1528
1529 /**
1530  * Function called to convert a string address to
1531  * a binary address.
1532  *
1533  * @param cls closure (`struct Plugin *`)
1534  * @param addr string address
1535  * @param addrlen length of the @a addr (strlen(addr) + '\0')
1536  * @param buf location to store the buffer
1537  *        If the function returns #GNUNET_SYSERR, its contents are undefined.
1538  * @param added length of created address
1539  * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
1540  */
1541 static int
1542 unix_plugin_string_to_address (void *cls,
1543                                const char *addr,
1544                                uint16_t addrlen,
1545                                void **buf, size_t *added)
1546 {
1547   struct UnixAddress *ua;
1548   char *address;
1549   char *plugin;
1550   char *optionstr;
1551   uint32_t options;
1552   size_t ua_size;
1553
1554   /* Format unix.options.address */
1555   address = NULL;
1556   plugin = NULL;
1557   optionstr = NULL;
1558
1559   if ((NULL == addr) || (addrlen == 0))
1560   {
1561     GNUNET_break (0);
1562     return GNUNET_SYSERR;
1563   }
1564   if ('\0' != addr[addrlen - 1])
1565   {
1566     GNUNET_break (0);
1567     return GNUNET_SYSERR;
1568   }
1569   if (strlen (addr) != addrlen - 1)
1570   {
1571     GNUNET_break (0);
1572     return GNUNET_SYSERR;
1573   }
1574   plugin = GNUNET_strdup (addr);
1575   optionstr = strchr (plugin, '.');
1576   if (NULL == optionstr)
1577   {
1578     GNUNET_break (0);
1579     GNUNET_free (plugin);
1580     return GNUNET_SYSERR;
1581   }
1582   optionstr[0] = '\0';
1583   optionstr++;
1584   options = atol (optionstr);
1585   address = strchr (optionstr, '.');
1586   if (NULL == address)
1587   {
1588     GNUNET_break (0);
1589     GNUNET_free (plugin);
1590     return GNUNET_SYSERR;
1591   }
1592   address[0] = '\0';
1593   address++;
1594   if (0 != strcmp(plugin, PLUGIN_NAME))
1595   {
1596     GNUNET_break (0);
1597     GNUNET_free (plugin);
1598     return GNUNET_SYSERR;
1599   }
1600
1601   ua_size = sizeof (struct UnixAddress) + strlen (address) + 1;
1602   ua = GNUNET_malloc (ua_size);
1603   ua->options = htonl (options);
1604   ua->addrlen = htonl (strlen (address) + 1);
1605   memcpy (&ua[1], address, strlen (address) + 1);
1606   GNUNET_free (plugin);
1607
1608   (*buf) = ua;
1609   (*added) = ua_size;
1610   return GNUNET_OK;
1611 }
1612
1613
1614 /**
1615  * Notify transport service about address
1616  *
1617  * @param cls the plugin
1618  */
1619 static void
1620 address_notification (void *cls)
1621 {
1622   struct Plugin *plugin = cls;
1623   struct GNUNET_HELLO_Address *address;
1624   size_t len;
1625   struct UnixAddress *ua;
1626   char *unix_path;
1627
1628   len = sizeof (struct UnixAddress) + strlen (plugin->unix_socket_path) + 1;
1629   ua = GNUNET_malloc (len);
1630   ua->options = htonl (plugin->myoptions);
1631   ua->addrlen = htonl(strlen (plugin->unix_socket_path) + 1);
1632   unix_path = (char *) &ua[1];
1633   memcpy (unix_path, plugin->unix_socket_path, strlen (plugin->unix_socket_path) + 1);
1634
1635   plugin->address_update_task = NULL;
1636   address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
1637                                            PLUGIN_NAME,
1638                                            ua,
1639                                            len,
1640                                            GNUNET_HELLO_ADDRESS_INFO_NONE);
1641   plugin->env->notify_address (plugin->env->cls,
1642                                GNUNET_YES,
1643                                address);
1644   GNUNET_free (ua);
1645   GNUNET_free (address);
1646 }
1647
1648
1649 /**
1650  * Function called on sessions to disconnect
1651  *
1652  * @param cls the plugin
1653  * @param key peer identity (unused)
1654  * @param value the `struct GNUNET_ATS_Session *` to disconnect
1655  * @return #GNUNET_YES (always, continue to iterate)
1656  */
1657 static int
1658 get_session_delete_it (void *cls,
1659                        const struct GNUNET_PeerIdentity *key,
1660                        void *value)
1661 {
1662   struct Plugin *plugin = cls;
1663   struct GNUNET_ATS_Session *session = value;
1664
1665   unix_plugin_session_disconnect (plugin, session);
1666   return GNUNET_YES;
1667 }
1668
1669
1670 /**
1671  * Disconnect from a remote node.  Clean up session if we have one for this peer
1672  *
1673  * @param cls closure for this call (should be handle to Plugin)
1674  * @param target the peeridentity of the peer to disconnect
1675  * @return #GNUNET_OK on success, #GNUNET_SYSERR if the operation failed
1676  */
1677 static void
1678 unix_plugin_peer_disconnect (void *cls,
1679                              const struct GNUNET_PeerIdentity *target)
1680 {
1681   struct Plugin *plugin = cls;
1682
1683   GNUNET_CONTAINER_multipeermap_get_multiple (plugin->session_map,
1684                                               target,
1685                                               &get_session_delete_it, plugin);
1686 }
1687
1688
1689 /**
1690  * Return information about the given session to the
1691  * monitor callback.
1692  *
1693  * @param cls the `struct Plugin` with the monitor callback (`sic`)
1694  * @param peer peer we send information about
1695  * @param value our `struct GNUNET_ATS_Session` to send information about
1696  * @return #GNUNET_OK (continue to iterate)
1697  */
1698 static int
1699 send_session_info_iter (void *cls,
1700                         const struct GNUNET_PeerIdentity *peer,
1701                         void *value)
1702 {
1703   struct Plugin *plugin = cls;
1704   struct GNUNET_ATS_Session *session = value;
1705
1706   notify_session_monitor (plugin,
1707                           session,
1708                           GNUNET_TRANSPORT_SS_INIT);
1709   notify_session_monitor (plugin,
1710                           session,
1711                           GNUNET_TRANSPORT_SS_UP);
1712   return GNUNET_OK;
1713 }
1714
1715
1716 /**
1717  * Begin monitoring sessions of a plugin.  There can only
1718  * be one active monitor per plugin (i.e. if there are
1719  * multiple monitors, the transport service needs to
1720  * multiplex the generated events over all of them).
1721  *
1722  * @param cls closure of the plugin
1723  * @param sic callback to invoke, NULL to disable monitor;
1724  *            plugin will being by iterating over all active
1725  *            sessions immediately and then enter monitor mode
1726  * @param sic_cls closure for @a sic
1727  */
1728 static void
1729 unix_plugin_setup_monitor (void *cls,
1730                            GNUNET_TRANSPORT_SessionInfoCallback sic,
1731                            void *sic_cls)
1732 {
1733   struct Plugin *plugin = cls;
1734
1735   plugin->sic = sic;
1736   plugin->sic_cls = sic_cls;
1737   if (NULL != sic)
1738   {
1739     GNUNET_CONTAINER_multipeermap_iterate (plugin->session_map,
1740                                            &send_session_info_iter,
1741                                            plugin);
1742     /* signal end of first iteration */
1743     sic (sic_cls, NULL, NULL);
1744   }
1745 }
1746
1747
1748 /**
1749  * The exported method.  Initializes the plugin and returns a
1750  * struct with the callbacks.
1751  *
1752  * @param cls the plugin's execution environment
1753  * @return NULL on error, plugin functions otherwise
1754  */
1755 void *
1756 libgnunet_plugin_transport_unix_init (void *cls)
1757 {
1758   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1759   struct GNUNET_TRANSPORT_PluginFunctions *api;
1760   struct Plugin *plugin;
1761   int sockets_created;
1762
1763   if (NULL == env->receive)
1764   {
1765     /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
1766        initialze the plugin or the API */
1767     api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
1768     api->cls = NULL;
1769     api->address_pretty_printer = &unix_plugin_address_pretty_printer;
1770     api->address_to_string = &unix_plugin_address_to_string;
1771     api->string_to_address = &unix_plugin_string_to_address;
1772     return api;
1773   }
1774
1775   plugin = GNUNET_new (struct Plugin);
1776   if (GNUNET_OK !=
1777       GNUNET_CONFIGURATION_get_value_filename (env->cfg,
1778                                                "transport-unix",
1779                                                "UNIXPATH",
1780                                                &plugin->unix_socket_path))
1781   {
1782     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
1783                                "transport-unix",
1784                                "UNIXPATH");
1785     GNUNET_free (plugin);
1786     return NULL;
1787   }
1788
1789   plugin->env = env;
1790
1791   /* Initialize my flags */
1792 #ifdef LINUX
1793   plugin->is_abstract = GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg,
1794                                                               "testing",
1795                                                               "USE_ABSTRACT_SOCKETS");
1796 #endif
1797   plugin->myoptions = UNIX_OPTIONS_NONE;
1798   if (GNUNET_YES == plugin->is_abstract)
1799     plugin->myoptions = UNIX_OPTIONS_USE_ABSTRACT_SOCKETS;
1800
1801   api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
1802   api->cls = plugin;
1803   api->get_session = &unix_plugin_get_session;
1804   api->send = &unix_plugin_send;
1805   api->disconnect_peer = &unix_plugin_peer_disconnect;
1806   api->disconnect_session = &unix_plugin_session_disconnect;
1807   api->query_keepalive_factor = &unix_plugin_query_keepalive_factor;
1808   api->address_pretty_printer = &unix_plugin_address_pretty_printer;
1809   api->address_to_string = &unix_plugin_address_to_string;
1810   api->check_address = &unix_plugin_check_address;
1811   api->string_to_address = &unix_plugin_string_to_address;
1812   api->get_network = &unix_plugin_get_network;
1813   api->get_network_for_address = &unix_plugin_get_network_for_address;
1814   api->update_session_timeout = &unix_plugin_update_session_timeout;
1815   api->setup_monitor = &unix_plugin_setup_monitor;
1816   sockets_created = unix_transport_server_start (plugin);
1817   if ((0 == sockets_created) || (GNUNET_SYSERR == sockets_created))
1818   {
1819     LOG (GNUNET_ERROR_TYPE_WARNING,
1820          _("Failed to open UNIX listen socket\n"));
1821     GNUNET_free (api);
1822     GNUNET_free (plugin->unix_socket_path);
1823     GNUNET_free (plugin);
1824     return NULL;
1825   }
1826   plugin->session_map = GNUNET_CONTAINER_multipeermap_create (10, GNUNET_NO);
1827   plugin->address_update_task = GNUNET_SCHEDULER_add_now (&address_notification,
1828                                                           plugin);
1829   return api;
1830 }
1831
1832
1833 /**
1834  * Shutdown the plugin.
1835  *
1836  * @param cls the plugin API returned from the initialization function
1837  * @return NULL (always)
1838  */
1839 void *
1840 libgnunet_plugin_transport_unix_done (void *cls)
1841 {
1842   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1843   struct Plugin *plugin = api->cls;
1844   struct GNUNET_HELLO_Address *address;
1845   struct UNIXMessageWrapper * msgw;
1846   struct UnixAddress *ua;
1847   size_t len;
1848   struct GNUNET_ATS_Session *session;
1849
1850   if (NULL == plugin)
1851   {
1852     GNUNET_free (api);
1853     return NULL;
1854   }
1855   len = sizeof (struct UnixAddress) + strlen (plugin->unix_socket_path) + 1;
1856   ua = GNUNET_malloc (len);
1857   ua->options = htonl (plugin->myoptions);
1858   ua->addrlen = htonl(strlen (plugin->unix_socket_path) + 1);
1859   memcpy (&ua[1],
1860           plugin->unix_socket_path,
1861           strlen (plugin->unix_socket_path) + 1);
1862   address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
1863                                            PLUGIN_NAME,
1864                                            ua, len,
1865                                            GNUNET_HELLO_ADDRESS_INFO_NONE);
1866   plugin->env->notify_address (plugin->env->cls,
1867                                GNUNET_NO,
1868                                address);
1869
1870   GNUNET_free (address);
1871   GNUNET_free (ua);
1872
1873   while (NULL != (msgw = plugin->msg_head))
1874   {
1875     GNUNET_CONTAINER_DLL_remove (plugin->msg_head,
1876                                  plugin->msg_tail,
1877                                  msgw);
1878     session = msgw->session;
1879     session->msgs_in_queue--;
1880     GNUNET_assert (session->bytes_in_queue >= msgw->msgsize);
1881     session->bytes_in_queue -= msgw->msgsize;
1882     GNUNET_assert (plugin->bytes_in_queue >= msgw->msgsize);
1883     plugin->bytes_in_queue -= msgw->msgsize;
1884     if (NULL != msgw->cont)
1885       msgw->cont (msgw->cont_cls,
1886                   &msgw->session->target,
1887                   GNUNET_SYSERR,
1888                   msgw->payload, 0);
1889     GNUNET_free (msgw->msg);
1890     GNUNET_free (msgw);
1891   }
1892
1893   if (NULL != plugin->read_task)
1894   {
1895     GNUNET_SCHEDULER_cancel (plugin->read_task);
1896     plugin->read_task = NULL;
1897   }
1898   if (NULL != plugin->write_task)
1899   {
1900     GNUNET_SCHEDULER_cancel (plugin->write_task);
1901     plugin->write_task = NULL;
1902   }
1903   if (NULL != plugin->address_update_task)
1904   {
1905     GNUNET_SCHEDULER_cancel (plugin->address_update_task);
1906     plugin->address_update_task = NULL;
1907   }
1908   if (NULL != plugin->unix_sock.desc)
1909   {
1910     GNUNET_break (GNUNET_OK ==
1911                   GNUNET_NETWORK_socket_close (plugin->unix_sock.desc));
1912     plugin->unix_sock.desc = NULL;
1913   }
1914   GNUNET_CONTAINER_multipeermap_iterate (plugin->session_map,
1915                                          &get_session_delete_it,
1916                                          plugin);
1917   GNUNET_CONTAINER_multipeermap_destroy (plugin->session_map);
1918   GNUNET_break (0 == plugin->bytes_in_queue);
1919   GNUNET_free (plugin->unix_socket_path);
1920   GNUNET_free (plugin);
1921   GNUNET_free (api);
1922   return NULL;
1923 }
1924
1925 /* end of plugin_transport_unix.c */