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