(no commit message)
[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)
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)
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
901   struct sockaddr *serverAddr;
902   socklen_t addrlen;
903   int sockets_created;
904   struct sockaddr_un un;
905   size_t slen;
906
907   memset(&un, 0, sizeof(un));
908   un.sun_family = AF_UNIX;
909   slen = strlen (plugin->unix_socket_path) + 1;
910
911   GNUNET_assert(slen < sizeof(un.sun_path));
912   memcpy (un.sun_path, plugin->unix_socket_path, slen);
913   un.sun_path[slen] = '\0';
914   slen += sizeof (sa_family_t);
915   serverAddr = (struct sockaddr*) &un;
916   addrlen = slen;
917   sockets_created = 0;
918 #if LINUX
919   un.sun_path[0] = '\0';
920 #endif
921
922   plugin->unix_sock.desc = GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_DGRAM, 0);
923   if (NULL == plugin->unix_sock.desc)
924     {
925       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "socket");
926     }
927   else
928     {
929       if (GNUNET_NETWORK_socket_bind (plugin->unix_sock.desc, serverAddr, addrlen) !=
930              GNUNET_OK)
931         {
932 #if DEBUG_UNIX
933           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
934                            "UNIX Binding failed!\n");
935 #endif
936         }
937       else
938         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Bound to `%s'\n", &un.sun_path[0]);
939       if (plugin->unix_sock.desc != NULL)
940         sockets_created++;
941     }
942
943   plugin->rs = GNUNET_NETWORK_fdset_create ();
944   GNUNET_NETWORK_fdset_zero (plugin->rs);
945   GNUNET_NETWORK_fdset_set (plugin->rs,
946                             plugin->unix_sock.desc);
947
948   plugin->select_task =
949     GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
950                                  GNUNET_SCHEDULER_NO_TASK,
951                                  GNUNET_TIME_UNIT_FOREVER_REL, plugin->rs,
952                                  NULL, &unix_plugin_select, plugin);
953   return sockets_created;
954 }
955
956
957 /**
958  * Function that will be called to check if a binary address for this
959  * plugin is well-formed and corresponds to an address for THIS peer
960  * (as per our configuration).  Naturally, if absolutely necessary,
961  * plugins can be a bit conservative in their answer, but in general
962  * plugins should make sure that the address does not redirect
963  * traffic to a 3rd party that might try to man-in-the-middle our
964  * traffic.
965  *
966  * @param cls closure, should be our handle to the Plugin
967  * @param addr pointer to the address
968  * @param addrlen length of addr
969  * @return GNUNET_OK if this is a plausible address for this peer
970  *         and transport, GNUNET_SYSERR if not
971  *
972  */
973 static int
974 unix_check_address (void *cls,
975                    const void *addr,
976                    size_t addrlen)
977 {
978
979 #if DEBUG_UNIX
980   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
981                    "Informing transport service about my address `%s'\n",
982                    (char *)addr);
983 #endif
984   return GNUNET_OK;
985 }
986
987
988 /**
989  * Append our port and forward the result.
990  */
991 static void
992 append_port (void *cls, const char *hostname)
993 {
994   struct PrettyPrinterContext *ppc = cls;
995   char *ret;
996
997   if (hostname == NULL)
998     {
999       ppc->asc (ppc->asc_cls, NULL);
1000       GNUNET_free (ppc);
1001       return;
1002     }
1003   GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
1004   ppc->asc (ppc->asc_cls, ret);
1005   GNUNET_free (ret);
1006 }
1007
1008
1009 /**
1010  * Convert the transports address to a nice, human-readable
1011  * format.
1012  *
1013  * @param cls closure
1014  * @param type name of the transport that generated the address
1015  * @param addr one of the addresses of the host, NULL for the last address
1016  *        the specific address format depends on the transport
1017  * @param addrlen length of the address
1018  * @param numeric should (IP) addresses be displayed in numeric form?
1019  * @param timeout after how long should we give up?
1020  * @param asc function to call on each string
1021  * @param asc_cls closure for asc
1022  */
1023 static void
1024 unix_plugin_address_pretty_printer (void *cls,
1025                                    const char *type,
1026                                    const void *addr,
1027                                    size_t addrlen,
1028                                    int numeric,
1029                                    struct GNUNET_TIME_Relative timeout,
1030                                    GNUNET_TRANSPORT_AddressStringCallback asc,
1031                                    void *asc_cls)
1032 {
1033   struct Plugin *plugin = cls;
1034   struct PrettyPrinterContext *ppc;
1035   const void *sb;
1036   size_t sbs;
1037   struct sockaddr_in a4;
1038   struct sockaddr_in6 a6;
1039   const struct IPv4UdpAddress *u4;
1040   const struct IPv6UdpAddress *u6;
1041   uint16_t port;
1042
1043   if (addrlen == sizeof (struct IPv6UdpAddress))
1044     {
1045       u6 = addr;
1046       memset (&a6, 0, sizeof (a6));
1047       a6.sin6_family = AF_INET6;
1048       a6.sin6_port = u6->u6_port;
1049       memcpy (&a6.sin6_addr,
1050               &u6->ipv6_addr,
1051               sizeof (struct in6_addr));
1052       port = ntohs (u6->u6_port);
1053       sb = &a6;
1054       sbs = sizeof (a6);
1055     }
1056   else if (addrlen == sizeof (struct IPv4UdpAddress))
1057     {
1058       u4 = addr;
1059       memset (&a4, 0, sizeof (a4));
1060       a4.sin_family = AF_INET;
1061       a4.sin_port = u4->u_port;
1062       a4.sin_addr.s_addr = u4->ipv4_addr;
1063       port = ntohs (u4->u_port);
1064       sb = &a4;
1065       sbs = sizeof (a4);
1066     }
1067   else
1068     {
1069       /* invalid address */
1070       GNUNET_break_op (0);
1071       asc (asc_cls, NULL);
1072       return;
1073     }
1074   ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1075   ppc->asc = asc;
1076   ppc->asc_cls = asc_cls;
1077   ppc->port = port;
1078   GNUNET_RESOLVER_hostname_get (plugin->env->cfg,
1079                                 sb,
1080                                 sbs,
1081                                 !numeric, timeout, &append_port, ppc);
1082 }
1083
1084 /**
1085  * Function called for a quick conversion of the binary address to
1086  * a numeric address.  Note that the caller must not free the
1087  * address and that the next call to this function is allowed
1088  * to override the address again.
1089  *
1090  * @param cls closure
1091  * @param addr binary address
1092  * @param addrlen length of the address
1093  * @return string representing the same address
1094  */
1095 static const char*
1096 unix_address_to_string (void *cls,
1097                        const void *addr,
1098                        size_t addrlen)
1099 {
1100   static char rbuf[INET6_ADDRSTRLEN + 10];
1101   char buf[INET6_ADDRSTRLEN];
1102   const void *sb;
1103   struct in_addr a4;
1104   struct in6_addr a6;
1105   const struct IPv4UdpAddress *t4;
1106   const struct IPv6UdpAddress *t6;
1107   int af;
1108   uint16_t port;
1109
1110   if (addrlen == sizeof (struct IPv6UdpAddress))
1111     {
1112       t6 = addr;
1113       af = AF_INET6;
1114       port = ntohs (t6->u6_port);
1115       memcpy (&a6, &t6->ipv6_addr, sizeof (a6));
1116       sb = &a6;
1117     }
1118   else if (addrlen == sizeof (struct IPv4UdpAddress))
1119     {
1120       t4 = addr;
1121       af = AF_INET;
1122       port = ntohs (t4->u_port);
1123       memcpy (&a4, &t4->ipv4_addr, sizeof (a4));
1124       sb = &a4;
1125     }
1126   else
1127     return NULL;
1128   inet_ntop (af, sb, buf, INET6_ADDRSTRLEN);
1129   GNUNET_snprintf (rbuf,
1130                    sizeof (rbuf),
1131                    "%s:%u",
1132                    buf,
1133                    port);
1134   return rbuf;
1135 }
1136
1137 /**
1138  * The exported method. Makes the core api available via a global and
1139  * returns the unix transport API.
1140  */
1141 void *
1142 libgnunet_plugin_transport_unix_init (void *cls)
1143 {
1144   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1145   unsigned long long port;
1146   struct GNUNET_TRANSPORT_PluginFunctions *api;
1147   struct Plugin *plugin;
1148   int sockets_created;
1149
1150   if (GNUNET_OK !=
1151       GNUNET_CONFIGURATION_get_value_number (env->cfg,
1152                                              "transport-unix",
1153                                              "PORT",
1154                                              &port))
1155     port = UNIX_NAT_DEFAULT_PORT;
1156   else if (port > 65535)
1157     {
1158       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1159                   _("Given `%s' option is out of range: %llu > %u\n"),
1160                   "PORT",
1161                   port,
1162                   65535);
1163       return NULL;
1164     }
1165
1166
1167   plugin = GNUNET_malloc (sizeof (struct Plugin));
1168   plugin->port = port;
1169   plugin->env = env;
1170   GNUNET_asprintf(&plugin->unix_socket_path, "/tmp/unix-plugin-sock.%d", plugin->port);
1171
1172   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1173   api->cls = plugin;
1174
1175   api->send = &unix_plugin_send;
1176   api->disconnect = &unix_disconnect;
1177   api->address_pretty_printer = &unix_plugin_address_pretty_printer;
1178   api->address_to_string = &unix_address_to_string;
1179   api->check_address = &unix_check_address;
1180
1181   add_to_address_list (plugin, plugin->unix_socket_path, strlen(plugin->unix_socket_path) + 1);
1182
1183   sockets_created = unix_transport_server_start (plugin);
1184   if (sockets_created == 0)
1185     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1186                 _("Failed to open UNIX sockets\n"));
1187
1188   plugin->env->notify_address(plugin->env->cls,
1189                               "unix",
1190                               plugin->unix_socket_path,
1191                               strlen(plugin->unix_socket_path) + 1,
1192                               GNUNET_TIME_UNIT_FOREVER_REL);
1193   return api;
1194 }
1195
1196 void *
1197 libgnunet_plugin_transport_unix_done (void *cls)
1198 {
1199   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1200   struct Plugin *plugin = api->cls;
1201   struct LocalAddrList *lal;
1202
1203   unix_transport_server_stop (plugin);
1204
1205   GNUNET_NETWORK_fdset_destroy (plugin->rs);
1206   while (NULL != (lal = plugin->lal_head))
1207     {
1208       GNUNET_CONTAINER_DLL_remove (plugin->lal_head,
1209                                    plugin->lal_tail,
1210                                    lal);
1211       GNUNET_free (lal);
1212     }
1213   GNUNET_free (plugin);
1214   GNUNET_free (api);
1215   return NULL;
1216 }
1217
1218 /* end of plugin_transport_unix.c */