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