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