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