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>
36 # include <netinet/in.h>
37 # include <arpa/inet.h>
41 # include <sys/types.h>
43 # include <winsock2.h>
48 #include "gcancellable.h"
49 #include "gioenumtypes.h"
50 #include "ginitable.h"
51 #include "gasynchelper.h"
61 * @short_description: Low-level socket object
63 * @see_also: #GInitable
65 * A #GSocket is a low-level networking primitive. It is a more or less
66 * direct mapping of the BSD socket API in a portable GObject based API.
67 * It supports both the unix socket implementations and winsock2 on Windows.
69 * #GSocket is the platform independent base upon which the higher level
70 * network primitives are based. Applications are not typically meant to
71 * use it directly, but rather through classes like #GSocketClient,
72 * #GSocketService and #GSocketConnection. However there may be cases where
73 * direct use of #GSocket is useful.
75 * #GSocket implements the #GInitable interface, so if it is manually constructed
76 * by e.g. g_object_new() you must call g_initable_init() and check the
77 * results before using the object. This is done automatically in
78 * g_socket_new() and g_socket_new_from_fd(), so these functions can return
81 * Sockets operate in two general modes, blocking or non-blocking. When
82 * in blocking mode all operations block until the requested operation
83 * is finished or there is an error. In non-blocking mode all calls that
84 * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
85 * To know when a call would successfully run you can call g_socket_condition_check(),
86 * or g_socket_condition_wait(). You can also use g_socket_create_source() and
87 * attach it to a #GMainContext to get callbacks when I/O is possible.
88 * Note that all sockets are always set to non blocking mode in the system, and
89 * blocking mode is emulated in GSocket.
91 * When working in non-blocking mode applications should always be able to
92 * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
93 * function said that I/O was possible. This can easily happen in case
94 * of a race condition in the application, but it can also happen for other
95 * reasons. For instance, on Windows a socket is always seen as writable
96 * until a write returns %G_IO_ERROR_WOULD_BLOCK.
98 * #GSocket<!-- -->s can be either connection oriented or datagram based.
99 * For connection oriented types you must first establish a connection by
100 * either connecting to an address or accepting a connection from another
101 * address. For connectionless socket types the target/source address is
102 * specified or received in each I/O operation.
104 * All socket file descriptors are set to be close-on-exec.
106 * Note that creating a #GSocket causes the signal %SIGPIPE to be
107 * ignored for the remainder of the program. If you are writing a
108 * command-line utility that uses #GSocket, you may need to take into
109 * account the fact that your program will not automatically be killed
110 * if it tries to write to %stdout after it has been closed.
115 static void g_socket_initable_iface_init (GInitableIface *iface);
116 static gboolean g_socket_initable_init (GInitable *initable,
117 GCancellable *cancellable,
120 G_DEFINE_TYPE_WITH_CODE (GSocket, g_socket, G_TYPE_OBJECT,
121 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
122 g_socket_initable_iface_init));
138 struct _GSocketPrivate
140 GSocketFamily family;
142 GSocketProtocol protocol;
145 GError *construct_error;
157 GList *requested_conditions; /* list of requested GIOCondition * */
162 get_socket_errno (void)
167 return WSAGetLastError ();
172 socket_io_error_from_errno (int err)
175 return g_io_error_from_errno (err);
180 return G_IO_ERROR_ADDRESS_IN_USE;
182 return G_IO_ERROR_WOULD_BLOCK;
184 return G_IO_ERROR_PERMISSION_DENIED;
185 case WSA_INVALID_HANDLE:
186 case WSA_INVALID_PARAMETER:
189 return G_IO_ERROR_INVALID_ARGUMENT;
190 case WSAEPROTONOSUPPORT:
191 return G_IO_ERROR_NOT_SUPPORTED;
193 return G_IO_ERROR_CANCELLED;
194 case WSAESOCKTNOSUPPORT:
196 case WSAEPFNOSUPPORT:
197 case WSAEAFNOSUPPORT:
198 return G_IO_ERROR_NOT_SUPPORTED;
200 return G_IO_ERROR_FAILED;
206 socket_strerror (int err)
209 return g_strerror (err);
211 static GStaticPrivate msg_private = G_STATIC_PRIVATE_INIT;
214 buf = g_static_private_get (&msg_private);
217 buf = g_new (gchar, 128);
218 g_static_private_set (&msg_private, buf, g_free);
221 msg = g_win32_error_message (err);
222 strncpy (buf, msg, 128);
229 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
231 _win32_unset_event_mask (GSocket *socket, int mask)
233 socket->priv->current_events &= ~mask;
234 socket->priv->current_errors &= ~mask;
237 #define win32_unset_event_mask(_socket, _mask)
241 set_fd_nonblocking (int fd)
250 if ((arg = fcntl (fd, F_GETFL, NULL)) < 0)
252 g_warning ("Error getting socket status flags: %s", socket_strerror (errno));
256 arg = arg | O_NONBLOCK;
258 if (fcntl (fd, F_SETFL, arg) < 0)
259 g_warning ("Error setting socket status flags: %s", socket_strerror (errno));
263 if (ioctlsocket (fd, FIONBIO, &arg) == SOCKET_ERROR)
265 int errsv = get_socket_errno ();
266 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
272 check_socket (GSocket *socket,
275 if (!socket->priv->inited)
277 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
278 _("Invalid socket, not initialized"));
282 if (socket->priv->construct_error)
284 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
285 _("Invalid socket, initialization failed due to: %s"),
286 socket->priv->construct_error->message);
290 if (socket->priv->closed)
292 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
293 _("Socket is already closed"));
300 g_socket_details_from_fd (GSocket *socket)
302 struct sockaddr_storage address;
314 fd = socket->priv->fd;
315 optlen = sizeof value;
316 if (getsockopt (fd, SOL_SOCKET, SO_TYPE, (void *)&value, &optlen) != 0)
318 errsv = get_socket_errno ();
329 /* programmer error */
330 g_error ("creating GSocket from fd %d: %s\n",
331 fd, socket_strerror (errsv));
339 g_assert (optlen == sizeof value);
343 socket->priv->type = G_SOCKET_TYPE_STREAM;
347 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
351 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
355 socket->priv->type = G_SOCKET_TYPE_INVALID;
359 addrlen = sizeof address;
360 if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
362 errsv = get_socket_errno ();
366 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
367 sizeof address.ss_family <= addrlen);
368 switch (address.ss_family)
370 case G_SOCKET_FAMILY_IPV4:
371 case G_SOCKET_FAMILY_IPV6:
372 case G_SOCKET_FAMILY_UNIX:
373 socket->priv->family = address.ss_family;
377 socket->priv->family = G_SOCKET_FAMILY_INVALID;
381 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
383 addrlen = sizeof address;
384 if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
385 socket->priv->connected = TRUE;
388 optlen = sizeof bool_val;
389 if (getsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
390 (void *)&bool_val, &optlen) == 0)
392 g_assert (optlen == sizeof bool_val);
393 socket->priv->keepalive = !!bool_val;
397 /* Can't read, maybe not supported, assume FALSE */
398 socket->priv->keepalive = FALSE;
404 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
405 socket_io_error_from_errno (errsv),
406 _("creating GSocket from fd: %s"),
407 socket_strerror (errsv));
411 g_socket_create_socket (GSocketFamily family,
421 case G_SOCKET_TYPE_STREAM:
422 native_type = SOCK_STREAM;
425 case G_SOCKET_TYPE_DATAGRAM:
426 native_type = SOCK_DGRAM;
429 case G_SOCKET_TYPE_SEQPACKET:
430 native_type = SOCK_SEQPACKET;
434 g_assert_not_reached ();
439 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
440 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
445 native_type |= SOCK_CLOEXEC;
447 fd = socket (family, native_type, protocol);
451 int errsv = get_socket_errno ();
453 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
454 _("Unable to create socket: %s"), socket_strerror (errsv));
461 /* We always want to set close-on-exec to protect users. If you
462 need to so some weird inheritance to exec you can re-enable this
463 using lower level hacks with g_socket_get_fd(). */
464 flags = fcntl (fd, F_GETFD, 0);
466 (flags & FD_CLOEXEC) == 0)
469 fcntl (fd, F_SETFD, flags);
478 g_socket_constructed (GObject *object)
480 GSocket *socket = G_SOCKET (object);
482 if (socket->priv->fd >= 0)
483 /* create socket->priv info from the fd */
484 g_socket_details_from_fd (socket);
487 /* create the fd from socket->priv info */
488 socket->priv->fd = g_socket_create_socket (socket->priv->family,
490 socket->priv->protocol,
491 &socket->priv->construct_error);
493 /* Always use native nonblocking sockets, as
494 windows sets sockets to nonblocking automatically
495 in certain operations. This way we make things work
496 the same on all platforms */
497 if (socket->priv->fd != -1)
498 set_fd_nonblocking (socket->priv->fd);
502 g_socket_get_property (GObject *object,
507 GSocket *socket = G_SOCKET (object);
508 GSocketAddress *address;
513 g_value_set_enum (value, socket->priv->family);
517 g_value_set_enum (value, socket->priv->type);
521 g_value_set_enum (value, socket->priv->protocol);
525 g_value_set_int (value, socket->priv->fd);
529 g_value_set_boolean (value, socket->priv->blocking);
532 case PROP_LISTEN_BACKLOG:
533 g_value_set_int (value, socket->priv->listen_backlog);
537 g_value_set_boolean (value, socket->priv->keepalive);
540 case PROP_LOCAL_ADDRESS:
541 address = g_socket_get_local_address (socket, NULL);
542 g_value_take_object (value, address);
545 case PROP_REMOTE_ADDRESS:
546 address = g_socket_get_remote_address (socket, NULL);
547 g_value_take_object (value, address);
551 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
556 g_socket_set_property (GObject *object,
561 GSocket *socket = G_SOCKET (object);
566 socket->priv->family = g_value_get_enum (value);
570 socket->priv->type = g_value_get_enum (value);
574 socket->priv->protocol = g_value_get_enum (value);
578 socket->priv->fd = g_value_get_int (value);
582 g_socket_set_blocking (socket, g_value_get_boolean (value));
585 case PROP_LISTEN_BACKLOG:
586 g_socket_set_listen_backlog (socket, g_value_get_int (value));
590 g_socket_set_keepalive (socket, g_value_get_boolean (value));
594 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
599 g_socket_finalize (GObject *object)
601 GSocket *socket = G_SOCKET (object);
603 g_clear_error (&socket->priv->construct_error);
605 if (socket->priv->fd != -1 &&
606 !socket->priv->closed)
607 g_socket_close (socket, NULL);
610 g_assert (socket->priv->requested_conditions == NULL);
613 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
614 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
618 g_socket_class_init (GSocketClass *klass)
620 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
623 /* Make sure winsock has been initialized */
624 type = g_inet_address_get_type ();
627 /* There is no portable, thread-safe way to avoid having the process
628 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
629 * forced to simply ignore the signal process-wide.
631 signal (SIGPIPE, SIG_IGN);
634 g_type_class_add_private (klass, sizeof (GSocketPrivate));
636 gobject_class->finalize = g_socket_finalize;
637 gobject_class->constructed = g_socket_constructed;
638 gobject_class->set_property = g_socket_set_property;
639 gobject_class->get_property = g_socket_get_property;
641 g_object_class_install_property (gobject_class, PROP_FAMILY,
642 g_param_spec_enum ("family",
644 P_("The sockets address family"),
645 G_TYPE_SOCKET_FAMILY,
646 G_SOCKET_FAMILY_INVALID,
647 G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
649 g_object_class_install_property (gobject_class, PROP_TYPE,
650 g_param_spec_enum ("type",
652 P_("The sockets type"),
654 G_SOCKET_TYPE_STREAM,
655 G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
657 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
658 g_param_spec_enum ("protocol",
659 P_("Socket protocol"),
660 P_("The id of the protocol to use, or -1 for unknown"),
661 G_TYPE_SOCKET_PROTOCOL,
662 G_SOCKET_PROTOCOL_UNKNOWN,
663 G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
665 g_object_class_install_property (gobject_class, PROP_FD,
666 g_param_spec_int ("fd",
667 P_("File descriptor"),
668 P_("The sockets file descriptor"),
672 G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
674 g_object_class_install_property (gobject_class, PROP_BLOCKING,
675 g_param_spec_boolean ("blocking",
677 P_("Whether or not I/O on this socket is blocking"),
679 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
681 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
682 g_param_spec_int ("listen-backlog",
683 P_("Listen backlog"),
684 P_("outstanding connections in the listen queue"),
688 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
690 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
691 g_param_spec_boolean ("keepalive",
692 P_("Keep connection alive"),
693 P_("Keep connection alive by sending periodic pings"),
695 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
697 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
698 g_param_spec_object ("local-address",
700 P_("The local address the socket is bound to"),
701 G_TYPE_SOCKET_ADDRESS,
702 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
704 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
705 g_param_spec_object ("remote-address",
706 P_("Remote address"),
707 P_("The remote address the socket is connected to"),
708 G_TYPE_SOCKET_ADDRESS,
709 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
713 g_socket_initable_iface_init (GInitableIface *iface)
715 iface->init = g_socket_initable_init;
719 g_socket_init (GSocket *socket)
721 socket->priv = G_TYPE_INSTANCE_GET_PRIVATE (socket, G_TYPE_SOCKET, GSocketPrivate);
723 socket->priv->fd = -1;
724 socket->priv->blocking = TRUE;
725 socket->priv->listen_backlog = 10;
726 socket->priv->construct_error = NULL;
728 socket->priv->event = WSA_INVALID_EVENT;
733 g_socket_initable_init (GInitable *initable,
734 GCancellable *cancellable,
739 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
741 socket = G_SOCKET (initable);
743 if (cancellable != NULL)
745 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
746 _("Cancellable initialization not supported"));
750 socket->priv->inited = TRUE;
752 if (socket->priv->construct_error)
755 *error = g_error_copy (socket->priv->construct_error);
765 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
766 * @type: the socket type to use.
767 * @protocol: the id of the protocol to use, or 0 for default.
768 * @error: #GError for error reporting, or %NULL to ignore.
770 * Creates a new #GSocket with the defined family, type and protocol.
771 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
772 * for the family and type is used.
774 * The @protocol is a family and type specific int that specifies what
775 * kind of protocol to use. #GSocketProtocol lists several common ones.
776 * Many families only support one protocol, and use 0 for this, others
777 * support several and using 0 means to use the default protocol for
778 * the family and type.
780 * The protocol id is passed directly to the operating
781 * system, so you can use protocols not listed in #GSocketProtocol if you
782 * know the protocol number used for it.
784 * Returns: a #GSocket or %NULL on error.
785 * Free the returned object with g_object_unref().
790 g_socket_new (GSocketFamily family,
792 GSocketProtocol protocol,
795 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
799 "protocol", protocol,
804 * g_socket_new_from_fd:
805 * @fd: a native socket file descriptor.
806 * @error: #GError for error reporting, or %NULL to ignore.
808 * Creates a new #GSocket from a native file descriptor
809 * or winsock SOCKET handle.
811 * This reads all the settings from the file descriptor so that
812 * all properties should work. Note that the file descriptor
813 * will be set to non-blocking mode, independent on the blocking
814 * mode of the #GSocket.
816 * Returns: a #GSocket or %NULL on error.
817 * Free the returned object with g_object_unref().
822 g_socket_new_from_fd (gint fd,
825 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
832 * g_socket_set_blocking:
833 * @socket: a #GSocket.
834 * @blocking: Whether to use blocking I/O or not.
836 * Sets the blocking mode of the socket. In blocking mode
837 * all operations block until they succeed or there is an error. In
838 * non-blocking mode all functions return results immediately or
839 * with a %G_IO_ERROR_WOULD_BLOCK error.
841 * All sockets are created in blocking mode. However, note that the
842 * platform level socket is always non-blocking, and blocking mode
843 * is a GSocket level feature.
848 g_socket_set_blocking (GSocket *socket,
851 g_return_if_fail (G_IS_SOCKET (socket));
853 blocking = !!blocking;
855 if (socket->priv->blocking == blocking)
858 socket->priv->blocking = blocking;
859 g_object_notify (G_OBJECT (socket), "blocking");
863 * g_socket_get_blocking:
864 * @socket: a #GSocket.
866 * Gets the blocking mode of the socket. For details on blocking I/O,
867 * see g_socket_set_blocking().
869 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
874 g_socket_get_blocking (GSocket *socket)
876 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
878 return socket->priv->blocking;
882 * g_socket_set_keepalive:
883 * @socket: a #GSocket.
884 * @keepalive: Whether to use try to keep the connection alive or not.
886 * Setting @keepalive to %TRUE enables the sending of periodic ping requests
887 * on idle connections in order to keep the connection alive. This is only
888 * useful for connection oriented sockets. The exact period used between
889 * each ping is system and protocol dependent.
891 * Sending keepalive requests like this has a few disadvantages. For instance,
892 * it uses more network bandwidth, and it makes your application more sensitive
893 * to temporary outages in the network (i.e. if a cable is pulled your otherwise
894 * idle connection could be terminated, whereas otherwise it would survive unless
895 * actually used before the cable was reinserted). However, it is sometimes
896 * useful to ensure that connections are eventually terminated if e.g. the
897 * remote side is disconnected, so as to avoid leaking resources forever.
902 g_socket_set_keepalive (GSocket *socket,
907 g_return_if_fail (G_IS_SOCKET (socket));
909 keepalive = !!keepalive;
910 if (socket->priv->keepalive == keepalive)
913 value = (gint) keepalive;
914 if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_KEEPALIVE,
915 (gpointer) &value, sizeof (value)) < 0)
917 int errsv = get_socket_errno ();
918 g_warning ("error setting keepalive: %s", socket_strerror (errsv));
922 socket->priv->keepalive = keepalive;
923 g_object_notify (G_OBJECT (socket), "keepalive");
927 * g_socket_get_keepalive:
928 * @socket: a #GSocket.
930 * Gets the keepalive mode of the socket. For details on this,
931 * see g_socket_set_keepalive().
933 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
938 g_socket_get_keepalive (GSocket *socket)
940 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
942 return socket->priv->keepalive;
946 * g_socket_get_listen_backlog:
947 * @socket: a #GSocket.
949 * Gets the listen backlog setting of the socket. For details on this,
950 * see g_socket_set_listen_backlog().
952 * Returns: the maximum number of pending connections.
957 g_socket_get_listen_backlog (GSocket *socket)
959 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
961 return socket->priv->listen_backlog;
965 * g_socket_set_listen_backlog:
966 * @socket: a #GSocket.
967 * @backlog: the maximum number of pending connections.
969 * Sets the maximum number of outstanding connections allowed
970 * when listening on this socket. If more clients than this are
971 * connecting to the socket and the application is not handling them
972 * on time then the new connections will be refused.
974 * Note that this must be called before g_socket_listen() and has no
975 * effect if called after that.
980 g_socket_set_listen_backlog (GSocket *socket,
983 g_return_if_fail (G_IS_SOCKET (socket));
984 g_return_if_fail (!socket->priv->listening);
986 if (backlog != socket->priv->listen_backlog)
988 socket->priv->listen_backlog = backlog;
989 g_object_notify (G_OBJECT (socket), "listen-backlog");
994 * g_socket_get_family:
995 * @socket: a #GSocket.
997 * Gets the socket family of the socket.
999 * Returns: a #GSocketFamily
1004 g_socket_get_family (GSocket *socket)
1006 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1008 return socket->priv->family;
1012 * g_socket_get_socket_type:
1013 * @socket: a #GSocket.
1015 * Gets the socket type of the socket.
1017 * Returns: a #GSocketType
1022 g_socket_get_socket_type (GSocket *socket)
1024 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1026 return socket->priv->type;
1030 * g_socket_get_protocol:
1031 * @socket: a #GSocket.
1033 * Gets the socket protocol id the socket was created with.
1034 * In case the protocol is unknown, -1 is returned.
1036 * Returns: a protocol id, or -1 if unknown
1041 g_socket_get_protocol (GSocket *socket)
1043 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1045 return socket->priv->protocol;
1050 * @socket: a #GSocket.
1052 * Returns the underlying OS socket object. On unix this
1053 * is a socket file descriptor, and on windows this is
1054 * a Winsock2 SOCKET handle. This may be useful for
1055 * doing platform specific or otherwise unusual operations
1058 * Returns: the file descriptor of the socket.
1063 g_socket_get_fd (GSocket *socket)
1065 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1067 return socket->priv->fd;
1071 * g_socket_get_local_address:
1072 * @socket: a #GSocket.
1073 * @error: #GError for error reporting, or %NULL to ignore.
1075 * Try to get the local address of a bound socket. This is only
1076 * useful if the socket has been bound to a local address,
1077 * either explicitly or implicitly when connecting.
1079 * Returns: a #GSocketAddress or %NULL on error.
1080 * Free the returned object with g_object_unref().
1085 g_socket_get_local_address (GSocket *socket,
1088 struct sockaddr_storage buffer;
1089 guint32 len = sizeof (buffer);
1091 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1093 if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1095 int errsv = get_socket_errno ();
1096 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1097 _("could not get local address: %s"), socket_strerror (errsv));
1101 return g_socket_address_new_from_native (&buffer, len);
1105 * g_socket_get_remote_address:
1106 * @socket: a #GSocket.
1107 * @error: #GError for error reporting, or %NULL to ignore.
1109 * Try to get the remove address of a connected socket. This is only
1110 * useful for connection oriented sockets that have been connected.
1112 * Returns: a #GSocketAddress or %NULL on error.
1113 * Free the returned object with g_object_unref().
1118 g_socket_get_remote_address (GSocket *socket,
1121 struct sockaddr_storage buffer;
1122 guint32 len = sizeof (buffer);
1124 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1126 if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1128 int errsv = get_socket_errno ();
1129 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1130 _("could not get remote address: %s"), socket_strerror (errsv));
1134 return g_socket_address_new_from_native (&buffer, len);
1138 * g_socket_is_connected:
1139 * @socket: a #GSocket.
1141 * Check whether the socket is connected. This is only useful for
1142 * connection-oriented sockets.
1144 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1149 g_socket_is_connected (GSocket *socket)
1151 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1153 return socket->priv->connected;
1158 * @socket: a #GSocket.
1159 * @error: #GError for error reporting, or %NULL to ignore.
1161 * Marks the socket as a server socket, i.e. a socket that is used
1162 * to accept incoming requests using g_socket_accept().
1164 * Before calling this the socket must be bound to a local address using
1167 * To set the maximum amount of outstanding clients, use
1168 * g_socket_set_listen_backlog().
1170 * Returns: %TRUE on success, %FALSE on error.
1175 g_socket_listen (GSocket *socket,
1178 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1180 if (!check_socket (socket, error))
1183 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1185 int errsv = get_socket_errno ();
1187 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1188 _("could not listen: %s"), socket_strerror (errsv));
1192 socket->priv->listening = TRUE;
1199 * @socket: a #GSocket.
1200 * @address: a #GSocketAddress specifying the local address.
1201 * @allow_reuse: whether to allow reusing this address
1202 * @error: #GError for error reporting, or %NULL to ignore.
1204 * When a socket is created it is attached to an address family, but it
1205 * doesn't have an address in this family. g_socket_bind() assigns the
1206 * address (sometimes called name) of the socket.
1208 * It is generally required to bind to a local address before you can
1209 * receive connections. (See g_socket_listen() and g_socket_accept() ).
1211 * If @allow_reuse is %TRUE this allows the bind call to succeed in some
1212 * situation where it would otherwise return a %G_IO_ERROR_ADDRESS_IN_USE
1213 * error. The main example is for a TCP server socket where there are
1214 * outstanding connections in the WAIT state, which are generally safe
1215 * to ignore. However, setting it to %TRUE doesn't mean the call will
1216 * succeed if there is a socket actively bound to the address.
1218 * In general, pass %TRUE if the socket will be used to accept connections,
1219 * otherwise pass %FALSE.
1221 * Returns: %TRUE on success, %FALSE on error.
1226 g_socket_bind (GSocket *socket,
1227 GSocketAddress *address,
1228 gboolean reuse_address,
1231 struct sockaddr_storage addr;
1234 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1236 if (!check_socket (socket, error))
1239 /* SO_REUSEADDR on windows means something else and is not what we want.
1240 It always allows the unix variant of SO_REUSEADDR anyway */
1242 value = (int) !!reuse_address;
1243 /* Ignore errors here, the only likely error is "not supported", and
1244 this is a "best effort" thing mainly */
1245 setsockopt (socket->priv->fd, SOL_SOCKET, SO_REUSEADDR,
1246 (gpointer) &value, sizeof (value));
1249 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1252 if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1253 g_socket_address_get_native_size (address)) < 0)
1255 int errsv = get_socket_errno ();
1257 G_IO_ERROR, socket_io_error_from_errno (errsv),
1258 _("Error binding to address: %s"), socket_strerror (errsv));
1267 * @socket: a #GSocket.
1268 * @error: #GError for error reporting, or %NULL to ignore.
1270 * Accept incoming connections on a connection-based socket. This removes
1271 * the first outstanding connection request from the listening socket and
1272 * creates a #GSocket object for it.
1274 * The @socket must be bound to a local address with g_socket_bind() and
1275 * must be listening for incoming connections (g_socket_listen()).
1277 * If there are no outstanding connections then the operation will block
1278 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
1279 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
1281 * Returns: a new #GSocket, or %NULL on error.
1282 * Free the returned object with g_object_unref().
1287 g_socket_accept (GSocket *socket,
1290 GSocket *new_socket;
1293 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1295 if (!check_socket (socket, error))
1300 if (socket->priv->blocking &&
1301 !g_socket_condition_wait (socket,
1302 G_IO_IN, NULL, error))
1305 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
1307 int errsv = get_socket_errno ();
1309 win32_unset_event_mask (socket, FD_ACCEPT);
1314 if (socket->priv->blocking)
1316 #ifdef WSAEWOULDBLOCK
1317 if (errsv == WSAEWOULDBLOCK)
1320 if (errsv == EWOULDBLOCK ||
1326 g_set_error (error, G_IO_ERROR,
1327 socket_io_error_from_errno (errsv),
1328 _("Error accepting connection: %s"), socket_strerror (errsv));
1334 win32_unset_event_mask (socket, FD_ACCEPT);
1338 /* The socket inherits the accepting sockets event mask and even object,
1339 we need to remove that */
1340 WSAEventSelect (ret, NULL, 0);
1346 /* We always want to set close-on-exec to protect users. If you
1347 need to so some weird inheritance to exec you can re-enable this
1348 using lower level hacks with g_socket_get_fd(). */
1349 flags = fcntl (ret, F_GETFD, 0);
1351 (flags & FD_CLOEXEC) == 0)
1353 flags |= FD_CLOEXEC;
1354 fcntl (ret, F_SETFD, flags);
1359 new_socket = g_socket_new_from_fd (ret, error);
1360 if (new_socket == NULL)
1369 new_socket->priv->protocol = socket->priv->protocol;
1376 * @socket: a #GSocket.
1377 * @address: a #GSocketAddress specifying the remote address.
1378 * @error: #GError for error reporting, or %NULL to ignore.
1380 * Connect the socket to the specified remote address.
1382 * For connection oriented socket this generally means we attempt to make
1383 * a connection to the @address. For a connection-less socket it sets
1384 * the default address for g_socket_send() and discards all incoming datagrams
1385 * from other sources.
1387 * Generally connection oriented sockets can only connect once, but connection-less
1388 * sockets can connect multiple times to change the default address.
1390 * If the connect call needs to do network I/O it will block, unless
1391 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
1392 * and the user can be notified of the connection finishing by waiting
1393 * for the G_IO_OUT condition. The result of the connection can then be
1394 * checked with g_socket_check_connect_result().
1396 * Returns: %TRUE if connected, %FALSE on error.
1401 g_socket_connect (GSocket *socket,
1402 GSocketAddress *address,
1405 struct sockaddr_storage buffer;
1407 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1409 if (!check_socket (socket, error))
1412 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
1417 if (socket->priv->blocking &&
1418 !g_socket_condition_wait (socket,
1419 G_IO_IN, NULL, error))
1422 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
1423 g_socket_address_get_native_size (address)) < 0)
1425 int errsv = get_socket_errno ();
1431 if (errsv == EINPROGRESS)
1433 if (errsv == WSAEINPROGRESS)
1436 if (socket->priv->blocking)
1438 g_socket_condition_wait (socket, G_IO_OUT, NULL, NULL);
1439 if (g_socket_check_connect_result (socket, error))
1442 g_prefix_error (error, _("Error connecting: "));
1445 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
1446 _("Connection in progress"));
1449 g_set_error (error, G_IO_ERROR,
1450 socket_io_error_from_errno (errsv),
1451 _("Error connecting: %s"), socket_strerror (errsv));
1458 win32_unset_event_mask (socket, FD_CONNECT);
1460 socket->priv->connected = TRUE;
1466 * g_socket_check_connect_result:
1467 * @socket: a #GSocket
1468 * @error: #GError for error reporting, or %NULL to ignore.
1470 * Checks and resets the pending connect error for the socket. This is
1471 * used to check for errors when g_socket_connect() is used in non-blocking mode.
1473 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
1478 g_socket_check_connect_result (GSocket *socket,
1484 optlen = sizeof (value);
1485 if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
1487 int errsv = get_socket_errno ();
1489 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1490 _("Unable to get pending error: %s"), socket_strerror (errsv));
1496 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
1497 socket_strerror (value));
1505 * @socket: a #GSocket
1506 * @buffer: a buffer to read data into (which should be at least count bytes long).
1507 * @size: the number of bytes that will be read from the stream
1508 * @error: #GError for error reporting, or %NULL to ignore.
1510 * Receive data (up to @size bytes) from a socket. This is mainly used by
1511 * connection oriented sockets, it is identical to g_socket_receive_from()
1512 * with @address set to %NULL.
1514 * If a message is too long to fit in @buffer, excess bytes may be discarded
1515 * depending on the type of socket the message is received from.
1517 * If the socket is in blocking mode the call will block until there is
1518 * some data to receive or there is an error. If there is no data available
1519 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1520 * will be returned. To be notified of available data, wait for the %G_IO_IN
1523 * On error -1 is returned and @error is set accordingly.
1525 * Returns: Number of bytes read, or -1 on error
1530 g_socket_receive (GSocket *socket,
1537 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1539 if (!check_socket (socket, error))
1544 if (socket->priv->blocking &&
1545 !g_socket_condition_wait (socket,
1546 G_IO_IN, NULL, error))
1549 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
1551 int errsv = get_socket_errno ();
1556 if (socket->priv->blocking)
1558 #ifdef WSAEWOULDBLOCK
1559 if (errsv == WSAEWOULDBLOCK)
1562 if (errsv == EWOULDBLOCK ||
1568 win32_unset_event_mask (socket, FD_READ);
1570 g_set_error (error, G_IO_ERROR,
1571 socket_io_error_from_errno (errsv),
1572 _("Error receiving data: %s"), socket_strerror (errsv));
1576 win32_unset_event_mask (socket, FD_READ);
1585 * g_socket_receive_from:
1586 * @socket: a #GSocket
1587 * @address: a pointer to a #GSocketAddress pointer, or %NULL
1588 * @buffer: a buffer to read data into (which should be at least count bytes long).
1589 * @size: the number of bytes that will be read from the stream
1590 * @error: #GError for error reporting, or %NULL to ignore.
1592 * Receive data (up to @size bytes) from a socket.
1594 * If @address is non-%NULL then @address will be set equal to the
1595 * source address of the received packet.
1596 * @address is owned by the caller.
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_from (GSocket *socket,
1612 GSocketAddress **address,
1622 return g_socket_receive_message (socket,
1631 * @socket: a #GSocket
1632 * @buffer: the buffer containing the data to send.
1633 * @size: the number of bytes to send
1634 * @error: #GError for error reporting, or %NULL to ignore.
1636 * Tries to send @size bytes from @buffer on the socket. This is mainly used by
1637 * connection oriented sockets, it is identical to g_socket_send_to()
1638 * with @address set to %NULL.
1640 * If the socket is in blocking mode the call will block until there is
1641 * space for the data in the socket queue. If there is no space available
1642 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1643 * will be returned. To be notified of available space, wait for the %G_IO_OUT
1646 * Note that on Windows you can't rely on a %G_IO_OUT condition
1647 * not producing a %G_IO_ERROR_WOULD_BLOCK error, as this is how Winsock
1648 * write notification works. However, robust apps should always be able to
1649 * handle this since it can easily appear in other cases too.
1651 * On error -1 is returned and @error is set accordingly.
1653 * Returns: Number of bytes read, or -1 on error
1658 g_socket_send (GSocket *socket,
1659 const gchar *buffer,
1665 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1667 if (!check_socket (socket, error))
1672 if (socket->priv->blocking &&
1673 !g_socket_condition_wait (socket,
1674 G_IO_OUT, NULL, error))
1677 if ((ret = send (socket->priv->fd, buffer, size, 0)) < 0)
1679 int errsv = get_socket_errno ();
1684 #ifdef WSAEWOULDBLOCK
1685 if (errsv == WSAEWOULDBLOCK)
1686 win32_unset_event_mask (socket, FD_WRITE);
1689 if (socket->priv->blocking)
1691 #ifdef WSAEWOULDBLOCK
1692 if (errsv == WSAEWOULDBLOCK)
1695 if (errsv == EWOULDBLOCK ||
1701 g_set_error (error, G_IO_ERROR,
1702 socket_io_error_from_errno (errsv),
1703 _("Error sending data: %s"), socket_strerror (errsv));
1714 * @socket: a #GSocket
1715 * @address: a #GSocketAddress, or %NULL
1716 * @buffer: the buffer containing the data to send.
1717 * @size: the number of bytes to send
1718 * @error: #GError for error reporting, or %NULL to ignore.
1720 * Tries to send @size bytes from @buffer to @address. If @address is
1721 * %NULL then the message is sent to the default receiver (set by
1722 * g_socket_connect()).
1724 * If the socket is in blocking mode the call will block until there is
1725 * space for the data in the socket queue. If there is no space available
1726 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1727 * will be returned. To be notified of available space, wait for the %G_IO_OUT
1730 * Note that on Windows you can't rely on a %G_IO_OUT condition
1731 * not producing a %G_IO_ERROR_WOULD_BLOCK error, as this is how Winsock
1732 * write notification works. However, robust apps should always be able to
1733 * handle this since it can easily appear in other cases too.
1735 * On error -1 is returned and @error is set accordingly.
1737 * Returns: Number of bytes read, or -1 on error
1742 g_socket_send_to (GSocket *socket,
1743 GSocketAddress *address,
1744 const gchar *buffer,
1753 return g_socket_send_message (socket,
1761 * g_socket_shutdown:
1762 * @socket: a #GSocket
1763 * @shutdown_read: whether to shut down the read side
1764 * @shutdown_write: whether to shut down the write side
1765 * @error: #GError for error reporting, or %NULL to ignore.
1767 * Shut down part of a full-duplex connection.
1769 * If @shutdown_read is %TRUE then the recieving side of the connection
1770 * is shut down, and further reading is disallowed.
1772 * If @shutdown_write is %TRUE then the sending side of the connection
1773 * is shut down, and further writing is disallowed.
1775 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
1777 * One example where this is used is graceful disconnect for TCP connections
1778 * where you close the sending side, then wait for the other side to close
1779 * the connection, thus ensuring that the other side saw all sent data.
1781 * Returns: %TRUE on success, %FALSE on error
1786 g_socket_shutdown (GSocket *socket,
1787 gboolean shutdown_read,
1788 gboolean shutdown_write,
1794 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
1796 if (!check_socket (socket, NULL))
1800 if (!shutdown_read && !shutdown_write)
1804 if (shutdown_read && shutdown_write)
1806 else if (shutdown_read)
1811 if (shutdown_read && shutdown_write)
1813 else if (shutdown_read)
1819 if (shutdown (socket->priv->fd, how) != 0)
1821 int errsv = get_socket_errno ();
1822 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1823 _("Unable to create socket: %s"), socket_strerror (errsv));
1827 if (shutdown_read && shutdown_write)
1828 socket->priv->connected = FALSE;
1835 * @socket: a #GSocket
1836 * @error: #GError for error reporting, or %NULL to ignore.
1838 * Closes the socket, shutting down any active connection.
1840 * Closing a socket does not wait for all outstanding I/O operations to finish,
1841 * so the caller should not rely on them to be guaranteed to complete even
1842 * if the close returns with no error.
1844 * Once the socket is closed, all other operations will return %G_IO_ERROR_CLOSED.
1845 * Closing a stream multiple times will not return an error.
1847 * Sockets will be automatically closed when the last reference
1848 * is dropped, but you might want to call this function to make sure
1849 * resources are released as early as possible.
1851 * Returns: %TRUE on success, %FALSE on error
1856 g_socket_close (GSocket *socket,
1861 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
1863 if (socket->priv->closed)
1864 return TRUE; /* Multiple close not an error */
1866 if (!check_socket (socket, NULL))
1872 res = closesocket (socket->priv->fd);
1874 res = close (socket->priv->fd);
1878 int errsv = get_socket_errno ();
1883 g_set_error (error, G_IO_ERROR,
1884 socket_io_error_from_errno (errsv),
1885 _("Error closing socket: %s"),
1886 socket_strerror (errsv));
1893 if (socket->priv->event != WSA_INVALID_EVENT)
1895 WSACloseEvent (socket->priv->event);
1896 socket->priv->event = WSA_INVALID_EVENT;
1900 socket->priv->connected = FALSE;
1901 socket->priv->closed = TRUE;
1907 * g_socket_is_closed:
1908 * @socket: a #GSocket
1910 * Checks whether a socket is closed.
1912 * Returns: %TRUE if socket is closed, %FALSE otherwise
1917 g_socket_is_closed (GSocket *socket)
1919 return socket->priv->closed;
1923 /* Broken source, used on errors */
1925 broken_prepare (GSource *source,
1932 broken_check (GSource *source)
1938 broken_dispatch (GSource *source,
1939 GSourceFunc callback,
1945 static GSourceFuncs broken_funcs =
1954 network_events_for_condition (GIOCondition condition)
1958 if (condition & G_IO_IN)
1959 event_mask |= (FD_READ | FD_ACCEPT);
1960 if (condition & G_IO_OUT)
1961 event_mask |= (FD_WRITE | FD_CONNECT);
1962 event_mask |= FD_CLOSE;
1968 ensure_event (GSocket *socket)
1970 if (socket->priv->event == WSA_INVALID_EVENT)
1971 socket->priv->event = WSACreateEvent();
1975 update_select_events (GSocket *socket)
1982 ensure_event (socket);
1985 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
1988 event_mask |= network_events_for_condition (*ptr);
1991 if (event_mask != socket->priv->selected_events)
1993 /* If no events selected, disable event so we can unset
1996 if (event_mask == 0)
1999 event = socket->priv->event;
2001 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
2002 socket->priv->selected_events = event_mask;
2007 add_condition_watch (GSocket *socket,
2008 GIOCondition *condition)
2010 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
2012 socket->priv->requested_conditions =
2013 g_list_prepend (socket->priv->requested_conditions, condition);
2015 update_select_events (socket);
2019 remove_condition_watch (GSocket *socket,
2020 GIOCondition *condition)
2022 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
2024 socket->priv->requested_conditions =
2025 g_list_remove (socket->priv->requested_conditions, condition);
2027 update_select_events (socket);
2031 update_condition (GSocket *socket)
2033 WSANETWORKEVENTS events;
2034 GIOCondition condition;
2036 if (WSAEnumNetworkEvents (socket->priv->fd,
2037 socket->priv->event,
2040 socket->priv->current_events |= events.lNetworkEvents;
2041 if (events.lNetworkEvents & FD_WRITE &&
2042 events.iErrorCode[FD_WRITE_BIT] != 0)
2043 socket->priv->current_errors |= FD_WRITE;
2044 if (events.lNetworkEvents & FD_CONNECT &&
2045 events.iErrorCode[FD_CONNECT_BIT] != 0)
2046 socket->priv->current_errors |= FD_CONNECT;
2050 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
2051 condition |= G_IO_IN;
2053 if (socket->priv->current_events & FD_CLOSE ||
2054 socket->priv->closed)
2055 condition |= G_IO_HUP;
2057 /* Never report both G_IO_OUT and HUP, these are
2058 mutually exclusive (can't write to a closed socket) */
2059 if ((condition & G_IO_HUP) == 0 &&
2060 socket->priv->current_events & FD_WRITE)
2062 if (socket->priv->current_errors & FD_WRITE)
2063 condition |= G_IO_ERR;
2065 condition |= G_IO_OUT;
2069 if (socket->priv->current_events & FD_CONNECT)
2071 if (socket->priv->current_errors & FD_CONNECT)
2072 condition |= (G_IO_HUP | G_IO_ERR);
2074 condition |= G_IO_OUT;
2085 GIOCondition condition;
2086 GCancellable *cancellable;
2087 GPollFD cancel_pollfd;
2088 GIOCondition result_condition;
2092 winsock_prepare (GSource *source,
2095 GWinsockSource *winsock_source = (GWinsockSource *)source;
2096 GIOCondition current_condition;
2098 current_condition = update_condition (winsock_source->socket);
2100 if (g_cancellable_is_cancelled (winsock_source->cancellable))
2102 winsock_source->result_condition = current_condition;
2106 if ((winsock_source->condition & current_condition) != 0)
2108 winsock_source->result_condition = current_condition;
2116 winsock_check (GSource *source)
2118 GWinsockSource *winsock_source = (GWinsockSource *)source;
2119 GIOCondition current_condition;
2121 current_condition = update_condition (winsock_source->socket);
2123 if (g_cancellable_is_cancelled (winsock_source->cancellable))
2125 winsock_source->result_condition = current_condition;
2129 if ((winsock_source->condition & current_condition) != 0)
2131 winsock_source->result_condition = current_condition;
2139 winsock_dispatch (GSource *source,
2140 GSourceFunc callback,
2143 GSocketSourceFunc func = (GSocketSourceFunc)callback;
2144 GWinsockSource *winsock_source = (GWinsockSource *)source;
2146 return (*func) (winsock_source->socket,
2147 winsock_source->result_condition & winsock_source->condition,
2152 winsock_finalize (GSource *source)
2154 GWinsockSource *winsock_source = (GWinsockSource *)source;
2157 socket = winsock_source->socket;
2159 remove_condition_watch (socket, &winsock_source->condition);
2160 g_object_unref (socket);
2162 if (winsock_source->cancellable)
2163 g_object_unref (winsock_source->cancellable);
2166 static GSourceFuncs winsock_funcs =
2175 winsock_source_new (GSocket *socket,
2176 GIOCondition condition,
2177 GCancellable *cancellable)
2180 GWinsockSource *winsock_source;
2182 ensure_event (socket);
2184 if (socket->priv->event == WSA_INVALID_EVENT)
2186 g_warning ("Failed to create WSAEvent");
2187 return g_source_new (&broken_funcs, sizeof (GSource));
2190 condition |= G_IO_HUP | G_IO_ERR;
2192 source = g_source_new (&winsock_funcs, sizeof (GWinsockSource));
2193 winsock_source = (GWinsockSource *)source;
2195 winsock_source->socket = g_object_ref (socket);
2196 winsock_source->condition = condition;
2197 add_condition_watch (socket, &winsock_source->condition);
2201 winsock_source->cancellable = g_object_ref (cancellable);
2202 g_cancellable_make_pollfd (cancellable,
2203 &winsock_source->cancel_pollfd);
2204 g_source_add_poll (source, &winsock_source->cancel_pollfd);
2207 winsock_source->pollfd.fd = (gintptr) socket->priv->event;
2208 winsock_source->pollfd.events = condition;
2209 g_source_add_poll (source, &winsock_source->pollfd);
2216 * g_socket_create_source:
2217 * @socket: a #GSocket
2218 * @condition: a #GIOCondition mask to monitor
2219 * @cancellable: a %GCancellable or %NULL
2221 * Creates a %GSource that can be attached to a %GMainContext to monitor
2222 * for the availibility of the specified @condition on the socket.
2224 * The callback on the source is of the #GSocketSourceFunc type.
2226 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2227 * these conditions will always be reported output if they are true.
2229 * @cancellable if not %NULL can be used to cancel the source, which will
2230 * cause the source to trigger, reporting the current condition (which
2231 * is likely 0 unless cancellation happened at the same time as a
2232 * condition change). You can check for this in the callback using
2233 * g_cancellable_is_cancelled().
2235 * Returns: a newly allocated %GSource, free with g_source_unref().
2240 g_socket_create_source (GSocket *socket,
2241 GIOCondition condition,
2242 GCancellable *cancellable)
2245 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
2248 source = winsock_source_new (socket, condition, cancellable);
2250 source =_g_fd_source_new_with_object (G_OBJECT (socket), socket->priv->fd,
2251 condition, cancellable);
2257 * g_socket_condition_check:
2258 * @socket: a #GSocket
2259 * @condition: a #GIOCondition mask to check
2261 * Checks on the readiness of @socket to perform operations. The
2262 * operations specified in @condition are checked for and masked
2263 * against the currently-satisfied conditions on @socket. The result
2266 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2267 * these conditions will always be set in the output if they are true.
2269 * This call never blocks.
2271 * Returns: the @GIOCondition mask of the current state
2276 g_socket_condition_check (GSocket *socket,
2277 GIOCondition condition)
2279 if (!check_socket (socket, NULL))
2284 GIOCondition current_condition;
2286 condition |= G_IO_ERR | G_IO_HUP;
2288 add_condition_watch (socket, &condition);
2289 current_condition = update_condition (socket);
2290 remove_condition_watch (socket, &condition);
2291 return condition & current_condition;
2297 poll_fd.fd = socket->priv->fd;
2298 poll_fd.events = condition;
2301 result = g_poll (&poll_fd, 1, 0);
2302 while (result == -1 && get_socket_errno () == EINTR);
2304 return poll_fd.revents;
2310 * g_socket_condition_wait:
2311 * @socket: a #GSocket
2312 * @condition: a #GIOCondition mask to wait for
2313 * @cancellable: a #GCancellable, or %NULL
2314 * @error: a #GError pointer, or %NULL
2316 * Waits for @condition to become true on @socket. When the condition
2317 * becomes true, %TRUE is returned.
2319 * If @cancellable is cancelled before the condition becomes true then
2320 * %FALSE is returned and @error, if non-%NULL, is set to %G_IO_ERROR_CANCELLED.
2322 * Returns: %TRUE if the condition was met, %FALSE otherwise
2327 g_socket_condition_wait (GSocket *socket,
2328 GIOCondition condition,
2329 GCancellable *cancellable,
2332 if (!check_socket (socket, error))
2335 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2340 GIOCondition current_condition;
2346 /* Always check these */
2347 condition |= G_IO_ERR | G_IO_HUP;
2349 add_condition_watch (socket, &condition);
2352 events[num_events++] = socket->priv->event;
2356 g_cancellable_make_pollfd (cancellable, &cancel_fd);
2357 events[num_events++] = (WSAEVENT)cancel_fd.fd;
2360 current_condition = update_condition (socket);
2361 while ((condition & current_condition) == 0)
2363 res = WSAWaitForMultipleEvents(num_events, events,
2364 FALSE, WSA_INFINITE, FALSE);
2365 if (res == WSA_WAIT_FAILED)
2367 int errsv = get_socket_errno ();
2369 g_set_error (error, G_IO_ERROR,
2370 socket_io_error_from_errno (errsv),
2371 _("Waiting for socket condition: %s"),
2372 socket_strerror (errsv));
2376 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2379 current_condition = update_condition (socket);
2381 remove_condition_watch (socket, &condition);
2383 return (condition & current_condition) != 0;
2391 poll_fd[0].fd = socket->priv->fd;
2392 poll_fd[0].events = condition;
2397 g_cancellable_make_pollfd (cancellable, &poll_fd[1]);
2402 result = g_poll (poll_fd, num, -1);
2403 while (result == -1 && get_socket_errno () == EINTR);
2405 return cancellable == NULL ||
2406 !g_cancellable_set_error_if_cancelled (cancellable, error);
2412 * g_socket_send_message:
2413 * @socket: a #GSocket
2414 * @address: a #GSocketAddress, or %NULL
2415 * @vectors: an array of #GOutputVector structs
2416 * @num_vectors: the number of elements in @vectors, or -1
2417 * @messages: a pointer to an array of #GSocketControlMessages, or
2419 * @num_messages: number of elements in @messages, or -1.
2420 * @flags: an int containing #GSocketMsgFlags flags
2421 * @error: #GError for error reporting, or %NULL to ignore.
2423 * Send data to @address on @socket. This is the most complicated and
2424 * fully-featured version of this call. For easier use, see
2425 * g_socket_send() and g_socket_send_to().
2427 * If @address is %NULL then the message is sent to the default receiver
2428 * (set by g_socket_connect()).
2430 * @vector must point to an array of #GOutputVector structs and
2431 * @num_vectors must be the length of this array. These structs
2432 * describe the buffers that the sent data will be gathered from.
2433 * If @num_vector is -1, then @vector is assumed to be terminated
2434 * by a #GOutputVector with a %NULL buffer pointer.
2437 * @messages, if non-%NULL, is taken to point to an array of @num_messages
2438 * #GSocketControlMessage instances. These correspond to the control
2439 * messages to be sent on the socket.
2440 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
2443 * @flags modify how the message sent. The commonly available arguments
2444 * for this is available in the #GSocketMsgFlags enum, but the
2445 * values there are the same as the system values, and the flags
2446 * are passed in as-is, so you can pass in system specific flags too.
2448 * If the socket is in blocking mode the call will block until there is
2449 * space for the data in the socket queue. If there is no space available
2450 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2451 * will be returned. To be notified of available space, wait for the %G_IO_OUT
2454 * Note that on Windows you can't rely on a %G_IO_OUT condition
2455 * not producing a %G_IO_ERROR_WOULD_BLOCK error, as this is how Winsock
2456 * write notification works. However, robust apps should always be able to
2457 * handle this since it can easily appear in other cases too.
2459 * On error -1 is returned and @error is set accordingly.
2461 * Returns: Number of bytes read, or -1 on error
2466 g_socket_send_message (GSocket *socket,
2467 GSocketAddress *address,
2468 GOutputVector *vectors,
2470 GSocketControlMessage **messages,
2475 GOutputVector one_vector;
2478 if (!check_socket (socket, error))
2481 if (num_vectors == -1)
2483 for (num_vectors = 0;
2484 vectors[num_vectors].buffer != NULL;
2489 if (num_messages == -1)
2491 for (num_messages = 0;
2492 messages != NULL && messages[num_messages] != NULL;
2497 if (num_vectors == 0)
2501 one_vector.buffer = &zero;
2502 one_vector.size = 1;
2504 vectors = &one_vector;
2515 msg.msg_namelen = g_socket_address_get_native_size (address);
2516 msg.msg_name = g_alloca (msg.msg_namelen);
2517 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
2523 /* this entire expression will be evaluated at compile time */
2524 if (sizeof *msg.msg_iov == sizeof *vectors &&
2525 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2526 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2527 G_STRUCT_OFFSET (GOutputVector, buffer) &&
2528 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2529 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2530 G_STRUCT_OFFSET (GOutputVector, size))
2531 /* ABI is compatible */
2533 msg.msg_iov = (struct iovec *) vectors;
2534 msg.msg_iovlen = num_vectors;
2537 /* ABI is incompatible */
2541 msg.msg_iov = g_newa (struct iovec, num_vectors);
2542 for (i = 0; i < num_vectors; i++)
2544 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
2545 msg.msg_iov[i].iov_len = vectors[i].size;
2547 msg.msg_iovlen = num_vectors;
2553 struct cmsghdr *cmsg;
2556 msg.msg_controllen = 0;
2557 for (i = 0; i < num_messages; i++)
2558 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
2560 msg.msg_control = g_alloca (msg.msg_controllen);
2562 cmsg = CMSG_FIRSTHDR (&msg);
2563 for (i = 0; i < num_messages; i++)
2565 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
2566 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
2567 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
2568 g_socket_control_message_serialize (messages[i],
2570 cmsg = CMSG_NXTHDR (&msg, cmsg);
2572 g_assert (cmsg == NULL);
2577 if (socket->priv->blocking &&
2578 !g_socket_condition_wait (socket,
2579 G_IO_OUT, NULL, error))
2582 result = sendmsg (socket->priv->fd, &msg, flags);
2585 int errsv = get_socket_errno ();
2590 if (socket->priv->blocking &&
2591 (errsv == EWOULDBLOCK ||
2595 g_set_error (error, G_IO_ERROR,
2596 socket_io_error_from_errno (errsv),
2597 _("Error sending message: %s"), socket_strerror (errsv));
2608 struct sockaddr_storage addr;
2615 /* Win32 doesn't support control messages.
2616 Actually this is possible for raw and datagram sockets
2617 via WSASendMessage on Vista or later, but that doesn't
2619 if (num_messages != 0)
2621 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2622 _("GSocketControlMessage not supported on windows"));
2627 bufs = g_newa (WSABUF, num_vectors);
2628 for (i = 0; i < num_vectors; i++)
2630 bufs[i].buf = (char *)vectors[i].buffer;
2631 bufs[i].len = (gulong)vectors[i].size;
2637 addrlen = g_socket_address_get_native_size (address);
2638 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
2644 if (socket->priv->blocking &&
2645 !g_socket_condition_wait (socket,
2646 G_IO_OUT, NULL, error))
2650 result = WSASendTo (socket->priv->fd,
2653 (const struct sockaddr *)&addr, addrlen,
2656 result = WSASend (socket->priv->fd,
2663 int errsv = get_socket_errno ();
2665 if (errsv == WSAEINTR)
2668 if (errsv == WSAEWOULDBLOCK)
2669 win32_unset_event_mask (socket, FD_WRITE);
2671 if (socket->priv->blocking &&
2672 errsv == WSAEWOULDBLOCK)
2675 g_set_error (error, G_IO_ERROR,
2676 socket_io_error_from_errno (errsv),
2677 _("Error sending message: %s"), socket_strerror (errsv));
2690 * g_socket_receive_message:
2691 * @socket: a #GSocket
2692 * @address: a pointer to a #GSocketAddress pointer, or %NULL
2693 * @vectors: an array of #GInputVector structs
2694 * @num_vectors: the number of elements in @vectors, or -1
2695 * @messages: a pointer which will be filled with an array of
2696 * #GSocketControlMessages, or %NULL
2697 * @num_messages: a pointer which will be filled with the number of
2698 * elements in @messages, or %NULL
2699 * @flags: a pointer to an int containing #GSocketMsgFlags flags
2700 * @error: a #GError pointer, or %NULL
2702 * Receive data from a socket. This is the most complicated and
2703 * fully-featured version of this call. For easier use, see
2704 * g_socket_receive() and g_socket_receive_from().
2706 * If @address is non-%NULL then @address will be set equal to the
2707 * source address of the received packet.
2708 * @address is owned by the caller.
2710 * @vector must point to an array of #GInputVector structs and
2711 * @num_vectors must be the length of this array. These structs
2712 * describe the buffers that received data will be scattered into.
2713 * If @num_vector is -1, then @vector is assumed to be terminated
2714 * by a #GInputVector with a %NULL buffer pointer.
2716 * As a special case, if the size of the array is zero (in which case,
2717 * @vectors may of course be %NULL), then a single byte is received
2718 * and discarded. This is to facilitate the common practice of
2719 * sending a single '\0' byte for the purposes of transferring
2722 * @messages, if non-%NULL, is taken to point to a pointer that will
2723 * be set to point to a newly-allocated array of
2724 * #GSocketControlMessage instances. These correspond to the control
2725 * messages received from the kernel, one #GSocketControlMessage per
2726 * message from the kernel. This array is %NULL-terminated and must be
2727 * freed by the caller using g_free().
2729 * @num_messages, if non-%NULL, will be set to the number of control
2730 * messages received.
2732 * If both @messages and @num_messages are non-%NULL, then
2733 * @num_messages gives the number of #GSocketControlMessage instances
2734 * in @messages (ie: not including the %NULL terminator).
2736 * @flags is an in/out parameter. The commonly available arguments
2737 * for this is available in the #GSocketMsgFlags enum, but the
2738 * values there are the same as the system values, and the flags
2739 * are passed in as-is, so you can pass in system specific flags too.
2741 * If the socket is in blocking mode the call will block until there is
2742 * some data to receive or there is an error. If there is no data available
2743 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2744 * will be returned. To be notified of available data, wait for the %G_IO_IN
2747 * On error -1 is returned and @error is set accordingly.
2749 * Returns: Number of bytes read, or -1 on error
2754 g_socket_receive_message (GSocket *socket,
2755 GSocketAddress **address,
2756 GInputVector *vectors,
2758 GSocketControlMessage ***messages,
2763 GInputVector one_vector;
2766 if (!check_socket (socket, error))
2769 if (num_vectors == -1)
2771 for (num_vectors = 0;
2772 vectors[num_vectors].buffer != NULL;
2777 if (num_vectors == 0)
2779 one_vector.buffer = &one_byte;
2780 one_vector.size = 1;
2782 vectors = &one_vector;
2789 struct sockaddr_storage one_sockaddr;
2794 msg.msg_name = &one_sockaddr;
2795 msg.msg_namelen = sizeof (struct sockaddr_storage);
2799 msg.msg_name = NULL;
2800 msg.msg_namelen = 0;
2804 /* this entire expression will be evaluated at compile time */
2805 if (sizeof *msg.msg_iov == sizeof *vectors &&
2806 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2807 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2808 G_STRUCT_OFFSET (GInputVector, buffer) &&
2809 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2810 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2811 G_STRUCT_OFFSET (GInputVector, size))
2812 /* ABI is compatible */
2814 msg.msg_iov = (struct iovec *) vectors;
2815 msg.msg_iovlen = num_vectors;
2818 /* ABI is incompatible */
2822 msg.msg_iov = g_newa (struct iovec, num_vectors);
2823 for (i = 0; i < num_vectors; i++)
2825 msg.msg_iov[i].iov_base = vectors[i].buffer;
2826 msg.msg_iov[i].iov_len = vectors[i].size;
2828 msg.msg_iovlen = num_vectors;
2832 msg.msg_control = g_alloca (2048);
2833 msg.msg_controllen = 2048;
2837 msg.msg_flags = *flags;
2844 if (socket->priv->blocking &&
2845 !g_socket_condition_wait (socket,
2846 G_IO_IN, NULL, error))
2849 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
2853 int errsv = get_socket_errno ();
2858 if (socket->priv->blocking &&
2859 (errsv == EWOULDBLOCK ||
2863 g_set_error (error, G_IO_ERROR,
2864 socket_io_error_from_errno (errsv),
2865 _("Error receiving message: %s"), socket_strerror (errsv));
2872 /* decode address */
2873 if (address != NULL)
2875 if (msg.msg_namelen > 0)
2876 *address = g_socket_address_new_from_native (msg.msg_name,
2882 /* decode control messages */
2884 GSocketControlMessage **my_messages = NULL;
2885 gint allocated = 0, index = 0;
2886 const gchar *scm_pointer;
2887 struct cmsghdr *cmsg;
2890 scm_pointer = (const gchar *) msg.msg_control;
2891 scm_size = msg.msg_controllen;
2893 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
2895 GSocketControlMessage *message;
2897 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
2899 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
2901 if (message == NULL)
2902 /* We've already spewed about the problem in the
2903 deserialization code, so just continue */
2906 if (index == allocated)
2908 /* estimated 99% case: exactly 1 control message */
2909 allocated = MIN (allocated * 2, 1);
2910 my_messages = g_new (GSocketControlMessage *, (allocated + 1));
2914 my_messages[index++] = message;
2918 *num_messages = index;
2922 my_messages[index++] = NULL;
2923 *messages = my_messages;
2929 /* free all those messages we just constructed.
2930 * we have to do it this way if the user ignores the
2931 * messages so that we will close any received fds.
2933 for (i = 0; i < index; i++)
2934 g_object_unref (my_messages[i]);
2935 g_free (my_messages);
2939 /* capture the flags */
2941 *flags = msg.msg_flags;
2947 struct sockaddr_storage addr;
2949 DWORD bytes_received;
2956 bufs = g_newa (WSABUF, num_vectors);
2957 for (i = 0; i < num_vectors; i++)
2959 bufs[i].buf = (char *)vectors[i].buffer;
2960 bufs[i].len = (gulong)vectors[i].size;
2972 if (socket->priv->blocking &&
2973 !g_socket_condition_wait (socket,
2974 G_IO_IN, NULL, error))
2977 addrlen = sizeof addr;
2979 result = WSARecvFrom (socket->priv->fd,
2981 &bytes_received, &win_flags,
2982 (struct sockaddr *)&addr, &addrlen,
2985 result = WSARecv (socket->priv->fd,
2987 &bytes_received, &win_flags,
2991 int errsv = get_socket_errno ();
2993 if (errsv == WSAEINTR)
2996 win32_unset_event_mask (socket, FD_READ);
2998 if (socket->priv->blocking &&
2999 errsv == WSAEWOULDBLOCK)
3002 g_set_error (error, G_IO_ERROR,
3003 socket_io_error_from_errno (errsv),
3004 _("Error receiving message: %s"), socket_strerror (errsv));
3008 win32_unset_event_mask (socket, FD_READ);
3012 /* decode address */
3013 if (address != NULL)
3016 *address = g_socket_address_new_from_native (&addr, addrlen);
3021 /* capture the flags */
3025 return bytes_received;
3030 #define __G_SOCKET_C__
3031 #include "gioaliasdef.c"