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