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"
50 #include "gcancellable.h"
51 #include "gioenumtypes.h"
52 #include "ginetaddress.h"
53 #include "ginitable.h"
57 #include "gio-marshal.h"
58 #include "gnetworkingprivate.h"
59 #include "gsocketaddress.h"
60 #include "gsocketcontrolmessage.h"
61 #include "gcredentials.h"
66 * @short_description: Low-level socket object
68 * @see_also: #GInitable
70 * A #GSocket is a low-level networking primitive. It is a more or less
71 * direct mapping of the BSD socket API in a portable GObject based API.
72 * It supports both the UNIX socket implementations and winsock2 on Windows.
74 * #GSocket is the platform independent base upon which the higher level
75 * network primitives are based. Applications are not typically meant to
76 * use it directly, but rather through classes like #GSocketClient,
77 * #GSocketService and #GSocketConnection. However there may be cases where
78 * direct use of #GSocket is useful.
80 * #GSocket implements the #GInitable interface, so if it is manually constructed
81 * by e.g. g_object_new() you must call g_initable_init() and check the
82 * results before using the object. This is done automatically in
83 * g_socket_new() and g_socket_new_from_fd(), so these functions can return
86 * Sockets operate in two general modes, blocking or non-blocking. When
87 * in blocking mode all operations block until the requested operation
88 * is finished or there is an error. In non-blocking mode all calls that
89 * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
90 * To know when a call would successfully run you can call g_socket_condition_check(),
91 * or g_socket_condition_wait(). You can also use g_socket_create_source() and
92 * attach it to a #GMainContext to get callbacks when I/O is possible.
93 * Note that all sockets are always set to non blocking mode in the system, and
94 * blocking mode is emulated in GSocket.
96 * When working in non-blocking mode applications should always be able to
97 * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
98 * function said that I/O was possible. This can easily happen in case
99 * of a race condition in the application, but it can also happen for other
100 * reasons. For instance, on Windows a socket is always seen as writable
101 * until a write returns %G_IO_ERROR_WOULD_BLOCK.
103 * #GSocket<!-- -->s can be either connection oriented or datagram based.
104 * For connection oriented types you must first establish a connection by
105 * either connecting to an address or accepting a connection from another
106 * address. For connectionless socket types the target/source address is
107 * specified or received in each I/O operation.
109 * All socket file descriptors are set to be close-on-exec.
111 * Note that creating a #GSocket causes the signal %SIGPIPE to be
112 * ignored for the remainder of the program. If you are writing a
113 * command-line utility that uses #GSocket, you may need to take into
114 * account the fact that your program will not automatically be killed
115 * if it tries to write to %stdout after it has been closed.
120 static void g_socket_initable_iface_init (GInitableIface *iface);
121 static gboolean g_socket_initable_init (GInitable *initable,
122 GCancellable *cancellable,
125 G_DEFINE_TYPE_WITH_CODE (GSocket, g_socket, G_TYPE_OBJECT,
126 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
127 g_socket_initable_iface_init));
144 struct _GSocketPrivate
146 GSocketFamily family;
148 GSocketProtocol protocol;
152 GError *construct_error;
153 GSocketAddress *remote_address;
161 guint connect_pending : 1;
167 GList *requested_conditions; /* list of requested GIOCondition * */
172 get_socket_errno (void)
177 return WSAGetLastError ();
182 socket_io_error_from_errno (int err)
185 return g_io_error_from_errno (err);
190 return G_IO_ERROR_ADDRESS_IN_USE;
192 return G_IO_ERROR_WOULD_BLOCK;
194 return G_IO_ERROR_PERMISSION_DENIED;
195 case WSA_INVALID_HANDLE:
196 case WSA_INVALID_PARAMETER:
199 return G_IO_ERROR_INVALID_ARGUMENT;
200 case WSAEPROTONOSUPPORT:
201 return G_IO_ERROR_NOT_SUPPORTED;
203 return G_IO_ERROR_CANCELLED;
204 case WSAESOCKTNOSUPPORT:
206 case WSAEPFNOSUPPORT:
207 case WSAEAFNOSUPPORT:
208 return G_IO_ERROR_NOT_SUPPORTED;
210 return G_IO_ERROR_FAILED;
216 socket_strerror (int err)
219 return g_strerror (err);
221 static GStaticPrivate last_msg = G_STATIC_PRIVATE_INIT;
224 msg = g_win32_error_message (err);
225 g_static_private_set (&last_msg, msg, g_free);
232 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
234 _win32_unset_event_mask (GSocket *socket, int mask)
236 socket->priv->current_events &= ~mask;
237 socket->priv->current_errors &= ~mask;
240 #define win32_unset_event_mask(_socket, _mask)
244 set_fd_nonblocking (int fd)
247 GError *error = NULL;
253 if (!g_unix_set_fd_nonblocking (fd, TRUE, &error))
255 g_warning ("Error setting socket nonblocking: %s", error->message);
256 g_clear_error (&error);
261 if (ioctlsocket (fd, FIONBIO, &arg) == SOCKET_ERROR)
263 int errsv = get_socket_errno ();
264 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
270 check_socket (GSocket *socket,
273 if (!socket->priv->inited)
275 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
276 _("Invalid socket, not initialized"));
280 if (socket->priv->construct_error)
282 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
283 _("Invalid socket, initialization failed due to: %s"),
284 socket->priv->construct_error->message);
288 if (socket->priv->closed)
290 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
291 _("Socket is already closed"));
295 if (socket->priv->timed_out)
297 socket->priv->timed_out = FALSE;
298 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
299 _("Socket I/O timed out"));
307 g_socket_details_from_fd (GSocket *socket)
309 struct sockaddr_storage address;
316 /* See bug #611756 */
317 BOOL bool_val = FALSE;
322 fd = socket->priv->fd;
323 optlen = sizeof value;
324 if (getsockopt (fd, SOL_SOCKET, SO_TYPE, (void *)&value, &optlen) != 0)
326 errsv = get_socket_errno ();
337 /* programmer error */
338 g_error ("creating GSocket from fd %d: %s\n",
339 fd, socket_strerror (errsv));
347 g_assert (optlen == sizeof value);
351 socket->priv->type = G_SOCKET_TYPE_STREAM;
355 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
359 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
363 socket->priv->type = G_SOCKET_TYPE_INVALID;
367 addrlen = sizeof address;
368 if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
370 errsv = get_socket_errno ();
374 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
375 sizeof address.ss_family <= addrlen);
376 switch (address.ss_family)
378 case G_SOCKET_FAMILY_IPV4:
379 case G_SOCKET_FAMILY_IPV6:
380 socket->priv->family = address.ss_family;
381 switch (socket->priv->type)
383 case G_SOCKET_TYPE_STREAM:
384 socket->priv->protocol = G_SOCKET_PROTOCOL_TCP;
387 case G_SOCKET_TYPE_DATAGRAM:
388 socket->priv->protocol = G_SOCKET_PROTOCOL_UDP;
391 case G_SOCKET_TYPE_SEQPACKET:
392 socket->priv->protocol = G_SOCKET_PROTOCOL_SCTP;
400 case G_SOCKET_FAMILY_UNIX:
401 socket->priv->family = G_SOCKET_FAMILY_UNIX;
402 socket->priv->protocol = G_SOCKET_PROTOCOL_DEFAULT;
406 socket->priv->family = G_SOCKET_FAMILY_INVALID;
410 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
412 addrlen = sizeof address;
413 if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
414 socket->priv->connected = TRUE;
417 optlen = sizeof bool_val;
418 if (getsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
419 (void *)&bool_val, &optlen) == 0)
422 /* Experimentation indicates that the SO_KEEPALIVE value is
423 * actually a char on Windows, even if documentation claims it
424 * to be a BOOL which is a typedef for int. So this g_assert()
425 * fails. See bug #611756.
427 g_assert (optlen == sizeof bool_val);
429 socket->priv->keepalive = !!bool_val;
433 /* Can't read, maybe not supported, assume FALSE */
434 socket->priv->keepalive = FALSE;
440 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
441 socket_io_error_from_errno (errsv),
442 _("creating GSocket from fd: %s"),
443 socket_strerror (errsv));
447 g_socket_create_socket (GSocketFamily family,
457 case G_SOCKET_TYPE_STREAM:
458 native_type = SOCK_STREAM;
461 case G_SOCKET_TYPE_DATAGRAM:
462 native_type = SOCK_DGRAM;
465 case G_SOCKET_TYPE_SEQPACKET:
466 native_type = SOCK_SEQPACKET;
470 g_assert_not_reached ();
475 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
476 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
481 fd = socket (family, native_type | SOCK_CLOEXEC, protocol);
482 /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
483 if (fd < 0 && errno == EINVAL)
485 fd = socket (family, native_type, protocol);
489 int errsv = get_socket_errno ();
491 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
492 _("Unable to create socket: %s"), socket_strerror (errsv));
499 /* We always want to set close-on-exec to protect users. If you
500 need to so some weird inheritance to exec you can re-enable this
501 using lower level hacks with g_socket_get_fd(). */
502 flags = fcntl (fd, F_GETFD, 0);
504 (flags & FD_CLOEXEC) == 0)
507 fcntl (fd, F_SETFD, flags);
516 g_socket_constructed (GObject *object)
518 GSocket *socket = G_SOCKET (object);
520 if (socket->priv->fd >= 0)
521 /* create socket->priv info from the fd */
522 g_socket_details_from_fd (socket);
525 /* create the fd from socket->priv info */
526 socket->priv->fd = g_socket_create_socket (socket->priv->family,
528 socket->priv->protocol,
529 &socket->priv->construct_error);
531 /* Always use native nonblocking sockets, as
532 windows sets sockets to nonblocking automatically
533 in certain operations. This way we make things work
534 the same on all platforms */
535 if (socket->priv->fd != -1)
536 set_fd_nonblocking (socket->priv->fd);
540 g_socket_get_property (GObject *object,
545 GSocket *socket = G_SOCKET (object);
546 GSocketAddress *address;
551 g_value_set_enum (value, socket->priv->family);
555 g_value_set_enum (value, socket->priv->type);
559 g_value_set_enum (value, socket->priv->protocol);
563 g_value_set_int (value, socket->priv->fd);
567 g_value_set_boolean (value, socket->priv->blocking);
570 case PROP_LISTEN_BACKLOG:
571 g_value_set_int (value, socket->priv->listen_backlog);
575 g_value_set_boolean (value, socket->priv->keepalive);
578 case PROP_LOCAL_ADDRESS:
579 address = g_socket_get_local_address (socket, NULL);
580 g_value_take_object (value, address);
583 case PROP_REMOTE_ADDRESS:
584 address = g_socket_get_remote_address (socket, NULL);
585 g_value_take_object (value, address);
589 g_value_set_uint (value, socket->priv->timeout);
593 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
598 g_socket_set_property (GObject *object,
603 GSocket *socket = G_SOCKET (object);
608 socket->priv->family = g_value_get_enum (value);
612 socket->priv->type = g_value_get_enum (value);
616 socket->priv->protocol = g_value_get_enum (value);
620 socket->priv->fd = g_value_get_int (value);
624 g_socket_set_blocking (socket, g_value_get_boolean (value));
627 case PROP_LISTEN_BACKLOG:
628 g_socket_set_listen_backlog (socket, g_value_get_int (value));
632 g_socket_set_keepalive (socket, g_value_get_boolean (value));
636 g_socket_set_timeout (socket, g_value_get_uint (value));
640 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
645 g_socket_finalize (GObject *object)
647 GSocket *socket = G_SOCKET (object);
649 g_clear_error (&socket->priv->construct_error);
651 if (socket->priv->fd != -1 &&
652 !socket->priv->closed)
653 g_socket_close (socket, NULL);
655 if (socket->priv->remote_address)
656 g_object_unref (socket->priv->remote_address);
659 if (socket->priv->event != WSA_INVALID_EVENT)
661 WSACloseEvent (socket->priv->event);
662 socket->priv->event = WSA_INVALID_EVENT;
665 g_assert (socket->priv->requested_conditions == NULL);
668 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
669 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
673 g_socket_class_init (GSocketClass *klass)
675 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
678 /* Make sure winsock has been initialized */
679 type = g_inet_address_get_type ();
680 (type); /* To avoid -Wunused-but-set-variable */
683 /* There is no portable, thread-safe way to avoid having the process
684 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
685 * forced to simply ignore the signal process-wide.
687 signal (SIGPIPE, SIG_IGN);
690 g_type_class_add_private (klass, sizeof (GSocketPrivate));
692 gobject_class->finalize = g_socket_finalize;
693 gobject_class->constructed = g_socket_constructed;
694 gobject_class->set_property = g_socket_set_property;
695 gobject_class->get_property = g_socket_get_property;
697 g_object_class_install_property (gobject_class, PROP_FAMILY,
698 g_param_spec_enum ("family",
700 P_("The sockets address family"),
701 G_TYPE_SOCKET_FAMILY,
702 G_SOCKET_FAMILY_INVALID,
703 G_PARAM_CONSTRUCT_ONLY |
705 G_PARAM_STATIC_STRINGS));
707 g_object_class_install_property (gobject_class, PROP_TYPE,
708 g_param_spec_enum ("type",
710 P_("The sockets type"),
712 G_SOCKET_TYPE_STREAM,
713 G_PARAM_CONSTRUCT_ONLY |
715 G_PARAM_STATIC_STRINGS));
717 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
718 g_param_spec_enum ("protocol",
719 P_("Socket protocol"),
720 P_("The id of the protocol to use, or -1 for unknown"),
721 G_TYPE_SOCKET_PROTOCOL,
722 G_SOCKET_PROTOCOL_UNKNOWN,
723 G_PARAM_CONSTRUCT_ONLY |
725 G_PARAM_STATIC_STRINGS));
727 g_object_class_install_property (gobject_class, PROP_FD,
728 g_param_spec_int ("fd",
729 P_("File descriptor"),
730 P_("The sockets file descriptor"),
734 G_PARAM_CONSTRUCT_ONLY |
736 G_PARAM_STATIC_STRINGS));
738 g_object_class_install_property (gobject_class, PROP_BLOCKING,
739 g_param_spec_boolean ("blocking",
741 P_("Whether or not I/O on this socket is blocking"),
744 G_PARAM_STATIC_STRINGS));
746 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
747 g_param_spec_int ("listen-backlog",
748 P_("Listen backlog"),
749 P_("Outstanding connections in the listen queue"),
754 G_PARAM_STATIC_STRINGS));
756 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
757 g_param_spec_boolean ("keepalive",
758 P_("Keep connection alive"),
759 P_("Keep connection alive by sending periodic pings"),
762 G_PARAM_STATIC_STRINGS));
764 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
765 g_param_spec_object ("local-address",
767 P_("The local address the socket is bound to"),
768 G_TYPE_SOCKET_ADDRESS,
770 G_PARAM_STATIC_STRINGS));
772 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
773 g_param_spec_object ("remote-address",
774 P_("Remote address"),
775 P_("The remote address the socket is connected to"),
776 G_TYPE_SOCKET_ADDRESS,
778 G_PARAM_STATIC_STRINGS));
783 * The timeout in seconds on socket I/O
787 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
788 g_param_spec_uint ("timeout",
790 P_("The timeout in seconds on socket I/O"),
795 G_PARAM_STATIC_STRINGS));
799 g_socket_initable_iface_init (GInitableIface *iface)
801 iface->init = g_socket_initable_init;
805 g_socket_init (GSocket *socket)
807 socket->priv = G_TYPE_INSTANCE_GET_PRIVATE (socket, G_TYPE_SOCKET, GSocketPrivate);
809 socket->priv->fd = -1;
810 socket->priv->blocking = TRUE;
811 socket->priv->listen_backlog = 10;
812 socket->priv->construct_error = NULL;
814 socket->priv->event = WSA_INVALID_EVENT;
819 g_socket_initable_init (GInitable *initable,
820 GCancellable *cancellable,
825 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
827 socket = G_SOCKET (initable);
829 if (cancellable != NULL)
831 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
832 _("Cancellable initialization not supported"));
836 socket->priv->inited = TRUE;
838 if (socket->priv->construct_error)
841 *error = g_error_copy (socket->priv->construct_error);
851 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
852 * @type: the socket type to use.
853 * @protocol: the id of the protocol to use, or 0 for default.
854 * @error: #GError for error reporting, or %NULL to ignore.
856 * Creates a new #GSocket with the defined family, type and protocol.
857 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
858 * for the family and type is used.
860 * The @protocol is a family and type specific int that specifies what
861 * kind of protocol to use. #GSocketProtocol lists several common ones.
862 * Many families only support one protocol, and use 0 for this, others
863 * support several and using 0 means to use the default protocol for
864 * the family and type.
866 * The protocol id is passed directly to the operating
867 * system, so you can use protocols not listed in #GSocketProtocol if you
868 * know the protocol number used for it.
870 * Returns: a #GSocket or %NULL on error.
871 * Free the returned object with g_object_unref().
876 g_socket_new (GSocketFamily family,
878 GSocketProtocol protocol,
881 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
885 "protocol", protocol,
890 * g_socket_new_from_fd:
891 * @fd: a native socket file descriptor.
892 * @error: #GError for error reporting, or %NULL to ignore.
894 * Creates a new #GSocket from a native file descriptor
895 * or winsock SOCKET handle.
897 * This reads all the settings from the file descriptor so that
898 * all properties should work. Note that the file descriptor
899 * will be set to non-blocking mode, independent on the blocking
900 * mode of the #GSocket.
902 * Returns: a #GSocket or %NULL on error.
903 * Free the returned object with g_object_unref().
908 g_socket_new_from_fd (gint fd,
911 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
918 * g_socket_set_blocking:
919 * @socket: a #GSocket.
920 * @blocking: Whether to use blocking I/O or not.
922 * Sets the blocking mode of the socket. In blocking mode
923 * all operations block until they succeed or there is an error. In
924 * non-blocking mode all functions return results immediately or
925 * with a %G_IO_ERROR_WOULD_BLOCK error.
927 * All sockets are created in blocking mode. However, note that the
928 * platform level socket is always non-blocking, and blocking mode
929 * is a GSocket level feature.
934 g_socket_set_blocking (GSocket *socket,
937 g_return_if_fail (G_IS_SOCKET (socket));
939 blocking = !!blocking;
941 if (socket->priv->blocking == blocking)
944 socket->priv->blocking = blocking;
945 g_object_notify (G_OBJECT (socket), "blocking");
949 * g_socket_get_blocking:
950 * @socket: a #GSocket.
952 * Gets the blocking mode of the socket. For details on blocking I/O,
953 * see g_socket_set_blocking().
955 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
960 g_socket_get_blocking (GSocket *socket)
962 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
964 return socket->priv->blocking;
968 * g_socket_set_keepalive:
969 * @socket: a #GSocket.
970 * @keepalive: Value for the keepalive flag
972 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
973 * this flag is set on a socket, the system will attempt to verify that the
974 * remote socket endpoint is still present if a sufficiently long period of
975 * time passes with no data being exchanged. If the system is unable to
976 * verify the presence of the remote endpoint, it will automatically close
979 * This option is only functional on certain kinds of sockets. (Notably,
980 * %G_SOCKET_PROTOCOL_TCP sockets.)
982 * The exact time between pings is system- and protocol-dependent, but will
983 * normally be at least two hours. Most commonly, you would set this flag
984 * on a server socket if you want to allow clients to remain idle for long
985 * periods of time, but also want to ensure that connections are eventually
986 * garbage-collected if clients crash or become unreachable.
991 g_socket_set_keepalive (GSocket *socket,
996 g_return_if_fail (G_IS_SOCKET (socket));
998 keepalive = !!keepalive;
999 if (socket->priv->keepalive == keepalive)
1002 value = (gint) keepalive;
1003 if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_KEEPALIVE,
1004 (gpointer) &value, sizeof (value)) < 0)
1006 int errsv = get_socket_errno ();
1007 g_warning ("error setting keepalive: %s", socket_strerror (errsv));
1011 socket->priv->keepalive = keepalive;
1012 g_object_notify (G_OBJECT (socket), "keepalive");
1016 * g_socket_get_keepalive:
1017 * @socket: a #GSocket.
1019 * Gets the keepalive mode of the socket. For details on this,
1020 * see g_socket_set_keepalive().
1022 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1027 g_socket_get_keepalive (GSocket *socket)
1029 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1031 return socket->priv->keepalive;
1035 * g_socket_get_listen_backlog:
1036 * @socket: a #GSocket.
1038 * Gets the listen backlog setting of the socket. For details on this,
1039 * see g_socket_set_listen_backlog().
1041 * Returns: the maximum number of pending connections.
1046 g_socket_get_listen_backlog (GSocket *socket)
1048 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1050 return socket->priv->listen_backlog;
1054 * g_socket_set_listen_backlog:
1055 * @socket: a #GSocket.
1056 * @backlog: the maximum number of pending connections.
1058 * Sets the maximum number of outstanding connections allowed
1059 * when listening on this socket. If more clients than this are
1060 * connecting to the socket and the application is not handling them
1061 * on time then the new connections will be refused.
1063 * Note that this must be called before g_socket_listen() and has no
1064 * effect if called after that.
1069 g_socket_set_listen_backlog (GSocket *socket,
1072 g_return_if_fail (G_IS_SOCKET (socket));
1073 g_return_if_fail (!socket->priv->listening);
1075 if (backlog != socket->priv->listen_backlog)
1077 socket->priv->listen_backlog = backlog;
1078 g_object_notify (G_OBJECT (socket), "listen-backlog");
1083 * g_socket_get_timeout:
1084 * @socket: a #GSocket.
1086 * Gets the timeout setting of the socket. For details on this, see
1087 * g_socket_set_timeout().
1089 * Returns: the timeout in seconds
1094 g_socket_get_timeout (GSocket *socket)
1096 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1098 return socket->priv->timeout;
1102 * g_socket_set_timeout:
1103 * @socket: a #GSocket.
1104 * @timeout: the timeout for @socket, in seconds, or 0 for none
1106 * Sets the time in seconds after which I/O operations on @socket will
1107 * time out if they have not yet completed.
1109 * On a blocking socket, this means that any blocking #GSocket
1110 * operation will time out after @timeout seconds of inactivity,
1111 * returning %G_IO_ERROR_TIMED_OUT.
1113 * On a non-blocking socket, calls to g_socket_condition_wait() will
1114 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1115 * created with g_socket_create_source() will trigger after
1116 * @timeout seconds of inactivity, with the requested condition
1117 * set, at which point calling g_socket_receive(), g_socket_send(),
1118 * g_socket_check_connect_result(), etc, will fail with
1119 * %G_IO_ERROR_TIMED_OUT.
1121 * If @timeout is 0 (the default), operations will never time out
1124 * Note that if an I/O operation is interrupted by a signal, this may
1125 * cause the timeout to be reset.
1130 g_socket_set_timeout (GSocket *socket,
1133 g_return_if_fail (G_IS_SOCKET (socket));
1135 if (timeout != socket->priv->timeout)
1137 socket->priv->timeout = timeout;
1138 g_object_notify (G_OBJECT (socket), "timeout");
1143 * g_socket_get_family:
1144 * @socket: a #GSocket.
1146 * Gets the socket family of the socket.
1148 * Returns: a #GSocketFamily
1153 g_socket_get_family (GSocket *socket)
1155 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1157 return socket->priv->family;
1161 * g_socket_get_socket_type:
1162 * @socket: a #GSocket.
1164 * Gets the socket type of the socket.
1166 * Returns: a #GSocketType
1171 g_socket_get_socket_type (GSocket *socket)
1173 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1175 return socket->priv->type;
1179 * g_socket_get_protocol:
1180 * @socket: a #GSocket.
1182 * Gets the socket protocol id the socket was created with.
1183 * In case the protocol is unknown, -1 is returned.
1185 * Returns: a protocol id, or -1 if unknown
1190 g_socket_get_protocol (GSocket *socket)
1192 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1194 return socket->priv->protocol;
1199 * @socket: a #GSocket.
1201 * Returns the underlying OS socket object. On unix this
1202 * is a socket file descriptor, and on windows this is
1203 * a Winsock2 SOCKET handle. This may be useful for
1204 * doing platform specific or otherwise unusual operations
1207 * Returns: the file descriptor of the socket.
1212 g_socket_get_fd (GSocket *socket)
1214 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1216 return socket->priv->fd;
1220 * g_socket_get_local_address:
1221 * @socket: a #GSocket.
1222 * @error: #GError for error reporting, or %NULL to ignore.
1224 * Try to get the local address of a bound socket. This is only
1225 * useful if the socket has been bound to a local address,
1226 * either explicitly or implicitly when connecting.
1228 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1229 * Free the returned object with g_object_unref().
1234 g_socket_get_local_address (GSocket *socket,
1237 struct sockaddr_storage buffer;
1238 guint32 len = sizeof (buffer);
1240 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1242 if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1244 int errsv = get_socket_errno ();
1245 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1246 _("could not get local address: %s"), socket_strerror (errsv));
1250 return g_socket_address_new_from_native (&buffer, len);
1254 * g_socket_get_remote_address:
1255 * @socket: a #GSocket.
1256 * @error: #GError for error reporting, or %NULL to ignore.
1258 * Try to get the remove address of a connected socket. This is only
1259 * useful for connection oriented sockets that have been connected.
1261 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1262 * Free the returned object with g_object_unref().
1267 g_socket_get_remote_address (GSocket *socket,
1270 struct sockaddr_storage buffer;
1271 guint32 len = sizeof (buffer);
1273 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1275 if (socket->priv->connect_pending)
1277 if (!g_socket_check_connect_result (socket, error))
1280 socket->priv->connect_pending = FALSE;
1283 if (!socket->priv->remote_address)
1285 if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1287 int errsv = get_socket_errno ();
1288 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1289 _("could not get remote address: %s"), socket_strerror (errsv));
1293 socket->priv->remote_address = g_socket_address_new_from_native (&buffer, len);
1296 return g_object_ref (socket->priv->remote_address);
1300 * g_socket_is_connected:
1301 * @socket: a #GSocket.
1303 * Check whether the socket is connected. This is only useful for
1304 * connection-oriented sockets.
1306 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1311 g_socket_is_connected (GSocket *socket)
1313 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1315 return socket->priv->connected;
1320 * @socket: a #GSocket.
1321 * @error: #GError for error reporting, or %NULL to ignore.
1323 * Marks the socket as a server socket, i.e. a socket that is used
1324 * to accept incoming requests using g_socket_accept().
1326 * Before calling this the socket must be bound to a local address using
1329 * To set the maximum amount of outstanding clients, use
1330 * g_socket_set_listen_backlog().
1332 * Returns: %TRUE on success, %FALSE on error.
1337 g_socket_listen (GSocket *socket,
1340 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1342 if (!check_socket (socket, error))
1345 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1347 int errsv = get_socket_errno ();
1349 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1350 _("could not listen: %s"), socket_strerror (errsv));
1354 socket->priv->listening = TRUE;
1361 * @socket: a #GSocket.
1362 * @address: a #GSocketAddress specifying the local address.
1363 * @allow_reuse: whether to allow reusing this address
1364 * @error: #GError for error reporting, or %NULL to ignore.
1366 * When a socket is created it is attached to an address family, but it
1367 * doesn't have an address in this family. g_socket_bind() assigns the
1368 * address (sometimes called name) of the socket.
1370 * It is generally required to bind to a local address before you can
1371 * receive connections. (See g_socket_listen() and g_socket_accept() ).
1372 * In certain situations, you may also want to bind a socket that will be
1373 * used to initiate connections, though this is not normally required.
1375 * @allow_reuse should be %TRUE for server sockets (sockets that you will
1376 * eventually call g_socket_accept() on), and %FALSE for client sockets.
1377 * (Specifically, if it is %TRUE, then g_socket_bind() will set the
1378 * %SO_REUSEADDR flag on the socket, allowing it to bind @address even if
1379 * that address was previously used by another socket that has not yet been
1380 * fully cleaned-up by the kernel. Failing to set this flag on a server
1381 * socket may cause the bind call to return %G_IO_ERROR_ADDRESS_IN_USE if
1382 * the server program is stopped and then immediately restarted.)
1384 * Returns: %TRUE on success, %FALSE on error.
1389 g_socket_bind (GSocket *socket,
1390 GSocketAddress *address,
1391 gboolean reuse_address,
1394 struct sockaddr_storage addr;
1396 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1398 if (!check_socket (socket, error))
1401 /* SO_REUSEADDR on windows means something else and is not what we want.
1402 It always allows the unix variant of SO_REUSEADDR anyway */
1407 value = (int) !!reuse_address;
1408 /* Ignore errors here, the only likely error is "not supported", and
1409 this is a "best effort" thing mainly */
1410 setsockopt (socket->priv->fd, SOL_SOCKET, SO_REUSEADDR,
1411 (gpointer) &value, sizeof (value));
1415 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1418 if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1419 g_socket_address_get_native_size (address)) < 0)
1421 int errsv = get_socket_errno ();
1423 G_IO_ERROR, socket_io_error_from_errno (errsv),
1424 _("Error binding to address: %s"), socket_strerror (errsv));
1432 * g_socket_speaks_ipv4:
1433 * @socket: a #GSocket
1435 * Checks if a socket is capable of speaking IPv4.
1437 * IPv4 sockets are capable of speaking IPv4. On some operating systems
1438 * and under some combinations of circumstances IPv6 sockets are also
1439 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
1442 * No other types of sockets are currently considered as being capable
1445 * Returns: %TRUE if this socket can be used with IPv4.
1450 g_socket_speaks_ipv4 (GSocket *socket)
1452 switch (socket->priv->family)
1454 case G_SOCKET_FAMILY_IPV4:
1457 case G_SOCKET_FAMILY_IPV6:
1458 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
1460 guint sizeof_int = sizeof (int);
1463 if (getsockopt (socket->priv->fd,
1464 IPPROTO_IPV6, IPV6_V6ONLY,
1465 &v6_only, &sizeof_int) != 0)
1481 * @socket: a #GSocket.
1482 * @cancellable: (allow-none): a %GCancellable or %NULL
1483 * @error: #GError for error reporting, or %NULL to ignore.
1485 * Accept incoming connections on a connection-based socket. This removes
1486 * the first outstanding connection request from the listening socket and
1487 * creates a #GSocket object for it.
1489 * The @socket must be bound to a local address with g_socket_bind() and
1490 * must be listening for incoming connections (g_socket_listen()).
1492 * If there are no outstanding connections then the operation will block
1493 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
1494 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
1496 * Returns: (transfer full): a new #GSocket, or %NULL on error.
1497 * Free the returned object with g_object_unref().
1502 g_socket_accept (GSocket *socket,
1503 GCancellable *cancellable,
1506 GSocket *new_socket;
1509 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1511 if (!check_socket (socket, error))
1516 if (socket->priv->blocking &&
1517 !g_socket_condition_wait (socket,
1518 G_IO_IN, cancellable, error))
1521 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
1523 int errsv = get_socket_errno ();
1525 win32_unset_event_mask (socket, FD_ACCEPT);
1530 if (socket->priv->blocking)
1532 #ifdef WSAEWOULDBLOCK
1533 if (errsv == WSAEWOULDBLOCK)
1536 if (errsv == EWOULDBLOCK ||
1542 g_set_error (error, G_IO_ERROR,
1543 socket_io_error_from_errno (errsv),
1544 _("Error accepting connection: %s"), socket_strerror (errsv));
1550 win32_unset_event_mask (socket, FD_ACCEPT);
1554 /* The socket inherits the accepting sockets event mask and even object,
1555 we need to remove that */
1556 WSAEventSelect (ret, NULL, 0);
1562 /* We always want to set close-on-exec to protect users. If you
1563 need to so some weird inheritance to exec you can re-enable this
1564 using lower level hacks with g_socket_get_fd(). */
1565 flags = fcntl (ret, F_GETFD, 0);
1567 (flags & FD_CLOEXEC) == 0)
1569 flags |= FD_CLOEXEC;
1570 fcntl (ret, F_SETFD, flags);
1575 new_socket = g_socket_new_from_fd (ret, error);
1576 if (new_socket == NULL)
1585 new_socket->priv->protocol = socket->priv->protocol;
1592 * @socket: a #GSocket.
1593 * @address: a #GSocketAddress specifying the remote address.
1594 * @cancellable: (allow-none): a %GCancellable or %NULL
1595 * @error: #GError for error reporting, or %NULL to ignore.
1597 * Connect the socket to the specified remote address.
1599 * For connection oriented socket this generally means we attempt to make
1600 * a connection to the @address. For a connection-less socket it sets
1601 * the default address for g_socket_send() and discards all incoming datagrams
1602 * from other sources.
1604 * Generally connection oriented sockets can only connect once, but
1605 * connection-less sockets can connect multiple times to change the
1608 * If the connect call needs to do network I/O it will block, unless
1609 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
1610 * and the user can be notified of the connection finishing by waiting
1611 * for the G_IO_OUT condition. The result of the connection can then be
1612 * checked with g_socket_check_connect_result().
1614 * Returns: %TRUE if connected, %FALSE on error.
1619 g_socket_connect (GSocket *socket,
1620 GSocketAddress *address,
1621 GCancellable *cancellable,
1624 struct sockaddr_storage buffer;
1626 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1628 if (!check_socket (socket, error))
1631 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
1634 if (socket->priv->remote_address)
1635 g_object_unref (socket->priv->remote_address);
1636 socket->priv->remote_address = g_object_ref (address);
1640 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
1641 g_socket_address_get_native_size (address)) < 0)
1643 int errsv = get_socket_errno ();
1649 if (errsv == EINPROGRESS)
1651 if (errsv == WSAEWOULDBLOCK)
1654 if (socket->priv->blocking)
1656 if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
1658 if (g_socket_check_connect_result (socket, error))
1661 g_prefix_error (error, _("Error connecting: "));
1665 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
1666 _("Connection in progress"));
1667 socket->priv->connect_pending = TRUE;
1671 g_set_error (error, G_IO_ERROR,
1672 socket_io_error_from_errno (errsv),
1673 _("Error connecting: %s"), socket_strerror (errsv));
1680 win32_unset_event_mask (socket, FD_CONNECT);
1682 socket->priv->connected = TRUE;
1688 * g_socket_check_connect_result:
1689 * @socket: a #GSocket
1690 * @error: #GError for error reporting, or %NULL to ignore.
1692 * Checks and resets the pending connect error for the socket.
1693 * This is used to check for errors when g_socket_connect() is
1694 * used in non-blocking mode.
1696 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
1701 g_socket_check_connect_result (GSocket *socket,
1707 if (!check_socket (socket, error))
1710 optlen = sizeof (value);
1711 if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
1713 int errsv = get_socket_errno ();
1715 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1716 _("Unable to get pending error: %s"), socket_strerror (errsv));
1722 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
1723 socket_strerror (value));
1724 if (socket->priv->remote_address)
1726 g_object_unref (socket->priv->remote_address);
1727 socket->priv->remote_address = NULL;
1736 * @socket: a #GSocket
1737 * @buffer: a buffer to read data into (which should be at least @size
1739 * @size: the number of bytes you want to read from the socket
1740 * @cancellable: (allow-none): a %GCancellable or %NULL
1741 * @error: #GError for error reporting, or %NULL to ignore.
1743 * Receive data (up to @size bytes) from a socket. This is mainly used by
1744 * connection-oriented sockets; it is identical to g_socket_receive_from()
1745 * with @address set to %NULL.
1747 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
1748 * g_socket_receive() will always read either 0 or 1 complete messages from
1749 * the socket. If the received message is too large to fit in @buffer, then
1750 * the data beyond @size bytes will be discarded, without any explicit
1751 * indication that this has occurred.
1753 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
1754 * number of bytes, up to @size. If more than @size bytes have been
1755 * received, the additional data will be returned in future calls to
1756 * g_socket_receive().
1758 * If the socket is in blocking mode the call will block until there
1759 * is some data to receive, the connection is closed, or there is an
1760 * error. If there is no data available and the socket is in
1761 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
1762 * returned. To be notified when data is available, wait for the
1763 * %G_IO_IN condition.
1765 * On error -1 is returned and @error is set accordingly.
1767 * Returns: Number of bytes read, or 0 if the connection was closed by
1768 * the peer, or -1 on error
1773 g_socket_receive (GSocket *socket,
1776 GCancellable *cancellable,
1779 return g_socket_receive_with_blocking (socket, buffer, size,
1780 socket->priv->blocking,
1781 cancellable, error);
1785 * g_socket_receive_with_blocking:
1786 * @socket: a #GSocket
1787 * @buffer: a buffer to read data into (which should be at least @size
1789 * @size: the number of bytes you want to read from the socket
1790 * @blocking: whether to do blocking or non-blocking I/O
1791 * @cancellable: (allow-none): a %GCancellable or %NULL
1792 * @error: #GError for error reporting, or %NULL to ignore.
1794 * This behaves exactly the same as g_socket_receive(), except that
1795 * the choice of blocking or non-blocking behavior is determined by
1796 * the @blocking argument rather than by @socket's properties.
1798 * Returns: Number of bytes read, or 0 if the connection was closed by
1799 * the peer, or -1 on error
1804 g_socket_receive_with_blocking (GSocket *socket,
1808 GCancellable *cancellable,
1813 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1815 if (!check_socket (socket, error))
1818 if (g_cancellable_set_error_if_cancelled (cancellable, error))
1824 !g_socket_condition_wait (socket,
1825 G_IO_IN, cancellable, error))
1828 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
1830 int errsv = get_socket_errno ();
1837 #ifdef WSAEWOULDBLOCK
1838 if (errsv == WSAEWOULDBLOCK)
1841 if (errsv == EWOULDBLOCK ||
1847 win32_unset_event_mask (socket, FD_READ);
1849 g_set_error (error, G_IO_ERROR,
1850 socket_io_error_from_errno (errsv),
1851 _("Error receiving data: %s"), socket_strerror (errsv));
1855 win32_unset_event_mask (socket, FD_READ);
1864 * g_socket_receive_from:
1865 * @socket: a #GSocket
1866 * @address: a pointer to a #GSocketAddress pointer, or %NULL
1867 * @buffer: a buffer to read data into (which should be at least @size
1869 * @size: the number of bytes you want to read from the socket
1870 * @cancellable: (allow-none): a %GCancellable or %NULL
1871 * @error: #GError for error reporting, or %NULL to ignore.
1873 * Receive data (up to @size bytes) from a socket.
1875 * If @address is non-%NULL then @address will be set equal to the
1876 * source address of the received packet.
1877 * @address is owned by the caller.
1879 * See g_socket_receive() for additional information.
1881 * Returns: Number of bytes read, or 0 if the connection was closed by
1882 * the peer, or -1 on error
1887 g_socket_receive_from (GSocket *socket,
1888 GSocketAddress **address,
1891 GCancellable *cancellable,
1899 return g_socket_receive_message (socket,
1907 /* Although we ignore SIGPIPE, gdb will still stop if the app receives
1908 * one, which can be confusing and annoying. So if possible, we want
1909 * to suppress the signal entirely.
1912 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
1914 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
1919 * @socket: a #GSocket
1920 * @buffer: (array length=size): the buffer containing the data to send.
1921 * @size: the number of bytes to send
1922 * @cancellable: (allow-none): a %GCancellable or %NULL
1923 * @error: #GError for error reporting, or %NULL to ignore.
1925 * Tries to send @size bytes from @buffer on the socket. This is
1926 * mainly used by connection-oriented sockets; it is identical to
1927 * g_socket_send_to() with @address set to %NULL.
1929 * If the socket is in blocking mode the call will block until there is
1930 * space for the data in the socket queue. If there is no space available
1931 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1932 * will be returned. To be notified when space is available, wait for the
1933 * %G_IO_OUT condition. Note though that you may still receive
1934 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
1935 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
1936 * very common due to the way the underlying APIs work.)
1938 * On error -1 is returned and @error is set accordingly.
1940 * Returns: Number of bytes written (which may be less than @size), or -1
1946 g_socket_send (GSocket *socket,
1947 const gchar *buffer,
1949 GCancellable *cancellable,
1952 return g_socket_send_with_blocking (socket, buffer, size,
1953 socket->priv->blocking,
1954 cancellable, error);
1958 * g_socket_send_with_blocking:
1959 * @socket: a #GSocket
1960 * @buffer: (array length=size): the buffer containing the data to send.
1961 * @size: the number of bytes to send
1962 * @blocking: whether to do blocking or non-blocking I/O
1963 * @cancellable: (allow-none): a %GCancellable or %NULL
1964 * @error: #GError for error reporting, or %NULL to ignore.
1966 * This behaves exactly the same as g_socket_send(), except that
1967 * the choice of blocking or non-blocking behavior is determined by
1968 * the @blocking argument rather than by @socket's properties.
1970 * Returns: Number of bytes written (which may be less than @size), or -1
1976 g_socket_send_with_blocking (GSocket *socket,
1977 const gchar *buffer,
1980 GCancellable *cancellable,
1985 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1987 if (!check_socket (socket, error))
1990 if (g_cancellable_set_error_if_cancelled (cancellable, error))
1996 !g_socket_condition_wait (socket,
1997 G_IO_OUT, cancellable, error))
2000 if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
2002 int errsv = get_socket_errno ();
2007 #ifdef WSAEWOULDBLOCK
2008 if (errsv == WSAEWOULDBLOCK)
2009 win32_unset_event_mask (socket, FD_WRITE);
2014 #ifdef WSAEWOULDBLOCK
2015 if (errsv == WSAEWOULDBLOCK)
2018 if (errsv == EWOULDBLOCK ||
2024 g_set_error (error, G_IO_ERROR,
2025 socket_io_error_from_errno (errsv),
2026 _("Error sending data: %s"), socket_strerror (errsv));
2037 * @socket: a #GSocket
2038 * @address: a #GSocketAddress, or %NULL
2039 * @buffer: (array length=size): the buffer containing the data to send.
2040 * @size: the number of bytes to send
2041 * @cancellable: (allow-none): a %GCancellable or %NULL
2042 * @error: #GError for error reporting, or %NULL to ignore.
2044 * Tries to send @size bytes from @buffer to @address. If @address is
2045 * %NULL then the message is sent to the default receiver (set by
2046 * g_socket_connect()).
2048 * See g_socket_send() for additional information.
2050 * Returns: Number of bytes written (which may be less than @size), or -1
2056 g_socket_send_to (GSocket *socket,
2057 GSocketAddress *address,
2058 const gchar *buffer,
2060 GCancellable *cancellable,
2068 return g_socket_send_message (socket,
2078 * g_socket_shutdown:
2079 * @socket: a #GSocket
2080 * @shutdown_read: whether to shut down the read side
2081 * @shutdown_write: whether to shut down the write side
2082 * @error: #GError for error reporting, or %NULL to ignore.
2084 * Shut down part of a full-duplex connection.
2086 * If @shutdown_read is %TRUE then the recieving side of the connection
2087 * is shut down, and further reading is disallowed.
2089 * If @shutdown_write is %TRUE then the sending side of the connection
2090 * is shut down, and further writing is disallowed.
2092 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
2094 * One example where this is used is graceful disconnect for TCP connections
2095 * where you close the sending side, then wait for the other side to close
2096 * the connection, thus ensuring that the other side saw all sent data.
2098 * Returns: %TRUE on success, %FALSE on error
2103 g_socket_shutdown (GSocket *socket,
2104 gboolean shutdown_read,
2105 gboolean shutdown_write,
2110 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2112 if (!check_socket (socket, NULL))
2116 if (!shutdown_read && !shutdown_write)
2120 if (shutdown_read && shutdown_write)
2122 else if (shutdown_read)
2127 if (shutdown_read && shutdown_write)
2129 else if (shutdown_read)
2135 if (shutdown (socket->priv->fd, how) != 0)
2137 int errsv = get_socket_errno ();
2138 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2139 _("Unable to create socket: %s"), socket_strerror (errsv));
2143 if (shutdown_read && shutdown_write)
2144 socket->priv->connected = FALSE;
2151 * @socket: a #GSocket
2152 * @error: #GError for error reporting, or %NULL to ignore.
2154 * Closes the socket, shutting down any active connection.
2156 * Closing a socket does not wait for all outstanding I/O operations
2157 * to finish, so the caller should not rely on them to be guaranteed
2158 * to complete even if the close returns with no error.
2160 * Once the socket is closed, all other operations will return
2161 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
2164 * Sockets will be automatically closed when the last reference
2165 * is dropped, but you might want to call this function to make sure
2166 * resources are released as early as possible.
2168 * Beware that due to the way that TCP works, it is possible for
2169 * recently-sent data to be lost if either you close a socket while the
2170 * %G_IO_IN condition is set, or else if the remote connection tries to
2171 * send something to you after you close the socket but before it has
2172 * finished reading all of the data you sent. There is no easy generic
2173 * way to avoid this problem; the easiest fix is to design the network
2174 * protocol such that the client will never send data "out of turn".
2175 * Another solution is for the server to half-close the connection by
2176 * calling g_socket_shutdown() with only the @shutdown_write flag set,
2177 * and then wait for the client to notice this and close its side of the
2178 * connection, after which the server can safely call g_socket_close().
2179 * (This is what #GTcpConnection does if you call
2180 * g_tcp_connection_set_graceful_disconnect(). But of course, this
2181 * only works if the client will close its connection after the server
2184 * Returns: %TRUE on success, %FALSE on error
2189 g_socket_close (GSocket *socket,
2194 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2196 if (socket->priv->closed)
2197 return TRUE; /* Multiple close not an error */
2199 if (!check_socket (socket, NULL))
2205 res = closesocket (socket->priv->fd);
2207 res = close (socket->priv->fd);
2211 int errsv = get_socket_errno ();
2216 g_set_error (error, G_IO_ERROR,
2217 socket_io_error_from_errno (errsv),
2218 _("Error closing socket: %s"),
2219 socket_strerror (errsv));
2225 socket->priv->connected = FALSE;
2226 socket->priv->closed = TRUE;
2227 if (socket->priv->remote_address)
2229 g_object_unref (socket->priv->remote_address);
2230 socket->priv->remote_address = NULL;
2237 * g_socket_is_closed:
2238 * @socket: a #GSocket
2240 * Checks whether a socket is closed.
2242 * Returns: %TRUE if socket is closed, %FALSE otherwise
2247 g_socket_is_closed (GSocket *socket)
2249 return socket->priv->closed;
2253 /* Broken source, used on errors */
2255 broken_prepare (GSource *source,
2262 broken_check (GSource *source)
2268 broken_dispatch (GSource *source,
2269 GSourceFunc callback,
2275 static GSourceFuncs broken_funcs =
2284 network_events_for_condition (GIOCondition condition)
2288 if (condition & G_IO_IN)
2289 event_mask |= (FD_READ | FD_ACCEPT);
2290 if (condition & G_IO_OUT)
2291 event_mask |= (FD_WRITE | FD_CONNECT);
2292 event_mask |= FD_CLOSE;
2298 ensure_event (GSocket *socket)
2300 if (socket->priv->event == WSA_INVALID_EVENT)
2301 socket->priv->event = WSACreateEvent();
2305 update_select_events (GSocket *socket)
2312 ensure_event (socket);
2315 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
2318 event_mask |= network_events_for_condition (*ptr);
2321 if (event_mask != socket->priv->selected_events)
2323 /* If no events selected, disable event so we can unset
2326 if (event_mask == 0)
2329 event = socket->priv->event;
2331 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
2332 socket->priv->selected_events = event_mask;
2337 add_condition_watch (GSocket *socket,
2338 GIOCondition *condition)
2340 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
2342 socket->priv->requested_conditions =
2343 g_list_prepend (socket->priv->requested_conditions, condition);
2345 update_select_events (socket);
2349 remove_condition_watch (GSocket *socket,
2350 GIOCondition *condition)
2352 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
2354 socket->priv->requested_conditions =
2355 g_list_remove (socket->priv->requested_conditions, condition);
2357 update_select_events (socket);
2361 update_condition (GSocket *socket)
2363 WSANETWORKEVENTS events;
2364 GIOCondition condition;
2366 if (WSAEnumNetworkEvents (socket->priv->fd,
2367 socket->priv->event,
2370 socket->priv->current_events |= events.lNetworkEvents;
2371 if (events.lNetworkEvents & FD_WRITE &&
2372 events.iErrorCode[FD_WRITE_BIT] != 0)
2373 socket->priv->current_errors |= FD_WRITE;
2374 if (events.lNetworkEvents & FD_CONNECT &&
2375 events.iErrorCode[FD_CONNECT_BIT] != 0)
2376 socket->priv->current_errors |= FD_CONNECT;
2380 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
2381 condition |= G_IO_IN;
2383 if (socket->priv->current_events & FD_CLOSE ||
2384 socket->priv->closed)
2385 condition |= G_IO_HUP;
2387 /* Never report both G_IO_OUT and HUP, these are
2388 mutually exclusive (can't write to a closed socket) */
2389 if ((condition & G_IO_HUP) == 0 &&
2390 socket->priv->current_events & FD_WRITE)
2392 if (socket->priv->current_errors & FD_WRITE)
2393 condition |= G_IO_ERR;
2395 condition |= G_IO_OUT;
2399 if (socket->priv->current_events & FD_CONNECT)
2401 if (socket->priv->current_errors & FD_CONNECT)
2402 condition |= (G_IO_HUP | G_IO_ERR);
2404 condition |= G_IO_OUT;
2416 GIOCondition condition;
2417 GCancellable *cancellable;
2418 GPollFD cancel_pollfd;
2419 gint64 timeout_time;
2423 socket_source_prepare (GSource *source,
2426 GSocketSource *socket_source = (GSocketSource *)source;
2428 if (g_cancellable_is_cancelled (socket_source->cancellable))
2431 if (socket_source->timeout_time)
2435 now = g_source_get_time (source);
2436 /* Round up to ensure that we don't try again too early */
2437 *timeout = (socket_source->timeout_time - now + 999) / 1000;
2440 socket_source->socket->priv->timed_out = TRUE;
2441 socket_source->pollfd.revents = socket_source->condition & (G_IO_IN | G_IO_OUT);
2450 socket_source->pollfd.revents = update_condition (socket_source->socket);
2453 if ((socket_source->condition & socket_source->pollfd.revents) != 0)
2460 socket_source_check (GSource *source)
2464 return socket_source_prepare (source, &timeout);
2468 socket_source_dispatch (GSource *source,
2469 GSourceFunc callback,
2472 GSocketSourceFunc func = (GSocketSourceFunc)callback;
2473 GSocketSource *socket_source = (GSocketSource *)source;
2476 socket_source->pollfd.revents = update_condition (socket_source->socket);
2479 return (*func) (socket_source->socket,
2480 socket_source->pollfd.revents & socket_source->condition,
2485 socket_source_finalize (GSource *source)
2487 GSocketSource *socket_source = (GSocketSource *)source;
2490 socket = socket_source->socket;
2493 remove_condition_watch (socket, &socket_source->condition);
2496 g_object_unref (socket);
2498 if (socket_source->cancellable)
2500 g_cancellable_release_fd (socket_source->cancellable);
2501 g_object_unref (socket_source->cancellable);
2506 socket_source_closure_callback (GSocket *socket,
2507 GIOCondition condition,
2510 GClosure *closure = data;
2512 GValue params[2] = { { 0, }, { 0, } };
2513 GValue result_value = { 0, };
2516 g_value_init (&result_value, G_TYPE_BOOLEAN);
2518 g_value_init (¶ms[0], G_TYPE_SOCKET);
2519 g_value_set_object (¶ms[0], socket);
2520 g_value_init (¶ms[1], G_TYPE_IO_CONDITION);
2521 g_value_set_flags (¶ms[1], condition);
2523 g_closure_invoke (closure, &result_value, 2, params, NULL);
2525 result = g_value_get_boolean (&result_value);
2526 g_value_unset (&result_value);
2527 g_value_unset (¶ms[0]);
2528 g_value_unset (¶ms[1]);
2533 static GSourceFuncs socket_source_funcs =
2535 socket_source_prepare,
2536 socket_source_check,
2537 socket_source_dispatch,
2538 socket_source_finalize,
2539 (GSourceFunc)socket_source_closure_callback,
2540 (GSourceDummyMarshal)_gio_marshal_BOOLEAN__FLAGS,
2544 socket_source_new (GSocket *socket,
2545 GIOCondition condition,
2546 GCancellable *cancellable)
2549 GSocketSource *socket_source;
2552 ensure_event (socket);
2554 if (socket->priv->event == WSA_INVALID_EVENT)
2556 g_warning ("Failed to create WSAEvent");
2557 return g_source_new (&broken_funcs, sizeof (GSource));
2561 condition |= G_IO_HUP | G_IO_ERR;
2563 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
2564 g_source_set_name (source, "GSocket");
2565 socket_source = (GSocketSource *)source;
2567 socket_source->socket = g_object_ref (socket);
2568 socket_source->condition = condition;
2570 if (g_cancellable_make_pollfd (cancellable,
2571 &socket_source->cancel_pollfd))
2573 socket_source->cancellable = g_object_ref (cancellable);
2574 g_source_add_poll (source, &socket_source->cancel_pollfd);
2578 add_condition_watch (socket, &socket_source->condition);
2579 socket_source->pollfd.fd = (gintptr) socket->priv->event;
2581 socket_source->pollfd.fd = socket->priv->fd;
2584 socket_source->pollfd.events = condition;
2585 socket_source->pollfd.revents = 0;
2586 g_source_add_poll (source, &socket_source->pollfd);
2588 if (socket->priv->timeout)
2589 socket_source->timeout_time = g_get_monotonic_time () +
2590 socket->priv->timeout * 1000000;
2593 socket_source->timeout_time = 0;
2599 * g_socket_create_source: (skip)
2600 * @socket: a #GSocket
2601 * @condition: a #GIOCondition mask to monitor
2602 * @cancellable: (allow-none): a %GCancellable or %NULL
2604 * Creates a %GSource that can be attached to a %GMainContext to monitor
2605 * for the availibility of the specified @condition on the socket.
2607 * The callback on the source is of the #GSocketSourceFunc type.
2609 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
2610 * these conditions will always be reported output if they are true.
2612 * @cancellable if not %NULL can be used to cancel the source, which will
2613 * cause the source to trigger, reporting the current condition (which
2614 * is likely 0 unless cancellation happened at the same time as a
2615 * condition change). You can check for this in the callback using
2616 * g_cancellable_is_cancelled().
2618 * If @socket has a timeout set, and it is reached before @condition
2619 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
2620 * %G_IO_OUT depending on @condition. However, @socket will have been
2621 * marked as having had a timeout, and so the next #GSocket I/O method
2622 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
2624 * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
2629 g_socket_create_source (GSocket *socket,
2630 GIOCondition condition,
2631 GCancellable *cancellable)
2633 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
2635 return socket_source_new (socket, condition, cancellable);
2639 * g_socket_condition_check:
2640 * @socket: a #GSocket
2641 * @condition: a #GIOCondition mask to check
2643 * Checks on the readiness of @socket to perform operations.
2644 * The operations specified in @condition are checked for and masked
2645 * against the currently-satisfied conditions on @socket. The result
2648 * Note that on Windows, it is possible for an operation to return
2649 * %G_IO_ERROR_WOULD_BLOCK even immediately after
2650 * g_socket_condition_check() has claimed that the socket is ready for
2651 * writing. Rather than calling g_socket_condition_check() and then
2652 * writing to the socket if it succeeds, it is generally better to
2653 * simply try writing to the socket right away, and try again later if
2654 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
2656 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2657 * these conditions will always be set in the output if they are true.
2659 * This call never blocks.
2661 * Returns: the @GIOCondition mask of the current state
2666 g_socket_condition_check (GSocket *socket,
2667 GIOCondition condition)
2669 if (!check_socket (socket, NULL))
2674 GIOCondition current_condition;
2676 condition |= G_IO_ERR | G_IO_HUP;
2678 add_condition_watch (socket, &condition);
2679 current_condition = update_condition (socket);
2680 remove_condition_watch (socket, &condition);
2681 return condition & current_condition;
2687 poll_fd.fd = socket->priv->fd;
2688 poll_fd.events = condition;
2691 result = g_poll (&poll_fd, 1, 0);
2692 while (result == -1 && get_socket_errno () == EINTR);
2694 return poll_fd.revents;
2700 * g_socket_condition_wait:
2701 * @socket: a #GSocket
2702 * @condition: a #GIOCondition mask to wait for
2703 * @cancellable: (allow-none): a #GCancellable, or %NULL
2704 * @error: a #GError pointer, or %NULL
2706 * Waits for @condition to become true on @socket. When the condition
2707 * is met, %TRUE is returned.
2709 * If @cancellable is cancelled before the condition is met, or if the
2710 * socket has a timeout set and it is reached before the condition is
2711 * met, then %FALSE is returned and @error, if non-%NULL, is set to
2712 * the appropriate value (%G_IO_ERROR_CANCELLED or
2713 * %G_IO_ERROR_TIMED_OUT).
2715 * Returns: %TRUE if the condition was met, %FALSE otherwise
2720 g_socket_condition_wait (GSocket *socket,
2721 GIOCondition condition,
2722 GCancellable *cancellable,
2725 if (!check_socket (socket, error))
2728 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2733 GIOCondition current_condition;
2739 /* Always check these */
2740 condition |= G_IO_ERR | G_IO_HUP;
2742 add_condition_watch (socket, &condition);
2745 events[num_events++] = socket->priv->event;
2747 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
2748 events[num_events++] = (WSAEVENT)cancel_fd.fd;
2750 if (socket->priv->timeout)
2751 timeout = socket->priv->timeout * 1000;
2753 timeout = WSA_INFINITE;
2755 current_condition = update_condition (socket);
2756 while ((condition & current_condition) == 0)
2758 res = WSAWaitForMultipleEvents(num_events, events,
2759 FALSE, timeout, FALSE);
2760 if (res == WSA_WAIT_FAILED)
2762 int errsv = get_socket_errno ();
2764 g_set_error (error, G_IO_ERROR,
2765 socket_io_error_from_errno (errsv),
2766 _("Waiting for socket condition: %s"),
2767 socket_strerror (errsv));
2770 else if (res == WSA_WAIT_TIMEOUT)
2772 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
2773 _("Socket I/O timed out"));
2777 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2780 current_condition = update_condition (socket);
2782 remove_condition_watch (socket, &condition);
2784 g_cancellable_release_fd (cancellable);
2786 return (condition & current_condition) != 0;
2795 poll_fd[0].fd = socket->priv->fd;
2796 poll_fd[0].events = condition;
2799 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
2802 if (socket->priv->timeout)
2803 timeout = socket->priv->timeout * 1000;
2808 result = g_poll (poll_fd, num, timeout);
2809 while (result == -1 && get_socket_errno () == EINTR);
2812 g_cancellable_release_fd (cancellable);
2816 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
2817 _("Socket I/O timed out"));
2821 return !g_cancellable_set_error_if_cancelled (cancellable, error);
2827 * g_socket_send_message:
2828 * @socket: a #GSocket
2829 * @address: a #GSocketAddress, or %NULL
2830 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
2831 * @num_vectors: the number of elements in @vectors, or -1
2832 * @messages: (array length=num_messages) (allow-none): a pointer to an
2833 * array of #GSocketControlMessages, or %NULL.
2834 * @num_messages: number of elements in @messages, or -1.
2835 * @flags: an int containing #GSocketMsgFlags flags
2836 * @cancellable: (allow-none): a %GCancellable or %NULL
2837 * @error: #GError for error reporting, or %NULL to ignore.
2839 * Send data to @address on @socket. This is the most complicated and
2840 * fully-featured version of this call. For easier use, see
2841 * g_socket_send() and g_socket_send_to().
2843 * If @address is %NULL then the message is sent to the default receiver
2844 * (set by g_socket_connect()).
2846 * @vectors must point to an array of #GOutputVector structs and
2847 * @num_vectors must be the length of this array. (If @num_vectors is -1,
2848 * then @vectors is assumed to be terminated by a #GOutputVector with a
2849 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
2850 * that the sent data will be gathered from. Using multiple
2851 * #GOutputVector<!-- -->s is more memory-efficient than manually copying
2852 * data from multiple sources into a single buffer, and more
2853 * network-efficient than making multiple calls to g_socket_send().
2855 * @messages, if non-%NULL, is taken to point to an array of @num_messages
2856 * #GSocketControlMessage instances. These correspond to the control
2857 * messages to be sent on the socket.
2858 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
2861 * @flags modify how the message is sent. The commonly available arguments
2862 * for this are available in the #GSocketMsgFlags enum, but the
2863 * values there are the same as the system values, and the flags
2864 * are passed in as-is, so you can pass in system-specific flags too.
2866 * If the socket is in blocking mode the call will block until there is
2867 * space for the data in the socket queue. If there is no space available
2868 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2869 * will be returned. To be notified when space is available, wait for the
2870 * %G_IO_OUT condition. Note though that you may still receive
2871 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2872 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2873 * very common due to the way the underlying APIs work.)
2875 * On error -1 is returned and @error is set accordingly.
2877 * Returns: Number of bytes written (which may be less than @size), or -1
2883 g_socket_send_message (GSocket *socket,
2884 GSocketAddress *address,
2885 GOutputVector *vectors,
2887 GSocketControlMessage **messages,
2890 GCancellable *cancellable,
2893 GOutputVector one_vector;
2896 if (!check_socket (socket, error))
2899 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2902 if (num_vectors == -1)
2904 for (num_vectors = 0;
2905 vectors[num_vectors].buffer != NULL;
2910 if (num_messages == -1)
2912 for (num_messages = 0;
2913 messages != NULL && messages[num_messages] != NULL;
2918 if (num_vectors == 0)
2922 one_vector.buffer = &zero;
2923 one_vector.size = 1;
2925 vectors = &one_vector;
2938 msg.msg_namelen = g_socket_address_get_native_size (address);
2939 msg.msg_name = g_alloca (msg.msg_namelen);
2940 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
2945 msg.msg_name = NULL;
2946 msg.msg_namelen = 0;
2951 /* this entire expression will be evaluated at compile time */
2952 if (sizeof *msg.msg_iov == sizeof *vectors &&
2953 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2954 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2955 G_STRUCT_OFFSET (GOutputVector, buffer) &&
2956 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2957 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2958 G_STRUCT_OFFSET (GOutputVector, size))
2959 /* ABI is compatible */
2961 msg.msg_iov = (struct iovec *) vectors;
2962 msg.msg_iovlen = num_vectors;
2965 /* ABI is incompatible */
2969 msg.msg_iov = g_newa (struct iovec, num_vectors);
2970 for (i = 0; i < num_vectors; i++)
2972 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
2973 msg.msg_iov[i].iov_len = vectors[i].size;
2975 msg.msg_iovlen = num_vectors;
2981 struct cmsghdr *cmsg;
2984 msg.msg_controllen = 0;
2985 for (i = 0; i < num_messages; i++)
2986 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
2988 if (msg.msg_controllen == 0)
2989 msg.msg_control = NULL;
2992 msg.msg_control = g_alloca (msg.msg_controllen);
2993 memset (msg.msg_control, '\0', msg.msg_controllen);
2996 cmsg = CMSG_FIRSTHDR (&msg);
2997 for (i = 0; i < num_messages; i++)
2999 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
3000 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
3001 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
3002 g_socket_control_message_serialize (messages[i],
3004 cmsg = CMSG_NXTHDR (&msg, cmsg);
3006 g_assert (cmsg == NULL);
3011 if (socket->priv->blocking &&
3012 !g_socket_condition_wait (socket,
3013 G_IO_OUT, cancellable, error))
3016 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
3019 int errsv = get_socket_errno ();
3024 if (socket->priv->blocking &&
3025 (errsv == EWOULDBLOCK ||
3029 g_set_error (error, G_IO_ERROR,
3030 socket_io_error_from_errno (errsv),
3031 _("Error sending message: %s"), socket_strerror (errsv));
3042 struct sockaddr_storage addr;
3049 /* Win32 doesn't support control messages.
3050 Actually this is possible for raw and datagram sockets
3051 via WSASendMessage on Vista or later, but that doesn't
3053 if (num_messages != 0)
3055 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
3056 _("GSocketControlMessage not supported on windows"));
3061 bufs = g_newa (WSABUF, num_vectors);
3062 for (i = 0; i < num_vectors; i++)
3064 bufs[i].buf = (char *)vectors[i].buffer;
3065 bufs[i].len = (gulong)vectors[i].size;
3069 addrlen = 0; /* Avoid warning */
3072 addrlen = g_socket_address_get_native_size (address);
3073 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
3079 if (socket->priv->blocking &&
3080 !g_socket_condition_wait (socket,
3081 G_IO_OUT, cancellable, error))
3085 result = WSASendTo (socket->priv->fd,
3088 (const struct sockaddr *)&addr, addrlen,
3091 result = WSASend (socket->priv->fd,
3098 int errsv = get_socket_errno ();
3100 if (errsv == WSAEINTR)
3103 if (errsv == WSAEWOULDBLOCK)
3104 win32_unset_event_mask (socket, FD_WRITE);
3106 if (socket->priv->blocking &&
3107 errsv == WSAEWOULDBLOCK)
3110 g_set_error (error, G_IO_ERROR,
3111 socket_io_error_from_errno (errsv),
3112 _("Error sending message: %s"), socket_strerror (errsv));
3125 * g_socket_receive_message:
3126 * @socket: a #GSocket
3127 * @address: a pointer to a #GSocketAddress pointer, or %NULL
3128 * @vectors: (array length=num_vectors): an array of #GInputVector structs
3129 * @num_vectors: the number of elements in @vectors, or -1
3130 * @messages: (array length=num_messages) (allow-none): a pointer which
3131 * may be filled with an array of #GSocketControlMessages, or %NULL
3132 * @num_messages: a pointer which will be filled with the number of
3133 * elements in @messages, or %NULL
3134 * @flags: a pointer to an int containing #GSocketMsgFlags flags
3135 * @cancellable: (allow-none): a %GCancellable or %NULL
3136 * @error: a #GError pointer, or %NULL
3138 * Receive data from a socket. This is the most complicated and
3139 * fully-featured version of this call. For easier use, see
3140 * g_socket_receive() and g_socket_receive_from().
3142 * If @address is non-%NULL then @address will be set equal to the
3143 * source address of the received packet.
3144 * @address is owned by the caller.
3146 * @vector must point to an array of #GInputVector structs and
3147 * @num_vectors must be the length of this array. These structs
3148 * describe the buffers that received data will be scattered into.
3149 * If @num_vectors is -1, then @vectors is assumed to be terminated
3150 * by a #GInputVector with a %NULL buffer pointer.
3152 * As a special case, if @num_vectors is 0 (in which case, @vectors
3153 * may of course be %NULL), then a single byte is received and
3154 * discarded. This is to facilitate the common practice of sending a
3155 * single '\0' byte for the purposes of transferring ancillary data.
3157 * @messages, if non-%NULL, will be set to point to a newly-allocated
3158 * array of #GSocketControlMessage instances or %NULL if no such
3159 * messages was received. These correspond to the control messages
3160 * received from the kernel, one #GSocketControlMessage per message
3161 * from the kernel. This array is %NULL-terminated and must be freed
3162 * by the caller using g_free() after calling g_object_unref() on each
3163 * element. If @messages is %NULL, any control messages received will
3166 * @num_messages, if non-%NULL, will be set to the number of control
3167 * messages received.
3169 * If both @messages and @num_messages are non-%NULL, then
3170 * @num_messages gives the number of #GSocketControlMessage instances
3171 * in @messages (ie: not including the %NULL terminator).
3173 * @flags is an in/out parameter. The commonly available arguments
3174 * for this are available in the #GSocketMsgFlags enum, but the
3175 * values there are the same as the system values, and the flags
3176 * are passed in as-is, so you can pass in system-specific flags too
3177 * (and g_socket_receive_message() may pass system-specific flags out).
3179 * As with g_socket_receive(), data may be discarded if @socket is
3180 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
3181 * provide enough buffer space to read a complete message. You can pass
3182 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
3183 * removing it from the receive queue, but there is no portable way to find
3184 * out the length of the message other than by reading it into a
3185 * sufficiently-large buffer.
3187 * If the socket is in blocking mode the call will block until there
3188 * is some data to receive, the connection is closed, or there is an
3189 * error. If there is no data available and the socket is in
3190 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
3191 * returned. To be notified when data is available, wait for the
3192 * %G_IO_IN condition.
3194 * On error -1 is returned and @error is set accordingly.
3196 * Returns: Number of bytes read, or 0 if the connection was closed by
3197 * the peer, or -1 on error
3202 g_socket_receive_message (GSocket *socket,
3203 GSocketAddress **address,
3204 GInputVector *vectors,
3206 GSocketControlMessage ***messages,
3209 GCancellable *cancellable,
3212 GInputVector one_vector;
3215 if (!check_socket (socket, error))
3218 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3221 if (num_vectors == -1)
3223 for (num_vectors = 0;
3224 vectors[num_vectors].buffer != NULL;
3229 if (num_vectors == 0)
3231 one_vector.buffer = &one_byte;
3232 one_vector.size = 1;
3234 vectors = &one_vector;
3241 struct sockaddr_storage one_sockaddr;
3246 msg.msg_name = &one_sockaddr;
3247 msg.msg_namelen = sizeof (struct sockaddr_storage);
3251 msg.msg_name = NULL;
3252 msg.msg_namelen = 0;
3256 /* this entire expression will be evaluated at compile time */
3257 if (sizeof *msg.msg_iov == sizeof *vectors &&
3258 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3259 G_STRUCT_OFFSET (struct iovec, iov_base) ==
3260 G_STRUCT_OFFSET (GInputVector, buffer) &&
3261 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3262 G_STRUCT_OFFSET (struct iovec, iov_len) ==
3263 G_STRUCT_OFFSET (GInputVector, size))
3264 /* ABI is compatible */
3266 msg.msg_iov = (struct iovec *) vectors;
3267 msg.msg_iovlen = num_vectors;
3270 /* ABI is incompatible */
3274 msg.msg_iov = g_newa (struct iovec, num_vectors);
3275 for (i = 0; i < num_vectors; i++)
3277 msg.msg_iov[i].iov_base = vectors[i].buffer;
3278 msg.msg_iov[i].iov_len = vectors[i].size;
3280 msg.msg_iovlen = num_vectors;
3284 msg.msg_control = g_alloca (2048);
3285 msg.msg_controllen = 2048;
3289 msg.msg_flags = *flags;
3293 /* We always set the close-on-exec flag so we don't leak file
3294 * descriptors into child processes. Note that gunixfdmessage.c
3295 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
3297 #ifdef MSG_CMSG_CLOEXEC
3298 msg.msg_flags |= MSG_CMSG_CLOEXEC;
3304 if (socket->priv->blocking &&
3305 !g_socket_condition_wait (socket,
3306 G_IO_IN, cancellable, error))
3309 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
3310 #ifdef MSG_CMSG_CLOEXEC
3311 if (result < 0 && get_socket_errno () == EINVAL)
3313 /* We must be running on an old kernel. Call without the flag. */
3314 msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
3315 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
3321 int errsv = get_socket_errno ();
3326 if (socket->priv->blocking &&
3327 (errsv == EWOULDBLOCK ||
3331 g_set_error (error, G_IO_ERROR,
3332 socket_io_error_from_errno (errsv),
3333 _("Error receiving message: %s"), socket_strerror (errsv));
3340 /* decode address */
3341 if (address != NULL)
3343 if (msg.msg_namelen > 0)
3344 *address = g_socket_address_new_from_native (msg.msg_name,
3350 /* decode control messages */
3352 GPtrArray *my_messages = NULL;
3353 struct cmsghdr *cmsg;
3355 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
3357 GSocketControlMessage *message;
3359 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
3361 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
3363 if (message == NULL)
3364 /* We've already spewed about the problem in the
3365 deserialization code, so just continue */
3368 if (messages == NULL)
3370 /* we have to do it this way if the user ignores the
3371 * messages so that we will close any received fds.
3373 g_object_unref (message);
3377 if (my_messages == NULL)
3378 my_messages = g_ptr_array_new ();
3379 g_ptr_array_add (my_messages, message);
3384 *num_messages = my_messages != NULL ? my_messages->len : 0;
3388 if (my_messages == NULL)
3394 g_ptr_array_add (my_messages, NULL);
3395 *messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
3400 g_assert (my_messages == NULL);
3404 /* capture the flags */
3406 *flags = msg.msg_flags;
3412 struct sockaddr_storage addr;
3414 DWORD bytes_received;
3421 bufs = g_newa (WSABUF, num_vectors);
3422 for (i = 0; i < num_vectors; i++)
3424 bufs[i].buf = (char *)vectors[i].buffer;
3425 bufs[i].len = (gulong)vectors[i].size;
3437 if (socket->priv->blocking &&
3438 !g_socket_condition_wait (socket,
3439 G_IO_IN, cancellable, error))
3442 addrlen = sizeof addr;
3444 result = WSARecvFrom (socket->priv->fd,
3446 &bytes_received, &win_flags,
3447 (struct sockaddr *)&addr, &addrlen,
3450 result = WSARecv (socket->priv->fd,
3452 &bytes_received, &win_flags,
3456 int errsv = get_socket_errno ();
3458 if (errsv == WSAEINTR)
3461 win32_unset_event_mask (socket, FD_READ);
3463 if (socket->priv->blocking &&
3464 errsv == WSAEWOULDBLOCK)
3467 g_set_error (error, G_IO_ERROR,
3468 socket_io_error_from_errno (errsv),
3469 _("Error receiving message: %s"), socket_strerror (errsv));
3473 win32_unset_event_mask (socket, FD_READ);
3477 /* decode address */
3478 if (address != NULL)
3481 *address = g_socket_address_new_from_native (&addr, addrlen);
3486 /* capture the flags */
3490 if (messages != NULL)
3492 if (num_messages != NULL)
3495 return bytes_received;
3501 * g_socket_get_credentials:
3502 * @socket: a #GSocket.
3503 * @error: #GError for error reporting, or %NULL to ignore.
3505 * Returns the credentials of the foreign process connected to this
3506 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
3509 * If this operation isn't supported on the OS, the method fails with
3510 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
3511 * by reading the %SO_PEERCRED option on the underlying socket.
3513 * Other ways to obtain credentials from a foreign peer includes the
3514 * #GUnixCredentialsMessage type and
3515 * g_unix_connection_send_credentials() /
3516 * g_unix_connection_receive_credentials() functions.
3518 * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
3519 * that must be freed with g_object_unref().
3524 g_socket_get_credentials (GSocket *socket,
3529 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
3530 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3536 struct ucred native_creds;
3538 optlen = sizeof (struct ucred);
3539 if (getsockopt (socket->priv->fd,
3542 (void *)&native_creds,
3545 int errsv = get_socket_errno ();
3548 socket_io_error_from_errno (errsv),
3549 _("Unable to get pending error: %s"),
3550 socket_strerror (errsv));
3554 ret = g_credentials_new ();
3555 g_credentials_set_native (ret,
3556 G_CREDENTIALS_TYPE_LINUX_UCRED,
3561 g_set_error_literal (error,
3563 G_IO_ERROR_NOT_SUPPORTED,
3564 _("g_socket_get_credentials not implemented for this OS"));