hunting bugs
[oweals/gnunet.git] / src / transport / plugin_transport_unix.c
1 /*
2      This file is part of GNUnet
3      (C) 2010 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
30 #include "platform.h"
31 #include "gnunet_hello_lib.h"
32 #include "gnunet_connection_lib.h"
33 #include "gnunet_container_lib.h"
34 #include "gnunet_os_lib.h"
35 #include "gnunet_peerinfo_service.h"
36 #include "gnunet_protocols.h"
37 #include "gnunet_resolver_service.h"
38 #include "gnunet_server_lib.h"
39 #include "gnunet_signatures.h"
40 #include "gnunet_statistics_service.h"
41 #include "gnunet_transport_service.h"
42 #include "gnunet_transport_plugin.h"
43 #include "transport.h"
44
45 #define MAX_PROBES 20
46
47 #define LOG(kind,...) GNUNET_log_from (kind, "transport-unix",__VA_ARGS__)
48
49 /*
50  * Transport cost to peer, always 1 for UNIX (direct connection)
51  */
52 #define UNIX_DIRECT_DISTANCE 1
53
54 #define DEFAULT_NAT_PORT 0
55
56 /**
57  * How long until we give up on transmitting the welcome message?
58  */
59 #define HOSTNAME_RESOLVE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
60
61 /**
62  * Starting port for listening and sending, eventually a config value
63  */
64 #define UNIX_NAT_DEFAULT_PORT 22086
65
66 GNUNET_NETWORK_STRUCT_BEGIN
67
68 /**
69  * UNIX Message-Packet header.
70  */
71 struct UNIXMessage
72 {
73   /**
74    * Message header.
75    */
76   struct GNUNET_MessageHeader header;
77
78   /**
79    * What is the identity of the sender (GNUNET_hash of public key)
80    */
81   struct GNUNET_PeerIdentity sender;
82
83 };
84
85 struct Session
86 {
87   struct GNUNET_PeerIdentity target;
88
89   void *addr;
90   size_t addrlen;
91
92   /**
93    * Session timeout task
94    */
95   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
96
97   struct Plugin * plugin;
98 };
99
100 struct UNIXMessageWrapper
101 {
102   struct UNIXMessageWrapper *next;
103   struct UNIXMessageWrapper *prev;
104
105   struct UNIXMessage * msg;
106   size_t msgsize;
107
108   struct GNUNET_TIME_Relative timeout;
109   unsigned int priority;
110
111   struct Session *session;
112   GNUNET_TRANSPORT_TransmitContinuation cont;
113   void *cont_cls;
114 };
115
116 /* Forward definition */
117 struct Plugin;
118
119
120 /**
121  * UNIX NAT "Session"
122  */
123 struct PeerSession
124 {
125
126   /**
127    * Stored in a linked list.
128    */
129   struct PeerSession *next;
130
131   /**
132    * Pointer to the global plugin struct.
133    */
134   struct Plugin *plugin;
135
136   /**
137    * To whom are we talking to (set to our identity
138    * if we are still waiting for the welcome message)
139    */
140   struct GNUNET_PeerIdentity target;
141
142   /**
143    * Address of the other peer (either based on our 'connect'
144    * call or on our 'accept' call).
145    */
146   void *connect_addr;
147
148   /**
149    * Length of connect_addr.
150    */
151   size_t connect_alen;
152
153   /**
154    * Are we still expecting the welcome message? (GNUNET_YES/GNUNET_NO)
155    */
156   int expecting_welcome;
157
158   /**
159    * From which socket do we need to send to this peer?
160    */
161   struct GNUNET_NETWORK_Handle *sock;
162
163   /*
164    * Queue of messages for this peer, in the case that
165    * we have to await a connection...
166    */
167   struct MessageQueue *messages;
168
169 };
170
171 /**
172  * Information we keep for each of our listen sockets.
173  */
174 struct UNIX_Sock_Info
175 {
176   /**
177    * The network handle
178    */
179   struct GNUNET_NETWORK_Handle *desc;
180
181   /**
182    * The port we bound to
183    */
184   uint16_t port;
185 };
186
187
188 /**
189  * Encapsulation of all of the state of the plugin.
190  */
191 struct Plugin
192 {
193   /**
194    * Our environment.
195    */
196   struct GNUNET_TRANSPORT_PluginEnvironment *env;
197
198   /**
199    * Sessions
200    */
201   struct GNUNET_CONTAINER_MultiHashMap *session_map;
202
203   /**
204    * ID of task used to update our addresses when one expires.
205    */
206   GNUNET_SCHEDULER_TaskIdentifier address_update_task;
207
208   /**
209    * ID of select task
210    */
211   GNUNET_SCHEDULER_TaskIdentifier select_task;
212
213   /**
214    * Integer to append to unix domain socket.
215    */
216   uint16_t port;
217
218   /**
219    * FD Read set
220    */
221   struct GNUNET_NETWORK_FDSet *rs;
222
223   /**
224    * FD Write set
225    */
226   struct GNUNET_NETWORK_FDSet *ws;
227
228   int with_ws;
229
230   /**
231    * socket that we transmit all data with
232    */
233   struct UNIX_Sock_Info unix_sock;
234
235   /**
236    * Path of our unix domain socket (/tmp/unix-plugin-PORT)
237    */
238   char *unix_socket_path;
239
240   struct UNIXMessageWrapper *msg_head;
241   struct UNIXMessageWrapper *msg_tail;
242
243   /**
244    * ATS network
245    */
246   struct GNUNET_ATS_Information ats_network;
247
248   unsigned int bytes_in_queue;
249   unsigned int bytes_in_sent;
250   unsigned int bytes_in_recv;
251   unsigned int bytes_discarded;
252 };
253
254 /**
255  * Start session timeout
256  */
257 static void
258 start_session_timeout (struct Session *s);
259
260 /**
261  * Increment session timeout due to activity
262  */
263 static void
264 reschedule_session_timeout (struct Session *s);
265
266 /**
267  * Cancel timeout
268  */
269 static void
270 stop_session_timeout (struct Session *s);
271
272
273 static void
274 unix_plugin_select (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
275
276
277 static void
278 reschedule_select (struct Plugin * plugin)
279 {
280
281   if (plugin->select_task != GNUNET_SCHEDULER_NO_TASK)
282   {
283     GNUNET_SCHEDULER_cancel (plugin->select_task);
284     plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
285   }
286
287   if (NULL != plugin->msg_head)
288   {
289     plugin->select_task =
290       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
291                                    GNUNET_TIME_UNIT_FOREVER_REL,
292                                    plugin->rs,
293                                    plugin->ws,
294                                    &unix_plugin_select, plugin);
295     plugin->with_ws = GNUNET_YES;
296   }
297   else
298   {
299     plugin->select_task =
300       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
301                                    GNUNET_TIME_UNIT_FOREVER_REL,
302                                    plugin->rs,
303                                    NULL,
304                                    &unix_plugin_select, plugin);
305     plugin->with_ws = GNUNET_NO;
306   }
307 }
308
309 struct LookupCtx
310 {
311   struct Session *s;
312   const struct sockaddr_un *addr;
313 };
314
315 int lookup_session_it (void *cls,
316                        const struct GNUNET_HashCode * key,
317                        void *value)
318 {
319   struct LookupCtx *lctx = cls;
320   struct Session *t = value;
321
322   if (0 == strcmp (t->addr, lctx->addr->sun_path))
323   {
324     lctx->s = t;
325     return GNUNET_NO;
326   }
327   return GNUNET_YES;
328 }
329
330
331 static struct Session *
332 lookup_session (struct Plugin *plugin, struct GNUNET_PeerIdentity *sender, const struct sockaddr_un *addr)
333 {
334   struct LookupCtx lctx;
335
336   GNUNET_assert (NULL != plugin);
337   GNUNET_assert (NULL != sender);
338   GNUNET_assert (NULL != addr);
339
340   lctx.s = NULL;
341   lctx.addr = addr;
342
343   GNUNET_CONTAINER_multihashmap_get_multiple (plugin->session_map, &sender->hashPubKey, &lookup_session_it, &lctx);
344
345   return lctx.s;
346 }
347
348 /**
349  * Functions with this signature are called whenever we need
350  * to close a session due to a disconnect or failure to
351  * establish a connection.
352  *
353  * @param s session to close down
354  */
355 static void
356 disconnect_session (struct Session *s)
357 {
358   struct UNIXMessageWrapper *msgw;
359   struct UNIXMessageWrapper *next;
360   struct Plugin * plugin = s->plugin;
361   int removed;
362   GNUNET_assert (plugin != NULL);
363   GNUNET_assert (s != NULL);
364
365   LOG (GNUNET_ERROR_TYPE_DEBUG, "Disconnecting session for peer `%s' `%s' \n", GNUNET_i2s (&s->target), s->addr);
366   stop_session_timeout (s);
367   plugin->env->session_end (plugin->env->cls, &s->target, s);
368
369   msgw = plugin->msg_head;
370   removed = GNUNET_NO;
371   next = plugin->msg_head;
372   while (NULL != next)
373   {
374     msgw = next;
375     next = msgw->next;
376     if (msgw->session != s)
377       continue;
378     GNUNET_CONTAINER_DLL_remove (plugin->msg_head, plugin->msg_tail, msgw);
379     if (NULL != msgw->cont)
380       msgw->cont (msgw->cont_cls,  &msgw->session->target, GNUNET_SYSERR);
381     GNUNET_free (msgw->msg);
382     GNUNET_free (msgw);
383     removed = GNUNET_YES;    
384   }
385   if ((GNUNET_YES == removed) && (NULL == plugin->msg_head))
386     reschedule_select (plugin);
387
388   GNUNET_assert (GNUNET_YES ==
389                  GNUNET_CONTAINER_multihashmap_remove(plugin->session_map, &s->target.hashPubKey, s));
390
391   GNUNET_STATISTICS_set(plugin->env->stats,
392                         "# UNIX sessions active",
393                         GNUNET_CONTAINER_multihashmap_size(plugin->session_map),
394                         GNUNET_NO);
395
396   GNUNET_free (s);
397 }
398
399 static int
400 get_session_delete_it (void *cls, const struct GNUNET_HashCode * key, void *value)
401 {
402   struct Session *s = value;
403   disconnect_session (s);
404   return GNUNET_YES;
405 }
406
407
408 /**
409  * Disconnect from a remote node.  Clean up session if we have one for this peer
410  *
411  * @param cls closure for this call (should be handle to Plugin)
412  * @param target the peeridentity of the peer to disconnect
413  * @return GNUNET_OK on success, GNUNET_SYSERR if the operation failed
414  */
415 static void
416 unix_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
417 {
418   struct Plugin *plugin = cls;
419   GNUNET_assert (plugin != NULL);
420
421   GNUNET_CONTAINER_multihashmap_get_multiple (plugin->session_map, &target->hashPubKey, &get_session_delete_it, plugin);
422   return;
423 }
424
425 /**
426  * Shutdown the server process (stop receiving inbound traffic). Maybe
427  * restarted later!
428  *
429  * @param cls Handle to the plugin for this transport
430  *
431  * @return returns the number of sockets successfully closed,
432  *         should equal the number of sockets successfully opened
433  */
434 static int
435 unix_transport_server_stop (void *cls)
436 {
437   struct Plugin *plugin = cls;
438
439   struct UNIXMessageWrapper * msgw = plugin->msg_head;
440
441   while (NULL != (msgw = plugin->msg_head))
442   {
443     GNUNET_CONTAINER_DLL_remove (plugin->msg_head, plugin->msg_tail, msgw);
444     if (msgw->cont != NULL)
445       msgw->cont (msgw->cont_cls,  &msgw->session->target, GNUNET_SYSERR);
446     GNUNET_free (msgw->msg);
447     GNUNET_free (msgw);
448   }
449
450   if (plugin->select_task != GNUNET_SCHEDULER_NO_TASK)
451   {
452     GNUNET_SCHEDULER_cancel (plugin->select_task);
453     plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
454   }
455
456   if (NULL != plugin->unix_sock.desc)
457   {
458     GNUNET_break (GNUNET_OK ==
459                   GNUNET_NETWORK_socket_close (plugin->unix_sock.desc));
460     plugin->unix_sock.desc = NULL;
461     plugin->with_ws = GNUNET_NO;
462   }
463   return GNUNET_OK;
464 }
465
466
467 /**
468  * Actually send out the message, assume we've got the address and
469  * send_handle squared away!
470  *
471  * @param cls closure
472  * @param send_handle which handle to send message on
473  * @param target who should receive this message (ignored by UNIX)
474  * @param msgbuf one or more GNUNET_MessageHeader(s) strung together
475  * @param msgbuf_size the size of the msgbuf to send
476  * @param priority how important is the message (ignored by UNIX)
477  * @param timeout when should we time out (give up) if we can not transmit?
478  * @param addr the addr to send the message to, needs to be a sockaddr for us
479  * @param addrlen the len of addr
480  * @param cont continuation to call once the message has
481  *        been transmitted (or if the transport is ready
482  *        for the next transmission call; or if the
483  *        peer disconnected...)
484  * @param cont_cls closure for cont
485  *
486  * @return the number of bytes written, -1 on errors
487  */
488 static ssize_t
489 unix_real_send (void *cls,
490                 struct GNUNET_NETWORK_Handle *send_handle,
491                 const struct GNUNET_PeerIdentity *target, const char *msgbuf,
492                 size_t msgbuf_size, unsigned int priority,
493                 struct GNUNET_TIME_Relative timeout, const void *addr,
494                 size_t addrlen, GNUNET_TRANSPORT_TransmitContinuation cont,
495                 void *cont_cls)
496 {
497   struct Plugin *plugin = cls;
498   ssize_t sent;
499   const void *sb;
500   size_t sbs;
501   struct sockaddr_un un;
502   size_t slen;
503
504   GNUNET_assert (NULL != plugin);
505
506   if (send_handle == NULL)
507   {
508     /* We do not have a send handle */
509     GNUNET_break (0);
510     if (cont != NULL)
511       cont (cont_cls, target, GNUNET_SYSERR);
512     return -1;
513   }
514   if ((addr == NULL) || (addrlen == 0))
515   {
516     /* Can never send if we don't have an address */
517     GNUNET_break (0);
518     if (cont != NULL)
519       cont (cont_cls, target, GNUNET_SYSERR);
520     return -1;
521   }
522
523   /* Prepare address */
524   memset (&un, 0, sizeof (un));
525   un.sun_family = AF_UNIX;
526   slen = strlen (addr) + 1;
527   if (slen >= sizeof (un.sun_path))
528     slen = sizeof (un.sun_path) - 1;
529   GNUNET_assert (slen < sizeof (un.sun_path));
530   memcpy (un.sun_path, addr, slen);
531   un.sun_path[slen] = '\0';
532   slen = sizeof (struct sockaddr_un);
533 #if LINUX
534   un.sun_path[0] = '\0';
535 #endif
536 #if HAVE_SOCKADDR_IN_SIN_LEN
537   un.sun_len = (u_char) slen;
538 #endif
539   sb = (struct sockaddr *) &un;
540   sbs = slen;
541
542   /* Send the data */
543   sent = 0;
544   sent = GNUNET_NETWORK_socket_sendto (send_handle, msgbuf, msgbuf_size, sb, sbs);
545
546   if ((GNUNET_SYSERR == sent) && ((errno == EAGAIN) || (errno == ENOBUFS)))
547   {
548     /* We have to retry later: retry */
549     return 0;
550   }
551
552   if ((GNUNET_SYSERR == sent) && (errno == EMSGSIZE))
553   {
554     socklen_t size = 0;
555     socklen_t len = sizeof (size);
556
557     GNUNET_NETWORK_socket_getsockopt ((struct GNUNET_NETWORK_Handle *)
558                                       send_handle, SOL_SOCKET, SO_SNDBUF, &size,
559                                       &len);
560
561     if (size < msgbuf_size)
562     {
563       LOG (GNUNET_ERROR_TYPE_DEBUG,
564                   "Trying to increase socket buffer size from %i to %i for message size %i\n",
565                   size,
566                   ((msgbuf_size / 1000) + 2) * 1000,
567                   msgbuf_size);
568       size = ((msgbuf_size / 1000) + 2) * 1000;
569       if (GNUNET_NETWORK_socket_setsockopt
570           ((struct GNUNET_NETWORK_Handle *) send_handle, SOL_SOCKET, SO_SNDBUF,
571            &size, sizeof (size)) == GNUNET_OK)
572       {
573         /* Increased buffer size, retry sending */
574         return 0;
575       }
576       else
577       {
578         /* Could not increase buffer size: error, no retry */
579         GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "setsockopt");
580         return -1;
581       }
582     }
583     else
584     {
585       /* Buffer is bigger than message:  error, no retry
586        * This should never happen!*/
587       GNUNET_break (0);
588       return -1;
589     }
590   }
591
592   LOG (GNUNET_ERROR_TYPE_DEBUG,
593               "UNIX transmit %u-byte message to %s (%d: %s)\n",
594               (unsigned int) msgbuf_size, GNUNET_a2s (sb, sbs), (int) sent,
595               (sent < 0) ? STRERROR (errno) : "ok");
596
597   /* Calling continuation */
598   if (cont != NULL)
599   {
600     if (sent == GNUNET_SYSERR)
601       cont (cont_cls, target, GNUNET_SYSERR);
602     if (sent > 0)
603       cont (cont_cls, target, GNUNET_OK);
604   }
605
606   /* return number of bytes successfully sent */
607   if (sent > 0)
608     return sent;
609   if (sent == 0)
610   {
611     /* That should never happen */
612     GNUNET_break (0);
613     return -1;
614   }
615   /* failed and retry: return 0 */
616   if (GNUNET_SYSERR == sent)
617     return 0;
618   /* default */
619   return -1;
620 }
621
622 struct gsi_ctx
623 {
624   char *address;
625   size_t addrlen;
626   struct Session *res;
627 };
628
629
630 static int
631 get_session_it (void *cls, const struct GNUNET_HashCode * key, void *value)
632 {
633   struct gsi_ctx *gsi = cls;
634   struct Session *s = value;
635
636   LOG (GNUNET_ERROR_TYPE_DEBUG, "Comparing session %s %s\n", gsi->address, s->addr);
637   if ((gsi->addrlen == s->addrlen) &&
638       (0 == memcmp (gsi->address, s->addr, s->addrlen)))
639   {
640     gsi->res = s;
641     return GNUNET_NO;
642   }
643   return GNUNET_YES;
644 }
645
646 /**
647  * Creates a new outbound session the transport service will use to send data to the
648  * peer
649  *
650  * @param cls the plugin
651  * @param address the address
652  * @return the session or NULL of max connections exceeded
653  */
654 static struct Session *
655 unix_plugin_get_session (void *cls,
656                   const struct GNUNET_HELLO_Address *address)
657 {
658   struct Session * s = NULL;
659   struct Plugin *plugin = cls;
660   struct gsi_ctx gsi;
661
662   /* Checks */
663   GNUNET_assert (plugin != NULL);
664   GNUNET_assert (address != NULL);
665
666   /* Check if already existing */
667   gsi.address = (char *) address->address;
668   gsi.addrlen = address->address_length;
669   gsi.res = NULL;
670   GNUNET_CONTAINER_multihashmap_get_multiple (plugin->session_map, &address->peer.hashPubKey, &get_session_it, &gsi);
671   if (gsi.res != NULL)
672   {
673     LOG (GNUNET_ERROR_TYPE_DEBUG, "Found existing session\n");
674     return gsi.res;
675   }
676
677   /* Create a new session */
678   s = GNUNET_malloc (sizeof (struct Session) + address->address_length);
679   s->addr = &s[1];
680   s->addrlen = address->address_length;
681   s->plugin = plugin;
682   memcpy(s->addr, address->address, s->addrlen);
683   memcpy(&s->target, &address->peer, sizeof (struct GNUNET_PeerIdentity));
684
685   start_session_timeout (s);
686
687   GNUNET_CONTAINER_multihashmap_put (plugin->session_map,
688       &address->peer.hashPubKey, s,
689       GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
690
691   GNUNET_STATISTICS_set(plugin->env->stats,
692                         "# UNIX sessions active",
693                         GNUNET_CONTAINER_multihashmap_size(plugin->session_map),
694                         GNUNET_NO);
695   LOG (GNUNET_ERROR_TYPE_DEBUG, "Creating new session\n");
696   return s;
697 }
698
699 /*
700  * @param cls the plugin handle
701  * @param tc the scheduling context (for rescheduling this function again)
702  *
703  * We have been notified that our writeset has something to read.  We don't
704  * know which socket needs to be read, so we have to check each one
705  * Then reschedule this function to be called again once more is available.
706  *
707  */
708 static void
709 unix_plugin_select (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
710
711 /**
712  * Function that can be used by the transport service to transmit
713  * a message using the plugin.   Note that in the case of a
714  * peer disconnecting, the continuation MUST be called
715  * prior to the disconnect notification itself.  This function
716  * will be called with this peer's HELLO message to initiate
717  * a fresh connection to another peer.
718  *
719  * @param cls closure
720  * @param session which session must be used
721  * @param msgbuf the message to transmit
722  * @param msgbuf_size number of bytes in 'msgbuf'
723  * @param priority how important is the message (most plugins will
724  *                 ignore message priority and just FIFO)
725  * @param to how long to wait at most for the transmission (does not
726  *                require plugins to discard the message after the timeout,
727  *                just advisory for the desired delay; most plugins will ignore
728  *                this as well)
729  * @param cont continuation to call once the message has
730  *        been transmitted (or if the transport is ready
731  *        for the next transmission call; or if the
732  *        peer disconnected...); can be NULL
733  * @param cont_cls closure for cont
734  * @return number of bytes used (on the physical network, with overheads);
735  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
736  *         and does NOT mean that the message was not transmitted (DV)
737  */
738 static ssize_t
739 unix_plugin_send (void *cls,
740                   struct Session *session,
741                   const char *msgbuf, size_t msgbuf_size,
742                   unsigned int priority,
743                   struct GNUNET_TIME_Relative to,
744                   GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
745 {
746   struct Plugin *plugin = cls;
747   struct UNIXMessageWrapper *wrapper;
748   struct UNIXMessage *message;
749   int ssize;
750   
751   GNUNET_assert (plugin != NULL);
752   GNUNET_assert (session != NULL);
753
754   if (GNUNET_OK != GNUNET_CONTAINER_multihashmap_contains_value(plugin->session_map,
755       &session->target.hashPubKey, session))
756   {
757     LOG (GNUNET_ERROR_TYPE_ERROR, "Invalid session for peer `%s' `%s'\n",
758                 GNUNET_i2s (&session->target),
759                 (char *) session->addr);
760     GNUNET_break (0);
761
762     return GNUNET_SYSERR;
763   }
764   LOG (GNUNET_ERROR_TYPE_DEBUG, "Sending %u bytes with session for peer `%s' `%s'\n",
765                 msgbuf_size,
766         GNUNET_i2s (&session->target),
767         (char *) session->addr);
768
769   ssize = sizeof (struct UNIXMessage) + msgbuf_size;
770   message = GNUNET_malloc (sizeof (struct UNIXMessage) + msgbuf_size);
771   message->header.size = htons (ssize);
772   message->header.type = htons (0);
773   memcpy (&message->sender, plugin->env->my_identity,
774           sizeof (struct GNUNET_PeerIdentity));
775   memcpy (&message[1], msgbuf, msgbuf_size);
776
777   reschedule_session_timeout (session);
778
779   wrapper = GNUNET_malloc (sizeof (struct UNIXMessageWrapper));
780   wrapper->msg = message;
781   wrapper->msgsize = ssize;
782   wrapper->priority = priority;
783   wrapper->timeout = to;
784   wrapper->cont = cont;
785   wrapper->cont_cls = cont_cls;
786   wrapper->session = session;
787
788   GNUNET_CONTAINER_DLL_insert(plugin->msg_head, plugin->msg_tail, wrapper);
789
790   plugin->bytes_in_queue += ssize;
791   GNUNET_STATISTICS_set (plugin->env->stats,"# UNIX bytes in send queue",
792       plugin->bytes_in_queue, GNUNET_NO);
793
794   LOG (GNUNET_ERROR_TYPE_DEBUG, "Sent %d bytes to `%s'\n", ssize,
795               (char *) session->addr);
796   if (plugin->with_ws == GNUNET_NO)
797   {
798     reschedule_select (plugin);
799   }
800
801   return ssize;
802 }
803
804
805 /**
806  * Demultiplexer for UNIX messages
807  *
808  * @param plugin the main plugin for this transport
809  * @param sender from which peer the message was received
810  * @param currhdr pointer to the header of the message
811  * @param un the address from which the message was received
812  * @param fromlen the length of the address
813  */
814 static void
815 unix_demultiplexer (struct Plugin *plugin, struct GNUNET_PeerIdentity *sender,
816                     const struct GNUNET_MessageHeader *currhdr,
817                     const struct sockaddr_un *un, size_t fromlen)
818 {
819   struct GNUNET_ATS_Information ats[2];
820   struct Session *s = NULL;
821   struct GNUNET_HELLO_Address * addr;
822
823   ats[0].type = htonl (GNUNET_ATS_QUALITY_NET_DISTANCE);
824   ats[0].value = htonl (UNIX_DIRECT_DISTANCE);
825   ats[1] = plugin->ats_network;
826   GNUNET_break (ntohl(plugin->ats_network.value) != GNUNET_ATS_NET_UNSPECIFIED);
827
828   GNUNET_assert (fromlen >= sizeof (struct sockaddr_un));
829
830   LOG (GNUNET_ERROR_TYPE_DEBUG, "Received message from %s\n",
831               un->sun_path);
832
833   plugin->bytes_in_recv += ntohs(currhdr->size);
834   GNUNET_STATISTICS_set (plugin->env->stats,"# UNIX bytes received",
835       plugin->bytes_in_recv, GNUNET_NO);
836
837   addr = GNUNET_HELLO_address_allocate(sender, "unix", un->sun_path, strlen (un->sun_path) + 1);
838   s = lookup_session (plugin, sender, un);
839   if (NULL == s)
840     s = unix_plugin_get_session (plugin, addr);
841   reschedule_session_timeout (s);
842
843   plugin->env->receive (plugin->env->cls, sender, currhdr,
844                         (const struct GNUNET_ATS_Information *) &ats, 2,
845                         s, un->sun_path, strlen (un->sun_path) + 1);
846   GNUNET_free (addr);
847 }
848
849
850 static void
851 unix_plugin_select_read (struct Plugin * plugin)
852 {
853   char buf[65536] GNUNET_ALIGN;
854   struct UNIXMessage *msg;
855   struct GNUNET_PeerIdentity sender;
856   struct sockaddr_un un;
857   socklen_t addrlen;
858   ssize_t ret;
859   int offset;
860   int tsize;
861   char *msgbuf;
862   const struct GNUNET_MessageHeader *currhdr;
863   uint16_t csize;
864
865   addrlen = sizeof (un);
866   memset (&un, 0, sizeof (un));
867
868   ret =
869       GNUNET_NETWORK_socket_recvfrom (plugin->unix_sock.desc, buf, sizeof (buf),
870                                       (struct sockaddr *) &un, &addrlen);
871
872   if ((GNUNET_SYSERR == ret) && ((errno == EAGAIN) || (errno == ENOBUFS)))
873     return;
874
875   if (ret == GNUNET_SYSERR)
876   {
877     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "recvfrom");
878     return;
879   }
880   else
881   {
882 #if LINUX
883     un.sun_path[0] = '/';
884 #endif
885     LOG (GNUNET_ERROR_TYPE_DEBUG, "Read %d bytes from socket %s\n", ret,
886                 &un.sun_path[0]);
887   }
888
889   GNUNET_assert (AF_UNIX == (un.sun_family));
890
891   msg = (struct UNIXMessage *) buf;
892   csize = ntohs (msg->header.size);
893   if ((csize < sizeof (struct UNIXMessage)) || (csize > ret))
894   {
895     GNUNET_break_op (0);
896     return;
897   }
898   msgbuf = (char *) &msg[1];
899   memcpy (&sender, &msg->sender, sizeof (struct GNUNET_PeerIdentity));
900   offset = 0;
901   tsize = csize - sizeof (struct UNIXMessage);
902   while (offset + sizeof (struct GNUNET_MessageHeader) <= tsize)
903   {
904     currhdr = (struct GNUNET_MessageHeader *) &msgbuf[offset];
905     csize = ntohs (currhdr->size);
906     if ((csize < sizeof (struct GNUNET_MessageHeader)) ||
907         (csize > tsize - offset))
908     {
909       GNUNET_break_op (0);
910       break;
911     }
912
913     unix_demultiplexer (plugin, &sender, currhdr, &un, sizeof (un));
914     offset += csize;
915   }
916 }
917
918
919 static void
920 unix_plugin_select_write (struct Plugin * plugin)
921 {
922   static int retry_counter;
923   int sent = 0;
924   struct UNIXMessageWrapper * msgw = plugin->msg_head;
925
926   sent = unix_real_send (plugin,
927                          plugin->unix_sock.desc,
928                          &msgw->session->target,
929                          (const char *) msgw->msg,
930                          msgw->msgsize,
931                          msgw->priority,
932                          msgw->timeout,
933                          msgw->session->addr,
934                          msgw->session->addrlen,
935                          msgw->cont, msgw->cont_cls);
936
937   if (sent == 0)
938   {
939     /* failed and retry */
940     retry_counter++;
941     GNUNET_STATISTICS_set (plugin->env->stats,"# UNIX retry attempt",
942         retry_counter, GNUNET_NO);
943     return;
944   }
945
946   if (retry_counter > 0 )
947   {
948     /* no retry: reset counter */
949     retry_counter = 0;
950     GNUNET_STATISTICS_set (plugin->env->stats,"# UNIX retry attempt",
951         retry_counter, GNUNET_NO);
952   }
953
954   if (sent == -1)
955   {
956     /* failed and no retry */
957     GNUNET_CONTAINER_DLL_remove(plugin->msg_head, plugin->msg_tail, msgw);
958
959     GNUNET_assert (plugin->bytes_in_queue >= msgw->msgsize);
960     plugin->bytes_in_queue -= msgw->msgsize;
961     GNUNET_STATISTICS_set (plugin->env->stats,"# UNIX bytes in send queue",
962         plugin->bytes_in_queue, GNUNET_NO);
963     plugin->bytes_discarded += msgw->msgsize;
964     GNUNET_STATISTICS_set (plugin->env->stats,"# UNIX bytes discarded",
965         plugin->bytes_discarded, GNUNET_NO);
966
967     GNUNET_free (msgw->msg);
968     GNUNET_free (msgw);
969     return;
970   }
971
972   if (sent > 0)
973   {
974     /* successfully sent bytes */
975     GNUNET_CONTAINER_DLL_remove(plugin->msg_head, plugin->msg_tail, msgw);
976
977     GNUNET_assert (plugin->bytes_in_queue >= msgw->msgsize);
978     plugin->bytes_in_queue -= msgw->msgsize;
979     GNUNET_STATISTICS_set (plugin->env->stats,"# UNIX bytes in send queue",
980         plugin->bytes_in_queue, GNUNET_NO);
981     plugin->bytes_in_sent += msgw->msgsize;
982     GNUNET_STATISTICS_set (plugin->env->stats,"# UNIX bytes sent",
983         plugin->bytes_in_sent, GNUNET_NO);
984
985     GNUNET_free (msgw->msg);
986     GNUNET_free (msgw);
987     return;
988   }
989
990 }
991
992
993 /**
994  * We have been notified that our writeset has something to read.  We don't
995  * know which socket needs to be read, so we have to check each one
996  * Then reschedule this function to be called again once more is available.
997  *
998  * @param cls the plugin handle
999  * @param tc the scheduling context (for rescheduling this function again)
1000  */
1001 static void
1002 unix_plugin_select (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1003 {
1004   struct Plugin *plugin = cls;
1005
1006   plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
1007   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
1008     return;
1009
1010   if ((tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY) != 0)
1011   {
1012     /* Ready to send data */
1013     GNUNET_assert (GNUNET_NETWORK_fdset_isset
1014                    (tc->write_ready, plugin->unix_sock.desc));
1015     if (plugin->msg_head != NULL)
1016       unix_plugin_select_write (plugin);
1017   }
1018
1019   if ((tc->reason & GNUNET_SCHEDULER_REASON_READ_READY) != 0)
1020   {
1021     /* Ready to receive data */
1022     GNUNET_assert (GNUNET_NETWORK_fdset_isset
1023                    (tc->read_ready, plugin->unix_sock.desc));
1024     unix_plugin_select_read (plugin);
1025   }
1026
1027   reschedule_select (plugin);
1028 }
1029
1030
1031 /**
1032  * Create a slew of UNIX sockets.  If possible, use IPv6 and IPv4.
1033  *
1034  * @param cls closure for server start, should be a struct Plugin *
1035  * @return number of sockets created or GNUNET_SYSERR on error
1036  */
1037 static int
1038 unix_transport_server_start (void *cls)
1039 {
1040   struct Plugin *plugin = cls;
1041   struct sockaddr *serverAddr;
1042   socklen_t addrlen;
1043   struct sockaddr_un un;
1044   size_t slen;
1045
1046   memset (&un, 0, sizeof (un));
1047   un.sun_family = AF_UNIX;
1048   slen = strlen (plugin->unix_socket_path) + 1;
1049   if (slen >= sizeof (un.sun_path))
1050     slen = sizeof (un.sun_path) - 1;
1051
1052   memcpy (un.sun_path, plugin->unix_socket_path, slen);
1053   un.sun_path[slen] = '\0';
1054   slen = sizeof (struct sockaddr_un);
1055 #if HAVE_SOCKADDR_IN_SIN_LEN
1056   un.sun_len = (u_char) slen;
1057 #endif
1058
1059   serverAddr = (struct sockaddr *) &un;
1060   addrlen = slen;
1061 #if LINUX
1062   un.sun_path[0] = '\0';
1063 #endif
1064   plugin->ats_network = plugin->env->get_address_type (plugin->env->cls, serverAddr, addrlen);
1065   plugin->unix_sock.desc =
1066       GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_DGRAM, 0);
1067   if (NULL == plugin->unix_sock.desc)
1068   {
1069     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
1070     return GNUNET_SYSERR;
1071   }
1072   if (GNUNET_NETWORK_socket_bind (plugin->unix_sock.desc, serverAddr, addrlen)
1073       != GNUNET_OK)
1074   {
1075     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
1076     GNUNET_NETWORK_socket_close (plugin->unix_sock.desc);
1077     plugin->unix_sock.desc = NULL;
1078     return GNUNET_SYSERR;
1079   }
1080   LOG (GNUNET_ERROR_TYPE_DEBUG, "Bound to `%s'\n", plugin->unix_socket_path);
1081   plugin->rs = GNUNET_NETWORK_fdset_create ();
1082   plugin->ws = GNUNET_NETWORK_fdset_create ();
1083   GNUNET_NETWORK_fdset_zero (plugin->rs);
1084   GNUNET_NETWORK_fdset_zero (plugin->ws);
1085   GNUNET_NETWORK_fdset_set (plugin->rs, plugin->unix_sock.desc);
1086   GNUNET_NETWORK_fdset_set (plugin->ws, plugin->unix_sock.desc);
1087
1088   reschedule_select (plugin);
1089
1090   return 1;
1091 }
1092
1093
1094 /**
1095  * Function that will be called to check if a binary address for this
1096  * plugin is well-formed and corresponds to an address for THIS peer
1097  * (as per our configuration).  Naturally, if absolutely necessary,
1098  * plugins can be a bit conservative in their answer, but in general
1099  * plugins should make sure that the address does not redirect
1100  * traffic to a 3rd party that might try to man-in-the-middle our
1101  * traffic.
1102  *
1103  * @param cls closure, should be our handle to the Plugin
1104  * @param addr pointer to the address
1105  * @param addrlen length of addr
1106  * @return GNUNET_OK if this is a plausible address for this peer
1107  *         and transport, GNUNET_SYSERR if not
1108  *
1109  */
1110 static int
1111 unix_check_address (void *cls, const void *addr, size_t addrlen)
1112 {
1113   LOG (GNUNET_ERROR_TYPE_DEBUG,
1114               "Informing transport service about my address `%s'\n",
1115               (char *) addr);
1116   return GNUNET_OK;
1117 }
1118
1119
1120 /**
1121  * Convert the transports address to a nice, human-readable
1122  * format.
1123  *
1124  * @param cls closure
1125  * @param type name of the transport that generated the address
1126  * @param addr one of the addresses of the host, NULL for the last address
1127  *        the specific address format depends on the transport
1128  * @param addrlen length of the address
1129  * @param numeric should (IP) addresses be displayed in numeric form?
1130  * @param timeout after how long should we give up?
1131  * @param asc function to call on each string
1132  * @param asc_cls closure for asc
1133  */
1134 static void
1135 unix_plugin_address_pretty_printer (void *cls, const char *type,
1136                                     const void *addr, size_t addrlen,
1137                                     int numeric,
1138                                     struct GNUNET_TIME_Relative timeout,
1139                                     GNUNET_TRANSPORT_AddressStringCallback asc,
1140                                     void *asc_cls)
1141 {
1142   if ((NULL != addr) && (addrlen > 0))
1143   {
1144     asc (asc_cls, (const char *) addr);
1145   }
1146   else
1147   {
1148     GNUNET_break (0);
1149     asc (asc_cls, "<invalid UNIX address>");
1150   }
1151   asc (asc_cls, NULL);
1152 }
1153
1154
1155 /**
1156  * Function called to convert a string address to
1157  * a binary address.
1158  *
1159  * @param cls closure ('struct Plugin*')
1160  * @param addr string address
1161  * @param addrlen length of the address (strlen(addr) + '\0')
1162  * @param buf location to store the buffer
1163  *        If the function returns GNUNET_SYSERR, its contents are undefined.
1164  * @param added length of created address
1165  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
1166  */
1167 static int
1168 unix_string_to_address (void *cls, const char *addr, uint16_t addrlen,
1169     void **buf, size_t *added)
1170 {
1171   if ((NULL == addr) || (0 == addrlen))
1172   {
1173     GNUNET_break (0);
1174     return GNUNET_SYSERR;
1175   }
1176
1177   if ('\0' != addr[addrlen - 1])
1178   {
1179     GNUNET_break (0);
1180     return GNUNET_SYSERR;
1181   }
1182
1183   if (strlen (addr) != addrlen - 1)
1184   {
1185     GNUNET_break (0);
1186     return GNUNET_SYSERR;
1187   }
1188
1189   (*buf) = strdup (addr);
1190   (*added) = strlen (addr) + 1;
1191   return GNUNET_OK;
1192 }
1193
1194
1195 /**
1196  * Function called for a quick conversion of the binary address to
1197  * a numeric address.  Note that the caller must not free the
1198  * address and that the next call to this function is allowed
1199  * to override the address again.
1200  *
1201  * @param cls closure
1202  * @param addr binary address
1203  * @param addrlen length of the address
1204  * @return string representing the same address
1205  */
1206 static const char *
1207 unix_address_to_string (void *cls, const void *addr, size_t addrlen)
1208 {
1209   if ((addr != NULL) && (addrlen > 0))
1210     return (const char *) addr;
1211   return NULL;
1212 }
1213
1214
1215 /**
1216  * Notify transport service about address
1217  *
1218  * @param cls the plugin
1219  * @param tc unused
1220  */
1221 static void
1222 address_notification (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1223 {
1224   struct Plugin *plugin = cls;
1225
1226   plugin->env->notify_address (plugin->env->cls, GNUNET_YES,
1227                                plugin->unix_socket_path,
1228                                strlen (plugin->unix_socket_path) + 1,
1229                                "unix");
1230 }
1231
1232
1233 /**
1234  * Session was idle, so disconnect it
1235  */
1236 static void
1237 session_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1238 {
1239   GNUNET_assert (NULL != cls);
1240   struct Session *s = cls;
1241
1242   s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1243   LOG (GNUNET_ERROR_TYPE_DEBUG,
1244               "Session %p was idle for %llu ms, disconnecting\n",
1245               s, (unsigned long long) GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value);
1246   /* call session destroy function */
1247   disconnect_session(s);
1248 }
1249
1250
1251 /**
1252  * Start session timeout
1253  */
1254 static void
1255 start_session_timeout (struct Session *s)
1256 {
1257   GNUNET_assert (NULL != s);
1258   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == s->timeout_task);
1259   s->timeout_task =  GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1260                                                    &session_timeout,
1261                                                    s);
1262   LOG (GNUNET_ERROR_TYPE_DEBUG,
1263               "Timeout for session %p set to %llu ms\n",
1264               s,  (unsigned long long) GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value);
1265 }
1266
1267
1268 /**
1269  * Increment session timeout due to activity
1270  */
1271 static void
1272 reschedule_session_timeout (struct Session *s)
1273 {
1274   GNUNET_assert (NULL != s);
1275   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != s->timeout_task);
1276
1277   GNUNET_SCHEDULER_cancel (s->timeout_task);
1278   s->timeout_task =  GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1279                                                    &session_timeout,
1280                                                    s);
1281   LOG (GNUNET_ERROR_TYPE_DEBUG,
1282               "Timeout rescheduled for session %p set to %llu ms\n",
1283               s, (unsigned long long) GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value);
1284 }
1285
1286
1287 /**
1288  * Cancel timeout
1289  */
1290 static void
1291 stop_session_timeout (struct Session *s)
1292 {
1293   GNUNET_assert (NULL != s);
1294
1295   if (GNUNET_SCHEDULER_NO_TASK != s->timeout_task)
1296   {
1297     GNUNET_SCHEDULER_cancel (s->timeout_task);
1298     s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1299     LOG (GNUNET_ERROR_TYPE_DEBUG,
1300                 "Timeout stopped for session %p canceled\n",
1301                 s, (unsigned long long) GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value);
1302   }
1303 }
1304
1305 /**
1306  * The exported method. Makes the core api available via a global and
1307  * returns the unix transport API.
1308  */
1309 void *
1310 libgnunet_plugin_transport_unix_init (void *cls)
1311 {
1312   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1313   unsigned long long port;
1314   struct GNUNET_TRANSPORT_PluginFunctions *api;
1315   struct Plugin *plugin;
1316   int sockets_created;
1317
1318   if (NULL == env->receive)
1319   {
1320     /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
1321        initialze the plugin or the API */
1322     api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1323     api->cls = NULL;
1324     api->address_pretty_printer = &unix_plugin_address_pretty_printer;
1325     api->address_to_string = &unix_address_to_string;
1326     api->string_to_address = &unix_string_to_address;
1327     return api;
1328   }
1329   GNUNET_assert( NULL != env->stats);
1330
1331   if (GNUNET_OK !=
1332       GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-unix", "PORT",
1333                                              &port))
1334     port = UNIX_NAT_DEFAULT_PORT;
1335   plugin = GNUNET_malloc (sizeof (struct Plugin));
1336   plugin->port = port;
1337   plugin->env = env;
1338   GNUNET_asprintf (&plugin->unix_socket_path, "/tmp/unix-plugin-sock.%d",
1339                    plugin->port);
1340
1341   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1342   api->cls = plugin;
1343
1344   api->get_session = &unix_plugin_get_session;
1345   api->send = &unix_plugin_send;
1346   api->disconnect = &unix_disconnect;
1347   api->address_pretty_printer = &unix_plugin_address_pretty_printer;
1348   api->address_to_string = &unix_address_to_string;
1349   api->check_address = &unix_check_address;
1350   api->string_to_address = &unix_string_to_address;
1351   sockets_created = unix_transport_server_start (plugin);
1352   if (sockets_created == 0)
1353     LOG (GNUNET_ERROR_TYPE_WARNING, _("Failed to open UNIX sockets\n"));
1354
1355   plugin->session_map = GNUNET_CONTAINER_multihashmap_create(10);
1356
1357   GNUNET_SCHEDULER_add_now (address_notification, plugin);
1358   return api;
1359 }
1360
1361 void *
1362 libgnunet_plugin_transport_unix_done (void *cls)
1363 {
1364   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1365   struct Plugin *plugin = api->cls;
1366
1367   if (NULL == plugin)
1368   {
1369     GNUNET_free (api);
1370     return NULL;
1371   }
1372
1373   plugin->env->notify_address (plugin->env->cls, GNUNET_NO,
1374                                plugin->unix_socket_path,
1375                                strlen (plugin->unix_socket_path) + 1,
1376                                "unix");
1377
1378   unix_transport_server_stop (plugin);
1379
1380
1381   GNUNET_CONTAINER_multihashmap_iterate (plugin->session_map, &get_session_delete_it, plugin);
1382   GNUNET_CONTAINER_multihashmap_destroy (plugin->session_map);
1383
1384
1385   if (NULL != plugin->rs)
1386     GNUNET_NETWORK_fdset_destroy (plugin->rs);
1387   if (NULL != plugin->ws)
1388     GNUNET_NETWORK_fdset_destroy (plugin->ws);
1389   GNUNET_free (plugin->unix_socket_path);
1390   GNUNET_free (plugin);
1391   GNUNET_free (api);
1392   return NULL;
1393 }
1394
1395 /* end of plugin_transport_unix.c */