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>
46 #include "gcancellable.h"
47 #include "gioenumtypes.h"
48 #include "ginetaddress.h"
49 #include "ginitable.h"
53 #include "gio-marshal.h"
54 #include "gnetworkingprivate.h"
55 #include "gsocketaddress.h"
56 #include "gsocketcontrolmessage.h"
57 #include "gcredentials.h"
62 * @short_description: Low-level socket object
64 * @see_also: #GInitable
66 * A #GSocket is a low-level networking primitive. It is a more or less
67 * direct mapping of the BSD socket API in a portable GObject based API.
68 * It supports both the UNIX socket implementations and winsock2 on Windows.
70 * #GSocket is the platform independent base upon which the higher level
71 * network primitives are based. Applications are not typically meant to
72 * use it directly, but rather through classes like #GSocketClient,
73 * #GSocketService and #GSocketConnection. However there may be cases where
74 * direct use of #GSocket is useful.
76 * #GSocket implements the #GInitable interface, so if it is manually constructed
77 * by e.g. g_object_new() you must call g_initable_init() and check the
78 * results before using the object. This is done automatically in
79 * g_socket_new() and g_socket_new_from_fd(), so these functions can return
82 * Sockets operate in two general modes, blocking or non-blocking. When
83 * in blocking mode all operations block until the requested operation
84 * is finished or there is an error. In non-blocking mode all calls that
85 * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
86 * To know when a call would successfully run you can call g_socket_condition_check(),
87 * or g_socket_condition_wait(). You can also use g_socket_create_source() and
88 * attach it to a #GMainContext to get callbacks when I/O is possible.
89 * Note that all sockets are always set to non blocking mode in the system, and
90 * blocking mode is emulated in GSocket.
92 * When working in non-blocking mode applications should always be able to
93 * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
94 * function said that I/O was possible. This can easily happen in case
95 * of a race condition in the application, but it can also happen for other
96 * reasons. For instance, on Windows a socket is always seen as writable
97 * until a write returns %G_IO_ERROR_WOULD_BLOCK.
99 * #GSocket<!-- -->s can be either connection oriented or datagram based.
100 * For connection oriented types you must first establish a connection by
101 * either connecting to an address or accepting a connection from another
102 * address. For connectionless socket types the target/source address is
103 * specified or received in each I/O operation.
105 * All socket file descriptors are set to be close-on-exec.
107 * Note that creating a #GSocket causes the signal %SIGPIPE to be
108 * ignored for the remainder of the program. If you are writing a
109 * command-line utility that uses #GSocket, you may need to take into
110 * account the fact that your program will not automatically be killed
111 * if it tries to write to %stdout after it has been closed.
116 static void g_socket_initable_iface_init (GInitableIface *iface);
117 static gboolean g_socket_initable_init (GInitable *initable,
118 GCancellable *cancellable,
121 G_DEFINE_TYPE_WITH_CODE (GSocket, g_socket, G_TYPE_OBJECT,
122 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
123 g_socket_initable_iface_init));
140 struct _GSocketPrivate
142 GSocketFamily family;
144 GSocketProtocol protocol;
148 GError *construct_error;
149 GSocketAddress *remote_address;
157 guint connect_pending : 1;
163 GList *requested_conditions; /* list of requested GIOCondition * */
168 get_socket_errno (void)
173 return WSAGetLastError ();
178 socket_io_error_from_errno (int err)
181 return g_io_error_from_errno (err);
186 return G_IO_ERROR_ADDRESS_IN_USE;
188 return G_IO_ERROR_WOULD_BLOCK;
190 return G_IO_ERROR_PERMISSION_DENIED;
191 case WSA_INVALID_HANDLE:
192 case WSA_INVALID_PARAMETER:
195 return G_IO_ERROR_INVALID_ARGUMENT;
196 case WSAEPROTONOSUPPORT:
197 return G_IO_ERROR_NOT_SUPPORTED;
199 return G_IO_ERROR_CANCELLED;
200 case WSAESOCKTNOSUPPORT:
202 case WSAEPFNOSUPPORT:
203 case WSAEAFNOSUPPORT:
204 return G_IO_ERROR_NOT_SUPPORTED;
206 return G_IO_ERROR_FAILED;
212 socket_strerror (int err)
215 return g_strerror (err);
217 static GStaticPrivate last_msg = G_STATIC_PRIVATE_INIT;
220 msg = g_win32_error_message (err);
221 g_static_private_set (&last_msg, msg, g_free);
228 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
230 _win32_unset_event_mask (GSocket *socket, int mask)
232 socket->priv->current_events &= ~mask;
233 socket->priv->current_errors &= ~mask;
236 #define win32_unset_event_mask(_socket, _mask)
240 set_fd_nonblocking (int fd)
249 if ((arg = fcntl (fd, F_GETFL, NULL)) < 0)
251 g_warning ("Error getting socket status flags: %s", socket_strerror (errno));
255 arg = arg | O_NONBLOCK;
257 if (fcntl (fd, F_SETFL, arg) < 0)
258 g_warning ("Error setting socket status flags: %s", socket_strerror (errno));
262 if (ioctlsocket (fd, FIONBIO, &arg) == SOCKET_ERROR)
264 int errsv = get_socket_errno ();
265 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
271 check_socket (GSocket *socket,
274 if (!socket->priv->inited)
276 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
277 _("Invalid socket, not initialized"));
281 if (socket->priv->construct_error)
283 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
284 _("Invalid socket, initialization failed due to: %s"),
285 socket->priv->construct_error->message);
289 if (socket->priv->closed)
291 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
292 _("Socket is already closed"));
296 if (socket->priv->timed_out)
298 socket->priv->timed_out = FALSE;
299 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
300 _("Socket I/O timed out"));
308 g_socket_details_from_fd (GSocket *socket)
310 struct sockaddr_storage address;
317 /* See bug #611756 */
318 BOOL bool_val = FALSE;
323 fd = socket->priv->fd;
324 optlen = sizeof value;
325 if (getsockopt (fd, SOL_SOCKET, SO_TYPE, (void *)&value, &optlen) != 0)
327 errsv = get_socket_errno ();
338 /* programmer error */
339 g_error ("creating GSocket from fd %d: %s\n",
340 fd, socket_strerror (errsv));
348 g_assert (optlen == sizeof value);
352 socket->priv->type = G_SOCKET_TYPE_STREAM;
356 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
360 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
364 socket->priv->type = G_SOCKET_TYPE_INVALID;
368 addrlen = sizeof address;
369 if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
371 errsv = get_socket_errno ();
375 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
376 sizeof address.ss_family <= addrlen);
377 switch (address.ss_family)
379 case G_SOCKET_FAMILY_IPV4:
380 case G_SOCKET_FAMILY_IPV6:
381 socket->priv->family = address.ss_family;
382 switch (socket->priv->type)
384 case G_SOCKET_TYPE_STREAM:
385 socket->priv->protocol = G_SOCKET_PROTOCOL_TCP;
388 case G_SOCKET_TYPE_DATAGRAM:
389 socket->priv->protocol = G_SOCKET_PROTOCOL_UDP;
392 case G_SOCKET_TYPE_SEQPACKET:
393 socket->priv->protocol = G_SOCKET_PROTOCOL_SCTP;
401 case G_SOCKET_FAMILY_UNIX:
402 socket->priv->family = G_SOCKET_FAMILY_UNIX;
403 socket->priv->protocol = G_SOCKET_PROTOCOL_DEFAULT;
407 socket->priv->family = G_SOCKET_FAMILY_INVALID;
411 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
413 addrlen = sizeof address;
414 if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
415 socket->priv->connected = TRUE;
418 optlen = sizeof bool_val;
419 if (getsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
420 (void *)&bool_val, &optlen) == 0)
423 /* Experimentation indicates that the SO_KEEPALIVE value is
424 * actually a char on Windows, even if documentation claims it
425 * to be a BOOL which is a typedef for int. So this g_assert()
426 * fails. See bug #611756.
428 g_assert (optlen == sizeof bool_val);
430 socket->priv->keepalive = !!bool_val;
434 /* Can't read, maybe not supported, assume FALSE */
435 socket->priv->keepalive = FALSE;
441 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
442 socket_io_error_from_errno (errsv),
443 _("creating GSocket from fd: %s"),
444 socket_strerror (errsv));
448 g_socket_create_socket (GSocketFamily family,
458 case G_SOCKET_TYPE_STREAM:
459 native_type = SOCK_STREAM;
462 case G_SOCKET_TYPE_DATAGRAM:
463 native_type = SOCK_DGRAM;
466 case G_SOCKET_TYPE_SEQPACKET:
467 native_type = SOCK_SEQPACKET;
471 g_assert_not_reached ();
476 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
477 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
482 fd = socket (family, native_type | SOCK_CLOEXEC, protocol);
483 /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
484 if (fd < 0 && errno == EINVAL)
486 fd = socket (family, native_type, protocol);
490 int errsv = get_socket_errno ();
492 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
493 _("Unable to create socket: %s"), socket_strerror (errsv));
500 /* We always want to set close-on-exec to protect users. If you
501 need to so some weird inheritance to exec you can re-enable this
502 using lower level hacks with g_socket_get_fd(). */
503 flags = fcntl (fd, F_GETFD, 0);
505 (flags & FD_CLOEXEC) == 0)
508 fcntl (fd, F_SETFD, flags);
517 g_socket_constructed (GObject *object)
519 GSocket *socket = G_SOCKET (object);
521 if (socket->priv->fd >= 0)
522 /* create socket->priv info from the fd */
523 g_socket_details_from_fd (socket);
526 /* create the fd from socket->priv info */
527 socket->priv->fd = g_socket_create_socket (socket->priv->family,
529 socket->priv->protocol,
530 &socket->priv->construct_error);
532 /* Always use native nonblocking sockets, as
533 windows sets sockets to nonblocking automatically
534 in certain operations. This way we make things work
535 the same on all platforms */
536 if (socket->priv->fd != -1)
537 set_fd_nonblocking (socket->priv->fd);
541 g_socket_get_property (GObject *object,
546 GSocket *socket = G_SOCKET (object);
547 GSocketAddress *address;
552 g_value_set_enum (value, socket->priv->family);
556 g_value_set_enum (value, socket->priv->type);
560 g_value_set_enum (value, socket->priv->protocol);
564 g_value_set_int (value, socket->priv->fd);
568 g_value_set_boolean (value, socket->priv->blocking);
571 case PROP_LISTEN_BACKLOG:
572 g_value_set_int (value, socket->priv->listen_backlog);
576 g_value_set_boolean (value, socket->priv->keepalive);
579 case PROP_LOCAL_ADDRESS:
580 address = g_socket_get_local_address (socket, NULL);
581 g_value_take_object (value, address);
584 case PROP_REMOTE_ADDRESS:
585 address = g_socket_get_remote_address (socket, NULL);
586 g_value_take_object (value, address);
590 g_value_set_uint (value, socket->priv->timeout);
594 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
599 g_socket_set_property (GObject *object,
604 GSocket *socket = G_SOCKET (object);
609 socket->priv->family = g_value_get_enum (value);
613 socket->priv->type = g_value_get_enum (value);
617 socket->priv->protocol = g_value_get_enum (value);
621 socket->priv->fd = g_value_get_int (value);
625 g_socket_set_blocking (socket, g_value_get_boolean (value));
628 case PROP_LISTEN_BACKLOG:
629 g_socket_set_listen_backlog (socket, g_value_get_int (value));
633 g_socket_set_keepalive (socket, g_value_get_boolean (value));
637 g_socket_set_timeout (socket, g_value_get_uint (value));
641 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
646 g_socket_finalize (GObject *object)
648 GSocket *socket = G_SOCKET (object);
650 g_clear_error (&socket->priv->construct_error);
652 if (socket->priv->fd != -1 &&
653 !socket->priv->closed)
654 g_socket_close (socket, NULL);
656 if (socket->priv->remote_address)
657 g_object_unref (socket->priv->remote_address);
660 if (socket->priv->event != WSA_INVALID_EVENT)
662 WSACloseEvent (socket->priv->event);
663 socket->priv->event = WSA_INVALID_EVENT;
666 g_assert (socket->priv->requested_conditions == NULL);
669 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
670 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
674 g_socket_class_init (GSocketClass *klass)
676 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
679 /* Make sure winsock has been initialized */
680 type = g_inet_address_get_type ();
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: 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: 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: 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 is
1759 * some data to receive or there is an error. If there is no data available
1760 * and the socket is in non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error
1761 * will be returned. To be notified when data is available, wait for the
1762 * %G_IO_IN condition.
1764 * On error -1 is returned and @error is set accordingly.
1766 * Returns: Number of bytes read, or -1 on error
1771 g_socket_receive (GSocket *socket,
1774 GCancellable *cancellable,
1777 return g_socket_receive_with_blocking (socket, buffer, size,
1778 socket->priv->blocking,
1779 cancellable, error);
1783 * g_socket_receive_with_blocking:
1784 * @socket: a #GSocket
1785 * @buffer: a buffer to read data into (which should be at least @size
1787 * @size: the number of bytes you want to read from the socket
1788 * @blocking: whether to do blocking or non-blocking I/O
1789 * @cancellable: a %GCancellable or %NULL
1790 * @error: #GError for error reporting, or %NULL to ignore.
1792 * This behaves exactly the same as g_socket_receive(), except that
1793 * the choice of blocking or non-blocking behavior is determined by
1794 * the @blocking argument rather than by @socket's properties.
1796 * Returns: Number of bytes read, or -1 on error
1801 g_socket_receive_with_blocking (GSocket *socket,
1805 GCancellable *cancellable,
1810 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1812 if (!check_socket (socket, error))
1815 if (g_cancellable_set_error_if_cancelled (cancellable, error))
1821 !g_socket_condition_wait (socket,
1822 G_IO_IN, cancellable, error))
1825 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
1827 int errsv = get_socket_errno ();
1834 #ifdef WSAEWOULDBLOCK
1835 if (errsv == WSAEWOULDBLOCK)
1838 if (errsv == EWOULDBLOCK ||
1844 win32_unset_event_mask (socket, FD_READ);
1846 g_set_error (error, G_IO_ERROR,
1847 socket_io_error_from_errno (errsv),
1848 _("Error receiving data: %s"), socket_strerror (errsv));
1852 win32_unset_event_mask (socket, FD_READ);
1861 * g_socket_receive_from:
1862 * @socket: a #GSocket
1863 * @address: a pointer to a #GSocketAddress pointer, or %NULL
1864 * @buffer: a buffer to read data into (which should be at least @size
1866 * @size: the number of bytes you want to read from the socket
1867 * @cancellable: a %GCancellable or %NULL
1868 * @error: #GError for error reporting, or %NULL to ignore.
1870 * Receive data (up to @size bytes) from a socket.
1872 * If @address is non-%NULL then @address will be set equal to the
1873 * source address of the received packet.
1874 * @address is owned by the caller.
1876 * See g_socket_receive() for additional information.
1878 * Returns: Number of bytes read, or -1 on error
1883 g_socket_receive_from (GSocket *socket,
1884 GSocketAddress **address,
1887 GCancellable *cancellable,
1895 return g_socket_receive_message (socket,
1903 /* Although we ignore SIGPIPE, gdb will still stop if the app receives
1904 * one, which can be confusing and annoying. So if possible, we want
1905 * to suppress the signal entirely.
1908 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
1910 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
1915 * @socket: a #GSocket
1916 * @buffer: the buffer containing the data to send.
1917 * @size: the number of bytes to send
1918 * @cancellable: a %GCancellable or %NULL
1919 * @error: #GError for error reporting, or %NULL to ignore.
1921 * Tries to send @size bytes from @buffer on the socket. This is
1922 * mainly used by connection-oriented sockets; it is identical to
1923 * g_socket_send_to() with @address set to %NULL.
1925 * If the socket is in blocking mode the call will block until there is
1926 * space for the data in the socket queue. If there is no space available
1927 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1928 * will be returned. To be notified when space is available, wait for the
1929 * %G_IO_OUT condition. Note though that you may still receive
1930 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
1931 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
1932 * very common due to the way the underlying APIs work.)
1934 * On error -1 is returned and @error is set accordingly.
1936 * Returns: Number of bytes written (which may be less than @size), or -1
1942 g_socket_send (GSocket *socket,
1943 const gchar *buffer,
1945 GCancellable *cancellable,
1948 return g_socket_send_with_blocking (socket, buffer, size,
1949 socket->priv->blocking,
1950 cancellable, error);
1954 * g_socket_send_with_blocking:
1955 * @socket: a #GSocket
1956 * @buffer: the buffer containing the data to send.
1957 * @size: the number of bytes to send
1958 * @blocking: whether to do blocking or non-blocking I/O
1959 * @cancellable: a %GCancellable or %NULL
1960 * @error: #GError for error reporting, or %NULL to ignore.
1962 * This behaves exactly the same as g_socket_send(), except that
1963 * the choice of blocking or non-blocking behavior is determined by
1964 * the @blocking argument rather than by @socket's properties.
1966 * Returns: Number of bytes written (which may be less than @size), or -1
1972 g_socket_send_with_blocking (GSocket *socket,
1973 const gchar *buffer,
1976 GCancellable *cancellable,
1981 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1983 if (!check_socket (socket, error))
1986 if (g_cancellable_set_error_if_cancelled (cancellable, error))
1992 !g_socket_condition_wait (socket,
1993 G_IO_OUT, cancellable, error))
1996 if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
1998 int errsv = get_socket_errno ();
2003 #ifdef WSAEWOULDBLOCK
2004 if (errsv == WSAEWOULDBLOCK)
2005 win32_unset_event_mask (socket, FD_WRITE);
2010 #ifdef WSAEWOULDBLOCK
2011 if (errsv == WSAEWOULDBLOCK)
2014 if (errsv == EWOULDBLOCK ||
2020 g_set_error (error, G_IO_ERROR,
2021 socket_io_error_from_errno (errsv),
2022 _("Error sending data: %s"), socket_strerror (errsv));
2033 * @socket: a #GSocket
2034 * @address: a #GSocketAddress, or %NULL
2035 * @buffer: the buffer containing the data to send.
2036 * @size: the number of bytes to send
2037 * @cancellable: a %GCancellable or %NULL
2038 * @error: #GError for error reporting, or %NULL to ignore.
2040 * Tries to send @size bytes from @buffer to @address. If @address is
2041 * %NULL then the message is sent to the default receiver (set by
2042 * g_socket_connect()).
2044 * See g_socket_send() for additional information.
2046 * Returns: Number of bytes written (which may be less than @size), or -1
2052 g_socket_send_to (GSocket *socket,
2053 GSocketAddress *address,
2054 const gchar *buffer,
2056 GCancellable *cancellable,
2064 return g_socket_send_message (socket,
2074 * g_socket_shutdown:
2075 * @socket: a #GSocket
2076 * @shutdown_read: whether to shut down the read side
2077 * @shutdown_write: whether to shut down the write side
2078 * @error: #GError for error reporting, or %NULL to ignore.
2080 * Shut down part of a full-duplex connection.
2082 * If @shutdown_read is %TRUE then the recieving side of the connection
2083 * is shut down, and further reading is disallowed.
2085 * If @shutdown_write is %TRUE then the sending side of the connection
2086 * is shut down, and further writing is disallowed.
2088 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
2090 * One example where this is used is graceful disconnect for TCP connections
2091 * where you close the sending side, then wait for the other side to close
2092 * the connection, thus ensuring that the other side saw all sent data.
2094 * Returns: %TRUE on success, %FALSE on error
2099 g_socket_shutdown (GSocket *socket,
2100 gboolean shutdown_read,
2101 gboolean shutdown_write,
2106 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2108 if (!check_socket (socket, NULL))
2112 if (!shutdown_read && !shutdown_write)
2116 if (shutdown_read && shutdown_write)
2118 else if (shutdown_read)
2123 if (shutdown_read && shutdown_write)
2125 else if (shutdown_read)
2131 if (shutdown (socket->priv->fd, how) != 0)
2133 int errsv = get_socket_errno ();
2134 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2135 _("Unable to create socket: %s"), socket_strerror (errsv));
2139 if (shutdown_read && shutdown_write)
2140 socket->priv->connected = FALSE;
2147 * @socket: a #GSocket
2148 * @error: #GError for error reporting, or %NULL to ignore.
2150 * Closes the socket, shutting down any active connection.
2152 * Closing a socket does not wait for all outstanding I/O operations
2153 * to finish, so the caller should not rely on them to be guaranteed
2154 * to complete even if the close returns with no error.
2156 * Once the socket is closed, all other operations will return
2157 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
2160 * Sockets will be automatically closed when the last reference
2161 * is dropped, but you might want to call this function to make sure
2162 * resources are released as early as possible.
2164 * Beware that due to the way that TCP works, it is possible for
2165 * recently-sent data to be lost if either you close a socket while the
2166 * %G_IO_IN condition is set, or else if the remote connection tries to
2167 * send something to you after you close the socket but before it has
2168 * finished reading all of the data you sent. There is no easy generic
2169 * way to avoid this problem; the easiest fix is to design the network
2170 * protocol such that the client will never send data "out of turn".
2171 * Another solution is for the server to half-close the connection by
2172 * calling g_socket_shutdown() with only the @shutdown_write flag set,
2173 * and then wait for the client to notice this and close its side of the
2174 * connection, after which the server can safely call g_socket_close().
2175 * (This is what #GTcpConnection does if you call
2176 * g_tcp_connection_set_graceful_disconnect(). But of course, this
2177 * only works if the client will close its connection after the server
2180 * Returns: %TRUE on success, %FALSE on error
2185 g_socket_close (GSocket *socket,
2190 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2192 if (socket->priv->closed)
2193 return TRUE; /* Multiple close not an error */
2195 if (!check_socket (socket, NULL))
2201 res = closesocket (socket->priv->fd);
2203 res = close (socket->priv->fd);
2207 int errsv = get_socket_errno ();
2212 g_set_error (error, G_IO_ERROR,
2213 socket_io_error_from_errno (errsv),
2214 _("Error closing socket: %s"),
2215 socket_strerror (errsv));
2221 socket->priv->connected = FALSE;
2222 socket->priv->closed = TRUE;
2223 if (socket->priv->remote_address)
2225 g_object_unref (socket->priv->remote_address);
2226 socket->priv->remote_address = NULL;
2233 * g_socket_is_closed:
2234 * @socket: a #GSocket
2236 * Checks whether a socket is closed.
2238 * Returns: %TRUE if socket is closed, %FALSE otherwise
2243 g_socket_is_closed (GSocket *socket)
2245 return socket->priv->closed;
2249 /* Broken source, used on errors */
2251 broken_prepare (GSource *source,
2258 broken_check (GSource *source)
2264 broken_dispatch (GSource *source,
2265 GSourceFunc callback,
2271 static GSourceFuncs broken_funcs =
2280 network_events_for_condition (GIOCondition condition)
2284 if (condition & G_IO_IN)
2285 event_mask |= (FD_READ | FD_ACCEPT);
2286 if (condition & G_IO_OUT)
2287 event_mask |= (FD_WRITE | FD_CONNECT);
2288 event_mask |= FD_CLOSE;
2294 ensure_event (GSocket *socket)
2296 if (socket->priv->event == WSA_INVALID_EVENT)
2297 socket->priv->event = WSACreateEvent();
2301 update_select_events (GSocket *socket)
2308 ensure_event (socket);
2311 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
2314 event_mask |= network_events_for_condition (*ptr);
2317 if (event_mask != socket->priv->selected_events)
2319 /* If no events selected, disable event so we can unset
2322 if (event_mask == 0)
2325 event = socket->priv->event;
2327 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
2328 socket->priv->selected_events = event_mask;
2333 add_condition_watch (GSocket *socket,
2334 GIOCondition *condition)
2336 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
2338 socket->priv->requested_conditions =
2339 g_list_prepend (socket->priv->requested_conditions, condition);
2341 update_select_events (socket);
2345 remove_condition_watch (GSocket *socket,
2346 GIOCondition *condition)
2348 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
2350 socket->priv->requested_conditions =
2351 g_list_remove (socket->priv->requested_conditions, condition);
2353 update_select_events (socket);
2357 update_condition (GSocket *socket)
2359 WSANETWORKEVENTS events;
2360 GIOCondition condition;
2362 if (WSAEnumNetworkEvents (socket->priv->fd,
2363 socket->priv->event,
2366 socket->priv->current_events |= events.lNetworkEvents;
2367 if (events.lNetworkEvents & FD_WRITE &&
2368 events.iErrorCode[FD_WRITE_BIT] != 0)
2369 socket->priv->current_errors |= FD_WRITE;
2370 if (events.lNetworkEvents & FD_CONNECT &&
2371 events.iErrorCode[FD_CONNECT_BIT] != 0)
2372 socket->priv->current_errors |= FD_CONNECT;
2376 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
2377 condition |= G_IO_IN;
2379 if (socket->priv->current_events & FD_CLOSE ||
2380 socket->priv->closed)
2381 condition |= G_IO_HUP;
2383 /* Never report both G_IO_OUT and HUP, these are
2384 mutually exclusive (can't write to a closed socket) */
2385 if ((condition & G_IO_HUP) == 0 &&
2386 socket->priv->current_events & FD_WRITE)
2388 if (socket->priv->current_errors & FD_WRITE)
2389 condition |= G_IO_ERR;
2391 condition |= G_IO_OUT;
2395 if (socket->priv->current_events & FD_CONNECT)
2397 if (socket->priv->current_errors & FD_CONNECT)
2398 condition |= (G_IO_HUP | G_IO_ERR);
2400 condition |= G_IO_OUT;
2412 GIOCondition condition;
2413 GCancellable *cancellable;
2414 GPollFD cancel_pollfd;
2415 gint64 timeout_time;
2419 socket_source_prepare (GSource *source,
2422 GSocketSource *socket_source = (GSocketSource *)source;
2424 if (g_cancellable_is_cancelled (socket_source->cancellable))
2427 if (socket_source->timeout_time)
2431 now = g_source_get_time (source);
2432 /* Round up to ensure that we don't try again too early */
2433 *timeout = (socket_source->timeout_time - now + 999) / 1000;
2436 socket_source->socket->priv->timed_out = TRUE;
2437 socket_source->pollfd.revents = socket_source->condition & (G_IO_IN | G_IO_OUT);
2446 socket_source->pollfd.revents = update_condition (socket_source->socket);
2449 if ((socket_source->condition & socket_source->pollfd.revents) != 0)
2456 socket_source_check (GSource *source)
2460 return socket_source_prepare (source, &timeout);
2464 socket_source_dispatch (GSource *source,
2465 GSourceFunc callback,
2468 GSocketSourceFunc func = (GSocketSourceFunc)callback;
2469 GSocketSource *socket_source = (GSocketSource *)source;
2471 return (*func) (socket_source->socket,
2472 socket_source->pollfd.revents & socket_source->condition,
2477 socket_source_finalize (GSource *source)
2479 GSocketSource *socket_source = (GSocketSource *)source;
2482 socket = socket_source->socket;
2485 remove_condition_watch (socket, &socket_source->condition);
2488 g_object_unref (socket);
2490 if (socket_source->cancellable)
2492 g_cancellable_release_fd (socket_source->cancellable);
2493 g_object_unref (socket_source->cancellable);
2498 socket_source_closure_callback (GSocket *socket,
2499 GIOCondition condition,
2502 GClosure *closure = data;
2504 GValue params[2] = { { 0, }, { 0, } };
2505 GValue result_value = { 0, };
2508 g_value_init (&result_value, G_TYPE_BOOLEAN);
2510 g_value_init (¶ms[0], G_TYPE_SOCKET);
2511 g_value_set_object (¶ms[0], socket);
2512 g_value_init (¶ms[1], G_TYPE_IO_CONDITION);
2513 g_value_set_flags (¶ms[1], condition);
2515 g_closure_invoke (closure, &result_value, 2, params, NULL);
2517 result = g_value_get_boolean (&result_value);
2518 g_value_unset (&result_value);
2519 g_value_unset (¶ms[0]);
2520 g_value_unset (¶ms[1]);
2525 static GSourceFuncs socket_source_funcs =
2527 socket_source_prepare,
2528 socket_source_check,
2529 socket_source_dispatch,
2530 socket_source_finalize,
2531 (GSourceFunc)socket_source_closure_callback,
2532 (GSourceDummyMarshal)_gio_marshal_BOOLEAN__FLAGS,
2536 socket_source_new (GSocket *socket,
2537 GIOCondition condition,
2538 GCancellable *cancellable)
2541 GSocketSource *socket_source;
2544 ensure_event (socket);
2546 if (socket->priv->event == WSA_INVALID_EVENT)
2548 g_warning ("Failed to create WSAEvent");
2549 return g_source_new (&broken_funcs, sizeof (GSource));
2553 condition |= G_IO_HUP | G_IO_ERR;
2555 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
2556 g_source_set_name (source, "GSocket");
2557 socket_source = (GSocketSource *)source;
2559 socket_source->socket = g_object_ref (socket);
2560 socket_source->condition = condition;
2562 if (g_cancellable_make_pollfd (cancellable,
2563 &socket_source->cancel_pollfd))
2565 socket_source->cancellable = g_object_ref (cancellable);
2566 g_source_add_poll (source, &socket_source->cancel_pollfd);
2570 add_condition_watch (socket, &socket_source->condition);
2571 socket_source->pollfd.fd = (gintptr) socket->priv->event;
2573 socket_source->pollfd.fd = socket->priv->fd;
2576 socket_source->pollfd.events = condition;
2577 socket_source->pollfd.revents = 0;
2578 g_source_add_poll (source, &socket_source->pollfd);
2580 if (socket->priv->timeout)
2581 socket_source->timeout_time = g_get_monotonic_time () +
2582 socket->priv->timeout * 1000000;
2585 socket_source->timeout_time = 0;
2591 * g_socket_create_source:
2592 * @socket: a #GSocket
2593 * @condition: a #GIOCondition mask to monitor
2594 * @cancellable: a %GCancellable or %NULL
2596 * Creates a %GSource that can be attached to a %GMainContext to monitor
2597 * for the availibility of the specified @condition on the socket.
2599 * The callback on the source is of the #GSocketSourceFunc type.
2601 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
2602 * these conditions will always be reported output if they are true.
2604 * @cancellable if not %NULL can be used to cancel the source, which will
2605 * cause the source to trigger, reporting the current condition (which
2606 * is likely 0 unless cancellation happened at the same time as a
2607 * condition change). You can check for this in the callback using
2608 * g_cancellable_is_cancelled().
2610 * If @socket has a timeout set, and it is reached before @condition
2611 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
2612 * %G_IO_OUT depending on @condition. However, @socket will have been
2613 * marked as having had a timeout, and so the next #GSocket I/O method
2614 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
2616 * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
2621 g_socket_create_source (GSocket *socket,
2622 GIOCondition condition,
2623 GCancellable *cancellable)
2625 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
2627 return socket_source_new (socket, condition, cancellable);
2631 * g_socket_condition_check:
2632 * @socket: a #GSocket
2633 * @condition: a #GIOCondition mask to check
2635 * Checks on the readiness of @socket to perform operations.
2636 * The operations specified in @condition are checked for and masked
2637 * against the currently-satisfied conditions on @socket. The result
2640 * Note that on Windows, it is possible for an operation to return
2641 * %G_IO_ERROR_WOULD_BLOCK even immediately after
2642 * g_socket_condition_check() has claimed that the socket is ready for
2643 * writing. Rather than calling g_socket_condition_check() and then
2644 * writing to the socket if it succeeds, it is generally better to
2645 * simply try writing to the socket right away, and try again later if
2646 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
2648 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2649 * these conditions will always be set in the output if they are true.
2651 * This call never blocks.
2653 * Returns: the @GIOCondition mask of the current state
2658 g_socket_condition_check (GSocket *socket,
2659 GIOCondition condition)
2661 if (!check_socket (socket, NULL))
2666 GIOCondition current_condition;
2668 condition |= G_IO_ERR | G_IO_HUP;
2670 add_condition_watch (socket, &condition);
2671 current_condition = update_condition (socket);
2672 remove_condition_watch (socket, &condition);
2673 return condition & current_condition;
2679 poll_fd.fd = socket->priv->fd;
2680 poll_fd.events = condition;
2683 result = g_poll (&poll_fd, 1, 0);
2684 while (result == -1 && get_socket_errno () == EINTR);
2686 return poll_fd.revents;
2692 * g_socket_condition_wait:
2693 * @socket: a #GSocket
2694 * @condition: a #GIOCondition mask to wait for
2695 * @cancellable: a #GCancellable, or %NULL
2696 * @error: a #GError pointer, or %NULL
2698 * Waits for @condition to become true on @socket. When the condition
2699 * is met, %TRUE is returned.
2701 * If @cancellable is cancelled before the condition is met, or if the
2702 * socket has a timeout set and it is reached before the condition is
2703 * met, then %FALSE is returned and @error, if non-%NULL, is set to
2704 * the appropriate value (%G_IO_ERROR_CANCELLED or
2705 * %G_IO_ERROR_TIMED_OUT).
2707 * Returns: %TRUE if the condition was met, %FALSE otherwise
2712 g_socket_condition_wait (GSocket *socket,
2713 GIOCondition condition,
2714 GCancellable *cancellable,
2717 if (!check_socket (socket, error))
2720 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2725 GIOCondition current_condition;
2731 /* Always check these */
2732 condition |= G_IO_ERR | G_IO_HUP;
2734 add_condition_watch (socket, &condition);
2737 events[num_events++] = socket->priv->event;
2739 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
2740 events[num_events++] = (WSAEVENT)cancel_fd.fd;
2742 if (socket->priv->timeout)
2743 timeout = socket->priv->timeout * 1000;
2745 timeout = WSA_INFINITE;
2747 current_condition = update_condition (socket);
2748 while ((condition & current_condition) == 0)
2750 res = WSAWaitForMultipleEvents(num_events, events,
2751 FALSE, timeout, FALSE);
2752 if (res == WSA_WAIT_FAILED)
2754 int errsv = get_socket_errno ();
2756 g_set_error (error, G_IO_ERROR,
2757 socket_io_error_from_errno (errsv),
2758 _("Waiting for socket condition: %s"),
2759 socket_strerror (errsv));
2762 else if (res == WSA_WAIT_TIMEOUT)
2764 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
2765 _("Socket I/O timed out"));
2769 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2772 current_condition = update_condition (socket);
2774 remove_condition_watch (socket, &condition);
2776 g_cancellable_release_fd (cancellable);
2778 return (condition & current_condition) != 0;
2787 poll_fd[0].fd = socket->priv->fd;
2788 poll_fd[0].events = condition;
2791 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
2794 if (socket->priv->timeout)
2795 timeout = socket->priv->timeout * 1000;
2800 result = g_poll (poll_fd, num, timeout);
2801 while (result == -1 && get_socket_errno () == EINTR);
2804 g_cancellable_release_fd (cancellable);
2808 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
2809 _("Socket I/O timed out"));
2813 return !g_cancellable_set_error_if_cancelled (cancellable, error);
2819 * g_socket_send_message:
2820 * @socket: a #GSocket
2821 * @address: a #GSocketAddress, or %NULL
2822 * @vectors: an array of #GOutputVector structs
2823 * @num_vectors: the number of elements in @vectors, or -1
2824 * @messages: a pointer to an array of #GSocketControlMessages, or
2826 * @num_messages: number of elements in @messages, or -1.
2827 * @flags: an int containing #GSocketMsgFlags flags
2828 * @cancellable: a %GCancellable or %NULL
2829 * @error: #GError for error reporting, or %NULL to ignore.
2831 * Send data to @address on @socket. This is the most complicated and
2832 * fully-featured version of this call. For easier use, see
2833 * g_socket_send() and g_socket_send_to().
2835 * If @address is %NULL then the message is sent to the default receiver
2836 * (set by g_socket_connect()).
2838 * @vectors must point to an array of #GOutputVector structs and
2839 * @num_vectors must be the length of this array. (If @num_vectors is -1,
2840 * then @vectors is assumed to be terminated by a #GOutputVector with a
2841 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
2842 * that the sent data will be gathered from. Using multiple
2843 * #GOutputVector<!-- -->s is more memory-efficient than manually copying
2844 * data from multiple sources into a single buffer, and more
2845 * network-efficient than making multiple calls to g_socket_send().
2847 * @messages, if non-%NULL, is taken to point to an array of @num_messages
2848 * #GSocketControlMessage instances. These correspond to the control
2849 * messages to be sent on the socket.
2850 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
2853 * @flags modify how the message is sent. The commonly available arguments
2854 * for this are available in the #GSocketMsgFlags enum, but the
2855 * values there are the same as the system values, and the flags
2856 * are passed in as-is, so you can pass in system-specific flags too.
2858 * If the socket is in blocking mode the call will block until there is
2859 * space for the data in the socket queue. If there is no space available
2860 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2861 * will be returned. To be notified when space is available, wait for the
2862 * %G_IO_OUT condition. Note though that you may still receive
2863 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2864 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2865 * very common due to the way the underlying APIs work.)
2867 * On error -1 is returned and @error is set accordingly.
2869 * Returns: Number of bytes written (which may be less than @size), or -1
2875 g_socket_send_message (GSocket *socket,
2876 GSocketAddress *address,
2877 GOutputVector *vectors,
2879 GSocketControlMessage **messages,
2882 GCancellable *cancellable,
2885 GOutputVector one_vector;
2888 if (!check_socket (socket, error))
2891 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2894 if (num_vectors == -1)
2896 for (num_vectors = 0;
2897 vectors[num_vectors].buffer != NULL;
2902 if (num_messages == -1)
2904 for (num_messages = 0;
2905 messages != NULL && messages[num_messages] != NULL;
2910 if (num_vectors == 0)
2914 one_vector.buffer = &zero;
2915 one_vector.size = 1;
2917 vectors = &one_vector;
2930 msg.msg_namelen = g_socket_address_get_native_size (address);
2931 msg.msg_name = g_alloca (msg.msg_namelen);
2932 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
2937 msg.msg_name = NULL;
2938 msg.msg_namelen = 0;
2943 /* this entire expression will be evaluated at compile time */
2944 if (sizeof *msg.msg_iov == sizeof *vectors &&
2945 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2946 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2947 G_STRUCT_OFFSET (GOutputVector, buffer) &&
2948 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2949 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2950 G_STRUCT_OFFSET (GOutputVector, size))
2951 /* ABI is compatible */
2953 msg.msg_iov = (struct iovec *) vectors;
2954 msg.msg_iovlen = num_vectors;
2957 /* ABI is incompatible */
2961 msg.msg_iov = g_newa (struct iovec, num_vectors);
2962 for (i = 0; i < num_vectors; i++)
2964 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
2965 msg.msg_iov[i].iov_len = vectors[i].size;
2967 msg.msg_iovlen = num_vectors;
2973 struct cmsghdr *cmsg;
2976 msg.msg_controllen = 0;
2977 for (i = 0; i < num_messages; i++)
2978 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
2980 if (msg.msg_controllen == 0)
2981 msg.msg_control = NULL;
2984 msg.msg_control = g_alloca (msg.msg_controllen);
2985 memset (msg.msg_control, '\0', msg.msg_controllen);
2988 cmsg = CMSG_FIRSTHDR (&msg);
2989 for (i = 0; i < num_messages; i++)
2991 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
2992 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
2993 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
2994 g_socket_control_message_serialize (messages[i],
2996 cmsg = CMSG_NXTHDR (&msg, cmsg);
2998 g_assert (cmsg == NULL);
3003 if (socket->priv->blocking &&
3004 !g_socket_condition_wait (socket,
3005 G_IO_OUT, cancellable, error))
3008 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
3011 int errsv = get_socket_errno ();
3016 if (socket->priv->blocking &&
3017 (errsv == EWOULDBLOCK ||
3021 g_set_error (error, G_IO_ERROR,
3022 socket_io_error_from_errno (errsv),
3023 _("Error sending message: %s"), socket_strerror (errsv));
3034 struct sockaddr_storage addr;
3041 /* Win32 doesn't support control messages.
3042 Actually this is possible for raw and datagram sockets
3043 via WSASendMessage on Vista or later, but that doesn't
3045 if (num_messages != 0)
3047 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
3048 _("GSocketControlMessage not supported on windows"));
3053 bufs = g_newa (WSABUF, num_vectors);
3054 for (i = 0; i < num_vectors; i++)
3056 bufs[i].buf = (char *)vectors[i].buffer;
3057 bufs[i].len = (gulong)vectors[i].size;
3061 addrlen = 0; /* Avoid warning */
3064 addrlen = g_socket_address_get_native_size (address);
3065 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
3071 if (socket->priv->blocking &&
3072 !g_socket_condition_wait (socket,
3073 G_IO_OUT, cancellable, error))
3077 result = WSASendTo (socket->priv->fd,
3080 (const struct sockaddr *)&addr, addrlen,
3083 result = WSASend (socket->priv->fd,
3090 int errsv = get_socket_errno ();
3092 if (errsv == WSAEINTR)
3095 if (errsv == WSAEWOULDBLOCK)
3096 win32_unset_event_mask (socket, FD_WRITE);
3098 if (socket->priv->blocking &&
3099 errsv == WSAEWOULDBLOCK)
3102 g_set_error (error, G_IO_ERROR,
3103 socket_io_error_from_errno (errsv),
3104 _("Error sending message: %s"), socket_strerror (errsv));
3117 * g_socket_receive_message:
3118 * @socket: a #GSocket
3119 * @address: a pointer to a #GSocketAddress pointer, or %NULL
3120 * @vectors: an array of #GInputVector structs
3121 * @num_vectors: the number of elements in @vectors, or -1
3122 * @messages: a pointer which may be filled with an array of
3123 * #GSocketControlMessages, or %NULL
3124 * @num_messages: a pointer which will be filled with the number of
3125 * elements in @messages, or %NULL
3126 * @flags: a pointer to an int containing #GSocketMsgFlags flags
3127 * @cancellable: a %GCancellable or %NULL
3128 * @error: a #GError pointer, or %NULL
3130 * Receive data from a socket. This is the most complicated and
3131 * fully-featured version of this call. For easier use, see
3132 * g_socket_receive() and g_socket_receive_from().
3134 * If @address is non-%NULL then @address will be set equal to the
3135 * source address of the received packet.
3136 * @address is owned by the caller.
3138 * @vector must point to an array of #GInputVector structs and
3139 * @num_vectors must be the length of this array. These structs
3140 * describe the buffers that received data will be scattered into.
3141 * If @num_vectors is -1, then @vectors is assumed to be terminated
3142 * by a #GInputVector with a %NULL buffer pointer.
3144 * As a special case, if @num_vectors is 0 (in which case, @vectors
3145 * may of course be %NULL), then a single byte is received and
3146 * discarded. This is to facilitate the common practice of sending a
3147 * single '\0' byte for the purposes of transferring ancillary data.
3149 * @messages, if non-%NULL, will be set to point to a newly-allocated
3150 * array of #GSocketControlMessage instances or %NULL if no such
3151 * messages was received. These correspond to the control messages
3152 * received from the kernel, one #GSocketControlMessage per message
3153 * from the kernel. This array is %NULL-terminated and must be freed
3154 * by the caller using g_free() after calling g_object_unref() on each
3155 * element. If @messages is %NULL, any control messages received will
3158 * @num_messages, if non-%NULL, will be set to the number of control
3159 * messages received.
3161 * If both @messages and @num_messages are non-%NULL, then
3162 * @num_messages gives the number of #GSocketControlMessage instances
3163 * in @messages (ie: not including the %NULL terminator).
3165 * @flags is an in/out parameter. The commonly available arguments
3166 * for this are available in the #GSocketMsgFlags enum, but the
3167 * values there are the same as the system values, and the flags
3168 * are passed in as-is, so you can pass in system-specific flags too
3169 * (and g_socket_receive_message() may pass system-specific flags out).
3171 * As with g_socket_receive(), data may be discarded if @socket is
3172 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
3173 * provide enough buffer space to read a complete message. You can pass
3174 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
3175 * removing it from the receive queue, but there is no portable way to find
3176 * out the length of the message other than by reading it into a
3177 * sufficiently-large buffer.
3179 * If the socket is in blocking mode the call will block until there
3180 * is some data to receive or there is an error. If there is no data
3181 * available and the socket is in non-blocking mode, a
3182 * %G_IO_ERROR_WOULD_BLOCK error will be returned. To be notified when
3183 * data is available, wait for the %G_IO_IN condition.
3185 * On error -1 is returned and @error is set accordingly.
3187 * Returns: Number of bytes read, or -1 on error
3192 g_socket_receive_message (GSocket *socket,
3193 GSocketAddress **address,
3194 GInputVector *vectors,
3196 GSocketControlMessage ***messages,
3199 GCancellable *cancellable,
3202 GInputVector one_vector;
3205 if (!check_socket (socket, error))
3208 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3211 if (num_vectors == -1)
3213 for (num_vectors = 0;
3214 vectors[num_vectors].buffer != NULL;
3219 if (num_vectors == 0)
3221 one_vector.buffer = &one_byte;
3222 one_vector.size = 1;
3224 vectors = &one_vector;
3231 struct sockaddr_storage one_sockaddr;
3236 msg.msg_name = &one_sockaddr;
3237 msg.msg_namelen = sizeof (struct sockaddr_storage);
3241 msg.msg_name = NULL;
3242 msg.msg_namelen = 0;
3246 /* this entire expression will be evaluated at compile time */
3247 if (sizeof *msg.msg_iov == sizeof *vectors &&
3248 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3249 G_STRUCT_OFFSET (struct iovec, iov_base) ==
3250 G_STRUCT_OFFSET (GInputVector, buffer) &&
3251 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3252 G_STRUCT_OFFSET (struct iovec, iov_len) ==
3253 G_STRUCT_OFFSET (GInputVector, size))
3254 /* ABI is compatible */
3256 msg.msg_iov = (struct iovec *) vectors;
3257 msg.msg_iovlen = num_vectors;
3260 /* ABI is incompatible */
3264 msg.msg_iov = g_newa (struct iovec, num_vectors);
3265 for (i = 0; i < num_vectors; i++)
3267 msg.msg_iov[i].iov_base = vectors[i].buffer;
3268 msg.msg_iov[i].iov_len = vectors[i].size;
3270 msg.msg_iovlen = num_vectors;
3274 msg.msg_control = g_alloca (2048);
3275 msg.msg_controllen = 2048;
3279 msg.msg_flags = *flags;
3286 if (socket->priv->blocking &&
3287 !g_socket_condition_wait (socket,
3288 G_IO_IN, cancellable, error))
3291 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
3295 int errsv = get_socket_errno ();
3300 if (socket->priv->blocking &&
3301 (errsv == EWOULDBLOCK ||
3305 g_set_error (error, G_IO_ERROR,
3306 socket_io_error_from_errno (errsv),
3307 _("Error receiving message: %s"), socket_strerror (errsv));
3314 /* decode address */
3315 if (address != NULL)
3317 if (msg.msg_namelen > 0)
3318 *address = g_socket_address_new_from_native (msg.msg_name,
3324 /* decode control messages */
3326 GPtrArray *my_messages = NULL;
3327 const gchar *scm_pointer;
3328 struct cmsghdr *cmsg;
3331 scm_pointer = (const gchar *) msg.msg_control;
3332 scm_size = msg.msg_controllen;
3334 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
3336 GSocketControlMessage *message;
3338 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
3340 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
3342 if (message == NULL)
3343 /* We've already spewed about the problem in the
3344 deserialization code, so just continue */
3347 if (messages == NULL)
3349 /* we have to do it this way if the user ignores the
3350 * messages so that we will close any received fds.
3352 g_object_unref (message);
3356 if (my_messages == NULL)
3357 my_messages = g_ptr_array_new ();
3358 g_ptr_array_add (my_messages, message);
3363 *num_messages = my_messages != NULL ? my_messages->len : 0;
3367 if (my_messages == NULL)
3373 g_ptr_array_add (my_messages, NULL);
3374 *messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
3379 g_assert (my_messages == NULL);
3383 /* capture the flags */
3385 *flags = msg.msg_flags;
3391 struct sockaddr_storage addr;
3393 DWORD bytes_received;
3400 bufs = g_newa (WSABUF, num_vectors);
3401 for (i = 0; i < num_vectors; i++)
3403 bufs[i].buf = (char *)vectors[i].buffer;
3404 bufs[i].len = (gulong)vectors[i].size;
3416 if (socket->priv->blocking &&
3417 !g_socket_condition_wait (socket,
3418 G_IO_IN, cancellable, error))
3421 addrlen = sizeof addr;
3423 result = WSARecvFrom (socket->priv->fd,
3425 &bytes_received, &win_flags,
3426 (struct sockaddr *)&addr, &addrlen,
3429 result = WSARecv (socket->priv->fd,
3431 &bytes_received, &win_flags,
3435 int errsv = get_socket_errno ();
3437 if (errsv == WSAEINTR)
3440 win32_unset_event_mask (socket, FD_READ);
3442 if (socket->priv->blocking &&
3443 errsv == WSAEWOULDBLOCK)
3446 g_set_error (error, G_IO_ERROR,
3447 socket_io_error_from_errno (errsv),
3448 _("Error receiving message: %s"), socket_strerror (errsv));
3452 win32_unset_event_mask (socket, FD_READ);
3456 /* decode address */
3457 if (address != NULL)
3460 *address = g_socket_address_new_from_native (&addr, addrlen);
3465 /* capture the flags */
3469 if (messages != NULL)
3471 if (num_messages != NULL)
3474 return bytes_received;
3480 * g_socket_get_credentials:
3481 * @socket: a #GSocket.
3482 * @error: #GError for error reporting, or %NULL to ignore.
3484 * Returns the credentials of the foreign process connected to this
3485 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
3488 * If this operation isn't supported on the OS, the method fails with
3489 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
3490 * by reading the %SO_PEERCRED option on the underlying socket.
3492 * Other ways to obtain credentials from a foreign peer includes the
3493 * #GUnixCredentialsMessage type and
3494 * g_unix_connection_send_credentials() /
3495 * g_unix_connection_receive_credentials() functions.
3497 * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
3498 * that must be freed with g_object_unref().
3503 g_socket_get_credentials (GSocket *socket,
3508 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
3509 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3515 struct ucred native_creds;
3517 optlen = sizeof (struct ucred);
3518 if (getsockopt (socket->priv->fd,
3521 (void *)&native_creds,
3524 int errsv = get_socket_errno ();
3527 socket_io_error_from_errno (errsv),
3528 _("Unable to get pending error: %s"),
3529 socket_strerror (errsv));
3533 ret = g_credentials_new ();
3534 g_credentials_set_native (ret,
3535 G_CREDENTIALS_TYPE_LINUX_UCRED,
3540 g_set_error_literal (error,
3542 G_IO_ERROR_NOT_SUPPORTED,
3543 _("g_socket_get_credentials not implemented for this OS"));