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