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>
35 # include <netinet/in.h>
36 # include <arpa/inet.h>
40 # include <sys/types.h>
42 # include <winsock2.h>
47 #include "gcancellable.h"
48 #include "gioenumtypes.h"
49 #include "ginitable.h"
50 #include "gasynchelper.h"
60 * @short_description: Low-level socket object
62 * @see_also: #GInitable
64 * A #GSocket is a low-level networking primitive. It is a more or less
65 * direct mapping of the BSD socket API in a portable GObject based API.
66 * It supports both the unix socket implementations and winsock2 on Windows.
68 * #GSocket is the platform independent base upon which the higher level
69 * network primitives are based. Applications are not typically meant to
70 * use it directly, but rather through classes like #GSocketClient,
71 * #GSocketService and #GSocketConnection. However there may be cases where
72 * direct use of #GSocket is useful.
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 get_protocol_name (int protocol_id)
410 struct protoent *protoent;
411 #ifdef HAVE_GETPROTOBYNUMBER_R
413 struct protoent my_protoent;
416 if (protocol_id == 0)
419 if (protocol_id == -1)
420 return g_strdup ("unknown");
422 #ifdef HAVE_GETPROTOBYNUMBER_R
424 getprotobynumber_r (protocol_id,
425 &my_protoent, buffer, sizeof (buffer),
428 protoent = getprotobynumber (protocol_id);
431 if (protoent == NULL)
432 return g_strdup_printf ("proto-%d", protocol_id);
434 return g_strdup (protoent->p_name);
438 * g_socket_protocol_id_lookup_by_name:
439 * @protocol_name: The name of a protocol, or %NULL
441 * Tries to look up the protocol id for a given
442 * protocol name. If the protocol name is not known
443 * on this system it returns -1.
445 * If @protocol_name is %NULL (default protocol) then
448 * Returns: a protocol id, or -1 if unknown
453 g_socket_protocol_id_lookup_by_name (const char *protocol_name)
455 struct protoent *protoent;
457 #ifdef HAVE_GETPROTOBYNAME_R
459 struct protoent my_protoent;
465 #ifdef HAVE_GETPROTOBYNAME_R
467 getprotobyname_r (protocol_name,
468 &my_protoent, buffer, sizeof (buffer),
471 protoent = getprotobyname (protocol_name);
474 if (protoent == NULL)
476 if (g_str_has_prefix (protocol_name, "proto-"))
477 return atoi (protocol_name + strlen ("proto-"));
480 protocol = protoent->p_proto;
486 g_socket_create_socket (GSocketFamily family,
496 case G_SOCKET_TYPE_STREAM:
497 native_type = SOCK_STREAM;
500 case G_SOCKET_TYPE_DATAGRAM:
501 native_type = SOCK_DGRAM;
504 case G_SOCKET_TYPE_SEQPACKET:
505 native_type = SOCK_SEQPACKET;
509 g_assert_not_reached ();
512 if (protocol_id == -1)
514 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
515 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
520 native_type |= SOCK_CLOEXEC;
522 fd = socket (family, native_type, protocol_id);
526 int errsv = get_socket_errno ();
528 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
529 _("Unable to create socket: %s"), socket_strerror (errsv));
536 /* We always want to set close-on-exec to protect users. If you
537 need to so some weird inheritance to exec you can re-enable this
538 using lower level hacks with g_socket_get_fd(). */
539 flags = fcntl (fd, F_GETFD, 0);
541 (flags & FD_CLOEXEC) == 0)
544 fcntl (fd, F_SETFD, flags);
553 g_socket_constructed (GObject *object)
555 GSocket *socket = G_SOCKET (object);
557 if (socket->priv->fd >= 0)
558 /* create socket->priv info from the fd */
559 g_socket_details_from_fd (socket);
562 /* create the fd from socket->priv info */
563 socket->priv->fd = g_socket_create_socket (socket->priv->family,
565 socket->priv->protocol,
566 &socket->priv->construct_error);
568 /* Always use native nonblocking sockets, as
569 windows sets sockets to nonblocking automatically
570 in certain operations. This way we make things work
571 the same on all platforms */
572 if (socket->priv->fd != -1)
573 set_fd_nonblocking (socket->priv->fd);
577 g_socket_get_property (GObject *object,
582 GSocket *socket = G_SOCKET (object);
587 g_value_set_enum (value, socket->priv->family);
591 g_value_set_enum (value, socket->priv->type);
595 g_value_set_int (value, socket->priv->protocol);
599 g_value_set_int (value, socket->priv->fd);
603 g_value_set_boolean (value, socket->priv->blocking);
606 case PROP_LISTEN_BACKLOG:
607 g_value_set_int (value, socket->priv->listen_backlog);
611 g_value_set_boolean (value, socket->priv->keepalive);
614 case PROP_LOCAL_ADDRESS:
615 g_value_set_object (value, socket->priv->local_address);
618 case PROP_REMOTE_ADDRESS:
619 g_value_set_object (value, socket->priv->remote_address);
623 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
628 g_socket_set_property (GObject *object,
633 GSocket *socket = G_SOCKET (object);
638 socket->priv->family = g_value_get_enum (value);
642 socket->priv->type = g_value_get_enum (value);
646 socket->priv->protocol = g_value_get_int (value);
650 socket->priv->fd = g_value_get_int (value);
654 g_socket_set_blocking (socket, g_value_get_boolean (value));
657 case PROP_LISTEN_BACKLOG:
658 g_socket_set_listen_backlog (socket, g_value_get_int (value));
662 g_socket_set_keepalive (socket, g_value_get_boolean (value));
666 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
671 g_socket_finalize (GObject *object)
673 GSocket *socket = G_SOCKET (object);
675 g_clear_error (&socket->priv->construct_error);
677 if (socket->priv->fd != -1 &&
678 !socket->priv->closed)
679 g_socket_close (socket, NULL);
682 g_assert (socket->priv->requested_conditions == NULL);
685 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
686 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
690 g_socket_dispose (GObject *object)
692 GSocket *socket = G_SOCKET (object);
694 if (socket->priv->local_address)
696 g_object_unref (socket->priv->local_address);
697 socket->priv->local_address = NULL;
700 if (socket->priv->remote_address)
702 g_object_unref (socket->priv->remote_address);
703 socket->priv->remote_address = NULL;
706 if (G_OBJECT_CLASS (g_socket_parent_class)->dispose)
707 (*G_OBJECT_CLASS (g_socket_parent_class)->dispose) (object);
711 g_socket_class_init (GSocketClass *klass)
713 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
716 /* Make sure winsock has been initialized */
717 type = g_inet_address_get_type ();
719 g_type_class_add_private (klass, sizeof (GSocketPrivate));
721 gobject_class->finalize = g_socket_finalize;
722 gobject_class->dispose = g_socket_dispose;
723 gobject_class->constructed = g_socket_constructed;
724 gobject_class->set_property = g_socket_set_property;
725 gobject_class->get_property = g_socket_get_property;
727 g_object_class_install_property (gobject_class, PROP_FAMILY,
728 g_param_spec_enum ("family",
730 P_("The sockets address family"),
731 G_TYPE_SOCKET_FAMILY,
732 G_SOCKET_FAMILY_INVALID,
733 G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
735 g_object_class_install_property (gobject_class, PROP_TYPE,
736 g_param_spec_enum ("type",
738 P_("The sockets type"),
740 G_SOCKET_TYPE_STREAM,
741 G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
743 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
744 g_param_spec_int ("protocol",
745 P_("Socket protocol"),
746 P_("The id of the protocol to use, or -1 for unknown"),
750 G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
752 g_object_class_install_property (gobject_class, PROP_FD,
753 g_param_spec_int ("fd",
754 P_("File descriptor"),
755 P_("The sockets file descriptor"),
759 G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
761 g_object_class_install_property (gobject_class, PROP_BLOCKING,
762 g_param_spec_boolean ("blocking",
764 P_("Whether or not I/O on this socket is blocking"),
766 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
768 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
769 g_param_spec_int ("listen-backlog",
770 P_("Listen backlog"),
771 P_("outstanding connections in the listen queue"),
775 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
777 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
778 g_param_spec_boolean ("keepalive",
779 P_("Keep connection alive"),
780 P_("Keep connection alive by sending periodic pings"),
782 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
784 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
785 g_param_spec_object ("local-address",
787 P_("The local address the socket is bound to"),
788 G_TYPE_SOCKET_ADDRESS,
789 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
791 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
792 g_param_spec_object ("remote-address",
793 P_("Remote address"),
794 P_("The remote address the socket is connected to"),
795 G_TYPE_SOCKET_ADDRESS,
796 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
800 g_socket_initable_iface_init (GInitableIface *iface)
802 iface->init = g_socket_initable_init;
806 g_socket_init (GSocket *socket)
808 socket->priv = G_TYPE_INSTANCE_GET_PRIVATE (socket, G_TYPE_SOCKET, GSocketPrivate);
810 socket->priv->fd = -1;
811 socket->priv->blocking = TRUE;
812 socket->priv->listen_backlog = 10;
813 socket->priv->construct_error = NULL;
814 socket->priv->remote_address = NULL;
815 socket->priv->local_address = NULL;
817 socket->priv->event = WSA_INVALID_EVENT;
822 g_socket_initable_init (GInitable *initable,
823 GCancellable *cancellable,
828 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
830 socket = G_SOCKET (initable);
832 if (cancellable != NULL)
834 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
835 _("Cancellable initialization not supported"));
839 socket->priv->inited = TRUE;
841 if (socket->priv->construct_error)
844 *error = g_error_copy (socket->priv->construct_error);
854 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
855 * @type: the socket type to use.
856 * @protocol_id: the id of the protocol to use, or 0 for default.
857 * @error: #GError for error reporting, or %NULL to ignore.
859 * Creates a new #GSocket with the defined family, type and protocol.
860 * If @protocol is %NULL the default protocol type for the family and
863 * The @protocol is a family and type specific int that specifies what
864 * kind of protocol to use. Many families only support one protocol,
865 * and use 0 for this, others support several and using 0 means
866 * to use the default protocol for the family and type. To use
867 * other protocol, you can use g_socket_protocol_id_lookup_by_name()
868 * to look up the protocol by name, or if you known the system specific
869 * protocol id you can use that.
871 * Returns: a #GSocket or %NULL on error.
872 * Free the returned object with g_object_unref().
877 g_socket_new (GSocketFamily family,
882 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
886 "protocol", protocol_id,
891 * g_socket_new_from_fd:
892 * @fd: a native socket file descriptor.
893 * @error: #GError for error reporting, or %NULL to ignore.
895 * Creates a new #GSocket from a native file descriptor
896 * or winsock SOCKET handle.
898 * This reads all the settings from the file descriptor so that
899 * all properties should work. Note that the file descriptor
900 * will be set to non-blocking mode, independent on the blocking
901 * mode of the #GSocket.
903 * Returns: a #GSocket or %NULL on error.
904 * Free the returned object with g_object_unref().
909 g_socket_new_from_fd (gint fd,
912 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
919 * g_socket_set_blocking:
920 * @socket: a #GSocket.
921 * @blocking: Whether to use blocking I/O or not.
923 * Sets the blocking mode of the socket. In blocking mode
924 * all operations block until they succeed or there is an error. In
925 * non-blocking mode all functions return results immediately or
926 * with a %G_IO_ERROR_WOULD_BLOCK error.
928 * All sockets are created in blocking mode. However, note that the
929 * platform level socket is always non-blocking, and blocking mode
930 * is a GSocket level feature.
935 g_socket_set_blocking (GSocket *socket,
938 g_return_if_fail (G_IS_SOCKET (socket));
940 blocking = !!blocking;
942 if (socket->priv->blocking == blocking)
945 socket->priv->blocking = blocking;
946 g_object_notify (G_OBJECT (socket), "blocking");
950 * g_socket_get_blocking:
951 * @socket: a #GSocket.
953 * Gets the blocking mode of the socket. For details on blocking I/O,
954 * see g_socket_set_blocking().
956 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
961 g_socket_get_blocking (GSocket *socket)
963 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
965 return socket->priv->blocking;
969 * g_socket_set_keepalive:
970 * @socket: a #GSocket.
971 * @keepalive: Whether to use try to keep the connection alive or not.
973 * Setting @keepalive to %TRUE enables the sending of periodic ping requests
974 * on idle connections in order to keep the connection alive. This is only
975 * useful for connection oriented sockets. The exact period used between
976 * each ping is system and protocol dependent.
978 * Sending keepalive requests like this has a few disadvantages. For instance,
979 * it uses more network bandwidth, and it makes your application more sensitive
980 * to temporary outages in the network (i.e. if a cable is pulled your otherwise
981 * idle connection could be terminated, whereas otherwise it would survive unless
982 * actually used before the cable was reinserted). However, it is sometimes
983 * useful to ensure that connections are eventually terminated if e.g. the
984 * remote side is disconnected, so as to avoid leaking resources forever.
989 g_socket_set_keepalive (GSocket *socket,
994 g_return_if_fail (G_IS_SOCKET (socket));
996 keepalive = !!keepalive;
997 if (socket->priv->keepalive == keepalive)
1000 value = (gint) keepalive;
1001 if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_KEEPALIVE,
1002 (gpointer) &value, sizeof (value)) < 0)
1004 int errsv = get_socket_errno ();
1005 g_warning ("error setting keepalive: %s", socket_strerror (errsv));
1009 socket->priv->keepalive = keepalive;
1010 g_object_notify (G_OBJECT (socket), "keepalive");
1014 * g_socket_get_keepalive:
1015 * @socket: a #GSocket.
1017 * Gets the keepalive mode of the socket. For details on this,
1018 * see g_socket_set_keepalive().
1020 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1025 g_socket_get_keepalive (GSocket *socket)
1027 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1029 return socket->priv->keepalive;
1033 * g_socket_get_listen_backlog:
1034 * @socket: a #GSocket.
1036 * Gets the listen backlog setting of the socket. For details on this,
1037 * see g_socket_set_listen_backlog().
1039 * Returns: the maximum number of pending connections.
1044 g_socket_get_listen_backlog (GSocket *socket)
1046 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1048 return socket->priv->listen_backlog;
1052 * g_socket_set_listen_backlog:
1053 * @socket: a #GSocket.
1054 * @backlog: the maximum number of pending connections.
1056 * Sets the maximum number of outstanding connections allowed
1057 * when listening on this socket. If more clients than this are
1058 * connecting to the socket and the application is not handling them
1059 * on time then the new connections will be refused.
1064 g_socket_set_listen_backlog (GSocket *socket,
1067 g_return_if_fail (G_IS_SOCKET (socket));
1069 if (backlog != socket->priv->listen_backlog)
1071 socket->priv->listen_backlog = backlog;
1072 g_object_notify (G_OBJECT (socket), "listen-backlog");
1077 * g_socket_get_family:
1078 * @socket: a #GSocket.
1080 * Gets the socket family of the socket.
1082 * Returns: a #GSocketFamily
1087 g_socket_get_family (GSocket *socket)
1089 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1091 return socket->priv->family;
1095 * g_socket_get_socket_type:
1096 * @socket: a #GSocket.
1098 * Gets the socket type of the socket.
1100 * Returns: a #GSocketType
1105 g_socket_get_socket_type (GSocket *socket)
1107 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1109 return socket->priv->type;
1113 * g_socket_get_protocol_id:
1114 * @socket: a #GSocket.
1116 * Gets the socket protocol id the socket was created with.
1117 * In case the protocol is unknown, -1 is returned.
1119 * Returns: a protocol id, or -1 if unknown
1124 g_socket_get_protocol_id (GSocket *socket)
1126 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1128 return socket->priv->protocol;
1132 * g_socket_get_protocol_name:
1133 * @socket: a #GSocket.
1135 * Gets the socket protocol type name the socket was created with.
1136 * This can be %NULL if the socket was created with a NULL protocol.
1138 * Returns: a string or %NULL, free with g_free
1143 g_socket_get_protocol_name (GSocket *socket)
1145 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1147 return get_protocol_name (socket->priv->protocol);
1152 * @socket: a #GSocket.
1154 * Returns the underlying OS socket object. On unix this
1155 * is a socket file descriptor, and on windows this is
1156 * a Winsock2 SOCKET handle. This may be useful for
1157 * doing platform specific or otherwise unusual operations
1160 * Returns: the file descriptor of the socket.
1165 g_socket_get_fd (GSocket *socket)
1167 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1169 return socket->priv->fd;
1173 * g_socket_get_local_address:
1174 * @socket: a #GSocket.
1175 * @error: #GError for error reporting, or %NULL to ignore.
1177 * Try to get the local address of a bound socket. This is only
1178 * useful if the socket has been bound to a local address.
1180 * Returns: a #GSocketAddress or %NULL on error.
1185 g_socket_get_local_address (GSocket *socket,
1191 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1193 if (socket->priv->local_address)
1194 return socket->priv->local_address;
1196 if (getsockname (socket->priv->fd, (struct sockaddr *) buffer, &len) < 0)
1198 int errsv = get_socket_errno ();
1199 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1200 _("could not get local address: %s"), socket_strerror (errsv));
1204 socket->priv->local_address = g_socket_address_new_from_native (buffer, len);
1205 return socket->priv->local_address;
1209 * g_socket_get_remote_address:
1210 * @socket: a #GSocket.
1211 * @error: #GError for error reporting, or %NULL to ignore.
1213 * Try to get the remove address of a connected socket. This is only
1214 * useful for connection oriented sockets that have been connected.
1216 * Returns: a #GSocketAddress or %NULL on error.
1221 g_socket_get_remote_address (GSocket *socket,
1227 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1229 if (socket->priv->remote_address)
1230 return socket->priv->remote_address;
1232 if (getpeername (socket->priv->fd, (struct sockaddr *) buffer, &len) < 0)
1234 int errsv = get_socket_errno ();
1235 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1236 _("could not get remote address: %s"), socket_strerror (errsv));
1240 socket->priv->remote_address = g_socket_address_new_from_native (buffer, len);
1241 return socket->priv->remote_address;
1245 * g_socket_is_connected:
1246 * @socket: a #GSocket.
1248 * Check whether the socket is connected. This is only useful for
1249 * connection-oriented sockets.
1251 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1256 g_socket_is_connected (GSocket *socket)
1258 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1260 return socket->priv->remote_address != NULL;
1265 * @socket: a #GSocket.
1266 * @error: #GError for error reporting, or %NULL to ignore.
1268 * Marks the socket as a server socket, i.e. a socket that is used
1269 * to accept incoming requests using g_socket_accept().
1271 * Before calling this the socket must be bound to a local address using
1274 * Returns: %TRUE on success, %FALSE on error.
1279 g_socket_listen (GSocket *socket,
1282 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1284 if (!check_socket (socket, error))
1287 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1289 int errsv = get_socket_errno ();
1291 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1292 _("could not listen: %s"), socket_strerror (errsv));
1301 * @socket: a #GSocket.
1302 * @address: a #GSocketAddress specifying the local address.
1303 * @allow_reuse: whether to allow reusing this address
1304 * @error: #GError for error reporting, or %NULL to ignore.
1306 * When a socket is created it is attached to an address family, but it
1307 * doesn't have an address in this family. g_socket_bind() assigns the
1308 * address (sometimes called name) of the socket.
1310 * It is generally required to bind to a local address before you can
1311 * receive connections. (See g_socket_listen() and g_socket_accept() ).
1313 * If @allow_reuse is %TRUE this allows the bind call to succeed in some
1314 * situation where it would otherwise return a %G_IO_ERROR_ADDRESS_IN_USE
1315 * error. The main example is for a TCP server socket where there are
1316 * outstanding connections in the WAIT state, which are generally safe
1317 * to ignore. However, setting it to %TRUE doesn't mean the call will
1318 * succeed if there is a socket actively bound to the address.
1320 * In general, pass %TRUE if the socket will be used to accept connections,
1321 * otherwise pass %FALSE.
1323 * Returns: %TRUE on success, %FALSE on error.
1328 g_socket_bind (GSocket *socket,
1329 GSocketAddress *address,
1330 gboolean reuse_address,
1336 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1338 if (!check_socket (socket, error))
1341 /* SO_REUSEADDR on windows means something else and is not what we want.
1342 It always allows the unix variant of SO_REUSEADDR anyway */
1344 value = (int) !!reuse_address;
1345 /* Ignore errors here, the only likely error is "not supported", and
1346 this is a "best effort" thing mainly */
1347 setsockopt (socket->priv->fd, SOL_SOCKET, SO_REUSEADDR,
1348 (gpointer) &value, sizeof (value));
1351 if (!g_socket_address_to_native (address, addr, sizeof addr, error))
1354 if (bind (socket->priv->fd, (struct sockaddr *) addr,
1355 g_socket_address_get_native_size (address)) < 0)
1357 int errsv = get_socket_errno ();
1359 G_IO_ERROR, socket_io_error_from_errno (errsv),
1360 _("Error binding to address: %s"), socket_strerror (errsv));
1364 socket->priv->local_address = g_object_ref (address);
1371 * @socket: a #GSocket.
1372 * @error: #GError for error reporting, or %NULL to ignore.
1374 * Accept incoming connections on a connection-based socket. This removes
1375 * the first outstanding connection request from the listening socket and
1376 * creates a #GSocket object for it.
1378 * The @socket must be bound to a local address with g_socket_bind() and
1379 * must be listening for incoming connections (g_socket_listen()).
1381 * If there are no outstanding connections then the operation will block
1382 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
1383 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
1385 * Returns: a new #GSocket, or %NULL on error.
1386 * Free the returned object with g_object_unref().
1391 g_socket_accept (GSocket *socket,
1394 GSocket *new_socket;
1397 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1399 if (!check_socket (socket, error))
1404 if (socket->priv->blocking &&
1405 !g_socket_condition_wait (socket,
1406 G_IO_IN, NULL, error))
1409 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
1411 int errsv = get_socket_errno ();
1413 win32_unset_event_mask (socket, FD_ACCEPT);
1418 if (socket->priv->blocking)
1420 #ifdef WSAEWOULDBLOCK
1421 if (errsv == WSAEWOULDBLOCK)
1424 if (errsv == EWOULDBLOCK ||
1430 g_set_error (error, G_IO_ERROR,
1431 socket_io_error_from_errno (errsv),
1432 _("Error accepting connection: %s"), socket_strerror (errsv));
1438 win32_unset_event_mask (socket, FD_ACCEPT);
1442 /* The socket inherits the accepting sockets event mask and even object,
1443 we need to remove that */
1444 WSAEventSelect (ret, NULL, 0);
1450 /* We always want to set close-on-exec to protect users. If you
1451 need to so some weird inheritance to exec you can re-enable this
1452 using lower level hacks with g_socket_get_fd(). */
1453 flags = fcntl (ret, F_GETFD, 0);
1455 (flags & FD_CLOEXEC) == 0)
1457 flags |= FD_CLOEXEC;
1458 fcntl (ret, F_SETFD, flags);
1463 new_socket = g_socket_new_from_fd (ret, error);
1464 if (new_socket == NULL)
1473 new_socket->priv->protocol = socket->priv->protocol;
1480 * @socket: a #GSocket.
1481 * @address: a #GSocketAddress specifying the remote address.
1482 * @error: #GError for error reporting, or %NULL to ignore.
1484 * Connect the socket to the specified remote address.
1486 * For connection oriented socket this generally means we attempt to make
1487 * a connection to the @address. For a connection-less socket it sets
1488 * the default address for g_socket_send() and discards all incoming datagrams
1489 * from other sources.
1491 * Generally connection oriented sockets can only connect once, but connection-less
1492 * sockets can connect multiple times to change the default address.
1494 * If the connect call needs to do network I/O it will block, unless
1495 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
1496 * and the user can be notified of the connection finishing by waiting
1497 * for the G_IO_OUT condition. The result of the connection can then be
1498 * checked with g_socket_check_pending_error().
1500 * Returns: %TRUE if connected, %FALSE on error.
1505 g_socket_connect (GSocket *socket,
1506 GSocketAddress *address,
1511 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1513 if (!check_socket (socket, error))
1516 if (!g_socket_address_to_native (address, buffer, sizeof buffer, error))
1521 if (socket->priv->blocking &&
1522 !g_socket_condition_wait (socket,
1523 G_IO_IN, NULL, error))
1526 if (connect (socket->priv->fd, (struct sockaddr *) buffer,
1527 g_socket_address_get_native_size (address)) < 0)
1529 int errsv = get_socket_errno ();
1535 if (errsv == EINPROGRESS)
1537 if (errsv == WSAEINPROGRESS)
1540 if (socket->priv->blocking)
1542 g_socket_condition_wait (socket, G_IO_OUT, NULL, NULL);
1543 if (g_socket_check_pending_error (socket, error))
1546 g_prefix_error (error, _("Error connecting: "));
1549 g_set_error (error, G_IO_ERROR, G_IO_ERROR_PENDING,
1550 _("Connection in progress"));
1553 g_set_error (error, G_IO_ERROR,
1554 socket_io_error_from_errno (errsv),
1555 _("Error connecting: %s"), socket_strerror (errsv));
1562 win32_unset_event_mask (socket, FD_CONNECT);
1564 socket->priv->remote_address = g_object_ref (address);
1570 * g_socket_check_pending_error:
1571 * @socket: a #GSocket
1572 * @error: #GError for error reporting, or %NULL to ignore.
1574 * Checks and resets the pending error for the socket. This is typically
1575 * used to check for errors when g_socket_connect() is used in non-blocking mode.
1577 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
1582 g_socket_check_pending_error (GSocket *socket,
1588 optlen = sizeof (value);
1589 if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
1591 int errsv = get_socket_errno ();
1593 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1594 _("Unable to get pending error: %s"), socket_strerror (errsv));
1600 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (value),
1601 "%s", socket_strerror (value));
1609 * @socket: a #GSocket
1610 * @buffer: a buffer to read data into (which should be at least count bytes long).
1611 * @size: the number of bytes that will be read from the stream
1612 * @error: #GError for error reporting, or %NULL to ignore.
1614 * Receive data (up to @size bytes) from a socket. This is mainly used by
1615 * connection oriented sockets, it is identical to g_socket_receive_from()
1616 * with @address set to %NULL.
1618 * If a message is too long to fit in @buffer, excess bytes may be discarded
1619 * depending on the type of socket the message is received from.
1621 * If the socket is in blocking mode the call will block until there is
1622 * some data to receive or there is an error. If there is no data available
1623 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1624 * will be returned. To be notified of available data, wait for the %G_IO_IN
1627 * On error -1 is returned and @error is set accordingly.
1629 * Returns: Number of bytes read, or -1 on error
1634 g_socket_receive (GSocket *socket,
1641 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1643 if (!check_socket (socket, error))
1648 if (socket->priv->blocking &&
1649 !g_socket_condition_wait (socket,
1650 G_IO_IN, NULL, error))
1653 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
1655 int errsv = get_socket_errno ();
1660 if (socket->priv->blocking)
1662 #ifdef WSAEWOULDBLOCK
1663 if (errsv == WSAEWOULDBLOCK)
1666 if (errsv == EWOULDBLOCK ||
1672 win32_unset_event_mask (socket, FD_READ);
1674 g_set_error (error, G_IO_ERROR,
1675 socket_io_error_from_errno (errsv),
1676 _("Error receiving data: %s"), socket_strerror (errsv));
1680 win32_unset_event_mask (socket, FD_READ);
1689 * g_socket_receive_from:
1690 * @socket: a #GSocket
1691 * @address: a pointer to a #GSocketAddress pointer, or %NULL
1692 * @buffer: a buffer to read data into (which should be at least count bytes long).
1693 * @size: the number of bytes that will be read from the stream
1694 * @error: #GError for error reporting, or %NULL to ignore.
1696 * Receive data (up to @size bytes) from a socket.
1698 * If @address is non-%NULL then @address will be set equal to the
1699 * source address of the received packet.
1700 * @address is owned by the caller.
1702 * If the socket is in blocking mode the call will block until there is
1703 * some data to receive or there is an error. If there is no data available
1704 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1705 * will be returned. To be notified of available data, wait for the %G_IO_IN
1708 * On error -1 is returned and @error is set accordingly.
1710 * Returns: Number of bytes read, or -1 on error
1715 g_socket_receive_from (GSocket *socket,
1716 GSocketAddress **address,
1726 return g_socket_receive_message (socket,
1735 * @socket: a #GSocket
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 on the socket. This is mainly used by
1741 * connection oriented sockets, it is identical to g_socket_send_to()
1742 * with @address set to %NULL.
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 (GSocket *socket,
1763 const gchar *buffer,
1769 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1771 if (!check_socket (socket, error))
1776 if (socket->priv->blocking &&
1777 !g_socket_condition_wait (socket,
1778 G_IO_OUT, NULL, error))
1781 if ((ret = send (socket->priv->fd, buffer, size, 0)) < 0)
1783 int errsv = get_socket_errno ();
1788 #ifdef WSAEWOULDBLOCK
1789 if (errsv == WSAEWOULDBLOCK)
1790 win32_unset_event_mask (socket, FD_WRITE);
1793 if (socket->priv->blocking)
1795 #ifdef WSAEWOULDBLOCK
1796 if (errsv == WSAEWOULDBLOCK)
1799 if (errsv == EWOULDBLOCK ||
1805 g_set_error (error, G_IO_ERROR,
1806 socket_io_error_from_errno (errsv),
1807 _("Error sending data: %s"), socket_strerror (errsv));
1818 * @socket: a #GSocket
1819 * @address: a #GSocketAddress, or %NULL
1820 * @buffer: the buffer containing the data to send.
1821 * @size: the number of bytes to send
1822 * @error: #GError for error reporting, or %NULL to ignore.
1824 * Tries to send @size bytes from @buffer to @address. If @address is
1825 * %NULL then the message is sent to the default receiver (set by
1826 * g_socket_connect()).
1828 * If the socket is in blocking mode the call will block until there is
1829 * space for the data in the socket queue. If there is no space available
1830 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1831 * will be returned. To be notified of available space, wait for the %G_IO_OUT
1834 * Note that on Windows you can't rely on a %G_IO_OUT condition
1835 * not producing a %G_IO_ERROR_WOULD_BLOCK error, as this is how Winsock
1836 * write notification works. However, robust apps should always be able to
1837 * handle this since it can easily appear in other cases too.
1839 * On error -1 is returned and @error is set accordingly.
1841 * Returns: Number of bytes read, or -1 on error
1846 g_socket_send_to (GSocket *socket,
1847 GSocketAddress *address,
1848 const gchar *buffer,
1857 return g_socket_send_message (socket,
1866 * @socket: a #GSocket
1867 * @error: #GError for error reporting, or %NULL to ignore.
1869 * Closes the socket, shutting down any active connection.
1871 * Closing a socket does not wait for all outstanding I/O operations to finish,
1872 * so the caller should not rely on them to be guaranteed to complete even
1873 * if the close returns with no error.
1875 * Once the socket is closed, all other operations will return %G_IO_ERROR_CLOSED.
1876 * Closing a stream multiple times will not return an error.
1878 * Sockets will be automatically closed when the last reference
1879 * is dropped, but you might want to call this function to make sure
1880 * resources are released as early as possible.
1882 * Returns: %TRUE on success, %FALSE on error
1887 g_socket_close (GSocket *socket,
1892 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
1894 if (socket->priv->closed)
1895 return TRUE; /* Multiple close not an error */
1897 if (!check_socket (socket, NULL))
1903 res = closesocket (socket->priv->fd);
1905 res = close (socket->priv->fd);
1909 int errsv = get_socket_errno ();
1914 g_set_error (error, G_IO_ERROR,
1915 socket_io_error_from_errno (errsv),
1916 _("Error closing socket: %s"),
1917 socket_strerror (errsv));
1924 if (socket->priv->event != WSA_INVALID_EVENT)
1926 WSACloseEvent (socket->priv->event);
1927 socket->priv->event = WSA_INVALID_EVENT;
1931 socket->priv->closed = TRUE;
1937 * g_socket_is_closed:
1938 * @socket: a #GSocket
1940 * Checks whether a socket is closed.
1942 * Returns: %TRUE if socket is closed, %FALSE otherwise
1947 g_socket_is_closed (GSocket *socket)
1949 return socket->priv->closed;
1953 /* Broken source, used on errors */
1955 broken_prepare (GSource *source,
1962 broken_check (GSource *source)
1968 broken_dispatch (GSource *source,
1969 GSourceFunc callback,
1975 static GSourceFuncs broken_funcs =
1984 network_events_for_condition (GIOCondition condition)
1988 if (condition & G_IO_IN)
1989 event_mask |= (FD_READ | FD_ACCEPT);
1990 if (condition & G_IO_OUT)
1991 event_mask |= (FD_WRITE | FD_CONNECT);
1992 event_mask |= FD_CLOSE;
1998 ensure_event (GSocket *socket)
2000 if (socket->priv->event == WSA_INVALID_EVENT)
2001 socket->priv->event = WSACreateEvent();
2005 update_select_events (GSocket *socket)
2012 ensure_event (socket);
2015 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
2018 event_mask |= network_events_for_condition (*ptr);
2021 if (event_mask != socket->priv->selected_events)
2023 /* If no events selected, disable event so we can unset
2026 if (event_mask == 0)
2029 event = socket->priv->event;
2031 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
2032 socket->priv->selected_events = event_mask;
2037 add_condition_watch (GSocket *socket,
2038 GIOCondition *condition)
2040 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
2042 socket->priv->requested_conditions =
2043 g_list_prepend (socket->priv->requested_conditions, condition);
2045 update_select_events (socket);
2049 remove_condition_watch (GSocket *socket,
2050 GIOCondition *condition)
2052 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
2054 socket->priv->requested_conditions =
2055 g_list_remove (socket->priv->requested_conditions, condition);
2057 update_select_events (socket);
2061 update_condition (GSocket *socket)
2063 WSANETWORKEVENTS events;
2064 GIOCondition condition;
2066 if (WSAEnumNetworkEvents (socket->priv->fd,
2067 socket->priv->event,
2070 socket->priv->current_events |= events.lNetworkEvents;
2071 if (events.lNetworkEvents & FD_WRITE &&
2072 events.iErrorCode[FD_WRITE_BIT] != 0)
2073 socket->priv->current_errors |= FD_WRITE;
2074 if (events.lNetworkEvents & FD_CONNECT &&
2075 events.iErrorCode[FD_CONNECT_BIT] != 0)
2076 socket->priv->current_errors |= FD_CONNECT;
2080 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
2081 condition |= G_IO_IN;
2083 if (socket->priv->current_events & FD_CLOSE ||
2084 socket->priv->closed)
2085 condition |= G_IO_HUP;
2087 /* Never report both G_IO_OUT and HUP, these are
2088 mutually exclusive (can't write to a closed socket) */
2089 if ((condition & G_IO_HUP) == 0 &&
2090 socket->priv->current_events & FD_WRITE)
2092 if (socket->priv->current_errors & FD_WRITE)
2093 condition |= G_IO_ERR;
2095 condition |= G_IO_OUT;
2099 if (socket->priv->current_events & FD_CONNECT)
2101 if (socket->priv->current_errors & FD_CONNECT)
2102 condition |= (G_IO_HUP | G_IO_ERR);
2104 condition |= G_IO_OUT;
2115 GIOCondition condition;
2116 GCancellable *cancellable;
2117 GPollFD cancel_pollfd;
2118 GIOCondition result_condition;
2122 winsock_prepare (GSource *source,
2125 GWinsockSource *winsock_source = (GWinsockSource *)source;
2126 GIOCondition current_condition;
2128 current_condition = update_condition (winsock_source->socket);
2130 if (g_cancellable_is_cancelled (winsock_source->cancellable))
2132 winsock_source->result_condition = current_condition;
2136 if ((winsock_source->condition & current_condition) != 0)
2138 winsock_source->result_condition = current_condition;
2146 winsock_check (GSource *source)
2148 GWinsockSource *winsock_source = (GWinsockSource *)source;
2149 GIOCondition current_condition;
2151 current_condition = update_condition (winsock_source->socket);
2153 if (g_cancellable_is_cancelled (winsock_source->cancellable))
2155 winsock_source->result_condition = current_condition;
2159 if ((winsock_source->condition & current_condition) != 0)
2161 winsock_source->result_condition = current_condition;
2169 winsock_dispatch (GSource *source,
2170 GSourceFunc callback,
2173 GSocketSourceFunc func = (GSocketSourceFunc)callback;
2174 GWinsockSource *winsock_source = (GWinsockSource *)source;
2176 return (*func) (winsock_source->socket,
2177 winsock_source->result_condition & winsock_source->condition,
2182 winsock_finalize (GSource *source)
2184 GWinsockSource *winsock_source = (GWinsockSource *)source;
2187 socket = winsock_source->socket;
2189 remove_condition_watch (socket, &winsock_source->condition);
2190 g_object_unref (socket);
2192 if (winsock_source->cancellable)
2193 g_object_unref (winsock_source->cancellable);
2196 static GSourceFuncs winsock_funcs =
2205 winsock_source_new (GSocket *socket,
2206 GIOCondition condition,
2207 GCancellable *cancellable)
2210 GWinsockSource *winsock_source;
2212 ensure_event (socket);
2214 if (socket->priv->event == WSA_INVALID_EVENT)
2216 g_warning ("Failed to create WSAEvent");
2217 return g_source_new (&broken_funcs, sizeof (GSource));
2220 condition |= G_IO_HUP | G_IO_ERR;
2222 source = g_source_new (&winsock_funcs, sizeof (GWinsockSource));
2223 winsock_source = (GWinsockSource *)source;
2225 winsock_source->socket = g_object_ref (socket);
2226 winsock_source->condition = condition;
2227 add_condition_watch (socket, &winsock_source->condition);
2231 winsock_source->cancellable = g_object_ref (cancellable);
2232 g_cancellable_make_pollfd (cancellable,
2233 &winsock_source->cancel_pollfd);
2234 g_source_add_poll (source, &winsock_source->cancel_pollfd);
2237 winsock_source->pollfd.fd = (gintptr) socket->priv->event;
2238 winsock_source->pollfd.events = condition;
2239 g_source_add_poll (source, &winsock_source->pollfd);
2246 * g_socket_create_source:
2247 * @socket: a #GSocket
2248 * @condition: a #GIOCondition mask to monitor
2249 * @cancellable: a %GCancellable or %NULL
2251 * Creates a %GSource that can be attached to a %GMainContext to monitor
2252 * for the availibility of the specified @condition on the socket.
2254 * The callback on the source is of the #GSocketSourceFunc type.
2256 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2257 * these conditions will always be reported output if they are true.
2259 * @cancellable if not %NULL can be used to cancel the source, which will
2260 * cause the source to trigger, reporting the current condition. You can
2261 * check for this in the callback using g_cancellable_is_cancelled().
2263 * Returns: a newly allocated %GSource, free with g_source_unref().
2268 g_socket_create_source (GSocket *socket,
2269 GIOCondition condition,
2270 GCancellable *cancellable)
2273 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
2276 source = winsock_source_new (socket, condition, cancellable);
2278 source =_g_fd_source_new_with_object (G_OBJECT (socket), socket->priv->fd,
2279 condition, cancellable);
2285 * g_socket_condition_check:
2286 * @socket: a #GSocket
2287 * @condition: a #GIOCondition mask to check
2289 * Checks on the readiness of @socket to perform operations. The
2290 * operations specified in @condition are checked for and masked
2291 * against the currently-satisfied conditions on @socket. The result
2294 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2295 * these conditions will always be set in the output if they are true.
2297 * This call never blocks.
2299 * Returns: the @GIOCondition mask of the current state
2304 g_socket_condition_check (GSocket *socket,
2305 GIOCondition condition)
2307 if (!check_socket (socket, NULL))
2312 GIOCondition current_condition;
2314 condition |= G_IO_ERR | G_IO_HUP;
2316 add_condition_watch (socket, &condition);
2317 current_condition = update_condition (socket);
2318 remove_condition_watch (socket, &condition);
2319 return condition & current_condition;
2325 poll_fd.fd = socket->priv->fd;
2326 poll_fd.events = condition;
2329 result = g_poll (&poll_fd, 1, 0);
2330 while (result == -1 && get_socket_errno () == EINTR);
2332 return poll_fd.revents;
2338 * g_socket_condition_wait:
2339 * @socket: a #GSocket
2340 * @condition: a #GIOCondition mask to wait for
2341 * @cancellable: a #GCancellable, or %NULL
2342 * @error: a #GError pointer, or %NULL
2344 * Waits for @condition to become true on @socket. When the condition
2345 * becomes true, %TRUE is returned.
2347 * If @cancellable is cancelled before the condition becomes true then
2348 * %FALSE is returned and @error, if non-%NULL, is set to %G_IO_ERROR_CANCELLED.
2350 * Returns: %TRUE if the condition was met, %FALSE otherwise
2355 g_socket_condition_wait (GSocket *socket,
2356 GIOCondition condition,
2357 GCancellable *cancellable,
2360 if (!check_socket (socket, error))
2363 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2368 GIOCondition current_condition;
2374 /* Always check these */
2375 condition |= G_IO_ERR | G_IO_HUP;
2377 add_condition_watch (socket, &condition);
2380 events[num_events++] = socket->priv->event;
2384 g_cancellable_make_pollfd (cancellable, &cancel_fd);
2385 events[num_events++] = (WSAEVENT)cancel_fd.fd;
2388 current_condition = update_condition (socket);
2389 while ((condition & current_condition) == 0)
2391 res = WSAWaitForMultipleEvents(num_events, events,
2392 FALSE, WSA_INFINITE, FALSE);
2393 if (res == WSA_WAIT_FAILED)
2395 int errsv = get_socket_errno ();
2397 g_set_error (error, G_IO_ERROR,
2398 socket_io_error_from_errno (errsv),
2399 _("Waiting for socket condition: %s"),
2400 socket_strerror (errsv));
2404 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2407 current_condition = update_condition (socket);
2409 remove_condition_watch (socket, &condition);
2411 return (condition & current_condition) != 0;
2419 poll_fd[0].fd = socket->priv->fd;
2420 poll_fd[0].events = condition;
2425 g_cancellable_make_pollfd (cancellable, &poll_fd[1]);
2430 result = g_poll (poll_fd, num, -1);
2431 while (result == -1 && get_socket_errno () == EINTR);
2433 return cancellable == NULL ||
2434 !g_cancellable_set_error_if_cancelled (cancellable, error);
2440 * g_socket_send_message:
2441 * @socket: a #GSocket
2442 * @address: a #GSocketAddress, or %NULL
2443 * @vectors: an array of #GOutputVector structs
2444 * @num_vectors: the number of elements in @vectors, or -1
2445 * @messages: a pointer to an array of #GSocketControlMessages, or
2447 * @num_messages: number of elements in @messages, or -1.
2448 * @flags: an int containing #GSocketMsgFlags flags
2449 * @error: #GError for error reporting, or %NULL to ignore.
2451 * Send data to @address on @socket. This is the most complicated and
2452 * fully-featured version of this call. For easier use, see
2453 * g_socket_send() and g_socket_send_to().
2455 * If @address is %NULL then the message is sent to the default receiver
2456 * (set by g_socket_connect()).
2458 * @vector must point to an array of #GOutputVector structs and
2459 * @num_vectors must be the length of this array. These structs
2460 * describe the buffers that the sent data will be gathered from.
2461 * If @num_vector is -1, then @vector is assumed to be terminated
2462 * by a #GOutputVector with a %NULL buffer pointer.
2465 * @messages, if non-%NULL, is taken to point to an array of @num_messages
2466 * #GSocketControlMessage instances. These correspond to the control
2467 * messages to be sent on the socket.
2468 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
2471 * @flags modify how the message sent. The commonly available arguments
2472 * for this is available in the #GSocketMsgFlags enum, but the
2473 * values there are the same as the system values, and the flags
2474 * are passed in as-is, so you can pass in system specific flags too.
2476 * If the socket is in blocking mode the call will block until there is
2477 * space for the data in the socket queue. If there is no space available
2478 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2479 * will be returned. To be notified of available space, wait for the %G_IO_OUT
2482 * Note that on Windows you can't rely on a %G_IO_OUT condition
2483 * not producing a %G_IO_ERROR_WOULD_BLOCK error, as this is how Winsock
2484 * write notification works. However, robust apps should always be able to
2485 * handle this since it can easily appear in other cases too.
2487 * On error -1 is returned and @error is set accordingly.
2489 * Returns: Number of bytes read, or -1 on error
2494 g_socket_send_message (GSocket *socket,
2495 GSocketAddress *address,
2496 GOutputVector *vectors,
2498 GSocketControlMessage **messages,
2503 GOutputVector one_vector;
2506 if (!check_socket (socket, error))
2509 if (num_vectors == -1)
2511 for (num_vectors = 0;
2512 vectors[num_vectors].buffer != NULL;
2517 if (num_messages == -1)
2519 for (num_messages = 0;
2520 messages != NULL && messages[num_messages] != NULL;
2525 if (num_vectors == 0)
2529 one_vector.buffer = &zero;
2530 one_vector.size = 1;
2532 vectors = &one_vector;
2543 msg.msg_namelen = g_socket_address_get_native_size (address);
2544 msg.msg_name = g_alloca (msg.msg_namelen);
2545 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
2551 /* this entire expression will be evaluated at compile time */
2552 if (sizeof *msg.msg_iov == sizeof *vectors &&
2553 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2554 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2555 G_STRUCT_OFFSET (GOutputVector, buffer) &&
2556 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2557 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2558 G_STRUCT_OFFSET (GOutputVector, size))
2559 /* ABI is compatible */
2561 msg.msg_iov = (struct iovec *) vectors;
2562 msg.msg_iovlen = num_vectors;
2565 /* ABI is incompatible */
2569 msg.msg_iov = g_newa (struct iovec, num_vectors);
2570 for (i = 0; i < num_vectors; i++)
2572 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
2573 msg.msg_iov[i].iov_len = vectors[i].size;
2575 msg.msg_iovlen = num_vectors;
2581 struct cmsghdr *cmsg;
2584 msg.msg_controllen = 0;
2585 for (i = 0; i < num_messages; i++)
2586 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
2588 msg.msg_control = g_alloca (msg.msg_controllen);
2590 cmsg = CMSG_FIRSTHDR (&msg);
2591 for (i = 0; i < num_messages; i++)
2593 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
2594 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
2595 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
2596 g_socket_control_message_serialize (messages[i],
2598 cmsg = CMSG_NXTHDR (&msg, cmsg);
2600 g_assert (cmsg == NULL);
2605 if (socket->priv->blocking &&
2606 !g_socket_condition_wait (socket,
2607 G_IO_OUT, NULL, error))
2610 result = sendmsg (socket->priv->fd, &msg, flags);
2613 int errsv = get_socket_errno ();
2618 if (socket->priv->blocking &&
2619 (errsv == EWOULDBLOCK ||
2623 g_set_error (error, G_IO_ERROR,
2624 socket_io_error_from_errno (errsv),
2625 _("Error sending message: %s"), socket_strerror (errsv));
2636 struct sockaddr_storage addr;
2643 /* Win32 doesn't support control messages.
2644 Actually this is possible for raw and datagram sockets
2645 via WSASendMessage on Vista or later, but that doesn't
2647 if (num_messages != 0)
2649 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2650 _("GSocketControlMessage not supported on windows"));
2655 bufs = g_newa (WSABUF, num_vectors);
2656 for (i = 0; i < num_vectors; i++)
2658 bufs[i].buf = (char *)vectors[i].buffer;
2659 bufs[i].len = (gulong)vectors[i].size;
2665 addrlen = g_socket_address_get_native_size (address);
2666 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
2672 if (socket->priv->blocking &&
2673 !g_socket_condition_wait (socket,
2674 G_IO_OUT, NULL, error))
2678 result = WSASendTo (socket->priv->fd,
2681 (const struct sockaddr *)&addr, addrlen,
2684 result = WSASend (socket->priv->fd,
2691 int errsv = get_socket_errno ();
2693 if (errsv == WSAEINTR)
2696 if (errsv == WSAEWOULDBLOCK)
2697 win32_unset_event_mask (socket, FD_WRITE);
2699 if (socket->priv->blocking &&
2700 errsv == WSAEWOULDBLOCK)
2703 g_set_error (error, G_IO_ERROR,
2704 socket_io_error_from_errno (errsv),
2705 _("Error sending message: %s"), socket_strerror (errsv));
2718 * g_socket_receive_message:
2719 * @socket: a #GSocket
2720 * @address: a pointer to a #GSocketAddress pointer, or %NULL
2721 * @vectors: an array of #GInputVector structs
2722 * @num_vectors: the number of elements in @vectors, or -1
2723 * @messages: a pointer which will be filled with an array of
2724 * #GSocketControlMessages, or %NULL
2725 * @num_messages: a pointer which will be filled with the number of
2726 * elements in @messages, or %NULL
2727 * @flags: a pointer to an int containing #GSocketMsgFlags flags
2728 * @error: a #GError pointer, or %NULL
2730 * Receive data from a socket. This is the most complicated and
2731 * fully-featured version of this call. For easier use, see
2732 * g_socket_receive() and g_socket_receive_from().
2734 * If @address is non-%NULL then @address will be set equal to the
2735 * source address of the received packet.
2736 * @address is owned by the caller.
2738 * @vector must point to an array of #GInputVector structs and
2739 * @num_vectors must be the length of this array. These structs
2740 * describe the buffers that received data will be scattered into.
2741 * If @num_vector is -1, then @vector is assumed to be terminated
2742 * by a #GInputVector with a %NULL buffer pointer.
2744 * As a special case, if the size of the array is zero (in which case,
2745 * @vectors may of course be %NULL), then a single byte is received
2746 * and discarded. This is to facilitate the common practice of
2747 * sending a single '\0' byte for the purposes of transferring
2750 * @messages, if non-%NULL, is taken to point to a pointer that will
2751 * be set to point to a newly-allocated array of
2752 * #GSocketControlMessage instances. These correspond to the control
2753 * messages received from the kernel, one #GSocketControlMessage per
2754 * message from the kernel. This array is %NULL-terminated and must be
2755 * freed by the caller using g_free().
2757 * @num_messages, if non-%NULL, will be set to the number of control
2758 * messages received.
2760 * If both @messages and @num_messages are non-%NULL, then
2761 * @num_messages gives the number of #GSocketControlMessage instances
2762 * in @messages (ie: not including the %NULL terminator).
2764 * @flags is an in/out parameter. The commonly available arguments
2765 * for this is available in the #GSocketMsgFlags enum, but the
2766 * values there are the same as the system values, and the flags
2767 * are passed in as-is, so you can pass in system specific flags too.
2769 * If the socket is in blocking mode the call will block until there is
2770 * some data to receive or there is an error. If there is no data available
2771 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2772 * will be returned. To be notified of available data, wait for the %G_IO_IN
2775 * On error -1 is returned and @error is set accordingly.
2777 * Returns: Number of bytes read, or -1 on error
2782 g_socket_receive_message (GSocket *socket,
2783 GSocketAddress **address,
2784 GInputVector *vectors,
2786 GSocketControlMessage ***messages,
2791 GInputVector one_vector;
2794 if (!check_socket (socket, error))
2797 if (num_vectors == -1)
2799 for (num_vectors = 0;
2800 vectors[num_vectors].buffer != NULL;
2805 if (num_vectors == 0)
2807 one_vector.buffer = &one_byte;
2808 one_vector.size = 1;
2810 vectors = &one_vector;
2817 struct sockaddr_storage one_sockaddr;
2822 msg.msg_name = &one_sockaddr;
2823 msg.msg_namelen = sizeof (struct sockaddr_storage);
2827 msg.msg_name = NULL;
2828 msg.msg_namelen = 0;
2832 /* this entire expression will be evaluated at compile time */
2833 if (sizeof *msg.msg_iov == sizeof *vectors &&
2834 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2835 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2836 G_STRUCT_OFFSET (GInputVector, buffer) &&
2837 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2838 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2839 G_STRUCT_OFFSET (GInputVector, size))
2840 /* ABI is compatible */
2842 msg.msg_iov = (struct iovec *) vectors;
2843 msg.msg_iovlen = num_vectors;
2846 /* ABI is incompatible */
2850 msg.msg_iov = g_newa (struct iovec, num_vectors);
2851 for (i = 0; i < num_vectors; i++)
2853 msg.msg_iov[i].iov_base = vectors[i].buffer;
2854 msg.msg_iov[i].iov_len = vectors[i].size;
2856 msg.msg_iovlen = num_vectors;
2860 msg.msg_control = g_alloca (2048);
2861 msg.msg_controllen = 2048;
2865 msg.msg_flags = *flags;
2872 if (socket->priv->blocking &&
2873 !g_socket_condition_wait (socket,
2874 G_IO_IN, NULL, error))
2877 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
2881 int errsv = get_socket_errno ();
2886 if (socket->priv->blocking &&
2887 (errsv == EWOULDBLOCK ||
2891 g_set_error (error, G_IO_ERROR,
2892 socket_io_error_from_errno (errsv),
2893 _("Error receiving message: %s"), socket_strerror (errsv));
2900 /* decode address */
2901 if (address != NULL)
2903 if (msg.msg_namelen > 0)
2904 *address = g_socket_address_new_from_native (msg.msg_name,
2910 /* decode control messages */
2912 GSocketControlMessage **my_messages = NULL;
2913 gint allocated = 0, index = 0;
2914 const gchar *scm_pointer;
2915 struct cmsghdr *cmsg;
2918 scm_pointer = (const gchar *) msg.msg_control;
2919 scm_size = msg.msg_controllen;
2921 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
2923 GSocketControlMessage *message;
2925 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
2927 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
2929 if (message == NULL)
2930 /* We've already spewed about the problem in the
2931 deserialization code, so just continue */
2934 if (index == allocated)
2936 /* estimated 99% case: exactly 1 control message */
2937 allocated = MIN (allocated * 2, 1);
2938 my_messages = g_new (GSocketControlMessage *, (allocated + 1));
2942 my_messages[index++] = message;
2946 *num_messages = index;
2950 my_messages[index++] = NULL;
2951 *messages = my_messages;
2957 /* free all those messages we just constructed.
2958 * we have to do it this way if the user ignores the
2959 * messages so that we will close any received fds.
2961 for (i = 0; i < index; i++)
2962 g_object_unref (my_messages[i]);
2963 g_free (my_messages);
2967 /* capture the flags */
2969 *flags = msg.msg_flags;
2975 struct sockaddr_storage addr;
2977 DWORD bytes_received;
2984 bufs = g_newa (WSABUF, num_vectors);
2985 for (i = 0; i < num_vectors; i++)
2987 bufs[i].buf = (char *)vectors[i].buffer;
2988 bufs[i].len = (gulong)vectors[i].size;
3000 if (socket->priv->blocking &&
3001 !g_socket_condition_wait (socket,
3002 G_IO_IN, NULL, error))
3005 addrlen = sizeof addr;
3007 result = WSARecvFrom (socket->priv->fd,
3009 &bytes_received, &win_flags,
3010 (struct sockaddr *)&addr, &addrlen,
3013 result = WSARecv (socket->priv->fd,
3015 &bytes_received, &win_flags,
3019 int errsv = get_socket_errno ();
3021 if (errsv == WSAEINTR)
3024 win32_unset_event_mask (socket, FD_READ);
3026 if (socket->priv->blocking &&
3027 errsv == WSAEWOULDBLOCK)
3030 g_set_error (error, G_IO_ERROR,
3031 socket_io_error_from_errno (errsv),
3032 _("Error receiving message: %s"), socket_strerror (errsv));
3036 win32_unset_event_mask (socket, FD_READ);
3040 /* decode address */
3041 if (address != NULL)
3044 *address = g_socket_address_new_from_native (&addr, addrlen);
3049 /* capture the flags */
3053 return bytes_received;
3058 #define __G_SOCKET_C__
3059 #include "gioaliasdef.c"