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;
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 addrlen = sizeof address;
377 if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
378 socket->priv->connected = TRUE;
381 optlen = sizeof bool_val;
382 if (getsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
383 (void *)&bool_val, &optlen) == 0)
385 g_assert (optlen == sizeof bool_val);
386 socket->priv->keepalive = !!bool_val;
390 /* Can't read, maybe not supported, assume FALSE */
391 socket->priv->keepalive = FALSE;
397 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
398 socket_io_error_from_errno (errsv),
399 _("creating GSocket from fd: %s"),
400 socket_strerror (errsv));
404 get_protocol_name (int protocol_id)
406 struct protoent *protoent;
407 #ifdef HAVE_GETPROTOBYNUMBER_R
409 struct protoent my_protoent;
412 if (protocol_id == 0)
415 if (protocol_id == -1)
416 return g_strdup ("unknown");
418 #ifdef HAVE_GETPROTOBYNUMBER_R
420 getprotobynumber_r (protocol_id,
421 &my_protoent, buffer, sizeof (buffer),
424 protoent = getprotobynumber (protocol_id);
427 if (protoent == NULL)
428 return g_strdup_printf ("proto-%d", protocol_id);
430 return g_strdup (protoent->p_name);
434 * g_socket_protocol_id_lookup_by_name:
435 * @protocol_name: The name of a protocol, or %NULL
437 * Tries to look up the protocol id for a given
438 * protocol name. If the protocol name is not known
439 * on this system it returns -1.
441 * If @protocol_name is %NULL (default protocol) then
444 * Returns: a protocol id, or -1 if unknown
449 g_socket_protocol_id_lookup_by_name (const char *protocol_name)
451 struct protoent *protoent;
453 #ifdef HAVE_GETPROTOBYNAME_R
455 struct protoent my_protoent;
461 #ifdef HAVE_GETPROTOBYNAME_R
463 getprotobyname_r (protocol_name,
464 &my_protoent, buffer, sizeof (buffer),
467 protoent = getprotobyname (protocol_name);
470 if (protoent == NULL)
472 if (g_str_has_prefix (protocol_name, "proto-"))
473 return atoi (protocol_name + strlen ("proto-"));
476 protocol = protoent->p_proto;
482 g_socket_create_socket (GSocketFamily family,
492 case G_SOCKET_TYPE_STREAM:
493 native_type = SOCK_STREAM;
496 case G_SOCKET_TYPE_DATAGRAM:
497 native_type = SOCK_DGRAM;
500 case G_SOCKET_TYPE_SEQPACKET:
501 native_type = SOCK_SEQPACKET;
505 g_assert_not_reached ();
508 if (protocol_id == -1)
510 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
511 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
516 native_type |= SOCK_CLOEXEC;
518 fd = socket (family, native_type, protocol_id);
522 int errsv = get_socket_errno ();
524 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
525 _("Unable to create socket: %s"), socket_strerror (errsv));
532 /* We always want to set close-on-exec to protect users. If you
533 need to so some weird inheritance to exec you can re-enable this
534 using lower level hacks with g_socket_get_fd(). */
535 flags = fcntl (fd, F_GETFD, 0);
537 (flags & FD_CLOEXEC) == 0)
540 fcntl (fd, F_SETFD, flags);
549 g_socket_constructed (GObject *object)
551 GSocket *socket = G_SOCKET (object);
553 if (socket->priv->fd >= 0)
554 /* create socket->priv info from the fd */
555 g_socket_details_from_fd (socket);
558 /* create the fd from socket->priv info */
559 socket->priv->fd = g_socket_create_socket (socket->priv->family,
561 socket->priv->protocol,
562 &socket->priv->construct_error);
564 /* Always use native nonblocking sockets, as
565 windows sets sockets to nonblocking automatically
566 in certain operations. This way we make things work
567 the same on all platforms */
568 if (socket->priv->fd != -1)
569 set_fd_nonblocking (socket->priv->fd);
573 g_socket_get_property (GObject *object,
578 GSocket *socket = G_SOCKET (object);
579 GSocketAddress *address;
584 g_value_set_enum (value, socket->priv->family);
588 g_value_set_enum (value, socket->priv->type);
592 g_value_set_int (value, socket->priv->protocol);
596 g_value_set_int (value, socket->priv->fd);
600 g_value_set_boolean (value, socket->priv->blocking);
603 case PROP_LISTEN_BACKLOG:
604 g_value_set_int (value, socket->priv->listen_backlog);
608 g_value_set_boolean (value, socket->priv->keepalive);
611 case PROP_LOCAL_ADDRESS:
612 address = g_socket_get_local_address (socket, NULL);
613 g_value_take_object (value, address);
616 case PROP_REMOTE_ADDRESS:
617 address = g_socket_get_remote_address (socket, NULL);
618 g_value_take_object (value, address);
622 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
627 g_socket_set_property (GObject *object,
632 GSocket *socket = G_SOCKET (object);
637 socket->priv->family = g_value_get_enum (value);
641 socket->priv->type = g_value_get_enum (value);
645 socket->priv->protocol = g_value_get_int (value);
649 socket->priv->fd = g_value_get_int (value);
653 g_socket_set_blocking (socket, g_value_get_boolean (value));
656 case PROP_LISTEN_BACKLOG:
657 g_socket_set_listen_backlog (socket, g_value_get_int (value));
661 g_socket_set_keepalive (socket, g_value_get_boolean (value));
665 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
670 g_socket_finalize (GObject *object)
672 GSocket *socket = G_SOCKET (object);
674 g_clear_error (&socket->priv->construct_error);
676 if (socket->priv->fd != -1 &&
677 !socket->priv->closed)
678 g_socket_close (socket, NULL);
681 g_assert (socket->priv->requested_conditions == NULL);
684 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
685 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
689 g_socket_class_init (GSocketClass *klass)
691 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
694 /* Make sure winsock has been initialized */
695 type = g_inet_address_get_type ();
697 g_type_class_add_private (klass, sizeof (GSocketPrivate));
699 gobject_class->finalize = g_socket_finalize;
700 gobject_class->constructed = g_socket_constructed;
701 gobject_class->set_property = g_socket_set_property;
702 gobject_class->get_property = g_socket_get_property;
704 g_object_class_install_property (gobject_class, PROP_FAMILY,
705 g_param_spec_enum ("family",
707 P_("The sockets address family"),
708 G_TYPE_SOCKET_FAMILY,
709 G_SOCKET_FAMILY_INVALID,
710 G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
712 g_object_class_install_property (gobject_class, PROP_TYPE,
713 g_param_spec_enum ("type",
715 P_("The sockets type"),
717 G_SOCKET_TYPE_STREAM,
718 G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
720 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
721 g_param_spec_int ("protocol",
722 P_("Socket protocol"),
723 P_("The id of the protocol to use, or -1 for unknown"),
727 G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
729 g_object_class_install_property (gobject_class, PROP_FD,
730 g_param_spec_int ("fd",
731 P_("File descriptor"),
732 P_("The sockets file descriptor"),
736 G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
738 g_object_class_install_property (gobject_class, PROP_BLOCKING,
739 g_param_spec_boolean ("blocking",
741 P_("Whether or not I/O on this socket is blocking"),
743 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
745 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
746 g_param_spec_int ("listen-backlog",
747 P_("Listen backlog"),
748 P_("outstanding connections in the listen queue"),
752 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
754 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
755 g_param_spec_boolean ("keepalive",
756 P_("Keep connection alive"),
757 P_("Keep connection alive by sending periodic pings"),
759 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
761 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
762 g_param_spec_object ("local-address",
764 P_("The local address the socket is bound to"),
765 G_TYPE_SOCKET_ADDRESS,
766 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
768 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
769 g_param_spec_object ("remote-address",
770 P_("Remote address"),
771 P_("The remote address the socket is connected to"),
772 G_TYPE_SOCKET_ADDRESS,
773 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
777 g_socket_initable_iface_init (GInitableIface *iface)
779 iface->init = g_socket_initable_init;
783 g_socket_init (GSocket *socket)
785 socket->priv = G_TYPE_INSTANCE_GET_PRIVATE (socket, G_TYPE_SOCKET, GSocketPrivate);
787 socket->priv->fd = -1;
788 socket->priv->blocking = TRUE;
789 socket->priv->listen_backlog = 10;
790 socket->priv->construct_error = NULL;
792 socket->priv->event = WSA_INVALID_EVENT;
797 g_socket_initable_init (GInitable *initable,
798 GCancellable *cancellable,
803 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
805 socket = G_SOCKET (initable);
807 if (cancellable != NULL)
809 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
810 _("Cancellable initialization not supported"));
814 socket->priv->inited = TRUE;
816 if (socket->priv->construct_error)
819 *error = g_error_copy (socket->priv->construct_error);
829 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
830 * @type: the socket type to use.
831 * @protocol_id: the id of the protocol to use, or 0 for default.
832 * @error: #GError for error reporting, or %NULL to ignore.
834 * Creates a new #GSocket with the defined family, type and protocol.
835 * If @protocol_id is 0 the default protocol type for the family and
838 * The @protocol_id is a family and type specific int that specifies what
839 * kind of protocol to use. Many families only support one protocol,
840 * and use 0 for this, others support several and using 0 means
841 * to use the default protocol for the family and type. To use
842 * other protocol, you can use g_socket_protocol_id_lookup_by_name()
843 * to look up the protocol by name, or if you known the system specific
844 * protocol id you can use that.
846 * Returns: a #GSocket or %NULL on error.
847 * Free the returned object with g_object_unref().
852 g_socket_new (GSocketFamily family,
857 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
861 "protocol", protocol_id,
866 * g_socket_new_from_fd:
867 * @fd: a native socket file descriptor.
868 * @error: #GError for error reporting, or %NULL to ignore.
870 * Creates a new #GSocket from a native file descriptor
871 * or winsock SOCKET handle.
873 * This reads all the settings from the file descriptor so that
874 * all properties should work. Note that the file descriptor
875 * will be set to non-blocking mode, independent on the blocking
876 * mode of the #GSocket.
878 * Returns: a #GSocket or %NULL on error.
879 * Free the returned object with g_object_unref().
884 g_socket_new_from_fd (gint fd,
887 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
894 * g_socket_set_blocking:
895 * @socket: a #GSocket.
896 * @blocking: Whether to use blocking I/O or not.
898 * Sets the blocking mode of the socket. In blocking mode
899 * all operations block until they succeed or there is an error. In
900 * non-blocking mode all functions return results immediately or
901 * with a %G_IO_ERROR_WOULD_BLOCK error.
903 * All sockets are created in blocking mode. However, note that the
904 * platform level socket is always non-blocking, and blocking mode
905 * is a GSocket level feature.
910 g_socket_set_blocking (GSocket *socket,
913 g_return_if_fail (G_IS_SOCKET (socket));
915 blocking = !!blocking;
917 if (socket->priv->blocking == blocking)
920 socket->priv->blocking = blocking;
921 g_object_notify (G_OBJECT (socket), "blocking");
925 * g_socket_get_blocking:
926 * @socket: a #GSocket.
928 * Gets the blocking mode of the socket. For details on blocking I/O,
929 * see g_socket_set_blocking().
931 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
936 g_socket_get_blocking (GSocket *socket)
938 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
940 return socket->priv->blocking;
944 * g_socket_set_keepalive:
945 * @socket: a #GSocket.
946 * @keepalive: Whether to use try to keep the connection alive or not.
948 * Setting @keepalive to %TRUE enables the sending of periodic ping requests
949 * on idle connections in order to keep the connection alive. This is only
950 * useful for connection oriented sockets. The exact period used between
951 * each ping is system and protocol dependent.
953 * Sending keepalive requests like this has a few disadvantages. For instance,
954 * it uses more network bandwidth, and it makes your application more sensitive
955 * to temporary outages in the network (i.e. if a cable is pulled your otherwise
956 * idle connection could be terminated, whereas otherwise it would survive unless
957 * actually used before the cable was reinserted). However, it is sometimes
958 * useful to ensure that connections are eventually terminated if e.g. the
959 * remote side is disconnected, so as to avoid leaking resources forever.
964 g_socket_set_keepalive (GSocket *socket,
969 g_return_if_fail (G_IS_SOCKET (socket));
971 keepalive = !!keepalive;
972 if (socket->priv->keepalive == keepalive)
975 value = (gint) keepalive;
976 if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_KEEPALIVE,
977 (gpointer) &value, sizeof (value)) < 0)
979 int errsv = get_socket_errno ();
980 g_warning ("error setting keepalive: %s", socket_strerror (errsv));
984 socket->priv->keepalive = keepalive;
985 g_object_notify (G_OBJECT (socket), "keepalive");
989 * g_socket_get_keepalive:
990 * @socket: a #GSocket.
992 * Gets the keepalive mode of the socket. For details on this,
993 * see g_socket_set_keepalive().
995 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1000 g_socket_get_keepalive (GSocket *socket)
1002 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1004 return socket->priv->keepalive;
1008 * g_socket_get_listen_backlog:
1009 * @socket: a #GSocket.
1011 * Gets the listen backlog setting of the socket. For details on this,
1012 * see g_socket_set_listen_backlog().
1014 * Returns: the maximum number of pending connections.
1019 g_socket_get_listen_backlog (GSocket *socket)
1021 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1023 return socket->priv->listen_backlog;
1027 * g_socket_set_listen_backlog:
1028 * @socket: a #GSocket.
1029 * @backlog: the maximum number of pending connections.
1031 * Sets the maximum number of outstanding connections allowed
1032 * when listening on this socket. If more clients than this are
1033 * connecting to the socket and the application is not handling them
1034 * on time then the new connections will be refused.
1036 * Note that this must be called before g_socket_listen() and has no
1037 * effect if called after that.
1042 g_socket_set_listen_backlog (GSocket *socket,
1045 g_return_if_fail (G_IS_SOCKET (socket));
1046 g_return_if_fail (!socket->priv->listening);
1048 if (backlog != socket->priv->listen_backlog)
1050 socket->priv->listen_backlog = backlog;
1051 g_object_notify (G_OBJECT (socket), "listen-backlog");
1056 * g_socket_get_family:
1057 * @socket: a #GSocket.
1059 * Gets the socket family of the socket.
1061 * Returns: a #GSocketFamily
1066 g_socket_get_family (GSocket *socket)
1068 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1070 return socket->priv->family;
1074 * g_socket_get_socket_type:
1075 * @socket: a #GSocket.
1077 * Gets the socket type of the socket.
1079 * Returns: a #GSocketType
1084 g_socket_get_socket_type (GSocket *socket)
1086 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1088 return socket->priv->type;
1092 * g_socket_get_protocol_id:
1093 * @socket: a #GSocket.
1095 * Gets the socket protocol id the socket was created with.
1096 * In case the protocol is unknown, -1 is returned.
1098 * Returns: a protocol id, or -1 if unknown
1103 g_socket_get_protocol_id (GSocket *socket)
1105 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1107 return socket->priv->protocol;
1111 * g_socket_get_protocol_name:
1112 * @socket: a #GSocket.
1114 * Gets the socket protocol type name the socket was created with.
1115 * This can be %NULL if the socket was created with a NULL protocol.
1117 * Returns: a string or %NULL, free with g_free
1122 g_socket_get_protocol_name (GSocket *socket)
1124 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1126 return get_protocol_name (socket->priv->protocol);
1131 * @socket: a #GSocket.
1133 * Returns the underlying OS socket object. On unix this
1134 * is a socket file descriptor, and on windows this is
1135 * a Winsock2 SOCKET handle. This may be useful for
1136 * doing platform specific or otherwise unusual operations
1139 * Returns: the file descriptor of the socket.
1144 g_socket_get_fd (GSocket *socket)
1146 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1148 return socket->priv->fd;
1152 * g_socket_get_local_address:
1153 * @socket: a #GSocket.
1154 * @error: #GError for error reporting, or %NULL to ignore.
1156 * Try to get the local address of a bound socket. This is only
1157 * useful if the socket has been bound to a local address,
1158 * either explicitly or implicitly when connecting.
1160 * Returns: a #GSocketAddress or %NULL on error.
1161 * Free the returned object with g_object_unref().
1166 g_socket_get_local_address (GSocket *socket,
1169 struct sockaddr_storage buffer;
1170 guint32 len = sizeof (buffer);
1172 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1174 if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1176 int errsv = get_socket_errno ();
1177 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1178 _("could not get local address: %s"), socket_strerror (errsv));
1182 return g_socket_address_new_from_native (&buffer, len);
1186 * g_socket_get_remote_address:
1187 * @socket: a #GSocket.
1188 * @error: #GError for error reporting, or %NULL to ignore.
1190 * Try to get the remove address of a connected socket. This is only
1191 * useful for connection oriented sockets that have been connected.
1193 * Returns: a #GSocketAddress or %NULL on error.
1194 * Free the returned object with g_object_unref().
1199 g_socket_get_remote_address (GSocket *socket,
1202 struct sockaddr_storage buffer;
1203 guint32 len = sizeof (buffer);
1205 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1207 if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1209 int errsv = get_socket_errno ();
1210 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1211 _("could not get remote address: %s"), socket_strerror (errsv));
1215 return g_socket_address_new_from_native (&buffer, len);
1219 * g_socket_is_connected:
1220 * @socket: a #GSocket.
1222 * Check whether the socket is connected. This is only useful for
1223 * connection-oriented sockets.
1225 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1230 g_socket_is_connected (GSocket *socket)
1232 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1234 return socket->priv->connected;
1239 * @socket: a #GSocket.
1240 * @error: #GError for error reporting, or %NULL to ignore.
1242 * Marks the socket as a server socket, i.e. a socket that is used
1243 * to accept incoming requests using g_socket_accept().
1245 * Before calling this the socket must be bound to a local address using
1248 * To set the maximum amount of outstanding clients, use
1249 * g_socket_set_listen_backlog().
1251 * Returns: %TRUE on success, %FALSE on error.
1256 g_socket_listen (GSocket *socket,
1259 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1261 if (!check_socket (socket, error))
1264 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1266 int errsv = get_socket_errno ();
1268 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1269 _("could not listen: %s"), socket_strerror (errsv));
1273 socket->priv->listening = TRUE;
1280 * @socket: a #GSocket.
1281 * @address: a #GSocketAddress specifying the local address.
1282 * @allow_reuse: whether to allow reusing this address
1283 * @error: #GError for error reporting, or %NULL to ignore.
1285 * When a socket is created it is attached to an address family, but it
1286 * doesn't have an address in this family. g_socket_bind() assigns the
1287 * address (sometimes called name) of the socket.
1289 * It is generally required to bind to a local address before you can
1290 * receive connections. (See g_socket_listen() and g_socket_accept() ).
1292 * If @allow_reuse is %TRUE this allows the bind call to succeed in some
1293 * situation where it would otherwise return a %G_IO_ERROR_ADDRESS_IN_USE
1294 * error. The main example is for a TCP server socket where there are
1295 * outstanding connections in the WAIT state, which are generally safe
1296 * to ignore. However, setting it to %TRUE doesn't mean the call will
1297 * succeed if there is a socket actively bound to the address.
1299 * In general, pass %TRUE if the socket will be used to accept connections,
1300 * otherwise pass %FALSE.
1302 * Returns: %TRUE on success, %FALSE on error.
1307 g_socket_bind (GSocket *socket,
1308 GSocketAddress *address,
1309 gboolean reuse_address,
1312 struct sockaddr_storage addr;
1315 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1317 if (!check_socket (socket, error))
1320 /* SO_REUSEADDR on windows means something else and is not what we want.
1321 It always allows the unix variant of SO_REUSEADDR anyway */
1323 value = (int) !!reuse_address;
1324 /* Ignore errors here, the only likely error is "not supported", and
1325 this is a "best effort" thing mainly */
1326 setsockopt (socket->priv->fd, SOL_SOCKET, SO_REUSEADDR,
1327 (gpointer) &value, sizeof (value));
1330 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1333 if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1334 g_socket_address_get_native_size (address)) < 0)
1336 int errsv = get_socket_errno ();
1338 G_IO_ERROR, socket_io_error_from_errno (errsv),
1339 _("Error binding to address: %s"), socket_strerror (errsv));
1348 * @socket: a #GSocket.
1349 * @error: #GError for error reporting, or %NULL to ignore.
1351 * Accept incoming connections on a connection-based socket. This removes
1352 * the first outstanding connection request from the listening socket and
1353 * creates a #GSocket object for it.
1355 * The @socket must be bound to a local address with g_socket_bind() and
1356 * must be listening for incoming connections (g_socket_listen()).
1358 * If there are no outstanding connections then the operation will block
1359 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
1360 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
1362 * Returns: a new #GSocket, or %NULL on error.
1363 * Free the returned object with g_object_unref().
1368 g_socket_accept (GSocket *socket,
1371 GSocket *new_socket;
1374 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1376 if (!check_socket (socket, error))
1381 if (socket->priv->blocking &&
1382 !g_socket_condition_wait (socket,
1383 G_IO_IN, NULL, error))
1386 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
1388 int errsv = get_socket_errno ();
1390 win32_unset_event_mask (socket, FD_ACCEPT);
1395 if (socket->priv->blocking)
1397 #ifdef WSAEWOULDBLOCK
1398 if (errsv == WSAEWOULDBLOCK)
1401 if (errsv == EWOULDBLOCK ||
1407 g_set_error (error, G_IO_ERROR,
1408 socket_io_error_from_errno (errsv),
1409 _("Error accepting connection: %s"), socket_strerror (errsv));
1415 win32_unset_event_mask (socket, FD_ACCEPT);
1419 /* The socket inherits the accepting sockets event mask and even object,
1420 we need to remove that */
1421 WSAEventSelect (ret, NULL, 0);
1427 /* We always want to set close-on-exec to protect users. If you
1428 need to so some weird inheritance to exec you can re-enable this
1429 using lower level hacks with g_socket_get_fd(). */
1430 flags = fcntl (ret, F_GETFD, 0);
1432 (flags & FD_CLOEXEC) == 0)
1434 flags |= FD_CLOEXEC;
1435 fcntl (ret, F_SETFD, flags);
1440 new_socket = g_socket_new_from_fd (ret, error);
1441 if (new_socket == NULL)
1450 new_socket->priv->protocol = socket->priv->protocol;
1457 * @socket: a #GSocket.
1458 * @address: a #GSocketAddress specifying the remote address.
1459 * @error: #GError for error reporting, or %NULL to ignore.
1461 * Connect the socket to the specified remote address.
1463 * For connection oriented socket this generally means we attempt to make
1464 * a connection to the @address. For a connection-less socket it sets
1465 * the default address for g_socket_send() and discards all incoming datagrams
1466 * from other sources.
1468 * Generally connection oriented sockets can only connect once, but connection-less
1469 * sockets can connect multiple times to change the default address.
1471 * If the connect call needs to do network I/O it will block, unless
1472 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
1473 * and the user can be notified of the connection finishing by waiting
1474 * for the G_IO_OUT condition. The result of the connection can then be
1475 * checked with g_socket_check_pending_error().
1477 * Returns: %TRUE if connected, %FALSE on error.
1482 g_socket_connect (GSocket *socket,
1483 GSocketAddress *address,
1486 struct sockaddr_storage buffer;
1488 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1490 if (!check_socket (socket, error))
1493 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
1498 if (socket->priv->blocking &&
1499 !g_socket_condition_wait (socket,
1500 G_IO_IN, NULL, error))
1503 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
1504 g_socket_address_get_native_size (address)) < 0)
1506 int errsv = get_socket_errno ();
1512 if (errsv == EINPROGRESS)
1514 if (errsv == WSAEINPROGRESS)
1517 if (socket->priv->blocking)
1519 g_socket_condition_wait (socket, G_IO_OUT, NULL, NULL);
1520 if (g_socket_check_pending_error (socket, error))
1523 g_prefix_error (error, _("Error connecting: "));
1526 g_set_error (error, G_IO_ERROR, G_IO_ERROR_PENDING,
1527 _("Connection in progress"));
1530 g_set_error (error, G_IO_ERROR,
1531 socket_io_error_from_errno (errsv),
1532 _("Error connecting: %s"), socket_strerror (errsv));
1539 win32_unset_event_mask (socket, FD_CONNECT);
1541 socket->priv->connected = TRUE;
1547 * g_socket_check_pending_error:
1548 * @socket: a #GSocket
1549 * @error: #GError for error reporting, or %NULL to ignore.
1551 * Checks and resets the pending error for the socket. This is typically
1552 * used to check for errors when g_socket_connect() is used in non-blocking mode.
1554 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
1559 g_socket_check_pending_error (GSocket *socket,
1565 optlen = sizeof (value);
1566 if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
1568 int errsv = get_socket_errno ();
1570 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1571 _("Unable to get pending error: %s"), socket_strerror (errsv));
1577 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (value),
1578 "%s", socket_strerror (value));
1586 * @socket: a #GSocket
1587 * @buffer: a buffer to read data into (which should be at least count bytes long).
1588 * @size: the number of bytes that will be read from the stream
1589 * @error: #GError for error reporting, or %NULL to ignore.
1591 * Receive data (up to @size bytes) from a socket. This is mainly used by
1592 * connection oriented sockets, it is identical to g_socket_receive_from()
1593 * with @address set to %NULL.
1595 * If a message is too long to fit in @buffer, excess bytes may be discarded
1596 * depending on the type of socket the message is received from.
1598 * If the socket is in blocking mode the call will block until there is
1599 * some data to receive or there is an error. If there is no data available
1600 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1601 * will be returned. To be notified of available data, wait for the %G_IO_IN
1604 * On error -1 is returned and @error is set accordingly.
1606 * Returns: Number of bytes read, or -1 on error
1611 g_socket_receive (GSocket *socket,
1618 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1620 if (!check_socket (socket, error))
1625 if (socket->priv->blocking &&
1626 !g_socket_condition_wait (socket,
1627 G_IO_IN, NULL, error))
1630 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
1632 int errsv = get_socket_errno ();
1637 if (socket->priv->blocking)
1639 #ifdef WSAEWOULDBLOCK
1640 if (errsv == WSAEWOULDBLOCK)
1643 if (errsv == EWOULDBLOCK ||
1649 win32_unset_event_mask (socket, FD_READ);
1651 g_set_error (error, G_IO_ERROR,
1652 socket_io_error_from_errno (errsv),
1653 _("Error receiving data: %s"), socket_strerror (errsv));
1657 win32_unset_event_mask (socket, FD_READ);
1666 * g_socket_receive_from:
1667 * @socket: a #GSocket
1668 * @address: a pointer to a #GSocketAddress pointer, or %NULL
1669 * @buffer: a buffer to read data into (which should be at least count bytes long).
1670 * @size: the number of bytes that will be read from the stream
1671 * @error: #GError for error reporting, or %NULL to ignore.
1673 * Receive data (up to @size bytes) from a socket.
1675 * If @address is non-%NULL then @address will be set equal to the
1676 * source address of the received packet.
1677 * @address is owned by the caller.
1679 * If the socket is in blocking mode the call will block until there is
1680 * some data to receive or there is an error. If there is no data available
1681 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1682 * will be returned. To be notified of available data, wait for the %G_IO_IN
1685 * On error -1 is returned and @error is set accordingly.
1687 * Returns: Number of bytes read, or -1 on error
1692 g_socket_receive_from (GSocket *socket,
1693 GSocketAddress **address,
1703 return g_socket_receive_message (socket,
1712 * @socket: a #GSocket
1713 * @buffer: the buffer containing the data to send.
1714 * @size: the number of bytes to send
1715 * @error: #GError for error reporting, or %NULL to ignore.
1717 * Tries to send @size bytes from @buffer on the socket. This is mainly used by
1718 * connection oriented sockets, it is identical to g_socket_send_to()
1719 * with @address set to %NULL.
1721 * If the socket is in blocking mode the call will block until there is
1722 * space for the data in the socket queue. If there is no space available
1723 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1724 * will be returned. To be notified of available space, wait for the %G_IO_OUT
1727 * Note that on Windows you can't rely on a %G_IO_OUT condition
1728 * not producing a %G_IO_ERROR_WOULD_BLOCK error, as this is how Winsock
1729 * write notification works. However, robust apps should always be able to
1730 * handle this since it can easily appear in other cases too.
1732 * On error -1 is returned and @error is set accordingly.
1734 * Returns: Number of bytes read, or -1 on error
1739 g_socket_send (GSocket *socket,
1740 const gchar *buffer,
1746 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1748 if (!check_socket (socket, error))
1753 if (socket->priv->blocking &&
1754 !g_socket_condition_wait (socket,
1755 G_IO_OUT, NULL, error))
1758 if ((ret = send (socket->priv->fd, buffer, size, 0)) < 0)
1760 int errsv = get_socket_errno ();
1765 #ifdef WSAEWOULDBLOCK
1766 if (errsv == WSAEWOULDBLOCK)
1767 win32_unset_event_mask (socket, FD_WRITE);
1770 if (socket->priv->blocking)
1772 #ifdef WSAEWOULDBLOCK
1773 if (errsv == WSAEWOULDBLOCK)
1776 if (errsv == EWOULDBLOCK ||
1782 g_set_error (error, G_IO_ERROR,
1783 socket_io_error_from_errno (errsv),
1784 _("Error sending data: %s"), socket_strerror (errsv));
1795 * @socket: a #GSocket
1796 * @address: a #GSocketAddress, or %NULL
1797 * @buffer: the buffer containing the data to send.
1798 * @size: the number of bytes to send
1799 * @error: #GError for error reporting, or %NULL to ignore.
1801 * Tries to send @size bytes from @buffer to @address. If @address is
1802 * %NULL then the message is sent to the default receiver (set by
1803 * g_socket_connect()).
1805 * If the socket is in blocking mode the call will block until there is
1806 * space for the data in the socket queue. If there is no space available
1807 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1808 * will be returned. To be notified of available space, wait for the %G_IO_OUT
1811 * Note that on Windows you can't rely on a %G_IO_OUT condition
1812 * not producing a %G_IO_ERROR_WOULD_BLOCK error, as this is how Winsock
1813 * write notification works. However, robust apps should always be able to
1814 * handle this since it can easily appear in other cases too.
1816 * On error -1 is returned and @error is set accordingly.
1818 * Returns: Number of bytes read, or -1 on error
1823 g_socket_send_to (GSocket *socket,
1824 GSocketAddress *address,
1825 const gchar *buffer,
1834 return g_socket_send_message (socket,
1843 * @socket: a #GSocket
1844 * @error: #GError for error reporting, or %NULL to ignore.
1846 * Closes the socket, shutting down any active connection.
1848 * Closing a socket does not wait for all outstanding I/O operations to finish,
1849 * so the caller should not rely on them to be guaranteed to complete even
1850 * if the close returns with no error.
1852 * Once the socket is closed, all other operations will return %G_IO_ERROR_CLOSED.
1853 * Closing a stream multiple times will not return an error.
1855 * Sockets will be automatically closed when the last reference
1856 * is dropped, but you might want to call this function to make sure
1857 * resources are released as early as possible.
1859 * Returns: %TRUE on success, %FALSE on error
1864 g_socket_close (GSocket *socket,
1869 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
1871 if (socket->priv->closed)
1872 return TRUE; /* Multiple close not an error */
1874 if (!check_socket (socket, NULL))
1880 res = closesocket (socket->priv->fd);
1882 res = close (socket->priv->fd);
1886 int errsv = get_socket_errno ();
1891 g_set_error (error, G_IO_ERROR,
1892 socket_io_error_from_errno (errsv),
1893 _("Error closing socket: %s"),
1894 socket_strerror (errsv));
1901 if (socket->priv->event != WSA_INVALID_EVENT)
1903 WSACloseEvent (socket->priv->event);
1904 socket->priv->event = WSA_INVALID_EVENT;
1908 socket->priv->connected = FALSE;
1909 socket->priv->closed = TRUE;
1915 * g_socket_is_closed:
1916 * @socket: a #GSocket
1918 * Checks whether a socket is closed.
1920 * Returns: %TRUE if socket is closed, %FALSE otherwise
1925 g_socket_is_closed (GSocket *socket)
1927 return socket->priv->closed;
1931 /* Broken source, used on errors */
1933 broken_prepare (GSource *source,
1940 broken_check (GSource *source)
1946 broken_dispatch (GSource *source,
1947 GSourceFunc callback,
1953 static GSourceFuncs broken_funcs =
1962 network_events_for_condition (GIOCondition condition)
1966 if (condition & G_IO_IN)
1967 event_mask |= (FD_READ | FD_ACCEPT);
1968 if (condition & G_IO_OUT)
1969 event_mask |= (FD_WRITE | FD_CONNECT);
1970 event_mask |= FD_CLOSE;
1976 ensure_event (GSocket *socket)
1978 if (socket->priv->event == WSA_INVALID_EVENT)
1979 socket->priv->event = WSACreateEvent();
1983 update_select_events (GSocket *socket)
1990 ensure_event (socket);
1993 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
1996 event_mask |= network_events_for_condition (*ptr);
1999 if (event_mask != socket->priv->selected_events)
2001 /* If no events selected, disable event so we can unset
2004 if (event_mask == 0)
2007 event = socket->priv->event;
2009 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
2010 socket->priv->selected_events = event_mask;
2015 add_condition_watch (GSocket *socket,
2016 GIOCondition *condition)
2018 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
2020 socket->priv->requested_conditions =
2021 g_list_prepend (socket->priv->requested_conditions, condition);
2023 update_select_events (socket);
2027 remove_condition_watch (GSocket *socket,
2028 GIOCondition *condition)
2030 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
2032 socket->priv->requested_conditions =
2033 g_list_remove (socket->priv->requested_conditions, condition);
2035 update_select_events (socket);
2039 update_condition (GSocket *socket)
2041 WSANETWORKEVENTS events;
2042 GIOCondition condition;
2044 if (WSAEnumNetworkEvents (socket->priv->fd,
2045 socket->priv->event,
2048 socket->priv->current_events |= events.lNetworkEvents;
2049 if (events.lNetworkEvents & FD_WRITE &&
2050 events.iErrorCode[FD_WRITE_BIT] != 0)
2051 socket->priv->current_errors |= FD_WRITE;
2052 if (events.lNetworkEvents & FD_CONNECT &&
2053 events.iErrorCode[FD_CONNECT_BIT] != 0)
2054 socket->priv->current_errors |= FD_CONNECT;
2058 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
2059 condition |= G_IO_IN;
2061 if (socket->priv->current_events & FD_CLOSE ||
2062 socket->priv->closed)
2063 condition |= G_IO_HUP;
2065 /* Never report both G_IO_OUT and HUP, these are
2066 mutually exclusive (can't write to a closed socket) */
2067 if ((condition & G_IO_HUP) == 0 &&
2068 socket->priv->current_events & FD_WRITE)
2070 if (socket->priv->current_errors & FD_WRITE)
2071 condition |= G_IO_ERR;
2073 condition |= G_IO_OUT;
2077 if (socket->priv->current_events & FD_CONNECT)
2079 if (socket->priv->current_errors & FD_CONNECT)
2080 condition |= (G_IO_HUP | G_IO_ERR);
2082 condition |= G_IO_OUT;
2093 GIOCondition condition;
2094 GCancellable *cancellable;
2095 GPollFD cancel_pollfd;
2096 GIOCondition result_condition;
2100 winsock_prepare (GSource *source,
2103 GWinsockSource *winsock_source = (GWinsockSource *)source;
2104 GIOCondition current_condition;
2106 current_condition = update_condition (winsock_source->socket);
2108 if (g_cancellable_is_cancelled (winsock_source->cancellable))
2110 winsock_source->result_condition = current_condition;
2114 if ((winsock_source->condition & current_condition) != 0)
2116 winsock_source->result_condition = current_condition;
2124 winsock_check (GSource *source)
2126 GWinsockSource *winsock_source = (GWinsockSource *)source;
2127 GIOCondition current_condition;
2129 current_condition = update_condition (winsock_source->socket);
2131 if (g_cancellable_is_cancelled (winsock_source->cancellable))
2133 winsock_source->result_condition = current_condition;
2137 if ((winsock_source->condition & current_condition) != 0)
2139 winsock_source->result_condition = current_condition;
2147 winsock_dispatch (GSource *source,
2148 GSourceFunc callback,
2151 GSocketSourceFunc func = (GSocketSourceFunc)callback;
2152 GWinsockSource *winsock_source = (GWinsockSource *)source;
2154 return (*func) (winsock_source->socket,
2155 winsock_source->result_condition & winsock_source->condition,
2160 winsock_finalize (GSource *source)
2162 GWinsockSource *winsock_source = (GWinsockSource *)source;
2165 socket = winsock_source->socket;
2167 remove_condition_watch (socket, &winsock_source->condition);
2168 g_object_unref (socket);
2170 if (winsock_source->cancellable)
2171 g_object_unref (winsock_source->cancellable);
2174 static GSourceFuncs winsock_funcs =
2183 winsock_source_new (GSocket *socket,
2184 GIOCondition condition,
2185 GCancellable *cancellable)
2188 GWinsockSource *winsock_source;
2190 ensure_event (socket);
2192 if (socket->priv->event == WSA_INVALID_EVENT)
2194 g_warning ("Failed to create WSAEvent");
2195 return g_source_new (&broken_funcs, sizeof (GSource));
2198 condition |= G_IO_HUP | G_IO_ERR;
2200 source = g_source_new (&winsock_funcs, sizeof (GWinsockSource));
2201 winsock_source = (GWinsockSource *)source;
2203 winsock_source->socket = g_object_ref (socket);
2204 winsock_source->condition = condition;
2205 add_condition_watch (socket, &winsock_source->condition);
2209 winsock_source->cancellable = g_object_ref (cancellable);
2210 g_cancellable_make_pollfd (cancellable,
2211 &winsock_source->cancel_pollfd);
2212 g_source_add_poll (source, &winsock_source->cancel_pollfd);
2215 winsock_source->pollfd.fd = (gintptr) socket->priv->event;
2216 winsock_source->pollfd.events = condition;
2217 g_source_add_poll (source, &winsock_source->pollfd);
2224 * g_socket_create_source:
2225 * @socket: a #GSocket
2226 * @condition: a #GIOCondition mask to monitor
2227 * @cancellable: a %GCancellable or %NULL
2229 * Creates a %GSource that can be attached to a %GMainContext to monitor
2230 * for the availibility of the specified @condition on the socket.
2232 * The callback on the source is of the #GSocketSourceFunc type.
2234 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2235 * these conditions will always be reported output if they are true.
2237 * @cancellable if not %NULL can be used to cancel the source, which will
2238 * cause the source to trigger, reporting the current condition. You can
2239 * check for this in the callback using g_cancellable_is_cancelled().
2241 * Returns: a newly allocated %GSource, free with g_source_unref().
2246 g_socket_create_source (GSocket *socket,
2247 GIOCondition condition,
2248 GCancellable *cancellable)
2251 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
2254 source = winsock_source_new (socket, condition, cancellable);
2256 source =_g_fd_source_new_with_object (G_OBJECT (socket), socket->priv->fd,
2257 condition, cancellable);
2263 * g_socket_condition_check:
2264 * @socket: a #GSocket
2265 * @condition: a #GIOCondition mask to check
2267 * Checks on the readiness of @socket to perform operations. The
2268 * operations specified in @condition are checked for and masked
2269 * against the currently-satisfied conditions on @socket. The result
2272 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2273 * these conditions will always be set in the output if they are true.
2275 * This call never blocks.
2277 * Returns: the @GIOCondition mask of the current state
2282 g_socket_condition_check (GSocket *socket,
2283 GIOCondition condition)
2285 if (!check_socket (socket, NULL))
2290 GIOCondition current_condition;
2292 condition |= G_IO_ERR | G_IO_HUP;
2294 add_condition_watch (socket, &condition);
2295 current_condition = update_condition (socket);
2296 remove_condition_watch (socket, &condition);
2297 return condition & current_condition;
2303 poll_fd.fd = socket->priv->fd;
2304 poll_fd.events = condition;
2307 result = g_poll (&poll_fd, 1, 0);
2308 while (result == -1 && get_socket_errno () == EINTR);
2310 return poll_fd.revents;
2316 * g_socket_condition_wait:
2317 * @socket: a #GSocket
2318 * @condition: a #GIOCondition mask to wait for
2319 * @cancellable: a #GCancellable, or %NULL
2320 * @error: a #GError pointer, or %NULL
2322 * Waits for @condition to become true on @socket. When the condition
2323 * becomes true, %TRUE is returned.
2325 * If @cancellable is cancelled before the condition becomes true then
2326 * %FALSE is returned and @error, if non-%NULL, is set to %G_IO_ERROR_CANCELLED.
2328 * Returns: %TRUE if the condition was met, %FALSE otherwise
2333 g_socket_condition_wait (GSocket *socket,
2334 GIOCondition condition,
2335 GCancellable *cancellable,
2338 if (!check_socket (socket, error))
2341 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2346 GIOCondition current_condition;
2352 /* Always check these */
2353 condition |= G_IO_ERR | G_IO_HUP;
2355 add_condition_watch (socket, &condition);
2358 events[num_events++] = socket->priv->event;
2362 g_cancellable_make_pollfd (cancellable, &cancel_fd);
2363 events[num_events++] = (WSAEVENT)cancel_fd.fd;
2366 current_condition = update_condition (socket);
2367 while ((condition & current_condition) == 0)
2369 res = WSAWaitForMultipleEvents(num_events, events,
2370 FALSE, WSA_INFINITE, FALSE);
2371 if (res == WSA_WAIT_FAILED)
2373 int errsv = get_socket_errno ();
2375 g_set_error (error, G_IO_ERROR,
2376 socket_io_error_from_errno (errsv),
2377 _("Waiting for socket condition: %s"),
2378 socket_strerror (errsv));
2382 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2385 current_condition = update_condition (socket);
2387 remove_condition_watch (socket, &condition);
2389 return (condition & current_condition) != 0;
2397 poll_fd[0].fd = socket->priv->fd;
2398 poll_fd[0].events = condition;
2403 g_cancellable_make_pollfd (cancellable, &poll_fd[1]);
2408 result = g_poll (poll_fd, num, -1);
2409 while (result == -1 && get_socket_errno () == EINTR);
2411 return cancellable == NULL ||
2412 !g_cancellable_set_error_if_cancelled (cancellable, error);
2418 * g_socket_send_message:
2419 * @socket: a #GSocket
2420 * @address: a #GSocketAddress, or %NULL
2421 * @vectors: an array of #GOutputVector structs
2422 * @num_vectors: the number of elements in @vectors, or -1
2423 * @messages: a pointer to an array of #GSocketControlMessages, or
2425 * @num_messages: number of elements in @messages, or -1.
2426 * @flags: an int containing #GSocketMsgFlags flags
2427 * @error: #GError for error reporting, or %NULL to ignore.
2429 * Send data to @address on @socket. This is the most complicated and
2430 * fully-featured version of this call. For easier use, see
2431 * g_socket_send() and g_socket_send_to().
2433 * If @address is %NULL then the message is sent to the default receiver
2434 * (set by g_socket_connect()).
2436 * @vector must point to an array of #GOutputVector structs and
2437 * @num_vectors must be the length of this array. These structs
2438 * describe the buffers that the sent data will be gathered from.
2439 * If @num_vector is -1, then @vector is assumed to be terminated
2440 * by a #GOutputVector with a %NULL buffer pointer.
2443 * @messages, if non-%NULL, is taken to point to an array of @num_messages
2444 * #GSocketControlMessage instances. These correspond to the control
2445 * messages to be sent on the socket.
2446 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
2449 * @flags modify how the message sent. The commonly available arguments
2450 * for this is available in the #GSocketMsgFlags enum, but the
2451 * values there are the same as the system values, and the flags
2452 * are passed in as-is, so you can pass in system specific flags too.
2454 * If the socket is in blocking mode the call will block until there is
2455 * space for the data in the socket queue. If there is no space available
2456 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2457 * will be returned. To be notified of available space, wait for the %G_IO_OUT
2460 * Note that on Windows you can't rely on a %G_IO_OUT condition
2461 * not producing a %G_IO_ERROR_WOULD_BLOCK error, as this is how Winsock
2462 * write notification works. However, robust apps should always be able to
2463 * handle this since it can easily appear in other cases too.
2465 * On error -1 is returned and @error is set accordingly.
2467 * Returns: Number of bytes read, or -1 on error
2472 g_socket_send_message (GSocket *socket,
2473 GSocketAddress *address,
2474 GOutputVector *vectors,
2476 GSocketControlMessage **messages,
2481 GOutputVector one_vector;
2484 if (!check_socket (socket, error))
2487 if (num_vectors == -1)
2489 for (num_vectors = 0;
2490 vectors[num_vectors].buffer != NULL;
2495 if (num_messages == -1)
2497 for (num_messages = 0;
2498 messages != NULL && messages[num_messages] != NULL;
2503 if (num_vectors == 0)
2507 one_vector.buffer = &zero;
2508 one_vector.size = 1;
2510 vectors = &one_vector;
2521 msg.msg_namelen = g_socket_address_get_native_size (address);
2522 msg.msg_name = g_alloca (msg.msg_namelen);
2523 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
2529 /* this entire expression will be evaluated at compile time */
2530 if (sizeof *msg.msg_iov == sizeof *vectors &&
2531 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2532 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2533 G_STRUCT_OFFSET (GOutputVector, buffer) &&
2534 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2535 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2536 G_STRUCT_OFFSET (GOutputVector, size))
2537 /* ABI is compatible */
2539 msg.msg_iov = (struct iovec *) vectors;
2540 msg.msg_iovlen = num_vectors;
2543 /* ABI is incompatible */
2547 msg.msg_iov = g_newa (struct iovec, num_vectors);
2548 for (i = 0; i < num_vectors; i++)
2550 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
2551 msg.msg_iov[i].iov_len = vectors[i].size;
2553 msg.msg_iovlen = num_vectors;
2559 struct cmsghdr *cmsg;
2562 msg.msg_controllen = 0;
2563 for (i = 0; i < num_messages; i++)
2564 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
2566 msg.msg_control = g_alloca (msg.msg_controllen);
2568 cmsg = CMSG_FIRSTHDR (&msg);
2569 for (i = 0; i < num_messages; i++)
2571 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
2572 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
2573 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
2574 g_socket_control_message_serialize (messages[i],
2576 cmsg = CMSG_NXTHDR (&msg, cmsg);
2578 g_assert (cmsg == NULL);
2583 if (socket->priv->blocking &&
2584 !g_socket_condition_wait (socket,
2585 G_IO_OUT, NULL, error))
2588 result = sendmsg (socket->priv->fd, &msg, flags);
2591 int errsv = get_socket_errno ();
2596 if (socket->priv->blocking &&
2597 (errsv == EWOULDBLOCK ||
2601 g_set_error (error, G_IO_ERROR,
2602 socket_io_error_from_errno (errsv),
2603 _("Error sending message: %s"), socket_strerror (errsv));
2614 struct sockaddr_storage addr;
2621 /* Win32 doesn't support control messages.
2622 Actually this is possible for raw and datagram sockets
2623 via WSASendMessage on Vista or later, but that doesn't
2625 if (num_messages != 0)
2627 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2628 _("GSocketControlMessage not supported on windows"));
2633 bufs = g_newa (WSABUF, num_vectors);
2634 for (i = 0; i < num_vectors; i++)
2636 bufs[i].buf = (char *)vectors[i].buffer;
2637 bufs[i].len = (gulong)vectors[i].size;
2643 addrlen = g_socket_address_get_native_size (address);
2644 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
2650 if (socket->priv->blocking &&
2651 !g_socket_condition_wait (socket,
2652 G_IO_OUT, NULL, error))
2656 result = WSASendTo (socket->priv->fd,
2659 (const struct sockaddr *)&addr, addrlen,
2662 result = WSASend (socket->priv->fd,
2669 int errsv = get_socket_errno ();
2671 if (errsv == WSAEINTR)
2674 if (errsv == WSAEWOULDBLOCK)
2675 win32_unset_event_mask (socket, FD_WRITE);
2677 if (socket->priv->blocking &&
2678 errsv == WSAEWOULDBLOCK)
2681 g_set_error (error, G_IO_ERROR,
2682 socket_io_error_from_errno (errsv),
2683 _("Error sending message: %s"), socket_strerror (errsv));
2696 * g_socket_receive_message:
2697 * @socket: a #GSocket
2698 * @address: a pointer to a #GSocketAddress pointer, or %NULL
2699 * @vectors: an array of #GInputVector structs
2700 * @num_vectors: the number of elements in @vectors, or -1
2701 * @messages: a pointer which will be filled with an array of
2702 * #GSocketControlMessages, or %NULL
2703 * @num_messages: a pointer which will be filled with the number of
2704 * elements in @messages, or %NULL
2705 * @flags: a pointer to an int containing #GSocketMsgFlags flags
2706 * @error: a #GError pointer, or %NULL
2708 * Receive data from a socket. This is the most complicated and
2709 * fully-featured version of this call. For easier use, see
2710 * g_socket_receive() and g_socket_receive_from().
2712 * If @address is non-%NULL then @address will be set equal to the
2713 * source address of the received packet.
2714 * @address is owned by the caller.
2716 * @vector must point to an array of #GInputVector structs and
2717 * @num_vectors must be the length of this array. These structs
2718 * describe the buffers that received data will be scattered into.
2719 * If @num_vector is -1, then @vector is assumed to be terminated
2720 * by a #GInputVector with a %NULL buffer pointer.
2722 * As a special case, if the size of the array is zero (in which case,
2723 * @vectors may of course be %NULL), then a single byte is received
2724 * and discarded. This is to facilitate the common practice of
2725 * sending a single '\0' byte for the purposes of transferring
2728 * @messages, if non-%NULL, is taken to point to a pointer that will
2729 * be set to point to a newly-allocated array of
2730 * #GSocketControlMessage instances. These correspond to the control
2731 * messages received from the kernel, one #GSocketControlMessage per
2732 * message from the kernel. This array is %NULL-terminated and must be
2733 * freed by the caller using g_free().
2735 * @num_messages, if non-%NULL, will be set to the number of control
2736 * messages received.
2738 * If both @messages and @num_messages are non-%NULL, then
2739 * @num_messages gives the number of #GSocketControlMessage instances
2740 * in @messages (ie: not including the %NULL terminator).
2742 * @flags is an in/out parameter. The commonly available arguments
2743 * for this is available in the #GSocketMsgFlags enum, but the
2744 * values there are the same as the system values, and the flags
2745 * are passed in as-is, so you can pass in system specific flags too.
2747 * If the socket is in blocking mode the call will block until there is
2748 * some data to receive or there is an error. If there is no data available
2749 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2750 * will be returned. To be notified of available data, wait for the %G_IO_IN
2753 * On error -1 is returned and @error is set accordingly.
2755 * Returns: Number of bytes read, or -1 on error
2760 g_socket_receive_message (GSocket *socket,
2761 GSocketAddress **address,
2762 GInputVector *vectors,
2764 GSocketControlMessage ***messages,
2769 GInputVector one_vector;
2772 if (!check_socket (socket, error))
2775 if (num_vectors == -1)
2777 for (num_vectors = 0;
2778 vectors[num_vectors].buffer != NULL;
2783 if (num_vectors == 0)
2785 one_vector.buffer = &one_byte;
2786 one_vector.size = 1;
2788 vectors = &one_vector;
2795 struct sockaddr_storage one_sockaddr;
2800 msg.msg_name = &one_sockaddr;
2801 msg.msg_namelen = sizeof (struct sockaddr_storage);
2805 msg.msg_name = NULL;
2806 msg.msg_namelen = 0;
2810 /* this entire expression will be evaluated at compile time */
2811 if (sizeof *msg.msg_iov == sizeof *vectors &&
2812 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2813 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2814 G_STRUCT_OFFSET (GInputVector, buffer) &&
2815 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2816 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2817 G_STRUCT_OFFSET (GInputVector, size))
2818 /* ABI is compatible */
2820 msg.msg_iov = (struct iovec *) vectors;
2821 msg.msg_iovlen = num_vectors;
2824 /* ABI is incompatible */
2828 msg.msg_iov = g_newa (struct iovec, num_vectors);
2829 for (i = 0; i < num_vectors; i++)
2831 msg.msg_iov[i].iov_base = vectors[i].buffer;
2832 msg.msg_iov[i].iov_len = vectors[i].size;
2834 msg.msg_iovlen = num_vectors;
2838 msg.msg_control = g_alloca (2048);
2839 msg.msg_controllen = 2048;
2843 msg.msg_flags = *flags;
2850 if (socket->priv->blocking &&
2851 !g_socket_condition_wait (socket,
2852 G_IO_IN, NULL, error))
2855 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
2859 int errsv = get_socket_errno ();
2864 if (socket->priv->blocking &&
2865 (errsv == EWOULDBLOCK ||
2869 g_set_error (error, G_IO_ERROR,
2870 socket_io_error_from_errno (errsv),
2871 _("Error receiving message: %s"), socket_strerror (errsv));
2878 /* decode address */
2879 if (address != NULL)
2881 if (msg.msg_namelen > 0)
2882 *address = g_socket_address_new_from_native (msg.msg_name,
2888 /* decode control messages */
2890 GSocketControlMessage **my_messages = NULL;
2891 gint allocated = 0, index = 0;
2892 const gchar *scm_pointer;
2893 struct cmsghdr *cmsg;
2896 scm_pointer = (const gchar *) msg.msg_control;
2897 scm_size = msg.msg_controllen;
2899 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
2901 GSocketControlMessage *message;
2903 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
2905 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
2907 if (message == NULL)
2908 /* We've already spewed about the problem in the
2909 deserialization code, so just continue */
2912 if (index == allocated)
2914 /* estimated 99% case: exactly 1 control message */
2915 allocated = MIN (allocated * 2, 1);
2916 my_messages = g_new (GSocketControlMessage *, (allocated + 1));
2920 my_messages[index++] = message;
2924 *num_messages = index;
2928 my_messages[index++] = NULL;
2929 *messages = my_messages;
2935 /* free all those messages we just constructed.
2936 * we have to do it this way if the user ignores the
2937 * messages so that we will close any received fds.
2939 for (i = 0; i < index; i++)
2940 g_object_unref (my_messages[i]);
2941 g_free (my_messages);
2945 /* capture the flags */
2947 *flags = msg.msg_flags;
2953 struct sockaddr_storage addr;
2955 DWORD bytes_received;
2962 bufs = g_newa (WSABUF, num_vectors);
2963 for (i = 0; i < num_vectors; i++)
2965 bufs[i].buf = (char *)vectors[i].buffer;
2966 bufs[i].len = (gulong)vectors[i].size;
2978 if (socket->priv->blocking &&
2979 !g_socket_condition_wait (socket,
2980 G_IO_IN, NULL, error))
2983 addrlen = sizeof addr;
2985 result = WSARecvFrom (socket->priv->fd,
2987 &bytes_received, &win_flags,
2988 (struct sockaddr *)&addr, &addrlen,
2991 result = WSARecv (socket->priv->fd,
2993 &bytes_received, &win_flags,
2997 int errsv = get_socket_errno ();
2999 if (errsv == WSAEINTR)
3002 win32_unset_event_mask (socket, FD_READ);
3004 if (socket->priv->blocking &&
3005 errsv == WSAEWOULDBLOCK)
3008 g_set_error (error, G_IO_ERROR,
3009 socket_io_error_from_errno (errsv),
3010 _("Error receiving message: %s"), socket_strerror (errsv));
3014 win32_unset_event_mask (socket, FD_READ);
3018 /* decode address */
3019 if (address != NULL)
3022 *address = g_socket_address_new_from_native (&addr, addrlen);
3027 /* capture the flags */
3031 return bytes_received;
3036 #define __G_SOCKET_C__
3037 #include "gioaliasdef.c"