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 optlen = sizeof (value);
1505 if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
1507 int errsv = get_socket_errno ();
1509 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1510 _("Unable to get pending error: %s"), socket_strerror (errsv));
1516 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (value),
1517 "%s", socket_strerror (value));
1525 * @socket: a #GSocket
1526 * @buffer: a buffer to read data into (which should be at least count bytes long).
1527 * @size: the number of bytes that will be read from the stream
1528 * @error: #GError for error reporting, or %NULL to ignore.
1530 * Receive data (up to @size bytes) from a socket. This is mainly used by
1531 * connection oriented sockets, it is identical to g_socket_receive_from()
1532 * with @address set to %NULL.
1534 * If a message is too long to fit in @buffer, excess bytes may be discarded
1535 * depending on the type of socket the message is received from.
1537 * If the socket is in blocking mode the call will block until there is
1538 * some data to receive or there is an error. If there is no data available
1539 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1540 * will be returned. To be notified of available data, wait for the %G_IO_IN
1543 * On error -1 is returned and @error is set accordingly.
1545 * Returns: Number of bytes read, or -1 on error
1550 g_socket_receive (GSocket *socket,
1557 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1559 if (!check_socket (socket, error))
1564 if (socket->priv->blocking &&
1565 !g_socket_condition_wait (socket,
1566 G_IO_IN, NULL, error))
1569 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
1571 int errsv = get_socket_errno ();
1576 if (socket->priv->blocking)
1578 #ifdef WSAEWOULDBLOCK
1579 if (errsv == WSAEWOULDBLOCK)
1582 if (errsv == EWOULDBLOCK ||
1588 win32_unset_event_mask (socket, FD_READ);
1590 g_set_error (error, G_IO_ERROR,
1591 socket_io_error_from_errno (errsv),
1592 _("Error receiving data: %s"), socket_strerror (errsv));
1596 win32_unset_event_mask (socket, FD_READ);
1605 * g_socket_receive_from:
1606 * @socket: a #GSocket
1607 * @address: a pointer to a #GSocketAddress pointer, or %NULL
1608 * @buffer: a buffer to read data into (which should be at least count bytes long).
1609 * @size: the number of bytes that will be read from the stream
1610 * @error: #GError for error reporting, or %NULL to ignore.
1612 * Receive data (up to @size bytes) from a socket.
1614 * If @address is non-%NULL then @address will be set equal to the
1615 * source address of the received packet.
1616 * @address is owned by the caller.
1618 * If the socket is in blocking mode the call will block until there is
1619 * some data to receive or there is an error. If there is no data available
1620 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1621 * will be returned. To be notified of available data, wait for the %G_IO_IN
1624 * On error -1 is returned and @error is set accordingly.
1626 * Returns: Number of bytes read, or -1 on error
1631 g_socket_receive_from (GSocket *socket,
1632 GSocketAddress **address,
1642 return g_socket_receive_message (socket,
1651 * @socket: a #GSocket
1652 * @buffer: the buffer containing the data to send.
1653 * @size: the number of bytes to send
1654 * @error: #GError for error reporting, or %NULL to ignore.
1656 * Tries to send @size bytes from @buffer on the socket. This is mainly used by
1657 * connection oriented sockets, it is identical to g_socket_send_to()
1658 * with @address set to %NULL.
1660 * If the socket is in blocking mode the call will block until there is
1661 * space for the data in the socket queue. If there is no space available
1662 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1663 * will be returned. To be notified of available space, wait for the %G_IO_OUT
1666 * Note that on Windows you can't rely on a %G_IO_OUT condition
1667 * not producing a %G_IO_ERROR_WOULD_BLOCK error, as this is how Winsock
1668 * write notification works. However, robust apps should always be able to
1669 * handle this since it can easily appear in other cases too.
1671 * On error -1 is returned and @error is set accordingly.
1673 * Returns: Number of bytes read, or -1 on error
1678 g_socket_send (GSocket *socket,
1679 const gchar *buffer,
1685 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1687 if (!check_socket (socket, error))
1692 if (socket->priv->blocking &&
1693 !g_socket_condition_wait (socket,
1694 G_IO_OUT, NULL, error))
1697 if ((ret = send (socket->priv->fd, buffer, size, 0)) < 0)
1699 int errsv = get_socket_errno ();
1704 #ifdef WSAEWOULDBLOCK
1705 if (errsv == WSAEWOULDBLOCK)
1706 win32_unset_event_mask (socket, FD_WRITE);
1709 if (socket->priv->blocking)
1711 #ifdef WSAEWOULDBLOCK
1712 if (errsv == WSAEWOULDBLOCK)
1715 if (errsv == EWOULDBLOCK ||
1721 g_set_error (error, G_IO_ERROR,
1722 socket_io_error_from_errno (errsv),
1723 _("Error sending data: %s"), socket_strerror (errsv));
1734 * @socket: a #GSocket
1735 * @address: a #GSocketAddress, or %NULL
1736 * @buffer: the buffer containing the data to send.
1737 * @size: the number of bytes to send
1738 * @error: #GError for error reporting, or %NULL to ignore.
1740 * Tries to send @size bytes from @buffer to @address. If @address is
1741 * %NULL then the message is sent to the default receiver (set by
1742 * g_socket_connect()).
1744 * If the socket is in blocking mode the call will block until there is
1745 * space for the data in the socket queue. If there is no space available
1746 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1747 * will be returned. To be notified of available space, wait for the %G_IO_OUT
1750 * Note that on Windows you can't rely on a %G_IO_OUT condition
1751 * not producing a %G_IO_ERROR_WOULD_BLOCK error, as this is how Winsock
1752 * write notification works. However, robust apps should always be able to
1753 * handle this since it can easily appear in other cases too.
1755 * On error -1 is returned and @error is set accordingly.
1757 * Returns: Number of bytes read, or -1 on error
1762 g_socket_send_to (GSocket *socket,
1763 GSocketAddress *address,
1764 const gchar *buffer,
1773 return g_socket_send_message (socket,
1782 * @socket: a #GSocket
1783 * @error: #GError for error reporting, or %NULL to ignore.
1785 * Closes the socket, shutting down any active connection.
1787 * Closing a socket does not wait for all outstanding I/O operations to finish,
1788 * so the caller should not rely on them to be guaranteed to complete even
1789 * if the close returns with no error.
1791 * Once the socket is closed, all other operations will return %G_IO_ERROR_CLOSED.
1792 * Closing a stream multiple times will not return an error.
1794 * Sockets will be automatically closed when the last reference
1795 * is dropped, but you might want to call this function to make sure
1796 * resources are released as early as possible.
1798 * Returns: %TRUE on success, %FALSE on error
1803 g_socket_close (GSocket *socket,
1808 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
1810 if (socket->priv->closed)
1811 return TRUE; /* Multiple close not an error */
1813 if (!check_socket (socket, NULL))
1819 res = closesocket (socket->priv->fd);
1821 res = close (socket->priv->fd);
1825 int errsv = get_socket_errno ();
1830 g_set_error (error, G_IO_ERROR,
1831 socket_io_error_from_errno (errsv),
1832 _("Error closing socket: %s"),
1833 socket_strerror (errsv));
1840 if (socket->priv->event != WSA_INVALID_EVENT)
1842 WSACloseEvent (socket->priv->event);
1843 socket->priv->event = WSA_INVALID_EVENT;
1847 socket->priv->closed = TRUE;
1853 * g_socket_is_closed:
1854 * @socket: a #GSocket
1856 * Checks whether a socket is closed.
1858 * Returns: %TRUE if socket is closed, %FALSE otherwise
1863 g_socket_is_closed (GSocket *socket)
1865 return socket->priv->closed;
1869 /* Broken source, used on errors */
1871 broken_prepare (GSource *source,
1878 broken_check (GSource *source)
1884 broken_dispatch (GSource *source,
1885 GSourceFunc callback,
1891 static GSourceFuncs broken_funcs =
1900 network_events_for_condition (GIOCondition condition)
1904 if (condition & G_IO_IN)
1905 event_mask |= (FD_READ | FD_ACCEPT);
1906 if (condition & G_IO_OUT)
1907 event_mask |= (FD_WRITE | FD_CONNECT);
1908 event_mask |= FD_CLOSE;
1914 ensure_event (GSocket *socket)
1916 if (socket->priv->event == WSA_INVALID_EVENT)
1917 socket->priv->event = WSACreateEvent();
1921 update_select_events (GSocket *socket)
1928 ensure_event (socket);
1931 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
1934 event_mask |= network_events_for_condition (*ptr);
1937 if (event_mask != socket->priv->selected_events)
1939 /* If no events selected, disable event so we can unset
1942 if (event_mask == 0)
1945 event = socket->priv->event;
1947 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
1948 socket->priv->selected_events = event_mask;
1953 add_condition_watch (GSocket *socket,
1954 GIOCondition *condition)
1956 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
1958 socket->priv->requested_conditions =
1959 g_list_prepend (socket->priv->requested_conditions, condition);
1961 update_select_events (socket);
1965 remove_condition_watch (GSocket *socket,
1966 GIOCondition *condition)
1968 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
1970 socket->priv->requested_conditions =
1971 g_list_remove (socket->priv->requested_conditions, condition);
1973 update_select_events (socket);
1977 update_condition (GSocket *socket)
1979 WSANETWORKEVENTS events;
1980 GIOCondition condition;
1982 if (WSAEnumNetworkEvents (socket->priv->fd,
1983 socket->priv->event,
1986 socket->priv->current_events |= events.lNetworkEvents;
1987 if (events.lNetworkEvents & FD_WRITE &&
1988 events.iErrorCode[FD_WRITE_BIT] != 0)
1989 socket->priv->current_errors |= FD_WRITE;
1990 if (events.lNetworkEvents & FD_CONNECT &&
1991 events.iErrorCode[FD_CONNECT_BIT] != 0)
1992 socket->priv->current_errors |= FD_CONNECT;
1996 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
1997 condition |= G_IO_IN;
1999 if (socket->priv->current_events & FD_CLOSE ||
2000 socket->priv->closed)
2001 condition |= G_IO_HUP;
2003 /* Never report both G_IO_OUT and HUP, these are
2004 mutually exclusive (can't write to a closed socket) */
2005 if ((condition & G_IO_HUP) == 0 &&
2006 socket->priv->current_events & FD_WRITE)
2008 if (socket->priv->current_errors & FD_WRITE)
2009 condition |= G_IO_ERR;
2011 condition |= G_IO_OUT;
2015 if (socket->priv->current_events & FD_CONNECT)
2017 if (socket->priv->current_errors & FD_CONNECT)
2018 condition |= (G_IO_HUP | G_IO_ERR);
2020 condition |= G_IO_OUT;
2031 GIOCondition condition;
2032 GCancellable *cancellable;
2033 GPollFD cancel_pollfd;
2034 GIOCondition result_condition;
2038 winsock_prepare (GSource *source,
2041 GWinsockSource *winsock_source = (GWinsockSource *)source;
2042 GIOCondition current_condition;
2044 current_condition = update_condition (winsock_source->socket);
2046 if (g_cancellable_is_cancelled (winsock_source->cancellable))
2048 winsock_source->result_condition = current_condition;
2052 if ((winsock_source->condition & current_condition) != 0)
2054 winsock_source->result_condition = current_condition;
2062 winsock_check (GSource *source)
2064 GWinsockSource *winsock_source = (GWinsockSource *)source;
2065 GIOCondition current_condition;
2067 current_condition = update_condition (winsock_source->socket);
2069 if (g_cancellable_is_cancelled (winsock_source->cancellable))
2071 winsock_source->result_condition = current_condition;
2075 if ((winsock_source->condition & current_condition) != 0)
2077 winsock_source->result_condition = current_condition;
2085 winsock_dispatch (GSource *source,
2086 GSourceFunc callback,
2089 GSocketSourceFunc func = (GSocketSourceFunc)callback;
2090 GWinsockSource *winsock_source = (GWinsockSource *)source;
2092 return (*func) (user_data,
2093 winsock_source->result_condition & winsock_source->condition);
2097 winsock_finalize (GSource *source)
2099 GWinsockSource *winsock_source = (GWinsockSource *)source;
2102 socket = winsock_source->socket;
2104 remove_condition_watch (socket, &winsock_source->condition);
2105 g_object_unref (socket);
2107 if (winsock_source->cancellable)
2108 g_object_unref (winsock_source->cancellable);
2111 static GSourceFuncs winsock_funcs =
2120 winsock_source_new (GSocket *socket,
2121 GIOCondition condition,
2122 GCancellable *cancellable)
2125 GWinsockSource *winsock_source;
2127 ensure_event (socket);
2129 if (socket->priv->event == WSA_INVALID_EVENT)
2131 g_warning ("Failed to create WSAEvent");
2132 return g_source_new (&broken_funcs, sizeof (GSource));
2135 condition |= G_IO_HUP | G_IO_ERR;
2137 source = g_source_new (&winsock_funcs, sizeof (GWinsockSource));
2138 winsock_source = (GWinsockSource *)source;
2140 winsock_source->socket = g_object_ref (socket);
2141 winsock_source->condition = condition;
2142 add_condition_watch (socket, &winsock_source->condition);
2146 winsock_source->cancellable = g_object_ref (cancellable);
2147 g_cancellable_make_pollfd (cancellable,
2148 &winsock_source->cancel_pollfd);
2149 g_source_add_poll (source, &winsock_source->cancel_pollfd);
2152 winsock_source->pollfd.fd = (gintptr) socket->priv->event;
2153 winsock_source->pollfd.events = condition;
2154 g_source_add_poll (source, &winsock_source->pollfd);
2161 * g_socket_create_source:
2162 * @socket: a #GSocket
2163 * @condition: a #GIOCondition mask to monitor
2164 * @cancellable: a %GCancellable or %NULL
2166 * Creates a %GSource that can be attached to a %GMainContext to monitor
2167 * for the availibility of the specified @condition on the socket.
2169 * The callback on the source is of the #GSocketSourceFunc type.
2171 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2172 * these conditions will always be reported output if they are true.
2174 * @cancellable if not %NULL can be used to cancel the source, which will
2175 * cause the source to trigger, reporting the current condition. You can
2176 * check for this in the callback using g_cancellable_is_cancelled().
2178 * Returns: a newly allocated %GSource, free with g_source_unref().
2183 g_socket_create_source (GSocket *socket,
2184 GIOCondition condition,
2185 GCancellable *cancellable)
2188 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
2191 source = winsock_source_new (socket, condition, cancellable);
2193 source =_g_fd_source_new (socket->priv->fd, condition, cancellable);
2199 * g_socket_condition_check:
2200 * @socket: a #GSocket
2201 * @condition: a #GIOCondition mask to check
2203 * Checks on the readiness of @socket to perform operations. The
2204 * operations specified in @condition are checked for and masked
2205 * against the currently-satisfied conditions on @socket. The result
2208 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2209 * these conditions will always be set in the output if they are true.
2211 * This call never blocks.
2213 * Returns: the @GIOCondition mask of the current state
2218 g_socket_condition_check (GSocket *socket,
2219 GIOCondition condition)
2221 if (!check_socket (socket, NULL))
2226 GIOCondition current_condition;
2228 condition |= G_IO_ERR | G_IO_HUP;
2230 add_condition_watch (socket, &condition);
2231 current_condition = update_condition (socket);
2232 remove_condition_watch (socket, &condition);
2233 return condition & current_condition;
2239 poll_fd.fd = socket->priv->fd;
2240 poll_fd.events = condition;
2243 result = g_poll (&poll_fd, 1, 0);
2244 while (result == -1 && get_socket_errno () == EINTR);
2246 return poll_fd.revents;
2252 * g_socket_condition_wait:
2253 * @socket: a #GSocket
2254 * @condition: a #GIOCondition mask to wait for
2255 * @cancellable: a #GCancellable, or %NULL
2256 * @error: a #GError pointer, or %NULL
2258 * Waits for @condition to become true on @socket. When the condition
2259 * becomes true, %TRUE is returned.
2261 * If @cancellable is cancelled before the condition becomes true then
2262 * %FALSE is returned and @error, if non-%NULL, is set to %G_IO_ERROR_CANCELLED.
2264 * Returns: %TRUE if the condition was met, %FALSE otherwise
2269 g_socket_condition_wait (GSocket *socket,
2270 GIOCondition condition,
2271 GCancellable *cancellable,
2274 if (!check_socket (socket, error))
2277 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2282 GIOCondition current_condition;
2288 /* Always check these */
2289 condition |= G_IO_ERR | G_IO_HUP;
2291 add_condition_watch (socket, &condition);
2294 events[num_events++] = socket->priv->event;
2298 g_cancellable_make_pollfd (cancellable, &cancel_fd);
2299 events[num_events++] = (WSAEVENT)cancel_fd.fd;
2302 current_condition = update_condition (socket);
2303 while ((condition & current_condition) == 0)
2305 res = WSAWaitForMultipleEvents(num_events, events,
2306 FALSE, WSA_INFINITE, FALSE);
2307 if (res == WSA_WAIT_FAILED)
2309 int errsv = get_socket_errno ();
2311 g_set_error (error, G_IO_ERROR,
2312 socket_io_error_from_errno (errsv),
2313 _("Waiting for socket condition: %s"),
2314 socket_strerror (errsv));
2318 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2321 current_condition = update_condition (socket);
2323 remove_condition_watch (socket, &condition);
2325 return (condition & current_condition) != 0;
2333 poll_fd[0].fd = socket->priv->fd;
2334 poll_fd[0].events = condition;
2339 g_cancellable_make_pollfd (cancellable, &poll_fd[1]);
2344 result = g_poll (poll_fd, num, -1);
2345 while (result == -1 && get_socket_errno () == EINTR);
2347 return cancellable == NULL ||
2348 !g_cancellable_set_error_if_cancelled (cancellable, error);
2355 * @socket: a #GSocket
2356 * @address: a #GSocketAddress, or %NULL
2357 * @vectors: an array of #GOutputVector structs
2358 * @num_vectors: the number of elements in @vectors, or -1
2359 * @messages: a pointer to an array of #GSocketControlMessages, or
2361 * @num_messages: number of elements in @messages, or -1.
2362 * @flags: an int containing #GSocketMsgFlags flags
2363 * @error: #GError for error reporting, or %NULL to ignore.
2365 * Send data to @address on @socket. This is the most complicated and
2366 * fully-featured version of this call. For easier use, see
2367 * g_socket_send() and g_socket_send_to().
2369 * If @address is %NULL then the message is sent to the default receiver
2370 * (set by g_socket_connect()).
2372 * @vector must point to an array of #GOutputVector structs and
2373 * @num_vectors must be the length of this array. These structs
2374 * describe the buffers that the sent data will be gathered from.
2375 * If @num_vector is -1, then @vector is assumed to be terminated
2376 * by a #GOutputVector with a %NULL buffer pointer.
2379 * @messages, if non-%NULL, is taken to point to an array of @num_messages
2380 * #GSocketControlMessage instances. These correspond to the control
2381 * messages to be sent on the socket.
2382 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
2385 * @flags modify how the message sent. The commonly available arguments
2386 * for this is available in the #GSocketMsgFlags enum, but the
2387 * values there are the same as the system values, and the flags
2388 * are passed in as-is, so you can pass in system specific flags too.
2390 * If the socket is in blocking mode the call will block until there is
2391 * space for the data in the socket queue. If there is no space available
2392 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2393 * will be returned. To be notified of available space, wait for the %G_IO_OUT
2396 * Note that on Windows you can't rely on a %G_IO_OUT condition
2397 * not producing a %G_IO_ERROR_WOULD_BLOCK error, as this is how Winsock
2398 * write notification works. However, robust apps should always be able to
2399 * handle this since it can easily appear in other cases too.
2401 * On error -1 is returned and @error is set accordingly.
2403 * Returns: Number of bytes read, or -1 on error
2408 g_socket_send_message (GSocket *socket,
2409 GSocketAddress *address,
2410 GOutputVector *vectors,
2412 GSocketControlMessage **messages,
2417 GOutputVector one_vector;
2420 if (!check_socket (socket, error))
2423 if (num_vectors == -1)
2425 for (num_vectors = 0;
2426 vectors[num_vectors].buffer != NULL;
2431 if (num_messages == -1)
2433 for (num_messages = 0;
2434 messages != NULL && messages[num_messages] != NULL;
2439 if (num_vectors == 0)
2443 one_vector.buffer = &zero;
2444 one_vector.size = 1;
2446 vectors = &one_vector;
2457 msg.msg_namelen = g_socket_address_get_native_size (address);
2458 msg.msg_name = g_alloca (msg.msg_namelen);
2459 g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen);
2464 /* this entire expression will be evaluated at compile time */
2465 if (sizeof *msg.msg_iov == sizeof *vectors &&
2466 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2467 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2468 G_STRUCT_OFFSET (GOutputVector, buffer) &&
2469 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2470 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2471 G_STRUCT_OFFSET (GOutputVector, size))
2472 /* ABI is compatible */
2474 msg.msg_iov = (struct iovec *) vectors;
2475 msg.msg_iovlen = num_vectors;
2478 /* ABI is incompatible */
2482 msg.msg_iov = g_newa (struct iovec, num_vectors);
2483 for (i = 0; i < num_vectors; i++)
2485 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
2486 msg.msg_iov[i].iov_len = vectors[i].size;
2488 msg.msg_iovlen = num_vectors;
2494 struct cmsghdr *cmsg;
2497 msg.msg_controllen = 0;
2498 for (i = 0; i < num_messages; i++)
2499 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
2501 msg.msg_control = g_alloca (msg.msg_controllen);
2503 cmsg = CMSG_FIRSTHDR (&msg);
2504 for (i = 0; i < num_messages; i++)
2506 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
2507 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
2508 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
2509 g_socket_control_message_serialize (messages[i],
2511 cmsg = CMSG_NXTHDR (&msg, cmsg);
2513 g_assert (cmsg == NULL);
2518 if (socket->priv->blocking &&
2519 !g_socket_condition_wait (socket,
2520 G_IO_OUT, NULL, error))
2523 result = sendmsg (socket->priv->fd, &msg, flags);
2526 int errsv = get_socket_errno ();
2531 if (socket->priv->blocking &&
2532 (errsv == EWOULDBLOCK ||
2536 g_set_error (error, G_IO_ERROR,
2537 socket_io_error_from_errno (errsv),
2538 _("Error sending message: %s"), socket_strerror (errsv));
2549 struct sockaddr_storage addr;
2556 /* Win32 doesn't support control messages.
2557 Actually this is possible for raw and datagram sockets
2558 via WSASendMessage on Vista or later, but that doesn't
2560 if (num_messages != 0)
2562 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2563 _("GSocketControlMessage not supported on windows"));
2568 bufs = g_newa (WSABUF, num_vectors);
2569 for (i = 0; i < num_vectors; i++)
2571 bufs[i].buf = (char *)vectors[i].buffer;
2572 bufs[i].len = (gulong)vectors[i].size;
2578 addrlen = g_socket_address_get_native_size (address);
2579 g_socket_address_to_native (address, &addr, sizeof addr);
2584 if (socket->priv->blocking &&
2585 !g_socket_condition_wait (socket,
2586 G_IO_OUT, NULL, error))
2590 result = WSASendTo (socket->priv->fd,
2593 (const struct sockaddr *)&addr, addrlen,
2596 result = WSASend (socket->priv->fd,
2603 int errsv = get_socket_errno ();
2605 if (errsv == WSAEINTR)
2608 if (errsv == WSAEWOULDBLOCK)
2609 win32_unset_event_mask (socket, FD_WRITE);
2611 if (socket->priv->blocking &&
2612 errsv == WSAEWOULDBLOCK)
2615 g_set_error (error, G_IO_ERROR,
2616 socket_io_error_from_errno (errsv),
2617 _("Error sending message: %s"), socket_strerror (errsv));
2630 * g_socket_receive_message:
2631 * @socket: a #GSocket
2632 * @address: a pointer to a #GSocketAddress pointer, or %NULL
2633 * @vectors: an array of #GInputVector structs
2634 * @num_vectors: the number of elements in @vectors, or -1
2635 * @messages: a pointer which will be filled with an array of
2636 * #GSocketControlMessages, or %NULL
2637 * @num_messages: a pointer which will be filled with the number of
2638 * elements in @messages, or %NULL
2639 * @flags: a pointer to an int containing #GSocketMsgFlags flags
2640 * @error: a #GError pointer, or %NULL
2642 * Receive data from a socket. This is the most complicated and
2643 * fully-featured version of this call. For easier use, see
2644 * g_socket_receive() and g_socket_receive_from().
2646 * If @address is non-%NULL then @address will be set equal to the
2647 * source address of the received packet.
2648 * @address is owned by the caller.
2650 * @vector must point to an array of #GInputVector structs and
2651 * @num_vectors must be the length of this array. These structs
2652 * describe the buffers that received data will be scattered into.
2653 * If @num_vector is -1, then @vector is assumed to be terminated
2654 * by a #GInputVector with a %NULL buffer pointer.
2656 * As a special case, if the size of the array is zero (in which case,
2657 * @vectors may of course be %NULL), then a single byte is received
2658 * and discarded. This is to facilitate the common practice of
2659 * sending a single '\0' byte for the purposes of transferring
2662 * @messages, if non-%NULL, is taken to point to a pointer that will
2663 * be set to point to a newly-allocated array of
2664 * #GSocketControlMessage instances. These correspond to the control
2665 * messages received from the kernel, one #GSocketControlMessage per
2666 * message from the kernel. This array is %NULL-terminated and must be
2667 * freed by the caller using g_free().
2669 * @num_messages, if non-%NULL, will be set to the number of control
2670 * messages received.
2672 * If both @messages and @num_messages are non-%NULL, then
2673 * @num_messages gives the number of #GSocketControlMessage instances
2674 * in @messages (ie: not including the %NULL terminator).
2676 * @flags is an in/out parameter. The commonly available arguments
2677 * for this is available in the #GSocketMsgFlags enum, but the
2678 * values there are the same as the system values, and the flags
2679 * are passed in as-is, so you can pass in system specific flags too.
2681 * If the socket is in blocking mode the call will block until there is
2682 * some data to receive or there is an error. If there is no data available
2683 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2684 * will be returned. To be notified of available data, wait for the %G_IO_IN
2687 * On error -1 is returned and @error is set accordingly.
2689 * Returns: Number of bytes read, or -1 on error
2694 g_socket_receive_message (GSocket *socket,
2695 GSocketAddress **address,
2696 GInputVector *vectors,
2698 GSocketControlMessage ***messages,
2703 GInputVector one_vector;
2706 if (!check_socket (socket, error))
2709 if (num_vectors == -1)
2711 for (num_vectors = 0;
2712 vectors[num_vectors].buffer != NULL;
2717 if (num_vectors == 0)
2719 one_vector.buffer = &one_byte;
2720 one_vector.size = 1;
2722 vectors = &one_vector;
2729 struct sockaddr_storage one_sockaddr;
2734 msg.msg_name = &one_sockaddr;
2735 msg.msg_namelen = sizeof (struct sockaddr_storage);
2739 msg.msg_name = NULL;
2740 msg.msg_namelen = 0;
2744 /* this entire expression will be evaluated at compile time */
2745 if (sizeof *msg.msg_iov == sizeof *vectors &&
2746 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2747 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2748 G_STRUCT_OFFSET (GInputVector, buffer) &&
2749 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2750 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2751 G_STRUCT_OFFSET (GInputVector, size))
2752 /* ABI is compatible */
2754 msg.msg_iov = (struct iovec *) vectors;
2755 msg.msg_iovlen = num_vectors;
2758 /* ABI is incompatible */
2762 msg.msg_iov = g_newa (struct iovec, num_vectors);
2763 for (i = 0; i < num_vectors; i++)
2765 msg.msg_iov[i].iov_base = vectors[i].buffer;
2766 msg.msg_iov[i].iov_len = vectors[i].size;
2768 msg.msg_iovlen = num_vectors;
2772 msg.msg_control = g_alloca (2048);
2773 msg.msg_controllen = 2048;
2777 msg.msg_flags = *flags;
2784 if (socket->priv->blocking &&
2785 !g_socket_condition_wait (socket,
2786 G_IO_IN, NULL, error))
2789 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
2793 int errsv = get_socket_errno ();
2798 if (socket->priv->blocking &&
2799 (errsv == EWOULDBLOCK ||
2803 g_set_error (error, G_IO_ERROR,
2804 socket_io_error_from_errno (errsv),
2805 _("Error receiving message: %s"), socket_strerror (errsv));
2812 /* decode address */
2813 if (address != NULL)
2815 if (msg.msg_namelen > 0)
2816 *address = g_socket_address_new_from_native (msg.msg_name,
2822 /* decode control messages */
2824 GSocketControlMessage **my_messages = NULL;
2825 gint allocated = 0, index = 0;
2826 const gchar *scm_pointer;
2827 struct cmsghdr *cmsg;
2830 scm_pointer = (const gchar *) msg.msg_control;
2831 scm_size = msg.msg_controllen;
2833 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
2835 GSocketControlMessage *message;
2837 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
2839 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
2841 if (message == NULL)
2842 /* We've already spewed about the problem in the
2843 deserialization code, so just continue */
2846 if (index == allocated)
2848 /* estimated 99% case: exactly 1 control message */
2849 allocated = MIN (allocated * 2, 1);
2850 my_messages = g_new (GSocketControlMessage *, (allocated + 1));
2854 my_messages[index++] = message;
2858 *num_messages = index;
2862 my_messages[index++] = NULL;
2863 *messages = my_messages;
2869 /* free all those messages we just constructed.
2870 * we have to do it this way if the user ignores the
2871 * messages so that we will close any received fds.
2873 for (i = 0; i < index; i++)
2874 g_object_unref (my_messages[i]);
2875 g_free (my_messages);
2879 /* capture the flags */
2881 *flags = msg.msg_flags;
2887 struct sockaddr_storage addr;
2889 DWORD bytes_received;
2896 bufs = g_newa (WSABUF, num_vectors);
2897 for (i = 0; i < num_vectors; i++)
2899 bufs[i].buf = (char *)vectors[i].buffer;
2900 bufs[i].len = (gulong)vectors[i].size;
2912 if (socket->priv->blocking &&
2913 !g_socket_condition_wait (socket,
2914 G_IO_IN, NULL, error))
2917 addrlen = sizeof addr;
2919 result = WSARecvFrom (socket->priv->fd,
2921 &bytes_received, &win_flags,
2922 (struct sockaddr *)&addr, &addrlen,
2925 result = WSARecv (socket->priv->fd,
2927 &bytes_received, &win_flags,
2931 int errsv = get_socket_errno ();
2933 if (errsv == WSAEINTR)
2936 win32_unset_event_mask (socket, FD_READ);
2938 if (socket->priv->blocking &&
2939 errsv == WSAEWOULDBLOCK)
2942 g_set_error (error, G_IO_ERROR,
2943 socket_io_error_from_errno (errsv),
2944 _("Error receiving message: %s"), socket_strerror (errsv));
2948 win32_unset_event_mask (socket, FD_READ);
2952 /* decode address */
2953 if (address != NULL)
2956 *address = g_socket_address_new_from_native (&addr, addrlen);
2961 /* capture the flags */
2965 return bytes_received;
2970 #define __G_SOCKET_C__
2971 #include "gioaliasdef.c"