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