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 (connect (socket->priv->fd, (struct sockaddr *) &buffer,
1422 g_socket_address_get_native_size (address)) < 0)
1424 int errsv = get_socket_errno ();
1430 if (errsv == EINPROGRESS)
1432 if (errsv == WSAEWOULDBLOCK)
1435 if (socket->priv->blocking)
1437 g_socket_condition_wait (socket, G_IO_OUT, NULL, NULL);
1438 if (g_socket_check_connect_result (socket, error))
1441 g_prefix_error (error, _("Error connecting: "));
1444 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
1445 _("Connection in progress"));
1448 g_set_error (error, G_IO_ERROR,
1449 socket_io_error_from_errno (errsv),
1450 _("Error connecting: %s"), socket_strerror (errsv));
1457 win32_unset_event_mask (socket, FD_CONNECT);
1459 socket->priv->connected = TRUE;
1465 * g_socket_check_connect_result:
1466 * @socket: a #GSocket
1467 * @error: #GError for error reporting, or %NULL to ignore.
1469 * Checks and resets the pending connect error for the socket. This is
1470 * used to check for errors when g_socket_connect() is used in non-blocking mode.
1472 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
1477 g_socket_check_connect_result (GSocket *socket,
1483 optlen = sizeof (value);
1484 if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
1486 int errsv = get_socket_errno ();
1488 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1489 _("Unable to get pending error: %s"), socket_strerror (errsv));
1495 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
1496 socket_strerror (value));
1504 * @socket: a #GSocket
1505 * @buffer: a buffer to read data into (which should be at least count bytes long).
1506 * @size: the number of bytes that will be read from the stream
1507 * @error: #GError for error reporting, or %NULL to ignore.
1509 * Receive data (up to @size bytes) from a socket. This is mainly used by
1510 * connection oriented sockets, it is identical to g_socket_receive_from()
1511 * with @address set to %NULL.
1513 * If a message is too long to fit in @buffer, excess bytes may be discarded
1514 * depending on the type of socket the message is received from.
1516 * If the socket is in blocking mode the call will block until there is
1517 * some data to receive or there is an error. If there is no data available
1518 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1519 * will be returned. To be notified of available data, wait for the %G_IO_IN
1522 * On error -1 is returned and @error is set accordingly.
1524 * Returns: Number of bytes read, or -1 on error
1529 g_socket_receive (GSocket *socket,
1536 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1538 if (!check_socket (socket, error))
1543 if (socket->priv->blocking &&
1544 !g_socket_condition_wait (socket,
1545 G_IO_IN, NULL, error))
1548 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
1550 int errsv = get_socket_errno ();
1555 if (socket->priv->blocking)
1557 #ifdef WSAEWOULDBLOCK
1558 if (errsv == WSAEWOULDBLOCK)
1561 if (errsv == EWOULDBLOCK ||
1567 win32_unset_event_mask (socket, FD_READ);
1569 g_set_error (error, G_IO_ERROR,
1570 socket_io_error_from_errno (errsv),
1571 _("Error receiving data: %s"), socket_strerror (errsv));
1575 win32_unset_event_mask (socket, FD_READ);
1584 * g_socket_receive_from:
1585 * @socket: a #GSocket
1586 * @address: a pointer to a #GSocketAddress pointer, or %NULL
1587 * @buffer: a buffer to read data into (which should be at least count bytes long).
1588 * @size: the number of bytes that will be read from the stream
1589 * @error: #GError for error reporting, or %NULL to ignore.
1591 * Receive data (up to @size bytes) from a socket.
1593 * If @address is non-%NULL then @address will be set equal to the
1594 * source address of the received packet.
1595 * @address is owned by the caller.
1597 * If the socket is in blocking mode the call will block until there is
1598 * some data to receive or there is an error. If there is no data available
1599 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1600 * will be returned. To be notified of available data, wait for the %G_IO_IN
1603 * On error -1 is returned and @error is set accordingly.
1605 * Returns: Number of bytes read, or -1 on error
1610 g_socket_receive_from (GSocket *socket,
1611 GSocketAddress **address,
1621 return g_socket_receive_message (socket,
1630 * @socket: a #GSocket
1631 * @buffer: the buffer containing the data to send.
1632 * @size: the number of bytes to send
1633 * @error: #GError for error reporting, or %NULL to ignore.
1635 * Tries to send @size bytes from @buffer on the socket. This is mainly used by
1636 * connection oriented sockets, it is identical to g_socket_send_to()
1637 * with @address set to %NULL.
1639 * If the socket is in blocking mode the call will block until there is
1640 * space for the data in the socket queue. If there is no space available
1641 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1642 * will be returned. To be notified of available space, wait for the %G_IO_OUT
1645 * Note that on Windows you can't rely on a %G_IO_OUT condition
1646 * not producing a %G_IO_ERROR_WOULD_BLOCK error, as this is how Winsock
1647 * write notification works. However, robust apps should always be able to
1648 * handle this since it can easily appear in other cases too.
1650 * On error -1 is returned and @error is set accordingly.
1652 * Returns: Number of bytes read, or -1 on error
1657 g_socket_send (GSocket *socket,
1658 const gchar *buffer,
1664 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1666 if (!check_socket (socket, error))
1671 if (socket->priv->blocking &&
1672 !g_socket_condition_wait (socket,
1673 G_IO_OUT, NULL, error))
1676 if ((ret = send (socket->priv->fd, buffer, size, 0)) < 0)
1678 int errsv = get_socket_errno ();
1683 #ifdef WSAEWOULDBLOCK
1684 if (errsv == WSAEWOULDBLOCK)
1685 win32_unset_event_mask (socket, FD_WRITE);
1688 if (socket->priv->blocking)
1690 #ifdef WSAEWOULDBLOCK
1691 if (errsv == WSAEWOULDBLOCK)
1694 if (errsv == EWOULDBLOCK ||
1700 g_set_error (error, G_IO_ERROR,
1701 socket_io_error_from_errno (errsv),
1702 _("Error sending data: %s"), socket_strerror (errsv));
1713 * @socket: a #GSocket
1714 * @address: a #GSocketAddress, or %NULL
1715 * @buffer: the buffer containing the data to send.
1716 * @size: the number of bytes to send
1717 * @error: #GError for error reporting, or %NULL to ignore.
1719 * Tries to send @size bytes from @buffer to @address. If @address is
1720 * %NULL then the message is sent to the default receiver (set by
1721 * g_socket_connect()).
1723 * If the socket is in blocking mode the call will block until there is
1724 * space for the data in the socket queue. If there is no space available
1725 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1726 * will be returned. To be notified of available space, wait for the %G_IO_OUT
1729 * Note that on Windows you can't rely on a %G_IO_OUT condition
1730 * not producing a %G_IO_ERROR_WOULD_BLOCK error, as this is how Winsock
1731 * write notification works. However, robust apps should always be able to
1732 * handle this since it can easily appear in other cases too.
1734 * On error -1 is returned and @error is set accordingly.
1736 * Returns: Number of bytes read, or -1 on error
1741 g_socket_send_to (GSocket *socket,
1742 GSocketAddress *address,
1743 const gchar *buffer,
1752 return g_socket_send_message (socket,
1760 * g_socket_shutdown:
1761 * @socket: a #GSocket
1762 * @shutdown_read: whether to shut down the read side
1763 * @shutdown_write: whether to shut down the write side
1764 * @error: #GError for error reporting, or %NULL to ignore.
1766 * Shut down part of a full-duplex connection.
1768 * If @shutdown_read is %TRUE then the recieving side of the connection
1769 * is shut down, and further reading is disallowed.
1771 * If @shutdown_write is %TRUE then the sending side of the connection
1772 * is shut down, and further writing is disallowed.
1774 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
1776 * One example where this is used is graceful disconnect for TCP connections
1777 * where you close the sending side, then wait for the other side to close
1778 * the connection, thus ensuring that the other side saw all sent data.
1780 * Returns: %TRUE on success, %FALSE on error
1785 g_socket_shutdown (GSocket *socket,
1786 gboolean shutdown_read,
1787 gboolean shutdown_write,
1792 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
1794 if (!check_socket (socket, NULL))
1798 if (!shutdown_read && !shutdown_write)
1802 if (shutdown_read && shutdown_write)
1804 else if (shutdown_read)
1809 if (shutdown_read && shutdown_write)
1811 else if (shutdown_read)
1817 if (shutdown (socket->priv->fd, how) != 0)
1819 int errsv = get_socket_errno ();
1820 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1821 _("Unable to create socket: %s"), socket_strerror (errsv));
1825 if (shutdown_read && shutdown_write)
1826 socket->priv->connected = FALSE;
1833 * @socket: a #GSocket
1834 * @error: #GError for error reporting, or %NULL to ignore.
1836 * Closes the socket, shutting down any active connection.
1838 * Closing a socket does not wait for all outstanding I/O operations to finish,
1839 * so the caller should not rely on them to be guaranteed to complete even
1840 * if the close returns with no error.
1842 * Once the socket is closed, all other operations will return %G_IO_ERROR_CLOSED.
1843 * Closing a stream multiple times will not return an error.
1845 * Sockets will be automatically closed when the last reference
1846 * is dropped, but you might want to call this function to make sure
1847 * resources are released as early as possible.
1849 * Returns: %TRUE on success, %FALSE on error
1854 g_socket_close (GSocket *socket,
1859 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
1861 if (socket->priv->closed)
1862 return TRUE; /* Multiple close not an error */
1864 if (!check_socket (socket, NULL))
1870 res = closesocket (socket->priv->fd);
1872 res = close (socket->priv->fd);
1876 int errsv = get_socket_errno ();
1881 g_set_error (error, G_IO_ERROR,
1882 socket_io_error_from_errno (errsv),
1883 _("Error closing socket: %s"),
1884 socket_strerror (errsv));
1891 if (socket->priv->event != WSA_INVALID_EVENT)
1893 WSACloseEvent (socket->priv->event);
1894 socket->priv->event = WSA_INVALID_EVENT;
1898 socket->priv->connected = FALSE;
1899 socket->priv->closed = TRUE;
1905 * g_socket_is_closed:
1906 * @socket: a #GSocket
1908 * Checks whether a socket is closed.
1910 * Returns: %TRUE if socket is closed, %FALSE otherwise
1915 g_socket_is_closed (GSocket *socket)
1917 return socket->priv->closed;
1921 /* Broken source, used on errors */
1923 broken_prepare (GSource *source,
1930 broken_check (GSource *source)
1936 broken_dispatch (GSource *source,
1937 GSourceFunc callback,
1943 static GSourceFuncs broken_funcs =
1952 network_events_for_condition (GIOCondition condition)
1956 if (condition & G_IO_IN)
1957 event_mask |= (FD_READ | FD_ACCEPT);
1958 if (condition & G_IO_OUT)
1959 event_mask |= (FD_WRITE | FD_CONNECT);
1960 event_mask |= FD_CLOSE;
1966 ensure_event (GSocket *socket)
1968 if (socket->priv->event == WSA_INVALID_EVENT)
1969 socket->priv->event = WSACreateEvent();
1973 update_select_events (GSocket *socket)
1980 ensure_event (socket);
1983 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
1986 event_mask |= network_events_for_condition (*ptr);
1989 if (event_mask != socket->priv->selected_events)
1991 /* If no events selected, disable event so we can unset
1994 if (event_mask == 0)
1997 event = socket->priv->event;
1999 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
2000 socket->priv->selected_events = event_mask;
2005 add_condition_watch (GSocket *socket,
2006 GIOCondition *condition)
2008 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
2010 socket->priv->requested_conditions =
2011 g_list_prepend (socket->priv->requested_conditions, condition);
2013 update_select_events (socket);
2017 remove_condition_watch (GSocket *socket,
2018 GIOCondition *condition)
2020 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
2022 socket->priv->requested_conditions =
2023 g_list_remove (socket->priv->requested_conditions, condition);
2025 update_select_events (socket);
2029 update_condition (GSocket *socket)
2031 WSANETWORKEVENTS events;
2032 GIOCondition condition;
2034 if (WSAEnumNetworkEvents (socket->priv->fd,
2035 socket->priv->event,
2038 socket->priv->current_events |= events.lNetworkEvents;
2039 if (events.lNetworkEvents & FD_WRITE &&
2040 events.iErrorCode[FD_WRITE_BIT] != 0)
2041 socket->priv->current_errors |= FD_WRITE;
2042 if (events.lNetworkEvents & FD_CONNECT &&
2043 events.iErrorCode[FD_CONNECT_BIT] != 0)
2044 socket->priv->current_errors |= FD_CONNECT;
2048 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
2049 condition |= G_IO_IN;
2051 if (socket->priv->current_events & FD_CLOSE ||
2052 socket->priv->closed)
2053 condition |= G_IO_HUP;
2055 /* Never report both G_IO_OUT and HUP, these are
2056 mutually exclusive (can't write to a closed socket) */
2057 if ((condition & G_IO_HUP) == 0 &&
2058 socket->priv->current_events & FD_WRITE)
2060 if (socket->priv->current_errors & FD_WRITE)
2061 condition |= G_IO_ERR;
2063 condition |= G_IO_OUT;
2067 if (socket->priv->current_events & FD_CONNECT)
2069 if (socket->priv->current_errors & FD_CONNECT)
2070 condition |= (G_IO_HUP | G_IO_ERR);
2072 condition |= G_IO_OUT;
2083 GIOCondition condition;
2084 GCancellable *cancellable;
2085 GPollFD cancel_pollfd;
2086 GIOCondition result_condition;
2090 winsock_prepare (GSource *source,
2093 GWinsockSource *winsock_source = (GWinsockSource *)source;
2094 GIOCondition current_condition;
2096 current_condition = update_condition (winsock_source->socket);
2098 if (g_cancellable_is_cancelled (winsock_source->cancellable))
2100 winsock_source->result_condition = current_condition;
2104 if ((winsock_source->condition & current_condition) != 0)
2106 winsock_source->result_condition = current_condition;
2114 winsock_check (GSource *source)
2116 GWinsockSource *winsock_source = (GWinsockSource *)source;
2117 GIOCondition current_condition;
2119 current_condition = update_condition (winsock_source->socket);
2121 if (g_cancellable_is_cancelled (winsock_source->cancellable))
2123 winsock_source->result_condition = current_condition;
2127 if ((winsock_source->condition & current_condition) != 0)
2129 winsock_source->result_condition = current_condition;
2137 winsock_dispatch (GSource *source,
2138 GSourceFunc callback,
2141 GSocketSourceFunc func = (GSocketSourceFunc)callback;
2142 GWinsockSource *winsock_source = (GWinsockSource *)source;
2144 return (*func) (winsock_source->socket,
2145 winsock_source->result_condition & winsock_source->condition,
2150 winsock_finalize (GSource *source)
2152 GWinsockSource *winsock_source = (GWinsockSource *)source;
2155 socket = winsock_source->socket;
2157 remove_condition_watch (socket, &winsock_source->condition);
2158 g_object_unref (socket);
2160 if (winsock_source->cancellable)
2161 g_object_unref (winsock_source->cancellable);
2164 static GSourceFuncs winsock_funcs =
2173 winsock_source_new (GSocket *socket,
2174 GIOCondition condition,
2175 GCancellable *cancellable)
2178 GWinsockSource *winsock_source;
2180 ensure_event (socket);
2182 if (socket->priv->event == WSA_INVALID_EVENT)
2184 g_warning ("Failed to create WSAEvent");
2185 return g_source_new (&broken_funcs, sizeof (GSource));
2188 condition |= G_IO_HUP | G_IO_ERR;
2190 source = g_source_new (&winsock_funcs, sizeof (GWinsockSource));
2191 winsock_source = (GWinsockSource *)source;
2193 winsock_source->socket = g_object_ref (socket);
2194 winsock_source->condition = condition;
2195 add_condition_watch (socket, &winsock_source->condition);
2199 winsock_source->cancellable = g_object_ref (cancellable);
2200 g_cancellable_make_pollfd (cancellable,
2201 &winsock_source->cancel_pollfd);
2202 g_source_add_poll (source, &winsock_source->cancel_pollfd);
2205 winsock_source->pollfd.fd = (gintptr) socket->priv->event;
2206 winsock_source->pollfd.events = condition;
2207 g_source_add_poll (source, &winsock_source->pollfd);
2214 * g_socket_create_source:
2215 * @socket: a #GSocket
2216 * @condition: a #GIOCondition mask to monitor
2217 * @cancellable: a %GCancellable or %NULL
2219 * Creates a %GSource that can be attached to a %GMainContext to monitor
2220 * for the availibility of the specified @condition on the socket.
2222 * The callback on the source is of the #GSocketSourceFunc type.
2224 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2225 * these conditions will always be reported output if they are true.
2227 * @cancellable if not %NULL can be used to cancel the source, which will
2228 * cause the source to trigger, reporting the current condition (which
2229 * is likely 0 unless cancellation happened at the same time as a
2230 * condition change). You can check for this in the callback using
2231 * g_cancellable_is_cancelled().
2233 * Returns: a newly allocated %GSource, free with g_source_unref().
2238 g_socket_create_source (GSocket *socket,
2239 GIOCondition condition,
2240 GCancellable *cancellable)
2243 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
2246 source = winsock_source_new (socket, condition, cancellable);
2248 source =_g_fd_source_new_with_object (G_OBJECT (socket), socket->priv->fd,
2249 condition, cancellable);
2255 * g_socket_condition_check:
2256 * @socket: a #GSocket
2257 * @condition: a #GIOCondition mask to check
2259 * Checks on the readiness of @socket to perform operations. The
2260 * operations specified in @condition are checked for and masked
2261 * against the currently-satisfied conditions on @socket. The result
2264 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2265 * these conditions will always be set in the output if they are true.
2267 * This call never blocks.
2269 * Returns: the @GIOCondition mask of the current state
2274 g_socket_condition_check (GSocket *socket,
2275 GIOCondition condition)
2277 if (!check_socket (socket, NULL))
2282 GIOCondition current_condition;
2284 condition |= G_IO_ERR | G_IO_HUP;
2286 add_condition_watch (socket, &condition);
2287 current_condition = update_condition (socket);
2288 remove_condition_watch (socket, &condition);
2289 return condition & current_condition;
2295 poll_fd.fd = socket->priv->fd;
2296 poll_fd.events = condition;
2299 result = g_poll (&poll_fd, 1, 0);
2300 while (result == -1 && get_socket_errno () == EINTR);
2302 return poll_fd.revents;
2308 * g_socket_condition_wait:
2309 * @socket: a #GSocket
2310 * @condition: a #GIOCondition mask to wait for
2311 * @cancellable: a #GCancellable, or %NULL
2312 * @error: a #GError pointer, or %NULL
2314 * Waits for @condition to become true on @socket. When the condition
2315 * becomes true, %TRUE is returned.
2317 * If @cancellable is cancelled before the condition becomes true then
2318 * %FALSE is returned and @error, if non-%NULL, is set to %G_IO_ERROR_CANCELLED.
2320 * Returns: %TRUE if the condition was met, %FALSE otherwise
2325 g_socket_condition_wait (GSocket *socket,
2326 GIOCondition condition,
2327 GCancellable *cancellable,
2330 if (!check_socket (socket, error))
2333 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2338 GIOCondition current_condition;
2344 /* Always check these */
2345 condition |= G_IO_ERR | G_IO_HUP;
2347 add_condition_watch (socket, &condition);
2350 events[num_events++] = socket->priv->event;
2354 g_cancellable_make_pollfd (cancellable, &cancel_fd);
2355 events[num_events++] = (WSAEVENT)cancel_fd.fd;
2358 current_condition = update_condition (socket);
2359 while ((condition & current_condition) == 0)
2361 res = WSAWaitForMultipleEvents(num_events, events,
2362 FALSE, WSA_INFINITE, FALSE);
2363 if (res == WSA_WAIT_FAILED)
2365 int errsv = get_socket_errno ();
2367 g_set_error (error, G_IO_ERROR,
2368 socket_io_error_from_errno (errsv),
2369 _("Waiting for socket condition: %s"),
2370 socket_strerror (errsv));
2374 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2377 current_condition = update_condition (socket);
2379 remove_condition_watch (socket, &condition);
2381 return (condition & current_condition) != 0;
2389 poll_fd[0].fd = socket->priv->fd;
2390 poll_fd[0].events = condition;
2395 g_cancellable_make_pollfd (cancellable, &poll_fd[1]);
2400 result = g_poll (poll_fd, num, -1);
2401 while (result == -1 && get_socket_errno () == EINTR);
2403 return cancellable == NULL ||
2404 !g_cancellable_set_error_if_cancelled (cancellable, error);
2410 * g_socket_send_message:
2411 * @socket: a #GSocket
2412 * @address: a #GSocketAddress, or %NULL
2413 * @vectors: an array of #GOutputVector structs
2414 * @num_vectors: the number of elements in @vectors, or -1
2415 * @messages: a pointer to an array of #GSocketControlMessages, or
2417 * @num_messages: number of elements in @messages, or -1.
2418 * @flags: an int containing #GSocketMsgFlags flags
2419 * @error: #GError for error reporting, or %NULL to ignore.
2421 * Send data to @address on @socket. This is the most complicated and
2422 * fully-featured version of this call. For easier use, see
2423 * g_socket_send() and g_socket_send_to().
2425 * If @address is %NULL then the message is sent to the default receiver
2426 * (set by g_socket_connect()).
2428 * @vector must point to an array of #GOutputVector structs and
2429 * @num_vectors must be the length of this array. These structs
2430 * describe the buffers that the sent data will be gathered from.
2431 * If @num_vector is -1, then @vector is assumed to be terminated
2432 * by a #GOutputVector with a %NULL buffer pointer.
2435 * @messages, if non-%NULL, is taken to point to an array of @num_messages
2436 * #GSocketControlMessage instances. These correspond to the control
2437 * messages to be sent on the socket.
2438 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
2441 * @flags modify how the message sent. The commonly available arguments
2442 * for this is available in the #GSocketMsgFlags enum, but the
2443 * values there are the same as the system values, and the flags
2444 * are passed in as-is, so you can pass in system specific flags too.
2446 * If the socket is in blocking mode the call will block until there is
2447 * space for the data in the socket queue. If there is no space available
2448 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2449 * will be returned. To be notified of available space, wait for the %G_IO_OUT
2452 * Note that on Windows you can't rely on a %G_IO_OUT condition
2453 * not producing a %G_IO_ERROR_WOULD_BLOCK error, as this is how Winsock
2454 * write notification works. However, robust apps should always be able to
2455 * handle this since it can easily appear in other cases too.
2457 * On error -1 is returned and @error is set accordingly.
2459 * Returns: Number of bytes read, or -1 on error
2464 g_socket_send_message (GSocket *socket,
2465 GSocketAddress *address,
2466 GOutputVector *vectors,
2468 GSocketControlMessage **messages,
2473 GOutputVector one_vector;
2476 if (!check_socket (socket, error))
2479 if (num_vectors == -1)
2481 for (num_vectors = 0;
2482 vectors[num_vectors].buffer != NULL;
2487 if (num_messages == -1)
2489 for (num_messages = 0;
2490 messages != NULL && messages[num_messages] != NULL;
2495 if (num_vectors == 0)
2499 one_vector.buffer = &zero;
2500 one_vector.size = 1;
2502 vectors = &one_vector;
2513 msg.msg_namelen = g_socket_address_get_native_size (address);
2514 msg.msg_name = g_alloca (msg.msg_namelen);
2515 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
2521 /* this entire expression will be evaluated at compile time */
2522 if (sizeof *msg.msg_iov == sizeof *vectors &&
2523 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2524 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2525 G_STRUCT_OFFSET (GOutputVector, buffer) &&
2526 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2527 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2528 G_STRUCT_OFFSET (GOutputVector, size))
2529 /* ABI is compatible */
2531 msg.msg_iov = (struct iovec *) vectors;
2532 msg.msg_iovlen = num_vectors;
2535 /* ABI is incompatible */
2539 msg.msg_iov = g_newa (struct iovec, num_vectors);
2540 for (i = 0; i < num_vectors; i++)
2542 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
2543 msg.msg_iov[i].iov_len = vectors[i].size;
2545 msg.msg_iovlen = num_vectors;
2551 struct cmsghdr *cmsg;
2554 msg.msg_controllen = 0;
2555 for (i = 0; i < num_messages; i++)
2556 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
2558 msg.msg_control = g_alloca (msg.msg_controllen);
2560 cmsg = CMSG_FIRSTHDR (&msg);
2561 for (i = 0; i < num_messages; i++)
2563 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
2564 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
2565 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
2566 g_socket_control_message_serialize (messages[i],
2568 cmsg = CMSG_NXTHDR (&msg, cmsg);
2570 g_assert (cmsg == NULL);
2575 if (socket->priv->blocking &&
2576 !g_socket_condition_wait (socket,
2577 G_IO_OUT, NULL, error))
2580 result = sendmsg (socket->priv->fd, &msg, flags);
2583 int errsv = get_socket_errno ();
2588 if (socket->priv->blocking &&
2589 (errsv == EWOULDBLOCK ||
2593 g_set_error (error, G_IO_ERROR,
2594 socket_io_error_from_errno (errsv),
2595 _("Error sending message: %s"), socket_strerror (errsv));
2606 struct sockaddr_storage addr;
2613 /* Win32 doesn't support control messages.
2614 Actually this is possible for raw and datagram sockets
2615 via WSASendMessage on Vista or later, but that doesn't
2617 if (num_messages != 0)
2619 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2620 _("GSocketControlMessage not supported on windows"));
2625 bufs = g_newa (WSABUF, num_vectors);
2626 for (i = 0; i < num_vectors; i++)
2628 bufs[i].buf = (char *)vectors[i].buffer;
2629 bufs[i].len = (gulong)vectors[i].size;
2633 addrlen = 0; /* Avoid warning */
2636 addrlen = g_socket_address_get_native_size (address);
2637 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
2643 if (socket->priv->blocking &&
2644 !g_socket_condition_wait (socket,
2645 G_IO_OUT, NULL, error))
2649 result = WSASendTo (socket->priv->fd,
2652 (const struct sockaddr *)&addr, addrlen,
2655 result = WSASend (socket->priv->fd,
2662 int errsv = get_socket_errno ();
2664 if (errsv == WSAEINTR)
2667 if (errsv == WSAEWOULDBLOCK)
2668 win32_unset_event_mask (socket, FD_WRITE);
2670 if (socket->priv->blocking &&
2671 errsv == WSAEWOULDBLOCK)
2674 g_set_error (error, G_IO_ERROR,
2675 socket_io_error_from_errno (errsv),
2676 _("Error sending message: %s"), socket_strerror (errsv));
2689 * g_socket_receive_message:
2690 * @socket: a #GSocket
2691 * @address: a pointer to a #GSocketAddress pointer, or %NULL
2692 * @vectors: an array of #GInputVector structs
2693 * @num_vectors: the number of elements in @vectors, or -1
2694 * @messages: a pointer which will be filled with an array of
2695 * #GSocketControlMessages, or %NULL
2696 * @num_messages: a pointer which will be filled with the number of
2697 * elements in @messages, or %NULL
2698 * @flags: a pointer to an int containing #GSocketMsgFlags flags
2699 * @error: a #GError pointer, or %NULL
2701 * Receive data from a socket. This is the most complicated and
2702 * fully-featured version of this call. For easier use, see
2703 * g_socket_receive() and g_socket_receive_from().
2705 * If @address is non-%NULL then @address will be set equal to the
2706 * source address of the received packet.
2707 * @address is owned by the caller.
2709 * @vector must point to an array of #GInputVector structs and
2710 * @num_vectors must be the length of this array. These structs
2711 * describe the buffers that received data will be scattered into.
2712 * If @num_vector is -1, then @vector is assumed to be terminated
2713 * by a #GInputVector with a %NULL buffer pointer.
2715 * As a special case, if the size of the array is zero (in which case,
2716 * @vectors may of course be %NULL), then a single byte is received
2717 * and discarded. This is to facilitate the common practice of
2718 * sending a single '\0' byte for the purposes of transferring
2721 * @messages, if non-%NULL, is taken to point to a pointer that will
2722 * be set to point to a newly-allocated array of
2723 * #GSocketControlMessage instances. These correspond to the control
2724 * messages received from the kernel, one #GSocketControlMessage per
2725 * message from the kernel. This array is %NULL-terminated and must be
2726 * freed by the caller using g_free().
2728 * @num_messages, if non-%NULL, will be set to the number of control
2729 * messages received.
2731 * If both @messages and @num_messages are non-%NULL, then
2732 * @num_messages gives the number of #GSocketControlMessage instances
2733 * in @messages (ie: not including the %NULL terminator).
2735 * @flags is an in/out parameter. The commonly available arguments
2736 * for this is available in the #GSocketMsgFlags enum, but the
2737 * values there are the same as the system values, and the flags
2738 * are passed in as-is, so you can pass in system specific flags too.
2740 * If the socket is in blocking mode the call will block until there is
2741 * some data to receive or there is an error. If there is no data available
2742 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2743 * will be returned. To be notified of available data, wait for the %G_IO_IN
2746 * On error -1 is returned and @error is set accordingly.
2748 * Returns: Number of bytes read, or -1 on error
2753 g_socket_receive_message (GSocket *socket,
2754 GSocketAddress **address,
2755 GInputVector *vectors,
2757 GSocketControlMessage ***messages,
2762 GInputVector one_vector;
2765 if (!check_socket (socket, error))
2768 if (num_vectors == -1)
2770 for (num_vectors = 0;
2771 vectors[num_vectors].buffer != NULL;
2776 if (num_vectors == 0)
2778 one_vector.buffer = &one_byte;
2779 one_vector.size = 1;
2781 vectors = &one_vector;
2788 struct sockaddr_storage one_sockaddr;
2793 msg.msg_name = &one_sockaddr;
2794 msg.msg_namelen = sizeof (struct sockaddr_storage);
2798 msg.msg_name = NULL;
2799 msg.msg_namelen = 0;
2803 /* this entire expression will be evaluated at compile time */
2804 if (sizeof *msg.msg_iov == sizeof *vectors &&
2805 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2806 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2807 G_STRUCT_OFFSET (GInputVector, buffer) &&
2808 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2809 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2810 G_STRUCT_OFFSET (GInputVector, size))
2811 /* ABI is compatible */
2813 msg.msg_iov = (struct iovec *) vectors;
2814 msg.msg_iovlen = num_vectors;
2817 /* ABI is incompatible */
2821 msg.msg_iov = g_newa (struct iovec, num_vectors);
2822 for (i = 0; i < num_vectors; i++)
2824 msg.msg_iov[i].iov_base = vectors[i].buffer;
2825 msg.msg_iov[i].iov_len = vectors[i].size;
2827 msg.msg_iovlen = num_vectors;
2831 msg.msg_control = g_alloca (2048);
2832 msg.msg_controllen = 2048;
2836 msg.msg_flags = *flags;
2843 if (socket->priv->blocking &&
2844 !g_socket_condition_wait (socket,
2845 G_IO_IN, NULL, error))
2848 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
2852 int errsv = get_socket_errno ();
2857 if (socket->priv->blocking &&
2858 (errsv == EWOULDBLOCK ||
2862 g_set_error (error, G_IO_ERROR,
2863 socket_io_error_from_errno (errsv),
2864 _("Error receiving message: %s"), socket_strerror (errsv));
2871 /* decode address */
2872 if (address != NULL)
2874 if (msg.msg_namelen > 0)
2875 *address = g_socket_address_new_from_native (msg.msg_name,
2881 /* decode control messages */
2883 GSocketControlMessage **my_messages = NULL;
2884 gint allocated = 0, index = 0;
2885 const gchar *scm_pointer;
2886 struct cmsghdr *cmsg;
2889 scm_pointer = (const gchar *) msg.msg_control;
2890 scm_size = msg.msg_controllen;
2892 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
2894 GSocketControlMessage *message;
2896 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
2898 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
2900 if (message == NULL)
2901 /* We've already spewed about the problem in the
2902 deserialization code, so just continue */
2905 if (index == allocated)
2907 /* estimated 99% case: exactly 1 control message */
2908 allocated = MIN (allocated * 2, 1);
2909 my_messages = g_new (GSocketControlMessage *, (allocated + 1));
2913 my_messages[index++] = message;
2917 *num_messages = index;
2921 my_messages[index++] = NULL;
2922 *messages = my_messages;
2928 /* free all those messages we just constructed.
2929 * we have to do it this way if the user ignores the
2930 * messages so that we will close any received fds.
2932 for (i = 0; i < index; i++)
2933 g_object_unref (my_messages[i]);
2934 g_free (my_messages);
2938 /* capture the flags */
2940 *flags = msg.msg_flags;
2946 struct sockaddr_storage addr;
2948 DWORD bytes_received;
2955 bufs = g_newa (WSABUF, num_vectors);
2956 for (i = 0; i < num_vectors; i++)
2958 bufs[i].buf = (char *)vectors[i].buffer;
2959 bufs[i].len = (gulong)vectors[i].size;
2971 if (socket->priv->blocking &&
2972 !g_socket_condition_wait (socket,
2973 G_IO_IN, NULL, error))
2976 addrlen = sizeof addr;
2978 result = WSARecvFrom (socket->priv->fd,
2980 &bytes_received, &win_flags,
2981 (struct sockaddr *)&addr, &addrlen,
2984 result = WSARecv (socket->priv->fd,
2986 &bytes_received, &win_flags,
2990 int errsv = get_socket_errno ();
2992 if (errsv == WSAEINTR)
2995 win32_unset_event_mask (socket, FD_READ);
2997 if (socket->priv->blocking &&
2998 errsv == WSAEWOULDBLOCK)
3001 g_set_error (error, G_IO_ERROR,
3002 socket_io_error_from_errno (errsv),
3003 _("Error receiving message: %s"), socket_strerror (errsv));
3007 win32_unset_event_mask (socket, FD_READ);
3011 /* decode address */
3012 if (address != NULL)
3015 *address = g_socket_address_new_from_native (&addr, addrlen);
3020 /* capture the flags */
3024 return bytes_received;
3029 #define __G_SOCKET_C__
3030 #include "gioaliasdef.c"