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