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