1 /* GIO - GLib Input, Output and Streaming Library
3 * Copyright (C) 2008 Christian Kellner, Samuel Cormier-Iijima
4 * Copyright © 2009 Codethink Limited
5 * Copyright © 2009 Red Hat, Inc
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General
18 * Public License along with this library; if not, write to the
19 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
20 * Boston, MA 02111-1307, USA.
22 * Authors: Christian Kellner <gicmo@gnome.org>
23 * Samuel Cormier-Iijima <sciyoshi@gmail.com>
24 * Ryan Lortie <desrt@desrt.ca>
25 * Alexander Larsson <alexl@redhat.com>
33 #include "glib-unix.h"
44 # include <sys/ioctl.h>
47 #ifdef HAVE_SYS_FILIO_H
48 # include <sys/filio.h>
55 #include "gcancellable.h"
56 #include "gioenumtypes.h"
57 #include "ginetaddress.h"
58 #include "ginitable.h"
62 #include "gnetworkingprivate.h"
63 #include "gsocketaddress.h"
64 #include "gsocketcontrolmessage.h"
65 #include "gcredentials.h"
70 * @short_description: Low-level socket object
72 * @see_also: #GInitable
74 * A #GSocket is a low-level networking primitive. It is a more or less
75 * direct mapping of the BSD socket API in a portable GObject based API.
76 * It supports both the UNIX socket implementations and winsock2 on Windows.
78 * #GSocket is the platform independent base upon which the higher level
79 * network primitives are based. Applications are not typically meant to
80 * use it directly, but rather through classes like #GSocketClient,
81 * #GSocketService and #GSocketConnection. However there may be cases where
82 * direct use of #GSocket is useful.
84 * #GSocket implements the #GInitable interface, so if it is manually constructed
85 * by e.g. g_object_new() you must call g_initable_init() and check the
86 * results before using the object. This is done automatically in
87 * g_socket_new() and g_socket_new_from_fd(), so these functions can return
90 * Sockets operate in two general modes, blocking or non-blocking. When
91 * in blocking mode all operations block until the requested operation
92 * is finished or there is an error. In non-blocking mode all calls that
93 * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
94 * To know when a call would successfully run you can call g_socket_condition_check(),
95 * or g_socket_condition_wait(). You can also use g_socket_create_source() and
96 * attach it to a #GMainContext to get callbacks when I/O is possible.
97 * Note that all sockets are always set to non blocking mode in the system, and
98 * blocking mode is emulated in GSocket.
100 * When working in non-blocking mode applications should always be able to
101 * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
102 * function said that I/O was possible. This can easily happen in case
103 * of a race condition in the application, but it can also happen for other
104 * reasons. For instance, on Windows a socket is always seen as writable
105 * until a write returns %G_IO_ERROR_WOULD_BLOCK.
107 * #GSocket<!-- -->s can be either connection oriented or datagram based.
108 * For connection oriented types you must first establish a connection by
109 * either connecting to an address or accepting a connection from another
110 * address. For connectionless socket types the target/source address is
111 * specified or received in each I/O operation.
113 * All socket file descriptors are set to be close-on-exec.
115 * Note that creating a #GSocket causes the signal %SIGPIPE to be
116 * ignored for the remainder of the program. If you are writing a
117 * command-line utility that uses #GSocket, you may need to take into
118 * account the fact that your program will not automatically be killed
119 * if it tries to write to %stdout after it has been closed.
124 static void g_socket_initable_iface_init (GInitableIface *iface);
125 static gboolean g_socket_initable_init (GInitable *initable,
126 GCancellable *cancellable,
129 G_DEFINE_TYPE_WITH_CODE (GSocket, g_socket, G_TYPE_OBJECT,
130 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
131 g_socket_initable_iface_init));
148 PROP_MULTICAST_LOOPBACK,
152 /* Size of the receiver cache for g_socket_receive_from() */
153 #define RECV_ADDR_CACHE_SIZE 8
155 struct _GSocketPrivate
157 GSocketFamily family;
159 GSocketProtocol protocol;
163 GError *construct_error;
164 GSocketAddress *remote_address;
172 guint connect_pending : 1;
178 GList *requested_conditions; /* list of requested GIOCondition * */
182 GSocketAddress *addr;
183 struct sockaddr *native;
186 } recv_addr_cache[RECV_ADDR_CACHE_SIZE];
190 get_socket_errno (void)
195 return WSAGetLastError ();
200 socket_io_error_from_errno (int err)
203 return g_io_error_from_errno (err);
208 return G_IO_ERROR_ADDRESS_IN_USE;
210 return G_IO_ERROR_WOULD_BLOCK;
212 return G_IO_ERROR_PERMISSION_DENIED;
213 case WSA_INVALID_HANDLE:
214 case WSA_INVALID_PARAMETER:
217 return G_IO_ERROR_INVALID_ARGUMENT;
218 case WSAEPROTONOSUPPORT:
219 return G_IO_ERROR_NOT_SUPPORTED;
221 return G_IO_ERROR_CANCELLED;
222 case WSAESOCKTNOSUPPORT:
224 case WSAEPFNOSUPPORT:
225 case WSAEAFNOSUPPORT:
226 return G_IO_ERROR_NOT_SUPPORTED;
228 return G_IO_ERROR_FAILED;
234 socket_strerror (int err)
237 return g_strerror (err);
242 msg = g_win32_error_message (err);
244 msg_ret = g_intern_string (msg);
252 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
254 _win32_unset_event_mask (GSocket *socket, int mask)
256 socket->priv->current_events &= ~mask;
257 socket->priv->current_errors &= ~mask;
260 #define win32_unset_event_mask(_socket, _mask)
264 set_fd_nonblocking (int fd)
267 GError *error = NULL;
273 if (!g_unix_set_fd_nonblocking (fd, TRUE, &error))
275 g_warning ("Error setting socket nonblocking: %s", error->message);
276 g_clear_error (&error);
281 if (ioctlsocket (fd, FIONBIO, &arg) == SOCKET_ERROR)
283 int errsv = get_socket_errno ();
284 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
290 check_socket (GSocket *socket,
293 if (!socket->priv->inited)
295 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
296 _("Invalid socket, not initialized"));
300 if (socket->priv->construct_error)
302 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
303 _("Invalid socket, initialization failed due to: %s"),
304 socket->priv->construct_error->message);
308 if (socket->priv->closed)
310 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
311 _("Socket is already closed"));
315 if (socket->priv->timed_out)
317 socket->priv->timed_out = FALSE;
318 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
319 _("Socket I/O timed out"));
327 g_socket_details_from_fd (GSocket *socket)
329 struct sockaddr_storage address;
336 /* See bug #611756 */
337 BOOL bool_val = FALSE;
342 fd = socket->priv->fd;
343 optlen = sizeof value;
344 if (getsockopt (fd, SOL_SOCKET, SO_TYPE, (void *)&value, &optlen) != 0)
346 errsv = get_socket_errno ();
358 /* programmer error */
359 g_error ("creating GSocket from fd %d: %s\n",
360 fd, socket_strerror (errsv));
368 g_assert (optlen == sizeof value);
372 socket->priv->type = G_SOCKET_TYPE_STREAM;
376 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
380 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
384 socket->priv->type = G_SOCKET_TYPE_INVALID;
388 addrlen = sizeof address;
389 if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
391 errsv = get_socket_errno ();
397 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
398 sizeof address.ss_family <= addrlen);
399 family = address.ss_family;
403 /* On Solaris, this happens if the socket is not yet connected.
404 * But we can use SO_DOMAIN as a workaround there.
407 optlen = sizeof family;
408 if (getsockopt (fd, SOL_SOCKET, SO_DOMAIN, (void *)&family, &optlen) != 0)
410 errsv = get_socket_errno ();
414 /* This will translate to G_IO_ERROR_FAILED on either unix or windows */
422 case G_SOCKET_FAMILY_IPV4:
423 case G_SOCKET_FAMILY_IPV6:
424 socket->priv->family = address.ss_family;
425 switch (socket->priv->type)
427 case G_SOCKET_TYPE_STREAM:
428 socket->priv->protocol = G_SOCKET_PROTOCOL_TCP;
431 case G_SOCKET_TYPE_DATAGRAM:
432 socket->priv->protocol = G_SOCKET_PROTOCOL_UDP;
435 case G_SOCKET_TYPE_SEQPACKET:
436 socket->priv->protocol = G_SOCKET_PROTOCOL_SCTP;
444 case G_SOCKET_FAMILY_UNIX:
445 socket->priv->family = G_SOCKET_FAMILY_UNIX;
446 socket->priv->protocol = G_SOCKET_PROTOCOL_DEFAULT;
450 socket->priv->family = G_SOCKET_FAMILY_INVALID;
454 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
456 addrlen = sizeof address;
457 if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
458 socket->priv->connected = TRUE;
461 optlen = sizeof bool_val;
462 if (getsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
463 (void *)&bool_val, &optlen) == 0)
466 /* Experimentation indicates that the SO_KEEPALIVE value is
467 * actually a char on Windows, even if documentation claims it
468 * to be a BOOL which is a typedef for int. So this g_assert()
469 * fails. See bug #611756.
471 g_assert (optlen == sizeof bool_val);
473 socket->priv->keepalive = !!bool_val;
477 /* Can't read, maybe not supported, assume FALSE */
478 socket->priv->keepalive = FALSE;
484 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
485 socket_io_error_from_errno (errsv),
486 _("creating GSocket from fd: %s"),
487 socket_strerror (errsv));
491 g_socket_create_socket (GSocketFamily family,
501 case G_SOCKET_TYPE_STREAM:
502 native_type = SOCK_STREAM;
505 case G_SOCKET_TYPE_DATAGRAM:
506 native_type = SOCK_DGRAM;
509 case G_SOCKET_TYPE_SEQPACKET:
510 native_type = SOCK_SEQPACKET;
514 g_assert_not_reached ();
519 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
520 _("Unable to create socket: %s"), _("Unknown family was specified"));
526 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
527 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
532 fd = socket (family, native_type | SOCK_CLOEXEC, protocol);
533 /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
534 if (fd < 0 && errno == EINVAL)
536 fd = socket (family, native_type, protocol);
540 int errsv = get_socket_errno ();
542 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
543 _("Unable to create socket: %s"), socket_strerror (errsv));
550 /* We always want to set close-on-exec to protect users. If you
551 need to so some weird inheritance to exec you can re-enable this
552 using lower level hacks with g_socket_get_fd(). */
553 flags = fcntl (fd, F_GETFD, 0);
555 (flags & FD_CLOEXEC) == 0)
558 fcntl (fd, F_SETFD, flags);
567 g_socket_constructed (GObject *object)
569 GSocket *socket = G_SOCKET (object);
571 if (socket->priv->fd >= 0)
572 /* create socket->priv info from the fd */
573 g_socket_details_from_fd (socket);
576 /* create the fd from socket->priv info */
577 socket->priv->fd = g_socket_create_socket (socket->priv->family,
579 socket->priv->protocol,
580 &socket->priv->construct_error);
582 /* Always use native nonblocking sockets, as
583 windows sets sockets to nonblocking automatically
584 in certain operations. This way we make things work
585 the same on all platforms */
586 if (socket->priv->fd != -1)
587 set_fd_nonblocking (socket->priv->fd);
591 g_socket_get_property (GObject *object,
596 GSocket *socket = G_SOCKET (object);
597 GSocketAddress *address;
602 g_value_set_enum (value, socket->priv->family);
606 g_value_set_enum (value, socket->priv->type);
610 g_value_set_enum (value, socket->priv->protocol);
614 g_value_set_int (value, socket->priv->fd);
618 g_value_set_boolean (value, socket->priv->blocking);
621 case PROP_LISTEN_BACKLOG:
622 g_value_set_int (value, socket->priv->listen_backlog);
626 g_value_set_boolean (value, socket->priv->keepalive);
629 case PROP_LOCAL_ADDRESS:
630 address = g_socket_get_local_address (socket, NULL);
631 g_value_take_object (value, address);
634 case PROP_REMOTE_ADDRESS:
635 address = g_socket_get_remote_address (socket, NULL);
636 g_value_take_object (value, address);
640 g_value_set_uint (value, socket->priv->timeout);
644 g_value_set_uint (value, g_socket_get_ttl (socket));
648 g_value_set_boolean (value, g_socket_get_broadcast (socket));
651 case PROP_MULTICAST_LOOPBACK:
652 g_value_set_boolean (value, g_socket_get_multicast_loopback (socket));
655 case PROP_MULTICAST_TTL:
656 g_value_set_uint (value, g_socket_get_multicast_ttl (socket));
660 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
665 g_socket_set_property (GObject *object,
670 GSocket *socket = G_SOCKET (object);
675 socket->priv->family = g_value_get_enum (value);
679 socket->priv->type = g_value_get_enum (value);
683 socket->priv->protocol = g_value_get_enum (value);
687 socket->priv->fd = g_value_get_int (value);
691 g_socket_set_blocking (socket, g_value_get_boolean (value));
694 case PROP_LISTEN_BACKLOG:
695 g_socket_set_listen_backlog (socket, g_value_get_int (value));
699 g_socket_set_keepalive (socket, g_value_get_boolean (value));
703 g_socket_set_timeout (socket, g_value_get_uint (value));
707 g_socket_set_ttl (socket, g_value_get_uint (value));
711 g_socket_set_broadcast (socket, g_value_get_boolean (value));
714 case PROP_MULTICAST_LOOPBACK:
715 g_socket_set_multicast_loopback (socket, g_value_get_boolean (value));
718 case PROP_MULTICAST_TTL:
719 g_socket_set_multicast_ttl (socket, g_value_get_uint (value));
723 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
728 g_socket_finalize (GObject *object)
730 GSocket *socket = G_SOCKET (object);
733 g_clear_error (&socket->priv->construct_error);
735 if (socket->priv->fd != -1 &&
736 !socket->priv->closed)
737 g_socket_close (socket, NULL);
739 if (socket->priv->remote_address)
740 g_object_unref (socket->priv->remote_address);
743 if (socket->priv->event != WSA_INVALID_EVENT)
745 WSACloseEvent (socket->priv->event);
746 socket->priv->event = WSA_INVALID_EVENT;
749 g_assert (socket->priv->requested_conditions == NULL);
752 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
754 if (socket->priv->recv_addr_cache[i].addr)
756 g_object_unref (socket->priv->recv_addr_cache[i].addr);
757 g_free (socket->priv->recv_addr_cache[i].native);
761 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
762 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
766 g_socket_class_init (GSocketClass *klass)
768 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
770 /* Make sure winsock has been initialized */
771 g_type_ensure (G_TYPE_INET_ADDRESS);
774 /* There is no portable, thread-safe way to avoid having the process
775 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
776 * forced to simply ignore the signal process-wide.
778 signal (SIGPIPE, SIG_IGN);
781 g_type_class_add_private (klass, sizeof (GSocketPrivate));
783 gobject_class->finalize = g_socket_finalize;
784 gobject_class->constructed = g_socket_constructed;
785 gobject_class->set_property = g_socket_set_property;
786 gobject_class->get_property = g_socket_get_property;
788 g_object_class_install_property (gobject_class, PROP_FAMILY,
789 g_param_spec_enum ("family",
791 P_("The sockets address family"),
792 G_TYPE_SOCKET_FAMILY,
793 G_SOCKET_FAMILY_INVALID,
794 G_PARAM_CONSTRUCT_ONLY |
796 G_PARAM_STATIC_STRINGS));
798 g_object_class_install_property (gobject_class, PROP_TYPE,
799 g_param_spec_enum ("type",
801 P_("The sockets type"),
803 G_SOCKET_TYPE_STREAM,
804 G_PARAM_CONSTRUCT_ONLY |
806 G_PARAM_STATIC_STRINGS));
808 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
809 g_param_spec_enum ("protocol",
810 P_("Socket protocol"),
811 P_("The id of the protocol to use, or -1 for unknown"),
812 G_TYPE_SOCKET_PROTOCOL,
813 G_SOCKET_PROTOCOL_UNKNOWN,
814 G_PARAM_CONSTRUCT_ONLY |
816 G_PARAM_STATIC_STRINGS));
818 g_object_class_install_property (gobject_class, PROP_FD,
819 g_param_spec_int ("fd",
820 P_("File descriptor"),
821 P_("The sockets file descriptor"),
825 G_PARAM_CONSTRUCT_ONLY |
827 G_PARAM_STATIC_STRINGS));
829 g_object_class_install_property (gobject_class, PROP_BLOCKING,
830 g_param_spec_boolean ("blocking",
832 P_("Whether or not I/O on this socket is blocking"),
835 G_PARAM_STATIC_STRINGS));
837 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
838 g_param_spec_int ("listen-backlog",
839 P_("Listen backlog"),
840 P_("Outstanding connections in the listen queue"),
845 G_PARAM_STATIC_STRINGS));
847 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
848 g_param_spec_boolean ("keepalive",
849 P_("Keep connection alive"),
850 P_("Keep connection alive by sending periodic pings"),
853 G_PARAM_STATIC_STRINGS));
855 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
856 g_param_spec_object ("local-address",
858 P_("The local address the socket is bound to"),
859 G_TYPE_SOCKET_ADDRESS,
861 G_PARAM_STATIC_STRINGS));
863 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
864 g_param_spec_object ("remote-address",
865 P_("Remote address"),
866 P_("The remote address the socket is connected to"),
867 G_TYPE_SOCKET_ADDRESS,
869 G_PARAM_STATIC_STRINGS));
874 * The timeout in seconds on socket I/O
878 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
879 g_param_spec_uint ("timeout",
881 P_("The timeout in seconds on socket I/O"),
886 G_PARAM_STATIC_STRINGS));
891 * Whether the socket should allow sending to and receiving from broadcast addresses.
895 g_object_class_install_property (gobject_class, PROP_BROADCAST,
896 g_param_spec_boolean ("broadcast",
898 P_("Whether to allow sending to and receiving from broadcast addresses"),
901 G_PARAM_STATIC_STRINGS));
906 * Time-to-live for outgoing unicast packets
910 g_object_class_install_property (gobject_class, PROP_TTL,
911 g_param_spec_uint ("ttl",
913 P_("Time-to-live of outgoing unicast packets"),
916 G_PARAM_STATIC_STRINGS));
919 * GSocket:multicast-loopback:
921 * Whether outgoing multicast packets loop back to the local host.
925 g_object_class_install_property (gobject_class, PROP_MULTICAST_LOOPBACK,
926 g_param_spec_boolean ("multicast-loopback",
927 P_("Multicast loopback"),
928 P_("Whether outgoing multicast packets loop back to the local host"),
931 G_PARAM_STATIC_STRINGS));
934 * GSocket:multicast-ttl:
936 * Time-to-live out outgoing multicast packets
940 g_object_class_install_property (gobject_class, PROP_MULTICAST_TTL,
941 g_param_spec_uint ("multicast-ttl",
943 P_("Time-to-live of outgoing multicast packets"),
946 G_PARAM_STATIC_STRINGS));
950 g_socket_initable_iface_init (GInitableIface *iface)
952 iface->init = g_socket_initable_init;
956 g_socket_init (GSocket *socket)
958 socket->priv = G_TYPE_INSTANCE_GET_PRIVATE (socket, G_TYPE_SOCKET, GSocketPrivate);
960 socket->priv->fd = -1;
961 socket->priv->blocking = TRUE;
962 socket->priv->listen_backlog = 10;
963 socket->priv->construct_error = NULL;
965 socket->priv->event = WSA_INVALID_EVENT;
970 g_socket_initable_init (GInitable *initable,
971 GCancellable *cancellable,
976 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
978 socket = G_SOCKET (initable);
980 if (cancellable != NULL)
982 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
983 _("Cancellable initialization not supported"));
987 socket->priv->inited = TRUE;
989 if (socket->priv->construct_error)
992 *error = g_error_copy (socket->priv->construct_error);
1002 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
1003 * @type: the socket type to use.
1004 * @protocol: the id of the protocol to use, or 0 for default.
1005 * @error: #GError for error reporting, or %NULL to ignore.
1007 * Creates a new #GSocket with the defined family, type and protocol.
1008 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
1009 * for the family and type is used.
1011 * The @protocol is a family and type specific int that specifies what
1012 * kind of protocol to use. #GSocketProtocol lists several common ones.
1013 * Many families only support one protocol, and use 0 for this, others
1014 * support several and using 0 means to use the default protocol for
1015 * the family and type.
1017 * The protocol id is passed directly to the operating
1018 * system, so you can use protocols not listed in #GSocketProtocol if you
1019 * know the protocol number used for it.
1021 * Returns: a #GSocket or %NULL on error.
1022 * Free the returned object with g_object_unref().
1027 g_socket_new (GSocketFamily family,
1029 GSocketProtocol protocol,
1032 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1036 "protocol", protocol,
1041 * g_socket_new_from_fd:
1042 * @fd: a native socket file descriptor.
1043 * @error: #GError for error reporting, or %NULL to ignore.
1045 * Creates a new #GSocket from a native file descriptor
1046 * or winsock SOCKET handle.
1048 * This reads all the settings from the file descriptor so that
1049 * all properties should work. Note that the file descriptor
1050 * will be set to non-blocking mode, independent on the blocking
1051 * mode of the #GSocket.
1053 * Returns: a #GSocket or %NULL on error.
1054 * Free the returned object with g_object_unref().
1059 g_socket_new_from_fd (gint fd,
1062 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1069 * g_socket_set_blocking:
1070 * @socket: a #GSocket.
1071 * @blocking: Whether to use blocking I/O or not.
1073 * Sets the blocking mode of the socket. In blocking mode
1074 * all operations block until they succeed or there is an error. In
1075 * non-blocking mode all functions return results immediately or
1076 * with a %G_IO_ERROR_WOULD_BLOCK error.
1078 * All sockets are created in blocking mode. However, note that the
1079 * platform level socket is always non-blocking, and blocking mode
1080 * is a GSocket level feature.
1085 g_socket_set_blocking (GSocket *socket,
1088 g_return_if_fail (G_IS_SOCKET (socket));
1090 blocking = !!blocking;
1092 if (socket->priv->blocking == blocking)
1095 socket->priv->blocking = blocking;
1096 g_object_notify (G_OBJECT (socket), "blocking");
1100 * g_socket_get_blocking:
1101 * @socket: a #GSocket.
1103 * Gets the blocking mode of the socket. For details on blocking I/O,
1104 * see g_socket_set_blocking().
1106 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
1111 g_socket_get_blocking (GSocket *socket)
1113 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1115 return socket->priv->blocking;
1119 * g_socket_set_keepalive:
1120 * @socket: a #GSocket.
1121 * @keepalive: Value for the keepalive flag
1123 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
1124 * this flag is set on a socket, the system will attempt to verify that the
1125 * remote socket endpoint is still present if a sufficiently long period of
1126 * time passes with no data being exchanged. If the system is unable to
1127 * verify the presence of the remote endpoint, it will automatically close
1130 * This option is only functional on certain kinds of sockets. (Notably,
1131 * %G_SOCKET_PROTOCOL_TCP sockets.)
1133 * The exact time between pings is system- and protocol-dependent, but will
1134 * normally be at least two hours. Most commonly, you would set this flag
1135 * on a server socket if you want to allow clients to remain idle for long
1136 * periods of time, but also want to ensure that connections are eventually
1137 * garbage-collected if clients crash or become unreachable.
1142 g_socket_set_keepalive (GSocket *socket,
1147 g_return_if_fail (G_IS_SOCKET (socket));
1149 keepalive = !!keepalive;
1150 if (socket->priv->keepalive == keepalive)
1153 value = (gint) keepalive;
1154 if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_KEEPALIVE,
1155 (gpointer) &value, sizeof (value)) < 0)
1157 int errsv = get_socket_errno ();
1158 g_warning ("error setting keepalive: %s", socket_strerror (errsv));
1162 socket->priv->keepalive = keepalive;
1163 g_object_notify (G_OBJECT (socket), "keepalive");
1167 * g_socket_get_keepalive:
1168 * @socket: a #GSocket.
1170 * Gets the keepalive mode of the socket. For details on this,
1171 * see g_socket_set_keepalive().
1173 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1178 g_socket_get_keepalive (GSocket *socket)
1180 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1182 return socket->priv->keepalive;
1186 * g_socket_get_listen_backlog:
1187 * @socket: a #GSocket.
1189 * Gets the listen backlog setting of the socket. For details on this,
1190 * see g_socket_set_listen_backlog().
1192 * Returns: the maximum number of pending connections.
1197 g_socket_get_listen_backlog (GSocket *socket)
1199 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1201 return socket->priv->listen_backlog;
1205 * g_socket_set_listen_backlog:
1206 * @socket: a #GSocket.
1207 * @backlog: the maximum number of pending connections.
1209 * Sets the maximum number of outstanding connections allowed
1210 * when listening on this socket. If more clients than this are
1211 * connecting to the socket and the application is not handling them
1212 * on time then the new connections will be refused.
1214 * Note that this must be called before g_socket_listen() and has no
1215 * effect if called after that.
1220 g_socket_set_listen_backlog (GSocket *socket,
1223 g_return_if_fail (G_IS_SOCKET (socket));
1224 g_return_if_fail (!socket->priv->listening);
1226 if (backlog != socket->priv->listen_backlog)
1228 socket->priv->listen_backlog = backlog;
1229 g_object_notify (G_OBJECT (socket), "listen-backlog");
1234 * g_socket_get_timeout:
1235 * @socket: a #GSocket.
1237 * Gets the timeout setting of the socket. For details on this, see
1238 * g_socket_set_timeout().
1240 * Returns: the timeout in seconds
1245 g_socket_get_timeout (GSocket *socket)
1247 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1249 return socket->priv->timeout;
1253 * g_socket_set_timeout:
1254 * @socket: a #GSocket.
1255 * @timeout: the timeout for @socket, in seconds, or 0 for none
1257 * Sets the time in seconds after which I/O operations on @socket will
1258 * time out if they have not yet completed.
1260 * On a blocking socket, this means that any blocking #GSocket
1261 * operation will time out after @timeout seconds of inactivity,
1262 * returning %G_IO_ERROR_TIMED_OUT.
1264 * On a non-blocking socket, calls to g_socket_condition_wait() will
1265 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1266 * created with g_socket_create_source() will trigger after
1267 * @timeout seconds of inactivity, with the requested condition
1268 * set, at which point calling g_socket_receive(), g_socket_send(),
1269 * g_socket_check_connect_result(), etc, will fail with
1270 * %G_IO_ERROR_TIMED_OUT.
1272 * If @timeout is 0 (the default), operations will never time out
1275 * Note that if an I/O operation is interrupted by a signal, this may
1276 * cause the timeout to be reset.
1281 g_socket_set_timeout (GSocket *socket,
1284 g_return_if_fail (G_IS_SOCKET (socket));
1286 if (timeout != socket->priv->timeout)
1288 socket->priv->timeout = timeout;
1289 g_object_notify (G_OBJECT (socket), "timeout");
1295 * @socket: a #GSocket.
1297 * Gets the unicast time-to-live setting on @socket; see
1298 * g_socket_set_ttl() for more details.
1300 * Returns: the time-to-live setting on @socket
1305 g_socket_get_ttl (GSocket *socket)
1308 guint value, optlen;
1310 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1312 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1316 optlen = sizeof (optval);
1317 result = getsockopt (socket->priv->fd, IPPROTO_IP, IP_TTL,
1321 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1323 optlen = sizeof (value);
1324 result = getsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1328 g_return_val_if_reached (FALSE);
1332 int errsv = get_socket_errno ();
1333 g_warning ("error getting unicast ttl: %s", socket_strerror (errsv));
1342 * @socket: a #GSocket.
1343 * @ttl: the time-to-live value for all unicast packets on @socket
1345 * Sets the time-to-live for outgoing unicast packets on @socket.
1346 * By default the platform-specific default value is used.
1351 g_socket_set_ttl (GSocket *socket,
1356 g_return_if_fail (G_IS_SOCKET (socket));
1358 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1360 guchar optval = (guchar)ttl;
1362 result = setsockopt (socket->priv->fd, IPPROTO_IP, IP_TTL,
1363 &optval, sizeof (optval));
1365 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1367 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1368 &ttl, sizeof (ttl));
1371 g_return_if_reached ();
1375 int errsv = get_socket_errno ();
1376 g_warning ("error setting unicast ttl: %s", socket_strerror (errsv));
1380 g_object_notify (G_OBJECT (socket), "ttl");
1384 * g_socket_get_broadcast:
1385 * @socket: a #GSocket.
1387 * Gets the broadcast setting on @socket; if %TRUE,
1388 * it is possible to send packets to broadcast
1389 * addresses or receive from broadcast addresses.
1391 * Returns: the broadcast setting on @socket
1396 g_socket_get_broadcast (GSocket *socket)
1399 guint value = 0, optlen;
1401 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1403 optlen = sizeof (guchar);
1404 result = getsockopt (socket->priv->fd, SOL_SOCKET, SO_BROADCAST,
1409 int errsv = get_socket_errno ();
1410 g_warning ("error getting broadcast: %s", socket_strerror (errsv));
1418 * g_socket_set_broadcast:
1419 * @socket: a #GSocket.
1420 * @broadcast: whether @socket should allow sending to and receiving
1421 * from broadcast addresses
1423 * Sets whether @socket should allow sending to and receiving from
1424 * broadcast addresses. This is %FALSE by default.
1429 g_socket_set_broadcast (GSocket *socket,
1435 g_return_if_fail (G_IS_SOCKET (socket));
1437 broadcast = !!broadcast;
1438 value = (guchar)broadcast;
1440 result = setsockopt (socket->priv->fd, SOL_SOCKET, SO_BROADCAST,
1441 &value, sizeof (value));
1445 int errsv = get_socket_errno ();
1446 g_warning ("error setting broadcast: %s", socket_strerror (errsv));
1450 g_object_notify (G_OBJECT (socket), "broadcast");
1454 * g_socket_get_multicast_loopback:
1455 * @socket: a #GSocket.
1457 * Gets the multicast loopback setting on @socket; if %TRUE (the
1458 * default), outgoing multicast packets will be looped back to
1459 * multicast listeners on the same host.
1461 * Returns: the multicast loopback setting on @socket
1466 g_socket_get_multicast_loopback (GSocket *socket)
1469 guint value = 0, optlen;
1471 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1473 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1475 optlen = sizeof (guchar);
1476 result = getsockopt (socket->priv->fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1479 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1481 optlen = sizeof (guint);
1482 result = getsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1486 g_return_val_if_reached (FALSE);
1490 int errsv = get_socket_errno ();
1491 g_warning ("error getting multicast loopback: %s", socket_strerror (errsv));
1499 * g_socket_set_multicast_loopback:
1500 * @socket: a #GSocket.
1501 * @loopback: whether @socket should receive messages sent to its
1502 * multicast groups from the local host
1504 * Sets whether outgoing multicast packets will be received by sockets
1505 * listening on that multicast address on the same host. This is %TRUE
1511 g_socket_set_multicast_loopback (GSocket *socket,
1516 g_return_if_fail (G_IS_SOCKET (socket));
1518 loopback = !!loopback;
1520 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1522 guchar value = (guchar)loopback;
1524 result = setsockopt (socket->priv->fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1525 &value, sizeof (value));
1527 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1529 guint value = (guint)loopback;
1531 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1532 &value, sizeof (value));
1535 g_return_if_reached ();
1539 int errsv = get_socket_errno ();
1540 g_warning ("error setting multicast loopback: %s", socket_strerror (errsv));
1544 g_object_notify (G_OBJECT (socket), "multicast-loopback");
1548 * g_socket_get_multicast_ttl:
1549 * @socket: a #GSocket.
1551 * Gets the multicast time-to-live setting on @socket; see
1552 * g_socket_set_multicast_ttl() for more details.
1554 * Returns: the multicast time-to-live setting on @socket
1559 g_socket_get_multicast_ttl (GSocket *socket)
1562 guint value, optlen;
1564 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1566 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1570 optlen = sizeof (optval);
1571 result = getsockopt (socket->priv->fd, IPPROTO_IP, IP_MULTICAST_TTL,
1575 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1577 optlen = sizeof (value);
1578 result = getsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1582 g_return_val_if_reached (FALSE);
1586 int errsv = get_socket_errno ();
1587 g_warning ("error getting multicast ttl: %s", socket_strerror (errsv));
1595 * g_socket_set_multicast_ttl:
1596 * @socket: a #GSocket.
1597 * @ttl: the time-to-live value for all multicast datagrams on @socket
1599 * Sets the time-to-live for outgoing multicast datagrams on @socket.
1600 * By default, this is 1, meaning that multicast packets will not leave
1601 * the local network.
1606 g_socket_set_multicast_ttl (GSocket *socket,
1611 g_return_if_fail (G_IS_SOCKET (socket));
1613 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1615 guchar optval = (guchar)ttl;
1617 result = setsockopt (socket->priv->fd, IPPROTO_IP, IP_MULTICAST_TTL,
1618 &optval, sizeof (optval));
1620 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1622 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1623 &ttl, sizeof (ttl));
1626 g_return_if_reached ();
1630 int errsv = get_socket_errno ();
1631 g_warning ("error setting multicast ttl: %s", socket_strerror (errsv));
1635 g_object_notify (G_OBJECT (socket), "multicast-ttl");
1639 * g_socket_get_family:
1640 * @socket: a #GSocket.
1642 * Gets the socket family of the socket.
1644 * Returns: a #GSocketFamily
1649 g_socket_get_family (GSocket *socket)
1651 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1653 return socket->priv->family;
1657 * g_socket_get_socket_type:
1658 * @socket: a #GSocket.
1660 * Gets the socket type of the socket.
1662 * Returns: a #GSocketType
1667 g_socket_get_socket_type (GSocket *socket)
1669 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1671 return socket->priv->type;
1675 * g_socket_get_protocol:
1676 * @socket: a #GSocket.
1678 * Gets the socket protocol id the socket was created with.
1679 * In case the protocol is unknown, -1 is returned.
1681 * Returns: a protocol id, or -1 if unknown
1686 g_socket_get_protocol (GSocket *socket)
1688 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1690 return socket->priv->protocol;
1695 * @socket: a #GSocket.
1697 * Returns the underlying OS socket object. On unix this
1698 * is a socket file descriptor, and on Windows this is
1699 * a Winsock2 SOCKET handle. This may be useful for
1700 * doing platform specific or otherwise unusual operations
1703 * Returns: the file descriptor of the socket.
1708 g_socket_get_fd (GSocket *socket)
1710 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1712 return socket->priv->fd;
1716 * g_socket_get_local_address:
1717 * @socket: a #GSocket.
1718 * @error: #GError for error reporting, or %NULL to ignore.
1720 * Try to get the local address of a bound socket. This is only
1721 * useful if the socket has been bound to a local address,
1722 * either explicitly or implicitly when connecting.
1724 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1725 * Free the returned object with g_object_unref().
1730 g_socket_get_local_address (GSocket *socket,
1733 struct sockaddr_storage buffer;
1734 guint32 len = sizeof (buffer);
1736 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1738 if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1740 int errsv = get_socket_errno ();
1741 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1742 _("could not get local address: %s"), socket_strerror (errsv));
1746 return g_socket_address_new_from_native (&buffer, len);
1750 * g_socket_get_remote_address:
1751 * @socket: a #GSocket.
1752 * @error: #GError for error reporting, or %NULL to ignore.
1754 * Try to get the remove address of a connected socket. This is only
1755 * useful for connection oriented sockets that have been connected.
1757 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1758 * Free the returned object with g_object_unref().
1763 g_socket_get_remote_address (GSocket *socket,
1766 struct sockaddr_storage buffer;
1767 guint32 len = sizeof (buffer);
1769 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1771 if (socket->priv->connect_pending)
1773 if (!g_socket_check_connect_result (socket, error))
1776 socket->priv->connect_pending = FALSE;
1779 if (!socket->priv->remote_address)
1781 if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1783 int errsv = get_socket_errno ();
1784 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1785 _("could not get remote address: %s"), socket_strerror (errsv));
1789 socket->priv->remote_address = g_socket_address_new_from_native (&buffer, len);
1792 return g_object_ref (socket->priv->remote_address);
1796 * g_socket_is_connected:
1797 * @socket: a #GSocket.
1799 * Check whether the socket is connected. This is only useful for
1800 * connection-oriented sockets.
1802 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1807 g_socket_is_connected (GSocket *socket)
1809 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1811 return socket->priv->connected;
1816 * @socket: a #GSocket.
1817 * @error: #GError for error reporting, or %NULL to ignore.
1819 * Marks the socket as a server socket, i.e. a socket that is used
1820 * to accept incoming requests using g_socket_accept().
1822 * Before calling this the socket must be bound to a local address using
1825 * To set the maximum amount of outstanding clients, use
1826 * g_socket_set_listen_backlog().
1828 * Returns: %TRUE on success, %FALSE on error.
1833 g_socket_listen (GSocket *socket,
1836 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1838 if (!check_socket (socket, error))
1841 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1843 int errsv = get_socket_errno ();
1845 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1846 _("could not listen: %s"), socket_strerror (errsv));
1850 socket->priv->listening = TRUE;
1857 * @socket: a #GSocket.
1858 * @address: a #GSocketAddress specifying the local address.
1859 * @allow_reuse: whether to allow reusing this address
1860 * @error: #GError for error reporting, or %NULL to ignore.
1862 * When a socket is created it is attached to an address family, but it
1863 * doesn't have an address in this family. g_socket_bind() assigns the
1864 * address (sometimes called name) of the socket.
1866 * It is generally required to bind to a local address before you can
1867 * receive connections. (See g_socket_listen() and g_socket_accept() ).
1868 * In certain situations, you may also want to bind a socket that will be
1869 * used to initiate connections, though this is not normally required.
1871 * @allow_reuse should be %TRUE for server sockets (sockets that you will
1872 * eventually call g_socket_accept() on), and %FALSE for client sockets.
1873 * (Specifically, if it is %TRUE, then g_socket_bind() will set the
1874 * %SO_REUSEADDR flag on the socket, allowing it to bind @address even if
1875 * that address was previously used by another socket that has not yet been
1876 * fully cleaned-up by the kernel. Failing to set this flag on a server
1877 * socket may cause the bind call to return %G_IO_ERROR_ADDRESS_IN_USE if
1878 * the server program is stopped and then immediately restarted.)
1880 * Returns: %TRUE on success, %FALSE on error.
1885 g_socket_bind (GSocket *socket,
1886 GSocketAddress *address,
1887 gboolean reuse_address,
1890 struct sockaddr_storage addr;
1892 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1894 if (!check_socket (socket, error))
1897 /* SO_REUSEADDR on Windows means something else and is not what we want.
1898 It always allows the unix variant of SO_REUSEADDR anyway */
1903 value = (int) !!reuse_address;
1904 /* Ignore errors here, the only likely error is "not supported", and
1905 this is a "best effort" thing mainly */
1906 setsockopt (socket->priv->fd, SOL_SOCKET, SO_REUSEADDR,
1907 (gpointer) &value, sizeof (value));
1911 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1914 if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1915 g_socket_address_get_native_size (address)) < 0)
1917 int errsv = get_socket_errno ();
1919 G_IO_ERROR, socket_io_error_from_errno (errsv),
1920 _("Error binding to address: %s"), socket_strerror (errsv));
1928 g_socket_multicast_group_operation (GSocket *socket,
1929 GInetAddress *group,
1930 gboolean source_specific,
1932 gboolean join_group,
1935 const guint8 *native_addr;
1936 gint optname, result;
1938 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1939 g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
1940 g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
1941 g_return_val_if_fail (g_inet_address_get_family (group) == socket->priv->family, FALSE);
1943 if (!check_socket (socket, error))
1946 native_addr = g_inet_address_to_bytes (group);
1947 if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1949 #ifdef HAVE_IP_MREQN
1950 struct ip_mreqn mc_req;
1952 struct ip_mreq mc_req;
1955 memcpy (&mc_req.imr_multiaddr, native_addr, sizeof (struct in_addr));
1957 #ifdef HAVE_IP_MREQN
1959 mc_req.imr_ifindex = if_nametoindex (iface);
1961 mc_req.imr_ifindex = 0; /* Pick any. */
1963 mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
1966 if (source_specific)
1968 #ifdef IP_ADD_SOURCE_MEMBERSHIP
1969 optname = join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
1971 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1973 _("Error joining multicast group: %s") :
1974 _("Error leaving multicast group: %s"),
1975 _("No support for source-specific multicast"));
1980 optname = join_group ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP;
1981 result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
1982 &mc_req, sizeof (mc_req));
1984 else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1986 struct ipv6_mreq mc_req_ipv6;
1988 memcpy (&mc_req_ipv6.ipv6mr_multiaddr, native_addr, sizeof (struct in6_addr));
1989 #ifdef HAVE_IF_NAMETOINDEX
1991 mc_req_ipv6.ipv6mr_interface = if_nametoindex (iface);
1994 mc_req_ipv6.ipv6mr_interface = 0;
1996 optname = join_group ? IPV6_JOIN_GROUP : IPV6_LEAVE_GROUP;
1997 result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
1998 &mc_req_ipv6, sizeof (mc_req_ipv6));
2001 g_return_val_if_reached (FALSE);
2005 int errsv = get_socket_errno ();
2007 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2009 _("Error joining multicast group: %s") :
2010 _("Error leaving multicast group: %s"),
2011 socket_strerror (errsv));
2019 * g_socket_join_multicast_group:
2020 * @socket: a #GSocket.
2021 * @group: a #GInetAddress specifying the group address to join.
2022 * @iface: (allow-none): Name of the interface to use, or %NULL
2023 * @source_specific: %TRUE if source-specific multicast should be used
2024 * @error: #GError for error reporting, or %NULL to ignore.
2026 * Registers @socket to receive multicast messages sent to @group.
2027 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2028 * been bound to an appropriate interface and port with
2031 * If @iface is %NULL, the system will automatically pick an interface
2032 * to bind to based on @group.
2034 * If @source_specific is %TRUE, source-specific multicast as defined
2035 * in RFC 4604 is used. Note that on older platforms this may fail
2036 * with a %G_IO_ERROR_NOT_SUPPORTED error.
2038 * Returns: %TRUE on success, %FALSE on error.
2043 g_socket_join_multicast_group (GSocket *socket,
2044 GInetAddress *group,
2045 gboolean source_specific,
2049 return g_socket_multicast_group_operation (socket, group, source_specific, iface, TRUE, error);
2053 * g_socket_leave_multicast_group:
2054 * @socket: a #GSocket.
2055 * @group: a #GInetAddress specifying the group address to leave.
2056 * @iface: (allow-none): Interface used
2057 * @source_specific: %TRUE if source-specific multicast was used
2058 * @error: #GError for error reporting, or %NULL to ignore.
2060 * Removes @socket from the multicast group defined by @group, @iface,
2061 * and @source_specific (which must all have the same values they had
2062 * when you joined the group).
2064 * @socket remains bound to its address and port, and can still receive
2065 * unicast messages after calling this.
2067 * Returns: %TRUE on success, %FALSE on error.
2072 g_socket_leave_multicast_group (GSocket *socket,
2073 GInetAddress *group,
2074 gboolean source_specific,
2078 return g_socket_multicast_group_operation (socket, group, source_specific, iface, FALSE, error);
2082 * g_socket_speaks_ipv4:
2083 * @socket: a #GSocket
2085 * Checks if a socket is capable of speaking IPv4.
2087 * IPv4 sockets are capable of speaking IPv4. On some operating systems
2088 * and under some combinations of circumstances IPv6 sockets are also
2089 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
2092 * No other types of sockets are currently considered as being capable
2095 * Returns: %TRUE if this socket can be used with IPv4.
2100 g_socket_speaks_ipv4 (GSocket *socket)
2102 switch (socket->priv->family)
2104 case G_SOCKET_FAMILY_IPV4:
2107 case G_SOCKET_FAMILY_IPV6:
2108 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
2110 guint sizeof_int = sizeof (int);
2113 if (getsockopt (socket->priv->fd,
2114 IPPROTO_IPV6, IPV6_V6ONLY,
2115 &v6_only, &sizeof_int) != 0)
2131 * @socket: a #GSocket.
2132 * @cancellable: (allow-none): a %GCancellable or %NULL
2133 * @error: #GError for error reporting, or %NULL to ignore.
2135 * Accept incoming connections on a connection-based socket. This removes
2136 * the first outstanding connection request from the listening socket and
2137 * creates a #GSocket object for it.
2139 * The @socket must be bound to a local address with g_socket_bind() and
2140 * must be listening for incoming connections (g_socket_listen()).
2142 * If there are no outstanding connections then the operation will block
2143 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
2144 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
2146 * Returns: (transfer full): a new #GSocket, or %NULL on error.
2147 * Free the returned object with g_object_unref().
2152 g_socket_accept (GSocket *socket,
2153 GCancellable *cancellable,
2156 GSocket *new_socket;
2159 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
2161 if (!check_socket (socket, error))
2166 if (socket->priv->blocking &&
2167 !g_socket_condition_wait (socket,
2168 G_IO_IN, cancellable, error))
2171 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
2173 int errsv = get_socket_errno ();
2175 win32_unset_event_mask (socket, FD_ACCEPT);
2180 if (socket->priv->blocking)
2182 #ifdef WSAEWOULDBLOCK
2183 if (errsv == WSAEWOULDBLOCK)
2186 if (errsv == EWOULDBLOCK ||
2192 g_set_error (error, G_IO_ERROR,
2193 socket_io_error_from_errno (errsv),
2194 _("Error accepting connection: %s"), socket_strerror (errsv));
2200 win32_unset_event_mask (socket, FD_ACCEPT);
2204 /* The socket inherits the accepting sockets event mask and even object,
2205 we need to remove that */
2206 WSAEventSelect (ret, NULL, 0);
2212 /* We always want to set close-on-exec to protect users. If you
2213 need to so some weird inheritance to exec you can re-enable this
2214 using lower level hacks with g_socket_get_fd(). */
2215 flags = fcntl (ret, F_GETFD, 0);
2217 (flags & FD_CLOEXEC) == 0)
2219 flags |= FD_CLOEXEC;
2220 fcntl (ret, F_SETFD, flags);
2225 new_socket = g_socket_new_from_fd (ret, error);
2226 if (new_socket == NULL)
2235 new_socket->priv->protocol = socket->priv->protocol;
2242 * @socket: a #GSocket.
2243 * @address: a #GSocketAddress specifying the remote address.
2244 * @cancellable: (allow-none): a %GCancellable or %NULL
2245 * @error: #GError for error reporting, or %NULL to ignore.
2247 * Connect the socket to the specified remote address.
2249 * For connection oriented socket this generally means we attempt to make
2250 * a connection to the @address. For a connection-less socket it sets
2251 * the default address for g_socket_send() and discards all incoming datagrams
2252 * from other sources.
2254 * Generally connection oriented sockets can only connect once, but
2255 * connection-less sockets can connect multiple times to change the
2258 * If the connect call needs to do network I/O it will block, unless
2259 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
2260 * and the user can be notified of the connection finishing by waiting
2261 * for the G_IO_OUT condition. The result of the connection must then be
2262 * checked with g_socket_check_connect_result().
2264 * Returns: %TRUE if connected, %FALSE on error.
2269 g_socket_connect (GSocket *socket,
2270 GSocketAddress *address,
2271 GCancellable *cancellable,
2274 struct sockaddr_storage buffer;
2276 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2278 if (!check_socket (socket, error))
2281 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
2284 if (socket->priv->remote_address)
2285 g_object_unref (socket->priv->remote_address);
2286 socket->priv->remote_address = g_object_ref (address);
2290 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
2291 g_socket_address_get_native_size (address)) < 0)
2293 int errsv = get_socket_errno ();
2299 if (errsv == EINPROGRESS)
2301 if (errsv == WSAEWOULDBLOCK)
2304 if (socket->priv->blocking)
2306 if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
2308 if (g_socket_check_connect_result (socket, error))
2314 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
2315 _("Connection in progress"));
2316 socket->priv->connect_pending = TRUE;
2320 g_set_error_literal (error, G_IO_ERROR,
2321 socket_io_error_from_errno (errsv),
2322 socket_strerror (errsv));
2329 win32_unset_event_mask (socket, FD_CONNECT);
2331 socket->priv->connected = TRUE;
2337 * g_socket_check_connect_result:
2338 * @socket: a #GSocket
2339 * @error: #GError for error reporting, or %NULL to ignore.
2341 * Checks and resets the pending connect error for the socket.
2342 * This is used to check for errors when g_socket_connect() is
2343 * used in non-blocking mode.
2345 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
2350 g_socket_check_connect_result (GSocket *socket,
2356 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2358 if (!check_socket (socket, error))
2361 optlen = sizeof (value);
2362 if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
2364 int errsv = get_socket_errno ();
2366 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2367 _("Unable to get pending error: %s"), socket_strerror (errsv));
2373 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
2374 socket_strerror (value));
2375 if (socket->priv->remote_address)
2377 g_object_unref (socket->priv->remote_address);
2378 socket->priv->remote_address = NULL;
2383 socket->priv->connected = TRUE;
2388 * g_socket_get_available_bytes:
2389 * @socket: a #GSocket
2391 * Get the amount of data that can be read from the socket without
2392 * blocking. In the case of datagram sockets this returns the size
2393 * of the first datagram and not the sum of the sizes of all currently
2396 * Returns: the number of bytes that can be read from the socket
2397 * without blocking or -1 on error.
2402 g_socket_get_available_bytes (GSocket *socket)
2408 gsize avail_len = sizeof (avail);
2411 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
2413 #if defined(G_OS_WIN32)
2414 if (WSAIoctl (socket->priv->fd, FIONREAD, NULL, 0, &avail, sizeof (avail), 0, 0) == SOCKET_ERROR)
2416 #elif defined(SO_NREAD)
2417 if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_NREAD, &avail, &avail_len) < 0)
2420 if (ioctl (socket->priv->fd, FIONREAD, &avail) < 0)
2429 * @socket: a #GSocket
2430 * @buffer: a buffer to read data into (which should be at least @size
2432 * @size: the number of bytes you want to read from the socket
2433 * @cancellable: (allow-none): a %GCancellable or %NULL
2434 * @error: #GError for error reporting, or %NULL to ignore.
2436 * Receive data (up to @size bytes) from a socket. This is mainly used by
2437 * connection-oriented sockets; it is identical to g_socket_receive_from()
2438 * with @address set to %NULL.
2440 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
2441 * g_socket_receive() will always read either 0 or 1 complete messages from
2442 * the socket. If the received message is too large to fit in @buffer, then
2443 * the data beyond @size bytes will be discarded, without any explicit
2444 * indication that this has occurred.
2446 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
2447 * number of bytes, up to @size. If more than @size bytes have been
2448 * received, the additional data will be returned in future calls to
2449 * g_socket_receive().
2451 * If the socket is in blocking mode the call will block until there
2452 * is some data to receive, the connection is closed, or there is an
2453 * error. If there is no data available and the socket is in
2454 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
2455 * returned. To be notified when data is available, wait for the
2456 * %G_IO_IN condition.
2458 * On error -1 is returned and @error is set accordingly.
2460 * Returns: Number of bytes read, or 0 if the connection was closed by
2461 * the peer, or -1 on error
2466 g_socket_receive (GSocket *socket,
2469 GCancellable *cancellable,
2472 return g_socket_receive_with_blocking (socket, buffer, size,
2473 socket->priv->blocking,
2474 cancellable, error);
2478 * g_socket_receive_with_blocking:
2479 * @socket: a #GSocket
2480 * @buffer: a buffer to read data into (which should be at least @size
2482 * @size: the number of bytes you want to read from the socket
2483 * @blocking: whether to do blocking or non-blocking I/O
2484 * @cancellable: (allow-none): a %GCancellable or %NULL
2485 * @error: #GError for error reporting, or %NULL to ignore.
2487 * This behaves exactly the same as g_socket_receive(), except that
2488 * the choice of blocking or non-blocking behavior is determined by
2489 * the @blocking argument rather than by @socket's properties.
2491 * Returns: Number of bytes read, or 0 if the connection was closed by
2492 * the peer, or -1 on error
2497 g_socket_receive_with_blocking (GSocket *socket,
2501 GCancellable *cancellable,
2506 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2508 if (!check_socket (socket, error))
2511 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2517 !g_socket_condition_wait (socket,
2518 G_IO_IN, cancellable, error))
2521 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
2523 int errsv = get_socket_errno ();
2530 #ifdef WSAEWOULDBLOCK
2531 if (errsv == WSAEWOULDBLOCK)
2534 if (errsv == EWOULDBLOCK ||
2540 win32_unset_event_mask (socket, FD_READ);
2542 g_set_error (error, G_IO_ERROR,
2543 socket_io_error_from_errno (errsv),
2544 _("Error receiving data: %s"), socket_strerror (errsv));
2548 win32_unset_event_mask (socket, FD_READ);
2557 * g_socket_receive_from:
2558 * @socket: a #GSocket
2559 * @address: (out) (allow-none): a pointer to a #GSocketAddress
2561 * @buffer: (array length=size) (element-type guint8): a buffer to
2562 * read data into (which should be at least @size bytes long).
2563 * @size: the number of bytes you want to read from the socket
2564 * @cancellable: (allow-none): a %GCancellable or %NULL
2565 * @error: #GError for error reporting, or %NULL to ignore.
2567 * Receive data (up to @size bytes) from a socket.
2569 * If @address is non-%NULL then @address will be set equal to the
2570 * source address of the received packet.
2571 * @address is owned by the caller.
2573 * See g_socket_receive() for additional information.
2575 * Returns: Number of bytes read, or 0 if the connection was closed by
2576 * the peer, or -1 on error
2581 g_socket_receive_from (GSocket *socket,
2582 GSocketAddress **address,
2585 GCancellable *cancellable,
2593 return g_socket_receive_message (socket,
2601 /* Although we ignore SIGPIPE, gdb will still stop if the app receives
2602 * one, which can be confusing and annoying. So if possible, we want
2603 * to suppress the signal entirely.
2606 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
2608 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
2613 * @socket: a #GSocket
2614 * @buffer: (array length=size) (element-type guint8): the buffer
2615 * containing the data to send.
2616 * @size: the number of bytes to send
2617 * @cancellable: (allow-none): a %GCancellable or %NULL
2618 * @error: #GError for error reporting, or %NULL to ignore.
2620 * Tries to send @size bytes from @buffer on the socket. This is
2621 * mainly used by connection-oriented sockets; it is identical to
2622 * g_socket_send_to() with @address set to %NULL.
2624 * If the socket is in blocking mode the call will block until there is
2625 * space for the data in the socket queue. If there is no space available
2626 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2627 * will be returned. To be notified when space is available, wait for the
2628 * %G_IO_OUT condition. Note though that you may still receive
2629 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2630 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2631 * very common due to the way the underlying APIs work.)
2633 * On error -1 is returned and @error is set accordingly.
2635 * Returns: Number of bytes written (which may be less than @size), or -1
2641 g_socket_send (GSocket *socket,
2642 const gchar *buffer,
2644 GCancellable *cancellable,
2647 return g_socket_send_with_blocking (socket, buffer, size,
2648 socket->priv->blocking,
2649 cancellable, error);
2653 * g_socket_send_with_blocking:
2654 * @socket: a #GSocket
2655 * @buffer: (array length=size) (element-type guint8): the buffer
2656 * containing the data to send.
2657 * @size: the number of bytes to send
2658 * @blocking: whether to do blocking or non-blocking I/O
2659 * @cancellable: (allow-none): a %GCancellable or %NULL
2660 * @error: #GError for error reporting, or %NULL to ignore.
2662 * This behaves exactly the same as g_socket_send(), except that
2663 * the choice of blocking or non-blocking behavior is determined by
2664 * the @blocking argument rather than by @socket's properties.
2666 * Returns: Number of bytes written (which may be less than @size), or -1
2672 g_socket_send_with_blocking (GSocket *socket,
2673 const gchar *buffer,
2676 GCancellable *cancellable,
2681 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2683 if (!check_socket (socket, error))
2686 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2692 !g_socket_condition_wait (socket,
2693 G_IO_OUT, cancellable, error))
2696 if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
2698 int errsv = get_socket_errno ();
2703 #ifdef WSAEWOULDBLOCK
2704 if (errsv == WSAEWOULDBLOCK)
2705 win32_unset_event_mask (socket, FD_WRITE);
2710 #ifdef WSAEWOULDBLOCK
2711 if (errsv == WSAEWOULDBLOCK)
2714 if (errsv == EWOULDBLOCK ||
2720 g_set_error (error, G_IO_ERROR,
2721 socket_io_error_from_errno (errsv),
2722 _("Error sending data: %s"), socket_strerror (errsv));
2733 * @socket: a #GSocket
2734 * @address: (allow-none): a #GSocketAddress, or %NULL
2735 * @buffer: (array length=size) (element-type guint8): the buffer
2736 * containing the data to send.
2737 * @size: the number of bytes to send
2738 * @cancellable: (allow-none): a %GCancellable or %NULL
2739 * @error: #GError for error reporting, or %NULL to ignore.
2741 * Tries to send @size bytes from @buffer to @address. If @address is
2742 * %NULL then the message is sent to the default receiver (set by
2743 * g_socket_connect()).
2745 * See g_socket_send() for additional information.
2747 * Returns: Number of bytes written (which may be less than @size), or -1
2753 g_socket_send_to (GSocket *socket,
2754 GSocketAddress *address,
2755 const gchar *buffer,
2757 GCancellable *cancellable,
2765 return g_socket_send_message (socket,
2775 * g_socket_shutdown:
2776 * @socket: a #GSocket
2777 * @shutdown_read: whether to shut down the read side
2778 * @shutdown_write: whether to shut down the write side
2779 * @error: #GError for error reporting, or %NULL to ignore.
2781 * Shut down part of a full-duplex connection.
2783 * If @shutdown_read is %TRUE then the receiving side of the connection
2784 * is shut down, and further reading is disallowed.
2786 * If @shutdown_write is %TRUE then the sending side of the connection
2787 * is shut down, and further writing is disallowed.
2789 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
2791 * One example where this is used is graceful disconnect for TCP connections
2792 * where you close the sending side, then wait for the other side to close
2793 * the connection, thus ensuring that the other side saw all sent data.
2795 * Returns: %TRUE on success, %FALSE on error
2800 g_socket_shutdown (GSocket *socket,
2801 gboolean shutdown_read,
2802 gboolean shutdown_write,
2807 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2809 if (!check_socket (socket, error))
2813 if (!shutdown_read && !shutdown_write)
2817 if (shutdown_read && shutdown_write)
2819 else if (shutdown_read)
2824 if (shutdown_read && shutdown_write)
2826 else if (shutdown_read)
2832 if (shutdown (socket->priv->fd, how) != 0)
2834 int errsv = get_socket_errno ();
2835 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2836 _("Unable to shutdown socket: %s"), socket_strerror (errsv));
2840 if (shutdown_read && shutdown_write)
2841 socket->priv->connected = FALSE;
2848 * @socket: a #GSocket
2849 * @error: #GError for error reporting, or %NULL to ignore.
2851 * Closes the socket, shutting down any active connection.
2853 * Closing a socket does not wait for all outstanding I/O operations
2854 * to finish, so the caller should not rely on them to be guaranteed
2855 * to complete even if the close returns with no error.
2857 * Once the socket is closed, all other operations will return
2858 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
2861 * Sockets will be automatically closed when the last reference
2862 * is dropped, but you might want to call this function to make sure
2863 * resources are released as early as possible.
2865 * Beware that due to the way that TCP works, it is possible for
2866 * recently-sent data to be lost if either you close a socket while the
2867 * %G_IO_IN condition is set, or else if the remote connection tries to
2868 * send something to you after you close the socket but before it has
2869 * finished reading all of the data you sent. There is no easy generic
2870 * way to avoid this problem; the easiest fix is to design the network
2871 * protocol such that the client will never send data "out of turn".
2872 * Another solution is for the server to half-close the connection by
2873 * calling g_socket_shutdown() with only the @shutdown_write flag set,
2874 * and then wait for the client to notice this and close its side of the
2875 * connection, after which the server can safely call g_socket_close().
2876 * (This is what #GTcpConnection does if you call
2877 * g_tcp_connection_set_graceful_disconnect(). But of course, this
2878 * only works if the client will close its connection after the server
2881 * Returns: %TRUE on success, %FALSE on error
2886 g_socket_close (GSocket *socket,
2891 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2893 if (socket->priv->closed)
2894 return TRUE; /* Multiple close not an error */
2896 if (!check_socket (socket, error))
2902 res = closesocket (socket->priv->fd);
2904 res = close (socket->priv->fd);
2908 int errsv = get_socket_errno ();
2913 g_set_error (error, G_IO_ERROR,
2914 socket_io_error_from_errno (errsv),
2915 _("Error closing socket: %s"),
2916 socket_strerror (errsv));
2922 socket->priv->connected = FALSE;
2923 socket->priv->closed = TRUE;
2924 if (socket->priv->remote_address)
2926 g_object_unref (socket->priv->remote_address);
2927 socket->priv->remote_address = NULL;
2934 * g_socket_is_closed:
2935 * @socket: a #GSocket
2937 * Checks whether a socket is closed.
2939 * Returns: %TRUE if socket is closed, %FALSE otherwise
2944 g_socket_is_closed (GSocket *socket)
2946 return socket->priv->closed;
2950 /* Broken source, used on errors */
2952 broken_prepare (GSource *source,
2959 broken_check (GSource *source)
2965 broken_dispatch (GSource *source,
2966 GSourceFunc callback,
2972 static GSourceFuncs broken_funcs =
2981 network_events_for_condition (GIOCondition condition)
2985 if (condition & G_IO_IN)
2986 event_mask |= (FD_READ | FD_ACCEPT);
2987 if (condition & G_IO_OUT)
2988 event_mask |= (FD_WRITE | FD_CONNECT);
2989 event_mask |= FD_CLOSE;
2995 ensure_event (GSocket *socket)
2997 if (socket->priv->event == WSA_INVALID_EVENT)
2998 socket->priv->event = WSACreateEvent();
3002 update_select_events (GSocket *socket)
3009 ensure_event (socket);
3012 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
3015 event_mask |= network_events_for_condition (*ptr);
3018 if (event_mask != socket->priv->selected_events)
3020 /* If no events selected, disable event so we can unset
3023 if (event_mask == 0)
3026 event = socket->priv->event;
3028 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
3029 socket->priv->selected_events = event_mask;
3034 add_condition_watch (GSocket *socket,
3035 GIOCondition *condition)
3037 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
3039 socket->priv->requested_conditions =
3040 g_list_prepend (socket->priv->requested_conditions, condition);
3042 update_select_events (socket);
3046 remove_condition_watch (GSocket *socket,
3047 GIOCondition *condition)
3049 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
3051 socket->priv->requested_conditions =
3052 g_list_remove (socket->priv->requested_conditions, condition);
3054 update_select_events (socket);
3058 update_condition (GSocket *socket)
3060 WSANETWORKEVENTS events;
3061 GIOCondition condition;
3063 if (WSAEnumNetworkEvents (socket->priv->fd,
3064 socket->priv->event,
3067 socket->priv->current_events |= events.lNetworkEvents;
3068 if (events.lNetworkEvents & FD_WRITE &&
3069 events.iErrorCode[FD_WRITE_BIT] != 0)
3070 socket->priv->current_errors |= FD_WRITE;
3071 if (events.lNetworkEvents & FD_CONNECT &&
3072 events.iErrorCode[FD_CONNECT_BIT] != 0)
3073 socket->priv->current_errors |= FD_CONNECT;
3077 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
3078 condition |= G_IO_IN;
3080 if (socket->priv->current_events & FD_CLOSE)
3082 int r, errsv, buffer;
3084 r = recv (socket->priv->fd, &buffer, sizeof (buffer), MSG_PEEK);
3086 errsv = get_socket_errno ();
3089 (r < 0 && errsv == WSAENOTCONN))
3090 condition |= G_IO_IN;
3092 (r < 0 && (errsv == WSAESHUTDOWN || errsv == WSAECONNRESET ||
3093 errsv == WSAECONNABORTED || errsv == WSAENETRESET)))
3094 condition |= G_IO_HUP;
3096 condition |= G_IO_ERR;
3099 if (socket->priv->closed)
3100 condition |= G_IO_HUP;
3102 /* Never report both G_IO_OUT and HUP, these are
3103 mutually exclusive (can't write to a closed socket) */
3104 if ((condition & G_IO_HUP) == 0 &&
3105 socket->priv->current_events & FD_WRITE)
3107 if (socket->priv->current_errors & FD_WRITE)
3108 condition |= G_IO_ERR;
3110 condition |= G_IO_OUT;
3114 if (socket->priv->current_events & FD_CONNECT)
3116 if (socket->priv->current_errors & FD_CONNECT)
3117 condition |= (G_IO_HUP | G_IO_ERR);
3119 condition |= G_IO_OUT;
3131 GIOCondition condition;
3132 GCancellable *cancellable;
3133 GPollFD cancel_pollfd;
3134 gint64 timeout_time;
3138 socket_source_prepare (GSource *source,
3141 GSocketSource *socket_source = (GSocketSource *)source;
3143 if (g_cancellable_is_cancelled (socket_source->cancellable))
3146 if (socket_source->timeout_time)
3150 now = g_source_get_time (source);
3151 /* Round up to ensure that we don't try again too early */
3152 *timeout = (socket_source->timeout_time - now + 999) / 1000;
3155 socket_source->socket->priv->timed_out = TRUE;
3164 socket_source->pollfd.revents = update_condition (socket_source->socket);
3167 if ((socket_source->condition & socket_source->pollfd.revents) != 0)
3174 socket_source_check (GSource *source)
3178 return socket_source_prepare (source, &timeout);
3182 socket_source_dispatch (GSource *source,
3183 GSourceFunc callback,
3186 GSocketSourceFunc func = (GSocketSourceFunc)callback;
3187 GSocketSource *socket_source = (GSocketSource *)source;
3188 GSocket *socket = socket_source->socket;
3192 socket_source->pollfd.revents = update_condition (socket_source->socket);
3194 if (socket_source->socket->priv->timed_out)
3195 socket_source->pollfd.revents |= socket_source->condition & (G_IO_IN | G_IO_OUT);
3197 ret = (*func) (socket,
3198 socket_source->pollfd.revents & socket_source->condition,
3201 if (socket->priv->timeout)
3202 socket_source->timeout_time = g_get_monotonic_time () +
3203 socket->priv->timeout * 1000000;
3206 socket_source->timeout_time = 0;
3212 socket_source_finalize (GSource *source)
3214 GSocketSource *socket_source = (GSocketSource *)source;
3217 socket = socket_source->socket;
3220 remove_condition_watch (socket, &socket_source->condition);
3223 g_object_unref (socket);
3225 if (socket_source->cancellable)
3227 g_cancellable_release_fd (socket_source->cancellable);
3228 g_object_unref (socket_source->cancellable);
3233 socket_source_closure_callback (GSocket *socket,
3234 GIOCondition condition,
3237 GClosure *closure = data;
3239 GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
3240 GValue result_value = G_VALUE_INIT;
3243 g_value_init (&result_value, G_TYPE_BOOLEAN);
3245 g_value_init (¶ms[0], G_TYPE_SOCKET);
3246 g_value_set_object (¶ms[0], socket);
3247 g_value_init (¶ms[1], G_TYPE_IO_CONDITION);
3248 g_value_set_flags (¶ms[1], condition);
3250 g_closure_invoke (closure, &result_value, 2, params, NULL);
3252 result = g_value_get_boolean (&result_value);
3253 g_value_unset (&result_value);
3254 g_value_unset (¶ms[0]);
3255 g_value_unset (¶ms[1]);
3260 static GSourceFuncs socket_source_funcs =
3262 socket_source_prepare,
3263 socket_source_check,
3264 socket_source_dispatch,
3265 socket_source_finalize,
3266 (GSourceFunc)socket_source_closure_callback,
3267 (GSourceDummyMarshal)g_cclosure_marshal_generic,
3271 socket_source_new (GSocket *socket,
3272 GIOCondition condition,
3273 GCancellable *cancellable)
3276 GSocketSource *socket_source;
3279 ensure_event (socket);
3281 if (socket->priv->event == WSA_INVALID_EVENT)
3283 g_warning ("Failed to create WSAEvent");
3284 return g_source_new (&broken_funcs, sizeof (GSource));
3288 condition |= G_IO_HUP | G_IO_ERR;
3290 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
3291 g_source_set_name (source, "GSocket");
3292 socket_source = (GSocketSource *)source;
3294 socket_source->socket = g_object_ref (socket);
3295 socket_source->condition = condition;
3297 if (g_cancellable_make_pollfd (cancellable,
3298 &socket_source->cancel_pollfd))
3300 socket_source->cancellable = g_object_ref (cancellable);
3301 g_source_add_poll (source, &socket_source->cancel_pollfd);
3305 add_condition_watch (socket, &socket_source->condition);
3306 socket_source->pollfd.fd = (gintptr) socket->priv->event;
3308 socket_source->pollfd.fd = socket->priv->fd;
3311 socket_source->pollfd.events = condition;
3312 socket_source->pollfd.revents = 0;
3313 g_source_add_poll (source, &socket_source->pollfd);
3315 if (socket->priv->timeout)
3316 socket_source->timeout_time = g_get_monotonic_time () +
3317 socket->priv->timeout * 1000000;
3320 socket_source->timeout_time = 0;
3326 * g_socket_create_source: (skip)
3327 * @socket: a #GSocket
3328 * @condition: a #GIOCondition mask to monitor
3329 * @cancellable: (allow-none): a %GCancellable or %NULL
3331 * Creates a %GSource that can be attached to a %GMainContext to monitor
3332 * for the availibility of the specified @condition on the socket.
3334 * The callback on the source is of the #GSocketSourceFunc type.
3336 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
3337 * these conditions will always be reported output if they are true.
3339 * @cancellable if not %NULL can be used to cancel the source, which will
3340 * cause the source to trigger, reporting the current condition (which
3341 * is likely 0 unless cancellation happened at the same time as a
3342 * condition change). You can check for this in the callback using
3343 * g_cancellable_is_cancelled().
3345 * If @socket has a timeout set, and it is reached before @condition
3346 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
3347 * %G_IO_OUT depending on @condition. However, @socket will have been
3348 * marked as having had a timeout, and so the next #GSocket I/O method
3349 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
3351 * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
3356 g_socket_create_source (GSocket *socket,
3357 GIOCondition condition,
3358 GCancellable *cancellable)
3360 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
3362 return socket_source_new (socket, condition, cancellable);
3366 * g_socket_condition_check:
3367 * @socket: a #GSocket
3368 * @condition: a #GIOCondition mask to check
3370 * Checks on the readiness of @socket to perform operations.
3371 * The operations specified in @condition are checked for and masked
3372 * against the currently-satisfied conditions on @socket. The result
3375 * Note that on Windows, it is possible for an operation to return
3376 * %G_IO_ERROR_WOULD_BLOCK even immediately after
3377 * g_socket_condition_check() has claimed that the socket is ready for
3378 * writing. Rather than calling g_socket_condition_check() and then
3379 * writing to the socket if it succeeds, it is generally better to
3380 * simply try writing to the socket right away, and try again later if
3381 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
3383 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
3384 * these conditions will always be set in the output if they are true.
3386 * This call never blocks.
3388 * Returns: the @GIOCondition mask of the current state
3393 g_socket_condition_check (GSocket *socket,
3394 GIOCondition condition)
3396 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
3398 if (!check_socket (socket, NULL))
3403 GIOCondition current_condition;
3405 condition |= G_IO_ERR | G_IO_HUP;
3407 add_condition_watch (socket, &condition);
3408 current_condition = update_condition (socket);
3409 remove_condition_watch (socket, &condition);
3410 return condition & current_condition;
3416 poll_fd.fd = socket->priv->fd;
3417 poll_fd.events = condition;
3418 poll_fd.revents = 0;
3421 result = g_poll (&poll_fd, 1, 0);
3422 while (result == -1 && get_socket_errno () == EINTR);
3424 return poll_fd.revents;
3430 * g_socket_condition_wait:
3431 * @socket: a #GSocket
3432 * @condition: a #GIOCondition mask to wait for
3433 * @cancellable: (allow-none): a #GCancellable, or %NULL
3434 * @error: a #GError pointer, or %NULL
3436 * Waits for @condition to become true on @socket. When the condition
3437 * is met, %TRUE is returned.
3439 * If @cancellable is cancelled before the condition is met, or if the
3440 * socket has a timeout set and it is reached before the condition is
3441 * met, then %FALSE is returned and @error, if non-%NULL, is set to
3442 * the appropriate value (%G_IO_ERROR_CANCELLED or
3443 * %G_IO_ERROR_TIMED_OUT).
3445 * See also g_socket_condition_timed_wait().
3447 * Returns: %TRUE if the condition was met, %FALSE otherwise
3452 g_socket_condition_wait (GSocket *socket,
3453 GIOCondition condition,
3454 GCancellable *cancellable,
3457 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3459 return g_socket_condition_timed_wait (socket, condition, -1,
3460 cancellable, error);
3464 * g_socket_condition_timed_wait:
3465 * @socket: a #GSocket
3466 * @condition: a #GIOCondition mask to wait for
3467 * @timeout: the maximum time (in microseconds) to wait, or -1
3468 * @cancellable: (allow-none): a #GCancellable, or %NULL
3469 * @error: a #GError pointer, or %NULL
3471 * Waits for up to @timeout microseconds for @condition to become true
3472 * on @socket. If the condition is met, %TRUE is returned.
3474 * If @cancellable is cancelled before the condition is met, or if
3475 * @timeout (or the socket's #GSocket:timeout) is reached before the
3476 * condition is met, then %FALSE is returned and @error, if non-%NULL,
3477 * is set to the appropriate value (%G_IO_ERROR_CANCELLED or
3478 * %G_IO_ERROR_TIMED_OUT).
3480 * If you don't want a timeout, use g_socket_condition_wait().
3481 * (Alternatively, you can pass -1 for @timeout.)
3483 * Note that although @timeout is in microseconds for consistency with
3484 * other GLib APIs, this function actually only has millisecond
3485 * resolution, and the behavior is undefined if @timeout is not an
3486 * exact number of milliseconds.
3488 * Returns: %TRUE if the condition was met, %FALSE otherwise
3493 g_socket_condition_timed_wait (GSocket *socket,
3494 GIOCondition condition,
3496 GCancellable *cancellable,
3501 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3503 if (!check_socket (socket, error))
3506 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3509 if (socket->priv->timeout &&
3510 (timeout < 0 || socket->priv->timeout < timeout / G_USEC_PER_SEC))
3511 timeout = socket->priv->timeout * 1000;
3512 else if (timeout != -1)
3513 timeout = timeout / 1000;
3515 start_time = g_get_monotonic_time ();
3519 GIOCondition current_condition;
3525 /* Always check these */
3526 condition |= G_IO_ERR | G_IO_HUP;
3528 add_condition_watch (socket, &condition);
3531 events[num_events++] = socket->priv->event;
3533 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
3534 events[num_events++] = (WSAEVENT)cancel_fd.fd;
3537 timeout = WSA_INFINITE;
3539 current_condition = update_condition (socket);
3540 while ((condition & current_condition) == 0)
3542 res = WSAWaitForMultipleEvents (num_events, events,
3543 FALSE, timeout, FALSE);
3544 if (res == WSA_WAIT_FAILED)
3546 int errsv = get_socket_errno ();
3548 g_set_error (error, G_IO_ERROR,
3549 socket_io_error_from_errno (errsv),
3550 _("Waiting for socket condition: %s"),
3551 socket_strerror (errsv));
3554 else if (res == WSA_WAIT_TIMEOUT)
3556 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3557 _("Socket I/O timed out"));
3561 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3564 current_condition = update_condition (socket);
3566 if (timeout != WSA_INFINITE)
3568 timeout -= (g_get_monotonic_time () - start_time) * 1000;
3573 remove_condition_watch (socket, &condition);
3575 g_cancellable_release_fd (cancellable);
3577 return (condition & current_condition) != 0;
3585 poll_fd[0].fd = socket->priv->fd;
3586 poll_fd[0].events = condition;
3589 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
3594 result = g_poll (poll_fd, num, timeout);
3595 if (result != -1 || errno != EINTR)
3600 timeout -= (g_get_monotonic_time () - start_time) * 1000;
3607 g_cancellable_release_fd (cancellable);
3611 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3612 _("Socket I/O timed out"));
3616 return !g_cancellable_set_error_if_cancelled (cancellable, error);
3622 * g_socket_send_message:
3623 * @socket: a #GSocket
3624 * @address: (allow-none): a #GSocketAddress, or %NULL
3625 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
3626 * @num_vectors: the number of elements in @vectors, or -1
3627 * @messages: (array length=num_messages) (allow-none): a pointer to an
3628 * array of #GSocketControlMessages, or %NULL.
3629 * @num_messages: number of elements in @messages, or -1.
3630 * @flags: an int containing #GSocketMsgFlags flags
3631 * @cancellable: (allow-none): a %GCancellable or %NULL
3632 * @error: #GError for error reporting, or %NULL to ignore.
3634 * Send data to @address on @socket. This is the most complicated and
3635 * fully-featured version of this call. For easier use, see
3636 * g_socket_send() and g_socket_send_to().
3638 * If @address is %NULL then the message is sent to the default receiver
3639 * (set by g_socket_connect()).
3641 * @vectors must point to an array of #GOutputVector structs and
3642 * @num_vectors must be the length of this array. (If @num_vectors is -1,
3643 * then @vectors is assumed to be terminated by a #GOutputVector with a
3644 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
3645 * that the sent data will be gathered from. Using multiple
3646 * #GOutputVector<!-- -->s is more memory-efficient than manually copying
3647 * data from multiple sources into a single buffer, and more
3648 * network-efficient than making multiple calls to g_socket_send().
3650 * @messages, if non-%NULL, is taken to point to an array of @num_messages
3651 * #GSocketControlMessage instances. These correspond to the control
3652 * messages to be sent on the socket.
3653 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
3656 * @flags modify how the message is sent. The commonly available arguments
3657 * for this are available in the #GSocketMsgFlags enum, but the
3658 * values there are the same as the system values, and the flags
3659 * are passed in as-is, so you can pass in system-specific flags too.
3661 * If the socket is in blocking mode the call will block until there is
3662 * space for the data in the socket queue. If there is no space available
3663 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3664 * will be returned. To be notified when space is available, wait for the
3665 * %G_IO_OUT condition. Note though that you may still receive
3666 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3667 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3668 * very common due to the way the underlying APIs work.)
3670 * On error -1 is returned and @error is set accordingly.
3672 * Returns: Number of bytes written (which may be less than @size), or -1
3678 g_socket_send_message (GSocket *socket,
3679 GSocketAddress *address,
3680 GOutputVector *vectors,
3682 GSocketControlMessage **messages,
3685 GCancellable *cancellable,
3688 GOutputVector one_vector;
3691 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3693 if (!check_socket (socket, error))
3696 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3699 if (num_vectors == -1)
3701 for (num_vectors = 0;
3702 vectors[num_vectors].buffer != NULL;
3707 if (num_messages == -1)
3709 for (num_messages = 0;
3710 messages != NULL && messages[num_messages] != NULL;
3715 if (num_vectors == 0)
3719 one_vector.buffer = &zero;
3720 one_vector.size = 1;
3722 vectors = &one_vector;
3735 msg.msg_namelen = g_socket_address_get_native_size (address);
3736 msg.msg_name = g_alloca (msg.msg_namelen);
3737 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
3742 msg.msg_name = NULL;
3743 msg.msg_namelen = 0;
3748 /* this entire expression will be evaluated at compile time */
3749 if (sizeof *msg.msg_iov == sizeof *vectors &&
3750 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3751 G_STRUCT_OFFSET (struct iovec, iov_base) ==
3752 G_STRUCT_OFFSET (GOutputVector, buffer) &&
3753 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3754 G_STRUCT_OFFSET (struct iovec, iov_len) ==
3755 G_STRUCT_OFFSET (GOutputVector, size))
3756 /* ABI is compatible */
3758 msg.msg_iov = (struct iovec *) vectors;
3759 msg.msg_iovlen = num_vectors;
3762 /* ABI is incompatible */
3766 msg.msg_iov = g_newa (struct iovec, num_vectors);
3767 for (i = 0; i < num_vectors; i++)
3769 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
3770 msg.msg_iov[i].iov_len = vectors[i].size;
3772 msg.msg_iovlen = num_vectors;
3778 struct cmsghdr *cmsg;
3781 msg.msg_controllen = 0;
3782 for (i = 0; i < num_messages; i++)
3783 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
3785 if (msg.msg_controllen == 0)
3786 msg.msg_control = NULL;
3789 msg.msg_control = g_alloca (msg.msg_controllen);
3790 memset (msg.msg_control, '\0', msg.msg_controllen);
3793 cmsg = CMSG_FIRSTHDR (&msg);
3794 for (i = 0; i < num_messages; i++)
3796 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
3797 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
3798 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
3799 g_socket_control_message_serialize (messages[i],
3801 cmsg = CMSG_NXTHDR (&msg, cmsg);
3803 g_assert (cmsg == NULL);
3808 if (socket->priv->blocking &&
3809 !g_socket_condition_wait (socket,
3810 G_IO_OUT, cancellable, error))
3813 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
3816 int errsv = get_socket_errno ();
3821 if (socket->priv->blocking &&
3822 (errsv == EWOULDBLOCK ||
3826 g_set_error (error, G_IO_ERROR,
3827 socket_io_error_from_errno (errsv),
3828 _("Error sending message: %s"), socket_strerror (errsv));
3839 struct sockaddr_storage addr;
3846 /* Win32 doesn't support control messages.
3847 Actually this is possible for raw and datagram sockets
3848 via WSASendMessage on Vista or later, but that doesn't
3850 if (num_messages != 0)
3852 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
3853 _("GSocketControlMessage not supported on Windows"));
3858 bufs = g_newa (WSABUF, num_vectors);
3859 for (i = 0; i < num_vectors; i++)
3861 bufs[i].buf = (char *)vectors[i].buffer;
3862 bufs[i].len = (gulong)vectors[i].size;
3866 addrlen = 0; /* Avoid warning */
3869 addrlen = g_socket_address_get_native_size (address);
3870 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
3876 if (socket->priv->blocking &&
3877 !g_socket_condition_wait (socket,
3878 G_IO_OUT, cancellable, error))
3882 result = WSASendTo (socket->priv->fd,
3885 (const struct sockaddr *)&addr, addrlen,
3888 result = WSASend (socket->priv->fd,
3895 int errsv = get_socket_errno ();
3897 if (errsv == WSAEINTR)
3900 if (errsv == WSAEWOULDBLOCK)
3901 win32_unset_event_mask (socket, FD_WRITE);
3903 if (socket->priv->blocking &&
3904 errsv == WSAEWOULDBLOCK)
3907 g_set_error (error, G_IO_ERROR,
3908 socket_io_error_from_errno (errsv),
3909 _("Error sending message: %s"), socket_strerror (errsv));
3921 static GSocketAddress *
3922 cache_recv_address (GSocket *socket, struct sockaddr *native, int native_len)
3924 GSocketAddress *saddr;
3926 guint64 oldest_time = G_MAXUINT64;
3927 gint oldest_index = 0;
3929 if (native_len <= 0)
3933 for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
3935 GSocketAddress *tmp = socket->priv->recv_addr_cache[i].addr;
3936 gpointer tmp_native = socket->priv->recv_addr_cache[i].native;
3937 gint tmp_native_len = socket->priv->recv_addr_cache[i].native_len;
3942 if (tmp_native_len != native_len)
3945 if (memcmp (tmp_native, native, native_len) == 0)
3947 saddr = g_object_ref (tmp);
3948 socket->priv->recv_addr_cache[i].last_used = g_get_monotonic_time ();
3952 if (socket->priv->recv_addr_cache[i].last_used < oldest_time)
3954 oldest_time = socket->priv->recv_addr_cache[i].last_used;
3959 saddr = g_socket_address_new_from_native (native, native_len);
3961 if (socket->priv->recv_addr_cache[oldest_index].addr)
3963 g_object_unref (socket->priv->recv_addr_cache[oldest_index].addr);
3964 g_free (socket->priv->recv_addr_cache[oldest_index].native);
3967 socket->priv->recv_addr_cache[oldest_index].native = g_memdup (native, native_len);
3968 socket->priv->recv_addr_cache[oldest_index].native_len = native_len;
3969 socket->priv->recv_addr_cache[oldest_index].addr = g_object_ref (saddr);
3970 socket->priv->recv_addr_cache[oldest_index].last_used = g_get_monotonic_time ();
3976 * g_socket_receive_message:
3977 * @socket: a #GSocket
3978 * @address: (out) (allow-none): a pointer to a #GSocketAddress
3980 * @vectors: (array length=num_vectors): an array of #GInputVector structs
3981 * @num_vectors: the number of elements in @vectors, or -1
3982 * @messages: (array length=num_messages) (allow-none): a pointer which
3983 * may be filled with an array of #GSocketControlMessages, or %NULL
3984 * @num_messages: a pointer which will be filled with the number of
3985 * elements in @messages, or %NULL
3986 * @flags: a pointer to an int containing #GSocketMsgFlags flags
3987 * @cancellable: (allow-none): a %GCancellable or %NULL
3988 * @error: a #GError pointer, or %NULL
3990 * Receive data from a socket. This is the most complicated and
3991 * fully-featured version of this call. For easier use, see
3992 * g_socket_receive() and g_socket_receive_from().
3994 * If @address is non-%NULL then @address will be set equal to the
3995 * source address of the received packet.
3996 * @address is owned by the caller.
3998 * @vector must point to an array of #GInputVector structs and
3999 * @num_vectors must be the length of this array. These structs
4000 * describe the buffers that received data will be scattered into.
4001 * If @num_vectors is -1, then @vectors is assumed to be terminated
4002 * by a #GInputVector with a %NULL buffer pointer.
4004 * As a special case, if @num_vectors is 0 (in which case, @vectors
4005 * may of course be %NULL), then a single byte is received and
4006 * discarded. This is to facilitate the common practice of sending a
4007 * single '\0' byte for the purposes of transferring ancillary data.
4009 * @messages, if non-%NULL, will be set to point to a newly-allocated
4010 * array of #GSocketControlMessage instances or %NULL if no such
4011 * messages was received. These correspond to the control messages
4012 * received from the kernel, one #GSocketControlMessage per message
4013 * from the kernel. This array is %NULL-terminated and must be freed
4014 * by the caller using g_free() after calling g_object_unref() on each
4015 * element. If @messages is %NULL, any control messages received will
4018 * @num_messages, if non-%NULL, will be set to the number of control
4019 * messages received.
4021 * If both @messages and @num_messages are non-%NULL, then
4022 * @num_messages gives the number of #GSocketControlMessage instances
4023 * in @messages (ie: not including the %NULL terminator).
4025 * @flags is an in/out parameter. The commonly available arguments
4026 * for this are available in the #GSocketMsgFlags enum, but the
4027 * values there are the same as the system values, and the flags
4028 * are passed in as-is, so you can pass in system-specific flags too
4029 * (and g_socket_receive_message() may pass system-specific flags out).
4031 * As with g_socket_receive(), data may be discarded if @socket is
4032 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
4033 * provide enough buffer space to read a complete message. You can pass
4034 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
4035 * removing it from the receive queue, but there is no portable way to find
4036 * out the length of the message other than by reading it into a
4037 * sufficiently-large buffer.
4039 * If the socket is in blocking mode the call will block until there
4040 * is some data to receive, the connection is closed, or there is an
4041 * error. If there is no data available and the socket is in
4042 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
4043 * returned. To be notified when data is available, wait for the
4044 * %G_IO_IN condition.
4046 * On error -1 is returned and @error is set accordingly.
4048 * Returns: Number of bytes read, or 0 if the connection was closed by
4049 * the peer, or -1 on error
4054 g_socket_receive_message (GSocket *socket,
4055 GSocketAddress **address,
4056 GInputVector *vectors,
4058 GSocketControlMessage ***messages,
4061 GCancellable *cancellable,
4064 GInputVector one_vector;
4067 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
4069 if (!check_socket (socket, error))
4072 if (g_cancellable_set_error_if_cancelled (cancellable, error))
4075 if (num_vectors == -1)
4077 for (num_vectors = 0;
4078 vectors[num_vectors].buffer != NULL;
4083 if (num_vectors == 0)
4085 one_vector.buffer = &one_byte;
4086 one_vector.size = 1;
4088 vectors = &one_vector;
4095 struct sockaddr_storage one_sockaddr;
4100 msg.msg_name = &one_sockaddr;
4101 msg.msg_namelen = sizeof (struct sockaddr_storage);
4105 msg.msg_name = NULL;
4106 msg.msg_namelen = 0;
4110 /* this entire expression will be evaluated at compile time */
4111 if (sizeof *msg.msg_iov == sizeof *vectors &&
4112 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
4113 G_STRUCT_OFFSET (struct iovec, iov_base) ==
4114 G_STRUCT_OFFSET (GInputVector, buffer) &&
4115 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
4116 G_STRUCT_OFFSET (struct iovec, iov_len) ==
4117 G_STRUCT_OFFSET (GInputVector, size))
4118 /* ABI is compatible */
4120 msg.msg_iov = (struct iovec *) vectors;
4121 msg.msg_iovlen = num_vectors;
4124 /* ABI is incompatible */
4128 msg.msg_iov = g_newa (struct iovec, num_vectors);
4129 for (i = 0; i < num_vectors; i++)
4131 msg.msg_iov[i].iov_base = vectors[i].buffer;
4132 msg.msg_iov[i].iov_len = vectors[i].size;
4134 msg.msg_iovlen = num_vectors;
4138 msg.msg_control = g_alloca (2048);
4139 msg.msg_controllen = 2048;
4143 msg.msg_flags = *flags;
4147 /* We always set the close-on-exec flag so we don't leak file
4148 * descriptors into child processes. Note that gunixfdmessage.c
4149 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
4151 #ifdef MSG_CMSG_CLOEXEC
4152 msg.msg_flags |= MSG_CMSG_CLOEXEC;
4158 if (socket->priv->blocking &&
4159 !g_socket_condition_wait (socket,
4160 G_IO_IN, cancellable, error))
4163 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4164 #ifdef MSG_CMSG_CLOEXEC
4165 if (result < 0 && get_socket_errno () == EINVAL)
4167 /* We must be running on an old kernel. Call without the flag. */
4168 msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
4169 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4175 int errsv = get_socket_errno ();
4180 if (socket->priv->blocking &&
4181 (errsv == EWOULDBLOCK ||
4185 g_set_error (error, G_IO_ERROR,
4186 socket_io_error_from_errno (errsv),
4187 _("Error receiving message: %s"), socket_strerror (errsv));
4194 /* decode address */
4195 if (address != NULL)
4197 *address = cache_recv_address (socket, msg.msg_name, msg.msg_namelen);
4200 /* decode control messages */
4202 GPtrArray *my_messages = NULL;
4203 struct cmsghdr *cmsg;
4205 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
4207 GSocketControlMessage *message;
4209 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
4211 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
4213 if (message == NULL)
4214 /* We've already spewed about the problem in the
4215 deserialization code, so just continue */
4218 if (messages == NULL)
4220 /* we have to do it this way if the user ignores the
4221 * messages so that we will close any received fds.
4223 g_object_unref (message);
4227 if (my_messages == NULL)
4228 my_messages = g_ptr_array_new ();
4229 g_ptr_array_add (my_messages, message);
4234 *num_messages = my_messages != NULL ? my_messages->len : 0;
4238 if (my_messages == NULL)
4244 g_ptr_array_add (my_messages, NULL);
4245 *messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
4250 g_assert (my_messages == NULL);
4254 /* capture the flags */
4256 *flags = msg.msg_flags;
4262 struct sockaddr_storage addr;
4264 DWORD bytes_received;
4271 bufs = g_newa (WSABUF, num_vectors);
4272 for (i = 0; i < num_vectors; i++)
4274 bufs[i].buf = (char *)vectors[i].buffer;
4275 bufs[i].len = (gulong)vectors[i].size;
4287 if (socket->priv->blocking &&
4288 !g_socket_condition_wait (socket,
4289 G_IO_IN, cancellable, error))
4292 addrlen = sizeof addr;
4294 result = WSARecvFrom (socket->priv->fd,
4296 &bytes_received, &win_flags,
4297 (struct sockaddr *)&addr, &addrlen,
4300 result = WSARecv (socket->priv->fd,
4302 &bytes_received, &win_flags,
4306 int errsv = get_socket_errno ();
4308 if (errsv == WSAEINTR)
4311 win32_unset_event_mask (socket, FD_READ);
4313 if (socket->priv->blocking &&
4314 errsv == WSAEWOULDBLOCK)
4317 g_set_error (error, G_IO_ERROR,
4318 socket_io_error_from_errno (errsv),
4319 _("Error receiving message: %s"), socket_strerror (errsv));
4323 win32_unset_event_mask (socket, FD_READ);
4327 /* decode address */
4328 if (address != NULL)
4330 *address = cache_recv_address (socket, &addr, addrlen);
4333 /* capture the flags */
4337 if (messages != NULL)
4339 if (num_messages != NULL)
4342 return bytes_received;
4348 * g_socket_get_credentials:
4349 * @socket: a #GSocket.
4350 * @error: #GError for error reporting, or %NULL to ignore.
4352 * Returns the credentials of the foreign process connected to this
4353 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
4356 * If this operation isn't supported on the OS, the method fails with
4357 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
4358 * by reading the %SO_PEERCRED option on the underlying socket.
4360 * Other ways to obtain credentials from a foreign peer includes the
4361 * #GUnixCredentialsMessage type and
4362 * g_unix_connection_send_credentials() /
4363 * g_unix_connection_receive_credentials() functions.
4365 * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
4366 * that must be freed with g_object_unref().
4371 g_socket_get_credentials (GSocket *socket,
4376 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
4377 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
4381 #if defined(__linux__) || defined(__OpenBSD__)
4384 #if defined(__linux__)
4385 struct ucred native_creds;
4386 optlen = sizeof (struct ucred);
4387 #elif defined(__OpenBSD__)
4388 struct sockpeercred native_creds;
4389 optlen = sizeof (struct sockpeercred);
4391 if (getsockopt (socket->priv->fd,
4394 (void *)&native_creds,
4397 int errsv = get_socket_errno ();
4400 socket_io_error_from_errno (errsv),
4401 _("Unable to get pending error: %s"),
4402 socket_strerror (errsv));
4406 ret = g_credentials_new ();
4407 g_credentials_set_native (ret,
4408 #if defined(__linux__)
4409 G_CREDENTIALS_TYPE_LINUX_UCRED,
4410 #elif defined(__OpenBSD__)
4411 G_CREDENTIALS_TYPE_OPENBSD_SOCKPEERCRED,
4417 g_set_error_literal (error,
4419 G_IO_ERROR_NOT_SUPPORTED,
4420 _("g_socket_get_credentials not implemented for this OS"));