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