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