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