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);
730 * Function obtain the network type for a session
732 * @param cls closure ('struct Plugin*')
733 * @param session the session
734 * @return the network type in HBO or GNUNET_SYSERR
736 static enum GNUNET_ATS_Network_Type
737 unix_get_network (void *cls, void *session)
739 GNUNET_assert (NULL != session);
740 return GNUNET_ATS_NET_LOOPBACK;
745 * Creates a new outbound session the transport service will use to send data to the
748 * @param cls the plugin
749 * @param address the address
750 * @return the session or NULL of max connections exceeded
752 static struct Session *
753 unix_plugin_get_session (void *cls,
754 const struct GNUNET_HELLO_Address *address)
756 struct Plugin *plugin = cls;
758 struct GetSessionIteratorContext gsi;
759 struct UnixAddress *ua;
761 uint32_t addr_str_len;
763 GNUNET_assert (NULL != plugin);
764 GNUNET_assert (NULL != address);
766 ua = (struct UnixAddress *) address->address;
767 if ((NULL == address->address) || (0 == address->address_length) ||
768 (sizeof (struct UnixAddress) > address->address_length))
773 addrstr = (char *) &ua[1];
774 addr_str_len = ntohl (ua->addrlen);
775 if (addr_str_len != address->address_length - sizeof (struct UnixAddress))
777 /* This can be a legacy address */
781 if ('\0' != addrstr[addr_str_len - 1])
786 if (strlen (addrstr) + 1 != addr_str_len)
792 /* Check if already existing */
793 gsi.address = (const char *) address->address;
794 gsi.addrlen = address->address_length;
796 GNUNET_CONTAINER_multihashmap_get_multiple (plugin->session_map,
797 &address->peer.hashPubKey,
798 &get_session_it, &gsi);
801 LOG (GNUNET_ERROR_TYPE_DEBUG,
802 "Found existing session\n");
806 /* create a new session */
807 s = GNUNET_malloc (sizeof (struct Session) + address->address_length);
808 s->addr = (struct UnixAddress *) &s[1];
809 s->addrlen = address->address_length;
811 memcpy (s->addr, address->address, address->address_length);
812 memcpy (&s->target, &address->peer, sizeof (struct GNUNET_PeerIdentity));
813 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == s->timeout_task);
814 s->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
817 LOG (GNUNET_ERROR_TYPE_DEBUG,
818 "Creating a new session %p for address `%s'\n",
819 s, unix_address_to_string (NULL, address->address, address->address_length));
820 (void) GNUNET_CONTAINER_multihashmap_put (plugin->session_map,
821 &address->peer.hashPubKey, s,
822 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
823 GNUNET_STATISTICS_set (plugin->env->stats,
824 "# UNIX sessions active",
825 GNUNET_CONTAINER_multihashmap_size (plugin->session_map),
832 * Function that can be used by the transport service to transmit
833 * a message using the plugin. Note that in the case of a
834 * peer disconnecting, the continuation MUST be called
835 * prior to the disconnect notification itself. This function
836 * will be called with this peer's HELLO message to initiate
837 * a fresh connection to another peer.
840 * @param session which session must be used
841 * @param msgbuf the message to transmit
842 * @param msgbuf_size number of bytes in 'msgbuf'
843 * @param priority how important is the message (most plugins will
844 * ignore message priority and just FIFO)
845 * @param to how long to wait at most for the transmission (does not
846 * require plugins to discard the message after the timeout,
847 * just advisory for the desired delay; most plugins will ignore
849 * @param cont continuation to call once the message has
850 * been transmitted (or if the transport is ready
851 * for the next transmission call; or if the
852 * peer disconnected...); can be NULL
853 * @param cont_cls closure for cont
854 * @return number of bytes used (on the physical network, with overheads);
855 * -1 on hard errors (i.e. address invalid); 0 is a legal value
856 * and does NOT mean that the message was not transmitted (DV)
859 unix_plugin_send (void *cls,
860 struct Session *session,
861 const char *msgbuf, size_t msgbuf_size,
862 unsigned int priority,
863 struct GNUNET_TIME_Relative to,
864 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
866 struct Plugin *plugin = cls;
867 struct UNIXMessageWrapper *wrapper;
868 struct UNIXMessage *message;
871 GNUNET_assert (NULL != plugin);
872 GNUNET_assert (NULL != session);
875 GNUNET_CONTAINER_multihashmap_contains_value (plugin->session_map,
876 &session->target.hashPubKey,
879 LOG (GNUNET_ERROR_TYPE_ERROR,
880 "Invalid session for peer `%s' `%s'\n",
881 GNUNET_i2s (&session->target),
882 (const char *) session->addr);
884 return GNUNET_SYSERR;
886 LOG (GNUNET_ERROR_TYPE_DEBUG,
887 "Sending %u bytes with session for peer `%s' `%s'\n",
889 GNUNET_i2s (&session->target),
890 (const char *) session->addr);
891 ssize = sizeof (struct UNIXMessage) + msgbuf_size;
892 message = GNUNET_malloc (sizeof (struct UNIXMessage) + msgbuf_size);
893 message->header.size = htons (ssize);
894 message->header.type = htons (0);
895 memcpy (&message->sender, plugin->env->my_identity,
896 sizeof (struct GNUNET_PeerIdentity));
897 memcpy (&message[1], msgbuf, msgbuf_size);
898 reschedule_session_timeout (session);
899 wrapper = GNUNET_malloc (sizeof (struct UNIXMessageWrapper));
900 wrapper->msg = message;
901 wrapper->msgsize = ssize;
902 wrapper->payload = msgbuf_size;
903 wrapper->priority = priority;
904 wrapper->timeout = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(), to);
905 wrapper->cont = cont;
906 wrapper->cont_cls = cont_cls;
907 wrapper->session = session;
908 GNUNET_CONTAINER_DLL_insert (plugin->msg_head,
911 plugin->bytes_in_queue += ssize;
912 GNUNET_STATISTICS_set (plugin->env->stats,
913 "# bytes currently in UNIX buffers",
914 plugin->bytes_in_queue,
916 if (GNUNET_NO == plugin->with_ws)
917 reschedule_select (plugin);
923 * Demultiplexer for UNIX messages
925 * @param plugin the main plugin for this transport
926 * @param sender from which peer the message was received
927 * @param currhdr pointer to the header of the message
928 * @param ua address to look for
929 * @param ua_len length of the address
932 unix_demultiplexer (struct Plugin *plugin, struct GNUNET_PeerIdentity *sender,
933 const struct GNUNET_MessageHeader *currhdr,
934 const struct UnixAddress *ua, size_t ua_len)
936 struct Session *s = NULL;
937 struct GNUNET_HELLO_Address * addr;
939 GNUNET_break (ntohl(plugin->ats_network.value) != GNUNET_ATS_NET_UNSPECIFIED);
941 GNUNET_assert (ua_len >= sizeof (struct UnixAddress));
943 LOG (GNUNET_ERROR_TYPE_DEBUG,
944 "Received message from %s\n",
945 unix_address_to_string(NULL, ua, ua_len));
946 GNUNET_STATISTICS_update (plugin->env->stats,
947 "# bytes received via UNIX",
948 ntohs (currhdr->size),
951 addr = GNUNET_HELLO_address_allocate (sender,
955 s = lookup_session (plugin, sender, ua, ua_len);
958 s = unix_plugin_get_session (plugin, addr);
959 /* Notify transport and ATS about new session */
960 plugin->env->session_start (NULL, sender,
961 PLUGIN_NAME, ua, ua_len, s, &plugin->ats_network, 1);
963 reschedule_session_timeout (s);
965 plugin->env->receive (plugin->env->cls, sender, currhdr,
966 s, (const char *) ua, ua_len);
968 plugin->env->update_address_metrics (plugin->env->cls,
970 (const char *) ua, ua_len,
972 &plugin->ats_network, 1);
979 * Read from UNIX domain socket (it is ready).
981 * @param plugin the plugin
984 unix_plugin_select_read (struct Plugin *plugin)
986 char buf[65536] GNUNET_ALIGN;
987 struct UnixAddress *ua;
988 struct UNIXMessage *msg;
989 struct GNUNET_PeerIdentity sender;
990 struct sockaddr_un un;
996 const struct GNUNET_MessageHeader *currhdr;
1000 addrlen = sizeof (un);
1001 memset (&un, 0, sizeof (un));
1004 GNUNET_NETWORK_socket_recvfrom (plugin->unix_sock.desc, buf, sizeof (buf),
1005 (struct sockaddr *) &un, &addrlen);
1007 if ((GNUNET_SYSERR == ret) && ((errno == EAGAIN) || (errno == ENOBUFS)))
1010 if (ret == GNUNET_SYSERR)
1012 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "recvfrom");
1018 un.sun_path[0] = '/';
1020 LOG (GNUNET_ERROR_TYPE_DEBUG, "Read %d bytes from socket %s\n", ret,
1024 GNUNET_assert (AF_UNIX == (un.sun_family));
1025 ua_len = sizeof (struct UnixAddress) + strlen (&un.sun_path[0]) +1;
1026 ua = GNUNET_malloc (ua_len);
1027 ua->addrlen = htonl (strlen (&un.sun_path[0]) +1);
1028 ua->options = htonl (0);
1029 memcpy (&ua[1], &un.sun_path[0], strlen (&un.sun_path[0]) +1);
1031 msg = (struct UNIXMessage *) buf;
1032 csize = ntohs (msg->header.size);
1033 if ((csize < sizeof (struct UNIXMessage)) || (csize > ret))
1035 GNUNET_break_op (0);
1038 msgbuf = (char *) &msg[1];
1039 memcpy (&sender, &msg->sender, sizeof (struct GNUNET_PeerIdentity));
1041 tsize = csize - sizeof (struct UNIXMessage);
1042 while (offset + sizeof (struct GNUNET_MessageHeader) <= tsize)
1044 currhdr = (struct GNUNET_MessageHeader *) &msgbuf[offset];
1045 csize = ntohs (currhdr->size);
1046 if ((csize < sizeof (struct GNUNET_MessageHeader)) ||
1047 (csize > tsize - offset))
1049 GNUNET_break_op (0);
1052 unix_demultiplexer (plugin, &sender, currhdr, ua, ua_len);
1060 * Write to UNIX domain socket (it is ready).
1062 * @param plugin the plugin
1065 unix_plugin_select_write (struct Plugin *plugin)
1068 struct UNIXMessageWrapper * msgw;
1070 while (NULL != (msgw = plugin->msg_tail))
1072 if (GNUNET_TIME_absolute_get_remaining (msgw->timeout).rel_value > 0)
1073 break; /* Message is ready for sending */
1074 /* Message has a timeout */
1075 LOG (GNUNET_ERROR_TYPE_DEBUG,
1076 "Timeout for message with %u bytes \n",
1077 (unsigned int) msgw->msgsize);
1078 GNUNET_CONTAINER_DLL_remove (plugin->msg_head, plugin->msg_tail, msgw);
1079 plugin->bytes_in_queue -= msgw->msgsize;
1080 GNUNET_STATISTICS_set (plugin->env->stats,
1081 "# bytes currently in UNIX buffers",
1082 plugin->bytes_in_queue, GNUNET_NO);
1083 GNUNET_STATISTICS_update (plugin->env->stats,
1084 "# UNIX bytes discarded",
1087 if (NULL != msgw->cont)
1088 msgw->cont (msgw->cont_cls,
1089 &msgw->session->target,
1093 GNUNET_free (msgw->msg);
1097 return; /* Nothing to send at the moment */
1099 sent = unix_real_send (plugin,
1100 plugin->unix_sock.desc,
1101 &msgw->session->target,
1102 (const char *) msgw->msg,
1106 msgw->session->addr,
1107 msgw->session->addrlen,
1109 msgw->cont, msgw->cont_cls);
1113 GNUNET_STATISTICS_update (plugin->env->stats,
1114 "# UNIX retry attempts",
1118 if (GNUNET_SYSERR == sent)
1120 /* failed and no retry */
1121 if (NULL != msgw->cont)
1122 msgw->cont (msgw->cont_cls, &msgw->session->target, GNUNET_SYSERR, msgw->payload, 0);
1124 GNUNET_CONTAINER_DLL_remove(plugin->msg_head, plugin->msg_tail, msgw);
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, GNUNET_NO);
1131 GNUNET_STATISTICS_update (plugin->env->stats,
1132 "# UNIX bytes discarded",
1136 GNUNET_free (msgw->msg);
1140 /* successfully sent bytes */
1141 GNUNET_break (sent > 0);
1142 GNUNET_CONTAINER_DLL_remove (plugin->msg_head,
1145 GNUNET_assert (plugin->bytes_in_queue >= msgw->msgsize);
1146 plugin->bytes_in_queue -= msgw->msgsize;
1147 GNUNET_STATISTICS_set (plugin->env->stats,
1148 "# bytes currently in UNIX buffers",
1149 plugin->bytes_in_queue,
1151 GNUNET_STATISTICS_update (plugin->env->stats,
1152 "# bytes transmitted via UNIX",
1155 if (NULL != msgw->cont)
1156 msgw->cont (msgw->cont_cls, &msgw->session->target,
1160 GNUNET_free (msgw->msg);
1166 * We have been notified that our writeset has something to read. We don't
1167 * know which socket needs to be read, so we have to check each one
1168 * Then reschedule this function to be called again once more is available.
1170 * @param cls the plugin handle
1171 * @param tc the scheduling context (for rescheduling this function again)
1174 unix_plugin_select (void *cls,
1175 const struct GNUNET_SCHEDULER_TaskContext *tc)
1177 struct Plugin *plugin = cls;
1179 plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
1180 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
1183 if ((tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY) != 0)
1185 /* Ready to send data */
1186 GNUNET_assert (GNUNET_NETWORK_fdset_isset
1187 (tc->write_ready, plugin->unix_sock.desc));
1188 if (NULL != plugin->msg_head)
1189 unix_plugin_select_write (plugin);
1192 if ((tc->reason & GNUNET_SCHEDULER_REASON_READ_READY) != 0)
1194 /* Ready to receive data */
1195 GNUNET_assert (GNUNET_NETWORK_fdset_isset
1196 (tc->read_ready, plugin->unix_sock.desc));
1197 unix_plugin_select_read (plugin);
1199 reschedule_select (plugin);
1204 * Create a slew of UNIX sockets. If possible, use IPv6 and IPv4.
1206 * @param cls closure for server start, should be a struct Plugin *
1207 * @return number of sockets created or GNUNET_SYSERR on error
1210 unix_transport_server_start (void *cls)
1212 struct Plugin *plugin = cls;
1213 struct sockaddr *serverAddr;
1215 struct sockaddr_un un;
1218 memset (&un, 0, sizeof (un));
1219 un.sun_family = AF_UNIX;
1220 slen = strlen (plugin->unix_socket_path) + 1;
1221 if (slen >= sizeof (un.sun_path))
1222 slen = sizeof (un.sun_path) - 1;
1224 memcpy (un.sun_path, plugin->unix_socket_path, slen);
1225 un.sun_path[slen] = '\0';
1226 slen = sizeof (struct sockaddr_un);
1227 #if HAVE_SOCKADDR_IN_SIN_LEN
1228 un.sun_len = (u_char) slen;
1231 serverAddr = (struct sockaddr *) &un;
1234 un.sun_path[0] = '\0';
1236 plugin->ats_network = plugin->env->get_address_type (plugin->env->cls, serverAddr, addrlen);
1237 plugin->unix_sock.desc =
1238 GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_DGRAM, 0);
1239 if (NULL == plugin->unix_sock.desc)
1241 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
1242 return GNUNET_SYSERR;
1244 if (GNUNET_NETWORK_socket_bind (plugin->unix_sock.desc, serverAddr, addrlen, 0)
1247 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
1248 GNUNET_NETWORK_socket_close (plugin->unix_sock.desc);
1249 plugin->unix_sock.desc = NULL;
1250 return GNUNET_SYSERR;
1252 LOG (GNUNET_ERROR_TYPE_DEBUG, "Bound to `%s'\n", plugin->unix_socket_path);
1253 plugin->rs = GNUNET_NETWORK_fdset_create ();
1254 plugin->ws = GNUNET_NETWORK_fdset_create ();
1255 GNUNET_NETWORK_fdset_zero (plugin->rs);
1256 GNUNET_NETWORK_fdset_zero (plugin->ws);
1257 GNUNET_NETWORK_fdset_set (plugin->rs, plugin->unix_sock.desc);
1258 GNUNET_NETWORK_fdset_set (plugin->ws, plugin->unix_sock.desc);
1260 reschedule_select (plugin);
1267 * Function called for a quick conversion of the binary address to
1268 * a numeric address. Note that the caller must not free the
1269 * address and that the next call to this function is allowed
1270 * to override the address again.
1272 * @param cls closure
1273 * @param addr binary address
1274 * @param addrlen length of the address
1275 * @return string representing the same address
1278 unix_address_to_string (void *cls, const void *addr, size_t addrlen)
1280 static char rbuf[1024];
1281 struct UnixAddress *ua = (struct UnixAddress *) addr;
1284 size_t addr_str_len;
1286 if ((NULL == addr) || (0 == addrlen) || (sizeof (struct UnixAddress) > addrlen))
1291 addrstr = (char *) &ua[1];
1292 addr_str_len = ntohl (ua->addrlen);
1294 if (addr_str_len != addrlen - sizeof (struct UnixAddress))
1300 if ('\0' != addrstr[addr_str_len - 1])
1305 if (strlen (addrstr) + 1 != addr_str_len)
1311 GNUNET_asprintf(&tmp, "%s.%u.%s", PLUGIN_NAME, ntohl (ua->options), addrstr);
1312 memcpy (rbuf, tmp, strlen (tmp) + 1);
1318 * Function that will be called to check if a binary address for this
1319 * plugin is well-formed and corresponds to an address for THIS peer
1320 * (as per our configuration). Naturally, if absolutely necessary,
1321 * plugins can be a bit conservative in their answer, but in general
1322 * plugins should make sure that the address does not redirect
1323 * traffic to a 3rd party that might try to man-in-the-middle our
1326 * @param cls closure, should be our handle to the Plugin
1327 * @param addr pointer to the address
1328 * @param addrlen length of addr
1329 * @return GNUNET_OK if this is a plausible address for this peer
1330 * and transport, GNUNET_SYSERR if not
1334 unix_check_address (void *cls, const void *addr, size_t addrlen)
1336 struct Plugin* plugin = cls;
1337 struct UnixAddress *ua = (struct UnixAddress *) addr;
1339 size_t addr_str_len;
1341 if ((NULL == addr) || (0 == addrlen) || (sizeof (struct UnixAddress) > addrlen))
1344 return GNUNET_SYSERR;
1346 addrstr = (char *) &ua[1];
1347 addr_str_len = ntohl (ua->addrlen);
1348 if ('\0' != addrstr[addr_str_len - 1])
1351 return GNUNET_SYSERR;
1353 if (strlen (addrstr) + 1 != addr_str_len)
1356 return GNUNET_SYSERR;
1359 if (0 == strcmp (plugin->unix_socket_path, addrstr))
1361 return GNUNET_SYSERR;
1366 * Convert the transports address to a nice, human-readable
1369 * @param cls closure
1370 * @param type name of the transport that generated the address
1371 * @param addr one of the addresses of the host, NULL for the last address
1372 * the specific address format depends on the transport
1373 * @param addrlen length of the address
1374 * @param numeric should (IP) addresses be displayed in numeric form?
1375 * @param timeout after how long should we give up?
1376 * @param asc function to call on each string
1377 * @param asc_cls closure for asc
1380 unix_plugin_address_pretty_printer (void *cls, const char *type,
1381 const void *addr, size_t addrlen,
1383 struct GNUNET_TIME_Relative timeout,
1384 GNUNET_TRANSPORT_AddressStringCallback asc,
1387 if ((NULL != addr) && (addrlen > 0))
1389 asc (asc_cls, unix_address_to_string (NULL, addr, addrlen));
1394 asc (asc_cls, "<invalid UNIX address>");
1396 asc (asc_cls, NULL);
1401 * Function called to convert a string address to
1404 * @param cls closure ('struct Plugin*')
1405 * @param addr string address
1406 * @param addrlen length of the address (strlen(addr) + '\0')
1407 * @param buf location to store the buffer
1408 * If the function returns GNUNET_SYSERR, its contents are undefined.
1409 * @param added length of created address
1410 * @return GNUNET_OK on success, GNUNET_SYSERR on failure
1413 unix_string_to_address (void *cls, const char *addr, uint16_t addrlen,
1414 void **buf, size_t *added)
1416 struct UnixAddress *ua;
1423 /* Format unix.options.address */
1428 if ((NULL == addr) || (addrlen == 0))
1431 return GNUNET_SYSERR;
1433 if ('\0' != addr[addrlen - 1])
1436 return GNUNET_SYSERR;
1438 if (strlen (addr) != addrlen - 1)
1441 return GNUNET_SYSERR;
1443 plugin = GNUNET_strdup (addr);
1444 optionstr = strchr (plugin, '.');
1445 if (NULL == optionstr)
1448 GNUNET_free (plugin);
1449 return GNUNET_SYSERR;
1451 optionstr[0] = '\0';
1453 options = atol (optionstr);
1454 address = strchr (optionstr, '.');
1455 if (NULL == address)
1458 GNUNET_free (plugin);
1459 return GNUNET_SYSERR;
1463 if (0 != strcmp(plugin, PLUGIN_NAME))
1466 GNUNET_free (plugin);
1467 return GNUNET_SYSERR;
1470 ua_size = sizeof (struct UnixAddress) + strlen (address) + 1;
1471 ua = GNUNET_malloc (ua_size);
1472 ua->options = htonl (options);
1473 ua->addrlen = htonl (strlen (address) + 1);
1474 memcpy (&ua[1], address, strlen (address) + 1);
1475 GNUNET_free (plugin);
1484 * Notify transport service about address
1486 * @param cls the plugin
1490 address_notification (void *cls,
1491 const struct GNUNET_SCHEDULER_TaskContext *tc)
1493 struct Plugin *plugin = cls;
1495 struct UnixAddress *ua;
1497 len = sizeof (struct UnixAddress) + strlen (plugin->unix_socket_path) + 1;
1498 ua = GNUNET_malloc (len);
1499 ua->options = htonl (myoptions);
1500 ua->addrlen = htonl(strlen (plugin->unix_socket_path) + 1);
1501 memcpy (&ua[1], plugin->unix_socket_path, strlen (plugin->unix_socket_path) + 1);
1503 plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1504 plugin->env->notify_address (plugin->env->cls, GNUNET_YES,
1511 * Increment session timeout due to activity
1513 * @param s session for which the timeout should be moved
1516 reschedule_session_timeout (struct Session *s)
1518 GNUNET_assert (NULL != s);
1519 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != s->timeout_task);
1520 GNUNET_SCHEDULER_cancel (s->timeout_task);
1521 s->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1524 LOG (GNUNET_ERROR_TYPE_DEBUG,
1525 "Timeout rescheduled for session %p set to %s\n",
1527 GNUNET_STRINGS_relative_time_to_string (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1533 * Function called on sessions to disconnect
1535 * @param cls the plugin (unused)
1536 * @param key peer identity (unused)
1537 * @param value the 'struct Session' to disconnect
1538 * @return GNUNET_YES (always, continue to iterate)
1541 get_session_delete_it (void *cls, const struct GNUNET_HashCode * key, void *value)
1543 struct Session *s = value;
1545 disconnect_session (s);
1551 * Disconnect from a remote node. Clean up session if we have one for this peer
1553 * @param cls closure for this call (should be handle to Plugin)
1554 * @param target the peeridentity of the peer to disconnect
1555 * @return GNUNET_OK on success, GNUNET_SYSERR if the operation failed
1558 unix_disconnect (void *cls,
1559 const struct GNUNET_PeerIdentity *target)
1561 struct Plugin *plugin = cls;
1563 GNUNET_assert (plugin != NULL);
1564 GNUNET_CONTAINER_multihashmap_get_multiple (plugin->session_map,
1565 &target->hashPubKey,
1566 &get_session_delete_it, plugin);
1571 * The exported method. Initializes the plugin and returns a
1572 * struct with the callbacks.
1574 * @param cls the plugin's execution environment
1575 * @return NULL on error, plugin functions otherwise
1578 libgnunet_plugin_transport_unix_init (void *cls)
1580 struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1581 unsigned long long port;
1582 struct GNUNET_TRANSPORT_PluginFunctions *api;
1583 struct Plugin *plugin;
1584 int sockets_created;
1586 if (NULL == env->receive)
1588 /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
1589 initialze the plugin or the API */
1590 api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1592 api->address_pretty_printer = &unix_plugin_address_pretty_printer;
1593 api->address_to_string = &unix_address_to_string;
1594 api->string_to_address = &unix_string_to_address;
1598 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-unix", "PORT",
1600 port = UNIX_NAT_DEFAULT_PORT;
1601 plugin = GNUNET_malloc (sizeof (struct Plugin));
1602 plugin->port = port;
1604 GNUNET_asprintf (&plugin->unix_socket_path,
1605 "/tmp/unix-plugin-sock.%d",
1608 /* Initialize my flags */
1611 api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1614 api->get_session = &unix_plugin_get_session;
1615 api->send = &unix_plugin_send;
1616 api->disconnect = &unix_disconnect;
1617 api->address_pretty_printer = &unix_plugin_address_pretty_printer;
1618 api->address_to_string = &unix_address_to_string;
1619 api->check_address = &unix_check_address;
1620 api->string_to_address = &unix_string_to_address;
1621 api->get_network = &unix_get_network;
1622 sockets_created = unix_transport_server_start (plugin);
1623 if (0 == sockets_created)
1624 LOG (GNUNET_ERROR_TYPE_WARNING,
1625 _("Failed to open UNIX listen socket\n"));
1626 plugin->session_map = GNUNET_CONTAINER_multihashmap_create (10, GNUNET_NO);
1627 plugin->address_update_task = GNUNET_SCHEDULER_add_now (&address_notification, plugin);
1633 * Shutdown the plugin.
1635 * @param cls the plugin API returned from the initialization function
1636 * @return NULL (always)
1639 libgnunet_plugin_transport_unix_done (void *cls)
1641 struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1642 struct Plugin *plugin = api->cls;
1643 struct UNIXMessageWrapper * msgw;
1644 struct UnixAddress *ua;
1653 len = sizeof (struct UnixAddress) + strlen (plugin->unix_socket_path) + 1;
1654 ua = GNUNET_malloc (len);
1655 ua->options = htonl (myoptions);
1656 ua->addrlen = htonl(strlen (plugin->unix_socket_path) + 1);
1657 memcpy (&ua[1], plugin->unix_socket_path, strlen (plugin->unix_socket_path) + 1);
1659 plugin->env->notify_address (plugin->env->cls, GNUNET_NO,
1662 while (NULL != (msgw = plugin->msg_head))
1664 GNUNET_CONTAINER_DLL_remove (plugin->msg_head, plugin->msg_tail, msgw);
1665 if (msgw->cont != NULL)
1666 msgw->cont (msgw->cont_cls, &msgw->session->target, GNUNET_SYSERR,
1668 GNUNET_free (msgw->msg);
1672 if (GNUNET_SCHEDULER_NO_TASK != plugin->select_task)
1674 GNUNET_SCHEDULER_cancel (plugin->select_task);
1675 plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
1677 if (GNUNET_SCHEDULER_NO_TASK != plugin->address_update_task)
1679 GNUNET_SCHEDULER_cancel (plugin->address_update_task);
1680 plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1682 if (NULL != plugin->unix_sock.desc)
1684 GNUNET_break (GNUNET_OK ==
1685 GNUNET_NETWORK_socket_close (plugin->unix_sock.desc));
1686 plugin->unix_sock.desc = NULL;
1687 plugin->with_ws = GNUNET_NO;
1689 GNUNET_CONTAINER_multihashmap_iterate (plugin->session_map,
1690 &get_session_delete_it, plugin);
1691 GNUNET_CONTAINER_multihashmap_destroy (plugin->session_map);
1692 if (NULL != plugin->rs)
1693 GNUNET_NETWORK_fdset_destroy (plugin->rs);
1694 if (NULL != plugin->ws)
1695 GNUNET_NETWORK_fdset_destroy (plugin->ws);
1696 GNUNET_free (plugin->unix_socket_path);
1697 GNUNET_free (plugin);
1702 /* end of plugin_transport_unix.c */