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