2 This file is part of GNUnet
3 (C) 2010, 2013 Christian Grothoff (and other contributing authors)
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.
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.
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.
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
30 #include "gnunet_hello_lib.h"
31 #include "gnunet_util_lib.h"
32 #include "gnunet_protocols.h"
33 #include "gnunet_statistics_service.h"
34 #include "gnunet_transport_service.h"
35 #include "gnunet_transport_plugin.h"
36 #include "transport.h"
40 * Return code we give on 'send' if we failed to send right now
41 * but it makes sense to retry later. (Note: we might want to
42 * move this to the plugin API!?).
46 #define PLUGIN_NAME "unix"
49 * How long until we give up on transmitting the welcome message?
51 #define HOSTNAME_RESOLVE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
54 * Default "port" to use, if configuration does not specify.
55 * Essentially just a number appended to the UNIX path.
57 #define UNIX_NAT_DEFAULT_PORT 22086
60 #define LOG(kind,...) GNUNET_log_from (kind, "transport-unix",__VA_ARGS__)
63 GNUNET_NETWORK_STRUCT_BEGIN
67 uint32_t options GNUNET_PACKED;
69 uint32_t addrlen GNUNET_PACKED;
74 * UNIX Message-Packet header.
81 struct GNUNET_MessageHeader header;
84 * What is the identity of the sender (GNUNET_hash of public key)
86 struct GNUNET_PeerIdentity sender;
90 GNUNET_NETWORK_STRUCT_END
95 static uint32_t myoptions;
98 * Handle for a session.
102 struct GNUNET_PeerIdentity target;
104 struct Plugin * plugin;
106 struct UnixAddress *addr;
111 * Session timeout task
113 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
117 struct UNIXMessageWrapper
120 * We keep messages in a doubly linked list.
122 struct UNIXMessageWrapper *next;
125 * We keep messages in a doubly linked list.
127 struct UNIXMessageWrapper *prev;
130 * The actual payload (allocated separately right now).
132 struct UNIXMessage * msg;
135 * Session this message belongs to.
137 struct Session *session;
140 * Function to call upon transmission.
142 GNUNET_TRANSPORT_TransmitContinuation cont;
145 * Closure for 'cont'.
150 * Timeout for this message.
152 struct GNUNET_TIME_Absolute timeout;
155 * Number of bytes in 'msg'.
160 * Number of bytes of payload encapsulated in 'msg'.
165 * Priority of the message (ignored, just dragged along in UNIX).
167 unsigned int priority;
172 * Encapsulation of all of the state of the plugin.
184 * Stored in a linked list.
186 struct PeerSession *next;
189 * Pointer to the global plugin struct.
191 struct Plugin *plugin;
194 * To whom are we talking to (set to our identity
195 * if we are still waiting for the welcome message)
197 struct GNUNET_PeerIdentity target;
200 * Address of the other peer (either based on our 'connect'
201 * call or on our 'accept' call).
206 * Length of connect_addr.
211 * Are we still expecting the welcome message? (GNUNET_YES/GNUNET_NO)
213 int expecting_welcome;
216 * From which socket do we need to send to this peer?
218 struct GNUNET_NETWORK_Handle *sock;
221 * Queue of messages for this peer, in the case that
222 * we have to await a connection...
224 struct MessageQueue *messages;
230 * Information we keep for each of our listen sockets.
232 struct UNIX_Sock_Info
237 struct GNUNET_NETWORK_Handle *desc;
240 * The port we bound to (not an actual PORT, as UNIX domain sockets
241 * don't have ports, but rather a number in the path name to make this
249 * Encapsulation of all of the state of the plugin.
255 * ID of task used to update our addresses when one expires.
257 GNUNET_SCHEDULER_TaskIdentifier address_update_task;
262 GNUNET_SCHEDULER_TaskIdentifier select_task;
265 * Number of bytes we currently have in our write queue.
267 unsigned long long bytes_in_queue;
272 struct GNUNET_TRANSPORT_PluginEnvironment *env;
277 struct GNUNET_CONTAINER_MultiHashMap *session_map;
282 struct GNUNET_NETWORK_FDSet *rs;
287 struct GNUNET_NETWORK_FDSet *ws;
290 * Path of our unix domain socket (/tmp/unix-plugin-PORT)
292 char *unix_socket_path;
295 * Head of queue of messages to transmit.
297 struct UNIXMessageWrapper *msg_head;
300 * Tail of queue of messages to transmit.
302 struct UNIXMessageWrapper *msg_tail;
305 * socket that we transmit all data with
307 struct UNIX_Sock_Info unix_sock;
312 struct GNUNET_ATS_Information ats_network;
315 * Is the write set in the current 'select' task? GNUNET_NO if the
316 * write queue was empty when the main task was scheduled,
317 * GNUNET_YES if we're already waiting for being allowed to write.
322 * Integer to append to unix domain socket.
330 * Increment session timeout due to activity
332 * @param s session for which the timeout should be moved
335 reschedule_session_timeout (struct Session *s);
339 * We have been notified that our writeset has something to read. We don't
340 * know which socket needs to be read, so we have to check each one
341 * Then reschedule this function to be called again once more is available.
343 * @param cls the plugin handle
344 * @param tc the scheduling context (for rescheduling this function again)
347 unix_plugin_select (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
350 * Function called for a quick conversion of the binary address to
351 * a numeric address. Note that the caller must not free the
352 * address and that the next call to this function is allowed
353 * to override the address again.
356 * @param addr binary address
357 * @param addrlen length of the address
358 * @return string representing the same address
361 unix_address_to_string (void *cls, const void *addr, size_t addrlen);
364 * Re-schedule the main 'select' callback (unix_plugin_select)
367 * @param plugin the plugin context
370 reschedule_select (struct Plugin * plugin)
372 if (plugin->select_task != GNUNET_SCHEDULER_NO_TASK)
374 GNUNET_SCHEDULER_cancel (plugin->select_task);
375 plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
377 if (NULL != plugin->msg_head)
379 plugin->select_task =
380 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
381 GNUNET_TIME_UNIT_FOREVER_REL,
384 &unix_plugin_select, plugin);
385 plugin->with_ws = GNUNET_YES;
389 plugin->select_task =
390 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
391 GNUNET_TIME_UNIT_FOREVER_REL,
394 &unix_plugin_select, plugin);
395 plugin->with_ws = GNUNET_NO;
401 * Closure to 'lookup_session_it'.
406 * Location to store the session, if found.
411 * Address we are looking for.
413 const struct UnixAddress *ua;
420 * Function called to find a session by address.
422 * @param cls the 'struct LookupCtx'
423 * @param key peer we are looking for (unused)
424 * @param value a session
425 * @return GNUNET_YES if not found (continue looking), GNUNET_NO on success
428 lookup_session_it (void *cls,
429 const struct GNUNET_HashCode * key,
432 struct LookupCtx *lctx = cls;
433 struct Session *t = value;
435 if (t->addrlen != lctx->ua_len)
438 if (0 == memcmp (&t->addr, lctx->ua, lctx->ua_len))
448 * Find an existing session by address.
450 * @param plugin the plugin
451 * @param sender for which peer should the session be?
452 * @param ua address to look for
453 * @param ua_len length of the address
454 * @return NULL if session was not found
456 static struct Session *
457 lookup_session (struct Plugin *plugin,
458 const struct GNUNET_PeerIdentity *sender,
459 const struct UnixAddress *ua, size_t ua_len)
461 struct LookupCtx lctx;
463 GNUNET_assert (NULL != plugin);
464 GNUNET_assert (NULL != sender);
465 GNUNET_assert (NULL != ua);
468 lctx.ua_len = ua_len;
469 GNUNET_CONTAINER_multihashmap_get_multiple (plugin->session_map,
471 &lookup_session_it, &lctx);
477 * Functions with this signature are called whenever we need
478 * to close a session due to a disconnect or failure to
479 * establish a connection.
481 * @param s session to close down
484 disconnect_session (struct Session *s)
486 struct Plugin *plugin = s->plugin;
487 struct UNIXMessageWrapper *msgw;
488 struct UNIXMessageWrapper *next;
491 LOG (GNUNET_ERROR_TYPE_DEBUG,
492 "Disconnecting session for peer `%s' `%s'\n",
493 GNUNET_i2s (&s->target),
495 plugin->env->session_end (plugin->env->cls, &s->target, s);
497 next = plugin->msg_head;
502 if (msgw->session != s)
504 GNUNET_CONTAINER_DLL_remove (plugin->msg_head, plugin->msg_tail, msgw);
505 if (NULL != msgw->cont)
506 msgw->cont (msgw->cont_cls, &msgw->session->target, GNUNET_SYSERR,
508 GNUNET_free (msgw->msg);
510 removed = GNUNET_YES;
512 GNUNET_assert (GNUNET_YES ==
513 GNUNET_CONTAINER_multihashmap_remove (plugin->session_map,
514 &s->target.hashPubKey,
516 GNUNET_STATISTICS_set (plugin->env->stats,
517 "# UNIX sessions active",
518 GNUNET_CONTAINER_multihashmap_size (plugin->session_map),
520 if ((GNUNET_YES == removed) && (NULL == plugin->msg_head))
521 reschedule_select (plugin);
522 if (GNUNET_SCHEDULER_NO_TASK != s->timeout_task)
524 GNUNET_SCHEDULER_cancel (s->timeout_task);
525 s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
532 * Actually send out the message, assume we've got the address and
533 * send_handle squared away!
536 * @param send_handle which handle to send message on
537 * @param target who should receive this message (ignored by UNIX)
538 * @param msgbuf one or more GNUNET_MessageHeader(s) strung together
539 * @param msgbuf_size the size of the msgbuf to send
540 * @param priority how important is the message (ignored by UNIX)
541 * @param timeout when should we time out (give up) if we can not transmit?
542 * @param addr the addr to send the message to, needs to be a sockaddr for us
543 * @param addrlen the len of addr
544 * @param payload bytes payload to send
545 * @param cont continuation to call once the message has
546 * been transmitted (or if the transport is ready
547 * for the next transmission call; or if the
548 * peer disconnected...)
549 * @param cont_cls closure for cont
550 * @return on success the number of bytes written, RETRY for retry, -1 on errors
553 unix_real_send (void *cls,
554 struct GNUNET_NETWORK_Handle *send_handle,
555 const struct GNUNET_PeerIdentity *target, const char *msgbuf,
556 size_t msgbuf_size, unsigned int priority,
557 struct GNUNET_TIME_Absolute timeout,
558 const struct UnixAddress *addr,
561 GNUNET_TRANSPORT_TransmitContinuation cont,
564 struct Plugin *plugin = cls;
568 struct sockaddr_un un;
570 const char *unix_path;
573 GNUNET_assert (NULL != plugin);
574 if (NULL == send_handle)
576 GNUNET_break (0); /* We do not have a send handle */
577 return GNUNET_SYSERR;
579 if ((NULL == addr) || (0 == addrlen))
581 GNUNET_break (0); /* Can never send if we don't have an address */
582 return GNUNET_SYSERR;
585 /* Prepare address */
586 unix_path = (const char *) &addr[1];
587 memset (&un, 0, sizeof (un));
588 un.sun_family = AF_UNIX;
589 slen = strlen (unix_path);
590 if (slen >= sizeof (un.sun_path))
591 slen = sizeof (un.sun_path) - 1;
592 GNUNET_assert (slen < sizeof (un.sun_path));
593 memcpy (un.sun_path, unix_path, slen);
594 un.sun_path[slen] = '\0';
595 slen = sizeof (struct sockaddr_un);
597 un.sun_path[0] = '\0';
599 #if HAVE_SOCKADDR_IN_SIN_LEN
600 un.sun_len = (u_char) slen;
602 sb = (struct sockaddr *) &un;
608 sent = GNUNET_NETWORK_socket_sendto (send_handle, msgbuf, msgbuf_size, sb, sbs);
610 if (GNUNET_SYSERR == sent)
612 if ( (EAGAIN == errno) ||
614 return RETRY; /* We have to retry later */
615 if (EMSGSIZE == errno)
618 socklen_t len = sizeof (size);
620 GNUNET_NETWORK_socket_getsockopt ((struct GNUNET_NETWORK_Handle *)
621 send_handle, SOL_SOCKET, SO_SNDBUF, &size,
623 if (size < msgbuf_size)
625 LOG (GNUNET_ERROR_TYPE_DEBUG,
626 "Trying to increase socket buffer size from %i to %i for message size %i\n",
627 size, ((msgbuf_size / 1000) + 2) * 1000, msgbuf_size);
628 size = ((msgbuf_size / 1000) + 2) * 1000;
629 if (GNUNET_OK == GNUNET_NETWORK_socket_setsockopt
630 ((struct GNUNET_NETWORK_Handle *) send_handle, SOL_SOCKET, SO_SNDBUF,
631 &size, sizeof (size)))
632 goto resend; /* Increased buffer size, retry sending */
635 /* Could not increase buffer size: error, no retry */
636 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "setsockopt");
637 return GNUNET_SYSERR;
642 /* Buffer is bigger than message: error, no retry
643 * This should never happen!*/
645 return GNUNET_SYSERR;
650 LOG (GNUNET_ERROR_TYPE_DEBUG,
651 "UNIX transmit %u-byte message to %s (%d: %s)\n",
652 (unsigned int) msgbuf_size,
653 GNUNET_a2s (sb, sbs),
655 (sent < 0) ? STRERROR (errno) : "ok");
661 * Closure for 'get_session_it'.
663 struct GetSessionIteratorContext
666 * Location to store the session, if found.
671 * Address information.
676 * Number of bytes in 'address'
683 * Function called to find a session by address.
685 * @param cls the 'struct LookupCtx'
686 * @param key peer we are looking for (unused)
687 * @param value a session
688 * @return GNUNET_YES if not found (continue looking), GNUNET_NO on success
691 get_session_it (void *cls,
692 const struct GNUNET_HashCode *key,
695 struct GetSessionIteratorContext *gsi = cls;
696 struct Session *s = value;
698 if ( (gsi->addrlen == s->addrlen) &&
699 (0 == memcmp (gsi->address, s->addr, s->addrlen)) )
709 * Session was idle for too long, so disconnect it
711 * @param cls the 'struct Session' to disconnect
712 * @param tc scheduler context
715 session_timeout (void *cls,
716 const struct GNUNET_SCHEDULER_TaskContext *tc)
718 struct Session *s = cls;
720 s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
721 LOG (GNUNET_ERROR_TYPE_DEBUG,
722 "Session %p was idle for %s, disconnecting\n",
724 GNUNET_STRINGS_relative_time_to_string (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
726 disconnect_session (s);
731 * Creates a new outbound session the transport service will use to send data to the
734 * @param cls the plugin
735 * @param address the address
736 * @return the session or NULL of max connections exceeded
738 static struct Session *
739 unix_plugin_get_session (void *cls,
740 const struct GNUNET_HELLO_Address *address)
742 struct Plugin *plugin = cls;
744 struct GetSessionIteratorContext gsi;
745 struct UnixAddress *ua;
747 uint32_t addr_str_len;
749 GNUNET_assert (NULL != plugin);
750 GNUNET_assert (NULL != address);
752 ua = (struct UnixAddress *) address->address;
753 if ((NULL == address->address) || (0 == address->address_length) ||
754 (sizeof (struct UnixAddress) > address->address_length))
759 addrstr = (char *) &ua[1];
760 addr_str_len = ntohl (ua->addrlen);
761 if (addr_str_len != address->address_length - sizeof (struct UnixAddress))
763 /* This can be a legacy address */
767 if ('\0' != addrstr[addr_str_len - 1])
772 if (strlen (addrstr) + 1 != addr_str_len)
778 /* Check if already existing */
779 gsi.address = (const char *) address->address;
780 gsi.addrlen = address->address_length;
782 GNUNET_CONTAINER_multihashmap_get_multiple (plugin->session_map,
783 &address->peer.hashPubKey,
784 &get_session_it, &gsi);
787 LOG (GNUNET_ERROR_TYPE_DEBUG,
788 "Found existing session\n");
792 /* create a new session */
793 s = GNUNET_malloc (sizeof (struct Session) + address->address_length);
794 s->addr = (struct UnixAddress *) &s[1];
795 s->addrlen = address->address_length;
797 memcpy (s->addr, address->address, address->address_length);
798 memcpy (&s->target, &address->peer, sizeof (struct GNUNET_PeerIdentity));
799 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == s->timeout_task);
800 s->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
803 LOG (GNUNET_ERROR_TYPE_DEBUG,
804 "Creating a new session %p for address `%s'\n",
805 s, unix_address_to_string (NULL, address->address, address->address_length));
806 (void) GNUNET_CONTAINER_multihashmap_put (plugin->session_map,
807 &address->peer.hashPubKey, s,
808 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
809 GNUNET_STATISTICS_set (plugin->env->stats,
810 "# UNIX sessions active",
811 GNUNET_CONTAINER_multihashmap_size (plugin->session_map),
818 * Function that can be used by the transport service to transmit
819 * a message using the plugin. Note that in the case of a
820 * peer disconnecting, the continuation MUST be called
821 * prior to the disconnect notification itself. This function
822 * will be called with this peer's HELLO message to initiate
823 * a fresh connection to another peer.
826 * @param session which session must be used
827 * @param msgbuf the message to transmit
828 * @param msgbuf_size number of bytes in 'msgbuf'
829 * @param priority how important is the message (most plugins will
830 * ignore message priority and just FIFO)
831 * @param to how long to wait at most for the transmission (does not
832 * require plugins to discard the message after the timeout,
833 * just advisory for the desired delay; most plugins will ignore
835 * @param cont continuation to call once the message has
836 * been transmitted (or if the transport is ready
837 * for the next transmission call; or if the
838 * peer disconnected...); can be NULL
839 * @param cont_cls closure for cont
840 * @return number of bytes used (on the physical network, with overheads);
841 * -1 on hard errors (i.e. address invalid); 0 is a legal value
842 * and does NOT mean that the message was not transmitted (DV)
845 unix_plugin_send (void *cls,
846 struct Session *session,
847 const char *msgbuf, size_t msgbuf_size,
848 unsigned int priority,
849 struct GNUNET_TIME_Relative to,
850 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
852 struct Plugin *plugin = cls;
853 struct UNIXMessageWrapper *wrapper;
854 struct UNIXMessage *message;
857 GNUNET_assert (NULL != plugin);
858 GNUNET_assert (NULL != session);
861 GNUNET_CONTAINER_multihashmap_contains_value (plugin->session_map,
862 &session->target.hashPubKey,
865 LOG (GNUNET_ERROR_TYPE_ERROR,
866 "Invalid session for peer `%s' `%s'\n",
867 GNUNET_i2s (&session->target),
868 (const char *) session->addr);
870 return GNUNET_SYSERR;
872 LOG (GNUNET_ERROR_TYPE_DEBUG,
873 "Sending %u bytes with session for peer `%s' `%s'\n",
875 GNUNET_i2s (&session->target),
876 (const char *) session->addr);
877 ssize = sizeof (struct UNIXMessage) + msgbuf_size;
878 message = GNUNET_malloc (sizeof (struct UNIXMessage) + msgbuf_size);
879 message->header.size = htons (ssize);
880 message->header.type = htons (0);
881 memcpy (&message->sender, plugin->env->my_identity,
882 sizeof (struct GNUNET_PeerIdentity));
883 memcpy (&message[1], msgbuf, msgbuf_size);
884 reschedule_session_timeout (session);
885 wrapper = GNUNET_malloc (sizeof (struct UNIXMessageWrapper));
886 wrapper->msg = message;
887 wrapper->msgsize = ssize;
888 wrapper->payload = msgbuf_size;
889 wrapper->priority = priority;
890 wrapper->timeout = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(), to);
891 wrapper->cont = cont;
892 wrapper->cont_cls = cont_cls;
893 wrapper->session = session;
894 GNUNET_CONTAINER_DLL_insert (plugin->msg_head,
897 plugin->bytes_in_queue += ssize;
898 GNUNET_STATISTICS_set (plugin->env->stats,
899 "# bytes currently in UNIX buffers",
900 plugin->bytes_in_queue,
902 if (GNUNET_NO == plugin->with_ws)
903 reschedule_select (plugin);
909 * Demultiplexer for UNIX messages
911 * @param plugin the main plugin for this transport
912 * @param sender from which peer the message was received
913 * @param currhdr pointer to the header of the message
914 * @param ua address to look for
915 * @param ua_len length of the address
918 unix_demultiplexer (struct Plugin *plugin, struct GNUNET_PeerIdentity *sender,
919 const struct GNUNET_MessageHeader *currhdr,
920 const struct UnixAddress *ua, size_t ua_len)
922 struct Session *s = NULL;
923 struct GNUNET_HELLO_Address * addr;
925 GNUNET_break (ntohl(plugin->ats_network.value) != GNUNET_ATS_NET_UNSPECIFIED);
927 GNUNET_assert (ua_len >= sizeof (struct UnixAddress));
929 LOG (GNUNET_ERROR_TYPE_DEBUG,
930 "Received message from %s\n",
931 unix_address_to_string(NULL, ua, ua_len));
932 GNUNET_STATISTICS_update (plugin->env->stats,
933 "# bytes received via UNIX",
934 ntohs (currhdr->size),
937 addr = GNUNET_HELLO_address_allocate (sender,
941 s = lookup_session (plugin, sender, ua, ua_len);
943 s = unix_plugin_get_session (plugin, addr);
944 reschedule_session_timeout (s);
946 plugin->env->receive (plugin->env->cls, sender, currhdr,
947 s, (const char *) ua, ua_len);
949 plugin->env->update_address_metrics (plugin->env->cls,
951 (const char *) ua, ua_len,
953 &plugin->ats_network, 1);
960 * Read from UNIX domain socket (it is ready).
962 * @param plugin the plugin
965 unix_plugin_select_read (struct Plugin *plugin)
967 char buf[65536] GNUNET_ALIGN;
968 struct UnixAddress *ua;
969 struct UNIXMessage *msg;
970 struct GNUNET_PeerIdentity sender;
971 struct sockaddr_un un;
977 const struct GNUNET_MessageHeader *currhdr;
981 addrlen = sizeof (un);
982 memset (&un, 0, sizeof (un));
985 GNUNET_NETWORK_socket_recvfrom (plugin->unix_sock.desc, buf, sizeof (buf),
986 (struct sockaddr *) &un, &addrlen);
988 if ((GNUNET_SYSERR == ret) && ((errno == EAGAIN) || (errno == ENOBUFS)))
991 if (ret == GNUNET_SYSERR)
993 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "recvfrom");
999 un.sun_path[0] = '/';
1001 LOG (GNUNET_ERROR_TYPE_DEBUG, "Read %d bytes from socket %s\n", ret,
1005 GNUNET_assert (AF_UNIX == (un.sun_family));
1006 ua_len = sizeof (struct UnixAddress) + strlen (&un.sun_path[0]) +1;
1007 ua = GNUNET_malloc (ua_len);
1008 ua->addrlen = htonl (strlen (&un.sun_path[0]) +1);
1009 ua->options = htonl (0);
1010 memcpy (&ua[1], &un.sun_path[0], strlen (&un.sun_path[0]) +1);
1012 msg = (struct UNIXMessage *) buf;
1013 csize = ntohs (msg->header.size);
1014 if ((csize < sizeof (struct UNIXMessage)) || (csize > ret))
1016 GNUNET_break_op (0);
1019 msgbuf = (char *) &msg[1];
1020 memcpy (&sender, &msg->sender, sizeof (struct GNUNET_PeerIdentity));
1022 tsize = csize - sizeof (struct UNIXMessage);
1023 while (offset + sizeof (struct GNUNET_MessageHeader) <= tsize)
1025 currhdr = (struct GNUNET_MessageHeader *) &msgbuf[offset];
1026 csize = ntohs (currhdr->size);
1027 if ((csize < sizeof (struct GNUNET_MessageHeader)) ||
1028 (csize > tsize - offset))
1030 GNUNET_break_op (0);
1033 unix_demultiplexer (plugin, &sender, currhdr, ua, ua_len);
1041 * Write to UNIX domain socket (it is ready).
1043 * @param plugin the plugin
1046 unix_plugin_select_write (struct Plugin *plugin)
1049 struct UNIXMessageWrapper * msgw;
1051 while (NULL != (msgw = plugin->msg_tail))
1053 if (GNUNET_TIME_absolute_get_remaining (msgw->timeout).rel_value > 0)
1054 break; /* Message is ready for sending */
1055 /* Message has a timeout */
1056 LOG (GNUNET_ERROR_TYPE_DEBUG,
1057 "Timeout for message with %u bytes \n",
1058 (unsigned int) msgw->msgsize);
1059 GNUNET_CONTAINER_DLL_remove (plugin->msg_head, plugin->msg_tail, msgw);
1060 plugin->bytes_in_queue -= msgw->msgsize;
1061 GNUNET_STATISTICS_set (plugin->env->stats,
1062 "# bytes currently in UNIX buffers",
1063 plugin->bytes_in_queue, GNUNET_NO);
1064 GNUNET_STATISTICS_update (plugin->env->stats,
1065 "# UNIX bytes discarded",
1068 if (NULL != msgw->cont)
1069 msgw->cont (msgw->cont_cls,
1070 &msgw->session->target,
1074 GNUNET_free (msgw->msg);
1078 return; /* Nothing to send at the moment */
1080 sent = unix_real_send (plugin,
1081 plugin->unix_sock.desc,
1082 &msgw->session->target,
1083 (const char *) msgw->msg,
1087 msgw->session->addr,
1088 msgw->session->addrlen,
1090 msgw->cont, msgw->cont_cls);
1094 GNUNET_STATISTICS_update (plugin->env->stats,
1095 "# UNIX retry attempts",
1099 if (GNUNET_SYSERR == sent)
1101 /* failed and no retry */
1102 if (NULL != msgw->cont)
1103 msgw->cont (msgw->cont_cls, &msgw->session->target, GNUNET_SYSERR, msgw->payload, 0);
1105 GNUNET_CONTAINER_DLL_remove(plugin->msg_head, plugin->msg_tail, msgw);
1107 GNUNET_assert (plugin->bytes_in_queue >= msgw->msgsize);
1108 plugin->bytes_in_queue -= msgw->msgsize;
1109 GNUNET_STATISTICS_set (plugin->env->stats,
1110 "# bytes currently in UNIX buffers",
1111 plugin->bytes_in_queue, GNUNET_NO);
1112 GNUNET_STATISTICS_update (plugin->env->stats,
1113 "# UNIX bytes discarded",
1117 GNUNET_free (msgw->msg);
1121 /* successfully sent bytes */
1122 GNUNET_break (sent > 0);
1123 GNUNET_CONTAINER_DLL_remove (plugin->msg_head,
1126 GNUNET_assert (plugin->bytes_in_queue >= msgw->msgsize);
1127 plugin->bytes_in_queue -= msgw->msgsize;
1128 GNUNET_STATISTICS_set (plugin->env->stats,
1129 "# bytes currently in UNIX buffers",
1130 plugin->bytes_in_queue,
1132 GNUNET_STATISTICS_update (plugin->env->stats,
1133 "# bytes transmitted via UNIX",
1136 if (NULL != msgw->cont)
1137 msgw->cont (msgw->cont_cls, &msgw->session->target,
1141 GNUNET_free (msgw->msg);
1147 * We have been notified that our writeset has something to read. We don't
1148 * know which socket needs to be read, so we have to check each one
1149 * Then reschedule this function to be called again once more is available.
1151 * @param cls the plugin handle
1152 * @param tc the scheduling context (for rescheduling this function again)
1155 unix_plugin_select (void *cls,
1156 const struct GNUNET_SCHEDULER_TaskContext *tc)
1158 struct Plugin *plugin = cls;
1160 plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
1161 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
1164 if ((tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY) != 0)
1166 /* Ready to send data */
1167 GNUNET_assert (GNUNET_NETWORK_fdset_isset
1168 (tc->write_ready, plugin->unix_sock.desc));
1169 if (NULL != plugin->msg_head)
1170 unix_plugin_select_write (plugin);
1173 if ((tc->reason & GNUNET_SCHEDULER_REASON_READ_READY) != 0)
1175 /* Ready to receive data */
1176 GNUNET_assert (GNUNET_NETWORK_fdset_isset
1177 (tc->read_ready, plugin->unix_sock.desc));
1178 unix_plugin_select_read (plugin);
1180 reschedule_select (plugin);
1185 * Create a slew of UNIX sockets. If possible, use IPv6 and IPv4.
1187 * @param cls closure for server start, should be a struct Plugin *
1188 * @return number of sockets created or GNUNET_SYSERR on error
1191 unix_transport_server_start (void *cls)
1193 struct Plugin *plugin = cls;
1194 struct sockaddr *serverAddr;
1196 struct sockaddr_un un;
1199 memset (&un, 0, sizeof (un));
1200 un.sun_family = AF_UNIX;
1201 slen = strlen (plugin->unix_socket_path) + 1;
1202 if (slen >= sizeof (un.sun_path))
1203 slen = sizeof (un.sun_path) - 1;
1205 memcpy (un.sun_path, plugin->unix_socket_path, slen);
1206 un.sun_path[slen] = '\0';
1207 slen = sizeof (struct sockaddr_un);
1208 #if HAVE_SOCKADDR_IN_SIN_LEN
1209 un.sun_len = (u_char) slen;
1212 serverAddr = (struct sockaddr *) &un;
1215 un.sun_path[0] = '\0';
1217 plugin->ats_network = plugin->env->get_address_type (plugin->env->cls, serverAddr, addrlen);
1218 plugin->unix_sock.desc =
1219 GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_DGRAM, 0);
1220 if (NULL == plugin->unix_sock.desc)
1222 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
1223 return GNUNET_SYSERR;
1225 if (GNUNET_NETWORK_socket_bind (plugin->unix_sock.desc, serverAddr, addrlen, 0)
1228 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
1229 GNUNET_NETWORK_socket_close (plugin->unix_sock.desc);
1230 plugin->unix_sock.desc = NULL;
1231 return GNUNET_SYSERR;
1233 LOG (GNUNET_ERROR_TYPE_DEBUG, "Bound to `%s'\n", plugin->unix_socket_path);
1234 plugin->rs = GNUNET_NETWORK_fdset_create ();
1235 plugin->ws = GNUNET_NETWORK_fdset_create ();
1236 GNUNET_NETWORK_fdset_zero (plugin->rs);
1237 GNUNET_NETWORK_fdset_zero (plugin->ws);
1238 GNUNET_NETWORK_fdset_set (plugin->rs, plugin->unix_sock.desc);
1239 GNUNET_NETWORK_fdset_set (plugin->ws, plugin->unix_sock.desc);
1241 reschedule_select (plugin);
1248 * Function called for a quick conversion of the binary address to
1249 * a numeric address. Note that the caller must not free the
1250 * address and that the next call to this function is allowed
1251 * to override the address again.
1253 * @param cls closure
1254 * @param addr binary address
1255 * @param addrlen length of the address
1256 * @return string representing the same address
1259 unix_address_to_string (void *cls, const void *addr, size_t addrlen)
1261 static char rbuf[1024];
1262 struct UnixAddress *ua = (struct UnixAddress *) addr;
1265 size_t addr_str_len;
1267 if ((NULL == addr) || (0 == addrlen) || (sizeof (struct UnixAddress) > addrlen))
1272 addrstr = (char *) &ua[1];
1273 addr_str_len = ntohl (ua->addrlen);
1275 if (addr_str_len != addrlen - sizeof (struct UnixAddress))
1281 if ('\0' != addrstr[addr_str_len - 1])
1286 if (strlen (addrstr) + 1 != addr_str_len)
1292 GNUNET_asprintf(&tmp, "%s.%u.%s", PLUGIN_NAME, ntohl (ua->options), addrstr);
1293 memcpy (rbuf, tmp, strlen (tmp) + 1);
1299 * Function that will be called to check if a binary address for this
1300 * plugin is well-formed and corresponds to an address for THIS peer
1301 * (as per our configuration). Naturally, if absolutely necessary,
1302 * plugins can be a bit conservative in their answer, but in general
1303 * plugins should make sure that the address does not redirect
1304 * traffic to a 3rd party that might try to man-in-the-middle our
1307 * @param cls closure, should be our handle to the Plugin
1308 * @param addr pointer to the address
1309 * @param addrlen length of addr
1310 * @return GNUNET_OK if this is a plausible address for this peer
1311 * and transport, GNUNET_SYSERR if not
1315 unix_check_address (void *cls, const void *addr, size_t addrlen)
1317 struct Plugin* plugin = cls;
1318 struct UnixAddress *ua = (struct UnixAddress *) addr;
1320 size_t addr_str_len;
1322 if ((NULL == addr) || (0 == addrlen) || (sizeof (struct UnixAddress) > addrlen))
1325 return GNUNET_SYSERR;
1327 addrstr = (char *) &ua[1];
1328 addr_str_len = ntohl (ua->addrlen);
1329 if ('\0' != addrstr[addr_str_len - 1])
1332 return GNUNET_SYSERR;
1334 if (strlen (addrstr) + 1 != addr_str_len)
1337 return GNUNET_SYSERR;
1340 if (0 == strcmp (plugin->unix_socket_path, addrstr))
1342 return GNUNET_SYSERR;
1347 * Convert the transports address to a nice, human-readable
1350 * @param cls closure
1351 * @param type name of the transport that generated the address
1352 * @param addr one of the addresses of the host, NULL for the last address
1353 * the specific address format depends on the transport
1354 * @param addrlen length of the address
1355 * @param numeric should (IP) addresses be displayed in numeric form?
1356 * @param timeout after how long should we give up?
1357 * @param asc function to call on each string
1358 * @param asc_cls closure for asc
1361 unix_plugin_address_pretty_printer (void *cls, const char *type,
1362 const void *addr, size_t addrlen,
1364 struct GNUNET_TIME_Relative timeout,
1365 GNUNET_TRANSPORT_AddressStringCallback asc,
1368 if ((NULL != addr) && (addrlen > 0))
1370 asc (asc_cls, unix_address_to_string (NULL, addr, addrlen));
1375 asc (asc_cls, "<invalid UNIX address>");
1377 asc (asc_cls, NULL);
1382 * Function called to convert a string address to
1385 * @param cls closure ('struct Plugin*')
1386 * @param addr string address
1387 * @param addrlen length of the address (strlen(addr) + '\0')
1388 * @param buf location to store the buffer
1389 * If the function returns GNUNET_SYSERR, its contents are undefined.
1390 * @param added length of created address
1391 * @return GNUNET_OK on success, GNUNET_SYSERR on failure
1394 unix_string_to_address (void *cls, const char *addr, uint16_t addrlen,
1395 void **buf, size_t *added)
1397 struct UnixAddress *ua;
1404 /* Format unix.options.address */
1409 if ((NULL == addr) || (addrlen == 0))
1412 return GNUNET_SYSERR;
1414 if ('\0' != addr[addrlen - 1])
1417 return GNUNET_SYSERR;
1419 if (strlen (addr) != addrlen - 1)
1422 return GNUNET_SYSERR;
1424 plugin = GNUNET_strdup (addr);
1425 optionstr = strchr (plugin, '.');
1426 if (NULL == optionstr)
1429 GNUNET_free (plugin);
1430 return GNUNET_SYSERR;
1432 optionstr[0] = '\0';
1434 options = atol (optionstr);
1435 address = strchr (optionstr, '.');
1436 if (NULL == address)
1439 GNUNET_free (plugin);
1440 return GNUNET_SYSERR;
1444 if (0 != strcmp(plugin, PLUGIN_NAME))
1447 GNUNET_free (plugin);
1448 return GNUNET_SYSERR;
1451 ua_size = sizeof (struct UnixAddress) + strlen (address) + 1;
1452 ua = GNUNET_malloc (ua_size);
1453 ua->options = htonl (options);
1454 ua->addrlen = htonl (strlen (address) + 1);
1455 memcpy (&ua[1], address, strlen (address) + 1);
1456 GNUNET_free (plugin);
1465 * Notify transport service about address
1467 * @param cls the plugin
1471 address_notification (void *cls,
1472 const struct GNUNET_SCHEDULER_TaskContext *tc)
1474 struct Plugin *plugin = cls;
1476 struct UnixAddress *ua;
1478 len = sizeof (struct UnixAddress) + strlen (plugin->unix_socket_path) + 1;
1479 ua = GNUNET_malloc (len);
1480 ua->options = htonl (myoptions);
1481 ua->addrlen = htonl(strlen (plugin->unix_socket_path) + 1);
1482 memcpy (&ua[1], plugin->unix_socket_path, strlen (plugin->unix_socket_path) + 1);
1484 plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1485 plugin->env->notify_address (plugin->env->cls, GNUNET_YES,
1492 * Increment session timeout due to activity
1494 * @param s session for which the timeout should be moved
1497 reschedule_session_timeout (struct Session *s)
1499 GNUNET_assert (NULL != s);
1500 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != s->timeout_task);
1501 GNUNET_SCHEDULER_cancel (s->timeout_task);
1502 s->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1505 LOG (GNUNET_ERROR_TYPE_DEBUG,
1506 "Timeout rescheduled for session %p set to %s\n",
1508 GNUNET_STRINGS_relative_time_to_string (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1514 * Function called on sessions to disconnect
1516 * @param cls the plugin (unused)
1517 * @param key peer identity (unused)
1518 * @param value the 'struct Session' to disconnect
1519 * @return GNUNET_YES (always, continue to iterate)
1522 get_session_delete_it (void *cls, const struct GNUNET_HashCode * key, void *value)
1524 struct Session *s = value;
1526 disconnect_session (s);
1532 * Disconnect from a remote node. Clean up session if we have one for this peer
1534 * @param cls closure for this call (should be handle to Plugin)
1535 * @param target the peeridentity of the peer to disconnect
1536 * @return GNUNET_OK on success, GNUNET_SYSERR if the operation failed
1539 unix_disconnect (void *cls,
1540 const struct GNUNET_PeerIdentity *target)
1542 struct Plugin *plugin = cls;
1544 GNUNET_assert (plugin != NULL);
1545 GNUNET_CONTAINER_multihashmap_get_multiple (plugin->session_map,
1546 &target->hashPubKey,
1547 &get_session_delete_it, plugin);
1552 * The exported method. Initializes the plugin and returns a
1553 * struct with the callbacks.
1555 * @param cls the plugin's execution environment
1556 * @return NULL on error, plugin functions otherwise
1559 libgnunet_plugin_transport_unix_init (void *cls)
1561 struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1562 unsigned long long port;
1563 struct GNUNET_TRANSPORT_PluginFunctions *api;
1564 struct Plugin *plugin;
1565 int sockets_created;
1567 if (NULL == env->receive)
1569 /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
1570 initialze the plugin or the API */
1571 api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1573 api->address_pretty_printer = &unix_plugin_address_pretty_printer;
1574 api->address_to_string = &unix_address_to_string;
1575 api->string_to_address = &unix_string_to_address;
1579 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-unix", "PORT",
1581 port = UNIX_NAT_DEFAULT_PORT;
1582 plugin = GNUNET_malloc (sizeof (struct Plugin));
1583 plugin->port = port;
1585 GNUNET_asprintf (&plugin->unix_socket_path,
1586 "/tmp/unix-plugin-sock.%d",
1589 /* Initialize my flags */
1592 api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1595 api->get_session = &unix_plugin_get_session;
1596 api->send = &unix_plugin_send;
1597 api->disconnect = &unix_disconnect;
1598 api->address_pretty_printer = &unix_plugin_address_pretty_printer;
1599 api->address_to_string = &unix_address_to_string;
1600 api->check_address = &unix_check_address;
1601 api->string_to_address = &unix_string_to_address;
1602 sockets_created = unix_transport_server_start (plugin);
1603 if (0 == sockets_created)
1604 LOG (GNUNET_ERROR_TYPE_WARNING,
1605 _("Failed to open UNIX listen socket\n"));
1606 plugin->session_map = GNUNET_CONTAINER_multihashmap_create (10, GNUNET_NO);
1607 plugin->address_update_task = GNUNET_SCHEDULER_add_now (&address_notification, plugin);
1613 * Shutdown the plugin.
1615 * @param cls the plugin API returned from the initialization function
1616 * @return NULL (always)
1619 libgnunet_plugin_transport_unix_done (void *cls)
1621 struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1622 struct Plugin *plugin = api->cls;
1623 struct UNIXMessageWrapper * msgw;
1624 struct UnixAddress *ua;
1633 len = sizeof (struct UnixAddress) + strlen (plugin->unix_socket_path) + 1;
1634 ua = GNUNET_malloc (len);
1635 ua->options = htonl (myoptions);
1636 ua->addrlen = htonl(strlen (plugin->unix_socket_path) + 1);
1637 memcpy (&ua[1], plugin->unix_socket_path, strlen (plugin->unix_socket_path) + 1);
1639 plugin->env->notify_address (plugin->env->cls, GNUNET_NO,
1642 while (NULL != (msgw = plugin->msg_head))
1644 GNUNET_CONTAINER_DLL_remove (plugin->msg_head, plugin->msg_tail, msgw);
1645 if (msgw->cont != NULL)
1646 msgw->cont (msgw->cont_cls, &msgw->session->target, GNUNET_SYSERR,
1648 GNUNET_free (msgw->msg);
1652 if (GNUNET_SCHEDULER_NO_TASK != plugin->select_task)
1654 GNUNET_SCHEDULER_cancel (plugin->select_task);
1655 plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
1657 if (GNUNET_SCHEDULER_NO_TASK != plugin->address_update_task)
1659 GNUNET_SCHEDULER_cancel (plugin->address_update_task);
1660 plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1662 if (NULL != plugin->unix_sock.desc)
1664 GNUNET_break (GNUNET_OK ==
1665 GNUNET_NETWORK_socket_close (plugin->unix_sock.desc));
1666 plugin->unix_sock.desc = NULL;
1667 plugin->with_ws = GNUNET_NO;
1669 GNUNET_CONTAINER_multihashmap_iterate (plugin->session_map,
1670 &get_session_delete_it, plugin);
1671 GNUNET_CONTAINER_multihashmap_destroy (plugin->session_map);
1672 if (NULL != plugin->rs)
1673 GNUNET_NETWORK_fdset_destroy (plugin->rs);
1674 if (NULL != plugin->ws)
1675 GNUNET_NETWORK_fdset_destroy (plugin->ws);
1676 GNUNET_free (plugin->unix_socket_path);
1677 GNUNET_free (plugin);
1682 /* end of plugin_transport_unix.c */