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