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: (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 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: (allow-none): 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: (allow-none): 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: (array length=size): the buffer containing the data to send.
1917 * @size: the number of bytes to send
1918 * @cancellable: (allow-none): 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: (array length=size): 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: (allow-none): 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: (array length=size): the buffer containing the data to send.
2036 * @size: the number of bytes to send
2037 * @cancellable: (allow-none): 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;
2472 socket_source->pollfd.revents = update_condition (socket_source->socket);
2475 return (*func) (socket_source->socket,
2476 socket_source->pollfd.revents & socket_source->condition,
2481 socket_source_finalize (GSource *source)
2483 GSocketSource *socket_source = (GSocketSource *)source;
2486 socket = socket_source->socket;
2489 remove_condition_watch (socket, &socket_source->condition);
2492 g_object_unref (socket);
2494 if (socket_source->cancellable)
2496 g_cancellable_release_fd (socket_source->cancellable);
2497 g_object_unref (socket_source->cancellable);
2502 socket_source_closure_callback (GSocket *socket,
2503 GIOCondition condition,
2506 GClosure *closure = data;
2508 GValue params[2] = { { 0, }, { 0, } };
2509 GValue result_value = { 0, };
2512 g_value_init (&result_value, G_TYPE_BOOLEAN);
2514 g_value_init (¶ms[0], G_TYPE_SOCKET);
2515 g_value_set_object (¶ms[0], socket);
2516 g_value_init (¶ms[1], G_TYPE_IO_CONDITION);
2517 g_value_set_flags (¶ms[1], condition);
2519 g_closure_invoke (closure, &result_value, 2, params, NULL);
2521 result = g_value_get_boolean (&result_value);
2522 g_value_unset (&result_value);
2523 g_value_unset (¶ms[0]);
2524 g_value_unset (¶ms[1]);
2529 static GSourceFuncs socket_source_funcs =
2531 socket_source_prepare,
2532 socket_source_check,
2533 socket_source_dispatch,
2534 socket_source_finalize,
2535 (GSourceFunc)socket_source_closure_callback,
2536 (GSourceDummyMarshal)_gio_marshal_BOOLEAN__FLAGS,
2540 socket_source_new (GSocket *socket,
2541 GIOCondition condition,
2542 GCancellable *cancellable)
2545 GSocketSource *socket_source;
2548 ensure_event (socket);
2550 if (socket->priv->event == WSA_INVALID_EVENT)
2552 g_warning ("Failed to create WSAEvent");
2553 return g_source_new (&broken_funcs, sizeof (GSource));
2557 condition |= G_IO_HUP | G_IO_ERR;
2559 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
2560 g_source_set_name (source, "GSocket");
2561 socket_source = (GSocketSource *)source;
2563 socket_source->socket = g_object_ref (socket);
2564 socket_source->condition = condition;
2566 if (g_cancellable_make_pollfd (cancellable,
2567 &socket_source->cancel_pollfd))
2569 socket_source->cancellable = g_object_ref (cancellable);
2570 g_source_add_poll (source, &socket_source->cancel_pollfd);
2574 add_condition_watch (socket, &socket_source->condition);
2575 socket_source->pollfd.fd = (gintptr) socket->priv->event;
2577 socket_source->pollfd.fd = socket->priv->fd;
2580 socket_source->pollfd.events = condition;
2581 socket_source->pollfd.revents = 0;
2582 g_source_add_poll (source, &socket_source->pollfd);
2584 if (socket->priv->timeout)
2585 socket_source->timeout_time = g_get_monotonic_time () +
2586 socket->priv->timeout * 1000000;
2589 socket_source->timeout_time = 0;
2595 * g_socket_create_source: (skip)
2596 * @socket: a #GSocket
2597 * @condition: a #GIOCondition mask to monitor
2598 * @cancellable: (allow-none): a %GCancellable or %NULL
2600 * Creates a %GSource that can be attached to a %GMainContext to monitor
2601 * for the availibility of the specified @condition on the socket.
2603 * The callback on the source is of the #GSocketSourceFunc type.
2605 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
2606 * these conditions will always be reported output if they are true.
2608 * @cancellable if not %NULL can be used to cancel the source, which will
2609 * cause the source to trigger, reporting the current condition (which
2610 * is likely 0 unless cancellation happened at the same time as a
2611 * condition change). You can check for this in the callback using
2612 * g_cancellable_is_cancelled().
2614 * If @socket has a timeout set, and it is reached before @condition
2615 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
2616 * %G_IO_OUT depending on @condition. However, @socket will have been
2617 * marked as having had a timeout, and so the next #GSocket I/O method
2618 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
2620 * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
2625 g_socket_create_source (GSocket *socket,
2626 GIOCondition condition,
2627 GCancellable *cancellable)
2629 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
2631 return socket_source_new (socket, condition, cancellable);
2635 * g_socket_condition_check:
2636 * @socket: a #GSocket
2637 * @condition: a #GIOCondition mask to check
2639 * Checks on the readiness of @socket to perform operations.
2640 * The operations specified in @condition are checked for and masked
2641 * against the currently-satisfied conditions on @socket. The result
2644 * Note that on Windows, it is possible for an operation to return
2645 * %G_IO_ERROR_WOULD_BLOCK even immediately after
2646 * g_socket_condition_check() has claimed that the socket is ready for
2647 * writing. Rather than calling g_socket_condition_check() and then
2648 * writing to the socket if it succeeds, it is generally better to
2649 * simply try writing to the socket right away, and try again later if
2650 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
2652 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2653 * these conditions will always be set in the output if they are true.
2655 * This call never blocks.
2657 * Returns: the @GIOCondition mask of the current state
2662 g_socket_condition_check (GSocket *socket,
2663 GIOCondition condition)
2665 if (!check_socket (socket, NULL))
2670 GIOCondition current_condition;
2672 condition |= G_IO_ERR | G_IO_HUP;
2674 add_condition_watch (socket, &condition);
2675 current_condition = update_condition (socket);
2676 remove_condition_watch (socket, &condition);
2677 return condition & current_condition;
2683 poll_fd.fd = socket->priv->fd;
2684 poll_fd.events = condition;
2687 result = g_poll (&poll_fd, 1, 0);
2688 while (result == -1 && get_socket_errno () == EINTR);
2690 return poll_fd.revents;
2696 * g_socket_condition_wait:
2697 * @socket: a #GSocket
2698 * @condition: a #GIOCondition mask to wait for
2699 * @cancellable: (allow-none): a #GCancellable, or %NULL
2700 * @error: a #GError pointer, or %NULL
2702 * Waits for @condition to become true on @socket. When the condition
2703 * is met, %TRUE is returned.
2705 * If @cancellable is cancelled before the condition is met, or if the
2706 * socket has a timeout set and it is reached before the condition is
2707 * met, then %FALSE is returned and @error, if non-%NULL, is set to
2708 * the appropriate value (%G_IO_ERROR_CANCELLED or
2709 * %G_IO_ERROR_TIMED_OUT).
2711 * Returns: %TRUE if the condition was met, %FALSE otherwise
2716 g_socket_condition_wait (GSocket *socket,
2717 GIOCondition condition,
2718 GCancellable *cancellable,
2721 if (!check_socket (socket, error))
2724 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2729 GIOCondition current_condition;
2735 /* Always check these */
2736 condition |= G_IO_ERR | G_IO_HUP;
2738 add_condition_watch (socket, &condition);
2741 events[num_events++] = socket->priv->event;
2743 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
2744 events[num_events++] = (WSAEVENT)cancel_fd.fd;
2746 if (socket->priv->timeout)
2747 timeout = socket->priv->timeout * 1000;
2749 timeout = WSA_INFINITE;
2751 current_condition = update_condition (socket);
2752 while ((condition & current_condition) == 0)
2754 res = WSAWaitForMultipleEvents(num_events, events,
2755 FALSE, timeout, FALSE);
2756 if (res == WSA_WAIT_FAILED)
2758 int errsv = get_socket_errno ();
2760 g_set_error (error, G_IO_ERROR,
2761 socket_io_error_from_errno (errsv),
2762 _("Waiting for socket condition: %s"),
2763 socket_strerror (errsv));
2766 else if (res == WSA_WAIT_TIMEOUT)
2768 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
2769 _("Socket I/O timed out"));
2773 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2776 current_condition = update_condition (socket);
2778 remove_condition_watch (socket, &condition);
2780 g_cancellable_release_fd (cancellable);
2782 return (condition & current_condition) != 0;
2791 poll_fd[0].fd = socket->priv->fd;
2792 poll_fd[0].events = condition;
2795 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
2798 if (socket->priv->timeout)
2799 timeout = socket->priv->timeout * 1000;
2804 result = g_poll (poll_fd, num, timeout);
2805 while (result == -1 && get_socket_errno () == EINTR);
2808 g_cancellable_release_fd (cancellable);
2812 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
2813 _("Socket I/O timed out"));
2817 return !g_cancellable_set_error_if_cancelled (cancellable, error);
2823 * g_socket_send_message:
2824 * @socket: a #GSocket
2825 * @address: a #GSocketAddress, or %NULL
2826 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
2827 * @num_vectors: the number of elements in @vectors, or -1
2828 * @messages: (array length=num_messages) (allow-none): a pointer to an
2829 * array of #GSocketControlMessages, or %NULL.
2830 * @num_messages: number of elements in @messages, or -1.
2831 * @flags: an int containing #GSocketMsgFlags flags
2832 * @cancellable: (allow-none): a %GCancellable or %NULL
2833 * @error: #GError for error reporting, or %NULL to ignore.
2835 * Send data to @address on @socket. This is the most complicated and
2836 * fully-featured version of this call. For easier use, see
2837 * g_socket_send() and g_socket_send_to().
2839 * If @address is %NULL then the message is sent to the default receiver
2840 * (set by g_socket_connect()).
2842 * @vectors must point to an array of #GOutputVector structs and
2843 * @num_vectors must be the length of this array. (If @num_vectors is -1,
2844 * then @vectors is assumed to be terminated by a #GOutputVector with a
2845 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
2846 * that the sent data will be gathered from. Using multiple
2847 * #GOutputVector<!-- -->s is more memory-efficient than manually copying
2848 * data from multiple sources into a single buffer, and more
2849 * network-efficient than making multiple calls to g_socket_send().
2851 * @messages, if non-%NULL, is taken to point to an array of @num_messages
2852 * #GSocketControlMessage instances. These correspond to the control
2853 * messages to be sent on the socket.
2854 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
2857 * @flags modify how the message is sent. The commonly available arguments
2858 * for this are available in the #GSocketMsgFlags enum, but the
2859 * values there are the same as the system values, and the flags
2860 * are passed in as-is, so you can pass in system-specific flags too.
2862 * If the socket is in blocking mode the call will block until there is
2863 * space for the data in the socket queue. If there is no space available
2864 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2865 * will be returned. To be notified when space is available, wait for the
2866 * %G_IO_OUT condition. Note though that you may still receive
2867 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2868 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2869 * very common due to the way the underlying APIs work.)
2871 * On error -1 is returned and @error is set accordingly.
2873 * Returns: Number of bytes written (which may be less than @size), or -1
2879 g_socket_send_message (GSocket *socket,
2880 GSocketAddress *address,
2881 GOutputVector *vectors,
2883 GSocketControlMessage **messages,
2886 GCancellable *cancellable,
2889 GOutputVector one_vector;
2892 if (!check_socket (socket, error))
2895 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2898 if (num_vectors == -1)
2900 for (num_vectors = 0;
2901 vectors[num_vectors].buffer != NULL;
2906 if (num_messages == -1)
2908 for (num_messages = 0;
2909 messages != NULL && messages[num_messages] != NULL;
2914 if (num_vectors == 0)
2918 one_vector.buffer = &zero;
2919 one_vector.size = 1;
2921 vectors = &one_vector;
2934 msg.msg_namelen = g_socket_address_get_native_size (address);
2935 msg.msg_name = g_alloca (msg.msg_namelen);
2936 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
2941 msg.msg_name = NULL;
2942 msg.msg_namelen = 0;
2947 /* this entire expression will be evaluated at compile time */
2948 if (sizeof *msg.msg_iov == sizeof *vectors &&
2949 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2950 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2951 G_STRUCT_OFFSET (GOutputVector, buffer) &&
2952 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2953 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2954 G_STRUCT_OFFSET (GOutputVector, size))
2955 /* ABI is compatible */
2957 msg.msg_iov = (struct iovec *) vectors;
2958 msg.msg_iovlen = num_vectors;
2961 /* ABI is incompatible */
2965 msg.msg_iov = g_newa (struct iovec, num_vectors);
2966 for (i = 0; i < num_vectors; i++)
2968 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
2969 msg.msg_iov[i].iov_len = vectors[i].size;
2971 msg.msg_iovlen = num_vectors;
2977 struct cmsghdr *cmsg;
2980 msg.msg_controllen = 0;
2981 for (i = 0; i < num_messages; i++)
2982 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
2984 if (msg.msg_controllen == 0)
2985 msg.msg_control = NULL;
2988 msg.msg_control = g_alloca (msg.msg_controllen);
2989 memset (msg.msg_control, '\0', msg.msg_controllen);
2992 cmsg = CMSG_FIRSTHDR (&msg);
2993 for (i = 0; i < num_messages; i++)
2995 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
2996 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
2997 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
2998 g_socket_control_message_serialize (messages[i],
3000 cmsg = CMSG_NXTHDR (&msg, cmsg);
3002 g_assert (cmsg == NULL);
3007 if (socket->priv->blocking &&
3008 !g_socket_condition_wait (socket,
3009 G_IO_OUT, cancellable, error))
3012 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
3015 int errsv = get_socket_errno ();
3020 if (socket->priv->blocking &&
3021 (errsv == EWOULDBLOCK ||
3025 g_set_error (error, G_IO_ERROR,
3026 socket_io_error_from_errno (errsv),
3027 _("Error sending message: %s"), socket_strerror (errsv));
3038 struct sockaddr_storage addr;
3045 /* Win32 doesn't support control messages.
3046 Actually this is possible for raw and datagram sockets
3047 via WSASendMessage on Vista or later, but that doesn't
3049 if (num_messages != 0)
3051 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
3052 _("GSocketControlMessage not supported on windows"));
3057 bufs = g_newa (WSABUF, num_vectors);
3058 for (i = 0; i < num_vectors; i++)
3060 bufs[i].buf = (char *)vectors[i].buffer;
3061 bufs[i].len = (gulong)vectors[i].size;
3065 addrlen = 0; /* Avoid warning */
3068 addrlen = g_socket_address_get_native_size (address);
3069 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
3075 if (socket->priv->blocking &&
3076 !g_socket_condition_wait (socket,
3077 G_IO_OUT, cancellable, error))
3081 result = WSASendTo (socket->priv->fd,
3084 (const struct sockaddr *)&addr, addrlen,
3087 result = WSASend (socket->priv->fd,
3094 int errsv = get_socket_errno ();
3096 if (errsv == WSAEINTR)
3099 if (errsv == WSAEWOULDBLOCK)
3100 win32_unset_event_mask (socket, FD_WRITE);
3102 if (socket->priv->blocking &&
3103 errsv == WSAEWOULDBLOCK)
3106 g_set_error (error, G_IO_ERROR,
3107 socket_io_error_from_errno (errsv),
3108 _("Error sending message: %s"), socket_strerror (errsv));
3121 * g_socket_receive_message:
3122 * @socket: a #GSocket
3123 * @address: a pointer to a #GSocketAddress pointer, or %NULL
3124 * @vectors: (array length=num_vectors): an array of #GInputVector structs
3125 * @num_vectors: the number of elements in @vectors, or -1
3126 * @messages: (array length=num_messages) (allow-none): a pointer which
3127 * may be filled with an array of #GSocketControlMessages, or %NULL
3128 * @num_messages: a pointer which will be filled with the number of
3129 * elements in @messages, or %NULL
3130 * @flags: a pointer to an int containing #GSocketMsgFlags flags
3131 * @cancellable: (allow-none): a %GCancellable or %NULL
3132 * @error: a #GError pointer, or %NULL
3134 * Receive data from a socket. This is the most complicated and
3135 * fully-featured version of this call. For easier use, see
3136 * g_socket_receive() and g_socket_receive_from().
3138 * If @address is non-%NULL then @address will be set equal to the
3139 * source address of the received packet.
3140 * @address is owned by the caller.
3142 * @vector must point to an array of #GInputVector structs and
3143 * @num_vectors must be the length of this array. These structs
3144 * describe the buffers that received data will be scattered into.
3145 * If @num_vectors is -1, then @vectors is assumed to be terminated
3146 * by a #GInputVector with a %NULL buffer pointer.
3148 * As a special case, if @num_vectors is 0 (in which case, @vectors
3149 * may of course be %NULL), then a single byte is received and
3150 * discarded. This is to facilitate the common practice of sending a
3151 * single '\0' byte for the purposes of transferring ancillary data.
3153 * @messages, if non-%NULL, will be set to point to a newly-allocated
3154 * array of #GSocketControlMessage instances or %NULL if no such
3155 * messages was received. These correspond to the control messages
3156 * received from the kernel, one #GSocketControlMessage per message
3157 * from the kernel. This array is %NULL-terminated and must be freed
3158 * by the caller using g_free() after calling g_object_unref() on each
3159 * element. If @messages is %NULL, any control messages received will
3162 * @num_messages, if non-%NULL, will be set to the number of control
3163 * messages received.
3165 * If both @messages and @num_messages are non-%NULL, then
3166 * @num_messages gives the number of #GSocketControlMessage instances
3167 * in @messages (ie: not including the %NULL terminator).
3169 * @flags is an in/out parameter. The commonly available arguments
3170 * for this are available in the #GSocketMsgFlags enum, but the
3171 * values there are the same as the system values, and the flags
3172 * are passed in as-is, so you can pass in system-specific flags too
3173 * (and g_socket_receive_message() may pass system-specific flags out).
3175 * As with g_socket_receive(), data may be discarded if @socket is
3176 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
3177 * provide enough buffer space to read a complete message. You can pass
3178 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
3179 * removing it from the receive queue, but there is no portable way to find
3180 * out the length of the message other than by reading it into a
3181 * sufficiently-large buffer.
3183 * If the socket is in blocking mode the call will block until there
3184 * is some data to receive or there is an error. If there is no data
3185 * available and the socket is in non-blocking mode, a
3186 * %G_IO_ERROR_WOULD_BLOCK error will be returned. To be notified when
3187 * data is available, wait for the %G_IO_IN condition.
3189 * On error -1 is returned and @error is set accordingly.
3191 * Returns: Number of bytes read, or -1 on error
3196 g_socket_receive_message (GSocket *socket,
3197 GSocketAddress **address,
3198 GInputVector *vectors,
3200 GSocketControlMessage ***messages,
3203 GCancellable *cancellable,
3206 GInputVector one_vector;
3209 if (!check_socket (socket, error))
3212 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3215 if (num_vectors == -1)
3217 for (num_vectors = 0;
3218 vectors[num_vectors].buffer != NULL;
3223 if (num_vectors == 0)
3225 one_vector.buffer = &one_byte;
3226 one_vector.size = 1;
3228 vectors = &one_vector;
3235 struct sockaddr_storage one_sockaddr;
3240 msg.msg_name = &one_sockaddr;
3241 msg.msg_namelen = sizeof (struct sockaddr_storage);
3245 msg.msg_name = NULL;
3246 msg.msg_namelen = 0;
3250 /* this entire expression will be evaluated at compile time */
3251 if (sizeof *msg.msg_iov == sizeof *vectors &&
3252 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3253 G_STRUCT_OFFSET (struct iovec, iov_base) ==
3254 G_STRUCT_OFFSET (GInputVector, buffer) &&
3255 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3256 G_STRUCT_OFFSET (struct iovec, iov_len) ==
3257 G_STRUCT_OFFSET (GInputVector, size))
3258 /* ABI is compatible */
3260 msg.msg_iov = (struct iovec *) vectors;
3261 msg.msg_iovlen = num_vectors;
3264 /* ABI is incompatible */
3268 msg.msg_iov = g_newa (struct iovec, num_vectors);
3269 for (i = 0; i < num_vectors; i++)
3271 msg.msg_iov[i].iov_base = vectors[i].buffer;
3272 msg.msg_iov[i].iov_len = vectors[i].size;
3274 msg.msg_iovlen = num_vectors;
3278 msg.msg_control = g_alloca (2048);
3279 msg.msg_controllen = 2048;
3283 msg.msg_flags = *flags;
3290 if (socket->priv->blocking &&
3291 !g_socket_condition_wait (socket,
3292 G_IO_IN, cancellable, error))
3295 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
3299 int errsv = get_socket_errno ();
3304 if (socket->priv->blocking &&
3305 (errsv == EWOULDBLOCK ||
3309 g_set_error (error, G_IO_ERROR,
3310 socket_io_error_from_errno (errsv),
3311 _("Error receiving message: %s"), socket_strerror (errsv));
3318 /* decode address */
3319 if (address != NULL)
3321 if (msg.msg_namelen > 0)
3322 *address = g_socket_address_new_from_native (msg.msg_name,
3328 /* decode control messages */
3330 GPtrArray *my_messages = NULL;
3331 const gchar *scm_pointer;
3332 struct cmsghdr *cmsg;
3335 scm_pointer = (const gchar *) msg.msg_control;
3336 scm_size = msg.msg_controllen;
3338 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
3340 GSocketControlMessage *message;
3342 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
3344 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
3346 if (message == NULL)
3347 /* We've already spewed about the problem in the
3348 deserialization code, so just continue */
3351 if (messages == NULL)
3353 /* we have to do it this way if the user ignores the
3354 * messages so that we will close any received fds.
3356 g_object_unref (message);
3360 if (my_messages == NULL)
3361 my_messages = g_ptr_array_new ();
3362 g_ptr_array_add (my_messages, message);
3367 *num_messages = my_messages != NULL ? my_messages->len : 0;
3371 if (my_messages == NULL)
3377 g_ptr_array_add (my_messages, NULL);
3378 *messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
3383 g_assert (my_messages == NULL);
3387 /* capture the flags */
3389 *flags = msg.msg_flags;
3395 struct sockaddr_storage addr;
3397 DWORD bytes_received;
3404 bufs = g_newa (WSABUF, num_vectors);
3405 for (i = 0; i < num_vectors; i++)
3407 bufs[i].buf = (char *)vectors[i].buffer;
3408 bufs[i].len = (gulong)vectors[i].size;
3420 if (socket->priv->blocking &&
3421 !g_socket_condition_wait (socket,
3422 G_IO_IN, cancellable, error))
3425 addrlen = sizeof addr;
3427 result = WSARecvFrom (socket->priv->fd,
3429 &bytes_received, &win_flags,
3430 (struct sockaddr *)&addr, &addrlen,
3433 result = WSARecv (socket->priv->fd,
3435 &bytes_received, &win_flags,
3439 int errsv = get_socket_errno ();
3441 if (errsv == WSAEINTR)
3444 win32_unset_event_mask (socket, FD_READ);
3446 if (socket->priv->blocking &&
3447 errsv == WSAEWOULDBLOCK)
3450 g_set_error (error, G_IO_ERROR,
3451 socket_io_error_from_errno (errsv),
3452 _("Error receiving message: %s"), socket_strerror (errsv));
3456 win32_unset_event_mask (socket, FD_READ);
3460 /* decode address */
3461 if (address != NULL)
3464 *address = g_socket_address_new_from_native (&addr, addrlen);
3469 /* capture the flags */
3473 if (messages != NULL)
3475 if (num_messages != NULL)
3478 return bytes_received;
3484 * g_socket_get_credentials:
3485 * @socket: a #GSocket.
3486 * @error: #GError for error reporting, or %NULL to ignore.
3488 * Returns the credentials of the foreign process connected to this
3489 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
3492 * If this operation isn't supported on the OS, the method fails with
3493 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
3494 * by reading the %SO_PEERCRED option on the underlying socket.
3496 * Other ways to obtain credentials from a foreign peer includes the
3497 * #GUnixCredentialsMessage type and
3498 * g_unix_connection_send_credentials() /
3499 * g_unix_connection_receive_credentials() functions.
3501 * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
3502 * that must be freed with g_object_unref().
3507 g_socket_get_credentials (GSocket *socket,
3512 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
3513 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3519 struct ucred native_creds;
3521 optlen = sizeof (struct ucred);
3522 if (getsockopt (socket->priv->fd,
3525 (void *)&native_creds,
3528 int errsv = get_socket_errno ();
3531 socket_io_error_from_errno (errsv),
3532 _("Unable to get pending error: %s"),
3533 socket_strerror (errsv));
3537 ret = g_credentials_new ();
3538 g_credentials_set_native (ret,
3539 G_CREDENTIALS_TYPE_LINUX_UCRED,
3544 g_set_error_literal (error,
3546 G_IO_ERROR_NOT_SUPPORTED,
3547 _("g_socket_get_credentials not implemented for this OS"));