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