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