-makefile for new test_stream_local (commented)
[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
247
248 static int
249 get_session_delete_it (void *cls, const GNUNET_HashCode * key, void *value)
250 {
251   struct Session *s = value;
252   struct Plugin *plugin = cls;
253   GNUNET_assert (plugin != NULL);
254
255 #if DEBUG_UNIX
256   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Deleting session for peer `%s' `%s' \n", GNUNET_i2s (&s->target), s->addr);
257 #endif
258
259   plugin->env->session_end (plugin->env->cls, &s->target, s);
260
261   GNUNET_assert (GNUNET_YES ==
262                  GNUNET_CONTAINER_multihashmap_remove(plugin->session_map, &s->target.hashPubKey, s));
263
264   GNUNET_free (s);
265
266   return GNUNET_YES;
267 }
268
269 /**
270  * Disconnect from a remote node.  Clean up session if we have one for this peer
271  *
272  * @param cls closure for this call (should be handle to Plugin)
273  * @param target the peeridentity of the peer to disconnect
274  * @return GNUNET_OK on success, GNUNET_SYSERR if the operation failed
275  */
276 void
277 unix_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
278 {
279   struct Plugin *plugin = cls;
280   GNUNET_assert (plugin != NULL);
281
282   GNUNET_CONTAINER_multihashmap_get_multiple (plugin->session_map, &target->hashPubKey, &get_session_delete_it, plugin);
283   return;
284 }
285
286 /**
287  * Shutdown the server process (stop receiving inbound traffic). Maybe
288  * restarted later!
289  *
290  * @param cls Handle to the plugin for this transport
291  *
292  * @return returns the number of sockets successfully closed,
293  *         should equal the number of sockets successfully opened
294  */
295 static int
296 unix_transport_server_stop (void *cls)
297 {
298   struct Plugin *plugin = cls;
299
300   struct UNIXMessageWrapper * msgw = plugin->msg_head;
301
302   while (NULL != (msgw = plugin->msg_head))
303   {
304     GNUNET_CONTAINER_DLL_remove (plugin->msg_head, plugin->msg_tail, msgw);
305     if (msgw->cont != NULL)
306       msgw->cont (msgw->cont_cls,  &msgw->session->target, GNUNET_SYSERR);
307     GNUNET_free (msgw->msg);
308     GNUNET_free (msgw);
309   }
310
311   if (plugin->select_task != GNUNET_SCHEDULER_NO_TASK)
312   {
313     GNUNET_SCHEDULER_cancel (plugin->select_task);
314     plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
315   }
316
317   GNUNET_break (GNUNET_OK ==
318                 GNUNET_NETWORK_socket_close (plugin->unix_sock.desc));
319   plugin->unix_sock.desc = NULL;
320   plugin->with_ws = GNUNET_NO;
321   return GNUNET_OK;
322 }
323
324
325 struct PeerSession *
326 find_session (struct Plugin *plugin, const struct GNUNET_PeerIdentity *peer)
327 {
328   struct PeerSession *pos;
329
330   pos = plugin->sessions;
331   while (pos != NULL)
332   {
333     if (memcmp (&pos->target, peer, sizeof (struct GNUNET_PeerIdentity)) == 0)
334       return pos;
335     pos = pos->next;
336   }
337
338   return pos;
339 }
340
341
342 /**
343  * Actually send out the message, assume we've got the address and
344  * send_handle squared away!
345  *
346  * @param cls closure
347  * @param send_handle which handle to send message on
348  * @param target who should receive this message (ignored by UNIX)
349  * @param msgbuf one or more GNUNET_MessageHeader(s) strung together
350  * @param msgbuf_size the size of the msgbuf to send
351  * @param priority how important is the message (ignored by UNIX)
352  * @param timeout when should we time out (give up) if we can not transmit?
353  * @param addr the addr to send the message to, needs to be a sockaddr for us
354  * @param addrlen the len of addr
355  * @param cont continuation to call once the message has
356  *        been transmitted (or if the transport is ready
357  *        for the next transmission call; or if the
358  *        peer disconnected...)
359  * @param cont_cls closure for cont
360  *
361  * @return the number of bytes written, -1 on errors
362  */
363 static ssize_t
364 unix_real_send (void *cls,
365                 struct GNUNET_NETWORK_Handle *send_handle,
366                 const struct GNUNET_PeerIdentity *target, const char *msgbuf,
367                 size_t msgbuf_size, unsigned int priority,
368                 struct GNUNET_TIME_Relative timeout, const void *addr,
369                 size_t addrlen, GNUNET_TRANSPORT_TransmitContinuation cont,
370                 void *cont_cls)
371 {
372
373   ssize_t sent;
374   const void *sb;
375   size_t sbs;
376   struct sockaddr_un un;
377   size_t slen;
378   int retry;
379
380   if (send_handle == NULL)
381   {
382 #if DEBUG_UNIX
383     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
384                 "unix_real_send with send_handle NULL!\n");
385 #endif
386     /* failed to open send socket for AF */
387     if (cont != NULL)
388       cont (cont_cls, target, GNUNET_SYSERR);
389     return 0;
390   }
391   if ((addr == NULL) || (addrlen == 0))
392   {
393 #if DEBUG_UNIX
394     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
395                 "unix_real_send called without address, returning!\n");
396 #endif
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         retry = GNUNET_YES;
445       else
446         GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "setsockopt");
447     }
448   }
449
450 #if DEBUG_UNIX
451   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
452               "UNIX transmit %u-byte message to %s (%d: %s)\n",
453               (unsigned int) msgbuf_size, GNUNET_a2s (sb, sbs), (int) sent,
454               (sent < 0) ? STRERROR (errno) : "ok");
455 #endif
456   /* Calling continuation */
457   if (cont != NULL)
458   {
459     if ((sent == GNUNET_SYSERR) && (retry == GNUNET_NO))
460       cont (cont_cls, target, GNUNET_SYSERR);
461     if (sent > 0)
462       cont (cont_cls, target, GNUNET_OK);
463   }
464
465   /* return number of bytes successfully sent */
466   if (sent > 0)
467     return sent;
468   /* failed and retry: return 0 */
469   if ((GNUNET_SYSERR == sent) && (retry == GNUNET_YES))
470     return 0;
471   /* failed and no retry: return -1 */
472   if ((GNUNET_SYSERR == sent) && (retry == GNUNET_NO))
473     return -1;
474
475   return sent;
476 }
477
478 struct gsi_ctx
479 {
480   char *address;
481   size_t addrlen;
482   struct Session *res;
483 };
484
485 static int
486 get_session_it (void *cls, const GNUNET_HashCode * key, void *value)
487 {
488   struct gsi_ctx *gsi = cls;
489   struct Session *s = value;
490
491 #if DEBUG_UNIX
492   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Comparing session %s %s\n", gsi->address, s->addr);
493 #endif
494   if ((gsi->addrlen == s->addrlen) &&
495       (0 == memcmp (gsi->address, s->addr, s->addrlen)))
496   {
497     gsi->res = s;
498     return GNUNET_NO;
499   }
500   return GNUNET_YES;
501 }
502
503 /**
504  * Creates a new outbound session the transport service will use to send data to the
505  * peer
506  *
507  * @param cls the plugin
508  * @param address the address
509  * @return the session or NULL of max connections exceeded
510  */
511 static struct Session *
512 unix_plugin_get_session (void *cls,
513                   const struct GNUNET_HELLO_Address *address)
514 {
515   struct Session * s = NULL;
516   struct Plugin *plugin = cls;
517   struct gsi_ctx gsi;
518
519   /* Checks */
520   GNUNET_assert (plugin != NULL);
521   GNUNET_assert (address != NULL);
522
523   /* Check if already existing */
524   gsi.address = (char *) address->address;
525   gsi.addrlen = address->address_length;
526   gsi.res = NULL;
527   GNUNET_CONTAINER_multihashmap_get_multiple (plugin->session_map, &address->peer.hashPubKey, &get_session_it, &gsi);
528   if (gsi.res != NULL)
529   {
530 #if DEBUG_UNIX
531     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Found existing session\n");
532 #endif
533     return gsi.res;
534   }
535
536   /* Create a new session */
537
538   s = GNUNET_malloc (sizeof (struct Session) + address->address_length);
539   s->addr = &s[1];
540   s->addrlen = address->address_length;
541   memcpy(s->addr, address->address, s->addrlen);
542   memcpy(&s->target, &address->peer, sizeof (struct GNUNET_PeerIdentity));
543
544   GNUNET_CONTAINER_multihashmap_put (plugin->session_map,
545       &address->peer.hashPubKey, s,
546       GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
547 #if DEBUG_UNIX
548     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Creating new session\n");
549 #endif
550
551   return s;
552 }
553
554 /*
555  * @param cls the plugin handle
556  * @param tc the scheduling context (for rescheduling this function again)
557  *
558  * We have been notified that our writeset has something to read.  We don't
559  * know which socket needs to be read, so we have to check each one
560  * Then reschedule this function to be called again once more is available.
561  *
562  */
563 static void
564 unix_plugin_select (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
565
566 /**
567  * Function that can be used by the transport service to transmit
568  * a message using the plugin.   Note that in the case of a
569  * peer disconnecting, the continuation MUST be called
570  * prior to the disconnect notification itself.  This function
571  * will be called with this peer's HELLO message to initiate
572  * a fresh connection to another peer.
573  *
574  * @param cls closure
575  * @param session which session must be used
576  * @param msgbuf the message to transmit
577  * @param msgbuf_size number of bytes in 'msgbuf'
578  * @param priority how important is the message (most plugins will
579  *                 ignore message priority and just FIFO)
580  * @param to how long to wait at most for the transmission (does not
581  *                require plugins to discard the message after the timeout,
582  *                just advisory for the desired delay; most plugins will ignore
583  *                this as well)
584  * @param cont continuation to call once the message has
585  *        been transmitted (or if the transport is ready
586  *        for the next transmission call; or if the
587  *        peer disconnected...); can be NULL
588  * @param cont_cls closure for cont
589  * @return number of bytes used (on the physical network, with overheads);
590  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
591  *         and does NOT mean that the message was not transmitted (DV)
592  */
593 static ssize_t
594 unix_plugin_send (void *cls,
595                   struct Session *session,
596                   const char *msgbuf, size_t msgbuf_size,
597                   unsigned int priority,
598                   struct GNUNET_TIME_Relative to,
599                   GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
600 {
601   struct Plugin *plugin = cls;
602   struct UNIXMessageWrapper *wrapper;
603   struct UNIXMessage *message;
604   int ssize;
605
606   GNUNET_assert (plugin != NULL);
607   GNUNET_assert (session != NULL);
608
609   if (GNUNET_OK != GNUNET_CONTAINER_multihashmap_contains_value(plugin->session_map,
610       &session->target.hashPubKey, session))
611   {
612     GNUNET_break (0);
613     return GNUNET_SYSERR;
614   }
615
616   ssize = sizeof (struct UNIXMessage) + msgbuf_size;
617   message = GNUNET_malloc (sizeof (struct UNIXMessage) + msgbuf_size);
618   message->header.size = htons (ssize);
619   message->header.type = htons (0);
620   memcpy (&message->sender, plugin->env->my_identity,
621           sizeof (struct GNUNET_PeerIdentity));
622   memcpy (&message[1], msgbuf, msgbuf_size);
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 #if DEBUG_UNIX
636   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sent %d bytes to `%s'\n", ssize,
637               (char *) session->addr);
638 #endif
639
640   if (plugin->with_ws == GNUNET_NO)
641   {
642     if (plugin->select_task != GNUNET_SCHEDULER_NO_TASK)
643       GNUNET_SCHEDULER_cancel(plugin->select_task);
644
645     plugin->select_task =
646         GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
647                                      GNUNET_SCHEDULER_NO_TASK,
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 #if DEBUG_UNIX
682   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received message from %s\n",
683               un->sun_path);
684 #endif
685   plugin->env->receive (plugin->env->cls, sender, currhdr,
686                         (const struct GNUNET_ATS_Information *) &ats, 2,
687                         NULL, un->sun_path, strlen (un->sun_path) + 1);
688 }
689
690
691 static void
692 unix_plugin_select_read (struct Plugin * plugin)
693 {
694   char buf[65536];
695   struct UNIXMessage *msg;
696   struct GNUNET_PeerIdentity sender;
697   struct sockaddr_un un;
698   socklen_t addrlen;
699   ssize_t ret;
700   int offset;
701   int tsize;
702   char *msgbuf;
703   const struct GNUNET_MessageHeader *currhdr;
704   uint16_t csize;
705
706   addrlen = sizeof (un);
707   memset (&un, 0, sizeof (un));
708
709   ret =
710       GNUNET_NETWORK_socket_recvfrom (plugin->unix_sock.desc, buf, sizeof (buf),
711                                       (struct sockaddr *) &un, &addrlen);
712
713   if ((GNUNET_SYSERR == ret) && ((errno == EAGAIN) || (errno == ENOBUFS)))
714     return;
715
716   if (ret == GNUNET_SYSERR)
717   {
718     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "recvfrom");
719     return;
720   }
721   else
722   {
723 #if LINUX
724     un.sun_path[0] = '/';
725 #endif
726 #if DEBUG_UNIX
727     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Read %d bytes from socket %s\n", ret,
728                 &un.sun_path[0]);
729 #endif
730   }
731
732   GNUNET_assert (AF_UNIX == (un.sun_family));
733
734   msg = (struct UNIXMessage *) buf;
735   csize = ntohs (msg->header.size);
736   if ((csize < sizeof (struct UNIXMessage)) || (csize > ret))
737   {
738     GNUNET_break_op (0);
739     return;
740   }
741   msgbuf = (char *) &msg[1];
742   memcpy (&sender, &msg->sender, sizeof (struct GNUNET_PeerIdentity));
743   offset = 0;
744   tsize = csize - sizeof (struct UNIXMessage);
745   while (offset + sizeof (struct GNUNET_MessageHeader) <= tsize)
746   {
747     currhdr = (struct GNUNET_MessageHeader *) &msgbuf[offset];
748     csize = ntohs (currhdr->size);
749     if ((csize < sizeof (struct GNUNET_MessageHeader)) ||
750         (csize > tsize - offset))
751     {
752       GNUNET_break_op (0);
753       break;
754     }
755     unix_demultiplexer (plugin, &sender, currhdr, &un, sizeof (un));
756     offset += csize;
757   }
758 }
759
760 static void
761 unix_plugin_select_write (struct Plugin * plugin)
762 {
763   int sent = 0;
764   struct UNIXMessageWrapper * msgw = plugin->msg_head;
765
766   sent = unix_real_send (plugin,
767                          plugin->unix_sock.desc,
768                          &msgw->session->target,
769                          (const char *) msgw->msg,
770                          msgw->msgsize,
771                          msgw->priority,
772                          msgw->timeout,
773                          msgw->session->addr,
774                          msgw->session->addrlen,
775                          msgw->cont, msgw->cont_cls);
776
777   /* successfully sent bytes */
778   if (sent > 0)
779   {
780     GNUNET_CONTAINER_DLL_remove(plugin->msg_head, plugin->msg_tail, msgw);
781     GNUNET_free (msgw->msg);
782     GNUNET_free (msgw);
783     return;
784   }
785
786   /* failed and no retry */
787   if (sent == -1)
788   {
789     GNUNET_CONTAINER_DLL_remove(plugin->msg_head, plugin->msg_tail, msgw);
790     GNUNET_free (msgw->msg);
791     GNUNET_free (msgw);
792     return;
793   }
794
795   /* failed and retry */
796   if (sent == 0)
797     return;
798 }
799
800 /*
801  * @param cls the plugin handle
802  * @param tc the scheduling context (for rescheduling this function again)
803  *
804  * We have been notified that our writeset has something to read.  We don't
805  * know which socket needs to be read, so we have to check each one
806  * Then reschedule this function to be called again once more is available.
807  *
808  */
809 static void
810 unix_plugin_select (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
811 {
812   struct Plugin *plugin = cls;
813
814   plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
815   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
816     return;
817
818   plugin->with_ws = GNUNET_NO;
819   if ((tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY) != 0)
820   {
821     GNUNET_assert (GNUNET_NETWORK_fdset_isset
822                    (tc->write_ready, plugin->unix_sock.desc));
823     if (plugin->msg_head != NULL)
824       unix_plugin_select_write (plugin);
825   }
826
827   if ((tc->reason & GNUNET_SCHEDULER_REASON_READ_READY) != 0)
828   {
829     GNUNET_assert (GNUNET_NETWORK_fdset_isset
830                    (tc->read_ready, plugin->unix_sock.desc));
831     unix_plugin_select_read (plugin);
832   }
833
834   if (plugin->select_task != GNUNET_SCHEDULER_NO_TASK)
835     GNUNET_SCHEDULER_cancel (plugin->select_task);
836   plugin->select_task =
837       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
838                                    GNUNET_SCHEDULER_NO_TASK,
839                                    GNUNET_TIME_UNIT_FOREVER_REL,
840                                    plugin->rs,
841                                    (plugin->msg_head != NULL) ? plugin->ws : NULL,
842                                    &unix_plugin_select, plugin);
843   if (plugin->msg_head != NULL)
844     plugin->with_ws = GNUNET_YES;
845 }
846
847 /**
848  * Create a slew of UNIX sockets.  If possible, use IPv6 and IPv4.
849  *
850  * @param cls closure for server start, should be a struct Plugin *
851  * @return number of sockets created or GNUNET_SYSERR on error
852 */
853 static int
854 unix_transport_server_start (void *cls)
855 {
856   struct Plugin *plugin = cls;
857   struct sockaddr *serverAddr;
858   socklen_t addrlen;
859   struct sockaddr_un un;
860   size_t slen;
861
862   memset (&un, 0, sizeof (un));
863   un.sun_family = AF_UNIX;
864   slen = strlen (plugin->unix_socket_path) + 1;
865   if (slen >= sizeof (un.sun_path))
866     slen = sizeof (un.sun_path) - 1;
867
868   memcpy (un.sun_path, plugin->unix_socket_path, slen);
869   un.sun_path[slen] = '\0';
870   slen = sizeof (struct sockaddr_un);
871 #if HAVE_SOCKADDR_IN_SIN_LEN
872   un.sun_len = (u_char) slen;
873 #endif
874
875   serverAddr = (struct sockaddr *) &un;
876   addrlen = slen;
877 #if LINUX
878   un.sun_path[0] = '\0';
879 #endif
880   plugin->ats_network = plugin->env->get_address_type (plugin->env->cls, serverAddr, addrlen);
881   plugin->unix_sock.desc =
882       GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_DGRAM, 0);
883   if (NULL == plugin->unix_sock.desc)
884   {
885     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
886     return GNUNET_SYSERR;
887   }
888   if (GNUNET_NETWORK_socket_bind (plugin->unix_sock.desc, serverAddr, addrlen)
889       != GNUNET_OK)
890   {
891     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
892     GNUNET_NETWORK_socket_close (plugin->unix_sock.desc);
893     plugin->unix_sock.desc = NULL;
894     return GNUNET_SYSERR;
895   }
896 #if DEBUG_UNIX
897   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "unix", "Bound to `%s'\n",
898                    &un.sun_path[0]);
899 #endif
900   plugin->rs = GNUNET_NETWORK_fdset_create ();
901   plugin->ws = GNUNET_NETWORK_fdset_create ();
902   GNUNET_NETWORK_fdset_zero (plugin->rs);
903   GNUNET_NETWORK_fdset_zero (plugin->ws);
904   GNUNET_NETWORK_fdset_set (plugin->rs, plugin->unix_sock.desc);
905   GNUNET_NETWORK_fdset_set (plugin->ws, plugin->unix_sock.desc);
906
907   plugin->select_task =
908       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
909                                    GNUNET_SCHEDULER_NO_TASK,
910                                    GNUNET_TIME_UNIT_FOREVER_REL,
911                                    plugin->rs,
912                                    NULL,
913                                    &unix_plugin_select, plugin);
914   plugin->with_ws = GNUNET_NO;
915
916   return 1;
917 }
918
919
920 /**
921  * Function that will be called to check if a binary address for this
922  * plugin is well-formed and corresponds to an address for THIS peer
923  * (as per our configuration).  Naturally, if absolutely necessary,
924  * plugins can be a bit conservative in their answer, but in general
925  * plugins should make sure that the address does not redirect
926  * traffic to a 3rd party that might try to man-in-the-middle our
927  * traffic.
928  *
929  * @param cls closure, should be our handle to the Plugin
930  * @param addr pointer to the address
931  * @param addrlen length of addr
932  * @return GNUNET_OK if this is a plausible address for this peer
933  *         and transport, GNUNET_SYSERR if not
934  *
935  */
936 static int
937 unix_check_address (void *cls, const void *addr, size_t addrlen)
938 {
939
940 #if DEBUG_UNIX
941   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
942               "Informing transport service about my address `%s'\n",
943               (char *) addr);
944 #endif
945   return GNUNET_OK;
946 }
947
948
949 /**
950  * Convert the transports address to a nice, human-readable
951  * format.
952  *
953  * @param cls closure
954  * @param type name of the transport that generated the address
955  * @param addr one of the addresses of the host, NULL for the last address
956  *        the specific address format depends on the transport
957  * @param addrlen length of the address
958  * @param numeric should (IP) addresses be displayed in numeric form?
959  * @param timeout after how long should we give up?
960  * @param asc function to call on each string
961  * @param asc_cls closure for asc
962  */
963 static void
964 unix_plugin_address_pretty_printer (void *cls, const char *type,
965                                     const void *addr, size_t addrlen,
966                                     int numeric,
967                                     struct GNUNET_TIME_Relative timeout,
968                                     GNUNET_TRANSPORT_AddressStringCallback asc,
969                                     void *asc_cls)
970 {
971   if ((addr != NULL) && (addrlen > 0))
972     asc (asc_cls, (const char *) addr);
973   else
974   {
975     GNUNET_break (0);
976     asc (asc_cls, "Invalid UNIX address");
977   }
978
979 }
980
981 /**
982  * Function called to convert a string address to
983  * a binary address.
984  *
985  * @param cls closure ('struct Plugin*')
986  * @param addr string address
987  * @param addrlen length of the address
988  * @param buf location to store the buffer
989  *        If the function returns GNUNET_SYSERR, its contents are undefined.
990  * @param added length of created address
991  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
992  */
993 int
994 unix_string_to_address (void *cls, const char *addr, uint16_t addrlen,
995     void **buf, size_t *added)
996 {
997   if ((NULL == addr) || (addrlen == 0))
998   {
999     GNUNET_break (0);
1000     return GNUNET_SYSERR;
1001   }
1002
1003   if ((strlen (addr) + 1) != addrlen)
1004   {
1005     GNUNET_break (0);
1006     return GNUNET_SYSERR;
1007   }
1008
1009   (*buf) = strdup (addr);
1010   (*added) = strlen (addr) + 1;
1011   return GNUNET_OK;
1012 }
1013
1014
1015
1016
1017 /**
1018  * Function called for a quick conversion of the binary address to
1019  * a numeric address.  Note that the caller must not free the
1020  * address and that the next call to this function is allowed
1021  * to override the address again.
1022  *
1023  * @param cls closure
1024  * @param addr binary address
1025  * @param addrlen length of the address
1026  * @return string representing the same address
1027  */
1028 static const char *
1029 unix_address_to_string (void *cls, const void *addr, size_t addrlen)
1030 {
1031   if ((addr != NULL) && (addrlen > 0))
1032     return (const char *) addr;
1033   else
1034     return NULL;
1035 }
1036
1037 /**
1038  * Notify transport service about address
1039  *
1040  * @param cls the plugin
1041  * @param tc unused
1042  */
1043 static void
1044 address_notification (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1045 {
1046   struct Plugin *plugin = cls;
1047
1048   plugin->env->notify_address (plugin->env->cls, GNUNET_YES,
1049                                plugin->unix_socket_path,
1050                                strlen (plugin->unix_socket_path) + 1);
1051 }
1052
1053 /**
1054  * The exported method. Makes the core api available via a global and
1055  * returns the unix transport API.
1056  */
1057 void *
1058 libgnunet_plugin_transport_unix_init (void *cls)
1059 {
1060   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1061   unsigned long long port;
1062   struct GNUNET_TRANSPORT_PluginFunctions *api;
1063   struct Plugin *plugin;
1064   int sockets_created;
1065
1066   if (NULL == env->receive)
1067   {
1068     /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
1069        initialze the plugin or the API */
1070     api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1071     api->cls = NULL;
1072     api->address_pretty_printer = &unix_plugin_address_pretty_printer;
1073     api->address_to_string = &unix_address_to_string;
1074     api->string_to_address = NULL; // FIXME!
1075     return api;
1076   }
1077
1078   if (GNUNET_OK !=
1079       GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-unix", "PORT",
1080                                              &port))
1081     port = UNIX_NAT_DEFAULT_PORT;
1082   plugin = GNUNET_malloc (sizeof (struct Plugin));
1083   plugin->port = port;
1084   plugin->env = env;
1085   GNUNET_asprintf (&plugin->unix_socket_path, "/tmp/unix-plugin-sock.%d",
1086                    plugin->port);
1087
1088   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1089   api->cls = plugin;
1090
1091   api->get_session = &unix_plugin_get_session;
1092   api->send = &unix_plugin_send;
1093   api->disconnect = &unix_disconnect;
1094   api->address_pretty_printer = &unix_plugin_address_pretty_printer;
1095   api->address_to_string = &unix_address_to_string;
1096   api->check_address = &unix_check_address;
1097   api->string_to_address = &unix_string_to_address;
1098   sockets_created = unix_transport_server_start (plugin);
1099   if (sockets_created == 0)
1100     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _("Failed to open UNIX sockets\n"));
1101
1102   plugin->session_map = GNUNET_CONTAINER_multihashmap_create(10);
1103
1104   GNUNET_SCHEDULER_add_now (address_notification, plugin);
1105   return api;
1106 }
1107
1108 void *
1109 libgnunet_plugin_transport_unix_done (void *cls)
1110 {
1111   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1112   struct Plugin *plugin = api->cls;
1113
1114   if (NULL == plugin)
1115   {
1116     GNUNET_free (api);
1117     return NULL;
1118   }
1119   unix_transport_server_stop (plugin);
1120
1121   GNUNET_CONTAINER_multihashmap_iterate (plugin->session_map, &get_session_delete_it, plugin);
1122   GNUNET_CONTAINER_multihashmap_destroy (plugin->session_map);
1123
1124   GNUNET_NETWORK_fdset_destroy (plugin->rs);
1125   GNUNET_NETWORK_fdset_destroy (plugin->ws);
1126   GNUNET_free (plugin->unix_socket_path);
1127   GNUNET_free (plugin);
1128   GNUNET_free (api);
1129   return NULL;
1130 }
1131
1132 /* end of plugin_transport_unix.c */