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 network socket handling
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, etc.
71 * However there may be cases where direct use of #GSocket is useful.
73 * TODO: Add more references to the highlevel API once that is more
76 * #GSocket implements the #GInitable interface, so if it is manually constructed
77 * by e.g. g_object_new() you must call g_initable_init() and check the
78 * results before using the object. This is done automatically in
79 * g_socket_new() and g_socket_new_from_fd(), so these functions can return
82 * Sockets operate in two general modes, blocking or non-blocking. When
83 * in blocking mode all operations block until the requested operation
84 * is finished or there is an error. In non-blocking mode all calls that
85 * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
86 * To know when a call would successfully run you can call g_socket_condition_check(),
87 * or g_socket_condition_wait(). You can also use g_socket_create_source() and
88 * attach it to a #GMainContext to get callbacks when I/O is possible.
89 * Note that all sockets are always set to non blocking mode in the system, and
90 * blocking mode is emulated in GSocket.
92 * When working in non-blocking mode applications should always be able to
93 * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
94 * function said that I/O was possible. This can easily happen in case
95 * of a race condition in the application, but it can also happen for other
96 * reasons. For instance, on Windows a socket is always seen as writable
97 * until a write returns %G_IO_ERROR_WOULD_BLOCK.
99 * #GSocket<!-- -->s can be either connection oriented or datagram based.
100 * For connection oriented types you must first establish a connection by
101 * either connecting to an address or accepting a connection from another
102 * address. For connectionless socket types the target/source address is
103 * specified or received in each I/O operation.
105 * All socket file descriptors are set to be close-on-exec.
110 static void g_socket_initable_iface_init (GInitableIface *iface);
111 static gboolean g_socket_initable_init (GInitable *initable,
112 GCancellable *cancellable,
115 G_DEFINE_TYPE_WITH_CODE (GSocket, g_socket, G_TYPE_OBJECT,
116 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
117 g_socket_initable_iface_init));
133 struct _GSocketPrivate
135 GSocketFamily family;
140 GError *construct_error;
141 GSocketAddress *local_address;
142 GSocketAddress *remote_address;
152 GList *requested_conditions; /* list of requested GIOCondition * */
157 get_socket_errno (void)
162 return WSAGetLastError ();
167 socket_io_error_from_errno (int err)
170 return g_io_error_from_errno (err);
175 return G_IO_ERROR_ADDRESS_IN_USE;
177 return G_IO_ERROR_WOULD_BLOCK;
179 return G_IO_ERROR_PERMISSION_DENIED;
180 case WSA_INVALID_HANDLE:
181 case WSA_INVALID_PARAMETER:
184 return G_IO_ERROR_INVALID_ARGUMENT;
185 case WSAEPROTONOSUPPORT:
186 return G_IO_ERROR_NOT_SUPPORTED;
188 return G_IO_ERROR_CANCELLED;
189 case WSAESOCKTNOSUPPORT:
191 case WSAEPFNOSUPPORT:
192 case WSAEAFNOSUPPORT:
193 return G_IO_ERROR_NOT_SUPPORTED;
195 return G_IO_ERROR_FAILED;
201 socket_strerror (int err)
204 return g_strerror (err);
206 static GStaticPrivate msg_private = G_STATIC_PRIVATE_INIT;
209 buf = g_static_private_get (&msg_private);
212 buf = g_new (gchar, 128);
213 g_static_private_set (&msg_private, buf, g_free);
216 msg = g_win32_error_message (err);
217 strncpy (buf, msg, 128);
224 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
226 _win32_unset_event_mask (GSocket *socket, int mask)
228 socket->priv->current_events &= ~mask;
229 socket->priv->current_errors &= ~mask;
232 #define win32_unset_event_mask(_socket, _mask)
236 set_fd_nonblocking (int fd)
245 if ((arg = fcntl (fd, F_GETFL, NULL)) < 0)
247 g_warning ("Error getting socket status flags: %s", socket_strerror (errno));
251 arg = arg | O_NONBLOCK;
253 if (fcntl (fd, F_SETFL, arg) < 0)
254 g_warning ("Error setting socket status flags: %s", socket_strerror (errno));
258 if (ioctlsocket (fd, FIONBIO, &arg) == SOCKET_ERROR)
260 int errsv = get_socket_errno ();
261 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
267 check_socket (GSocket *socket,
270 if (!socket->priv->inited)
272 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
273 _("Invalid socket, not initialized"));
277 if (socket->priv->construct_error)
279 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
280 _("Invalid socket, initialization failed due to: %s"),
281 socket->priv->construct_error->message);
285 if (socket->priv->closed)
287 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
288 _("Socket is already closed"));
295 g_socket_details_from_fd (GSocket *socket)
297 struct sockaddr_storage address;
309 fd = socket->priv->fd;
310 optlen = sizeof value;
311 if (getsockopt (fd, SOL_SOCKET, SO_TYPE, (void *)&value, &optlen) != 0)
313 errsv = get_socket_errno ();
324 /* programmer error */
325 g_error ("creating GSocket from fd %d: %s\n",
326 fd, socket_strerror (errsv));
334 g_assert (optlen == sizeof value);
338 socket->priv->type = G_SOCKET_TYPE_STREAM;
342 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
346 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
350 socket->priv->type = G_SOCKET_TYPE_INVALID;
354 addrlen = sizeof address;
355 if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
357 errsv = get_socket_errno ();
361 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
362 sizeof address.ss_family <= addrlen);
363 switch (address.ss_family)
365 case G_SOCKET_FAMILY_IPV4:
366 case G_SOCKET_FAMILY_IPV6:
367 case G_SOCKET_FAMILY_UNIX:
368 socket->priv->family = address.ss_family;
372 socket->priv->family = G_SOCKET_FAMILY_INVALID;
376 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
378 socket->priv->local_address =
379 g_socket_address_new_from_native (&address, addrlen);
381 addrlen = sizeof address;
382 if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
383 socket->priv->remote_address =
384 g_socket_address_new_from_native (&address, addrlen);
387 optlen = sizeof bool_val;
388 if (getsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
389 (void *)&bool_val, &optlen) == 0)
391 g_assert (optlen == sizeof bool_val);
392 socket->priv->keepalive = !!bool_val;
396 /* Can't read, maybe not supported, assume FALSE */
397 socket->priv->keepalive = FALSE;
403 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
404 socket_io_error_from_errno (errsv),
405 _("creating GSocket from fd: %s"),
406 socket_strerror (errsv));
410 get_protocol_name (int protocol_id)
412 struct protoent *protoent;
413 #ifdef HAVE_GETPROTOBYNUMBER_R
415 struct protoent my_protoent;
418 if (protocol_id == 0)
421 if (protocol_id == -1)
422 return g_strdup ("unknown");
424 #ifdef HAVE_GETPROTOBYNUMBER_R
426 getprotobynumber_r (protocol_id,
427 &my_protoent, buffer, sizeof (buffer),
430 protoent = getprotobynumber (protocol_id);
433 if (protoent == NULL)
434 return g_strdup_printf ("proto-%d", protocol_id);
436 return g_strdup (protoent->p_name);
440 * g_socket_protocol_id_lookup_by_name:
441 * @protocol_name: The name of a protocol, or %NULL
443 * Tries to look up the protocol id for a given
444 * protocol name. If the protocol name is not known
445 * on this system it returns -1.
447 * If @protocol_name is %NULL (default protocol) then
450 * Returns: a protocol id, or -1 if unknown
455 g_socket_protocol_id_lookup_by_name (const char *protocol_name)
457 struct protoent *protoent;
459 #ifdef HAVE_GETPROTOBYNAME_R
461 struct protoent my_protoent;
467 #ifdef HAVE_GETPROTOBYNAME_R
469 getprotobyname_r (protocol_name,
470 &my_protoent, buffer, sizeof (buffer),
473 protoent = getprotobyname (protocol_name);
476 if (protoent == NULL)
478 if (g_str_has_prefix (protocol_name, "proto-"))
479 return atoi (protocol_name + strlen ("proto-"));
482 protocol = protoent->p_proto;
488 g_socket_create_socket (GSocketFamily family,
498 case G_SOCKET_TYPE_STREAM:
499 native_type = SOCK_STREAM;
502 case G_SOCKET_TYPE_DATAGRAM:
503 native_type = SOCK_DGRAM;
506 case G_SOCKET_TYPE_SEQPACKET:
507 native_type = SOCK_SEQPACKET;
511 g_assert_not_reached ();
514 if (protocol_id == -1)
516 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
517 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
522 native_type |= SOCK_CLOEXEC;
524 fd = socket (family, native_type, protocol_id);
528 int errsv = get_socket_errno ();
530 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
531 _("Unable to create socket: %s"), socket_strerror (errsv));
538 /* We always want to set close-on-exec to protect users. If you
539 need to so some weird inheritance to exec you can re-enable this
540 using lower level hacks with g_socket_get_fd(). */
541 flags = fcntl (fd, F_GETFD, 0);
543 (flags & FD_CLOEXEC) == 0)
546 fcntl (fd, F_SETFD, flags);
555 g_socket_constructed (GObject *object)
557 GSocket *socket = G_SOCKET (object);
559 if (socket->priv->fd >= 0)
560 /* create socket->priv info from the fd */
561 g_socket_details_from_fd (socket);
564 /* create the fd from socket->priv info */
565 socket->priv->fd = g_socket_create_socket (socket->priv->family,
567 socket->priv->protocol,
568 &socket->priv->construct_error);
570 /* Always use native nonblocking sockets, as
571 windows sets sockets to nonblocking automatically
572 in certain operations. This way we make things work
573 the same on all platforms */
574 if (socket->priv->fd != -1)
575 set_fd_nonblocking (socket->priv->fd);
579 g_socket_get_property (GObject *object,
584 GSocket *socket = G_SOCKET (object);
589 g_value_set_enum (value, socket->priv->family);
593 g_value_set_enum (value, socket->priv->type);
597 g_value_set_int (value, socket->priv->protocol);
601 g_value_set_int (value, socket->priv->fd);
605 g_value_set_boolean (value, socket->priv->blocking);
608 case PROP_LISTEN_BACKLOG:
609 g_value_set_int (value, socket->priv->listen_backlog);
613 g_value_set_boolean (value, socket->priv->keepalive);
616 case PROP_LOCAL_ADDRESS:
617 g_value_set_object (value, socket->priv->local_address);
620 case PROP_REMOTE_ADDRESS:
621 g_value_set_object (value, socket->priv->remote_address);
625 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
630 g_socket_set_property (GObject *object,
635 GSocket *socket = G_SOCKET (object);
640 socket->priv->family = g_value_get_enum (value);
644 socket->priv->type = g_value_get_enum (value);
648 socket->priv->protocol = g_value_get_int (value);
652 socket->priv->fd = g_value_get_int (value);
656 g_socket_set_blocking (socket, g_value_get_boolean (value));
659 case PROP_LISTEN_BACKLOG:
660 g_socket_set_listen_backlog (socket, g_value_get_int (value));
664 g_socket_set_keepalive (socket, g_value_get_boolean (value));
668 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
673 g_socket_finalize (GObject *object)
675 GSocket *socket = G_SOCKET (object);
677 g_clear_error (&socket->priv->construct_error);
679 if (socket->priv->fd != -1 &&
680 !socket->priv->closed)
681 g_socket_close (socket, NULL);
684 g_assert (socket->priv->requested_conditions == NULL);
687 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
688 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
692 g_socket_dispose (GObject *object)
694 GSocket *socket = G_SOCKET (object);
696 if (socket->priv->local_address)
698 g_object_unref (socket->priv->local_address);
699 socket->priv->local_address = NULL;
702 if (socket->priv->remote_address)
704 g_object_unref (socket->priv->remote_address);
705 socket->priv->remote_address = NULL;
708 if (G_OBJECT_CLASS (g_socket_parent_class)->dispose)
709 (*G_OBJECT_CLASS (g_socket_parent_class)->dispose) (object);
713 g_socket_class_init (GSocketClass *klass)
715 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
718 /* Make sure winsock has been initialized */
719 type = g_inet_address_get_type ();
721 g_type_class_add_private (klass, sizeof (GSocketPrivate));
723 gobject_class->finalize = g_socket_finalize;
724 gobject_class->dispose = g_socket_dispose;
725 gobject_class->constructed = g_socket_constructed;
726 gobject_class->set_property = g_socket_set_property;
727 gobject_class->get_property = g_socket_get_property;
729 g_object_class_install_property (gobject_class, PROP_FAMILY,
730 g_param_spec_enum ("family",
732 P_("The sockets address family"),
733 G_TYPE_SOCKET_FAMILY,
734 G_SOCKET_FAMILY_INVALID,
735 G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
737 g_object_class_install_property (gobject_class, PROP_TYPE,
738 g_param_spec_enum ("type",
740 P_("The sockets type"),
742 G_SOCKET_TYPE_STREAM,
743 G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
745 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
746 g_param_spec_int ("protocol",
747 P_("Socket protocol"),
748 P_("The id of the protocol to use, or -1 for unknown"),
752 G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
754 g_object_class_install_property (gobject_class, PROP_FD,
755 g_param_spec_int ("fd",
756 P_("File descriptor"),
757 P_("The sockets file descriptor"),
761 G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
763 g_object_class_install_property (gobject_class, PROP_BLOCKING,
764 g_param_spec_boolean ("blocking",
766 P_("Whether or not I/O on this socket is blocking"),
768 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
770 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
771 g_param_spec_int ("listen-backlog",
772 P_("Listen backlog"),
773 P_("outstanding connections in the listen queue"),
777 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
779 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
780 g_param_spec_boolean ("keepalive",
781 P_("Keep connection alive"),
782 P_("Keep connection alive by sending periodic pings"),
784 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
786 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
787 g_param_spec_object ("local-address",
789 P_("The local address the socket is bound to"),
790 G_TYPE_SOCKET_ADDRESS,
791 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
793 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
794 g_param_spec_object ("remote-address",
795 P_("Remote address"),
796 P_("The remote address the socket is connected to"),
797 G_TYPE_SOCKET_ADDRESS,
798 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
802 g_socket_initable_iface_init (GInitableIface *iface)
804 iface->init = g_socket_initable_init;
808 g_socket_init (GSocket *socket)
810 socket->priv = G_TYPE_INSTANCE_GET_PRIVATE (socket, G_TYPE_SOCKET, GSocketPrivate);
812 socket->priv->fd = -1;
813 socket->priv->blocking = TRUE;
814 socket->priv->listen_backlog = 10;
815 socket->priv->construct_error = NULL;
816 socket->priv->remote_address = NULL;
817 socket->priv->local_address = NULL;
819 socket->priv->event = WSA_INVALID_EVENT;
824 g_socket_initable_init (GInitable *initable,
825 GCancellable *cancellable,
830 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
832 socket = G_SOCKET (initable);
834 if (cancellable != NULL)
836 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
837 _("Cancellable initialization not supported"));
841 socket->priv->inited = TRUE;
843 if (socket->priv->construct_error)
846 *error = g_error_copy (socket->priv->construct_error);
856 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
857 * @type: the socket type to use.
858 * @protocol_id: the id of the protocol to use, or 0 for default.
859 * @error: #GError for error reporting, or %NULL to ignore.
861 * Creates a new #GSocket with the defined family, type and protocol.
862 * If @protocol is %NULL the default protocol type for the family and
865 * The @protocol is a family and type specific int that specifies what
866 * kind of protocol to use. Many families only support one protocol,
867 * and use 0 for this, others support several and using 0 means
868 * to use the default protocol for the family and type. To use
869 * other protocol, you can use g_socket_protocol_id_lookup_by_name()
870 * to look up the protocol by name, or if you known the system specific
871 * protocol id you can use that.
873 * Returns: a #GSocket or %NULL on error.
874 * Free the returned object with g_object_unref().
879 g_socket_new (GSocketFamily family,
884 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
888 "protocol", protocol_id,
893 * g_socket_new_from_fd:
894 * @fd: a native socket file descriptor.
895 * @error: #GError for error reporting, or %NULL to ignore.
897 * Creates a new #GSocket from a native file descriptor
898 * or winsock SOCKET handle.
900 * This reads all the settings from the file descriptor so that
901 * all properties should work. Note that the file descriptor
902 * will be set to non-blocking mode, independent on the blocking
903 * mode of the #GSocket.
905 * Returns: a #GSocket or %NULL on error.
906 * Free the returned object with g_object_unref().
911 g_socket_new_from_fd (gint fd,
914 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
921 * g_socket_set_blocking:
922 * @socket: a #GSocket.
923 * @blocking: Whether to use blocking I/O or not.
925 * Sets the blocking mode of the socket. In blocking mode
926 * all operations block until they succeed or there is an error. In
927 * non-blocking mode all functions return results immediately or
928 * with a %G_IO_ERROR_WOULD_BLOCK error.
930 * All sockets are created in blocking mode. However, note that the
931 * platform level socket is always non-blocking, and blocking mode
932 * is a GSocket level feature.
937 g_socket_set_blocking (GSocket *socket,
940 g_return_if_fail (G_IS_SOCKET (socket));
942 blocking = !!blocking;
944 if (socket->priv->blocking == blocking)
947 socket->priv->blocking = blocking;
948 g_object_notify (G_OBJECT (socket), "blocking");
952 * g_socket_get_blocking:
953 * @socket: a #GSocket.
955 * Gets the blocking mode of the socket. For details on blocking I/O,
956 * see g_socket_set_blocking().
958 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
963 g_socket_get_blocking (GSocket *socket)
965 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
967 return socket->priv->blocking;
971 * g_socket_set_keepalive:
972 * @socket: a #GSocket.
973 * @keepalive: Whether to use try to keep the connection alive or not.
975 * Setting @keepalive to %TRUE enables the sending of periodic ping requests
976 * on idle connections in order to keep the connection alive. This is only
977 * useful for connection oriented sockets. The exact period used between
978 * each ping is system and protocol dependent.
980 * Sending keepalive requests like this has a few disadvantages. For instance,
981 * it uses more network bandwidth, and it makes your application more sensitive
982 * to temporary outages in the network (i.e. if a cable is pulled your otherwise
983 * idle connection could be terminated, whereas otherwise it would survive unless
984 * actually used before the cable was reinserted). However, it is sometimes
985 * useful to ensure that connections are eventually terminated if e.g. the
986 * remote side is disconnected, so as to avoid leaking resources forever.
991 g_socket_set_keepalive (GSocket *socket,
996 g_return_if_fail (G_IS_SOCKET (socket));
998 keepalive = !!keepalive;
999 if (socket->priv->keepalive == keepalive)
1002 value = (gint) keepalive;
1003 if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_KEEPALIVE,
1004 (gpointer) &value, sizeof (value)) < 0)
1006 int errsv = get_socket_errno ();
1007 g_warning ("error setting keepalive: %s", socket_strerror (errsv));
1011 socket->priv->keepalive = keepalive;
1012 g_object_notify (G_OBJECT (socket), "keepalive");
1016 * g_socket_get_keepalive:
1017 * @socket: a #GSocket.
1019 * Gets the keepalive mode of the socket. For details on this,
1020 * see g_socket_set_keepalive().
1022 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1027 g_socket_get_keepalive (GSocket *socket)
1029 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1031 return socket->priv->keepalive;
1035 * g_socket_get_listen_backlog:
1036 * @socket: a #GSocket.
1038 * Gets the listen backlog setting of the socket. For details on this,
1039 * see g_socket_set_listen_backlog().
1041 * Returns: the maximum number of pending connections.
1046 g_socket_get_listen_backlog (GSocket *socket)
1048 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1050 return socket->priv->listen_backlog;
1054 * g_socket_set_listen_backlog:
1055 * @socket: a #GSocket.
1056 * @backlog: the maximum number of pending connections.
1058 * Sets the maximum number of outstanding connections allowed
1059 * when listening on this socket. If more clients than this are
1060 * connecting to the socket and the application is not handling them
1061 * on time then the new connections will be refused.
1066 g_socket_set_listen_backlog (GSocket *socket,
1069 g_return_if_fail (G_IS_SOCKET (socket));
1071 if (backlog != socket->priv->listen_backlog)
1073 socket->priv->listen_backlog = backlog;
1074 g_object_notify (G_OBJECT (socket), "listen-backlog");
1079 * g_socket_get_family:
1080 * @socket: a #GSocket.
1082 * Gets the socket family of the socket.
1084 * Returns: a #GSocketFamily
1089 g_socket_get_family (GSocket *socket)
1091 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1093 return socket->priv->family;
1097 * g_socket_get_socket_type:
1098 * @socket: a #GSocket.
1100 * Gets the socket type of the socket.
1102 * Returns: a #GSocketType
1107 g_socket_get_socket_type (GSocket *socket)
1109 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1111 return socket->priv->type;
1115 * g_socket_get_protocol_id:
1116 * @socket: a #GSocket.
1118 * Gets the socket protocol id the socket was created with.
1119 * In case the protocol is unknown, -1 is returned.
1121 * Returns: a protocol id, or -1 if unknown
1126 g_socket_get_protocol_id (GSocket *socket)
1128 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1130 return socket->priv->protocol;
1134 * g_socket_get_protocol_name:
1135 * @socket: a #GSocket.
1137 * Gets the socket protocol type name the socket was created with.
1138 * This can be %NULL if the socket was created with a NULL protocol.
1140 * Returns: a string or %NULL, free with g_free
1145 g_socket_get_protocol_name (GSocket *socket)
1147 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1149 return get_protocol_name (socket->priv->protocol);
1154 * @socket: a #GSocket.
1156 * Returns the underlying OS socket object. On unix this
1157 * is a socket file descriptor, and on windows this is
1158 * a Winsock2 SOCKET handle. This may be useful for
1159 * doing platform specific or otherwise unusual operations
1162 * Returns: the file descriptor of the socket.
1167 g_socket_get_fd (GSocket *socket)
1169 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1171 return socket->priv->fd;
1175 * g_socket_get_local_address:
1176 * @socket: a #GSocket.
1177 * @error: #GError for error reporting, or %NULL to ignore.
1179 * Try to get the local address of a bound socket. This is only
1180 * useful if the socket has been bound to a local address.
1182 * Returns: a #GSocketAddress or %NULL on error.
1187 g_socket_get_local_address (GSocket *socket,
1193 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1195 if (socket->priv->local_address)
1196 return socket->priv->local_address;
1198 if (getsockname (socket->priv->fd, (struct sockaddr *) buffer, &len) < 0)
1200 int errsv = get_socket_errno ();
1201 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1202 _("could not get local address: %s"), socket_strerror (errsv));
1206 socket->priv->local_address = g_socket_address_new_from_native (buffer, len);
1207 return socket->priv->local_address;
1211 * g_socket_get_remote_address:
1212 * @socket: a #GSocket.
1213 * @error: #GError for error reporting, or %NULL to ignore.
1215 * Try to get the remove address of a connected socket. This is only
1216 * useful for connection oriented sockets that have been connected.
1218 * Returns: a #GSocketAddress or %NULL on error.
1223 g_socket_get_remote_address (GSocket *socket,
1229 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1231 if (socket->priv->remote_address)
1232 return socket->priv->remote_address;
1234 if (getpeername (socket->priv->fd, (struct sockaddr *) buffer, &len) < 0)
1236 int errsv = get_socket_errno ();
1237 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1238 _("could not get remote address: %s"), socket_strerror (errsv));
1242 socket->priv->remote_address = g_socket_address_new_from_native (buffer, len);
1243 return socket->priv->remote_address;
1247 * g_socket_is_connected:
1248 * @socket: a #GSocket.
1250 * Check whether the socket is connected. This is only useful for
1251 * connection-oriented sockets.
1253 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1258 g_socket_is_connected (GSocket *socket)
1260 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1262 return socket->priv->remote_address != NULL;
1267 * @socket: a #GSocket.
1268 * @error: #GError for error reporting, or %NULL to ignore.
1270 * Marks the socket as a server socket, i.e. a socket that is used
1271 * to accept incoming requests using g_socket_accept().
1273 * Before calling this the socket must be bound to a local address using
1276 * Returns: %TRUE on success, %FALSE on error.
1281 g_socket_listen (GSocket *socket,
1284 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1286 if (!check_socket (socket, error))
1289 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1291 int errsv = get_socket_errno ();
1293 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1294 _("could not listen: %s"), socket_strerror (errsv));
1303 * @socket: a #GSocket.
1304 * @address: a #GSocketAddress specifying the local address.
1305 * @allow_reuse: whether to allow reusing this address
1306 * @error: #GError for error reporting, or %NULL to ignore.
1308 * When a socket is created it is attached to an address family, but it
1309 * doesn't have an address in this family. g_socket_bind() assigns the
1310 * address (sometimes called name) of the socket.
1312 * It is generally required to bind to a local address before you can
1313 * receive connections. (See g_socket_listen() and g_socket_accept() ).
1315 * If @allow_reuse is %TRUE this allows the bind call to succeed in some
1316 * situation where it would otherwise return a %G_IO_ERROR_ADDRESS_IN_USE
1317 * error. The main example is for a TCP server socket where there are
1318 * outstanding connections in the WAIT state, which are generally safe
1319 * to ignore. However, setting it to %TRUE doesn't mean the call will
1320 * succeed if there is a socket actively bound to the address.
1322 * In general, pass %TRUE if the socket will be used to accept connections,
1323 * otherwise pass %FALSE.
1325 * Returns: %TRUE on success, %FALSE on error.
1330 g_socket_bind (GSocket *socket,
1331 GSocketAddress *address,
1332 gboolean reuse_address,
1338 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1340 if (!check_socket (socket, error))
1343 /* SO_REUSEADDR on windows means something else and is not what we want.
1344 It always allows the unix variant of SO_REUSEADDR anyway */
1346 value = (int) !!reuse_address;
1347 if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_REUSEADDR,
1348 (gpointer) &value, sizeof (value)) < 0)
1350 int errsv = get_socket_errno ();
1352 G_IO_ERROR, socket_io_error_from_errno (errsv),
1353 _("Error setting reuse_address: %s"), socket_strerror (errsv));
1358 if (!g_socket_address_to_native (address, addr, sizeof addr))
1361 if (bind (socket->priv->fd, (struct sockaddr *) addr,
1362 g_socket_address_get_native_size (address)) < 0)
1364 int errsv = get_socket_errno ();
1366 G_IO_ERROR, socket_io_error_from_errno (errsv),
1367 _("Error binding to address: %s"), socket_strerror (errsv));
1371 socket->priv->local_address = g_object_ref (address);
1378 * @socket: a #GSocket.
1379 * @error: #GError for error reporting, or %NULL to ignore.
1381 * Accept incoming connections on a connection-based socket. This removes
1382 * the first outstanding connection request from the listening socket and
1383 * creates a #GSocket object for it.
1385 * The @socket must be bound to a local address with g_socket_bind() and
1386 * must be listening for incoming connections (g_socket_listen()).
1388 * If there are no outstanding connections then the operation will block
1389 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
1390 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
1392 * Returns: a new #GSocket, or %NULL on error.
1393 * Free the returned object with g_object_unref().
1398 g_socket_accept (GSocket *socket,
1401 GSocket *new_socket;
1404 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1406 if (!check_socket (socket, error))
1411 if (socket->priv->blocking &&
1412 !g_socket_condition_wait (socket,
1413 G_IO_IN, NULL, error))
1416 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
1418 int errsv = get_socket_errno ();
1420 win32_unset_event_mask (socket, FD_ACCEPT);
1425 if (socket->priv->blocking)
1427 #ifdef WSAEWOULDBLOCK
1428 if (errsv == WSAEWOULDBLOCK)
1431 if (errsv == EWOULDBLOCK ||
1437 g_set_error (error, G_IO_ERROR,
1438 socket_io_error_from_errno (errsv),
1439 _("Error accepting connection: %s"), socket_strerror (errsv));
1445 win32_unset_event_mask (socket, FD_ACCEPT);
1449 /* The socket inherits the accepting sockets event mask and even object,
1450 we need to remove that */
1451 WSAEventSelect (ret, NULL, 0);
1457 /* We always want to set close-on-exec to protect users. If you
1458 need to so some weird inheritance to exec you can re-enable this
1459 using lower level hacks with g_socket_get_fd(). */
1460 flags = fcntl (ret, F_GETFD, 0);
1462 (flags & FD_CLOEXEC) == 0)
1464 flags |= FD_CLOEXEC;
1465 fcntl (ret, F_SETFD, flags);
1470 new_socket = g_socket_new_from_fd (ret, error);
1471 if (new_socket == NULL)
1480 new_socket->priv->protocol = socket->priv->protocol;
1487 * @socket: a #GSocket.
1488 * @address: a #GSocketAddress specifying the remote address.
1489 * @error: #GError for error reporting, or %NULL to ignore.
1491 * Connect the socket to the specified remote address.
1493 * For connection oriented socket this generally means we attempt to make
1494 * a connection to the @address. For a connection-less socket it sets
1495 * the default address for g_socket_send() and discards all incoming datagrams
1496 * from other sources.
1498 * Generally connection oriented sockets can only connect once, but connection-less
1499 * sockets can connect multiple times to change the default address.
1501 * If the connect call needs to do network I/O it will block, unless
1502 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
1503 * and the user can be notified of the connection finishing by waiting
1504 * for the G_IO_OUT condition. The result of the connection can then be
1505 * checked with g_socket_check_pending_error().
1507 * Returns: %TRUE if connected, %FALSE on error.
1512 g_socket_connect (GSocket *socket,
1513 GSocketAddress *address,
1518 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1520 if (!check_socket (socket, error))
1523 g_socket_address_to_native (address, buffer, sizeof buffer);
1527 if (socket->priv->blocking &&
1528 !g_socket_condition_wait (socket,
1529 G_IO_IN, NULL, error))
1532 if (connect (socket->priv->fd, (struct sockaddr *) buffer,
1533 g_socket_address_get_native_size (address)) < 0)
1535 int errsv = get_socket_errno ();
1541 if (errsv == EINPROGRESS)
1543 if (errsv == WSAEINPROGRESS)
1546 if (socket->priv->blocking)
1548 g_socket_condition_wait (socket, G_IO_OUT, NULL, NULL);
1549 if (g_socket_check_pending_error (socket, error))
1552 g_prefix_error (error, _("Error connecting: "));
1555 g_set_error (error, G_IO_ERROR, G_IO_ERROR_PENDING,
1556 _("Connection in progress"));
1559 g_set_error (error, G_IO_ERROR,
1560 socket_io_error_from_errno (errsv),
1561 _("Error connecting: %s"), socket_strerror (errsv));
1568 win32_unset_event_mask (socket, FD_CONNECT);
1570 socket->priv->remote_address = g_object_ref (address);
1576 * g_socket_check_pending_error:
1577 * @socket: a #GSocket
1578 * @error: #GError for error reporting, or %NULL to ignore.
1580 * Checks and resets the pending error for the socket. This is typically
1581 * used to check for errors when g_socket_connect() is used in non-blocking mode.
1583 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
1588 g_socket_check_pending_error (GSocket *socket,
1594 optlen = sizeof (value);
1595 if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
1597 int errsv = get_socket_errno ();
1599 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1600 _("Unable to get pending error: %s"), socket_strerror (errsv));
1606 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (value),
1607 "%s", socket_strerror (value));
1615 * @socket: a #GSocket
1616 * @buffer: a buffer to read data into (which should be at least count bytes long).
1617 * @size: the number of bytes that will be read from the stream
1618 * @error: #GError for error reporting, or %NULL to ignore.
1620 * Receive data (up to @size bytes) from a socket. This is mainly used by
1621 * connection oriented sockets, it is identical to g_socket_receive_from()
1622 * with @address set to %NULL.
1624 * If a message is too long to fit in @buffer, excess bytes may be discarded
1625 * depending on the type of socket the message is received from.
1627 * If the socket is in blocking mode the call will block until there is
1628 * some data to receive or there is an error. If there is no data available
1629 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1630 * will be returned. To be notified of available data, wait for the %G_IO_IN
1633 * On error -1 is returned and @error is set accordingly.
1635 * Returns: Number of bytes read, or -1 on error
1640 g_socket_receive (GSocket *socket,
1647 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1649 if (!check_socket (socket, error))
1654 if (socket->priv->blocking &&
1655 !g_socket_condition_wait (socket,
1656 G_IO_IN, NULL, error))
1659 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
1661 int errsv = get_socket_errno ();
1666 if (socket->priv->blocking)
1668 #ifdef WSAEWOULDBLOCK
1669 if (errsv == WSAEWOULDBLOCK)
1672 if (errsv == EWOULDBLOCK ||
1678 win32_unset_event_mask (socket, FD_READ);
1680 g_set_error (error, G_IO_ERROR,
1681 socket_io_error_from_errno (errsv),
1682 _("Error receiving data: %s"), socket_strerror (errsv));
1686 win32_unset_event_mask (socket, FD_READ);
1695 * g_socket_receive_from:
1696 * @socket: a #GSocket
1697 * @address: a pointer to a #GSocketAddress pointer, or %NULL
1698 * @buffer: a buffer to read data into (which should be at least count bytes long).
1699 * @size: the number of bytes that will be read from the stream
1700 * @error: #GError for error reporting, or %NULL to ignore.
1702 * Receive data (up to @size bytes) from a socket.
1704 * If @address is non-%NULL then @address will be set equal to the
1705 * source address of the received packet.
1706 * @address is owned by the caller.
1708 * If the socket is in blocking mode the call will block until there is
1709 * some data to receive or there is an error. If there is no data available
1710 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1711 * will be returned. To be notified of available data, wait for the %G_IO_IN
1714 * On error -1 is returned and @error is set accordingly.
1716 * Returns: Number of bytes read, or -1 on error
1721 g_socket_receive_from (GSocket *socket,
1722 GSocketAddress **address,
1732 return g_socket_receive_message (socket,
1741 * @socket: a #GSocket
1742 * @buffer: the buffer containing the data to send.
1743 * @size: the number of bytes to send
1744 * @error: #GError for error reporting, or %NULL to ignore.
1746 * Tries to send @size bytes from @buffer on the socket. This is mainly used by
1747 * connection oriented sockets, it is identical to g_socket_send_to()
1748 * with @address set to %NULL.
1750 * If the socket is in blocking mode the call will block until there is
1751 * space for the data in the socket queue. If there is no space available
1752 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1753 * will be returned. To be notified of available space, wait for the %G_IO_OUT
1756 * Note that on Windows you can't rely on a %G_IO_OUT condition
1757 * not producing a %G_IO_ERROR_WOULD_BLOCK error, as this is how Winsock
1758 * write notification works. However, robust apps should always be able to
1759 * handle this since it can easily appear in other cases too.
1761 * On error -1 is returned and @error is set accordingly.
1763 * Returns: Number of bytes read, or -1 on error
1768 g_socket_send (GSocket *socket,
1769 const gchar *buffer,
1775 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1777 if (!check_socket (socket, error))
1782 if (socket->priv->blocking &&
1783 !g_socket_condition_wait (socket,
1784 G_IO_OUT, NULL, error))
1787 if ((ret = send (socket->priv->fd, buffer, size, 0)) < 0)
1789 int errsv = get_socket_errno ();
1794 #ifdef WSAEWOULDBLOCK
1795 if (errsv == WSAEWOULDBLOCK)
1796 win32_unset_event_mask (socket, FD_WRITE);
1799 if (socket->priv->blocking)
1801 #ifdef WSAEWOULDBLOCK
1802 if (errsv == WSAEWOULDBLOCK)
1805 if (errsv == EWOULDBLOCK ||
1811 g_set_error (error, G_IO_ERROR,
1812 socket_io_error_from_errno (errsv),
1813 _("Error sending data: %s"), socket_strerror (errsv));
1824 * @socket: a #GSocket
1825 * @address: a #GSocketAddress, or %NULL
1826 * @buffer: the buffer containing the data to send.
1827 * @size: the number of bytes to send
1828 * @error: #GError for error reporting, or %NULL to ignore.
1830 * Tries to send @size bytes from @buffer to @address. If @address is
1831 * %NULL then the message is sent to the default receiver (set by
1832 * g_socket_connect()).
1834 * If the socket is in blocking mode the call will block until there is
1835 * space for the data in the socket queue. If there is no space available
1836 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1837 * will be returned. To be notified of available space, wait for the %G_IO_OUT
1840 * Note that on Windows you can't rely on a %G_IO_OUT condition
1841 * not producing a %G_IO_ERROR_WOULD_BLOCK error, as this is how Winsock
1842 * write notification works. However, robust apps should always be able to
1843 * handle this since it can easily appear in other cases too.
1845 * On error -1 is returned and @error is set accordingly.
1847 * Returns: Number of bytes read, or -1 on error
1852 g_socket_send_to (GSocket *socket,
1853 GSocketAddress *address,
1854 const gchar *buffer,
1863 return g_socket_send_message (socket,
1872 * @socket: a #GSocket
1873 * @error: #GError for error reporting, or %NULL to ignore.
1875 * Closes the socket, shutting down any active connection.
1877 * Closing a socket does not wait for all outstanding I/O operations to finish,
1878 * so the caller should not rely on them to be guaranteed to complete even
1879 * if the close returns with no error.
1881 * Once the socket is closed, all other operations will return %G_IO_ERROR_CLOSED.
1882 * Closing a stream multiple times will not return an error.
1884 * Sockets will be automatically closed when the last reference
1885 * is dropped, but you might want to call this function to make sure
1886 * resources are released as early as possible.
1888 * Returns: %TRUE on success, %FALSE on error
1893 g_socket_close (GSocket *socket,
1898 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
1900 if (socket->priv->closed)
1901 return TRUE; /* Multiple close not an error */
1903 if (!check_socket (socket, NULL))
1909 res = closesocket (socket->priv->fd);
1911 res = close (socket->priv->fd);
1915 int errsv = get_socket_errno ();
1920 g_set_error (error, G_IO_ERROR,
1921 socket_io_error_from_errno (errsv),
1922 _("Error closing socket: %s"),
1923 socket_strerror (errsv));
1930 if (socket->priv->event != WSA_INVALID_EVENT)
1932 WSACloseEvent (socket->priv->event);
1933 socket->priv->event = WSA_INVALID_EVENT;
1937 socket->priv->closed = TRUE;
1943 * g_socket_is_closed:
1944 * @socket: a #GSocket
1946 * Checks whether a socket is closed.
1948 * Returns: %TRUE if socket is closed, %FALSE otherwise
1953 g_socket_is_closed (GSocket *socket)
1955 return socket->priv->closed;
1959 /* Broken source, used on errors */
1961 broken_prepare (GSource *source,
1968 broken_check (GSource *source)
1974 broken_dispatch (GSource *source,
1975 GSourceFunc callback,
1981 static GSourceFuncs broken_funcs =
1990 network_events_for_condition (GIOCondition condition)
1994 if (condition & G_IO_IN)
1995 event_mask |= (FD_READ | FD_ACCEPT);
1996 if (condition & G_IO_OUT)
1997 event_mask |= (FD_WRITE | FD_CONNECT);
1998 event_mask |= FD_CLOSE;
2004 ensure_event (GSocket *socket)
2006 if (socket->priv->event == WSA_INVALID_EVENT)
2007 socket->priv->event = WSACreateEvent();
2011 update_select_events (GSocket *socket)
2018 ensure_event (socket);
2021 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
2024 event_mask |= network_events_for_condition (*ptr);
2027 if (event_mask != socket->priv->selected_events)
2029 /* If no events selected, disable event so we can unset
2032 if (event_mask == 0)
2035 event = socket->priv->event;
2037 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
2038 socket->priv->selected_events = event_mask;
2043 add_condition_watch (GSocket *socket,
2044 GIOCondition *condition)
2046 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
2048 socket->priv->requested_conditions =
2049 g_list_prepend (socket->priv->requested_conditions, condition);
2051 update_select_events (socket);
2055 remove_condition_watch (GSocket *socket,
2056 GIOCondition *condition)
2058 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
2060 socket->priv->requested_conditions =
2061 g_list_remove (socket->priv->requested_conditions, condition);
2063 update_select_events (socket);
2067 update_condition (GSocket *socket)
2069 WSANETWORKEVENTS events;
2070 GIOCondition condition;
2072 if (WSAEnumNetworkEvents (socket->priv->fd,
2073 socket->priv->event,
2076 socket->priv->current_events |= events.lNetworkEvents;
2077 if (events.lNetworkEvents & FD_WRITE &&
2078 events.iErrorCode[FD_WRITE_BIT] != 0)
2079 socket->priv->current_errors |= FD_WRITE;
2080 if (events.lNetworkEvents & FD_CONNECT &&
2081 events.iErrorCode[FD_CONNECT_BIT] != 0)
2082 socket->priv->current_errors |= FD_CONNECT;
2086 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
2087 condition |= G_IO_IN;
2089 if (socket->priv->current_events & FD_CLOSE ||
2090 socket->priv->closed)
2091 condition |= G_IO_HUP;
2093 /* Never report both G_IO_OUT and HUP, these are
2094 mutually exclusive (can't write to a closed socket) */
2095 if ((condition & G_IO_HUP) == 0 &&
2096 socket->priv->current_events & FD_WRITE)
2098 if (socket->priv->current_errors & FD_WRITE)
2099 condition |= G_IO_ERR;
2101 condition |= G_IO_OUT;
2105 if (socket->priv->current_events & FD_CONNECT)
2107 if (socket->priv->current_errors & FD_CONNECT)
2108 condition |= (G_IO_HUP | G_IO_ERR);
2110 condition |= G_IO_OUT;
2121 GIOCondition condition;
2122 GCancellable *cancellable;
2123 GPollFD cancel_pollfd;
2124 GIOCondition result_condition;
2128 winsock_prepare (GSource *source,
2131 GWinsockSource *winsock_source = (GWinsockSource *)source;
2132 GIOCondition current_condition;
2134 current_condition = update_condition (winsock_source->socket);
2136 if (g_cancellable_is_cancelled (winsock_source->cancellable))
2138 winsock_source->result_condition = current_condition;
2142 if ((winsock_source->condition & current_condition) != 0)
2144 winsock_source->result_condition = current_condition;
2152 winsock_check (GSource *source)
2154 GWinsockSource *winsock_source = (GWinsockSource *)source;
2155 GIOCondition current_condition;
2157 current_condition = update_condition (winsock_source->socket);
2159 if (g_cancellable_is_cancelled (winsock_source->cancellable))
2161 winsock_source->result_condition = current_condition;
2165 if ((winsock_source->condition & current_condition) != 0)
2167 winsock_source->result_condition = current_condition;
2175 winsock_dispatch (GSource *source,
2176 GSourceFunc callback,
2179 GSocketSourceFunc func = (GSocketSourceFunc)callback;
2180 GWinsockSource *winsock_source = (GWinsockSource *)source;
2182 return (*func) (winsock_source->socket,
2183 winsock_source->result_condition & winsock_source->condition,
2188 winsock_finalize (GSource *source)
2190 GWinsockSource *winsock_source = (GWinsockSource *)source;
2193 socket = winsock_source->socket;
2195 remove_condition_watch (socket, &winsock_source->condition);
2196 g_object_unref (socket);
2198 if (winsock_source->cancellable)
2199 g_object_unref (winsock_source->cancellable);
2202 static GSourceFuncs winsock_funcs =
2211 winsock_source_new (GSocket *socket,
2212 GIOCondition condition,
2213 GCancellable *cancellable)
2216 GWinsockSource *winsock_source;
2218 ensure_event (socket);
2220 if (socket->priv->event == WSA_INVALID_EVENT)
2222 g_warning ("Failed to create WSAEvent");
2223 return g_source_new (&broken_funcs, sizeof (GSource));
2226 condition |= G_IO_HUP | G_IO_ERR;
2228 source = g_source_new (&winsock_funcs, sizeof (GWinsockSource));
2229 winsock_source = (GWinsockSource *)source;
2231 winsock_source->socket = g_object_ref (socket);
2232 winsock_source->condition = condition;
2233 add_condition_watch (socket, &winsock_source->condition);
2237 winsock_source->cancellable = g_object_ref (cancellable);
2238 g_cancellable_make_pollfd (cancellable,
2239 &winsock_source->cancel_pollfd);
2240 g_source_add_poll (source, &winsock_source->cancel_pollfd);
2243 winsock_source->pollfd.fd = (gintptr) socket->priv->event;
2244 winsock_source->pollfd.events = condition;
2245 g_source_add_poll (source, &winsock_source->pollfd);
2252 * g_socket_create_source:
2253 * @socket: a #GSocket
2254 * @condition: a #GIOCondition mask to monitor
2255 * @cancellable: a %GCancellable or %NULL
2257 * Creates a %GSource that can be attached to a %GMainContext to monitor
2258 * for the availibility of the specified @condition on the socket.
2260 * The callback on the source is of the #GSocketSourceFunc type.
2262 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2263 * these conditions will always be reported output if they are true.
2265 * @cancellable if not %NULL can be used to cancel the source, which will
2266 * cause the source to trigger, reporting the current condition. You can
2267 * check for this in the callback using g_cancellable_is_cancelled().
2269 * Returns: a newly allocated %GSource, free with g_source_unref().
2274 g_socket_create_source (GSocket *socket,
2275 GIOCondition condition,
2276 GCancellable *cancellable)
2279 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
2282 source = winsock_source_new (socket, condition, cancellable);
2284 source =_g_fd_source_new_with_object (G_OBJECT (socket), socket->priv->fd,
2285 condition, cancellable);
2291 * g_socket_condition_check:
2292 * @socket: a #GSocket
2293 * @condition: a #GIOCondition mask to check
2295 * Checks on the readiness of @socket to perform operations. The
2296 * operations specified in @condition are checked for and masked
2297 * against the currently-satisfied conditions on @socket. The result
2300 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2301 * these conditions will always be set in the output if they are true.
2303 * This call never blocks.
2305 * Returns: the @GIOCondition mask of the current state
2310 g_socket_condition_check (GSocket *socket,
2311 GIOCondition condition)
2313 if (!check_socket (socket, NULL))
2318 GIOCondition current_condition;
2320 condition |= G_IO_ERR | G_IO_HUP;
2322 add_condition_watch (socket, &condition);
2323 current_condition = update_condition (socket);
2324 remove_condition_watch (socket, &condition);
2325 return condition & current_condition;
2331 poll_fd.fd = socket->priv->fd;
2332 poll_fd.events = condition;
2335 result = g_poll (&poll_fd, 1, 0);
2336 while (result == -1 && get_socket_errno () == EINTR);
2338 return poll_fd.revents;
2344 * g_socket_condition_wait:
2345 * @socket: a #GSocket
2346 * @condition: a #GIOCondition mask to wait for
2347 * @cancellable: a #GCancellable, or %NULL
2348 * @error: a #GError pointer, or %NULL
2350 * Waits for @condition to become true on @socket. When the condition
2351 * becomes true, %TRUE is returned.
2353 * If @cancellable is cancelled before the condition becomes true then
2354 * %FALSE is returned and @error, if non-%NULL, is set to %G_IO_ERROR_CANCELLED.
2356 * Returns: %TRUE if the condition was met, %FALSE otherwise
2361 g_socket_condition_wait (GSocket *socket,
2362 GIOCondition condition,
2363 GCancellable *cancellable,
2366 if (!check_socket (socket, error))
2369 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2374 GIOCondition current_condition;
2380 /* Always check these */
2381 condition |= G_IO_ERR | G_IO_HUP;
2383 add_condition_watch (socket, &condition);
2386 events[num_events++] = socket->priv->event;
2390 g_cancellable_make_pollfd (cancellable, &cancel_fd);
2391 events[num_events++] = (WSAEVENT)cancel_fd.fd;
2394 current_condition = update_condition (socket);
2395 while ((condition & current_condition) == 0)
2397 res = WSAWaitForMultipleEvents(num_events, events,
2398 FALSE, WSA_INFINITE, FALSE);
2399 if (res == WSA_WAIT_FAILED)
2401 int errsv = get_socket_errno ();
2403 g_set_error (error, G_IO_ERROR,
2404 socket_io_error_from_errno (errsv),
2405 _("Waiting for socket condition: %s"),
2406 socket_strerror (errsv));
2410 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2413 current_condition = update_condition (socket);
2415 remove_condition_watch (socket, &condition);
2417 return (condition & current_condition) != 0;
2425 poll_fd[0].fd = socket->priv->fd;
2426 poll_fd[0].events = condition;
2431 g_cancellable_make_pollfd (cancellable, &poll_fd[1]);
2436 result = g_poll (poll_fd, num, -1);
2437 while (result == -1 && get_socket_errno () == EINTR);
2439 return cancellable == NULL ||
2440 !g_cancellable_set_error_if_cancelled (cancellable, error);
2447 * @socket: a #GSocket
2448 * @address: a #GSocketAddress, or %NULL
2449 * @vectors: an array of #GOutputVector structs
2450 * @num_vectors: the number of elements in @vectors, or -1
2451 * @messages: a pointer to an array of #GSocketControlMessages, or
2453 * @num_messages: number of elements in @messages, or -1.
2454 * @flags: an int containing #GSocketMsgFlags flags
2455 * @error: #GError for error reporting, or %NULL to ignore.
2457 * Send data to @address on @socket. This is the most complicated and
2458 * fully-featured version of this call. For easier use, see
2459 * g_socket_send() and g_socket_send_to().
2461 * If @address is %NULL then the message is sent to the default receiver
2462 * (set by g_socket_connect()).
2464 * @vector must point to an array of #GOutputVector structs and
2465 * @num_vectors must be the length of this array. These structs
2466 * describe the buffers that the sent data will be gathered from.
2467 * If @num_vector is -1, then @vector is assumed to be terminated
2468 * by a #GOutputVector with a %NULL buffer pointer.
2471 * @messages, if non-%NULL, is taken to point to an array of @num_messages
2472 * #GSocketControlMessage instances. These correspond to the control
2473 * messages to be sent on the socket.
2474 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
2477 * @flags modify how the message sent. The commonly available arguments
2478 * for this is available in the #GSocketMsgFlags enum, but the
2479 * values there are the same as the system values, and the flags
2480 * are passed in as-is, so you can pass in system specific flags too.
2482 * If the socket is in blocking mode the call will block until there is
2483 * space for the data in the socket queue. If there is no space available
2484 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2485 * will be returned. To be notified of available space, wait for the %G_IO_OUT
2488 * Note that on Windows you can't rely on a %G_IO_OUT condition
2489 * not producing a %G_IO_ERROR_WOULD_BLOCK error, as this is how Winsock
2490 * write notification works. However, robust apps should always be able to
2491 * handle this since it can easily appear in other cases too.
2493 * On error -1 is returned and @error is set accordingly.
2495 * Returns: Number of bytes read, or -1 on error
2500 g_socket_send_message (GSocket *socket,
2501 GSocketAddress *address,
2502 GOutputVector *vectors,
2504 GSocketControlMessage **messages,
2509 GOutputVector one_vector;
2512 if (!check_socket (socket, error))
2515 if (num_vectors == -1)
2517 for (num_vectors = 0;
2518 vectors[num_vectors].buffer != NULL;
2523 if (num_messages == -1)
2525 for (num_messages = 0;
2526 messages != NULL && messages[num_messages] != NULL;
2531 if (num_vectors == 0)
2535 one_vector.buffer = &zero;
2536 one_vector.size = 1;
2538 vectors = &one_vector;
2549 msg.msg_namelen = g_socket_address_get_native_size (address);
2550 msg.msg_name = g_alloca (msg.msg_namelen);
2551 g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen);
2556 /* this entire expression will be evaluated at compile time */
2557 if (sizeof *msg.msg_iov == sizeof *vectors &&
2558 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2559 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2560 G_STRUCT_OFFSET (GOutputVector, buffer) &&
2561 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2562 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2563 G_STRUCT_OFFSET (GOutputVector, size))
2564 /* ABI is compatible */
2566 msg.msg_iov = (struct iovec *) vectors;
2567 msg.msg_iovlen = num_vectors;
2570 /* ABI is incompatible */
2574 msg.msg_iov = g_newa (struct iovec, num_vectors);
2575 for (i = 0; i < num_vectors; i++)
2577 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
2578 msg.msg_iov[i].iov_len = vectors[i].size;
2580 msg.msg_iovlen = num_vectors;
2586 struct cmsghdr *cmsg;
2589 msg.msg_controllen = 0;
2590 for (i = 0; i < num_messages; i++)
2591 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
2593 msg.msg_control = g_alloca (msg.msg_controllen);
2595 cmsg = CMSG_FIRSTHDR (&msg);
2596 for (i = 0; i < num_messages; i++)
2598 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
2599 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
2600 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
2601 g_socket_control_message_serialize (messages[i],
2603 cmsg = CMSG_NXTHDR (&msg, cmsg);
2605 g_assert (cmsg == NULL);
2610 if (socket->priv->blocking &&
2611 !g_socket_condition_wait (socket,
2612 G_IO_OUT, NULL, error))
2615 result = sendmsg (socket->priv->fd, &msg, flags);
2618 int errsv = get_socket_errno ();
2623 if (socket->priv->blocking &&
2624 (errsv == EWOULDBLOCK ||
2628 g_set_error (error, G_IO_ERROR,
2629 socket_io_error_from_errno (errsv),
2630 _("Error sending message: %s"), socket_strerror (errsv));
2641 struct sockaddr_storage addr;
2648 /* Win32 doesn't support control messages.
2649 Actually this is possible for raw and datagram sockets
2650 via WSASendMessage on Vista or later, but that doesn't
2652 if (num_messages != 0)
2654 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2655 _("GSocketControlMessage not supported on windows"));
2660 bufs = g_newa (WSABUF, num_vectors);
2661 for (i = 0; i < num_vectors; i++)
2663 bufs[i].buf = (char *)vectors[i].buffer;
2664 bufs[i].len = (gulong)vectors[i].size;
2670 addrlen = g_socket_address_get_native_size (address);
2671 g_socket_address_to_native (address, &addr, sizeof addr);
2676 if (socket->priv->blocking &&
2677 !g_socket_condition_wait (socket,
2678 G_IO_OUT, NULL, error))
2682 result = WSASendTo (socket->priv->fd,
2685 (const struct sockaddr *)&addr, addrlen,
2688 result = WSASend (socket->priv->fd,
2695 int errsv = get_socket_errno ();
2697 if (errsv == WSAEINTR)
2700 if (errsv == WSAEWOULDBLOCK)
2701 win32_unset_event_mask (socket, FD_WRITE);
2703 if (socket->priv->blocking &&
2704 errsv == WSAEWOULDBLOCK)
2707 g_set_error (error, G_IO_ERROR,
2708 socket_io_error_from_errno (errsv),
2709 _("Error sending message: %s"), socket_strerror (errsv));
2722 * g_socket_receive_message:
2723 * @socket: a #GSocket
2724 * @address: a pointer to a #GSocketAddress pointer, or %NULL
2725 * @vectors: an array of #GInputVector structs
2726 * @num_vectors: the number of elements in @vectors, or -1
2727 * @messages: a pointer which will be filled with an array of
2728 * #GSocketControlMessages, or %NULL
2729 * @num_messages: a pointer which will be filled with the number of
2730 * elements in @messages, or %NULL
2731 * @flags: a pointer to an int containing #GSocketMsgFlags flags
2732 * @error: a #GError pointer, or %NULL
2734 * Receive data from a socket. This is the most complicated and
2735 * fully-featured version of this call. For easier use, see
2736 * g_socket_receive() and g_socket_receive_from().
2738 * If @address is non-%NULL then @address will be set equal to the
2739 * source address of the received packet.
2740 * @address is owned by the caller.
2742 * @vector must point to an array of #GInputVector structs and
2743 * @num_vectors must be the length of this array. These structs
2744 * describe the buffers that received data will be scattered into.
2745 * If @num_vector is -1, then @vector is assumed to be terminated
2746 * by a #GInputVector with a %NULL buffer pointer.
2748 * As a special case, if the size of the array is zero (in which case,
2749 * @vectors may of course be %NULL), then a single byte is received
2750 * and discarded. This is to facilitate the common practice of
2751 * sending a single '\0' byte for the purposes of transferring
2754 * @messages, if non-%NULL, is taken to point to a pointer that will
2755 * be set to point to a newly-allocated array of
2756 * #GSocketControlMessage instances. These correspond to the control
2757 * messages received from the kernel, one #GSocketControlMessage per
2758 * message from the kernel. This array is %NULL-terminated and must be
2759 * freed by the caller using g_free().
2761 * @num_messages, if non-%NULL, will be set to the number of control
2762 * messages received.
2764 * If both @messages and @num_messages are non-%NULL, then
2765 * @num_messages gives the number of #GSocketControlMessage instances
2766 * in @messages (ie: not including the %NULL terminator).
2768 * @flags is an in/out parameter. The commonly available arguments
2769 * for this is available in the #GSocketMsgFlags enum, but the
2770 * values there are the same as the system values, and the flags
2771 * are passed in as-is, so you can pass in system specific flags too.
2773 * If the socket is in blocking mode the call will block until there is
2774 * some data to receive or there is an error. If there is no data available
2775 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2776 * will be returned. To be notified of available data, wait for the %G_IO_IN
2779 * On error -1 is returned and @error is set accordingly.
2781 * Returns: Number of bytes read, or -1 on error
2786 g_socket_receive_message (GSocket *socket,
2787 GSocketAddress **address,
2788 GInputVector *vectors,
2790 GSocketControlMessage ***messages,
2795 GInputVector one_vector;
2798 if (!check_socket (socket, error))
2801 if (num_vectors == -1)
2803 for (num_vectors = 0;
2804 vectors[num_vectors].buffer != NULL;
2809 if (num_vectors == 0)
2811 one_vector.buffer = &one_byte;
2812 one_vector.size = 1;
2814 vectors = &one_vector;
2821 struct sockaddr_storage one_sockaddr;
2826 msg.msg_name = &one_sockaddr;
2827 msg.msg_namelen = sizeof (struct sockaddr_storage);
2831 msg.msg_name = NULL;
2832 msg.msg_namelen = 0;
2836 /* this entire expression will be evaluated at compile time */
2837 if (sizeof *msg.msg_iov == sizeof *vectors &&
2838 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2839 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2840 G_STRUCT_OFFSET (GInputVector, buffer) &&
2841 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2842 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2843 G_STRUCT_OFFSET (GInputVector, size))
2844 /* ABI is compatible */
2846 msg.msg_iov = (struct iovec *) vectors;
2847 msg.msg_iovlen = num_vectors;
2850 /* ABI is incompatible */
2854 msg.msg_iov = g_newa (struct iovec, num_vectors);
2855 for (i = 0; i < num_vectors; i++)
2857 msg.msg_iov[i].iov_base = vectors[i].buffer;
2858 msg.msg_iov[i].iov_len = vectors[i].size;
2860 msg.msg_iovlen = num_vectors;
2864 msg.msg_control = g_alloca (2048);
2865 msg.msg_controllen = 2048;
2869 msg.msg_flags = *flags;
2876 if (socket->priv->blocking &&
2877 !g_socket_condition_wait (socket,
2878 G_IO_IN, NULL, error))
2881 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
2885 int errsv = get_socket_errno ();
2890 if (socket->priv->blocking &&
2891 (errsv == EWOULDBLOCK ||
2895 g_set_error (error, G_IO_ERROR,
2896 socket_io_error_from_errno (errsv),
2897 _("Error receiving message: %s"), socket_strerror (errsv));
2904 /* decode address */
2905 if (address != NULL)
2907 if (msg.msg_namelen > 0)
2908 *address = g_socket_address_new_from_native (msg.msg_name,
2914 /* decode control messages */
2916 GSocketControlMessage **my_messages = NULL;
2917 gint allocated = 0, index = 0;
2918 const gchar *scm_pointer;
2919 struct cmsghdr *cmsg;
2922 scm_pointer = (const gchar *) msg.msg_control;
2923 scm_size = msg.msg_controllen;
2925 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
2927 GSocketControlMessage *message;
2929 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
2931 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
2933 if (message == NULL)
2934 /* We've already spewed about the problem in the
2935 deserialization code, so just continue */
2938 if (index == allocated)
2940 /* estimated 99% case: exactly 1 control message */
2941 allocated = MIN (allocated * 2, 1);
2942 my_messages = g_new (GSocketControlMessage *, (allocated + 1));
2946 my_messages[index++] = message;
2950 *num_messages = index;
2954 my_messages[index++] = NULL;
2955 *messages = my_messages;
2961 /* free all those messages we just constructed.
2962 * we have to do it this way if the user ignores the
2963 * messages so that we will close any received fds.
2965 for (i = 0; i < index; i++)
2966 g_object_unref (my_messages[i]);
2967 g_free (my_messages);
2971 /* capture the flags */
2973 *flags = msg.msg_flags;
2979 struct sockaddr_storage addr;
2981 DWORD bytes_received;
2988 bufs = g_newa (WSABUF, num_vectors);
2989 for (i = 0; i < num_vectors; i++)
2991 bufs[i].buf = (char *)vectors[i].buffer;
2992 bufs[i].len = (gulong)vectors[i].size;
3004 if (socket->priv->blocking &&
3005 !g_socket_condition_wait (socket,
3006 G_IO_IN, NULL, error))
3009 addrlen = sizeof addr;
3011 result = WSARecvFrom (socket->priv->fd,
3013 &bytes_received, &win_flags,
3014 (struct sockaddr *)&addr, &addrlen,
3017 result = WSARecv (socket->priv->fd,
3019 &bytes_received, &win_flags,
3023 int errsv = get_socket_errno ();
3025 if (errsv == WSAEINTR)
3028 win32_unset_event_mask (socket, FD_READ);
3030 if (socket->priv->blocking &&
3031 errsv == WSAEWOULDBLOCK)
3034 g_set_error (error, G_IO_ERROR,
3035 socket_io_error_from_errno (errsv),
3036 _("Error receiving message: %s"), socket_strerror (errsv));
3040 win32_unset_event_mask (socket, FD_READ);
3044 /* decode address */
3045 if (address != NULL)
3048 *address = g_socket_address_new_from_native (&addr, addrlen);
3053 /* capture the flags */
3057 return bytes_received;
3062 #define __G_SOCKET_C__
3063 #include "gioaliasdef.c"