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