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