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