Various changes:
[oweals/gnunet.git] / src / transport / plugin_transport_unix.c
1 /*
2      This file is part of GNUnet
3      (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., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file transport/plugin_transport_unix.c
23  * @brief Transport plugin using unix domain sockets (!)
24  *        Clearly, can only be used locally on Unix/Linux hosts...
25  *        ONLY INTENDED FOR TESTING!!!
26  * @author Christian Grothoff
27  * @author Nathan Evans
28  */
29 #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    * ATS network
322    */
323   struct GNUNET_ATS_Information ats_network;
324
325   /**
326    * Are we using an abstract UNIX domain socket?
327    */
328   int is_abstract;
329
330 };
331
332
333 /**
334  * If a session monitor is attached, notify it about the new
335  * session state.
336  *
337  * @param plugin our plugin
338  * @param session session that changed state
339  * @param state new state of the session
340  */
341 static void
342 notify_session_monitor (struct Plugin *plugin,
343                         struct Session *session,
344                         enum GNUNET_TRANSPORT_SessionState state)
345 {
346   struct GNUNET_TRANSPORT_SessionInfo info;
347
348   if (NULL == plugin->sic)
349     return;
350   memset (&info, 0, sizeof (info));
351   info.state = state;
352   info.is_inbound = GNUNET_SYSERR; /* hard to say */
353   info.num_msg_pending = session->msgs_in_queue;
354   info.num_bytes_pending = session->bytes_in_queue;
355   /* info.receive_delay remains zero as this is not supported by UNIX
356      (cannot selectively not receive from 'some' peer while continuing
357      to receive from others) */
358   info.session_timeout = session->timeout;
359   info.address = session->address;
360   plugin->sic (plugin->sic_cls,
361                session,
362                &info);
363 }
364
365
366 /**
367  * Function called for a quick conversion of the binary address to
368  * a numeric address.  Note that the caller must not free the
369  * address and that the next call to this function is allowed
370  * to override the address again.
371  *
372  * @param cls closure
373  * @param addr binary address
374  * @param addrlen length of the @a addr
375  * @return string representing the same address
376  */
377 static const char *
378 unix_plugin_address_to_string (void *cls,
379                                const void *addr,
380                                size_t addrlen)
381 {
382   static char rbuf[1024];
383   struct UnixAddress *ua = (struct UnixAddress *) addr;
384   char *addrstr;
385   size_t addr_str_len;
386   unsigned int off;
387
388   if ((NULL == addr) || (sizeof (struct UnixAddress) > addrlen))
389   {
390     GNUNET_break(0);
391     return NULL;
392   }
393   addrstr = (char *) &ua[1];
394   addr_str_len = ntohl (ua->addrlen);
395
396   if (addr_str_len != addrlen - sizeof(struct UnixAddress))
397   {
398     GNUNET_break(0);
399     return NULL;
400   }
401   if ('\0' != addrstr[addr_str_len - 1])
402   {
403     GNUNET_break(0);
404     return NULL;
405   }
406   if (strlen (addrstr) + 1 != addr_str_len)
407   {
408     GNUNET_break(0);
409     return NULL;
410   }
411
412   off = 0;
413   if ('\0' == addrstr[0])
414     off++;
415   memset (rbuf, 0, sizeof (rbuf));
416   GNUNET_snprintf (rbuf,
417                    sizeof (rbuf) - 1,
418                    "%s.%u.%s%.*s",
419                    PLUGIN_NAME,
420                    ntohl (ua->options),
421                    (off == 1) ? "@" : "",
422                    (int) (addr_str_len - off),
423                    &addrstr[off]);
424   return rbuf;
425 }
426
427
428 /**
429  * Functions with this signature are called whenever we need
430  * to close a session due to a disconnect or failure to
431  * establish a connection.
432  *
433  * @param cls closure with the `struct Plugin *`
434  * @param session session to close down
435  * @return #GNUNET_OK on success
436  */
437 static int
438 unix_plugin_session_disconnect (void *cls,
439                                 struct Session *session)
440 {
441   struct Plugin *plugin = cls;
442   struct UNIXMessageWrapper *msgw;
443   struct UNIXMessageWrapper *next;
444
445   LOG (GNUNET_ERROR_TYPE_DEBUG,
446        "Disconnecting session for peer `%s' `%s'\n",
447        GNUNET_i2s (&session->target),
448        unix_plugin_address_to_string (NULL,
449                                       session->address->address,
450                                       session->address->address_length));
451   plugin->env->session_end (plugin->env->cls,
452                             session->address,
453                             session);
454   next = plugin->msg_head;
455   while (NULL != next)
456   {
457     msgw = next;
458     next = msgw->next;
459     if (msgw->session != session)
460       continue;
461     GNUNET_CONTAINER_DLL_remove (plugin->msg_head,
462                                  plugin->msg_tail,
463                                  msgw);
464     session->msgs_in_queue--;
465     GNUNET_assert (session->bytes_in_queue >= msgw->msgsize);
466     session->bytes_in_queue -= msgw->msgsize;
467     GNUNET_assert (plugin->bytes_in_queue >= msgw->msgsize);
468     plugin->bytes_in_queue -= msgw->msgsize;
469     if (NULL != msgw->cont)
470       msgw->cont (msgw->cont_cls,
471                   &msgw->session->target,
472                   GNUNET_SYSERR,
473                   msgw->payload, 0);
474     GNUNET_free (msgw->msg);
475     GNUNET_free (msgw);
476   }
477   GNUNET_assert (GNUNET_YES ==
478                  GNUNET_CONTAINER_multipeermap_remove (plugin->session_map,
479                                                        &session->target,
480                                                        session));
481   GNUNET_STATISTICS_set (plugin->env->stats,
482                          "# UNIX sessions active",
483                          GNUNET_CONTAINER_multipeermap_size (plugin->session_map),
484                          GNUNET_NO);
485   if (NULL != session->timeout_task)
486   {
487     GNUNET_SCHEDULER_cancel (session->timeout_task);
488     session->timeout_task = NULL;
489     session->timeout = GNUNET_TIME_UNIT_ZERO_ABS;
490   }
491   notify_session_monitor (plugin,
492                           session,
493                           GNUNET_TRANSPORT_SS_DONE);
494   GNUNET_HELLO_address_free (session->address);
495   GNUNET_break (0 == session->bytes_in_queue);
496   GNUNET_break (0 == session->msgs_in_queue);
497   GNUNET_free (session);
498   return GNUNET_OK;
499 }
500
501
502 /**
503  * Session was idle for too long, so disconnect it
504  *
505  * @param cls the `struct Session *` to disconnect
506  * @param tc scheduler context
507  */
508 static void
509 session_timeout (void *cls,
510                  const struct GNUNET_SCHEDULER_TaskContext *tc)
511 {
512   struct Session *session = cls;
513   struct GNUNET_TIME_Relative left;
514
515   session->timeout_task = NULL;
516   left = GNUNET_TIME_absolute_get_remaining (session->timeout);
517   if (0 != left.rel_value_us)
518   {
519     /* not actually our turn yet, but let's at least update
520        the monitor, it may think we're about to die ... */
521     notify_session_monitor (session->plugin,
522                             session,
523                             GNUNET_TRANSPORT_SS_UPDATE);
524     session->timeout_task = GNUNET_SCHEDULER_add_delayed (left,
525                                                           &session_timeout,
526                                                           session);
527     return;
528   }
529   LOG (GNUNET_ERROR_TYPE_DEBUG,
530        "Session %p was idle for %s, disconnecting\n",
531        session,
532        GNUNET_STRINGS_relative_time_to_string (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
533                                                GNUNET_YES));
534   unix_plugin_session_disconnect (session->plugin, session);
535 }
536
537
538 /**
539  * Increment session timeout due to activity.  We do not immediately
540  * notify the monitor here as that might generate excessive
541  * signalling.
542  *
543  * @param session session for which the timeout should be rescheduled
544  */
545 static void
546 reschedule_session_timeout (struct Session *session)
547 {
548   GNUNET_assert (NULL != session->timeout_task);
549   session->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
550 }
551
552
553 /**
554  * Convert unix path to a `struct sockaddr_un *`
555  *
556  * @param unixpath path to convert
557  * @param[out] sock_len set to the length of the address
558  * @return converted unix path
559  */
560 static struct sockaddr_un *
561 unix_address_to_sockaddr (const char *unixpath,
562                           socklen_t *sock_len)
563 {
564   struct sockaddr_un *un;
565   size_t slen;
566
567   GNUNET_assert (0 < strlen (unixpath));        /* sanity check */
568   un = GNUNET_new (struct sockaddr_un);
569   un->sun_family = AF_UNIX;
570   slen = strlen (unixpath);
571   if (slen >= sizeof (un->sun_path))
572     slen = sizeof (un->sun_path) - 1;
573   memcpy (un->sun_path, unixpath, slen);
574   un->sun_path[slen] = '\0';
575   slen = sizeof (struct sockaddr_un);
576 #if HAVE_SOCKADDR_IN_SIN_LEN
577   un->sun_len = (u_char) slen;
578 #endif
579   (*sock_len) = slen;
580   return un;
581 }
582
583
584 /**
585  * Closure to #lookup_session_it().
586  */
587 struct LookupCtx
588 {
589   /**
590    * Location to store the session, if found.
591    */
592   struct Session *res;
593
594   /**
595    * Address we are looking for.
596    */
597   const struct GNUNET_HELLO_Address *address;
598 };
599
600
601 /**
602  * Function called to find a session by address.
603  *
604  * @param cls the `struct LookupCtx *`
605  * @param key peer we are looking for (unused)
606  * @param value a session
607  * @return #GNUNET_YES if not found (continue looking), #GNUNET_NO on success
608  */
609 static int
610 lookup_session_it (void *cls,
611                    const struct GNUNET_PeerIdentity * key,
612                    void *value)
613 {
614   struct LookupCtx *lctx = cls;
615   struct Session *session = value;
616
617   if (0 == GNUNET_HELLO_address_cmp (lctx->address,
618                                      session->address))
619   {
620     lctx->res = session;
621     return GNUNET_NO;
622   }
623   return GNUNET_YES;
624 }
625
626
627 /**
628  * Find an existing session by address.
629  *
630  * @param plugin the plugin
631  * @param address the address to find
632  * @return NULL if session was not found
633  */
634 static struct Session *
635 lookup_session (struct Plugin *plugin,
636                 const struct GNUNET_HELLO_Address *address)
637 {
638   struct LookupCtx lctx;
639
640   lctx.address = address;
641   lctx.res = NULL;
642   GNUNET_CONTAINER_multipeermap_get_multiple (plugin->session_map,
643                                               &address->peer,
644                                               &lookup_session_it, &lctx);
645   return lctx.res;
646 }
647
648
649 /**
650  * Function that is called to get the keepalive factor.
651  * #GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT is divided by this number to
652  * calculate the interval between keepalive packets.
653  *
654  * @param cls closure with the `struct Plugin`
655  * @return keepalive factor
656  */
657 static unsigned int
658 unix_plugin_query_keepalive_factor (void *cls)
659 {
660   return 3;
661 }
662
663
664 /**
665  * Actually send out the message, assume we've got the address and
666  * send_handle squared away!
667  *
668  * @param cls closure
669  * @param send_handle which handle to send message on
670  * @param target who should receive this message (ignored by UNIX)
671  * @param msgbuf one or more GNUNET_MessageHeader(s) strung together
672  * @param msgbuf_size the size of the @a msgbuf to send
673  * @param priority how important is the message (ignored by UNIX)
674  * @param timeout when should we time out (give up) if we can not transmit?
675  * @param addr the addr to send the message to, needs to be a sockaddr for us
676  * @param addrlen the len of @a addr
677  * @param payload bytes payload to send
678  * @param cont continuation to call once the message has
679  *        been transmitted (or if the transport is ready
680  *        for the next transmission call; or if the
681  *        peer disconnected...)
682  * @param cont_cls closure for @a cont
683  * @return on success the number of bytes written, RETRY for retry, -1 on errors
684  */
685 static ssize_t
686 unix_real_send (void *cls,
687                 struct GNUNET_NETWORK_Handle *send_handle,
688                 const struct GNUNET_PeerIdentity *target,
689                 const char *msgbuf,
690                 size_t msgbuf_size,
691                 unsigned int priority,
692                 struct GNUNET_TIME_Absolute timeout,
693                 const struct UnixAddress *addr,
694                 size_t addrlen,
695                 size_t payload,
696                 GNUNET_TRANSPORT_TransmitContinuation cont,
697                 void *cont_cls)
698 {
699   struct Plugin *plugin = cls;
700   ssize_t sent;
701   struct sockaddr_un *un;
702   socklen_t un_len;
703   const char *unixpath;
704
705   if (NULL == send_handle)
706   {
707     GNUNET_break (0); /* We do not have a send handle */
708     return GNUNET_SYSERR;
709   }
710   if ((NULL == addr) || (0 == addrlen))
711   {
712     GNUNET_break (0); /* Can never send if we don't have an address */
713     return GNUNET_SYSERR;
714   }
715
716   /* Prepare address */
717   unixpath = (const char *)  &addr[1];
718   if (NULL == (un = unix_address_to_sockaddr (unixpath,
719                                               &un_len)))
720   {
721     GNUNET_break (0);
722     return -1;
723   }
724
725   if ((GNUNET_YES == plugin->is_abstract) &&
726       (0 != (UNIX_OPTIONS_USE_ABSTRACT_SOCKETS & ntohl(addr->options) )) )
727   {
728     un->sun_path[0] = '\0';
729   }
730 resend:
731   /* Send the data */
732   sent = GNUNET_NETWORK_socket_sendto (send_handle,
733                                        msgbuf,
734                                        msgbuf_size,
735                                        (const struct sockaddr *) un,
736                                        un_len);
737   if (GNUNET_SYSERR == sent)
738   {
739     if ( (EAGAIN == errno) ||
740          (ENOBUFS == errno) )
741     {
742       GNUNET_free (un);
743       return RETRY; /* We have to retry later  */
744     }
745     if (EMSGSIZE == errno)
746     {
747       socklen_t size = 0;
748       socklen_t len = sizeof (size);
749
750       GNUNET_NETWORK_socket_getsockopt ((struct GNUNET_NETWORK_Handle *)
751                                         send_handle, SOL_SOCKET, SO_SNDBUF, &size,
752                                         &len);
753       if (size < msgbuf_size)
754       {
755         LOG (GNUNET_ERROR_TYPE_DEBUG,
756              "Trying to increase socket buffer size from %u to %u for message size %u\n",
757              (unsigned int) size,
758              (unsigned int) ((msgbuf_size / 1000) + 2) * 1000,
759              (unsigned int) msgbuf_size);
760         size = ((msgbuf_size / 1000) + 2) * 1000;
761         if (GNUNET_OK ==
762             GNUNET_NETWORK_socket_setsockopt ((struct GNUNET_NETWORK_Handle *) send_handle,
763                                               SOL_SOCKET, SO_SNDBUF,
764                                               &size, sizeof (size)))
765           goto resend; /* Increased buffer size, retry sending */
766         else
767         {
768           /* Could not increase buffer size: error, no retry */
769           GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "setsockopt");
770           GNUNET_free (un);
771           return GNUNET_SYSERR;
772         }
773       }
774       else
775       {
776         /* Buffer is bigger than message:  error, no retry
777          * This should never happen!*/
778         GNUNET_break (0);
779         GNUNET_free (un);
780         return GNUNET_SYSERR;
781       }
782     }
783   }
784
785   LOG (GNUNET_ERROR_TYPE_DEBUG,
786        "UNIX transmitted %u-byte message to %s (%d: %s)\n",
787        (unsigned int) msgbuf_size,
788        GNUNET_a2s ((const struct sockaddr *)un, un_len),
789        (int) sent,
790        (sent < 0) ? STRERROR (errno) : "ok");
791   GNUNET_free (un);
792   return sent;
793 }
794
795
796 /**
797  * Function obtain the network type for a session
798  *
799  * @param cls closure ('struct Plugin*')
800  * @param session the session
801  * @return the network type in HBO or #GNUNET_SYSERR
802  */
803 static enum GNUNET_ATS_Network_Type
804 unix_plugin_get_network (void *cls,
805                          struct Session *session)
806 {
807   GNUNET_assert (NULL != session);
808   return GNUNET_ATS_NET_LOOPBACK;
809 }
810
811
812 /**
813  * Creates a new outbound session the transport service will use to send data to the
814  * peer
815  *
816  * @param cls the plugin
817  * @param address the address
818  * @return the session or NULL of max connections exceeded
819  */
820 static struct Session *
821 unix_plugin_get_session (void *cls,
822                          const struct GNUNET_HELLO_Address *address)
823 {
824   struct Plugin *plugin = cls;
825   struct Session *session;
826   struct UnixAddress *ua;
827   char * addrstr;
828   uint32_t addr_str_len;
829   uint32_t addr_option;
830
831   ua = (struct UnixAddress *) address->address;
832   if ((NULL == address->address) || (0 == address->address_length) ||
833                 (sizeof (struct UnixAddress) > address->address_length))
834   {
835     GNUNET_break (0);
836     return NULL;
837   }
838   addrstr = (char *) &ua[1];
839   addr_str_len = ntohl (ua->addrlen);
840   addr_option = ntohl (ua->options);
841
842   if ( (0 != (UNIX_OPTIONS_USE_ABSTRACT_SOCKETS & addr_option)) &&
843     (GNUNET_NO == plugin->is_abstract))
844   {
845     return NULL;
846   }
847
848   if (addr_str_len != address->address_length - sizeof (struct UnixAddress))
849   {
850     return NULL; /* This can be a legacy address */
851   }
852
853   if ('\0' != addrstr[addr_str_len - 1])
854   {
855     GNUNET_break (0);
856     return NULL;
857   }
858   if (strlen (addrstr) + 1 != addr_str_len)
859   {
860     GNUNET_break (0);
861     return NULL;
862   }
863
864   /* Check if a session for this address already exists */
865   if (NULL != (session = lookup_session (plugin,
866                                          address)))
867     {
868     LOG (GNUNET_ERROR_TYPE_DEBUG,
869          "Found existing session %p for address `%s'\n",
870          session,
871          unix_plugin_address_to_string (NULL,
872                                         address->address,
873                                         address->address_length));
874     return session;
875   }
876
877   /* create a new session */
878   session = GNUNET_new (struct Session);
879   session->target = address->peer;
880   session->address = GNUNET_HELLO_address_copy (address);
881   session->plugin = plugin;
882   session->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
883   session->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
884                                                         &session_timeout,
885                                                         session);
886   LOG (GNUNET_ERROR_TYPE_DEBUG,
887        "Creating a new session %p for address `%s'\n",
888        session,
889        unix_plugin_address_to_string (NULL,
890                                       address->address,
891                                       address->address_length));
892   (void) GNUNET_CONTAINER_multipeermap_put (plugin->session_map,
893                                             &address->peer, session,
894                                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
895   GNUNET_STATISTICS_set (plugin->env->stats,
896                          "# UNIX sessions active",
897                          GNUNET_CONTAINER_multipeermap_size (plugin->session_map),
898                          GNUNET_NO);
899   notify_session_monitor (plugin,
900                           session,
901                           GNUNET_TRANSPORT_SS_INIT);
902   notify_session_monitor (plugin,
903                           session,
904                           GNUNET_TRANSPORT_SS_UP);
905   return session;
906 }
907
908
909 /**
910  * Function that will be called whenever the transport service wants
911  * to notify the plugin that a session is still active and in use and
912  * therefore the session timeout for this session has to be updated
913  *
914  * @param cls closure with the `struct Plugin *`
915  * @param peer which peer was the session for
916  * @param session which session is being updated
917  */
918 static void
919 unix_plugin_update_session_timeout (void *cls,
920                                     const struct GNUNET_PeerIdentity *peer,
921                                     struct Session *session)
922 {
923   struct Plugin *plugin = cls;
924
925   if (GNUNET_OK !=
926       GNUNET_CONTAINER_multipeermap_contains_value (plugin->session_map,
927                                                     &session->target,
928                                                     session))
929   {
930     GNUNET_break (0);
931     return;
932   }
933   reschedule_session_timeout (session);
934 }
935
936
937 /**
938  * Demultiplexer for UNIX messages
939  *
940  * @param plugin the main plugin for this transport
941  * @param sender from which peer the message was received
942  * @param currhdr pointer to the header of the message
943  * @param ua address to look for
944  * @param ua_len length of the address @a ua
945  */
946 static void
947 unix_demultiplexer (struct Plugin *plugin,
948                     struct GNUNET_PeerIdentity *sender,
949                     const struct GNUNET_MessageHeader *currhdr,
950                     const struct UnixAddress *ua, size_t ua_len)
951 {
952   struct Session *session;
953   struct GNUNET_HELLO_Address *address;
954
955   GNUNET_break (ntohl(plugin->ats_network.value) != GNUNET_ATS_NET_UNSPECIFIED);
956   GNUNET_assert (ua_len >= sizeof (struct UnixAddress));
957   LOG (GNUNET_ERROR_TYPE_DEBUG,
958        "Received message from %s\n",
959        unix_plugin_address_to_string (NULL, ua, ua_len));
960   GNUNET_STATISTICS_update (plugin->env->stats,
961                             "# bytes received via UNIX",
962                             ntohs (currhdr->size),
963                             GNUNET_NO);
964
965   /* Look for existing session */
966   address = GNUNET_HELLO_address_allocate (sender,
967                                            PLUGIN_NAME,
968                                            ua, ua_len,
969                                            GNUNET_HELLO_ADDRESS_INFO_NONE); /* UNIX does not have "inbound" sessions */
970   session = lookup_session (plugin, address);
971   if (NULL == session)
972   {
973     session = unix_plugin_get_session (plugin, address);
974     /* Notify transport and ATS about new inbound session */
975     plugin->env->session_start (NULL,
976                                 session->address,
977                                 session,
978                                 &plugin->ats_network, 1);
979   }
980   else
981   {
982     reschedule_session_timeout (session);
983   }
984   GNUNET_HELLO_address_free (address);
985   plugin->env->receive (plugin->env->cls,
986                         session->address,
987                         session,
988                         currhdr);
989   plugin->env->update_address_metrics (plugin->env->cls,
990                                        session->address,
991                                        session,
992                                        &plugin->ats_network, 1);
993 }
994
995
996 /**
997  * Read from UNIX domain socket (it is ready).
998  *
999  * @param plugin the plugin
1000  */
1001 static void
1002 unix_plugin_do_read (struct Plugin *plugin)
1003 {
1004   char buf[65536] GNUNET_ALIGN;
1005   struct UnixAddress *ua;
1006   struct UNIXMessage *msg;
1007   struct GNUNET_PeerIdentity sender;
1008   struct sockaddr_un un;
1009   socklen_t addrlen;
1010   ssize_t ret;
1011   int offset;
1012   int tsize;
1013   int is_abstract;
1014   char *msgbuf;
1015   const struct GNUNET_MessageHeader *currhdr;
1016   uint16_t csize;
1017   size_t ua_len;
1018
1019   addrlen = sizeof (un);
1020   memset (&un, 0, sizeof (un));
1021   ret = GNUNET_NETWORK_socket_recvfrom (plugin->unix_sock.desc,
1022                                         buf, sizeof (buf),
1023                                         (struct sockaddr *) &un,
1024                                         &addrlen);
1025   if ((GNUNET_SYSERR == ret) && ((errno == EAGAIN) || (errno == ENOBUFS)))
1026     return;
1027   if (GNUNET_SYSERR == ret)
1028   {
1029     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
1030                          "recvfrom");
1031     return;
1032   }
1033   else
1034   {
1035     LOG (GNUNET_ERROR_TYPE_DEBUG,
1036          "Read %d bytes from socket %s\n",
1037          (int) ret,
1038          un.sun_path);
1039   }
1040
1041   GNUNET_assert (AF_UNIX == (un.sun_family));
1042   is_abstract = GNUNET_NO;
1043   if ('\0' == un.sun_path[0])
1044   {
1045     un.sun_path[0] = '@';
1046     is_abstract = GNUNET_YES;
1047   }
1048
1049   ua_len = sizeof (struct UnixAddress) + strlen (un.sun_path) + 1;
1050   ua = GNUNET_malloc (ua_len);
1051   ua->addrlen = htonl (strlen (&un.sun_path[0]) +1);
1052   memcpy (&ua[1], &un.sun_path[0], strlen (un.sun_path) + 1);
1053   if (is_abstract)
1054     ua->options = htonl(UNIX_OPTIONS_USE_ABSTRACT_SOCKETS);
1055   else
1056     ua->options = htonl(UNIX_OPTIONS_NONE);
1057
1058   msg = (struct UNIXMessage *) buf;
1059   csize = ntohs (msg->header.size);
1060   if ((csize < sizeof (struct UNIXMessage)) || (csize > ret))
1061   {
1062     GNUNET_break_op (0);
1063     GNUNET_free (ua);
1064     return;
1065   }
1066   msgbuf = (char *) &msg[1];
1067   memcpy (&sender,
1068           &msg->sender,
1069           sizeof (struct GNUNET_PeerIdentity));
1070   offset = 0;
1071   tsize = csize - sizeof (struct UNIXMessage);
1072   while (offset + sizeof (struct GNUNET_MessageHeader) <= tsize)
1073   {
1074     currhdr = (struct GNUNET_MessageHeader *) &msgbuf[offset];
1075     csize = ntohs (currhdr->size);
1076     if ((csize < sizeof (struct GNUNET_MessageHeader)) ||
1077         (csize > tsize - offset))
1078     {
1079       GNUNET_break_op (0);
1080       break;
1081     }
1082     unix_demultiplexer (plugin, &sender, currhdr, ua, ua_len);
1083     offset += csize;
1084   }
1085   GNUNET_free (ua);
1086 }
1087
1088
1089 /**
1090  * Write to UNIX domain socket (it is ready).
1091  *
1092  * @param plugin handle to the plugin
1093  */
1094 static void
1095 unix_plugin_do_write (struct Plugin *plugin)
1096 {
1097   ssize_t sent = 0;
1098   struct UNIXMessageWrapper *msgw;
1099   struct Session *session;
1100   int did_delete;
1101
1102   session = NULL;
1103   did_delete = GNUNET_NO;
1104   while (NULL != (msgw = plugin->msg_head))
1105   {
1106     if (GNUNET_TIME_absolute_get_remaining (msgw->timeout).rel_value_us > 0)
1107       break; /* Message is ready for sending */
1108     /* Message has a timeout */
1109     did_delete = GNUNET_YES;
1110     LOG (GNUNET_ERROR_TYPE_DEBUG,
1111          "Timeout for message with %u bytes \n",
1112          (unsigned int) msgw->msgsize);
1113     GNUNET_CONTAINER_DLL_remove (plugin->msg_head,
1114                                  plugin->msg_tail,
1115                                  msgw);
1116     session = msgw->session;
1117     session->msgs_in_queue--;
1118     GNUNET_assert (session->bytes_in_queue >= msgw->msgsize);
1119     session->bytes_in_queue -= msgw->msgsize;
1120     GNUNET_assert (plugin->bytes_in_queue >= msgw->msgsize);
1121     plugin->bytes_in_queue -= msgw->msgsize;
1122     GNUNET_STATISTICS_set (plugin->env->stats,
1123                            "# bytes currently in UNIX buffers",
1124                            plugin->bytes_in_queue,
1125                            GNUNET_NO);
1126     GNUNET_STATISTICS_update (plugin->env->stats,
1127                               "# UNIX bytes discarded",
1128                               msgw->msgsize,
1129                               GNUNET_NO);
1130     if (NULL != msgw->cont)
1131       msgw->cont (msgw->cont_cls,
1132                   &msgw->session->target,
1133                   GNUNET_SYSERR,
1134                   msgw->payload,
1135                   0);
1136     GNUNET_free (msgw->msg);
1137     GNUNET_free (msgw);
1138   }
1139   if (NULL == msgw)
1140   {
1141     if (GNUNET_YES == did_delete)
1142       notify_session_monitor (plugin,
1143                               session,
1144                               GNUNET_TRANSPORT_SS_UPDATE);
1145     return; /* Nothing to send at the moment */
1146   }
1147   session = msgw->session;
1148   sent = unix_real_send (plugin,
1149                          plugin->unix_sock.desc,
1150                          &session->target,
1151                          (const char *) msgw->msg,
1152                          msgw->msgsize,
1153                          msgw->priority,
1154                          msgw->timeout,
1155                          msgw->session->address->address,
1156                          msgw->session->address->address_length,
1157                          msgw->payload,
1158                          msgw->cont, msgw->cont_cls);
1159   if (RETRY == sent)
1160   {
1161     GNUNET_STATISTICS_update (plugin->env->stats,
1162                               "# UNIX retry attempts",
1163                               1, GNUNET_NO);
1164     notify_session_monitor (plugin,
1165                             session,
1166                             GNUNET_TRANSPORT_SS_UPDATE);
1167     return;
1168   }
1169   GNUNET_CONTAINER_DLL_remove (plugin->msg_head,
1170                                plugin->msg_tail,
1171                                msgw);
1172   session->msgs_in_queue--;
1173   GNUNET_assert (session->bytes_in_queue >= msgw->msgsize);
1174   session->bytes_in_queue -= msgw->msgsize;
1175   GNUNET_assert (plugin->bytes_in_queue >= msgw->msgsize);
1176   plugin->bytes_in_queue -= msgw->msgsize;
1177   GNUNET_STATISTICS_set (plugin->env->stats,
1178                          "# bytes currently in UNIX buffers",
1179                          plugin->bytes_in_queue, GNUNET_NO);
1180   notify_session_monitor (plugin,
1181                           session,
1182                           GNUNET_TRANSPORT_SS_UPDATE);
1183   if (GNUNET_SYSERR == sent)
1184   {
1185     /* failed and no retry */
1186     if (NULL != msgw->cont)
1187       msgw->cont (msgw->cont_cls,
1188                   &msgw->session->target,
1189                   GNUNET_SYSERR,
1190                   msgw->payload, 0);
1191     GNUNET_STATISTICS_update (plugin->env->stats,
1192                               "# UNIX bytes discarded",
1193                               msgw->msgsize,
1194                               GNUNET_NO);
1195     GNUNET_free (msgw->msg);
1196     GNUNET_free (msgw);
1197     return;
1198   }
1199   /* successfully sent bytes */
1200   GNUNET_break (sent > 0);
1201   GNUNET_STATISTICS_update (plugin->env->stats,
1202                             "# bytes transmitted via UNIX",
1203                             msgw->msgsize,
1204                             GNUNET_NO);
1205   if (NULL != msgw->cont)
1206     msgw->cont (msgw->cont_cls,
1207                 &msgw->session->target,
1208                 GNUNET_OK,
1209                 msgw->payload,
1210                 msgw->msgsize);
1211   GNUNET_free (msgw->msg);
1212   GNUNET_free (msgw);
1213 }
1214
1215
1216 /**
1217  * We have been notified that our socket has something to read.
1218  * Then reschedule this function to be called again once more is available.
1219  *
1220  * @param cls the plugin handle
1221  * @param tc the scheduling context
1222  */
1223 static void
1224 unix_plugin_select_read (void *cls,
1225                          const struct GNUNET_SCHEDULER_TaskContext *tc)
1226 {
1227   struct Plugin *plugin = cls;
1228
1229   plugin->read_task = NULL;
1230   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1231     return;
1232   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_READ_READY))
1233     unix_plugin_do_read (plugin);
1234   plugin->read_task =
1235     GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
1236                                    plugin->unix_sock.desc,
1237                                    &unix_plugin_select_read, plugin);
1238 }
1239
1240
1241 /**
1242  * We have been notified that our socket is ready to write.
1243  * Then reschedule this function to be called again once more is available.
1244  *
1245  * @param cls the plugin handle
1246  * @param tc the scheduling context
1247  */
1248 static void
1249 unix_plugin_select_write (void *cls,
1250                          const struct GNUNET_SCHEDULER_TaskContext *tc)
1251 {
1252   struct Plugin *plugin = cls;
1253
1254   plugin->write_task = NULL;
1255   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1256     return;
1257   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY))
1258     unix_plugin_do_write (plugin);
1259   if (NULL == plugin->msg_head)
1260     return; /* write queue empty */
1261   plugin->write_task =
1262     GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
1263                                     plugin->unix_sock.desc,
1264                                     &unix_plugin_select_write, plugin);
1265 }
1266
1267
1268 /**
1269  * Function that can be used by the transport service to transmit
1270  * a message using the plugin.   Note that in the case of a
1271  * peer disconnecting, the continuation MUST be called
1272  * prior to the disconnect notification itself.  This function
1273  * will be called with this peer's HELLO message to initiate
1274  * a fresh connection to another peer.
1275  *
1276  * @param cls closure
1277  * @param session which session must be used
1278  * @param msgbuf the message to transmit
1279  * @param msgbuf_size number of bytes in @a msgbuf
1280  * @param priority how important is the message (most plugins will
1281  *                 ignore message priority and just FIFO)
1282  * @param to how long to wait at most for the transmission (does not
1283  *                require plugins to discard the message after the timeout,
1284  *                just advisory for the desired delay; most plugins will ignore
1285  *                this as well)
1286  * @param cont continuation to call once the message has
1287  *        been transmitted (or if the transport is ready
1288  *        for the next transmission call; or if the
1289  *        peer disconnected...); can be NULL
1290  * @param cont_cls closure for @a cont
1291  * @return number of bytes used (on the physical network, with overheads);
1292  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
1293  *         and does NOT mean that the message was not transmitted (DV)
1294  */
1295 static ssize_t
1296 unix_plugin_send (void *cls,
1297                   struct Session *session,
1298                   const char *msgbuf,
1299                   size_t msgbuf_size,
1300                   unsigned int priority,
1301                   struct GNUNET_TIME_Relative to,
1302                   GNUNET_TRANSPORT_TransmitContinuation cont,
1303                   void *cont_cls)
1304 {
1305   struct Plugin *plugin = cls;
1306   struct UNIXMessageWrapper *wrapper;
1307   struct UNIXMessage *message;
1308   int ssize;
1309
1310   if (GNUNET_OK !=
1311       GNUNET_CONTAINER_multipeermap_contains_value (plugin->session_map,
1312                                                     &session->target,
1313                                                     session))
1314   {
1315     LOG (GNUNET_ERROR_TYPE_ERROR,
1316          "Invalid session for peer `%s' `%s'\n",
1317          GNUNET_i2s (&session->target),
1318          unix_plugin_address_to_string (NULL,
1319                                         session->address->address,
1320                                         session->address->address_length));
1321     GNUNET_break (0);
1322     return GNUNET_SYSERR;
1323   }
1324   LOG (GNUNET_ERROR_TYPE_DEBUG,
1325        "Sending %u bytes with session for peer `%s' `%s'\n",
1326        msgbuf_size,
1327        GNUNET_i2s (&session->target),
1328        unix_plugin_address_to_string (NULL,
1329                                       session->address->address,
1330                                       session->address->address_length));
1331   ssize = sizeof (struct UNIXMessage) + msgbuf_size;
1332   message = GNUNET_malloc (sizeof (struct UNIXMessage) + msgbuf_size);
1333   message->header.size = htons (ssize);
1334   message->header.type = htons (0);
1335   memcpy (&message->sender, plugin->env->my_identity,
1336           sizeof (struct GNUNET_PeerIdentity));
1337   memcpy (&message[1], msgbuf, msgbuf_size);
1338   wrapper = GNUNET_new (struct UNIXMessageWrapper);
1339   wrapper->msg = message;
1340   wrapper->msgsize = ssize;
1341   wrapper->payload = msgbuf_size;
1342   wrapper->priority = priority;
1343   wrapper->timeout = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (),
1344                                                to);
1345   wrapper->cont = cont;
1346   wrapper->cont_cls = cont_cls;
1347   wrapper->session = session;
1348   GNUNET_CONTAINER_DLL_insert_tail (plugin->msg_head,
1349                                     plugin->msg_tail,
1350                                     wrapper);
1351   plugin->bytes_in_queue += ssize;
1352   session->bytes_in_queue += ssize;
1353   session->msgs_in_queue++;
1354   GNUNET_STATISTICS_set (plugin->env->stats,
1355                          "# bytes currently in UNIX buffers",
1356                          plugin->bytes_in_queue,
1357                          GNUNET_NO);
1358   notify_session_monitor (plugin,
1359                           session,
1360                           GNUNET_TRANSPORT_SS_UPDATE);
1361   if (NULL == plugin->write_task)
1362     plugin->write_task =
1363       GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
1364                                       plugin->unix_sock.desc,
1365                                       &unix_plugin_select_write, plugin);
1366   return ssize;
1367 }
1368
1369
1370 /**
1371  * Create a slew of UNIX sockets.  If possible, use IPv6 and IPv4.
1372  *
1373  * @param cls closure for server start, should be a `struct Plugin *`
1374  * @return number of sockets created or #GNUNET_SYSERR on error
1375  */
1376 static int
1377 unix_transport_server_start (void *cls)
1378 {
1379   struct Plugin *plugin = cls;
1380   struct sockaddr_un *un;
1381   socklen_t un_len;
1382
1383   un = unix_address_to_sockaddr (plugin->unix_socket_path,
1384                                  &un_len);
1385   if (GNUNET_YES == plugin->is_abstract)
1386   {
1387     plugin->unix_socket_path[0] = '@';
1388     un->sun_path[0] = '\0';
1389   }
1390   plugin->ats_network.type = htonl (GNUNET_ATS_NETWORK_TYPE);
1391   plugin->ats_network.value = htonl (plugin->env->get_address_type (plugin->env->cls,
1392                                                                     (const struct sockaddr *) un,
1393                                                                     un_len));
1394   plugin->unix_sock.desc =
1395       GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_DGRAM, 0);
1396   if (NULL == plugin->unix_sock.desc)
1397   {
1398     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
1399     return GNUNET_SYSERR;
1400   }
1401   if ('\0' != un->sun_path[0])
1402   {
1403     if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (un->sun_path))
1404     {
1405       LOG (GNUNET_ERROR_TYPE_ERROR, _("Cannot create path to `%s'\n"),
1406           un->sun_path);
1407       GNUNET_NETWORK_socket_close (plugin->unix_sock.desc);
1408       plugin->unix_sock.desc = NULL;
1409       GNUNET_free (un);
1410       return GNUNET_SYSERR;
1411     }
1412   }
1413   if (GNUNET_OK !=
1414       GNUNET_NETWORK_socket_bind (plugin->unix_sock.desc,
1415                                   (const struct sockaddr *) un, un_len))
1416   {
1417     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
1418     LOG (GNUNET_ERROR_TYPE_ERROR, _("Cannot bind to `%s'\n"),
1419         un->sun_path);
1420     GNUNET_NETWORK_socket_close (plugin->unix_sock.desc);
1421     plugin->unix_sock.desc = NULL;
1422     GNUNET_free (un);
1423     return GNUNET_SYSERR;
1424   }
1425   LOG (GNUNET_ERROR_TYPE_DEBUG,
1426        "Bound to `%s'\n",
1427        plugin->unix_socket_path);
1428   plugin->read_task =
1429     GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
1430                                    plugin->unix_sock.desc,
1431                                    &unix_plugin_select_read, plugin);
1432   GNUNET_free (un);
1433   return 1;
1434 }
1435
1436
1437 /**
1438  * Function that will be called to check if a binary address for this
1439  * plugin is well-formed and corresponds to an address for THIS peer
1440  * (as per our configuration).  Naturally, if absolutely necessary,
1441  * plugins can be a bit conservative in their answer, but in general
1442  * plugins should make sure that the address does not redirect
1443  * traffic to a 3rd party that might try to man-in-the-middle our
1444  * traffic.
1445  *
1446  * @param cls closure, should be our handle to the Plugin
1447  * @param addr pointer to the address
1448  * @param addrlen length of @a addr
1449  * @return #GNUNET_OK if this is a plausible address for this peer
1450  *         and transport, #GNUNET_SYSERR if not
1451  *
1452  */
1453 static int
1454 unix_plugin_check_address (void *cls,
1455                            const void *addr,
1456                            size_t addrlen)
1457 {
1458   struct Plugin* plugin = cls;
1459   const struct UnixAddress *ua = addr;
1460   char *addrstr;
1461   size_t addr_str_len;
1462
1463   if ( (NULL == addr) ||
1464        (0 == addrlen) ||
1465        (sizeof (struct UnixAddress) > addrlen) )
1466   {
1467     GNUNET_break (0);
1468     return GNUNET_SYSERR;
1469   }
1470   addrstr = (char *) &ua[1];
1471   addr_str_len = ntohl (ua->addrlen);
1472   if ('\0' != addrstr[addr_str_len - 1])
1473   {
1474     GNUNET_break (0);
1475     return GNUNET_SYSERR;
1476   }
1477   if (strlen (addrstr) + 1 != addr_str_len)
1478   {
1479     GNUNET_break (0);
1480     return GNUNET_SYSERR;
1481   }
1482
1483   if (0 == strcmp (plugin->unix_socket_path, addrstr))
1484         return GNUNET_OK;
1485   return GNUNET_SYSERR;
1486 }
1487
1488
1489 /**
1490  * Convert the transports address to a nice, human-readable
1491  * format.
1492  *
1493  * @param cls closure
1494  * @param type name of the transport that generated the address
1495  * @param addr one of the addresses of the host, NULL for the last address
1496  *        the specific address format depends on the transport
1497  * @param addrlen length of the @a addr
1498  * @param numeric should (IP) addresses be displayed in numeric form?
1499  * @param timeout after how long should we give up?
1500  * @param asc function to call on each string
1501  * @param asc_cls closure for @a asc
1502  */
1503 static void
1504 unix_plugin_address_pretty_printer (void *cls, const char *type,
1505                                     const void *addr,
1506                                     size_t addrlen,
1507                                     int numeric,
1508                                     struct GNUNET_TIME_Relative timeout,
1509                                     GNUNET_TRANSPORT_AddressStringCallback asc,
1510                                     void *asc_cls)
1511 {
1512   const char *ret;
1513
1514   if ( (NULL != addr) && (addrlen > 0))
1515     ret = unix_plugin_address_to_string (NULL,
1516                                          addr,
1517                                          addrlen);
1518   else
1519     ret = NULL;
1520   asc (asc_cls,
1521        ret,
1522        (NULL == ret) ? GNUNET_SYSERR : GNUNET_OK);
1523   asc (asc_cls, NULL, GNUNET_OK);
1524 }
1525
1526
1527 /**
1528  * Function called to convert a string address to
1529  * a binary address.
1530  *
1531  * @param cls closure (`struct Plugin *`)
1532  * @param addr string address
1533  * @param addrlen length of the @a addr (strlen(addr) + '\0')
1534  * @param buf location to store the buffer
1535  *        If the function returns #GNUNET_SYSERR, its contents are undefined.
1536  * @param added length of created address
1537  * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
1538  */
1539 static int
1540 unix_plugin_string_to_address (void *cls,
1541                                const char *addr,
1542                                uint16_t addrlen,
1543                                void **buf, size_t *added)
1544 {
1545   struct UnixAddress *ua;
1546   char *address;
1547   char *plugin;
1548   char *optionstr;
1549   uint32_t options;
1550   size_t ua_size;
1551
1552   /* Format unix.options.address */
1553   address = NULL;
1554   plugin = NULL;
1555   optionstr = NULL;
1556
1557   if ((NULL == addr) || (addrlen == 0))
1558   {
1559     GNUNET_break (0);
1560     return GNUNET_SYSERR;
1561   }
1562   if ('\0' != addr[addrlen - 1])
1563   {
1564     GNUNET_break (0);
1565     return GNUNET_SYSERR;
1566   }
1567   if (strlen (addr) != addrlen - 1)
1568   {
1569     GNUNET_break (0);
1570     return GNUNET_SYSERR;
1571   }
1572   plugin = GNUNET_strdup (addr);
1573   optionstr = strchr (plugin, '.');
1574   if (NULL == optionstr)
1575   {
1576     GNUNET_break (0);
1577     GNUNET_free (plugin);
1578     return GNUNET_SYSERR;
1579   }
1580   optionstr[0] = '\0';
1581   optionstr++;
1582   options = atol (optionstr);
1583   address = strchr (optionstr, '.');
1584   if (NULL == address)
1585   {
1586     GNUNET_break (0);
1587     GNUNET_free (plugin);
1588     return GNUNET_SYSERR;
1589   }
1590   address[0] = '\0';
1591   address++;
1592   if (0 != strcmp(plugin, PLUGIN_NAME))
1593   {
1594     GNUNET_break (0);
1595     GNUNET_free (plugin);
1596     return GNUNET_SYSERR;
1597   }
1598
1599   ua_size = sizeof (struct UnixAddress) + strlen (address) + 1;
1600   ua = GNUNET_malloc (ua_size);
1601   ua->options = htonl (options);
1602   ua->addrlen = htonl (strlen (address) + 1);
1603   memcpy (&ua[1], address, strlen (address) + 1);
1604   GNUNET_free (plugin);
1605
1606   (*buf) = ua;
1607   (*added) = ua_size;
1608   return GNUNET_OK;
1609 }
1610
1611
1612 /**
1613  * Notify transport service about address
1614  *
1615  * @param cls the plugin
1616  * @param tc unused
1617  */
1618 static void
1619 address_notification (void *cls,
1620                       const struct GNUNET_SCHEDULER_TaskContext *tc)
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 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 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 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 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->update_session_timeout = &unix_plugin_update_session_timeout;
1814   api->setup_monitor = &unix_plugin_setup_monitor;
1815   sockets_created = unix_transport_server_start (plugin);
1816   if ((0 == sockets_created) || (GNUNET_SYSERR == sockets_created))
1817   {
1818     LOG (GNUNET_ERROR_TYPE_WARNING,
1819          _("Failed to open UNIX listen socket\n"));
1820     GNUNET_free (api);
1821     GNUNET_free (plugin->unix_socket_path);
1822     GNUNET_free (plugin);
1823     return NULL;
1824   }
1825   plugin->session_map = GNUNET_CONTAINER_multipeermap_create (10, GNUNET_NO);
1826   plugin->address_update_task = GNUNET_SCHEDULER_add_now (&address_notification,
1827                                                           plugin);
1828   return api;
1829 }
1830
1831
1832 /**
1833  * Shutdown the plugin.
1834  *
1835  * @param cls the plugin API returned from the initialization function
1836  * @return NULL (always)
1837  */
1838 void *
1839 libgnunet_plugin_transport_unix_done (void *cls)
1840 {
1841   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1842   struct Plugin *plugin = api->cls;
1843   struct GNUNET_HELLO_Address *address;
1844   struct UNIXMessageWrapper * msgw;
1845   struct UnixAddress *ua;
1846   size_t len;
1847   struct Session *session;
1848
1849   if (NULL == plugin)
1850   {
1851     GNUNET_free (api);
1852     return NULL;
1853   }
1854   len = sizeof (struct UnixAddress) + strlen (plugin->unix_socket_path) + 1;
1855   ua = GNUNET_malloc (len);
1856   ua->options = htonl (plugin->myoptions);
1857   ua->addrlen = htonl(strlen (plugin->unix_socket_path) + 1);
1858   memcpy (&ua[1],
1859           plugin->unix_socket_path,
1860           strlen (plugin->unix_socket_path) + 1);
1861   address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
1862                                            PLUGIN_NAME,
1863                                            ua, len,
1864                                            GNUNET_HELLO_ADDRESS_INFO_NONE);
1865   plugin->env->notify_address (plugin->env->cls,
1866                                GNUNET_NO,
1867                                address);
1868
1869   GNUNET_free (address);
1870   GNUNET_free (ua);
1871
1872   while (NULL != (msgw = plugin->msg_head))
1873   {
1874     GNUNET_CONTAINER_DLL_remove (plugin->msg_head,
1875                                  plugin->msg_tail,
1876                                  msgw);
1877     session = msgw->session;
1878     session->msgs_in_queue--;
1879     GNUNET_assert (session->bytes_in_queue >= msgw->msgsize);
1880     session->bytes_in_queue -= msgw->msgsize;
1881     GNUNET_assert (plugin->bytes_in_queue >= msgw->msgsize);
1882     plugin->bytes_in_queue -= msgw->msgsize;
1883     if (NULL != msgw->cont)
1884       msgw->cont (msgw->cont_cls,
1885                   &msgw->session->target,
1886                   GNUNET_SYSERR,
1887                   msgw->payload, 0);
1888     GNUNET_free (msgw->msg);
1889     GNUNET_free (msgw);
1890   }
1891
1892   if (NULL != plugin->read_task)
1893   {
1894     GNUNET_SCHEDULER_cancel (plugin->read_task);
1895     plugin->read_task = NULL;
1896   }
1897   if (NULL != plugin->write_task)
1898   {
1899     GNUNET_SCHEDULER_cancel (plugin->write_task);
1900     plugin->write_task = NULL;
1901   }
1902   if (NULL != plugin->address_update_task)
1903   {
1904     GNUNET_SCHEDULER_cancel (plugin->address_update_task);
1905     plugin->address_update_task = NULL;
1906   }
1907   if (NULL != plugin->unix_sock.desc)
1908   {
1909     GNUNET_break (GNUNET_OK ==
1910                   GNUNET_NETWORK_socket_close (plugin->unix_sock.desc));
1911     plugin->unix_sock.desc = NULL;
1912   }
1913   GNUNET_CONTAINER_multipeermap_iterate (plugin->session_map,
1914                                          &get_session_delete_it,
1915                                          plugin);
1916   GNUNET_CONTAINER_multipeermap_destroy (plugin->session_map);
1917   GNUNET_break (0 == plugin->bytes_in_queue);
1918   GNUNET_free (plugin->unix_socket_path);
1919   GNUNET_free (plugin);
1920   GNUNET_free (api);
1921   return NULL;
1922 }
1923
1924 /* end of plugin_transport_unix.c */