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