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