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