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