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;
149 GList *requested_conditions; /* list of requested GIOCondition * */
154 get_socket_errno (void)
159 return WSAGetLastError ();
164 socket_io_error_from_errno (int err)
167 return g_io_error_from_errno (err);
172 return G_IO_ERROR_ADDRESS_IN_USE;
174 return G_IO_ERROR_WOULD_BLOCK;
176 return G_IO_ERROR_PERMISSION_DENIED;
177 case WSA_INVALID_HANDLE:
178 case WSA_INVALID_PARAMETER:
181 return G_IO_ERROR_INVALID_ARGUMENT;
182 case WSAEPROTONOSUPPORT:
183 return G_IO_ERROR_NOT_SUPPORTED;
185 return G_IO_ERROR_CANCELLED;
186 case WSAESOCKTNOSUPPORT:
188 case WSAEPFNOSUPPORT:
189 case WSAEAFNOSUPPORT:
190 return G_IO_ERROR_NOT_SUPPORTED;
192 return G_IO_ERROR_FAILED;
198 socket_strerror (int err)
201 return g_strerror (err);
203 static GStaticPrivate msg_private = G_STATIC_PRIVATE_INIT;
206 buf = g_static_private_get (&msg_private);
209 buf = g_new (gchar, 128);
210 g_static_private_set (&msg_private, buf, g_free);
213 msg = g_win32_error_message (err);
214 strncpy (buf, msg, 128);
221 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
223 _win32_unset_event_mask (GSocket *socket, int mask)
225 socket->priv->current_events &= ~mask;
226 socket->priv->current_errors &= ~mask;
229 #define win32_unset_event_mask(_socket, _mask)
233 set_fd_nonblocking (int fd)
242 if ((arg = fcntl (fd, F_GETFL, NULL)) < 0)
244 g_warning ("Error getting socket status flags: %s", socket_strerror (errno));
248 arg = arg | O_NONBLOCK;
250 if (fcntl (fd, F_SETFL, arg) < 0)
251 g_warning ("Error setting socket status flags: %s", socket_strerror (errno));
255 if (ioctlsocket (fd, FIONBIO, &arg) == SOCKET_ERROR)
257 int errsv = get_socket_errno ();
258 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
264 check_socket (GSocket *socket,
267 if (!socket->priv->inited)
269 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
270 _("Invalid socket, not initialized"));
274 if (socket->priv->construct_error)
276 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
277 _("Invalid socket, initialization failed due to: %s"),
278 socket->priv->construct_error->message);
282 if (socket->priv->closed)
284 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
285 _("Socket is already closed"));
292 g_socket_details_from_fd (GSocket *socket)
294 struct sockaddr_storage address;
306 fd = socket->priv->fd;
307 optlen = sizeof value;
308 if (getsockopt (fd, SOL_SOCKET, SO_TYPE, (void *)&value, &optlen) != 0)
310 errsv = get_socket_errno ();
321 /* programmer error */
322 g_error ("creating GSocket from fd %d: %s\n",
323 fd, socket_strerror (errsv));
331 g_assert (optlen == sizeof value);
335 socket->priv->type = G_SOCKET_TYPE_STREAM;
339 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
343 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
347 socket->priv->type = G_SOCKET_TYPE_INVALID;
351 addrlen = sizeof address;
352 if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
354 errsv = get_socket_errno ();
358 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
359 sizeof address.ss_family <= addrlen);
360 switch (address.ss_family)
362 case G_SOCKET_FAMILY_IPV4:
363 case G_SOCKET_FAMILY_IPV6:
364 case G_SOCKET_FAMILY_UNIX:
365 socket->priv->family = address.ss_family;
369 socket->priv->family = G_SOCKET_FAMILY_INVALID;
373 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
375 addrlen = sizeof address;
376 if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
377 socket->priv->connected = TRUE;
380 optlen = sizeof bool_val;
381 if (getsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
382 (void *)&bool_val, &optlen) == 0)
384 g_assert (optlen == sizeof bool_val);
385 socket->priv->keepalive = !!bool_val;
389 /* Can't read, maybe not supported, assume FALSE */
390 socket->priv->keepalive = FALSE;
396 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
397 socket_io_error_from_errno (errsv),
398 _("creating GSocket from fd: %s"),
399 socket_strerror (errsv));
403 get_protocol_name (int protocol_id)
405 struct protoent *protoent;
406 #ifdef HAVE_GETPROTOBYNUMBER_R
408 struct protoent my_protoent;
411 if (protocol_id == 0)
414 if (protocol_id == -1)
415 return g_strdup ("unknown");
417 #ifdef HAVE_GETPROTOBYNUMBER_R
419 getprotobynumber_r (protocol_id,
420 &my_protoent, buffer, sizeof (buffer),
423 protoent = getprotobynumber (protocol_id);
426 if (protoent == NULL)
427 return g_strdup_printf ("proto-%d", protocol_id);
429 return g_strdup (protoent->p_name);
433 * g_socket_protocol_id_lookup_by_name:
434 * @protocol_name: The name of a protocol, or %NULL
436 * Tries to look up the protocol id for a given
437 * protocol name. If the protocol name is not known
438 * on this system it returns -1.
440 * If @protocol_name is %NULL (default protocol) then
443 * Returns: a protocol id, or -1 if unknown
448 g_socket_protocol_id_lookup_by_name (const char *protocol_name)
450 struct protoent *protoent;
452 #ifdef HAVE_GETPROTOBYNAME_R
454 struct protoent my_protoent;
460 #ifdef HAVE_GETPROTOBYNAME_R
462 getprotobyname_r (protocol_name,
463 &my_protoent, buffer, sizeof (buffer),
466 protoent = getprotobyname (protocol_name);
469 if (protoent == NULL)
471 if (g_str_has_prefix (protocol_name, "proto-"))
472 return atoi (protocol_name + strlen ("proto-"));
475 protocol = protoent->p_proto;
481 g_socket_create_socket (GSocketFamily family,
491 case G_SOCKET_TYPE_STREAM:
492 native_type = SOCK_STREAM;
495 case G_SOCKET_TYPE_DATAGRAM:
496 native_type = SOCK_DGRAM;
499 case G_SOCKET_TYPE_SEQPACKET:
500 native_type = SOCK_SEQPACKET;
504 g_assert_not_reached ();
507 if (protocol_id == -1)
509 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
510 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
515 native_type |= SOCK_CLOEXEC;
517 fd = socket (family, native_type, protocol_id);
521 int errsv = get_socket_errno ();
523 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
524 _("Unable to create socket: %s"), socket_strerror (errsv));
531 /* We always want to set close-on-exec to protect users. If you
532 need to so some weird inheritance to exec you can re-enable this
533 using lower level hacks with g_socket_get_fd(). */
534 flags = fcntl (fd, F_GETFD, 0);
536 (flags & FD_CLOEXEC) == 0)
539 fcntl (fd, F_SETFD, flags);
548 g_socket_constructed (GObject *object)
550 GSocket *socket = G_SOCKET (object);
552 if (socket->priv->fd >= 0)
553 /* create socket->priv info from the fd */
554 g_socket_details_from_fd (socket);
557 /* create the fd from socket->priv info */
558 socket->priv->fd = g_socket_create_socket (socket->priv->family,
560 socket->priv->protocol,
561 &socket->priv->construct_error);
563 /* Always use native nonblocking sockets, as
564 windows sets sockets to nonblocking automatically
565 in certain operations. This way we make things work
566 the same on all platforms */
567 if (socket->priv->fd != -1)
568 set_fd_nonblocking (socket->priv->fd);
572 g_socket_get_property (GObject *object,
577 GSocket *socket = G_SOCKET (object);
578 GSocketAddress *address;
583 g_value_set_enum (value, socket->priv->family);
587 g_value_set_enum (value, socket->priv->type);
591 g_value_set_int (value, socket->priv->protocol);
595 g_value_set_int (value, socket->priv->fd);
599 g_value_set_boolean (value, socket->priv->blocking);
602 case PROP_LISTEN_BACKLOG:
603 g_value_set_int (value, socket->priv->listen_backlog);
607 g_value_set_boolean (value, socket->priv->keepalive);
610 case PROP_LOCAL_ADDRESS:
611 address = g_socket_get_local_address (socket, NULL);
612 g_value_take_object (value, address);
615 case PROP_REMOTE_ADDRESS:
616 address = g_socket_get_remote_address (socket, NULL);
617 g_value_take_object (value, address);
621 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
626 g_socket_set_property (GObject *object,
631 GSocket *socket = G_SOCKET (object);
636 socket->priv->family = g_value_get_enum (value);
640 socket->priv->type = g_value_get_enum (value);
644 socket->priv->protocol = g_value_get_int (value);
648 socket->priv->fd = g_value_get_int (value);
652 g_socket_set_blocking (socket, g_value_get_boolean (value));
655 case PROP_LISTEN_BACKLOG:
656 g_socket_set_listen_backlog (socket, g_value_get_int (value));
660 g_socket_set_keepalive (socket, g_value_get_boolean (value));
664 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
669 g_socket_finalize (GObject *object)
671 GSocket *socket = G_SOCKET (object);
673 g_clear_error (&socket->priv->construct_error);
675 if (socket->priv->fd != -1 &&
676 !socket->priv->closed)
677 g_socket_close (socket, NULL);
680 g_assert (socket->priv->requested_conditions == NULL);
683 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
684 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
688 g_socket_class_init (GSocketClass *klass)
690 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
693 /* Make sure winsock has been initialized */
694 type = g_inet_address_get_type ();
696 g_type_class_add_private (klass, sizeof (GSocketPrivate));
698 gobject_class->finalize = g_socket_finalize;
699 gobject_class->constructed = g_socket_constructed;
700 gobject_class->set_property = g_socket_set_property;
701 gobject_class->get_property = g_socket_get_property;
703 g_object_class_install_property (gobject_class, PROP_FAMILY,
704 g_param_spec_enum ("family",
706 P_("The sockets address family"),
707 G_TYPE_SOCKET_FAMILY,
708 G_SOCKET_FAMILY_INVALID,
709 G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
711 g_object_class_install_property (gobject_class, PROP_TYPE,
712 g_param_spec_enum ("type",
714 P_("The sockets type"),
716 G_SOCKET_TYPE_STREAM,
717 G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
719 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
720 g_param_spec_int ("protocol",
721 P_("Socket protocol"),
722 P_("The id of the protocol to use, or -1 for unknown"),
726 G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
728 g_object_class_install_property (gobject_class, PROP_FD,
729 g_param_spec_int ("fd",
730 P_("File descriptor"),
731 P_("The sockets file descriptor"),
735 G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
737 g_object_class_install_property (gobject_class, PROP_BLOCKING,
738 g_param_spec_boolean ("blocking",
740 P_("Whether or not I/O on this socket is blocking"),
742 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
744 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
745 g_param_spec_int ("listen-backlog",
746 P_("Listen backlog"),
747 P_("outstanding connections in the listen queue"),
751 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
753 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
754 g_param_spec_boolean ("keepalive",
755 P_("Keep connection alive"),
756 P_("Keep connection alive by sending periodic pings"),
758 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
760 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
761 g_param_spec_object ("local-address",
763 P_("The local address the socket is bound to"),
764 G_TYPE_SOCKET_ADDRESS,
765 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
767 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
768 g_param_spec_object ("remote-address",
769 P_("Remote address"),
770 P_("The remote address the socket is connected to"),
771 G_TYPE_SOCKET_ADDRESS,
772 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
776 g_socket_initable_iface_init (GInitableIface *iface)
778 iface->init = g_socket_initable_init;
782 g_socket_init (GSocket *socket)
784 socket->priv = G_TYPE_INSTANCE_GET_PRIVATE (socket, G_TYPE_SOCKET, GSocketPrivate);
786 socket->priv->fd = -1;
787 socket->priv->blocking = TRUE;
788 socket->priv->listen_backlog = 10;
789 socket->priv->construct_error = NULL;
791 socket->priv->event = WSA_INVALID_EVENT;
796 g_socket_initable_init (GInitable *initable,
797 GCancellable *cancellable,
802 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
804 socket = G_SOCKET (initable);
806 if (cancellable != NULL)
808 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
809 _("Cancellable initialization not supported"));
813 socket->priv->inited = TRUE;
815 if (socket->priv->construct_error)
818 *error = g_error_copy (socket->priv->construct_error);
828 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
829 * @type: the socket type to use.
830 * @protocol_id: the id of the protocol to use, or 0 for default.
831 * @error: #GError for error reporting, or %NULL to ignore.
833 * Creates a new #GSocket with the defined family, type and protocol.
834 * If @protocol_id is 0 the default protocol type for the family and
837 * The @protocol_id is a family and type specific int that specifies what
838 * kind of protocol to use. Many families only support one protocol,
839 * and use 0 for this, others support several and using 0 means
840 * to use the default protocol for the family and type. To use
841 * other protocol, you can use g_socket_protocol_id_lookup_by_name()
842 * to look up the protocol by name, or if you known the system specific
843 * protocol id you can use that.
845 * Returns: a #GSocket or %NULL on error.
846 * Free the returned object with g_object_unref().
851 g_socket_new (GSocketFamily family,
856 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
860 "protocol", protocol_id,
865 * g_socket_new_from_fd:
866 * @fd: a native socket file descriptor.
867 * @error: #GError for error reporting, or %NULL to ignore.
869 * Creates a new #GSocket from a native file descriptor
870 * or winsock SOCKET handle.
872 * This reads all the settings from the file descriptor so that
873 * all properties should work. Note that the file descriptor
874 * will be set to non-blocking mode, independent on the blocking
875 * mode of the #GSocket.
877 * Returns: a #GSocket or %NULL on error.
878 * Free the returned object with g_object_unref().
883 g_socket_new_from_fd (gint fd,
886 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
893 * g_socket_set_blocking:
894 * @socket: a #GSocket.
895 * @blocking: Whether to use blocking I/O or not.
897 * Sets the blocking mode of the socket. In blocking mode
898 * all operations block until they succeed or there is an error. In
899 * non-blocking mode all functions return results immediately or
900 * with a %G_IO_ERROR_WOULD_BLOCK error.
902 * All sockets are created in blocking mode. However, note that the
903 * platform level socket is always non-blocking, and blocking mode
904 * is a GSocket level feature.
909 g_socket_set_blocking (GSocket *socket,
912 g_return_if_fail (G_IS_SOCKET (socket));
914 blocking = !!blocking;
916 if (socket->priv->blocking == blocking)
919 socket->priv->blocking = blocking;
920 g_object_notify (G_OBJECT (socket), "blocking");
924 * g_socket_get_blocking:
925 * @socket: a #GSocket.
927 * Gets the blocking mode of the socket. For details on blocking I/O,
928 * see g_socket_set_blocking().
930 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
935 g_socket_get_blocking (GSocket *socket)
937 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
939 return socket->priv->blocking;
943 * g_socket_set_keepalive:
944 * @socket: a #GSocket.
945 * @keepalive: Whether to use try to keep the connection alive or not.
947 * Setting @keepalive to %TRUE enables the sending of periodic ping requests
948 * on idle connections in order to keep the connection alive. This is only
949 * useful for connection oriented sockets. The exact period used between
950 * each ping is system and protocol dependent.
952 * Sending keepalive requests like this has a few disadvantages. For instance,
953 * it uses more network bandwidth, and it makes your application more sensitive
954 * to temporary outages in the network (i.e. if a cable is pulled your otherwise
955 * idle connection could be terminated, whereas otherwise it would survive unless
956 * actually used before the cable was reinserted). However, it is sometimes
957 * useful to ensure that connections are eventually terminated if e.g. the
958 * remote side is disconnected, so as to avoid leaking resources forever.
963 g_socket_set_keepalive (GSocket *socket,
968 g_return_if_fail (G_IS_SOCKET (socket));
970 keepalive = !!keepalive;
971 if (socket->priv->keepalive == keepalive)
974 value = (gint) keepalive;
975 if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_KEEPALIVE,
976 (gpointer) &value, sizeof (value)) < 0)
978 int errsv = get_socket_errno ();
979 g_warning ("error setting keepalive: %s", socket_strerror (errsv));
983 socket->priv->keepalive = keepalive;
984 g_object_notify (G_OBJECT (socket), "keepalive");
988 * g_socket_get_keepalive:
989 * @socket: a #GSocket.
991 * Gets the keepalive mode of the socket. For details on this,
992 * see g_socket_set_keepalive().
994 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
999 g_socket_get_keepalive (GSocket *socket)
1001 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1003 return socket->priv->keepalive;
1007 * g_socket_get_listen_backlog:
1008 * @socket: a #GSocket.
1010 * Gets the listen backlog setting of the socket. For details on this,
1011 * see g_socket_set_listen_backlog().
1013 * Returns: the maximum number of pending connections.
1018 g_socket_get_listen_backlog (GSocket *socket)
1020 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1022 return socket->priv->listen_backlog;
1026 * g_socket_set_listen_backlog:
1027 * @socket: a #GSocket.
1028 * @backlog: the maximum number of pending connections.
1030 * Sets the maximum number of outstanding connections allowed
1031 * when listening on this socket. If more clients than this are
1032 * connecting to the socket and the application is not handling them
1033 * on time then the new connections will be refused.
1038 g_socket_set_listen_backlog (GSocket *socket,
1041 g_return_if_fail (G_IS_SOCKET (socket));
1043 if (backlog != socket->priv->listen_backlog)
1045 socket->priv->listen_backlog = backlog;
1046 g_object_notify (G_OBJECT (socket), "listen-backlog");
1051 * g_socket_get_family:
1052 * @socket: a #GSocket.
1054 * Gets the socket family of the socket.
1056 * Returns: a #GSocketFamily
1061 g_socket_get_family (GSocket *socket)
1063 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1065 return socket->priv->family;
1069 * g_socket_get_socket_type:
1070 * @socket: a #GSocket.
1072 * Gets the socket type of the socket.
1074 * Returns: a #GSocketType
1079 g_socket_get_socket_type (GSocket *socket)
1081 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1083 return socket->priv->type;
1087 * g_socket_get_protocol_id:
1088 * @socket: a #GSocket.
1090 * Gets the socket protocol id the socket was created with.
1091 * In case the protocol is unknown, -1 is returned.
1093 * Returns: a protocol id, or -1 if unknown
1098 g_socket_get_protocol_id (GSocket *socket)
1100 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1102 return socket->priv->protocol;
1106 * g_socket_get_protocol_name:
1107 * @socket: a #GSocket.
1109 * Gets the socket protocol type name the socket was created with.
1110 * This can be %NULL if the socket was created with a NULL protocol.
1112 * Returns: a string or %NULL, free with g_free
1117 g_socket_get_protocol_name (GSocket *socket)
1119 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1121 return get_protocol_name (socket->priv->protocol);
1126 * @socket: a #GSocket.
1128 * Returns the underlying OS socket object. On unix this
1129 * is a socket file descriptor, and on windows this is
1130 * a Winsock2 SOCKET handle. This may be useful for
1131 * doing platform specific or otherwise unusual operations
1134 * Returns: the file descriptor of the socket.
1139 g_socket_get_fd (GSocket *socket)
1141 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1143 return socket->priv->fd;
1147 * g_socket_get_local_address:
1148 * @socket: a #GSocket.
1149 * @error: #GError for error reporting, or %NULL to ignore.
1151 * Try to get the local address of a bound socket. This is only
1152 * useful if the socket has been bound to a local address,
1153 * either explicitly or implicitly when connecting.
1155 * Returns: a #GSocketAddress or %NULL on error.
1156 * Free the returned object with g_object_unref().
1161 g_socket_get_local_address (GSocket *socket,
1164 struct sockaddr_storage buffer;
1165 guint32 len = sizeof (buffer);
1167 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1169 if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1171 int errsv = get_socket_errno ();
1172 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1173 _("could not get local address: %s"), socket_strerror (errsv));
1177 return g_socket_address_new_from_native (&buffer, len);
1181 * g_socket_get_remote_address:
1182 * @socket: a #GSocket.
1183 * @error: #GError for error reporting, or %NULL to ignore.
1185 * Try to get the remove address of a connected socket. This is only
1186 * useful for connection oriented sockets that have been connected.
1188 * Returns: a #GSocketAddress or %NULL on error.
1189 * Free the returned object with g_object_unref().
1194 g_socket_get_remote_address (GSocket *socket,
1197 struct sockaddr_storage buffer;
1198 guint32 len = sizeof (buffer);
1200 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1202 if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1204 int errsv = get_socket_errno ();
1205 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1206 _("could not get remote address: %s"), socket_strerror (errsv));
1210 return g_socket_address_new_from_native (&buffer, len);
1214 * g_socket_is_connected:
1215 * @socket: a #GSocket.
1217 * Check whether the socket is connected. This is only useful for
1218 * connection-oriented sockets.
1220 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1225 g_socket_is_connected (GSocket *socket)
1227 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1229 return socket->priv->connected;
1234 * @socket: a #GSocket.
1235 * @error: #GError for error reporting, or %NULL to ignore.
1237 * Marks the socket as a server socket, i.e. a socket that is used
1238 * to accept incoming requests using g_socket_accept().
1240 * Before calling this the socket must be bound to a local address using
1243 * Returns: %TRUE on success, %FALSE on error.
1248 g_socket_listen (GSocket *socket,
1251 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1253 if (!check_socket (socket, error))
1256 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1258 int errsv = get_socket_errno ();
1260 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1261 _("could not listen: %s"), socket_strerror (errsv));
1270 * @socket: a #GSocket.
1271 * @address: a #GSocketAddress specifying the local address.
1272 * @allow_reuse: whether to allow reusing this address
1273 * @error: #GError for error reporting, or %NULL to ignore.
1275 * When a socket is created it is attached to an address family, but it
1276 * doesn't have an address in this family. g_socket_bind() assigns the
1277 * address (sometimes called name) of the socket.
1279 * It is generally required to bind to a local address before you can
1280 * receive connections. (See g_socket_listen() and g_socket_accept() ).
1282 * If @allow_reuse is %TRUE this allows the bind call to succeed in some
1283 * situation where it would otherwise return a %G_IO_ERROR_ADDRESS_IN_USE
1284 * error. The main example is for a TCP server socket where there are
1285 * outstanding connections in the WAIT state, which are generally safe
1286 * to ignore. However, setting it to %TRUE doesn't mean the call will
1287 * succeed if there is a socket actively bound to the address.
1289 * In general, pass %TRUE if the socket will be used to accept connections,
1290 * otherwise pass %FALSE.
1292 * Returns: %TRUE on success, %FALSE on error.
1297 g_socket_bind (GSocket *socket,
1298 GSocketAddress *address,
1299 gboolean reuse_address,
1302 struct sockaddr_storage addr;
1305 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1307 if (!check_socket (socket, error))
1310 /* SO_REUSEADDR on windows means something else and is not what we want.
1311 It always allows the unix variant of SO_REUSEADDR anyway */
1313 value = (int) !!reuse_address;
1314 /* Ignore errors here, the only likely error is "not supported", and
1315 this is a "best effort" thing mainly */
1316 setsockopt (socket->priv->fd, SOL_SOCKET, SO_REUSEADDR,
1317 (gpointer) &value, sizeof (value));
1320 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1323 if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1324 g_socket_address_get_native_size (address)) < 0)
1326 int errsv = get_socket_errno ();
1328 G_IO_ERROR, socket_io_error_from_errno (errsv),
1329 _("Error binding to address: %s"), socket_strerror (errsv));
1338 * @socket: a #GSocket.
1339 * @error: #GError for error reporting, or %NULL to ignore.
1341 * Accept incoming connections on a connection-based socket. This removes
1342 * the first outstanding connection request from the listening socket and
1343 * creates a #GSocket object for it.
1345 * The @socket must be bound to a local address with g_socket_bind() and
1346 * must be listening for incoming connections (g_socket_listen()).
1348 * If there are no outstanding connections then the operation will block
1349 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
1350 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
1352 * Returns: a new #GSocket, or %NULL on error.
1353 * Free the returned object with g_object_unref().
1358 g_socket_accept (GSocket *socket,
1361 GSocket *new_socket;
1364 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1366 if (!check_socket (socket, error))
1371 if (socket->priv->blocking &&
1372 !g_socket_condition_wait (socket,
1373 G_IO_IN, NULL, error))
1376 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
1378 int errsv = get_socket_errno ();
1380 win32_unset_event_mask (socket, FD_ACCEPT);
1385 if (socket->priv->blocking)
1387 #ifdef WSAEWOULDBLOCK
1388 if (errsv == WSAEWOULDBLOCK)
1391 if (errsv == EWOULDBLOCK ||
1397 g_set_error (error, G_IO_ERROR,
1398 socket_io_error_from_errno (errsv),
1399 _("Error accepting connection: %s"), socket_strerror (errsv));
1405 win32_unset_event_mask (socket, FD_ACCEPT);
1409 /* The socket inherits the accepting sockets event mask and even object,
1410 we need to remove that */
1411 WSAEventSelect (ret, NULL, 0);
1417 /* We always want to set close-on-exec to protect users. If you
1418 need to so some weird inheritance to exec you can re-enable this
1419 using lower level hacks with g_socket_get_fd(). */
1420 flags = fcntl (ret, F_GETFD, 0);
1422 (flags & FD_CLOEXEC) == 0)
1424 flags |= FD_CLOEXEC;
1425 fcntl (ret, F_SETFD, flags);
1430 new_socket = g_socket_new_from_fd (ret, error);
1431 if (new_socket == NULL)
1440 new_socket->priv->protocol = socket->priv->protocol;
1447 * @socket: a #GSocket.
1448 * @address: a #GSocketAddress specifying the remote address.
1449 * @error: #GError for error reporting, or %NULL to ignore.
1451 * Connect the socket to the specified remote address.
1453 * For connection oriented socket this generally means we attempt to make
1454 * a connection to the @address. For a connection-less socket it sets
1455 * the default address for g_socket_send() and discards all incoming datagrams
1456 * from other sources.
1458 * Generally connection oriented sockets can only connect once, but connection-less
1459 * sockets can connect multiple times to change the default address.
1461 * If the connect call needs to do network I/O it will block, unless
1462 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
1463 * and the user can be notified of the connection finishing by waiting
1464 * for the G_IO_OUT condition. The result of the connection can then be
1465 * checked with g_socket_check_pending_error().
1467 * Returns: %TRUE if connected, %FALSE on error.
1472 g_socket_connect (GSocket *socket,
1473 GSocketAddress *address,
1476 struct sockaddr_storage buffer;
1478 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1480 if (!check_socket (socket, error))
1483 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
1488 if (socket->priv->blocking &&
1489 !g_socket_condition_wait (socket,
1490 G_IO_IN, NULL, error))
1493 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
1494 g_socket_address_get_native_size (address)) < 0)
1496 int errsv = get_socket_errno ();
1502 if (errsv == EINPROGRESS)
1504 if (errsv == WSAEINPROGRESS)
1507 if (socket->priv->blocking)
1509 g_socket_condition_wait (socket, G_IO_OUT, NULL, NULL);
1510 if (g_socket_check_pending_error (socket, error))
1513 g_prefix_error (error, _("Error connecting: "));
1516 g_set_error (error, G_IO_ERROR, G_IO_ERROR_PENDING,
1517 _("Connection in progress"));
1520 g_set_error (error, G_IO_ERROR,
1521 socket_io_error_from_errno (errsv),
1522 _("Error connecting: %s"), socket_strerror (errsv));
1529 win32_unset_event_mask (socket, FD_CONNECT);
1531 socket->priv->connected = TRUE;
1537 * g_socket_check_pending_error:
1538 * @socket: a #GSocket
1539 * @error: #GError for error reporting, or %NULL to ignore.
1541 * Checks and resets the pending error for the socket. This is typically
1542 * used to check for errors when g_socket_connect() is used in non-blocking mode.
1544 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
1549 g_socket_check_pending_error (GSocket *socket,
1555 optlen = sizeof (value);
1556 if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
1558 int errsv = get_socket_errno ();
1560 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1561 _("Unable to get pending error: %s"), socket_strerror (errsv));
1567 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (value),
1568 "%s", socket_strerror (value));
1576 * @socket: a #GSocket
1577 * @buffer: a buffer to read data into (which should be at least count bytes long).
1578 * @size: the number of bytes that will be read from the stream
1579 * @error: #GError for error reporting, or %NULL to ignore.
1581 * Receive data (up to @size bytes) from a socket. This is mainly used by
1582 * connection oriented sockets, it is identical to g_socket_receive_from()
1583 * with @address set to %NULL.
1585 * If a message is too long to fit in @buffer, excess bytes may be discarded
1586 * depending on the type of socket the message is received from.
1588 * If the socket is in blocking mode the call will block until there is
1589 * some data to receive or there is an error. If there is no data available
1590 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1591 * will be returned. To be notified of available data, wait for the %G_IO_IN
1594 * On error -1 is returned and @error is set accordingly.
1596 * Returns: Number of bytes read, or -1 on error
1601 g_socket_receive (GSocket *socket,
1608 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1610 if (!check_socket (socket, error))
1615 if (socket->priv->blocking &&
1616 !g_socket_condition_wait (socket,
1617 G_IO_IN, NULL, error))
1620 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
1622 int errsv = get_socket_errno ();
1627 if (socket->priv->blocking)
1629 #ifdef WSAEWOULDBLOCK
1630 if (errsv == WSAEWOULDBLOCK)
1633 if (errsv == EWOULDBLOCK ||
1639 win32_unset_event_mask (socket, FD_READ);
1641 g_set_error (error, G_IO_ERROR,
1642 socket_io_error_from_errno (errsv),
1643 _("Error receiving data: %s"), socket_strerror (errsv));
1647 win32_unset_event_mask (socket, FD_READ);
1656 * g_socket_receive_from:
1657 * @socket: a #GSocket
1658 * @address: a pointer to a #GSocketAddress pointer, or %NULL
1659 * @buffer: a buffer to read data into (which should be at least count bytes long).
1660 * @size: the number of bytes that will be read from the stream
1661 * @error: #GError for error reporting, or %NULL to ignore.
1663 * Receive data (up to @size bytes) from a socket.
1665 * If @address is non-%NULL then @address will be set equal to the
1666 * source address of the received packet.
1667 * @address is owned by the caller.
1669 * If the socket is in blocking mode the call will block until there is
1670 * some data to receive or there is an error. If there is no data available
1671 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1672 * will be returned. To be notified of available data, wait for the %G_IO_IN
1675 * On error -1 is returned and @error is set accordingly.
1677 * Returns: Number of bytes read, or -1 on error
1682 g_socket_receive_from (GSocket *socket,
1683 GSocketAddress **address,
1693 return g_socket_receive_message (socket,
1702 * @socket: a #GSocket
1703 * @buffer: the buffer containing the data to send.
1704 * @size: the number of bytes to send
1705 * @error: #GError for error reporting, or %NULL to ignore.
1707 * Tries to send @size bytes from @buffer on the socket. This is mainly used by
1708 * connection oriented sockets, it is identical to g_socket_send_to()
1709 * with @address set to %NULL.
1711 * If the socket is in blocking mode the call will block until there is
1712 * space for the data in the socket queue. If there is no space available
1713 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1714 * will be returned. To be notified of available space, wait for the %G_IO_OUT
1717 * Note that on Windows you can't rely on a %G_IO_OUT condition
1718 * not producing a %G_IO_ERROR_WOULD_BLOCK error, as this is how Winsock
1719 * write notification works. However, robust apps should always be able to
1720 * handle this since it can easily appear in other cases too.
1722 * On error -1 is returned and @error is set accordingly.
1724 * Returns: Number of bytes read, or -1 on error
1729 g_socket_send (GSocket *socket,
1730 const gchar *buffer,
1736 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1738 if (!check_socket (socket, error))
1743 if (socket->priv->blocking &&
1744 !g_socket_condition_wait (socket,
1745 G_IO_OUT, NULL, error))
1748 if ((ret = send (socket->priv->fd, buffer, size, 0)) < 0)
1750 int errsv = get_socket_errno ();
1755 #ifdef WSAEWOULDBLOCK
1756 if (errsv == WSAEWOULDBLOCK)
1757 win32_unset_event_mask (socket, FD_WRITE);
1760 if (socket->priv->blocking)
1762 #ifdef WSAEWOULDBLOCK
1763 if (errsv == WSAEWOULDBLOCK)
1766 if (errsv == EWOULDBLOCK ||
1772 g_set_error (error, G_IO_ERROR,
1773 socket_io_error_from_errno (errsv),
1774 _("Error sending data: %s"), socket_strerror (errsv));
1785 * @socket: a #GSocket
1786 * @address: a #GSocketAddress, or %NULL
1787 * @buffer: the buffer containing the data to send.
1788 * @size: the number of bytes to send
1789 * @error: #GError for error reporting, or %NULL to ignore.
1791 * Tries to send @size bytes from @buffer to @address. If @address is
1792 * %NULL then the message is sent to the default receiver (set by
1793 * g_socket_connect()).
1795 * If the socket is in blocking mode the call will block until there is
1796 * space for the data in the socket queue. If there is no space available
1797 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1798 * will be returned. To be notified of available space, wait for the %G_IO_OUT
1801 * Note that on Windows you can't rely on a %G_IO_OUT condition
1802 * not producing a %G_IO_ERROR_WOULD_BLOCK error, as this is how Winsock
1803 * write notification works. However, robust apps should always be able to
1804 * handle this since it can easily appear in other cases too.
1806 * On error -1 is returned and @error is set accordingly.
1808 * Returns: Number of bytes read, or -1 on error
1813 g_socket_send_to (GSocket *socket,
1814 GSocketAddress *address,
1815 const gchar *buffer,
1824 return g_socket_send_message (socket,
1833 * @socket: a #GSocket
1834 * @error: #GError for error reporting, or %NULL to ignore.
1836 * Closes the socket, shutting down any active connection.
1838 * Closing a socket does not wait for all outstanding I/O operations to finish,
1839 * so the caller should not rely on them to be guaranteed to complete even
1840 * if the close returns with no error.
1842 * Once the socket is closed, all other operations will return %G_IO_ERROR_CLOSED.
1843 * Closing a stream multiple times will not return an error.
1845 * Sockets will be automatically closed when the last reference
1846 * is dropped, but you might want to call this function to make sure
1847 * resources are released as early as possible.
1849 * Returns: %TRUE on success, %FALSE on error
1854 g_socket_close (GSocket *socket,
1859 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
1861 if (socket->priv->closed)
1862 return TRUE; /* Multiple close not an error */
1864 if (!check_socket (socket, NULL))
1870 res = closesocket (socket->priv->fd);
1872 res = close (socket->priv->fd);
1876 int errsv = get_socket_errno ();
1881 g_set_error (error, G_IO_ERROR,
1882 socket_io_error_from_errno (errsv),
1883 _("Error closing socket: %s"),
1884 socket_strerror (errsv));
1891 if (socket->priv->event != WSA_INVALID_EVENT)
1893 WSACloseEvent (socket->priv->event);
1894 socket->priv->event = WSA_INVALID_EVENT;
1898 socket->priv->connected = FALSE;
1899 socket->priv->closed = TRUE;
1905 * g_socket_is_closed:
1906 * @socket: a #GSocket
1908 * Checks whether a socket is closed.
1910 * Returns: %TRUE if socket is closed, %FALSE otherwise
1915 g_socket_is_closed (GSocket *socket)
1917 return socket->priv->closed;
1921 /* Broken source, used on errors */
1923 broken_prepare (GSource *source,
1930 broken_check (GSource *source)
1936 broken_dispatch (GSource *source,
1937 GSourceFunc callback,
1943 static GSourceFuncs broken_funcs =
1952 network_events_for_condition (GIOCondition condition)
1956 if (condition & G_IO_IN)
1957 event_mask |= (FD_READ | FD_ACCEPT);
1958 if (condition & G_IO_OUT)
1959 event_mask |= (FD_WRITE | FD_CONNECT);
1960 event_mask |= FD_CLOSE;
1966 ensure_event (GSocket *socket)
1968 if (socket->priv->event == WSA_INVALID_EVENT)
1969 socket->priv->event = WSACreateEvent();
1973 update_select_events (GSocket *socket)
1980 ensure_event (socket);
1983 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
1986 event_mask |= network_events_for_condition (*ptr);
1989 if (event_mask != socket->priv->selected_events)
1991 /* If no events selected, disable event so we can unset
1994 if (event_mask == 0)
1997 event = socket->priv->event;
1999 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
2000 socket->priv->selected_events = event_mask;
2005 add_condition_watch (GSocket *socket,
2006 GIOCondition *condition)
2008 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
2010 socket->priv->requested_conditions =
2011 g_list_prepend (socket->priv->requested_conditions, condition);
2013 update_select_events (socket);
2017 remove_condition_watch (GSocket *socket,
2018 GIOCondition *condition)
2020 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
2022 socket->priv->requested_conditions =
2023 g_list_remove (socket->priv->requested_conditions, condition);
2025 update_select_events (socket);
2029 update_condition (GSocket *socket)
2031 WSANETWORKEVENTS events;
2032 GIOCondition condition;
2034 if (WSAEnumNetworkEvents (socket->priv->fd,
2035 socket->priv->event,
2038 socket->priv->current_events |= events.lNetworkEvents;
2039 if (events.lNetworkEvents & FD_WRITE &&
2040 events.iErrorCode[FD_WRITE_BIT] != 0)
2041 socket->priv->current_errors |= FD_WRITE;
2042 if (events.lNetworkEvents & FD_CONNECT &&
2043 events.iErrorCode[FD_CONNECT_BIT] != 0)
2044 socket->priv->current_errors |= FD_CONNECT;
2048 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
2049 condition |= G_IO_IN;
2051 if (socket->priv->current_events & FD_CLOSE ||
2052 socket->priv->closed)
2053 condition |= G_IO_HUP;
2055 /* Never report both G_IO_OUT and HUP, these are
2056 mutually exclusive (can't write to a closed socket) */
2057 if ((condition & G_IO_HUP) == 0 &&
2058 socket->priv->current_events & FD_WRITE)
2060 if (socket->priv->current_errors & FD_WRITE)
2061 condition |= G_IO_ERR;
2063 condition |= G_IO_OUT;
2067 if (socket->priv->current_events & FD_CONNECT)
2069 if (socket->priv->current_errors & FD_CONNECT)
2070 condition |= (G_IO_HUP | G_IO_ERR);
2072 condition |= G_IO_OUT;
2083 GIOCondition condition;
2084 GCancellable *cancellable;
2085 GPollFD cancel_pollfd;
2086 GIOCondition result_condition;
2090 winsock_prepare (GSource *source,
2093 GWinsockSource *winsock_source = (GWinsockSource *)source;
2094 GIOCondition current_condition;
2096 current_condition = update_condition (winsock_source->socket);
2098 if (g_cancellable_is_cancelled (winsock_source->cancellable))
2100 winsock_source->result_condition = current_condition;
2104 if ((winsock_source->condition & current_condition) != 0)
2106 winsock_source->result_condition = current_condition;
2114 winsock_check (GSource *source)
2116 GWinsockSource *winsock_source = (GWinsockSource *)source;
2117 GIOCondition current_condition;
2119 current_condition = update_condition (winsock_source->socket);
2121 if (g_cancellable_is_cancelled (winsock_source->cancellable))
2123 winsock_source->result_condition = current_condition;
2127 if ((winsock_source->condition & current_condition) != 0)
2129 winsock_source->result_condition = current_condition;
2137 winsock_dispatch (GSource *source,
2138 GSourceFunc callback,
2141 GSocketSourceFunc func = (GSocketSourceFunc)callback;
2142 GWinsockSource *winsock_source = (GWinsockSource *)source;
2144 return (*func) (winsock_source->socket,
2145 winsock_source->result_condition & winsock_source->condition,
2150 winsock_finalize (GSource *source)
2152 GWinsockSource *winsock_source = (GWinsockSource *)source;
2155 socket = winsock_source->socket;
2157 remove_condition_watch (socket, &winsock_source->condition);
2158 g_object_unref (socket);
2160 if (winsock_source->cancellable)
2161 g_object_unref (winsock_source->cancellable);
2164 static GSourceFuncs winsock_funcs =
2173 winsock_source_new (GSocket *socket,
2174 GIOCondition condition,
2175 GCancellable *cancellable)
2178 GWinsockSource *winsock_source;
2180 ensure_event (socket);
2182 if (socket->priv->event == WSA_INVALID_EVENT)
2184 g_warning ("Failed to create WSAEvent");
2185 return g_source_new (&broken_funcs, sizeof (GSource));
2188 condition |= G_IO_HUP | G_IO_ERR;
2190 source = g_source_new (&winsock_funcs, sizeof (GWinsockSource));
2191 winsock_source = (GWinsockSource *)source;
2193 winsock_source->socket = g_object_ref (socket);
2194 winsock_source->condition = condition;
2195 add_condition_watch (socket, &winsock_source->condition);
2199 winsock_source->cancellable = g_object_ref (cancellable);
2200 g_cancellable_make_pollfd (cancellable,
2201 &winsock_source->cancel_pollfd);
2202 g_source_add_poll (source, &winsock_source->cancel_pollfd);
2205 winsock_source->pollfd.fd = (gintptr) socket->priv->event;
2206 winsock_source->pollfd.events = condition;
2207 g_source_add_poll (source, &winsock_source->pollfd);
2214 * g_socket_create_source:
2215 * @socket: a #GSocket
2216 * @condition: a #GIOCondition mask to monitor
2217 * @cancellable: a %GCancellable or %NULL
2219 * Creates a %GSource that can be attached to a %GMainContext to monitor
2220 * for the availibility of the specified @condition on the socket.
2222 * The callback on the source is of the #GSocketSourceFunc type.
2224 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2225 * these conditions will always be reported output if they are true.
2227 * @cancellable if not %NULL can be used to cancel the source, which will
2228 * cause the source to trigger, reporting the current condition. You can
2229 * check for this in the callback using g_cancellable_is_cancelled().
2231 * Returns: a newly allocated %GSource, free with g_source_unref().
2236 g_socket_create_source (GSocket *socket,
2237 GIOCondition condition,
2238 GCancellable *cancellable)
2241 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
2244 source = winsock_source_new (socket, condition, cancellable);
2246 source =_g_fd_source_new_with_object (G_OBJECT (socket), socket->priv->fd,
2247 condition, cancellable);
2253 * g_socket_condition_check:
2254 * @socket: a #GSocket
2255 * @condition: a #GIOCondition mask to check
2257 * Checks on the readiness of @socket to perform operations. The
2258 * operations specified in @condition are checked for and masked
2259 * against the currently-satisfied conditions on @socket. The result
2262 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2263 * these conditions will always be set in the output if they are true.
2265 * This call never blocks.
2267 * Returns: the @GIOCondition mask of the current state
2272 g_socket_condition_check (GSocket *socket,
2273 GIOCondition condition)
2275 if (!check_socket (socket, NULL))
2280 GIOCondition current_condition;
2282 condition |= G_IO_ERR | G_IO_HUP;
2284 add_condition_watch (socket, &condition);
2285 current_condition = update_condition (socket);
2286 remove_condition_watch (socket, &condition);
2287 return condition & current_condition;
2293 poll_fd.fd = socket->priv->fd;
2294 poll_fd.events = condition;
2297 result = g_poll (&poll_fd, 1, 0);
2298 while (result == -1 && get_socket_errno () == EINTR);
2300 return poll_fd.revents;
2306 * g_socket_condition_wait:
2307 * @socket: a #GSocket
2308 * @condition: a #GIOCondition mask to wait for
2309 * @cancellable: a #GCancellable, or %NULL
2310 * @error: a #GError pointer, or %NULL
2312 * Waits for @condition to become true on @socket. When the condition
2313 * becomes true, %TRUE is returned.
2315 * If @cancellable is cancelled before the condition becomes true then
2316 * %FALSE is returned and @error, if non-%NULL, is set to %G_IO_ERROR_CANCELLED.
2318 * Returns: %TRUE if the condition was met, %FALSE otherwise
2323 g_socket_condition_wait (GSocket *socket,
2324 GIOCondition condition,
2325 GCancellable *cancellable,
2328 if (!check_socket (socket, error))
2331 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2336 GIOCondition current_condition;
2342 /* Always check these */
2343 condition |= G_IO_ERR | G_IO_HUP;
2345 add_condition_watch (socket, &condition);
2348 events[num_events++] = socket->priv->event;
2352 g_cancellable_make_pollfd (cancellable, &cancel_fd);
2353 events[num_events++] = (WSAEVENT)cancel_fd.fd;
2356 current_condition = update_condition (socket);
2357 while ((condition & current_condition) == 0)
2359 res = WSAWaitForMultipleEvents(num_events, events,
2360 FALSE, WSA_INFINITE, FALSE);
2361 if (res == WSA_WAIT_FAILED)
2363 int errsv = get_socket_errno ();
2365 g_set_error (error, G_IO_ERROR,
2366 socket_io_error_from_errno (errsv),
2367 _("Waiting for socket condition: %s"),
2368 socket_strerror (errsv));
2372 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2375 current_condition = update_condition (socket);
2377 remove_condition_watch (socket, &condition);
2379 return (condition & current_condition) != 0;
2387 poll_fd[0].fd = socket->priv->fd;
2388 poll_fd[0].events = condition;
2393 g_cancellable_make_pollfd (cancellable, &poll_fd[1]);
2398 result = g_poll (poll_fd, num, -1);
2399 while (result == -1 && get_socket_errno () == EINTR);
2401 return cancellable == NULL ||
2402 !g_cancellable_set_error_if_cancelled (cancellable, error);
2408 * g_socket_send_message:
2409 * @socket: a #GSocket
2410 * @address: a #GSocketAddress, or %NULL
2411 * @vectors: an array of #GOutputVector structs
2412 * @num_vectors: the number of elements in @vectors, or -1
2413 * @messages: a pointer to an array of #GSocketControlMessages, or
2415 * @num_messages: number of elements in @messages, or -1.
2416 * @flags: an int containing #GSocketMsgFlags flags
2417 * @error: #GError for error reporting, or %NULL to ignore.
2419 * Send data to @address on @socket. This is the most complicated and
2420 * fully-featured version of this call. For easier use, see
2421 * g_socket_send() and g_socket_send_to().
2423 * If @address is %NULL then the message is sent to the default receiver
2424 * (set by g_socket_connect()).
2426 * @vector must point to an array of #GOutputVector structs and
2427 * @num_vectors must be the length of this array. These structs
2428 * describe the buffers that the sent data will be gathered from.
2429 * If @num_vector is -1, then @vector is assumed to be terminated
2430 * by a #GOutputVector with a %NULL buffer pointer.
2433 * @messages, if non-%NULL, is taken to point to an array of @num_messages
2434 * #GSocketControlMessage instances. These correspond to the control
2435 * messages to be sent on the socket.
2436 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
2439 * @flags modify how the message sent. The commonly available arguments
2440 * for this is available in the #GSocketMsgFlags enum, but the
2441 * values there are the same as the system values, and the flags
2442 * are passed in as-is, so you can pass in system specific flags too.
2444 * If the socket is in blocking mode the call will block until there is
2445 * space for the data in the socket queue. If there is no space available
2446 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2447 * will be returned. To be notified of available space, wait for the %G_IO_OUT
2450 * Note that on Windows you can't rely on a %G_IO_OUT condition
2451 * not producing a %G_IO_ERROR_WOULD_BLOCK error, as this is how Winsock
2452 * write notification works. However, robust apps should always be able to
2453 * handle this since it can easily appear in other cases too.
2455 * On error -1 is returned and @error is set accordingly.
2457 * Returns: Number of bytes read, or -1 on error
2462 g_socket_send_message (GSocket *socket,
2463 GSocketAddress *address,
2464 GOutputVector *vectors,
2466 GSocketControlMessage **messages,
2471 GOutputVector one_vector;
2474 if (!check_socket (socket, error))
2477 if (num_vectors == -1)
2479 for (num_vectors = 0;
2480 vectors[num_vectors].buffer != NULL;
2485 if (num_messages == -1)
2487 for (num_messages = 0;
2488 messages != NULL && messages[num_messages] != NULL;
2493 if (num_vectors == 0)
2497 one_vector.buffer = &zero;
2498 one_vector.size = 1;
2500 vectors = &one_vector;
2511 msg.msg_namelen = g_socket_address_get_native_size (address);
2512 msg.msg_name = g_alloca (msg.msg_namelen);
2513 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
2519 /* this entire expression will be evaluated at compile time */
2520 if (sizeof *msg.msg_iov == sizeof *vectors &&
2521 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2522 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2523 G_STRUCT_OFFSET (GOutputVector, buffer) &&
2524 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2525 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2526 G_STRUCT_OFFSET (GOutputVector, size))
2527 /* ABI is compatible */
2529 msg.msg_iov = (struct iovec *) vectors;
2530 msg.msg_iovlen = num_vectors;
2533 /* ABI is incompatible */
2537 msg.msg_iov = g_newa (struct iovec, num_vectors);
2538 for (i = 0; i < num_vectors; i++)
2540 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
2541 msg.msg_iov[i].iov_len = vectors[i].size;
2543 msg.msg_iovlen = num_vectors;
2549 struct cmsghdr *cmsg;
2552 msg.msg_controllen = 0;
2553 for (i = 0; i < num_messages; i++)
2554 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
2556 msg.msg_control = g_alloca (msg.msg_controllen);
2558 cmsg = CMSG_FIRSTHDR (&msg);
2559 for (i = 0; i < num_messages; i++)
2561 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
2562 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
2563 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
2564 g_socket_control_message_serialize (messages[i],
2566 cmsg = CMSG_NXTHDR (&msg, cmsg);
2568 g_assert (cmsg == NULL);
2573 if (socket->priv->blocking &&
2574 !g_socket_condition_wait (socket,
2575 G_IO_OUT, NULL, error))
2578 result = sendmsg (socket->priv->fd, &msg, flags);
2581 int errsv = get_socket_errno ();
2586 if (socket->priv->blocking &&
2587 (errsv == EWOULDBLOCK ||
2591 g_set_error (error, G_IO_ERROR,
2592 socket_io_error_from_errno (errsv),
2593 _("Error sending message: %s"), socket_strerror (errsv));
2604 struct sockaddr_storage addr;
2611 /* Win32 doesn't support control messages.
2612 Actually this is possible for raw and datagram sockets
2613 via WSASendMessage on Vista or later, but that doesn't
2615 if (num_messages != 0)
2617 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2618 _("GSocketControlMessage not supported on windows"));
2623 bufs = g_newa (WSABUF, num_vectors);
2624 for (i = 0; i < num_vectors; i++)
2626 bufs[i].buf = (char *)vectors[i].buffer;
2627 bufs[i].len = (gulong)vectors[i].size;
2633 addrlen = g_socket_address_get_native_size (address);
2634 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
2640 if (socket->priv->blocking &&
2641 !g_socket_condition_wait (socket,
2642 G_IO_OUT, NULL, error))
2646 result = WSASendTo (socket->priv->fd,
2649 (const struct sockaddr *)&addr, addrlen,
2652 result = WSASend (socket->priv->fd,
2659 int errsv = get_socket_errno ();
2661 if (errsv == WSAEINTR)
2664 if (errsv == WSAEWOULDBLOCK)
2665 win32_unset_event_mask (socket, FD_WRITE);
2667 if (socket->priv->blocking &&
2668 errsv == WSAEWOULDBLOCK)
2671 g_set_error (error, G_IO_ERROR,
2672 socket_io_error_from_errno (errsv),
2673 _("Error sending message: %s"), socket_strerror (errsv));
2686 * g_socket_receive_message:
2687 * @socket: a #GSocket
2688 * @address: a pointer to a #GSocketAddress pointer, or %NULL
2689 * @vectors: an array of #GInputVector structs
2690 * @num_vectors: the number of elements in @vectors, or -1
2691 * @messages: a pointer which will be filled with an array of
2692 * #GSocketControlMessages, or %NULL
2693 * @num_messages: a pointer which will be filled with the number of
2694 * elements in @messages, or %NULL
2695 * @flags: a pointer to an int containing #GSocketMsgFlags flags
2696 * @error: a #GError pointer, or %NULL
2698 * Receive data from a socket. This is the most complicated and
2699 * fully-featured version of this call. For easier use, see
2700 * g_socket_receive() and g_socket_receive_from().
2702 * If @address is non-%NULL then @address will be set equal to the
2703 * source address of the received packet.
2704 * @address is owned by the caller.
2706 * @vector must point to an array of #GInputVector structs and
2707 * @num_vectors must be the length of this array. These structs
2708 * describe the buffers that received data will be scattered into.
2709 * If @num_vector is -1, then @vector is assumed to be terminated
2710 * by a #GInputVector with a %NULL buffer pointer.
2712 * As a special case, if the size of the array is zero (in which case,
2713 * @vectors may of course be %NULL), then a single byte is received
2714 * and discarded. This is to facilitate the common practice of
2715 * sending a single '\0' byte for the purposes of transferring
2718 * @messages, if non-%NULL, is taken to point to a pointer that will
2719 * be set to point to a newly-allocated array of
2720 * #GSocketControlMessage instances. These correspond to the control
2721 * messages received from the kernel, one #GSocketControlMessage per
2722 * message from the kernel. This array is %NULL-terminated and must be
2723 * freed by the caller using g_free().
2725 * @num_messages, if non-%NULL, will be set to the number of control
2726 * messages received.
2728 * If both @messages and @num_messages are non-%NULL, then
2729 * @num_messages gives the number of #GSocketControlMessage instances
2730 * in @messages (ie: not including the %NULL terminator).
2732 * @flags is an in/out parameter. The commonly available arguments
2733 * for this is available in the #GSocketMsgFlags enum, but the
2734 * values there are the same as the system values, and the flags
2735 * are passed in as-is, so you can pass in system specific flags too.
2737 * If the socket is in blocking mode the call will block until there is
2738 * some data to receive or there is an error. If there is no data available
2739 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2740 * will be returned. To be notified of available data, wait for the %G_IO_IN
2743 * On error -1 is returned and @error is set accordingly.
2745 * Returns: Number of bytes read, or -1 on error
2750 g_socket_receive_message (GSocket *socket,
2751 GSocketAddress **address,
2752 GInputVector *vectors,
2754 GSocketControlMessage ***messages,
2759 GInputVector one_vector;
2762 if (!check_socket (socket, error))
2765 if (num_vectors == -1)
2767 for (num_vectors = 0;
2768 vectors[num_vectors].buffer != NULL;
2773 if (num_vectors == 0)
2775 one_vector.buffer = &one_byte;
2776 one_vector.size = 1;
2778 vectors = &one_vector;
2785 struct sockaddr_storage one_sockaddr;
2790 msg.msg_name = &one_sockaddr;
2791 msg.msg_namelen = sizeof (struct sockaddr_storage);
2795 msg.msg_name = NULL;
2796 msg.msg_namelen = 0;
2800 /* this entire expression will be evaluated at compile time */
2801 if (sizeof *msg.msg_iov == sizeof *vectors &&
2802 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2803 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2804 G_STRUCT_OFFSET (GInputVector, buffer) &&
2805 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2806 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2807 G_STRUCT_OFFSET (GInputVector, size))
2808 /* ABI is compatible */
2810 msg.msg_iov = (struct iovec *) vectors;
2811 msg.msg_iovlen = num_vectors;
2814 /* ABI is incompatible */
2818 msg.msg_iov = g_newa (struct iovec, num_vectors);
2819 for (i = 0; i < num_vectors; i++)
2821 msg.msg_iov[i].iov_base = vectors[i].buffer;
2822 msg.msg_iov[i].iov_len = vectors[i].size;
2824 msg.msg_iovlen = num_vectors;
2828 msg.msg_control = g_alloca (2048);
2829 msg.msg_controllen = 2048;
2833 msg.msg_flags = *flags;
2840 if (socket->priv->blocking &&
2841 !g_socket_condition_wait (socket,
2842 G_IO_IN, NULL, error))
2845 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
2849 int errsv = get_socket_errno ();
2854 if (socket->priv->blocking &&
2855 (errsv == EWOULDBLOCK ||
2859 g_set_error (error, G_IO_ERROR,
2860 socket_io_error_from_errno (errsv),
2861 _("Error receiving message: %s"), socket_strerror (errsv));
2868 /* decode address */
2869 if (address != NULL)
2871 if (msg.msg_namelen > 0)
2872 *address = g_socket_address_new_from_native (msg.msg_name,
2878 /* decode control messages */
2880 GSocketControlMessage **my_messages = NULL;
2881 gint allocated = 0, index = 0;
2882 const gchar *scm_pointer;
2883 struct cmsghdr *cmsg;
2886 scm_pointer = (const gchar *) msg.msg_control;
2887 scm_size = msg.msg_controllen;
2889 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
2891 GSocketControlMessage *message;
2893 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
2895 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
2897 if (message == NULL)
2898 /* We've already spewed about the problem in the
2899 deserialization code, so just continue */
2902 if (index == allocated)
2904 /* estimated 99% case: exactly 1 control message */
2905 allocated = MIN (allocated * 2, 1);
2906 my_messages = g_new (GSocketControlMessage *, (allocated + 1));
2910 my_messages[index++] = message;
2914 *num_messages = index;
2918 my_messages[index++] = NULL;
2919 *messages = my_messages;
2925 /* free all those messages we just constructed.
2926 * we have to do it this way if the user ignores the
2927 * messages so that we will close any received fds.
2929 for (i = 0; i < index; i++)
2930 g_object_unref (my_messages[i]);
2931 g_free (my_messages);
2935 /* capture the flags */
2937 *flags = msg.msg_flags;
2943 struct sockaddr_storage addr;
2945 DWORD bytes_received;
2952 bufs = g_newa (WSABUF, num_vectors);
2953 for (i = 0; i < num_vectors; i++)
2955 bufs[i].buf = (char *)vectors[i].buffer;
2956 bufs[i].len = (gulong)vectors[i].size;
2968 if (socket->priv->blocking &&
2969 !g_socket_condition_wait (socket,
2970 G_IO_IN, NULL, error))
2973 addrlen = sizeof addr;
2975 result = WSARecvFrom (socket->priv->fd,
2977 &bytes_received, &win_flags,
2978 (struct sockaddr *)&addr, &addrlen,
2981 result = WSARecv (socket->priv->fd,
2983 &bytes_received, &win_flags,
2987 int errsv = get_socket_errno ();
2989 if (errsv == WSAEINTR)
2992 win32_unset_event_mask (socket, FD_READ);
2994 if (socket->priv->blocking &&
2995 errsv == WSAEWOULDBLOCK)
2998 g_set_error (error, G_IO_ERROR,
2999 socket_io_error_from_errno (errsv),
3000 _("Error receiving message: %s"), socket_strerror (errsv));
3004 win32_unset_event_mask (socket, FD_READ);
3008 /* decode address */
3009 if (address != NULL)
3012 *address = g_socket_address_new_from_native (&addr, addrlen);
3017 /* capture the flags */
3021 return bytes_received;
3026 #define __G_SOCKET_C__
3027 #include "gioaliasdef.c"