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