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>
37 # include <netinet/in.h>
38 # include <arpa/inet.h>
42 # include <sys/types.h>
44 # include <winsock2.h>
49 #include "gcancellable.h"
50 #include "gioenumtypes.h"
51 #include "ginitable.h"
52 #include "gasynchelper.h"
62 * @short_description: Low-level socket object
64 * @see_also: #GInitable
66 * A #GSocket is a low-level networking primitive. It is a more or less
67 * direct mapping of the BSD socket API in a portable GObject based API.
68 * It supports both the unix socket implementations and winsock2 on Windows.
70 * #GSocket is the platform independent base upon which the higher level
71 * network primitives are based. Applications are not typically meant to
72 * use it directly, but rather through classes like #GSocketClient,
73 * #GSocketService and #GSocketConnection. However there may be cases where
74 * direct use of #GSocket is useful.
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.
107 * Note that creating a #GSocket causes the signal %SIGPIPE to be
108 * ignored for the remainder of the program. If you are writing a
109 * command-line utility that uses #GSocket, you may need to take into
110 * account the fact that your program will not automatically be killed
111 * if it tries to write to %stdout after it has been closed.
116 static void g_socket_initable_iface_init (GInitableIface *iface);
117 static gboolean g_socket_initable_init (GInitable *initable,
118 GCancellable *cancellable,
121 G_DEFINE_TYPE_WITH_CODE (GSocket, g_socket, G_TYPE_OBJECT,
122 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
123 g_socket_initable_iface_init));
139 struct _GSocketPrivate
141 GSocketFamily family;
143 GSocketProtocol protocol;
146 GError *construct_error;
158 GList *requested_conditions; /* list of requested GIOCondition * */
163 get_socket_errno (void)
168 return WSAGetLastError ();
173 socket_io_error_from_errno (int err)
176 return g_io_error_from_errno (err);
181 return G_IO_ERROR_ADDRESS_IN_USE;
183 return G_IO_ERROR_WOULD_BLOCK;
185 return G_IO_ERROR_PERMISSION_DENIED;
186 case WSA_INVALID_HANDLE:
187 case WSA_INVALID_PARAMETER:
190 return G_IO_ERROR_INVALID_ARGUMENT;
191 case WSAEPROTONOSUPPORT:
192 return G_IO_ERROR_NOT_SUPPORTED;
194 return G_IO_ERROR_CANCELLED;
195 case WSAESOCKTNOSUPPORT:
197 case WSAEPFNOSUPPORT:
198 case WSAEAFNOSUPPORT:
199 return G_IO_ERROR_NOT_SUPPORTED;
201 return G_IO_ERROR_FAILED;
207 socket_strerror (int err)
210 return g_strerror (err);
212 static GStaticPrivate msg_private = G_STATIC_PRIVATE_INIT;
215 buf = g_static_private_get (&msg_private);
218 buf = g_new (gchar, 128);
219 g_static_private_set (&msg_private, buf, g_free);
222 msg = g_win32_error_message (err);
223 strncpy (buf, msg, 128);
230 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
232 _win32_unset_event_mask (GSocket *socket, int mask)
234 socket->priv->current_events &= ~mask;
235 socket->priv->current_errors &= ~mask;
238 #define win32_unset_event_mask(_socket, _mask)
242 set_fd_nonblocking (int fd)
251 if ((arg = fcntl (fd, F_GETFL, NULL)) < 0)
253 g_warning ("Error getting socket status flags: %s", socket_strerror (errno));
257 arg = arg | O_NONBLOCK;
259 if (fcntl (fd, F_SETFL, arg) < 0)
260 g_warning ("Error setting socket status flags: %s", socket_strerror (errno));
264 if (ioctlsocket (fd, FIONBIO, &arg) == SOCKET_ERROR)
266 int errsv = get_socket_errno ();
267 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
273 check_socket (GSocket *socket,
276 if (!socket->priv->inited)
278 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
279 _("Invalid socket, not initialized"));
283 if (socket->priv->construct_error)
285 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
286 _("Invalid socket, initialization failed due to: %s"),
287 socket->priv->construct_error->message);
291 if (socket->priv->closed)
293 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
294 _("Socket is already closed"));
301 g_socket_details_from_fd (GSocket *socket)
303 struct sockaddr_storage address;
315 fd = socket->priv->fd;
316 optlen = sizeof value;
317 if (getsockopt (fd, SOL_SOCKET, SO_TYPE, (void *)&value, &optlen) != 0)
319 errsv = get_socket_errno ();
330 /* programmer error */
331 g_error ("creating GSocket from fd %d: %s\n",
332 fd, socket_strerror (errsv));
340 g_assert (optlen == sizeof value);
344 socket->priv->type = G_SOCKET_TYPE_STREAM;
348 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
352 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
356 socket->priv->type = G_SOCKET_TYPE_INVALID;
360 addrlen = sizeof address;
361 if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
363 errsv = get_socket_errno ();
367 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
368 sizeof address.ss_family <= addrlen);
369 switch (address.ss_family)
371 case G_SOCKET_FAMILY_IPV4:
372 case G_SOCKET_FAMILY_IPV6:
373 case G_SOCKET_FAMILY_UNIX:
374 socket->priv->family = address.ss_family;
378 socket->priv->family = G_SOCKET_FAMILY_INVALID;
382 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
384 addrlen = sizeof address;
385 if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
386 socket->priv->connected = TRUE;
389 optlen = sizeof bool_val;
390 if (getsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
391 (void *)&bool_val, &optlen) == 0)
393 g_assert (optlen == sizeof bool_val);
394 socket->priv->keepalive = !!bool_val;
398 /* Can't read, maybe not supported, assume FALSE */
399 socket->priv->keepalive = FALSE;
405 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
406 socket_io_error_from_errno (errsv),
407 _("creating GSocket from fd: %s"),
408 socket_strerror (errsv));
412 g_socket_create_socket (GSocketFamily family,
422 case G_SOCKET_TYPE_STREAM:
423 native_type = SOCK_STREAM;
426 case G_SOCKET_TYPE_DATAGRAM:
427 native_type = SOCK_DGRAM;
430 case G_SOCKET_TYPE_SEQPACKET:
431 native_type = SOCK_SEQPACKET;
435 g_assert_not_reached ();
440 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
441 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
446 native_type |= SOCK_CLOEXEC;
448 fd = socket (family, native_type, protocol);
452 int errsv = get_socket_errno ();
454 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
455 _("Unable to create socket: %s"), socket_strerror (errsv));
462 /* We always want to set close-on-exec to protect users. If you
463 need to so some weird inheritance to exec you can re-enable this
464 using lower level hacks with g_socket_get_fd(). */
465 flags = fcntl (fd, F_GETFD, 0);
467 (flags & FD_CLOEXEC) == 0)
470 fcntl (fd, F_SETFD, flags);
479 g_socket_constructed (GObject *object)
481 GSocket *socket = G_SOCKET (object);
483 if (socket->priv->fd >= 0)
484 /* create socket->priv info from the fd */
485 g_socket_details_from_fd (socket);
488 /* create the fd from socket->priv info */
489 socket->priv->fd = g_socket_create_socket (socket->priv->family,
491 socket->priv->protocol,
492 &socket->priv->construct_error);
494 /* Always use native nonblocking sockets, as
495 windows sets sockets to nonblocking automatically
496 in certain operations. This way we make things work
497 the same on all platforms */
498 if (socket->priv->fd != -1)
499 set_fd_nonblocking (socket->priv->fd);
503 g_socket_get_property (GObject *object,
508 GSocket *socket = G_SOCKET (object);
509 GSocketAddress *address;
514 g_value_set_enum (value, socket->priv->family);
518 g_value_set_enum (value, socket->priv->type);
522 g_value_set_enum (value, socket->priv->protocol);
526 g_value_set_int (value, socket->priv->fd);
530 g_value_set_boolean (value, socket->priv->blocking);
533 case PROP_LISTEN_BACKLOG:
534 g_value_set_int (value, socket->priv->listen_backlog);
538 g_value_set_boolean (value, socket->priv->keepalive);
541 case PROP_LOCAL_ADDRESS:
542 address = g_socket_get_local_address (socket, NULL);
543 g_value_take_object (value, address);
546 case PROP_REMOTE_ADDRESS:
547 address = g_socket_get_remote_address (socket, NULL);
548 g_value_take_object (value, address);
552 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
557 g_socket_set_property (GObject *object,
562 GSocket *socket = G_SOCKET (object);
567 socket->priv->family = g_value_get_enum (value);
571 socket->priv->type = g_value_get_enum (value);
575 socket->priv->protocol = g_value_get_enum (value);
579 socket->priv->fd = g_value_get_int (value);
583 g_socket_set_blocking (socket, g_value_get_boolean (value));
586 case PROP_LISTEN_BACKLOG:
587 g_socket_set_listen_backlog (socket, g_value_get_int (value));
591 g_socket_set_keepalive (socket, g_value_get_boolean (value));
595 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
600 g_socket_finalize (GObject *object)
602 GSocket *socket = G_SOCKET (object);
604 g_clear_error (&socket->priv->construct_error);
606 if (socket->priv->fd != -1 &&
607 !socket->priv->closed)
608 g_socket_close (socket, NULL);
611 g_assert (socket->priv->requested_conditions == NULL);
614 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
615 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
619 g_socket_class_init (GSocketClass *klass)
621 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
624 /* Make sure winsock has been initialized */
625 type = g_inet_address_get_type ();
628 /* There is no portable, thread-safe way to avoid having the process
629 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
630 * forced to simply ignore the signal process-wide.
632 signal (SIGPIPE, SIG_IGN);
635 g_type_class_add_private (klass, sizeof (GSocketPrivate));
637 gobject_class->finalize = g_socket_finalize;
638 gobject_class->constructed = g_socket_constructed;
639 gobject_class->set_property = g_socket_set_property;
640 gobject_class->get_property = g_socket_get_property;
642 g_object_class_install_property (gobject_class, PROP_FAMILY,
643 g_param_spec_enum ("family",
645 P_("The sockets address family"),
646 G_TYPE_SOCKET_FAMILY,
647 G_SOCKET_FAMILY_INVALID,
648 G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
650 g_object_class_install_property (gobject_class, PROP_TYPE,
651 g_param_spec_enum ("type",
653 P_("The sockets type"),
655 G_SOCKET_TYPE_STREAM,
656 G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
658 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
659 g_param_spec_enum ("protocol",
660 P_("Socket protocol"),
661 P_("The id of the protocol to use, or -1 for unknown"),
662 G_TYPE_SOCKET_PROTOCOL,
663 G_SOCKET_PROTOCOL_UNKNOWN,
664 G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
666 g_object_class_install_property (gobject_class, PROP_FD,
667 g_param_spec_int ("fd",
668 P_("File descriptor"),
669 P_("The sockets file descriptor"),
673 G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
675 g_object_class_install_property (gobject_class, PROP_BLOCKING,
676 g_param_spec_boolean ("blocking",
678 P_("Whether or not I/O on this socket is blocking"),
680 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
682 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
683 g_param_spec_int ("listen-backlog",
684 P_("Listen backlog"),
685 P_("outstanding connections in the listen queue"),
689 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
691 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
692 g_param_spec_boolean ("keepalive",
693 P_("Keep connection alive"),
694 P_("Keep connection alive by sending periodic pings"),
696 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
698 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
699 g_param_spec_object ("local-address",
701 P_("The local address the socket is bound to"),
702 G_TYPE_SOCKET_ADDRESS,
703 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
705 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
706 g_param_spec_object ("remote-address",
707 P_("Remote address"),
708 P_("The remote address the socket is connected to"),
709 G_TYPE_SOCKET_ADDRESS,
710 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
714 g_socket_initable_iface_init (GInitableIface *iface)
716 iface->init = g_socket_initable_init;
720 g_socket_init (GSocket *socket)
722 socket->priv = G_TYPE_INSTANCE_GET_PRIVATE (socket, G_TYPE_SOCKET, GSocketPrivate);
724 socket->priv->fd = -1;
725 socket->priv->blocking = TRUE;
726 socket->priv->listen_backlog = 10;
727 socket->priv->construct_error = NULL;
729 socket->priv->event = WSA_INVALID_EVENT;
734 g_socket_initable_init (GInitable *initable,
735 GCancellable *cancellable,
740 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
742 socket = G_SOCKET (initable);
744 if (cancellable != NULL)
746 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
747 _("Cancellable initialization not supported"));
751 socket->priv->inited = TRUE;
753 if (socket->priv->construct_error)
756 *error = g_error_copy (socket->priv->construct_error);
766 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
767 * @type: the socket type to use.
768 * @protocol: the id of the protocol to use, or 0 for default.
769 * @error: #GError for error reporting, or %NULL to ignore.
771 * Creates a new #GSocket with the defined family, type and protocol.
772 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
773 * for the family and type is used.
775 * The @protocol is a family and type specific int that specifies what
776 * kind of protocol to use. #GSocketProtocol lists several common ones.
777 * Many families only support one protocol, and use 0 for this, others
778 * support several and using 0 means to use the default protocol for
779 * the family and type.
781 * The protocol id is passed directly to the operating
782 * system, so you can use protocols not listed in #GSocketProtocol if you
783 * know the protocol number used for it.
785 * Returns: a #GSocket or %NULL on error.
786 * Free the returned object with g_object_unref().
791 g_socket_new (GSocketFamily family,
793 GSocketProtocol protocol,
796 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
800 "protocol", protocol,
805 * g_socket_new_from_fd:
806 * @fd: a native socket file descriptor.
807 * @error: #GError for error reporting, or %NULL to ignore.
809 * Creates a new #GSocket from a native file descriptor
810 * or winsock SOCKET handle.
812 * This reads all the settings from the file descriptor so that
813 * all properties should work. Note that the file descriptor
814 * will be set to non-blocking mode, independent on the blocking
815 * mode of the #GSocket.
817 * Returns: a #GSocket or %NULL on error.
818 * Free the returned object with g_object_unref().
823 g_socket_new_from_fd (gint fd,
826 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
833 * g_socket_set_blocking:
834 * @socket: a #GSocket.
835 * @blocking: Whether to use blocking I/O or not.
837 * Sets the blocking mode of the socket. In blocking mode
838 * all operations block until they succeed or there is an error. In
839 * non-blocking mode all functions return results immediately or
840 * with a %G_IO_ERROR_WOULD_BLOCK error.
842 * All sockets are created in blocking mode. However, note that the
843 * platform level socket is always non-blocking, and blocking mode
844 * is a GSocket level feature.
849 g_socket_set_blocking (GSocket *socket,
852 g_return_if_fail (G_IS_SOCKET (socket));
854 blocking = !!blocking;
856 if (socket->priv->blocking == blocking)
859 socket->priv->blocking = blocking;
860 g_object_notify (G_OBJECT (socket), "blocking");
864 * g_socket_get_blocking:
865 * @socket: a #GSocket.
867 * Gets the blocking mode of the socket. For details on blocking I/O,
868 * see g_socket_set_blocking().
870 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
875 g_socket_get_blocking (GSocket *socket)
877 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
879 return socket->priv->blocking;
883 * g_socket_set_keepalive:
884 * @socket: a #GSocket.
885 * @keepalive: Whether to use try to keep the connection alive or not.
887 * Setting @keepalive to %TRUE enables the sending of periodic ping requests
888 * on idle connections in order to keep the connection alive. This is only
889 * useful for connection oriented sockets. The exact period used between
890 * each ping is system and protocol dependent.
892 * Sending keepalive requests like this has a few disadvantages. For instance,
893 * it uses more network bandwidth, and it makes your application more sensitive
894 * to temporary outages in the network (i.e. if a cable is pulled your otherwise
895 * idle connection could be terminated, whereas otherwise it would survive unless
896 * actually used before the cable was reinserted). However, it is sometimes
897 * useful to ensure that connections are eventually terminated if e.g. the
898 * remote side is disconnected, so as to avoid leaking resources forever.
903 g_socket_set_keepalive (GSocket *socket,
908 g_return_if_fail (G_IS_SOCKET (socket));
910 keepalive = !!keepalive;
911 if (socket->priv->keepalive == keepalive)
914 value = (gint) keepalive;
915 if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_KEEPALIVE,
916 (gpointer) &value, sizeof (value)) < 0)
918 int errsv = get_socket_errno ();
919 g_warning ("error setting keepalive: %s", socket_strerror (errsv));
923 socket->priv->keepalive = keepalive;
924 g_object_notify (G_OBJECT (socket), "keepalive");
928 * g_socket_get_keepalive:
929 * @socket: a #GSocket.
931 * Gets the keepalive mode of the socket. For details on this,
932 * see g_socket_set_keepalive().
934 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
939 g_socket_get_keepalive (GSocket *socket)
941 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
943 return socket->priv->keepalive;
947 * g_socket_get_listen_backlog:
948 * @socket: a #GSocket.
950 * Gets the listen backlog setting of the socket. For details on this,
951 * see g_socket_set_listen_backlog().
953 * Returns: the maximum number of pending connections.
958 g_socket_get_listen_backlog (GSocket *socket)
960 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
962 return socket->priv->listen_backlog;
966 * g_socket_set_listen_backlog:
967 * @socket: a #GSocket.
968 * @backlog: the maximum number of pending connections.
970 * Sets the maximum number of outstanding connections allowed
971 * when listening on this socket. If more clients than this are
972 * connecting to the socket and the application is not handling them
973 * on time then the new connections will be refused.
975 * Note that this must be called before g_socket_listen() and has no
976 * effect if called after that.
981 g_socket_set_listen_backlog (GSocket *socket,
984 g_return_if_fail (G_IS_SOCKET (socket));
985 g_return_if_fail (!socket->priv->listening);
987 if (backlog != socket->priv->listen_backlog)
989 socket->priv->listen_backlog = backlog;
990 g_object_notify (G_OBJECT (socket), "listen-backlog");
995 * g_socket_get_family:
996 * @socket: a #GSocket.
998 * Gets the socket family of the socket.
1000 * Returns: a #GSocketFamily
1005 g_socket_get_family (GSocket *socket)
1007 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1009 return socket->priv->family;
1013 * g_socket_get_socket_type:
1014 * @socket: a #GSocket.
1016 * Gets the socket type of the socket.
1018 * Returns: a #GSocketType
1023 g_socket_get_socket_type (GSocket *socket)
1025 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1027 return socket->priv->type;
1031 * g_socket_get_protocol:
1032 * @socket: a #GSocket.
1034 * Gets the socket protocol id the socket was created with.
1035 * In case the protocol is unknown, -1 is returned.
1037 * Returns: a protocol id, or -1 if unknown
1042 g_socket_get_protocol (GSocket *socket)
1044 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1046 return socket->priv->protocol;
1051 * @socket: a #GSocket.
1053 * Returns the underlying OS socket object. On unix this
1054 * is a socket file descriptor, and on windows this is
1055 * a Winsock2 SOCKET handle. This may be useful for
1056 * doing platform specific or otherwise unusual operations
1059 * Returns: the file descriptor of the socket.
1064 g_socket_get_fd (GSocket *socket)
1066 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1068 return socket->priv->fd;
1072 * g_socket_get_local_address:
1073 * @socket: a #GSocket.
1074 * @error: #GError for error reporting, or %NULL to ignore.
1076 * Try to get the local address of a bound socket. This is only
1077 * useful if the socket has been bound to a local address,
1078 * either explicitly or implicitly when connecting.
1080 * Returns: a #GSocketAddress or %NULL on error.
1081 * Free the returned object with g_object_unref().
1086 g_socket_get_local_address (GSocket *socket,
1089 struct sockaddr_storage buffer;
1090 guint32 len = sizeof (buffer);
1092 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1094 if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1096 int errsv = get_socket_errno ();
1097 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1098 _("could not get local address: %s"), socket_strerror (errsv));
1102 return g_socket_address_new_from_native (&buffer, len);
1106 * g_socket_get_remote_address:
1107 * @socket: a #GSocket.
1108 * @error: #GError for error reporting, or %NULL to ignore.
1110 * Try to get the remove address of a connected socket. This is only
1111 * useful for connection oriented sockets that have been connected.
1113 * Returns: a #GSocketAddress or %NULL on error.
1114 * Free the returned object with g_object_unref().
1119 g_socket_get_remote_address (GSocket *socket,
1122 struct sockaddr_storage buffer;
1123 guint32 len = sizeof (buffer);
1125 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1127 if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1129 int errsv = get_socket_errno ();
1130 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1131 _("could not get remote address: %s"), socket_strerror (errsv));
1135 return g_socket_address_new_from_native (&buffer, len);
1139 * g_socket_is_connected:
1140 * @socket: a #GSocket.
1142 * Check whether the socket is connected. This is only useful for
1143 * connection-oriented sockets.
1145 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1150 g_socket_is_connected (GSocket *socket)
1152 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1154 return socket->priv->connected;
1159 * @socket: a #GSocket.
1160 * @error: #GError for error reporting, or %NULL to ignore.
1162 * Marks the socket as a server socket, i.e. a socket that is used
1163 * to accept incoming requests using g_socket_accept().
1165 * Before calling this the socket must be bound to a local address using
1168 * To set the maximum amount of outstanding clients, use
1169 * g_socket_set_listen_backlog().
1171 * Returns: %TRUE on success, %FALSE on error.
1176 g_socket_listen (GSocket *socket,
1179 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1181 if (!check_socket (socket, error))
1184 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1186 int errsv = get_socket_errno ();
1188 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1189 _("could not listen: %s"), socket_strerror (errsv));
1193 socket->priv->listening = TRUE;
1200 * @socket: a #GSocket.
1201 * @address: a #GSocketAddress specifying the local address.
1202 * @allow_reuse: whether to allow reusing this address
1203 * @error: #GError for error reporting, or %NULL to ignore.
1205 * When a socket is created it is attached to an address family, but it
1206 * doesn't have an address in this family. g_socket_bind() assigns the
1207 * address (sometimes called name) of the socket.
1209 * It is generally required to bind to a local address before you can
1210 * receive connections. (See g_socket_listen() and g_socket_accept() ).
1212 * If @allow_reuse is %TRUE this allows the bind call to succeed in some
1213 * situation where it would otherwise return a %G_IO_ERROR_ADDRESS_IN_USE
1214 * error. The main example is for a TCP server socket where there are
1215 * outstanding connections in the WAIT state, which are generally safe
1216 * to ignore. However, setting it to %TRUE doesn't mean the call will
1217 * succeed if there is a socket actively bound to the address.
1219 * In general, pass %TRUE if the socket will be used to accept connections,
1220 * otherwise pass %FALSE.
1222 * Returns: %TRUE on success, %FALSE on error.
1227 g_socket_bind (GSocket *socket,
1228 GSocketAddress *address,
1229 gboolean reuse_address,
1232 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 */
1245 value = (int) !!reuse_address;
1246 /* Ignore errors here, the only likely error is "not supported", and
1247 this is a "best effort" thing mainly */
1248 setsockopt (socket->priv->fd, SOL_SOCKET, SO_REUSEADDR,
1249 (gpointer) &value, sizeof (value));
1253 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1256 if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1257 g_socket_address_get_native_size (address)) < 0)
1259 int errsv = get_socket_errno ();
1261 G_IO_ERROR, socket_io_error_from_errno (errsv),
1262 _("Error binding to address: %s"), socket_strerror (errsv));
1271 * @socket: a #GSocket.
1272 * @error: #GError for error reporting, or %NULL to ignore.
1274 * Accept incoming connections on a connection-based socket. This removes
1275 * the first outstanding connection request from the listening socket and
1276 * creates a #GSocket object for it.
1278 * The @socket must be bound to a local address with g_socket_bind() and
1279 * must be listening for incoming connections (g_socket_listen()).
1281 * If there are no outstanding connections then the operation will block
1282 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
1283 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
1285 * Returns: a new #GSocket, or %NULL on error.
1286 * Free the returned object with g_object_unref().
1291 g_socket_accept (GSocket *socket,
1294 GSocket *new_socket;
1297 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1299 if (!check_socket (socket, error))
1304 if (socket->priv->blocking &&
1305 !g_socket_condition_wait (socket,
1306 G_IO_IN, NULL, error))
1309 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
1311 int errsv = get_socket_errno ();
1313 win32_unset_event_mask (socket, FD_ACCEPT);
1318 if (socket->priv->blocking)
1320 #ifdef WSAEWOULDBLOCK
1321 if (errsv == WSAEWOULDBLOCK)
1324 if (errsv == EWOULDBLOCK ||
1330 g_set_error (error, G_IO_ERROR,
1331 socket_io_error_from_errno (errsv),
1332 _("Error accepting connection: %s"), socket_strerror (errsv));
1338 win32_unset_event_mask (socket, FD_ACCEPT);
1342 /* The socket inherits the accepting sockets event mask and even object,
1343 we need to remove that */
1344 WSAEventSelect (ret, NULL, 0);
1350 /* We always want to set close-on-exec to protect users. If you
1351 need to so some weird inheritance to exec you can re-enable this
1352 using lower level hacks with g_socket_get_fd(). */
1353 flags = fcntl (ret, F_GETFD, 0);
1355 (flags & FD_CLOEXEC) == 0)
1357 flags |= FD_CLOEXEC;
1358 fcntl (ret, F_SETFD, flags);
1363 new_socket = g_socket_new_from_fd (ret, error);
1364 if (new_socket == NULL)
1373 new_socket->priv->protocol = socket->priv->protocol;
1380 * @socket: a #GSocket.
1381 * @address: a #GSocketAddress specifying the remote address.
1382 * @error: #GError for error reporting, or %NULL to ignore.
1384 * Connect the socket to the specified remote address.
1386 * For connection oriented socket this generally means we attempt to make
1387 * a connection to the @address. For a connection-less socket it sets
1388 * the default address for g_socket_send() and discards all incoming datagrams
1389 * from other sources.
1391 * Generally connection oriented sockets can only connect once, but connection-less
1392 * sockets can connect multiple times to change the default address.
1394 * If the connect call needs to do network I/O it will block, unless
1395 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
1396 * and the user can be notified of the connection finishing by waiting
1397 * for the G_IO_OUT condition. The result of the connection can then be
1398 * checked with g_socket_check_connect_result().
1400 * Returns: %TRUE if connected, %FALSE on error.
1405 g_socket_connect (GSocket *socket,
1406 GSocketAddress *address,
1409 struct sockaddr_storage buffer;
1411 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1413 if (!check_socket (socket, error))
1416 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
1421 if (socket->priv->blocking &&
1422 !g_socket_condition_wait (socket,
1423 G_IO_IN, NULL, error))
1426 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
1427 g_socket_address_get_native_size (address)) < 0)
1429 int errsv = get_socket_errno ();
1435 if (errsv == EINPROGRESS)
1437 if (errsv == WSAEINPROGRESS)
1440 if (socket->priv->blocking)
1442 g_socket_condition_wait (socket, G_IO_OUT, NULL, NULL);
1443 if (g_socket_check_connect_result (socket, error))
1446 g_prefix_error (error, _("Error connecting: "));
1449 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
1450 _("Connection in progress"));
1453 g_set_error (error, G_IO_ERROR,
1454 socket_io_error_from_errno (errsv),
1455 _("Error connecting: %s"), socket_strerror (errsv));
1462 win32_unset_event_mask (socket, FD_CONNECT);
1464 socket->priv->connected = TRUE;
1470 * g_socket_check_connect_result:
1471 * @socket: a #GSocket
1472 * @error: #GError for error reporting, or %NULL to ignore.
1474 * Checks and resets the pending connect error for the socket. This is
1475 * used to check for errors when g_socket_connect() is used in non-blocking mode.
1477 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
1482 g_socket_check_connect_result (GSocket *socket,
1488 optlen = sizeof (value);
1489 if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
1491 int errsv = get_socket_errno ();
1493 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1494 _("Unable to get pending error: %s"), socket_strerror (errsv));
1500 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
1501 socket_strerror (value));
1509 * @socket: a #GSocket
1510 * @buffer: a buffer to read data into (which should be at least count bytes long).
1511 * @size: the number of bytes that will be read from the stream
1512 * @error: #GError for error reporting, or %NULL to ignore.
1514 * Receive data (up to @size bytes) from a socket. This is mainly used by
1515 * connection oriented sockets, it is identical to g_socket_receive_from()
1516 * with @address set to %NULL.
1518 * If a message is too long to fit in @buffer, excess bytes may be discarded
1519 * depending on the type of socket the message is received from.
1521 * If the socket is in blocking mode the call will block until there is
1522 * some data to receive or there is an error. If there is no data available
1523 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1524 * will be returned. To be notified of available data, wait for the %G_IO_IN
1527 * On error -1 is returned and @error is set accordingly.
1529 * Returns: Number of bytes read, or -1 on error
1534 g_socket_receive (GSocket *socket,
1541 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1543 if (!check_socket (socket, error))
1548 if (socket->priv->blocking &&
1549 !g_socket_condition_wait (socket,
1550 G_IO_IN, NULL, error))
1553 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
1555 int errsv = get_socket_errno ();
1560 if (socket->priv->blocking)
1562 #ifdef WSAEWOULDBLOCK
1563 if (errsv == WSAEWOULDBLOCK)
1566 if (errsv == EWOULDBLOCK ||
1572 win32_unset_event_mask (socket, FD_READ);
1574 g_set_error (error, G_IO_ERROR,
1575 socket_io_error_from_errno (errsv),
1576 _("Error receiving data: %s"), socket_strerror (errsv));
1580 win32_unset_event_mask (socket, FD_READ);
1589 * g_socket_receive_from:
1590 * @socket: a #GSocket
1591 * @address: a pointer to a #GSocketAddress pointer, or %NULL
1592 * @buffer: a buffer to read data into (which should be at least count bytes long).
1593 * @size: the number of bytes that will be read from the stream
1594 * @error: #GError for error reporting, or %NULL to ignore.
1596 * Receive data (up to @size bytes) from a socket.
1598 * If @address is non-%NULL then @address will be set equal to the
1599 * source address of the received packet.
1600 * @address is owned by the caller.
1602 * If the socket is in blocking mode the call will block until there is
1603 * some data to receive or there is an error. If there is no data available
1604 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1605 * will be returned. To be notified of available data, wait for the %G_IO_IN
1608 * On error -1 is returned and @error is set accordingly.
1610 * Returns: Number of bytes read, or -1 on error
1615 g_socket_receive_from (GSocket *socket,
1616 GSocketAddress **address,
1626 return g_socket_receive_message (socket,
1635 * @socket: a #GSocket
1636 * @buffer: the buffer containing the data to send.
1637 * @size: the number of bytes to send
1638 * @error: #GError for error reporting, or %NULL to ignore.
1640 * Tries to send @size bytes from @buffer on the socket. This is mainly used by
1641 * connection oriented sockets, it is identical to g_socket_send_to()
1642 * with @address set to %NULL.
1644 * If the socket is in blocking mode the call will block until there is
1645 * space for the data in the socket queue. If there is no space available
1646 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1647 * will be returned. To be notified of available space, wait for the %G_IO_OUT
1650 * Note that on Windows you can't rely on a %G_IO_OUT condition
1651 * not producing a %G_IO_ERROR_WOULD_BLOCK error, as this is how Winsock
1652 * write notification works. However, robust apps should always be able to
1653 * handle this since it can easily appear in other cases too.
1655 * On error -1 is returned and @error is set accordingly.
1657 * Returns: Number of bytes read, or -1 on error
1662 g_socket_send (GSocket *socket,
1663 const gchar *buffer,
1669 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1671 if (!check_socket (socket, error))
1676 if (socket->priv->blocking &&
1677 !g_socket_condition_wait (socket,
1678 G_IO_OUT, NULL, error))
1681 if ((ret = send (socket->priv->fd, buffer, size, 0)) < 0)
1683 int errsv = get_socket_errno ();
1688 #ifdef WSAEWOULDBLOCK
1689 if (errsv == WSAEWOULDBLOCK)
1690 win32_unset_event_mask (socket, FD_WRITE);
1693 if (socket->priv->blocking)
1695 #ifdef WSAEWOULDBLOCK
1696 if (errsv == WSAEWOULDBLOCK)
1699 if (errsv == EWOULDBLOCK ||
1705 g_set_error (error, G_IO_ERROR,
1706 socket_io_error_from_errno (errsv),
1707 _("Error sending data: %s"), socket_strerror (errsv));
1718 * @socket: a #GSocket
1719 * @address: a #GSocketAddress, or %NULL
1720 * @buffer: the buffer containing the data to send.
1721 * @size: the number of bytes to send
1722 * @error: #GError for error reporting, or %NULL to ignore.
1724 * Tries to send @size bytes from @buffer to @address. If @address is
1725 * %NULL then the message is sent to the default receiver (set by
1726 * g_socket_connect()).
1728 * If the socket is in blocking mode the call will block until there is
1729 * space for the data in the socket queue. If there is no space available
1730 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1731 * will be returned. To be notified of available space, wait for the %G_IO_OUT
1734 * Note that on Windows you can't rely on a %G_IO_OUT condition
1735 * not producing a %G_IO_ERROR_WOULD_BLOCK error, as this is how Winsock
1736 * write notification works. However, robust apps should always be able to
1737 * handle this since it can easily appear in other cases too.
1739 * On error -1 is returned and @error is set accordingly.
1741 * Returns: Number of bytes read, or -1 on error
1746 g_socket_send_to (GSocket *socket,
1747 GSocketAddress *address,
1748 const gchar *buffer,
1757 return g_socket_send_message (socket,
1765 * g_socket_shutdown:
1766 * @socket: a #GSocket
1767 * @shutdown_read: whether to shut down the read side
1768 * @shutdown_write: whether to shut down the write side
1769 * @error: #GError for error reporting, or %NULL to ignore.
1771 * Shut down part of a full-duplex connection.
1773 * If @shutdown_read is %TRUE then the recieving side of the connection
1774 * is shut down, and further reading is disallowed.
1776 * If @shutdown_write is %TRUE then the sending side of the connection
1777 * is shut down, and further writing is disallowed.
1779 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
1781 * One example where this is used is graceful disconnect for TCP connections
1782 * where you close the sending side, then wait for the other side to close
1783 * the connection, thus ensuring that the other side saw all sent data.
1785 * Returns: %TRUE on success, %FALSE on error
1790 g_socket_shutdown (GSocket *socket,
1791 gboolean shutdown_read,
1792 gboolean shutdown_write,
1797 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
1799 if (!check_socket (socket, NULL))
1803 if (!shutdown_read && !shutdown_write)
1807 if (shutdown_read && shutdown_write)
1809 else if (shutdown_read)
1814 if (shutdown_read && shutdown_write)
1816 else if (shutdown_read)
1822 if (shutdown (socket->priv->fd, how) != 0)
1824 int errsv = get_socket_errno ();
1825 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1826 _("Unable to create socket: %s"), socket_strerror (errsv));
1830 if (shutdown_read && shutdown_write)
1831 socket->priv->connected = FALSE;
1838 * @socket: a #GSocket
1839 * @error: #GError for error reporting, or %NULL to ignore.
1841 * Closes the socket, shutting down any active connection.
1843 * Closing a socket does not wait for all outstanding I/O operations to finish,
1844 * so the caller should not rely on them to be guaranteed to complete even
1845 * if the close returns with no error.
1847 * Once the socket is closed, all other operations will return %G_IO_ERROR_CLOSED.
1848 * Closing a stream multiple times will not return an error.
1850 * Sockets will be automatically closed when the last reference
1851 * is dropped, but you might want to call this function to make sure
1852 * resources are released as early as possible.
1854 * Returns: %TRUE on success, %FALSE on error
1859 g_socket_close (GSocket *socket,
1864 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
1866 if (socket->priv->closed)
1867 return TRUE; /* Multiple close not an error */
1869 if (!check_socket (socket, NULL))
1875 res = closesocket (socket->priv->fd);
1877 res = close (socket->priv->fd);
1881 int errsv = get_socket_errno ();
1886 g_set_error (error, G_IO_ERROR,
1887 socket_io_error_from_errno (errsv),
1888 _("Error closing socket: %s"),
1889 socket_strerror (errsv));
1896 if (socket->priv->event != WSA_INVALID_EVENT)
1898 WSACloseEvent (socket->priv->event);
1899 socket->priv->event = WSA_INVALID_EVENT;
1903 socket->priv->connected = FALSE;
1904 socket->priv->closed = TRUE;
1910 * g_socket_is_closed:
1911 * @socket: a #GSocket
1913 * Checks whether a socket is closed.
1915 * Returns: %TRUE if socket is closed, %FALSE otherwise
1920 g_socket_is_closed (GSocket *socket)
1922 return socket->priv->closed;
1926 /* Broken source, used on errors */
1928 broken_prepare (GSource *source,
1935 broken_check (GSource *source)
1941 broken_dispatch (GSource *source,
1942 GSourceFunc callback,
1948 static GSourceFuncs broken_funcs =
1957 network_events_for_condition (GIOCondition condition)
1961 if (condition & G_IO_IN)
1962 event_mask |= (FD_READ | FD_ACCEPT);
1963 if (condition & G_IO_OUT)
1964 event_mask |= (FD_WRITE | FD_CONNECT);
1965 event_mask |= FD_CLOSE;
1971 ensure_event (GSocket *socket)
1973 if (socket->priv->event == WSA_INVALID_EVENT)
1974 socket->priv->event = WSACreateEvent();
1978 update_select_events (GSocket *socket)
1985 ensure_event (socket);
1988 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
1991 event_mask |= network_events_for_condition (*ptr);
1994 if (event_mask != socket->priv->selected_events)
1996 /* If no events selected, disable event so we can unset
1999 if (event_mask == 0)
2002 event = socket->priv->event;
2004 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
2005 socket->priv->selected_events = event_mask;
2010 add_condition_watch (GSocket *socket,
2011 GIOCondition *condition)
2013 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
2015 socket->priv->requested_conditions =
2016 g_list_prepend (socket->priv->requested_conditions, condition);
2018 update_select_events (socket);
2022 remove_condition_watch (GSocket *socket,
2023 GIOCondition *condition)
2025 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
2027 socket->priv->requested_conditions =
2028 g_list_remove (socket->priv->requested_conditions, condition);
2030 update_select_events (socket);
2034 update_condition (GSocket *socket)
2036 WSANETWORKEVENTS events;
2037 GIOCondition condition;
2039 if (WSAEnumNetworkEvents (socket->priv->fd,
2040 socket->priv->event,
2043 socket->priv->current_events |= events.lNetworkEvents;
2044 if (events.lNetworkEvents & FD_WRITE &&
2045 events.iErrorCode[FD_WRITE_BIT] != 0)
2046 socket->priv->current_errors |= FD_WRITE;
2047 if (events.lNetworkEvents & FD_CONNECT &&
2048 events.iErrorCode[FD_CONNECT_BIT] != 0)
2049 socket->priv->current_errors |= FD_CONNECT;
2053 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
2054 condition |= G_IO_IN;
2056 if (socket->priv->current_events & FD_CLOSE ||
2057 socket->priv->closed)
2058 condition |= G_IO_HUP;
2060 /* Never report both G_IO_OUT and HUP, these are
2061 mutually exclusive (can't write to a closed socket) */
2062 if ((condition & G_IO_HUP) == 0 &&
2063 socket->priv->current_events & FD_WRITE)
2065 if (socket->priv->current_errors & FD_WRITE)
2066 condition |= G_IO_ERR;
2068 condition |= G_IO_OUT;
2072 if (socket->priv->current_events & FD_CONNECT)
2074 if (socket->priv->current_errors & FD_CONNECT)
2075 condition |= (G_IO_HUP | G_IO_ERR);
2077 condition |= G_IO_OUT;
2088 GIOCondition condition;
2089 GCancellable *cancellable;
2090 GPollFD cancel_pollfd;
2091 GIOCondition result_condition;
2095 winsock_prepare (GSource *source,
2098 GWinsockSource *winsock_source = (GWinsockSource *)source;
2099 GIOCondition current_condition;
2101 current_condition = update_condition (winsock_source->socket);
2103 if (g_cancellable_is_cancelled (winsock_source->cancellable))
2105 winsock_source->result_condition = current_condition;
2109 if ((winsock_source->condition & current_condition) != 0)
2111 winsock_source->result_condition = current_condition;
2119 winsock_check (GSource *source)
2121 GWinsockSource *winsock_source = (GWinsockSource *)source;
2122 GIOCondition current_condition;
2124 current_condition = update_condition (winsock_source->socket);
2126 if (g_cancellable_is_cancelled (winsock_source->cancellable))
2128 winsock_source->result_condition = current_condition;
2132 if ((winsock_source->condition & current_condition) != 0)
2134 winsock_source->result_condition = current_condition;
2142 winsock_dispatch (GSource *source,
2143 GSourceFunc callback,
2146 GSocketSourceFunc func = (GSocketSourceFunc)callback;
2147 GWinsockSource *winsock_source = (GWinsockSource *)source;
2149 return (*func) (winsock_source->socket,
2150 winsock_source->result_condition & winsock_source->condition,
2155 winsock_finalize (GSource *source)
2157 GWinsockSource *winsock_source = (GWinsockSource *)source;
2160 socket = winsock_source->socket;
2162 remove_condition_watch (socket, &winsock_source->condition);
2163 g_object_unref (socket);
2165 if (winsock_source->cancellable)
2166 g_object_unref (winsock_source->cancellable);
2169 static GSourceFuncs winsock_funcs =
2178 winsock_source_new (GSocket *socket,
2179 GIOCondition condition,
2180 GCancellable *cancellable)
2183 GWinsockSource *winsock_source;
2185 ensure_event (socket);
2187 if (socket->priv->event == WSA_INVALID_EVENT)
2189 g_warning ("Failed to create WSAEvent");
2190 return g_source_new (&broken_funcs, sizeof (GSource));
2193 condition |= G_IO_HUP | G_IO_ERR;
2195 source = g_source_new (&winsock_funcs, sizeof (GWinsockSource));
2196 winsock_source = (GWinsockSource *)source;
2198 winsock_source->socket = g_object_ref (socket);
2199 winsock_source->condition = condition;
2200 add_condition_watch (socket, &winsock_source->condition);
2204 winsock_source->cancellable = g_object_ref (cancellable);
2205 g_cancellable_make_pollfd (cancellable,
2206 &winsock_source->cancel_pollfd);
2207 g_source_add_poll (source, &winsock_source->cancel_pollfd);
2210 winsock_source->pollfd.fd = (gintptr) socket->priv->event;
2211 winsock_source->pollfd.events = condition;
2212 g_source_add_poll (source, &winsock_source->pollfd);
2219 * g_socket_create_source:
2220 * @socket: a #GSocket
2221 * @condition: a #GIOCondition mask to monitor
2222 * @cancellable: a %GCancellable or %NULL
2224 * Creates a %GSource that can be attached to a %GMainContext to monitor
2225 * for the availibility of the specified @condition on the socket.
2227 * The callback on the source is of the #GSocketSourceFunc type.
2229 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2230 * these conditions will always be reported output if they are true.
2232 * @cancellable if not %NULL can be used to cancel the source, which will
2233 * cause the source to trigger, reporting the current condition (which
2234 * is likely 0 unless cancellation happened at the same time as a
2235 * condition change). You can check for this in the callback using
2236 * g_cancellable_is_cancelled().
2238 * Returns: a newly allocated %GSource, free with g_source_unref().
2243 g_socket_create_source (GSocket *socket,
2244 GIOCondition condition,
2245 GCancellable *cancellable)
2248 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
2251 source = winsock_source_new (socket, condition, cancellable);
2253 source =_g_fd_source_new_with_object (G_OBJECT (socket), socket->priv->fd,
2254 condition, cancellable);
2260 * g_socket_condition_check:
2261 * @socket: a #GSocket
2262 * @condition: a #GIOCondition mask to check
2264 * Checks on the readiness of @socket to perform operations. The
2265 * operations specified in @condition are checked for and masked
2266 * against the currently-satisfied conditions on @socket. The result
2269 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2270 * these conditions will always be set in the output if they are true.
2272 * This call never blocks.
2274 * Returns: the @GIOCondition mask of the current state
2279 g_socket_condition_check (GSocket *socket,
2280 GIOCondition condition)
2282 if (!check_socket (socket, NULL))
2287 GIOCondition current_condition;
2289 condition |= G_IO_ERR | G_IO_HUP;
2291 add_condition_watch (socket, &condition);
2292 current_condition = update_condition (socket);
2293 remove_condition_watch (socket, &condition);
2294 return condition & current_condition;
2300 poll_fd.fd = socket->priv->fd;
2301 poll_fd.events = condition;
2304 result = g_poll (&poll_fd, 1, 0);
2305 while (result == -1 && get_socket_errno () == EINTR);
2307 return poll_fd.revents;
2313 * g_socket_condition_wait:
2314 * @socket: a #GSocket
2315 * @condition: a #GIOCondition mask to wait for
2316 * @cancellable: a #GCancellable, or %NULL
2317 * @error: a #GError pointer, or %NULL
2319 * Waits for @condition to become true on @socket. When the condition
2320 * becomes true, %TRUE is returned.
2322 * If @cancellable is cancelled before the condition becomes true then
2323 * %FALSE is returned and @error, if non-%NULL, is set to %G_IO_ERROR_CANCELLED.
2325 * Returns: %TRUE if the condition was met, %FALSE otherwise
2330 g_socket_condition_wait (GSocket *socket,
2331 GIOCondition condition,
2332 GCancellable *cancellable,
2335 if (!check_socket (socket, error))
2338 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2343 GIOCondition current_condition;
2349 /* Always check these */
2350 condition |= G_IO_ERR | G_IO_HUP;
2352 add_condition_watch (socket, &condition);
2355 events[num_events++] = socket->priv->event;
2359 g_cancellable_make_pollfd (cancellable, &cancel_fd);
2360 events[num_events++] = (WSAEVENT)cancel_fd.fd;
2363 current_condition = update_condition (socket);
2364 while ((condition & current_condition) == 0)
2366 res = WSAWaitForMultipleEvents(num_events, events,
2367 FALSE, WSA_INFINITE, FALSE);
2368 if (res == WSA_WAIT_FAILED)
2370 int errsv = get_socket_errno ();
2372 g_set_error (error, G_IO_ERROR,
2373 socket_io_error_from_errno (errsv),
2374 _("Waiting for socket condition: %s"),
2375 socket_strerror (errsv));
2379 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2382 current_condition = update_condition (socket);
2384 remove_condition_watch (socket, &condition);
2386 return (condition & current_condition) != 0;
2394 poll_fd[0].fd = socket->priv->fd;
2395 poll_fd[0].events = condition;
2400 g_cancellable_make_pollfd (cancellable, &poll_fd[1]);
2405 result = g_poll (poll_fd, num, -1);
2406 while (result == -1 && get_socket_errno () == EINTR);
2408 return cancellable == NULL ||
2409 !g_cancellable_set_error_if_cancelled (cancellable, error);
2415 * g_socket_send_message:
2416 * @socket: a #GSocket
2417 * @address: a #GSocketAddress, or %NULL
2418 * @vectors: an array of #GOutputVector structs
2419 * @num_vectors: the number of elements in @vectors, or -1
2420 * @messages: a pointer to an array of #GSocketControlMessages, or
2422 * @num_messages: number of elements in @messages, or -1.
2423 * @flags: an int containing #GSocketMsgFlags flags
2424 * @error: #GError for error reporting, or %NULL to ignore.
2426 * Send data to @address on @socket. This is the most complicated and
2427 * fully-featured version of this call. For easier use, see
2428 * g_socket_send() and g_socket_send_to().
2430 * If @address is %NULL then the message is sent to the default receiver
2431 * (set by g_socket_connect()).
2433 * @vector must point to an array of #GOutputVector structs and
2434 * @num_vectors must be the length of this array. These structs
2435 * describe the buffers that the sent data will be gathered from.
2436 * If @num_vector is -1, then @vector is assumed to be terminated
2437 * by a #GOutputVector with a %NULL buffer pointer.
2440 * @messages, if non-%NULL, is taken to point to an array of @num_messages
2441 * #GSocketControlMessage instances. These correspond to the control
2442 * messages to be sent on the socket.
2443 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
2446 * @flags modify how the message sent. The commonly available arguments
2447 * for this is available in the #GSocketMsgFlags enum, but the
2448 * values there are the same as the system values, and the flags
2449 * are passed in as-is, so you can pass in system specific flags too.
2451 * If the socket is in blocking mode the call will block until there is
2452 * space for the data in the socket queue. If there is no space available
2453 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2454 * will be returned. To be notified of available space, wait for the %G_IO_OUT
2457 * Note that on Windows you can't rely on a %G_IO_OUT condition
2458 * not producing a %G_IO_ERROR_WOULD_BLOCK error, as this is how Winsock
2459 * write notification works. However, robust apps should always be able to
2460 * handle this since it can easily appear in other cases too.
2462 * On error -1 is returned and @error is set accordingly.
2464 * Returns: Number of bytes read, or -1 on error
2469 g_socket_send_message (GSocket *socket,
2470 GSocketAddress *address,
2471 GOutputVector *vectors,
2473 GSocketControlMessage **messages,
2478 GOutputVector one_vector;
2481 if (!check_socket (socket, error))
2484 if (num_vectors == -1)
2486 for (num_vectors = 0;
2487 vectors[num_vectors].buffer != NULL;
2492 if (num_messages == -1)
2494 for (num_messages = 0;
2495 messages != NULL && messages[num_messages] != NULL;
2500 if (num_vectors == 0)
2504 one_vector.buffer = &zero;
2505 one_vector.size = 1;
2507 vectors = &one_vector;
2518 msg.msg_namelen = g_socket_address_get_native_size (address);
2519 msg.msg_name = g_alloca (msg.msg_namelen);
2520 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
2526 /* this entire expression will be evaluated at compile time */
2527 if (sizeof *msg.msg_iov == sizeof *vectors &&
2528 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2529 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2530 G_STRUCT_OFFSET (GOutputVector, buffer) &&
2531 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2532 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2533 G_STRUCT_OFFSET (GOutputVector, size))
2534 /* ABI is compatible */
2536 msg.msg_iov = (struct iovec *) vectors;
2537 msg.msg_iovlen = num_vectors;
2540 /* ABI is incompatible */
2544 msg.msg_iov = g_newa (struct iovec, num_vectors);
2545 for (i = 0; i < num_vectors; i++)
2547 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
2548 msg.msg_iov[i].iov_len = vectors[i].size;
2550 msg.msg_iovlen = num_vectors;
2556 struct cmsghdr *cmsg;
2559 msg.msg_controllen = 0;
2560 for (i = 0; i < num_messages; i++)
2561 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
2563 msg.msg_control = g_alloca (msg.msg_controllen);
2565 cmsg = CMSG_FIRSTHDR (&msg);
2566 for (i = 0; i < num_messages; i++)
2568 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
2569 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
2570 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
2571 g_socket_control_message_serialize (messages[i],
2573 cmsg = CMSG_NXTHDR (&msg, cmsg);
2575 g_assert (cmsg == NULL);
2580 if (socket->priv->blocking &&
2581 !g_socket_condition_wait (socket,
2582 G_IO_OUT, NULL, error))
2585 result = sendmsg (socket->priv->fd, &msg, flags);
2588 int errsv = get_socket_errno ();
2593 if (socket->priv->blocking &&
2594 (errsv == EWOULDBLOCK ||
2598 g_set_error (error, G_IO_ERROR,
2599 socket_io_error_from_errno (errsv),
2600 _("Error sending message: %s"), socket_strerror (errsv));
2611 struct sockaddr_storage addr;
2618 /* Win32 doesn't support control messages.
2619 Actually this is possible for raw and datagram sockets
2620 via WSASendMessage on Vista or later, but that doesn't
2622 if (num_messages != 0)
2624 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2625 _("GSocketControlMessage not supported on windows"));
2630 bufs = g_newa (WSABUF, num_vectors);
2631 for (i = 0; i < num_vectors; i++)
2633 bufs[i].buf = (char *)vectors[i].buffer;
2634 bufs[i].len = (gulong)vectors[i].size;
2638 addrlen = 0; /* Avoid warning */
2641 addrlen = g_socket_address_get_native_size (address);
2642 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
2648 if (socket->priv->blocking &&
2649 !g_socket_condition_wait (socket,
2650 G_IO_OUT, NULL, error))
2654 result = WSASendTo (socket->priv->fd,
2657 (const struct sockaddr *)&addr, addrlen,
2660 result = WSASend (socket->priv->fd,
2667 int errsv = get_socket_errno ();
2669 if (errsv == WSAEINTR)
2672 if (errsv == WSAEWOULDBLOCK)
2673 win32_unset_event_mask (socket, FD_WRITE);
2675 if (socket->priv->blocking &&
2676 errsv == WSAEWOULDBLOCK)
2679 g_set_error (error, G_IO_ERROR,
2680 socket_io_error_from_errno (errsv),
2681 _("Error sending message: %s"), socket_strerror (errsv));
2694 * g_socket_receive_message:
2695 * @socket: a #GSocket
2696 * @address: a pointer to a #GSocketAddress pointer, or %NULL
2697 * @vectors: an array of #GInputVector structs
2698 * @num_vectors: the number of elements in @vectors, or -1
2699 * @messages: a pointer which will be filled with an array of
2700 * #GSocketControlMessages, or %NULL
2701 * @num_messages: a pointer which will be filled with the number of
2702 * elements in @messages, or %NULL
2703 * @flags: a pointer to an int containing #GSocketMsgFlags flags
2704 * @error: a #GError pointer, or %NULL
2706 * Receive data from a socket. This is the most complicated and
2707 * fully-featured version of this call. For easier use, see
2708 * g_socket_receive() and g_socket_receive_from().
2710 * If @address is non-%NULL then @address will be set equal to the
2711 * source address of the received packet.
2712 * @address is owned by the caller.
2714 * @vector must point to an array of #GInputVector structs and
2715 * @num_vectors must be the length of this array. These structs
2716 * describe the buffers that received data will be scattered into.
2717 * If @num_vector is -1, then @vector is assumed to be terminated
2718 * by a #GInputVector with a %NULL buffer pointer.
2720 * As a special case, if the size of the array is zero (in which case,
2721 * @vectors may of course be %NULL), then a single byte is received
2722 * and discarded. This is to facilitate the common practice of
2723 * sending a single '\0' byte for the purposes of transferring
2726 * @messages, if non-%NULL, is taken to point to a pointer that will
2727 * be set to point to a newly-allocated array of
2728 * #GSocketControlMessage instances. These correspond to the control
2729 * messages received from the kernel, one #GSocketControlMessage per
2730 * message from the kernel. This array is %NULL-terminated and must be
2731 * freed by the caller using g_free().
2733 * @num_messages, if non-%NULL, will be set to the number of control
2734 * messages received.
2736 * If both @messages and @num_messages are non-%NULL, then
2737 * @num_messages gives the number of #GSocketControlMessage instances
2738 * in @messages (ie: not including the %NULL terminator).
2740 * @flags is an in/out parameter. The commonly available arguments
2741 * for this is available in the #GSocketMsgFlags enum, but the
2742 * values there are the same as the system values, and the flags
2743 * are passed in as-is, so you can pass in system specific flags too.
2745 * If the socket is in blocking mode the call will block until there is
2746 * some data to receive or there is an error. If there is no data available
2747 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2748 * will be returned. To be notified of available data, wait for the %G_IO_IN
2751 * On error -1 is returned and @error is set accordingly.
2753 * Returns: Number of bytes read, or -1 on error
2758 g_socket_receive_message (GSocket *socket,
2759 GSocketAddress **address,
2760 GInputVector *vectors,
2762 GSocketControlMessage ***messages,
2767 GInputVector one_vector;
2770 if (!check_socket (socket, error))
2773 if (num_vectors == -1)
2775 for (num_vectors = 0;
2776 vectors[num_vectors].buffer != NULL;
2781 if (num_vectors == 0)
2783 one_vector.buffer = &one_byte;
2784 one_vector.size = 1;
2786 vectors = &one_vector;
2793 struct sockaddr_storage one_sockaddr;
2798 msg.msg_name = &one_sockaddr;
2799 msg.msg_namelen = sizeof (struct sockaddr_storage);
2803 msg.msg_name = NULL;
2804 msg.msg_namelen = 0;
2808 /* this entire expression will be evaluated at compile time */
2809 if (sizeof *msg.msg_iov == sizeof *vectors &&
2810 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2811 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2812 G_STRUCT_OFFSET (GInputVector, buffer) &&
2813 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2814 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2815 G_STRUCT_OFFSET (GInputVector, size))
2816 /* ABI is compatible */
2818 msg.msg_iov = (struct iovec *) vectors;
2819 msg.msg_iovlen = num_vectors;
2822 /* ABI is incompatible */
2826 msg.msg_iov = g_newa (struct iovec, num_vectors);
2827 for (i = 0; i < num_vectors; i++)
2829 msg.msg_iov[i].iov_base = vectors[i].buffer;
2830 msg.msg_iov[i].iov_len = vectors[i].size;
2832 msg.msg_iovlen = num_vectors;
2836 msg.msg_control = g_alloca (2048);
2837 msg.msg_controllen = 2048;
2841 msg.msg_flags = *flags;
2848 if (socket->priv->blocking &&
2849 !g_socket_condition_wait (socket,
2850 G_IO_IN, NULL, error))
2853 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
2857 int errsv = get_socket_errno ();
2862 if (socket->priv->blocking &&
2863 (errsv == EWOULDBLOCK ||
2867 g_set_error (error, G_IO_ERROR,
2868 socket_io_error_from_errno (errsv),
2869 _("Error receiving message: %s"), socket_strerror (errsv));
2876 /* decode address */
2877 if (address != NULL)
2879 if (msg.msg_namelen > 0)
2880 *address = g_socket_address_new_from_native (msg.msg_name,
2886 /* decode control messages */
2888 GSocketControlMessage **my_messages = NULL;
2889 gint allocated = 0, index = 0;
2890 const gchar *scm_pointer;
2891 struct cmsghdr *cmsg;
2894 scm_pointer = (const gchar *) msg.msg_control;
2895 scm_size = msg.msg_controllen;
2897 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
2899 GSocketControlMessage *message;
2901 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
2903 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
2905 if (message == NULL)
2906 /* We've already spewed about the problem in the
2907 deserialization code, so just continue */
2910 if (index == allocated)
2912 /* estimated 99% case: exactly 1 control message */
2913 allocated = MIN (allocated * 2, 1);
2914 my_messages = g_new (GSocketControlMessage *, (allocated + 1));
2918 my_messages[index++] = message;
2922 *num_messages = index;
2926 my_messages[index++] = NULL;
2927 *messages = my_messages;
2933 /* free all those messages we just constructed.
2934 * we have to do it this way if the user ignores the
2935 * messages so that we will close any received fds.
2937 for (i = 0; i < index; i++)
2938 g_object_unref (my_messages[i]);
2939 g_free (my_messages);
2943 /* capture the flags */
2945 *flags = msg.msg_flags;
2951 struct sockaddr_storage addr;
2953 DWORD bytes_received;
2960 bufs = g_newa (WSABUF, num_vectors);
2961 for (i = 0; i < num_vectors; i++)
2963 bufs[i].buf = (char *)vectors[i].buffer;
2964 bufs[i].len = (gulong)vectors[i].size;
2976 if (socket->priv->blocking &&
2977 !g_socket_condition_wait (socket,
2978 G_IO_IN, NULL, error))
2981 addrlen = sizeof addr;
2983 result = WSARecvFrom (socket->priv->fd,
2985 &bytes_received, &win_flags,
2986 (struct sockaddr *)&addr, &addrlen,
2989 result = WSARecv (socket->priv->fd,
2991 &bytes_received, &win_flags,
2995 int errsv = get_socket_errno ();
2997 if (errsv == WSAEINTR)
3000 win32_unset_event_mask (socket, FD_READ);
3002 if (socket->priv->blocking &&
3003 errsv == WSAEWOULDBLOCK)
3006 g_set_error (error, G_IO_ERROR,
3007 socket_io_error_from_errno (errsv),
3008 _("Error receiving message: %s"), socket_strerror (errsv));
3012 win32_unset_event_mask (socket, FD_READ);
3016 /* decode address */
3017 if (address != NULL)
3020 *address = g_socket_address_new_from_native (&addr, addrlen);
3025 /* capture the flags */
3029 return bytes_received;
3034 #define __G_SOCKET_C__
3035 #include "gioaliasdef.c"