1 /* GIO - GLib Input, Output and Streaming Library
3 * Copyright (C) 2008 Christian Kellner, Samuel Cormier-Iijima
4 * Copyright © 2009 Codethink Limited
5 * Copyright © 2009 Red Hat, Inc
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General
18 * Public License along with this library; if not, write to the
19 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
20 * Boston, MA 02111-1307, USA.
22 * Authors: Christian Kellner <gicmo@gnome.org>
23 * Samuel Cormier-Iijima <sciyoshi@gmail.com>
24 * Ryan Lortie <desrt@desrt.ca>
25 * Alexander Larsson <alexl@redhat.com>
33 # include <netinet/in.h>
34 # include <arpa/inet.h>
38 # include <sys/types.h>
40 # include <winsock2.h>
45 #include "gcancellable.h"
46 #include "gioenumtypes.h"
47 #include "ginitable.h"
48 #include "gasynchelper.h"
58 * @short_description: Low-level network socket handling
60 * @see_also: #GInitable
62 * A #GSocket is a low-level networking primitive. It is a more or less
63 * direct mapping of the BSD socket API in a portable GObject based API.
64 * It supports both the unix socket implementations and winsock2 on Windows.
66 * #GSocket is the platform independent base upon which the higher level
67 * network primitives are based. Applications are not typically meant to
68 * use it directly, but rather through classes like #GSocketClient, etc.
69 * However there may be cases where direct use of #GSocket is useful.
71 * TODO: Add more references to the highlevel API once that is more
74 * #GSocket implements the #GInitable interface, so if it is manually constructed
75 * by e.g. g_object_new() you must call g_initable_init() and check the
76 * results before using the object. This is done automatically in
77 * g_socket_new() and g_socket_new_from_fd(), so these functions can return
80 * Sockets operate in two general modes, blocking or non-blocking. When
81 * in blocking mode all operations block until the requested operation
82 * is finished or there is an error. In non-blocking mode all calls that
83 * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
84 * To know when a call would successfully run you can call g_socket_condition_check(),
85 * or g_socket_condition_wait(). You can also use g_socket_create_source() and
86 * attach it to a #GMainContext to get callbacks when I/O is possible.
87 * Note that all sockets are always set to non blocking mode in the system, and
88 * blocking mode is emulated in GSocket.
90 * When working in non-blocking mode applications should always be able to
91 * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
92 * function said that I/O was possible. This can easily happen in case
93 * of a race condition in the application, but it can also happen for other
94 * reasons. For instance, on Windows a socket is always seen as writable
95 * until a write returns %G_IO_ERROR_WOULD_BLOCK.
97 * #GSocket<!-- -->s can be either connection oriented or datagram based.
98 * For connection oriented types you must first establish a connection by
99 * either connecting to an address or accepting a connection from another
100 * address. For connectionless socket types the target/source address is
101 * specified or received in each I/O operation.
103 * All socket file descriptors are set to be close-on-exec.
108 static void g_socket_initable_iface_init (GInitableIface *iface);
109 static gboolean g_socket_initable_init (GInitable *initable,
110 GCancellable *cancellable,
113 G_DEFINE_TYPE_WITH_CODE (GSocket, g_socket, G_TYPE_OBJECT,
114 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
115 g_socket_initable_iface_init));
131 struct _GSocketPrivate
133 GSocketFamily family;
138 GError *construct_error;
139 GSocketAddress *local_address;
140 GSocketAddress *remote_address;
150 GList *requested_conditions; /* list of requested GIOCondition * */
155 get_socket_errno (void)
160 return WSAGetLastError ();
165 socket_io_error_from_errno (int err)
168 return g_io_error_from_errno (err);
173 return G_IO_ERROR_ADDRESS_IN_USE;
175 return G_IO_ERROR_WOULD_BLOCK;
177 return G_IO_ERROR_PERMISSION_DENIED;
178 case WSA_INVALID_HANDLE:
179 case WSA_INVALID_PARAMETER:
182 return G_IO_ERROR_INVALID_ARGUMENT;
183 case WSAEPROTONOSUPPORT:
184 return G_IO_ERROR_NOT_SUPPORTED;
186 return G_IO_ERROR_CANCELLED;
187 case WSAESOCKTNOSUPPORT:
189 case WSAEPFNOSUPPORT:
190 case WSAEAFNOSUPPORT:
191 return G_IO_ERROR_NOT_SUPPORTED;
193 return G_IO_ERROR_FAILED;
199 socket_strerror (int err)
202 return g_strerror (err);
204 static GStaticPrivate msg_private = G_STATIC_PRIVATE_INIT;
207 buf = g_static_private_get (&msg_private);
210 buf = g_new (gchar, 128);
211 g_static_private_set (&msg_private, buf, g_free);
214 msg = g_win32_error_message (err);
215 strncpy (buf, msg, 128);
222 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
224 _win32_unset_event_mask (GSocket *socket, int mask)
226 socket->priv->current_events &= ~mask;
227 socket->priv->current_errors &= ~mask;
230 #define win32_unset_event_mask(_socket, _mask)
234 set_fd_nonblocking (int fd)
243 if ((arg = fcntl (fd, F_GETFL, NULL)) < 0)
245 g_warning ("Error getting socket status flags: %s", socket_strerror (errno));
249 arg = arg | O_NONBLOCK;
251 if (fcntl (fd, F_SETFL, arg) < 0)
252 g_warning ("Error setting socket status flags: %s", socket_strerror (errno));
256 if (ioctlsocket (fd, FIONBIO, &arg) == SOCKET_ERROR)
258 int errsv = get_socket_errno ();
259 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
265 check_socket (GSocket *socket,
268 if (!socket->priv->inited)
270 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
271 _("Invalid socket, not initialized"));
275 if (socket->priv->construct_error)
277 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
278 _("Invalid socket, initialization failed due to: %s"),
279 socket->priv->construct_error->message);
283 if (socket->priv->closed)
285 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
286 _("Socket is already closed"));
293 g_socket_details_from_fd (GSocket *socket)
295 struct sockaddr_storage address;
307 fd = socket->priv->fd;
308 optlen = sizeof value;
309 if (getsockopt (fd, SOL_SOCKET, SO_TYPE, (void *)&value, &optlen) != 0)
311 errsv = get_socket_errno ();
322 /* programmer error */
323 g_error ("creating GSocket from fd %d: %s\n",
324 fd, socket_strerror (errsv));
332 g_assert (optlen == sizeof value);
336 socket->priv->type = G_SOCKET_TYPE_STREAM;
340 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
344 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
348 socket->priv->type = G_SOCKET_TYPE_INVALID;
352 addrlen = sizeof address;
353 if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
355 errsv = get_socket_errno ();
359 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
360 sizeof address.ss_family <= addrlen);
361 switch (address.ss_family)
363 case G_SOCKET_FAMILY_IPV4:
364 case G_SOCKET_FAMILY_IPV6:
365 case G_SOCKET_FAMILY_UNIX:
366 socket->priv->family = address.ss_family;
370 socket->priv->family = G_SOCKET_FAMILY_INVALID;
374 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
376 socket->priv->local_address =
377 g_socket_address_new_from_native (&address, addrlen);
379 addrlen = sizeof address;
380 if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
381 socket->priv->remote_address =
382 g_socket_address_new_from_native (&address, addrlen);
385 optlen = sizeof bool_val;
386 if (getsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
387 (void *)&bool_val, &optlen) == 0)
389 g_assert (optlen == sizeof bool_val);
390 socket->priv->keepalive = !!bool_val;
394 /* Can't read, maybe not supported, assume FALSE */
395 socket->priv->keepalive = FALSE;
401 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
402 socket_io_error_from_errno (errsv),
403 _("creating GSocket from fd: %s"),
404 socket_strerror (errsv));
408 g_socket_create_socket (GSocketFamily family,
410 const char *protocol_name,
416 struct protoent *protoent;
420 case G_SOCKET_TYPE_STREAM:
421 native_type = SOCK_STREAM;
424 case G_SOCKET_TYPE_DATAGRAM:
425 native_type = SOCK_DGRAM;
428 case G_SOCKET_TYPE_SEQPACKET:
429 native_type = SOCK_SEQPACKET;
433 g_assert_not_reached ();
439 #ifdef HAVE_GETPROTOBYNAME_R
441 struct protoent my_protoent;
444 getprotobyname_r (protocol_name,
445 &my_protoent, buffer, sizeof (buffer),
448 protoent = getprotobyname (protocol_name);
450 if (protoent == NULL)
452 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
453 _("unable to create socket: Protocol %s not supported"),
457 protocol = protoent->p_proto;
461 native_type |= SOCK_CLOEXEC;
463 fd = socket (family, native_type, protocol);
467 int errsv = get_socket_errno ();
469 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
470 _("unable to create socket: %s"), socket_strerror (errsv));
477 /* We always want to set close-on-exec to protect users. If you
478 need to so some weird inheritance to exec you can re-enable this
479 using lower level hacks with g_socket_get_fd(). */
480 flags = fcntl (fd, F_GETFD, 0);
482 (flags & FD_CLOEXEC) == 0)
485 fcntl (fd, F_SETFD, flags);
494 g_socket_constructed (GObject *object)
496 GSocket *socket = G_SOCKET (object);
498 if (socket->priv->fd >= 0)
499 /* create socket->priv info from the fd */
500 g_socket_details_from_fd (socket);
503 /* create the fd from socket->priv info */
504 socket->priv->fd = g_socket_create_socket (socket->priv->family,
506 socket->priv->protocol,
507 &socket->priv->construct_error);
509 /* Always use native nonblocking sockets, as
510 windows sets sockets to nonblocking automatically
511 in certain operations. This way we make things work
512 the same on all platforms */
513 if (socket->priv->fd != -1)
514 set_fd_nonblocking (socket->priv->fd);
518 g_socket_get_property (GObject *object,
523 GSocket *socket = G_SOCKET (object);
528 g_value_set_enum (value, socket->priv->family);
532 g_value_set_enum (value, socket->priv->type);
536 g_value_set_string (value, socket->priv->protocol);
540 g_value_set_int (value, socket->priv->fd);
544 g_value_set_boolean (value, socket->priv->blocking);
547 case PROP_LISTEN_BACKLOG:
548 g_value_set_int (value, socket->priv->listen_backlog);
552 g_value_set_boolean (value, socket->priv->keepalive);
555 case PROP_LOCAL_ADDRESS:
556 g_value_set_object (value, socket->priv->local_address);
559 case PROP_REMOTE_ADDRESS:
560 g_value_set_object (value, socket->priv->remote_address);
564 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
569 g_socket_set_property (GObject *object,
574 GSocket *socket = G_SOCKET (object);
579 socket->priv->family = g_value_get_enum (value);
583 socket->priv->type = g_value_get_enum (value);
587 socket->priv->protocol = g_value_dup_string (value);
591 socket->priv->fd = g_value_get_int (value);
595 g_socket_set_blocking (socket, g_value_get_boolean (value));
598 case PROP_LISTEN_BACKLOG:
599 g_socket_set_listen_backlog (socket, g_value_get_int (value));
603 g_socket_set_keepalive (socket, g_value_get_boolean (value));
607 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
612 g_socket_finalize (GObject *object)
614 GSocket *socket = G_SOCKET (object);
616 g_clear_error (&socket->priv->construct_error);
618 if (socket->priv->fd != -1 &&
619 !socket->priv->closed)
620 g_socket_close (socket, NULL);
622 g_free (socket->priv->protocol);
625 g_assert (socket->priv->requested_conditions == NULL);
628 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
629 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
633 g_socket_dispose (GObject *object)
635 GSocket *socket = G_SOCKET (object);
637 if (socket->priv->local_address)
639 g_object_unref (socket->priv->local_address);
640 socket->priv->local_address = NULL;
643 if (socket->priv->remote_address)
645 g_object_unref (socket->priv->remote_address);
646 socket->priv->remote_address = NULL;
649 if (G_OBJECT_CLASS (g_socket_parent_class)->dispose)
650 (*G_OBJECT_CLASS (g_socket_parent_class)->dispose) (object);
654 g_socket_class_init (GSocketClass *klass)
656 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
659 /* Make sure winsock has been initialized */
660 type = g_inet_address_get_type ();
662 g_type_class_add_private (klass, sizeof (GSocketPrivate));
664 gobject_class->finalize = g_socket_finalize;
665 gobject_class->dispose = g_socket_dispose;
666 gobject_class->constructed = g_socket_constructed;
667 gobject_class->set_property = g_socket_set_property;
668 gobject_class->get_property = g_socket_get_property;
670 g_object_class_install_property (gobject_class, PROP_FAMILY,
671 g_param_spec_enum ("family",
673 P_("The sockets address family"),
674 G_TYPE_SOCKET_FAMILY,
675 G_SOCKET_FAMILY_INVALID,
676 G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
678 g_object_class_install_property (gobject_class, PROP_TYPE,
679 g_param_spec_enum ("type",
681 P_("The sockets type"),
683 G_SOCKET_TYPE_STREAM,
684 G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
686 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
687 g_param_spec_string ("protocol",
688 P_("Socket protocol"),
689 P_("The name of the protocol to use, or NULL"),
691 G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
693 g_object_class_install_property (gobject_class, PROP_FD,
694 g_param_spec_int ("fd",
695 P_("File descriptor"),
696 P_("The sockets file descriptor"),
700 G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
702 g_object_class_install_property (gobject_class, PROP_BLOCKING,
703 g_param_spec_boolean ("blocking",
705 P_("Whether or not I/O on this socket is blocking"),
707 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
709 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
710 g_param_spec_int ("listen-backlog",
711 P_("Listen backlog"),
712 P_("outstanding connections in the listen queue"),
716 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
718 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
719 g_param_spec_boolean ("keepalive",
720 P_("Keep connection alive"),
721 P_("Keep connection alive by sending periodic pings"),
723 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
725 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
726 g_param_spec_object ("local-address",
728 P_("The local address the socket is bound to"),
729 G_TYPE_SOCKET_ADDRESS,
730 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
732 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
733 g_param_spec_object ("remote-address",
734 P_("Remote address"),
735 P_("The remote address the socket is connected to"),
736 G_TYPE_SOCKET_ADDRESS,
737 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
741 g_socket_initable_iface_init (GInitableIface *iface)
743 iface->init = g_socket_initable_init;
747 g_socket_init (GSocket *socket)
749 socket->priv = G_TYPE_INSTANCE_GET_PRIVATE (socket, G_TYPE_SOCKET, GSocketPrivate);
751 socket->priv->fd = -1;
752 socket->priv->blocking = TRUE;
753 socket->priv->listen_backlog = 10;
754 socket->priv->construct_error = NULL;
755 socket->priv->remote_address = NULL;
756 socket->priv->local_address = NULL;
758 socket->priv->event = WSA_INVALID_EVENT;
763 g_socket_initable_init (GInitable *initable,
764 GCancellable *cancellable,
769 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
771 socket = G_SOCKET (initable);
773 if (cancellable != NULL)
775 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
776 _("Cancellable initialization not supported"));
780 socket->priv->inited = TRUE;
782 if (socket->priv->construct_error)
785 *error = g_error_copy (socket->priv->construct_error);
795 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
796 * @type: the socket type to use.
797 * @protocol: the name of the protocol to use, or %NULL.
798 * @error: #GError for error reporting, or %NULL to ignore.
800 * Creates a new #GSocket with the defined family, type and protocol.
801 * If @protocol is %NULL the default protocol type for the family and
804 * Returns: a #GSocket or %NULL on error.
805 * Free the returned object with g_object_unref().
810 g_socket_new (GSocketFamily family,
812 const char *protocol,
815 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
819 "protocol", protocol,
824 * g_socket_new_from_fd:
825 * @fd: a native socket file descriptor.
826 * @error: #GError for error reporting, or %NULL to ignore.
828 * Creates a new #GSocket from a native file descriptor
829 * or winsock SOCKET handle.
831 * This reads all the settings from the file descriptor so that
832 * all properties should work. Note that the file descriptor
833 * will be set to non-blocking mode, independent on the blocking
834 * mode of the #GSocket.
836 * Returns: a #GSocket or %NULL on error.
837 * Free the returned object with g_object_unref().
842 g_socket_new_from_fd (gint fd,
845 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
852 * g_socket_set_blocking:
853 * @socket: a #GSocket.
854 * @blocking: Whether to use blocking I/O or not.
856 * Sets the blocking mode of the socket. In blocking mode
857 * all operations block until they succeed or there is an error. In
858 * non-blocking mode all functions return results immediately or
859 * with a %G_IO_ERROR_WOULD_BLOCK error.
861 * All sockets are created in blocking mode. However, note that the
862 * platform level socket is always non-blocking, and blocking mode
863 * is a GSocket level feature.
868 g_socket_set_blocking (GSocket *socket,
871 g_return_if_fail (G_IS_SOCKET (socket));
873 blocking = !!blocking;
875 if (socket->priv->blocking == blocking)
878 socket->priv->blocking = blocking;
879 g_object_notify (G_OBJECT (socket), "blocking");
883 * g_socket_get_blocking:
884 * @socket: a #GSocket.
886 * Gets the blocking mode of the socket. For details on blocking I/O,
887 * see g_socket_set_blocking().
889 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
894 g_socket_get_blocking (GSocket *socket)
896 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
898 return socket->priv->blocking;
902 * g_socket_set_keepalive:
903 * @socket: a #GSocket.
904 * @keepalive: Whether to use try to keep the connection alive or not.
906 * Setting @keepalive to %TRUE enables the sending of periodic ping requests
907 * on idle connections in order to keep the connection alive. This is only
908 * useful for connection oriented sockets. The exact period used between
909 * each ping is system and protocol dependent.
911 * Sending keepalive requests like this has a few disadvantages. For instance,
912 * it uses more network bandwidth, and it makes your application more sensitive
913 * to temporary outages in the network (i.e. if a cable is pulled your otherwise
914 * idle connection could be terminated, whereas otherwise it would survive unless
915 * actually used before the cable was reinserted). However, it is sometimes
916 * useful to ensure that connections are eventually terminated if e.g. the
917 * remote side is disconnected, so as to avoid leaking resources forever.
922 g_socket_set_keepalive (GSocket *socket,
927 g_return_if_fail (G_IS_SOCKET (socket));
929 keepalive = !!keepalive;
930 if (socket->priv->keepalive == keepalive)
933 value = (gint) keepalive;
934 if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_KEEPALIVE,
935 (gpointer) &value, sizeof (value)) < 0)
937 int errsv = get_socket_errno ();
938 g_warning ("error setting keepalive: %s", socket_strerror (errsv));
942 socket->priv->keepalive = keepalive;
943 g_object_notify (G_OBJECT (socket), "keepalive");
947 * g_socket_get_keepalive:
948 * @socket: a #GSocket.
950 * Gets the keepalive mode of the socket. For details on this,
951 * see g_socket_set_keepalive().
953 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
958 g_socket_get_keepalive (GSocket *socket)
960 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
962 return socket->priv->keepalive;
966 * g_socket_get_listen_backlog:
967 * @socket: a #GSocket.
969 * Gets the listen backlog setting of the socket. For details on this,
970 * see g_socket_set_listen_backlog().
972 * Returns: the maximum number of pending connections.
977 g_socket_get_listen_backlog (GSocket *socket)
979 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
981 return socket->priv->listen_backlog;
985 * g_socket_set_listen_backlog:
986 * @socket: a #GSocket.
987 * @backlog: the maximum number of pending connections.
989 * Sets the maximum number of outstanding connections allowed
990 * when listening on this socket. If more clients than this are
991 * connecting to the socket and the application is not handling them
992 * on time then the new connections will be refused.
997 g_socket_set_listen_backlog (GSocket *socket,
1000 g_return_if_fail (G_IS_SOCKET (socket));
1002 if (backlog != socket->priv->listen_backlog)
1004 socket->priv->listen_backlog = backlog;
1005 g_object_notify (G_OBJECT (socket), "listen-backlog");
1010 * g_socket_get_family:
1011 * @socket: a #GSocket.
1013 * Gets the socket family of the socket.
1015 * Returns: a #GSocketFamily
1020 g_socket_get_family (GSocket *socket)
1022 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1024 return socket->priv->family;
1028 * g_socket_get_socket_type:
1029 * @socket: a #GSocket.
1031 * Gets the socket type of the socket.
1033 * Returns: a #GSocketType
1038 g_socket_get_socket_type (GSocket *socket)
1040 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1042 return socket->priv->type;
1046 * g_socket_get_protocol:
1047 * @socket: a #GSocket.
1049 * Gets the socket protocol type name the socket was created with.
1050 * This can be %NULL if the socket was created with a NULL protocol.
1052 * Returns: a string or %NULL, do not free
1057 g_socket_get_protocol (GSocket *socket)
1059 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1061 return socket->priv->protocol;
1066 * @socket: a #GSocket.
1068 * Returns the underlying OS socket object. On unix this
1069 * is a socket file descriptor, and on windows this is
1070 * a Winsock2 SOCKET handle. This may be useful for
1071 * doing platform specific or otherwise unusual operations
1074 * Returns: the file descriptor of the socket.
1079 g_socket_get_fd (GSocket *socket)
1081 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1083 return socket->priv->fd;
1087 * g_socket_get_local_address:
1088 * @socket: a #GSocket.
1089 * @error: #GError for error reporting, or %NULL to ignore.
1091 * Try to get the local address of a bound socket. This is only
1092 * useful if the socket has been bound to a local address.
1094 * Returns: a #GSocketAddress or %NULL on error.
1099 g_socket_get_local_address (GSocket *socket,
1105 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1107 if (socket->priv->local_address)
1108 return socket->priv->local_address;
1110 if (getsockname (socket->priv->fd, (struct sockaddr *) buffer, &len) < 0)
1112 int errsv = get_socket_errno ();
1113 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1114 _("could not get local address: %s"), socket_strerror (errsv));
1118 socket->priv->local_address = g_socket_address_new_from_native (buffer, len);
1119 return socket->priv->local_address;
1123 * g_socket_get_remote_address:
1124 * @socket: a #GSocket.
1125 * @error: #GError for error reporting, or %NULL to ignore.
1127 * Try to get the remove address of a connected socket. This is only
1128 * useful for connection oriented sockets that have been connected.
1130 * Returns: a #GSocketAddress or %NULL on error.
1135 g_socket_get_remote_address (GSocket *socket,
1141 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1143 if (socket->priv->remote_address)
1144 return socket->priv->remote_address;
1146 if (getpeername (socket->priv->fd, (struct sockaddr *) buffer, &len) < 0)
1148 int errsv = get_socket_errno ();
1149 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1150 _("could not get remote address: %s"), socket_strerror (errsv));
1154 socket->priv->remote_address = g_socket_address_new_from_native (buffer, len);
1155 return socket->priv->remote_address;
1159 * g_socket_is_connected:
1160 * @socket: a #GSocket.
1162 * Check whether the socket is connected. This is only useful for
1163 * connection-oriented sockets.
1165 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1170 g_socket_is_connected (GSocket *socket)
1172 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1174 return socket->priv->remote_address != NULL;
1179 * @socket: a #GSocket.
1180 * @error: #GError for error reporting, or %NULL to ignore.
1182 * Marks the socket as a server socket, i.e. a socket that is used
1183 * to accept incoming requests using g_socket_accept().
1185 * Before calling this the socket must be bound to a local address using
1188 * Returns: %TRUE on success, %FALSE on error.
1193 g_socket_listen (GSocket *socket,
1196 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1198 if (!check_socket (socket, error))
1201 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1203 int errsv = get_socket_errno ();
1205 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1206 _("could not listen: %s"), socket_strerror (errsv));
1215 * @socket: a #GSocket.
1216 * @address: a #GSocketAddress specifying the local address.
1217 * @allow_reuse: whether to allow reusing this address
1218 * @error: #GError for error reporting, or %NULL to ignore.
1220 * When a socket is created it is attached to an address family, but it
1221 * doesn't have an address in this family. g_socket_bind() assigns the
1222 * address (sometimes called name) of the socket.
1224 * It is generally required to bind to a local address before you can
1225 * receive connections. (See g_socket_listen() and g_socket_accept() ).
1227 * If @allow_reuse is %TRUE this allows the bind call to succeed in some
1228 * situation where it would otherwise return a %G_IO_ERROR_ADDRESS_IN_USE
1229 * error. The main example is for a TCP server socket where there are
1230 * outstanding connections in the WAIT state, which are generally safe
1231 * to ignore. However, setting it to %TRUE doesn't mean the call will
1232 * succeed if there is a socket actively bound to the address.
1234 * In general, pass %TRUE if the socket will be used to accept connections,
1235 * otherwise pass %FALSE.
1237 * Returns: %TRUE on success, %FALSE on error.
1242 g_socket_bind (GSocket *socket,
1243 GSocketAddress *address,
1244 gboolean reuse_address,
1250 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1252 if (!check_socket (socket, error))
1255 /* SO_REUSEADDR on windows means something else and is not what we want.
1256 It always allows the unix variant of SO_REUSEADDR anyway */
1258 value = (int) !!reuse_address;
1259 if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_REUSEADDR,
1260 (gpointer) &value, sizeof (value)) < 0)
1262 int errsv = get_socket_errno ();
1264 G_IO_ERROR, socket_io_error_from_errno (errsv),
1265 _("Error setting reuse_address: %s"), socket_strerror (errsv));
1270 if (!g_socket_address_to_native (address, addr, sizeof addr))
1273 if (bind (socket->priv->fd, (struct sockaddr *) addr,
1274 g_socket_address_get_native_size (address)) < 0)
1276 int errsv = get_socket_errno ();
1278 G_IO_ERROR, socket_io_error_from_errno (errsv),
1279 _("Error binding to address: %s"), socket_strerror (errsv));
1283 socket->priv->local_address = g_object_ref (address);
1290 * @socket: a #GSocket.
1291 * @error: #GError for error reporting, or %NULL to ignore.
1293 * Accept incoming connections on a connection-based socket. This removes
1294 * the first outstanding connection request from the listening socket and
1295 * creates a #GSocket object for it.
1297 * The @socket must be bound to a local address with g_socket_bind() and
1298 * must be listening for incoming connections (g_socket_listen()).
1300 * If there are no outstanding connections then the operation will block
1301 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
1302 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
1304 * Returns: a new #GSocket, or %NULL on error.
1305 * Free the returned object with g_object_unref().
1310 g_socket_accept (GSocket *socket,
1313 GSocket *new_socket;
1316 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1318 if (!check_socket (socket, error))
1323 if (socket->priv->blocking &&
1324 !g_socket_condition_wait (socket,
1325 G_IO_IN, NULL, error))
1328 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
1330 int errsv = get_socket_errno ();
1332 win32_unset_event_mask (socket, FD_ACCEPT);
1337 if (socket->priv->blocking)
1339 #ifdef WSAEWOULDBLOCK
1340 if (errsv == WSAEWOULDBLOCK)
1343 if (errsv == EWOULDBLOCK ||
1349 g_set_error (error, G_IO_ERROR,
1350 socket_io_error_from_errno (errsv),
1351 _("Error accepting connection: %s"), socket_strerror (errsv));
1357 win32_unset_event_mask (socket, FD_ACCEPT);
1361 /* The socket inherits the accepting sockets event mask and even object,
1362 we need to remove that */
1363 WSAEventSelect (ret, NULL, 0);
1369 /* We always want to set close-on-exec to protect users. If you
1370 need to so some weird inheritance to exec you can re-enable this
1371 using lower level hacks with g_socket_get_fd(). */
1372 flags = fcntl (ret, F_GETFD, 0);
1374 (flags & FD_CLOEXEC) == 0)
1376 flags |= FD_CLOEXEC;
1377 fcntl (ret, F_SETFD, flags);
1382 new_socket = g_socket_new_from_fd (ret, error);
1383 if (new_socket == NULL)
1397 * @socket: a #GSocket.
1398 * @address: a #GSocketAddress specifying the remote address.
1399 * @error: #GError for error reporting, or %NULL to ignore.
1401 * Connect the socket to the specified remote address.
1403 * For connection oriented socket this generally means we attempt to make
1404 * a connection to the @address. For a connection-less socket it sets
1405 * the default address for g_socket_send() and discards all incoming datagrams
1406 * from other sources.
1408 * Generally connection oriented sockets can only connect once, but connection-less
1409 * sockets can connect multiple times to change the default address.
1411 * If the connect call needs to do network I/O it will block, unless
1412 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
1413 * and the user can be notified of the connection finishing by waiting
1414 * for the G_IO_OUT condition. The result of the connection can then be
1415 * checked with g_socket_check_pending_error().
1417 * Returns: %TRUE if connected, %FALSE on error.
1422 g_socket_connect (GSocket *socket,
1423 GSocketAddress *address,
1428 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1430 if (!check_socket (socket, error))
1433 g_socket_address_to_native (address, buffer, sizeof buffer);
1437 if (socket->priv->blocking &&
1438 !g_socket_condition_wait (socket,
1439 G_IO_IN, NULL, error))
1442 if (connect (socket->priv->fd, (struct sockaddr *) buffer,
1443 g_socket_address_get_native_size (address)) < 0)
1445 int errsv = get_socket_errno ();
1451 if (errsv == EINPROGRESS)
1453 if (errsv == WSAEINPROGRESS)
1456 if (socket->priv->blocking)
1458 g_socket_condition_wait (socket, G_IO_OUT, NULL, NULL);
1459 if (g_socket_check_pending_error (socket, error))
1462 g_prefix_error (error, _("Error connecting: "));
1465 g_set_error (error, G_IO_ERROR, G_IO_ERROR_PENDING,
1466 _("Connection in progress"));
1469 g_set_error (error, G_IO_ERROR,
1470 socket_io_error_from_errno (errsv),
1471 _("Error connecting: %s"), socket_strerror (errsv));
1478 win32_unset_event_mask (socket, FD_CONNECT);
1480 socket->priv->remote_address = g_object_ref (address);
1486 * g_socket_check_pending_error:
1487 * @socket: a #GSocket
1488 * @error: #GError for error reporting, or %NULL to ignore.
1490 * Checks and resets the pending error for the socket. This is typically
1491 * used to check for errors when g_socket_connect() is used in non-blocking mode.
1493 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
1498 g_socket_check_pending_error (GSocket *socket,
1504 if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
1506 int errsv = get_socket_errno ();
1508 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1509 _("Unable to get pending error: %s"), socket_strerror (errsv));
1515 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (value),
1516 "%s", socket_strerror (value));
1524 * @socket: a #GSocket
1525 * @buffer: a buffer to read data into (which should be at least count bytes long).
1526 * @size: the number of bytes that will be read from the stream
1527 * @error: #GError for error reporting, or %NULL to ignore.
1529 * Receive data (up to @size bytes) from a socket. This is mainly used by
1530 * connection oriented sockets, it is identical to g_socket_receive_from()
1531 * with @address set to %NULL.
1533 * If a message is too long to fit in @buffer, excess bytes may be discarded
1534 * depending on the type of socket the message is received from.
1536 * If the socket is in blocking mode the call will block until there is
1537 * some data to receive or there is an error. If there is no data available
1538 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1539 * will be returned. To be notified of available data, wait for the %G_IO_IN
1542 * On error -1 is returned and @error is set accordingly.
1544 * Returns: Number of bytes read, or -1 on error
1549 g_socket_receive (GSocket *socket,
1556 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1558 if (!check_socket (socket, error))
1563 if (socket->priv->blocking &&
1564 !g_socket_condition_wait (socket,
1565 G_IO_IN, NULL, error))
1568 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
1570 int errsv = get_socket_errno ();
1575 if (socket->priv->blocking)
1577 #ifdef WSAEWOULDBLOCK
1578 if (errsv == WSAEWOULDBLOCK)
1581 if (errsv == EWOULDBLOCK ||
1587 win32_unset_event_mask (socket, FD_READ);
1589 g_set_error (error, G_IO_ERROR,
1590 socket_io_error_from_errno (errsv),
1591 _("Error receiving data: %s"), socket_strerror (errsv));
1595 win32_unset_event_mask (socket, FD_READ);
1604 * g_socket_receive_from:
1605 * @socket: a #GSocket
1606 * @address: a pointer to a #GSocketAddress pointer, or %NULL
1607 * @buffer: a buffer to read data into (which should be at least count bytes long).
1608 * @size: the number of bytes that will be read from the stream
1609 * @error: #GError for error reporting, or %NULL to ignore.
1611 * Receive data (up to @size bytes) from a socket.
1613 * If @address is non-%NULL then @address will be set equal to the
1614 * source address of the received packet.
1615 * @address is owned by the caller.
1617 * If the socket is in blocking mode the call will block until there is
1618 * some data to receive or there is an error. If there is no data available
1619 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1620 * will be returned. To be notified of available data, wait for the %G_IO_IN
1623 * On error -1 is returned and @error is set accordingly.
1625 * Returns: Number of bytes read, or -1 on error
1630 g_socket_receive_from (GSocket *socket,
1631 GSocketAddress **address,
1641 return g_socket_receive_message (socket,
1650 * @socket: a #GSocket
1651 * @buffer: the buffer containing the data to send.
1652 * @size: the number of bytes to send
1653 * @error: #GError for error reporting, or %NULL to ignore.
1655 * Tries to send @size bytes from @buffer on the socket. This is mainly used by
1656 * connection oriented sockets, it is identical to g_socket_send_to()
1657 * with @address set to %NULL.
1659 * If the socket is in blocking mode the call will block until there is
1660 * space for the data in the socket queue. If there is no space available
1661 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1662 * will be returned. To be notified of available space, wait for the %G_IO_OUT
1665 * Note that on Windows you can't rely on a %G_IO_OUT condition
1666 * not producing a %G_IO_ERROR_WOULD_BLOCK error, as this is how Winsock
1667 * write notification works. However, robust apps should always be able to
1668 * handle this since it can easily appear in other cases too.
1670 * On error -1 is returned and @error is set accordingly.
1672 * Returns: Number of bytes read, or -1 on error
1677 g_socket_send (GSocket *socket,
1678 const gchar *buffer,
1684 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1686 if (!check_socket (socket, error))
1691 if (socket->priv->blocking &&
1692 !g_socket_condition_wait (socket,
1693 G_IO_OUT, NULL, error))
1696 if ((ret = send (socket->priv->fd, buffer, size, 0)) < 0)
1698 int errsv = get_socket_errno ();
1703 #ifdef WSAEWOULDBLOCK
1704 if (errsv == WSAEWOULDBLOCK)
1705 win32_unset_event_mask (socket, FD_WRITE);
1708 if (socket->priv->blocking)
1710 #ifdef WSAEWOULDBLOCK
1711 if (errsv == WSAEWOULDBLOCK)
1714 if (errsv == EWOULDBLOCK ||
1720 g_set_error (error, G_IO_ERROR,
1721 socket_io_error_from_errno (errsv),
1722 _("Error sending data: %s"), socket_strerror (errsv));
1733 * @socket: a #GSocket
1734 * @address: a #GSocketAddress, or %NULL
1735 * @buffer: the buffer containing the data to send.
1736 * @size: the number of bytes to send
1737 * @error: #GError for error reporting, or %NULL to ignore.
1739 * Tries to send @size bytes from @buffer to @address. If @address is
1740 * %NULL then the message is sent to the default receiver (set by
1741 * g_socket_connect()).
1743 * If the socket is in blocking mode the call will block until there is
1744 * space for the data in the socket queue. If there is no space available
1745 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1746 * will be returned. To be notified of available space, wait for the %G_IO_OUT
1749 * Note that on Windows you can't rely on a %G_IO_OUT condition
1750 * not producing a %G_IO_ERROR_WOULD_BLOCK error, as this is how Winsock
1751 * write notification works. However, robust apps should always be able to
1752 * handle this since it can easily appear in other cases too.
1754 * On error -1 is returned and @error is set accordingly.
1756 * Returns: Number of bytes read, or -1 on error
1761 g_socket_send_to (GSocket *socket,
1762 GSocketAddress *address,
1763 const gchar *buffer,
1772 return g_socket_send_message (socket,
1781 * @socket: a #GSocket
1782 * @error: #GError for error reporting, or %NULL to ignore.
1784 * Closes the socket, shutting down any active connection.
1786 * Closing a socket does not wait for all outstanding I/O operations to finish,
1787 * so the caller should not rely on them to be guaranteed to complete even
1788 * if the close returns with no error.
1790 * Once the socket is closed, all other operations will return %G_IO_ERROR_CLOSED.
1791 * Closing a stream multiple times will not return an error.
1793 * Sockets will be automatically closed when the last reference
1794 * is dropped, but you might want to call this function to make sure
1795 * resources are released as early as possible.
1797 * Returns: %TRUE on success, %FALSE on error
1802 g_socket_close (GSocket *socket,
1807 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
1809 if (socket->priv->closed)
1810 return TRUE; /* Multiple close not an error */
1812 if (!check_socket (socket, NULL))
1818 res = closesocket (socket->priv->fd);
1820 res = close (socket->priv->fd);
1824 int errsv = get_socket_errno ();
1829 g_set_error (error, G_IO_ERROR,
1830 socket_io_error_from_errno (errsv),
1831 _("Error closing socket: %s"),
1832 socket_strerror (errsv));
1839 if (socket->priv->event != WSA_INVALID_EVENT)
1841 WSACloseEvent (socket->priv->event);
1842 socket->priv->event = WSA_INVALID_EVENT;
1846 socket->priv->closed = TRUE;
1852 * g_socket_is_closed:
1853 * @socket: a #GSocket
1855 * Checks whether a socket is closed.
1857 * Returns: %TRUE if socket is closed, %FALSE otherwise
1862 g_socket_is_closed (GSocket *socket)
1864 return socket->priv->closed;
1868 /* Broken source, used on errors */
1870 broken_prepare (GSource *source,
1877 broken_check (GSource *source)
1883 broken_dispatch (GSource *source,
1884 GSourceFunc callback,
1890 static GSourceFuncs broken_funcs =
1899 network_events_for_condition (GIOCondition condition)
1903 if (condition & G_IO_IN)
1904 event_mask |= (FD_READ | FD_ACCEPT);
1905 if (condition & G_IO_OUT)
1906 event_mask |= (FD_WRITE | FD_CONNECT);
1907 event_mask |= FD_CLOSE;
1913 ensure_event (GSocket *socket)
1915 if (socket->priv->event == WSA_INVALID_EVENT)
1916 socket->priv->event = WSACreateEvent();
1920 update_select_events (GSocket *socket)
1927 ensure_event (socket);
1930 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
1933 event_mask |= network_events_for_condition (*ptr);
1936 if (event_mask != socket->priv->selected_events)
1938 /* If no events selected, disable event so we can unset
1941 if (event_mask == 0)
1944 event = socket->priv->event;
1946 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
1947 socket->priv->selected_events = event_mask;
1952 add_condition_watch (GSocket *socket,
1953 GIOCondition *condition)
1955 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
1957 socket->priv->requested_conditions =
1958 g_list_prepend (socket->priv->requested_conditions, condition);
1960 update_select_events (socket);
1964 remove_condition_watch (GSocket *socket,
1965 GIOCondition *condition)
1967 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
1969 socket->priv->requested_conditions =
1970 g_list_remove (socket->priv->requested_conditions, condition);
1972 update_select_events (socket);
1976 update_condition (GSocket *socket)
1978 WSANETWORKEVENTS events;
1979 GIOCondition condition;
1981 if (WSAEnumNetworkEvents (socket->priv->fd,
1982 socket->priv->event,
1985 socket->priv->current_events |= events.lNetworkEvents;
1986 if (events.lNetworkEvents & FD_WRITE &&
1987 events.iErrorCode[FD_WRITE_BIT] != 0)
1988 socket->priv->current_errors |= FD_WRITE;
1989 if (events.lNetworkEvents & FD_CONNECT &&
1990 events.iErrorCode[FD_CONNECT_BIT] != 0)
1991 socket->priv->current_errors |= FD_CONNECT;
1995 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
1996 condition |= G_IO_IN;
1998 if (socket->priv->current_events & FD_CLOSE ||
1999 socket->priv->closed)
2000 condition |= G_IO_HUP;
2002 /* Never report both G_IO_OUT and HUP, these are
2003 mutually exclusive (can't write to a closed socket) */
2004 if ((condition & G_IO_HUP) == 0 &&
2005 socket->priv->current_events & FD_WRITE)
2007 if (socket->priv->current_errors & FD_WRITE)
2008 condition |= G_IO_ERR;
2010 condition |= G_IO_OUT;
2014 if (socket->priv->current_events & FD_CONNECT)
2016 if (socket->priv->current_errors & FD_CONNECT)
2017 condition |= (G_IO_HUP | G_IO_ERR);
2019 condition |= G_IO_OUT;
2030 GIOCondition condition;
2031 GCancellable *cancellable;
2032 GPollFD cancel_pollfd;
2033 GIOCondition result_condition;
2037 winsock_prepare (GSource *source,
2040 GWinsockSource *winsock_source = (GWinsockSource *)source;
2041 GIOCondition current_condition;
2043 current_condition = update_condition (winsock_source->socket);
2045 if (g_cancellable_is_cancelled (winsock_source->cancellable))
2047 winsock_source->result_condition = current_condition;
2051 if ((winsock_source->condition & current_condition) != 0)
2053 winsock_source->result_condition = current_condition;
2061 winsock_check (GSource *source)
2063 GWinsockSource *winsock_source = (GWinsockSource *)source;
2064 GIOCondition current_condition;
2066 current_condition = update_condition (winsock_source->socket);
2068 if (g_cancellable_is_cancelled (winsock_source->cancellable))
2070 winsock_source->result_condition = current_condition;
2074 if ((winsock_source->condition & current_condition) != 0)
2076 winsock_source->result_condition = current_condition;
2084 winsock_dispatch (GSource *source,
2085 GSourceFunc callback,
2088 GSocketSourceFunc func = (GSocketSourceFunc)callback;
2089 GWinsockSource *winsock_source = (GWinsockSource *)source;
2091 return (*func) (user_data,
2092 winsock_source->result_condition & winsock_source->condition);
2096 winsock_finalize (GSource *source)
2098 GWinsockSource *winsock_source = (GWinsockSource *)source;
2101 socket = winsock_source->socket;
2103 remove_condition_watch (socket, &winsock_source->condition);
2104 g_object_unref (socket);
2106 if (winsock_source->cancellable)
2107 g_object_unref (winsock_source->cancellable);
2110 static GSourceFuncs winsock_funcs =
2119 winsock_source_new (GSocket *socket,
2120 GIOCondition condition,
2121 GCancellable *cancellable)
2124 GWinsockSource *winsock_source;
2126 ensure_event (socket);
2128 if (socket->priv->event == WSA_INVALID_EVENT)
2130 g_warning ("Failed to create WSAEvent");
2131 return g_source_new (&broken_funcs, sizeof (GSource));
2134 condition |= G_IO_HUP | G_IO_ERR;
2136 source = g_source_new (&winsock_funcs, sizeof (GWinsockSource));
2137 winsock_source = (GWinsockSource *)source;
2139 winsock_source->socket = g_object_ref (socket);
2140 winsock_source->condition = condition;
2141 add_condition_watch (socket, &winsock_source->condition);
2145 winsock_source->cancellable = g_object_ref (cancellable);
2146 g_cancellable_make_pollfd (cancellable,
2147 &winsock_source->cancel_pollfd);
2148 g_source_add_poll (source, &winsock_source->cancel_pollfd);
2151 winsock_source->pollfd.fd = (gintptr) socket->priv->event;
2152 winsock_source->pollfd.events = condition;
2153 g_source_add_poll (source, &winsock_source->pollfd);
2160 * g_socket_create_source:
2161 * @socket: a #GSocket
2162 * @condition: a #GIOCondition mask to monitor
2163 * @cancellable: a %GCancellable or %NULL
2165 * Creates a %GSource that can be attached to a %GMainContext to monitor
2166 * for the availibility of the specified @condition on the socket.
2168 * The callback on the source is of the #GSocketSourceFunc type.
2170 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2171 * these conditions will always be reported output if they are true.
2173 * @cancellable if not %NULL can be used to cancel the source, which will
2174 * cause the source to trigger, reporting the current condition. You can
2175 * check for this in the callback using g_cancellable_is_cancelled().
2177 * Returns: a newly allocated %GSource, free with g_source_unref().
2182 g_socket_create_source (GSocket *socket,
2183 GIOCondition condition,
2184 GCancellable *cancellable)
2187 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
2190 source = winsock_source_new (socket, condition, cancellable);
2192 source =_g_fd_source_new (socket->priv->fd, condition, cancellable);
2198 * g_socket_condition_check:
2199 * @socket: a #GSocket
2200 * @condition: a #GIOCondition mask to check
2202 * Checks on the readiness of @socket to perform operations. The
2203 * operations specified in @condition are checked for and masked
2204 * against the currently-satisfied conditions on @socket. The result
2207 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2208 * these conditions will always be set in the output if they are true.
2210 * This call never blocks.
2212 * Returns: the @GIOCondition mask of the current state
2217 g_socket_condition_check (GSocket *socket,
2218 GIOCondition condition)
2220 if (!check_socket (socket, NULL))
2225 GIOCondition current_condition;
2227 condition |= G_IO_ERR | G_IO_HUP;
2229 add_condition_watch (socket, &condition);
2230 current_condition = update_condition (socket);
2231 remove_condition_watch (socket, &condition);
2232 return condition & current_condition;
2238 poll_fd.fd = socket->priv->fd;
2239 poll_fd.events = condition;
2242 result = g_poll (&poll_fd, 1, 0);
2243 while (result == -1 && get_socket_errno () == EINTR);
2245 return poll_fd.revents;
2251 * g_socket_condition_wait:
2252 * @socket: a #GSocket
2253 * @condition: a #GIOCondition mask to wait for
2254 * @cancellable: a #GCancellable, or %NULL
2255 * @error: a #GError pointer, or %NULL
2257 * Waits for @condition to become true on @socket. When the condition
2258 * becomes true, %TRUE is returned.
2260 * If @cancellable is cancelled before the condition becomes true then
2261 * %FALSE is returned and @error, if non-%NULL, is set to %G_IO_ERROR_CANCELLED.
2263 * Returns: %TRUE if the condition was met, %FALSE otherwise
2268 g_socket_condition_wait (GSocket *socket,
2269 GIOCondition condition,
2270 GCancellable *cancellable,
2273 if (!check_socket (socket, error))
2276 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2281 GIOCondition current_condition;
2287 /* Always check these */
2288 condition |= G_IO_ERR | G_IO_HUP;
2290 add_condition_watch (socket, &condition);
2293 events[num_events++] = socket->priv->event;
2297 g_cancellable_make_pollfd (cancellable, &cancel_fd);
2298 events[num_events++] = (WSAEVENT)cancel_fd.fd;
2301 current_condition = update_condition (socket);
2302 while ((condition & current_condition) == 0)
2304 res = WSAWaitForMultipleEvents(num_events, events,
2305 FALSE, WSA_INFINITE, FALSE);
2306 if (res == WSA_WAIT_FAILED)
2308 int errsv = get_socket_errno ();
2310 g_set_error (error, G_IO_ERROR,
2311 socket_io_error_from_errno (errsv),
2312 _("Waiting for socket condition: %s"),
2313 socket_strerror (errsv));
2317 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2320 current_condition = update_condition (socket);
2322 remove_condition_watch (socket, &condition);
2324 return (condition & current_condition) != 0;
2332 poll_fd[0].fd = socket->priv->fd;
2333 poll_fd[0].events = condition;
2338 g_cancellable_make_pollfd (cancellable, &poll_fd[1]);
2343 result = g_poll (poll_fd, num, -1);
2344 while (result == -1 && get_socket_errno () == EINTR);
2346 return cancellable == NULL ||
2347 !g_cancellable_set_error_if_cancelled (cancellable, error);
2354 * @socket: a #GSocket
2355 * @address: a #GSocketAddress, or %NULL
2356 * @vectors: an array of #GOutputVector structs
2357 * @num_vectors: the number of elements in @vectors, or -1
2358 * @messages: a pointer to an array of #GSocketControlMessages, or
2360 * @num_messages: number of elements in @messages, or -1.
2361 * @flags: an int containing #GSocketMsgFlags flags
2362 * @error: #GError for error reporting, or %NULL to ignore.
2364 * Send data to @address on @socket. This is the most complicated and
2365 * fully-featured version of this call. For easier use, see
2366 * g_socket_send() and g_socket_send_to().
2368 * If @address is %NULL then the message is sent to the default receiver
2369 * (set by g_socket_connect()).
2371 * @vector must point to an array of #GOutputVector structs and
2372 * @num_vectors must be the length of this array. These structs
2373 * describe the buffers that the sent data will be gathered from.
2374 * If @num_vector is -1, then @vector is assumed to be terminated
2375 * by a #GOutputVector with a %NULL buffer pointer.
2378 * @messages, if non-%NULL, is taken to point to an array of @num_messages
2379 * #GSocketControlMessage instances. These correspond to the control
2380 * messages to be sent on the socket.
2381 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
2384 * @flags modify how the message sent. The commonly available arguments
2385 * for this is available in the #GSocketMsgFlags enum, but the
2386 * values there are the same as the system values, and the flags
2387 * are passed in as-is, so you can pass in system specific flags too.
2389 * If the socket is in blocking mode the call will block until there is
2390 * space for the data in the socket queue. If there is no space available
2391 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2392 * will be returned. To be notified of available space, wait for the %G_IO_OUT
2395 * Note that on Windows you can't rely on a %G_IO_OUT condition
2396 * not producing a %G_IO_ERROR_WOULD_BLOCK error, as this is how Winsock
2397 * write notification works. However, robust apps should always be able to
2398 * handle this since it can easily appear in other cases too.
2400 * On error -1 is returned and @error is set accordingly.
2402 * Returns: Number of bytes read, or -1 on error
2407 g_socket_send_message (GSocket *socket,
2408 GSocketAddress *address,
2409 GOutputVector *vectors,
2411 GSocketControlMessage **messages,
2416 GOutputVector one_vector;
2419 if (!check_socket (socket, error))
2422 if (num_vectors == -1)
2424 for (num_vectors = 0;
2425 vectors[num_vectors].buffer != NULL;
2430 if (num_messages == -1)
2432 for (num_messages = 0;
2433 messages != NULL && messages[num_messages] != NULL;
2438 if (num_vectors == 0)
2442 one_vector.buffer = &zero;
2443 one_vector.size = 1;
2445 vectors = &one_vector;
2456 msg.msg_namelen = g_socket_address_get_native_size (address);
2457 msg.msg_name = g_alloca (msg.msg_namelen);
2458 g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen);
2463 /* this entire expression will be evaluated at compile time */
2464 if (sizeof *msg.msg_iov == sizeof *vectors &&
2465 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2466 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2467 G_STRUCT_OFFSET (GOutputVector, buffer) &&
2468 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2469 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2470 G_STRUCT_OFFSET (GOutputVector, size))
2471 /* ABI is compatible */
2473 msg.msg_iov = (struct iovec *) vectors;
2474 msg.msg_iovlen = num_vectors;
2477 /* ABI is incompatible */
2481 msg.msg_iov = g_newa (struct iovec, num_vectors);
2482 for (i = 0; i < num_vectors; i++)
2484 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
2485 msg.msg_iov[i].iov_len = vectors[i].size;
2487 msg.msg_iovlen = num_vectors;
2493 struct cmsghdr *cmsg;
2496 msg.msg_controllen = 0;
2497 for (i = 0; i < num_messages; i++)
2498 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
2500 msg.msg_control = g_alloca (msg.msg_controllen);
2502 cmsg = CMSG_FIRSTHDR (&msg);
2503 for (i = 0; i < num_messages; i++)
2505 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
2506 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
2507 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
2508 g_socket_control_message_serialize (messages[i],
2510 cmsg = CMSG_NXTHDR (&msg, cmsg);
2512 g_assert (cmsg == NULL);
2517 if (socket->priv->blocking &&
2518 !g_socket_condition_wait (socket,
2519 G_IO_OUT, NULL, error))
2522 result = sendmsg (socket->priv->fd, &msg, flags);
2525 int errsv = get_socket_errno ();
2530 if (socket->priv->blocking &&
2531 (errsv == EWOULDBLOCK ||
2535 g_set_error (error, G_IO_ERROR,
2536 socket_io_error_from_errno (errsv),
2537 _("Error sending message: %s"), socket_strerror (errsv));
2548 struct sockaddr_storage addr;
2555 /* Win32 doesn't support control messages.
2556 Actually this is possible for raw and datagram sockets
2557 via WSASendMessage on Vista or later, but that doesn't
2559 if (num_messages != 0)
2561 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2562 _("GSocketControlMessage not supported on windows"));
2567 bufs = g_newa (WSABUF, num_vectors);
2568 for (i = 0; i < num_vectors; i++)
2570 bufs[i].buf = (char *)vectors[i].buffer;
2571 bufs[i].len = (gulong)vectors[i].size;
2577 addrlen = g_socket_address_get_native_size (address);
2578 g_socket_address_to_native (address, &addr, sizeof addr);
2583 if (socket->priv->blocking &&
2584 !g_socket_condition_wait (socket,
2585 G_IO_OUT, NULL, error))
2589 result = WSASendTo (socket->priv->fd,
2592 (const struct sockaddr *)&addr, addrlen,
2595 result = WSASend (socket->priv->fd,
2602 int errsv = get_socket_errno ();
2604 if (errsv == WSAEINTR)
2607 if (errsv == WSAEWOULDBLOCK)
2608 win32_unset_event_mask (socket, FD_WRITE);
2610 if (socket->priv->blocking &&
2611 errsv == WSAEWOULDBLOCK)
2614 g_set_error (error, G_IO_ERROR,
2615 socket_io_error_from_errno (errsv),
2616 _("Error sending message: %s"), socket_strerror (errsv));
2629 * g_socket_receive_message:
2630 * @socket: a #GSocket
2631 * @address: a pointer to a #GSocketAddress pointer, or %NULL
2632 * @vectors: an array of #GInputVector structs
2633 * @num_vectors: the number of elements in @vectors, or -1
2634 * @messages: a pointer which will be filled with an array of
2635 * #GSocketControlMessages, or %NULL
2636 * @num_messages: a pointer which will be filled with the number of
2637 * elements in @messages, or %NULL
2638 * @flags: a pointer to an int containing #GSocketMsgFlags flags
2639 * @error: a #GError pointer, or %NULL
2641 * Receive data from a socket. This is the most complicated and
2642 * fully-featured version of this call. For easier use, see
2643 * g_socket_receive() and g_socket_receive_from().
2645 * If @address is non-%NULL then @address will be set equal to the
2646 * source address of the received packet.
2647 * @address is owned by the caller.
2649 * @vector must point to an array of #GInputVector structs and
2650 * @num_vectors must be the length of this array. These structs
2651 * describe the buffers that received data will be scattered into.
2652 * If @num_vector is -1, then @vector is assumed to be terminated
2653 * by a #GInputVector with a %NULL buffer pointer.
2655 * As a special case, if the size of the array is zero (in which case,
2656 * @vectors may of course be %NULL), then a single byte is received
2657 * and discarded. This is to facilitate the common practice of
2658 * sending a single '\0' byte for the purposes of transferring
2661 * @messages, if non-%NULL, is taken to point to a pointer that will
2662 * be set to point to a newly-allocated array of
2663 * #GSocketControlMessage instances. These correspond to the control
2664 * messages received from the kernel, one #GSocketControlMessage per
2665 * message from the kernel. This array is %NULL-terminated and must be
2666 * freed by the caller using g_free().
2668 * @num_messages, if non-%NULL, will be set to the number of control
2669 * messages received.
2671 * If both @messages and @num_messages are non-%NULL, then
2672 * @num_messages gives the number of #GSocketControlMessage instances
2673 * in @messages (ie: not including the %NULL terminator).
2675 * @flags is an in/out parameter. The commonly available arguments
2676 * for this is available in the #GSocketMsgFlags enum, but the
2677 * values there are the same as the system values, and the flags
2678 * are passed in as-is, so you can pass in system specific flags too.
2680 * If the socket is in blocking mode the call will block until there is
2681 * some data to receive or there is an error. If there is no data available
2682 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2683 * will be returned. To be notified of available data, wait for the %G_IO_IN
2686 * On error -1 is returned and @error is set accordingly.
2688 * Returns: Number of bytes read, or -1 on error
2693 g_socket_receive_message (GSocket *socket,
2694 GSocketAddress **address,
2695 GInputVector *vectors,
2697 GSocketControlMessage ***messages,
2702 GInputVector one_vector;
2705 if (!check_socket (socket, error))
2708 if (num_vectors == -1)
2710 for (num_vectors = 0;
2711 vectors[num_vectors].buffer != NULL;
2716 if (num_vectors == 0)
2718 one_vector.buffer = &one_byte;
2719 one_vector.size = 1;
2721 vectors = &one_vector;
2728 struct sockaddr_storage one_sockaddr;
2733 msg.msg_name = &one_sockaddr;
2734 msg.msg_namelen = sizeof (struct sockaddr_storage);
2738 msg.msg_name = NULL;
2739 msg.msg_namelen = 0;
2743 /* this entire expression will be evaluated at compile time */
2744 if (sizeof *msg.msg_iov == sizeof *vectors &&
2745 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2746 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2747 G_STRUCT_OFFSET (GInputVector, buffer) &&
2748 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2749 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2750 G_STRUCT_OFFSET (GInputVector, size))
2751 /* ABI is compatible */
2753 msg.msg_iov = (struct iovec *) vectors;
2754 msg.msg_iovlen = num_vectors;
2757 /* ABI is incompatible */
2761 msg.msg_iov = g_newa (struct iovec, num_vectors);
2762 for (i = 0; i < num_vectors; i++)
2764 msg.msg_iov[i].iov_base = vectors[i].buffer;
2765 msg.msg_iov[i].iov_len = vectors[i].size;
2767 msg.msg_iovlen = num_vectors;
2771 msg.msg_control = g_alloca (2048);
2772 msg.msg_controllen = 2048;
2776 msg.msg_flags = *flags;
2783 if (socket->priv->blocking &&
2784 !g_socket_condition_wait (socket,
2785 G_IO_IN, NULL, error))
2788 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
2792 int errsv = get_socket_errno ();
2797 if (socket->priv->blocking &&
2798 (errsv == EWOULDBLOCK ||
2802 g_set_error (error, G_IO_ERROR,
2803 socket_io_error_from_errno (errsv),
2804 _("Error receiving message: %s"), socket_strerror (errsv));
2811 /* decode address */
2812 if (address != NULL)
2814 if (msg.msg_namelen > 0)
2815 *address = g_socket_address_new_from_native (msg.msg_name,
2821 /* decode control messages */
2823 GSocketControlMessage **my_messages = NULL;
2824 gint allocated = 0, index = 0;
2825 const gchar *scm_pointer;
2826 struct cmsghdr *cmsg;
2829 scm_pointer = (const gchar *) msg.msg_control;
2830 scm_size = msg.msg_controllen;
2832 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
2834 GSocketControlMessage *message;
2836 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
2838 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
2840 if (message == NULL)
2841 /* We've already spewed about the problem in the
2842 deserialization code, so just continue */
2845 if (index == allocated)
2847 /* estimated 99% case: exactly 1 control message */
2848 allocated = MIN (allocated * 2, 1);
2849 my_messages = g_new (GSocketControlMessage *, (allocated + 1));
2853 my_messages[index++] = message;
2857 *num_messages = index;
2861 my_messages[index++] = NULL;
2862 *messages = my_messages;
2868 /* free all those messages we just constructed.
2869 * we have to do it this way if the user ignores the
2870 * messages so that we will close any received fds.
2872 for (i = 0; i < index; i++)
2873 g_object_unref (my_messages[i]);
2874 g_free (my_messages);
2878 /* capture the flags */
2880 *flags = msg.msg_flags;
2886 struct sockaddr_storage addr;
2888 DWORD bytes_received;
2895 bufs = g_newa (WSABUF, num_vectors);
2896 for (i = 0; i < num_vectors; i++)
2898 bufs[i].buf = (char *)vectors[i].buffer;
2899 bufs[i].len = (gulong)vectors[i].size;
2911 if (socket->priv->blocking &&
2912 !g_socket_condition_wait (socket,
2913 G_IO_IN, NULL, error))
2916 addrlen = sizeof addr;
2918 result = WSARecvFrom (socket->priv->fd,
2920 &bytes_received, &win_flags,
2921 (struct sockaddr *)&addr, &addrlen,
2924 result = WSARecv (socket->priv->fd,
2926 &bytes_received, &win_flags,
2930 int errsv = get_socket_errno ();
2932 if (errsv == WSAEINTR)
2935 win32_unset_event_mask (socket, FD_READ);
2937 if (socket->priv->blocking &&
2938 errsv == WSAEWOULDBLOCK)
2941 g_set_error (error, G_IO_ERROR,
2942 socket_io_error_from_errno (errsv),
2943 _("Error receiving message: %s"), socket_strerror (errsv));
2947 win32_unset_event_mask (socket, FD_READ);
2951 /* decode address */
2952 if (address != NULL)
2955 *address = g_socket_address_new_from_native (&addr, addrlen);
2960 /* capture the flags */
2964 return bytes_received;
2969 #define __G_SOCKET_C__
2970 #include "gioaliasdef.c"