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