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 |
650 G_PARAM_STATIC_STRINGS));
652 g_object_class_install_property (gobject_class, PROP_TYPE,
653 g_param_spec_enum ("type",
655 P_("The sockets type"),
657 G_SOCKET_TYPE_STREAM,
658 G_PARAM_CONSTRUCT_ONLY |
660 G_PARAM_STATIC_STRINGS));
662 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
663 g_param_spec_enum ("protocol",
664 P_("Socket protocol"),
665 P_("The id of the protocol to use, or -1 for unknown"),
666 G_TYPE_SOCKET_PROTOCOL,
667 G_SOCKET_PROTOCOL_UNKNOWN,
668 G_PARAM_CONSTRUCT_ONLY |
670 G_PARAM_STATIC_STRINGS));
672 g_object_class_install_property (gobject_class, PROP_FD,
673 g_param_spec_int ("fd",
674 P_("File descriptor"),
675 P_("The sockets file descriptor"),
679 G_PARAM_CONSTRUCT_ONLY |
681 G_PARAM_STATIC_STRINGS));
683 g_object_class_install_property (gobject_class, PROP_BLOCKING,
684 g_param_spec_boolean ("blocking",
686 P_("Whether or not I/O on this socket is blocking"),
689 G_PARAM_STATIC_STRINGS));
691 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
692 g_param_spec_int ("listen-backlog",
693 P_("Listen backlog"),
694 P_("Outstanding connections in the listen queue"),
699 G_PARAM_STATIC_STRINGS));
701 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
702 g_param_spec_boolean ("keepalive",
703 P_("Keep connection alive"),
704 P_("Keep connection alive by sending periodic pings"),
707 G_PARAM_STATIC_STRINGS));
709 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
710 g_param_spec_object ("local-address",
712 P_("The local address the socket is bound to"),
713 G_TYPE_SOCKET_ADDRESS,
715 G_PARAM_STATIC_STRINGS));
717 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
718 g_param_spec_object ("remote-address",
719 P_("Remote address"),
720 P_("The remote address the socket is connected to"),
721 G_TYPE_SOCKET_ADDRESS,
723 G_PARAM_STATIC_STRINGS));
727 g_socket_initable_iface_init (GInitableIface *iface)
729 iface->init = g_socket_initable_init;
733 g_socket_init (GSocket *socket)
735 socket->priv = G_TYPE_INSTANCE_GET_PRIVATE (socket, G_TYPE_SOCKET, GSocketPrivate);
737 socket->priv->fd = -1;
738 socket->priv->blocking = TRUE;
739 socket->priv->listen_backlog = 10;
740 socket->priv->construct_error = NULL;
742 socket->priv->event = WSA_INVALID_EVENT;
747 g_socket_initable_init (GInitable *initable,
748 GCancellable *cancellable,
753 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
755 socket = G_SOCKET (initable);
757 if (cancellable != NULL)
759 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
760 _("Cancellable initialization not supported"));
764 socket->priv->inited = TRUE;
766 if (socket->priv->construct_error)
769 *error = g_error_copy (socket->priv->construct_error);
779 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
780 * @type: the socket type to use.
781 * @protocol: the id of the protocol to use, or 0 for default.
782 * @error: #GError for error reporting, or %NULL to ignore.
784 * Creates a new #GSocket with the defined family, type and protocol.
785 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
786 * for the family and type is used.
788 * The @protocol is a family and type specific int that specifies what
789 * kind of protocol to use. #GSocketProtocol lists several common ones.
790 * Many families only support one protocol, and use 0 for this, others
791 * support several and using 0 means to use the default protocol for
792 * the family and type.
794 * The protocol id is passed directly to the operating
795 * system, so you can use protocols not listed in #GSocketProtocol if you
796 * know the protocol number used for it.
798 * Returns: a #GSocket or %NULL on error.
799 * Free the returned object with g_object_unref().
804 g_socket_new (GSocketFamily family,
806 GSocketProtocol protocol,
809 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
813 "protocol", protocol,
818 * g_socket_new_from_fd:
819 * @fd: a native socket file descriptor.
820 * @error: #GError for error reporting, or %NULL to ignore.
822 * Creates a new #GSocket from a native file descriptor
823 * or winsock SOCKET handle.
825 * This reads all the settings from the file descriptor so that
826 * all properties should work. Note that the file descriptor
827 * will be set to non-blocking mode, independent on the blocking
828 * mode of the #GSocket.
830 * Returns: a #GSocket or %NULL on error.
831 * Free the returned object with g_object_unref().
836 g_socket_new_from_fd (gint fd,
839 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
846 * g_socket_set_blocking:
847 * @socket: a #GSocket.
848 * @blocking: Whether to use blocking I/O or not.
850 * Sets the blocking mode of the socket. In blocking mode
851 * all operations block until they succeed or there is an error. In
852 * non-blocking mode all functions return results immediately or
853 * with a %G_IO_ERROR_WOULD_BLOCK error.
855 * All sockets are created in blocking mode. However, note that the
856 * platform level socket is always non-blocking, and blocking mode
857 * is a GSocket level feature.
862 g_socket_set_blocking (GSocket *socket,
865 g_return_if_fail (G_IS_SOCKET (socket));
867 blocking = !!blocking;
869 if (socket->priv->blocking == blocking)
872 socket->priv->blocking = blocking;
873 g_object_notify (G_OBJECT (socket), "blocking");
877 * g_socket_get_blocking:
878 * @socket: a #GSocket.
880 * Gets the blocking mode of the socket. For details on blocking I/O,
881 * see g_socket_set_blocking().
883 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
888 g_socket_get_blocking (GSocket *socket)
890 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
892 return socket->priv->blocking;
896 * g_socket_set_keepalive:
897 * @socket: a #GSocket.
898 * @keepalive: Whether to use try to keep the connection alive or not.
900 * Setting @keepalive to %TRUE enables the sending of periodic ping requests
901 * on idle connections in order to keep the connection alive. This is only
902 * useful for connection oriented sockets. The exact period used between
903 * each ping is system and protocol dependent.
905 * Sending keepalive requests like this has a few disadvantages. For instance,
906 * it uses more network bandwidth, and it makes your application more sensitive
907 * to temporary outages in the network (i.e. if a cable is pulled your otherwise
908 * idle connection could be terminated, whereas otherwise it would survive unless
909 * actually used before the cable was reinserted). However, it is sometimes
910 * useful to ensure that connections are eventually terminated if e.g. the
911 * remote side is disconnected, so as to avoid leaking resources forever.
916 g_socket_set_keepalive (GSocket *socket,
921 g_return_if_fail (G_IS_SOCKET (socket));
923 keepalive = !!keepalive;
924 if (socket->priv->keepalive == keepalive)
927 value = (gint) keepalive;
928 if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_KEEPALIVE,
929 (gpointer) &value, sizeof (value)) < 0)
931 int errsv = get_socket_errno ();
932 g_warning ("error setting keepalive: %s", socket_strerror (errsv));
936 socket->priv->keepalive = keepalive;
937 g_object_notify (G_OBJECT (socket), "keepalive");
941 * g_socket_get_keepalive:
942 * @socket: a #GSocket.
944 * Gets the keepalive mode of the socket. For details on this,
945 * see g_socket_set_keepalive().
947 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
952 g_socket_get_keepalive (GSocket *socket)
954 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
956 return socket->priv->keepalive;
960 * g_socket_get_listen_backlog:
961 * @socket: a #GSocket.
963 * Gets the listen backlog setting of the socket. For details on this,
964 * see g_socket_set_listen_backlog().
966 * Returns: the maximum number of pending connections.
971 g_socket_get_listen_backlog (GSocket *socket)
973 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
975 return socket->priv->listen_backlog;
979 * g_socket_set_listen_backlog:
980 * @socket: a #GSocket.
981 * @backlog: the maximum number of pending connections.
983 * Sets the maximum number of outstanding connections allowed
984 * when listening on this socket. If more clients than this are
985 * connecting to the socket and the application is not handling them
986 * on time then the new connections will be refused.
988 * Note that this must be called before g_socket_listen() and has no
989 * effect if called after that.
994 g_socket_set_listen_backlog (GSocket *socket,
997 g_return_if_fail (G_IS_SOCKET (socket));
998 g_return_if_fail (!socket->priv->listening);
1000 if (backlog != socket->priv->listen_backlog)
1002 socket->priv->listen_backlog = backlog;
1003 g_object_notify (G_OBJECT (socket), "listen-backlog");
1008 * g_socket_get_family:
1009 * @socket: a #GSocket.
1011 * Gets the socket family of the socket.
1013 * Returns: a #GSocketFamily
1018 g_socket_get_family (GSocket *socket)
1020 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1022 return socket->priv->family;
1026 * g_socket_get_socket_type:
1027 * @socket: a #GSocket.
1029 * Gets the socket type of the socket.
1031 * Returns: a #GSocketType
1036 g_socket_get_socket_type (GSocket *socket)
1038 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1040 return socket->priv->type;
1044 * g_socket_get_protocol:
1045 * @socket: a #GSocket.
1047 * Gets the socket protocol id the socket was created with.
1048 * In case the protocol is unknown, -1 is returned.
1050 * Returns: a protocol id, or -1 if unknown
1055 g_socket_get_protocol (GSocket *socket)
1057 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1059 return socket->priv->protocol;
1064 * @socket: a #GSocket.
1066 * Returns the underlying OS socket object. On unix this
1067 * is a socket file descriptor, and on windows this is
1068 * a Winsock2 SOCKET handle. This may be useful for
1069 * doing platform specific or otherwise unusual operations
1072 * Returns: the file descriptor of the socket.
1077 g_socket_get_fd (GSocket *socket)
1079 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1081 return socket->priv->fd;
1085 * g_socket_get_local_address:
1086 * @socket: a #GSocket.
1087 * @error: #GError for error reporting, or %NULL to ignore.
1089 * Try to get the local address of a bound socket. This is only
1090 * useful if the socket has been bound to a local address,
1091 * either explicitly or implicitly when connecting.
1093 * Returns: a #GSocketAddress or %NULL on error.
1094 * Free the returned object with g_object_unref().
1099 g_socket_get_local_address (GSocket *socket,
1102 struct sockaddr_storage buffer;
1103 guint32 len = sizeof (buffer);
1105 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1107 if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1109 int errsv = get_socket_errno ();
1110 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1111 _("could not get local address: %s"), socket_strerror (errsv));
1115 return g_socket_address_new_from_native (&buffer, len);
1119 * g_socket_get_remote_address:
1120 * @socket: a #GSocket.
1121 * @error: #GError for error reporting, or %NULL to ignore.
1123 * Try to get the remove address of a connected socket. This is only
1124 * useful for connection oriented sockets that have been connected.
1126 * Returns: a #GSocketAddress or %NULL on error.
1127 * Free the returned object with g_object_unref().
1132 g_socket_get_remote_address (GSocket *socket,
1135 struct sockaddr_storage buffer;
1136 guint32 len = sizeof (buffer);
1138 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1140 if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1142 int errsv = get_socket_errno ();
1143 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1144 _("could not get remote address: %s"), socket_strerror (errsv));
1148 return g_socket_address_new_from_native (&buffer, len);
1152 * g_socket_is_connected:
1153 * @socket: a #GSocket.
1155 * Check whether the socket is connected. This is only useful for
1156 * connection-oriented sockets.
1158 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1163 g_socket_is_connected (GSocket *socket)
1165 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1167 return socket->priv->connected;
1172 * @socket: a #GSocket.
1173 * @error: #GError for error reporting, or %NULL to ignore.
1175 * Marks the socket as a server socket, i.e. a socket that is used
1176 * to accept incoming requests using g_socket_accept().
1178 * Before calling this the socket must be bound to a local address using
1181 * To set the maximum amount of outstanding clients, use
1182 * g_socket_set_listen_backlog().
1184 * Returns: %TRUE on success, %FALSE on error.
1189 g_socket_listen (GSocket *socket,
1192 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1194 if (!check_socket (socket, error))
1197 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1199 int errsv = get_socket_errno ();
1201 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1202 _("could not listen: %s"), socket_strerror (errsv));
1206 socket->priv->listening = TRUE;
1213 * @socket: a #GSocket.
1214 * @address: a #GSocketAddress specifying the local address.
1215 * @allow_reuse: whether to allow reusing this address
1216 * @error: #GError for error reporting, or %NULL to ignore.
1218 * When a socket is created it is attached to an address family, but it
1219 * doesn't have an address in this family. g_socket_bind() assigns the
1220 * address (sometimes called name) of the socket.
1222 * It is generally required to bind to a local address before you can
1223 * receive connections. (See g_socket_listen() and g_socket_accept() ).
1225 * If @allow_reuse is %TRUE this allows the bind call to succeed in some
1226 * situation where it would otherwise return a %G_IO_ERROR_ADDRESS_IN_USE
1227 * error. The main example is for a TCP server socket where there are
1228 * outstanding connections in the WAIT state, which are generally safe
1229 * to ignore. However, setting it to %TRUE doesn't mean the call will
1230 * succeed if there is a socket actively bound to the address.
1232 * In general, pass %TRUE if the socket will be used to accept connections,
1233 * otherwise pass %FALSE.
1235 * Returns: %TRUE on success, %FALSE on error.
1240 g_socket_bind (GSocket *socket,
1241 GSocketAddress *address,
1242 gboolean reuse_address,
1245 struct sockaddr_storage addr;
1247 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1249 if (!check_socket (socket, error))
1252 /* SO_REUSEADDR on windows means something else and is not what we want.
1253 It always allows the unix variant of SO_REUSEADDR anyway */
1258 value = (int) !!reuse_address;
1259 /* Ignore errors here, the only likely error is "not supported", and
1260 this is a "best effort" thing mainly */
1261 setsockopt (socket->priv->fd, SOL_SOCKET, SO_REUSEADDR,
1262 (gpointer) &value, sizeof (value));
1266 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1269 if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1270 g_socket_address_get_native_size (address)) < 0)
1272 int errsv = get_socket_errno ();
1274 G_IO_ERROR, socket_io_error_from_errno (errsv),
1275 _("Error binding to address: %s"), socket_strerror (errsv));
1284 * @socket: a #GSocket.
1285 * @error: #GError for error reporting, or %NULL to ignore.
1287 * Accept incoming connections on a connection-based socket. This removes
1288 * the first outstanding connection request from the listening socket and
1289 * creates a #GSocket object for it.
1291 * The @socket must be bound to a local address with g_socket_bind() and
1292 * must be listening for incoming connections (g_socket_listen()).
1294 * If there are no outstanding connections then the operation will block
1295 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
1296 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
1298 * Returns: a new #GSocket, or %NULL on error.
1299 * Free the returned object with g_object_unref().
1304 g_socket_accept (GSocket *socket,
1307 GSocket *new_socket;
1310 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1312 if (!check_socket (socket, error))
1317 if (socket->priv->blocking &&
1318 !g_socket_condition_wait (socket,
1319 G_IO_IN, NULL, error))
1322 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
1324 int errsv = get_socket_errno ();
1326 win32_unset_event_mask (socket, FD_ACCEPT);
1331 if (socket->priv->blocking)
1333 #ifdef WSAEWOULDBLOCK
1334 if (errsv == WSAEWOULDBLOCK)
1337 if (errsv == EWOULDBLOCK ||
1343 g_set_error (error, G_IO_ERROR,
1344 socket_io_error_from_errno (errsv),
1345 _("Error accepting connection: %s"), socket_strerror (errsv));
1351 win32_unset_event_mask (socket, FD_ACCEPT);
1355 /* The socket inherits the accepting sockets event mask and even object,
1356 we need to remove that */
1357 WSAEventSelect (ret, NULL, 0);
1363 /* We always want to set close-on-exec to protect users. If you
1364 need to so some weird inheritance to exec you can re-enable this
1365 using lower level hacks with g_socket_get_fd(). */
1366 flags = fcntl (ret, F_GETFD, 0);
1368 (flags & FD_CLOEXEC) == 0)
1370 flags |= FD_CLOEXEC;
1371 fcntl (ret, F_SETFD, flags);
1376 new_socket = g_socket_new_from_fd (ret, error);
1377 if (new_socket == NULL)
1386 new_socket->priv->protocol = socket->priv->protocol;
1393 * @socket: a #GSocket.
1394 * @address: a #GSocketAddress specifying the remote address.
1395 * @error: #GError for error reporting, or %NULL to ignore.
1397 * Connect the socket to the specified remote address.
1399 * For connection oriented socket this generally means we attempt to make
1400 * a connection to the @address. For a connection-less socket it sets
1401 * the default address for g_socket_send() and discards all incoming datagrams
1402 * from other sources.
1404 * Generally connection oriented sockets can only connect once, but
1405 * connection-less sockets can connect multiple times to change the
1408 * If the connect call needs to do network I/O it will block, unless
1409 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
1410 * and the user can be notified of the connection finishing by waiting
1411 * for the G_IO_OUT condition. The result of the connection can then be
1412 * checked with g_socket_check_connect_result().
1414 * Returns: %TRUE if connected, %FALSE on error.
1419 g_socket_connect (GSocket *socket,
1420 GSocketAddress *address,
1423 struct sockaddr_storage buffer;
1425 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1427 if (!check_socket (socket, error))
1430 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
1435 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
1436 g_socket_address_get_native_size (address)) < 0)
1438 int errsv = get_socket_errno ();
1444 if (errsv == EINPROGRESS)
1446 if (errsv == WSAEWOULDBLOCK)
1449 if (socket->priv->blocking)
1451 g_socket_condition_wait (socket, G_IO_OUT, NULL, NULL);
1452 if (g_socket_check_connect_result (socket, error))
1455 g_prefix_error (error, _("Error connecting: "));
1458 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
1459 _("Connection in progress"));
1462 g_set_error (error, G_IO_ERROR,
1463 socket_io_error_from_errno (errsv),
1464 _("Error connecting: %s"), socket_strerror (errsv));
1471 win32_unset_event_mask (socket, FD_CONNECT);
1473 socket->priv->connected = TRUE;
1479 * g_socket_check_connect_result:
1480 * @socket: a #GSocket
1481 * @error: #GError for error reporting, or %NULL to ignore.
1483 * Checks and resets the pending connect error for the socket.
1484 * This is used to check for errors when g_socket_connect() is
1485 * used in non-blocking mode.
1487 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
1492 g_socket_check_connect_result (GSocket *socket,
1498 optlen = sizeof (value);
1499 if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
1501 int errsv = get_socket_errno ();
1503 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1504 _("Unable to get pending error: %s"), socket_strerror (errsv));
1510 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
1511 socket_strerror (value));
1519 * @socket: a #GSocket
1520 * @buffer: a buffer to read data into (which should be at least @size
1522 * @size: the number of bytes that will be read from the stream
1523 * @error: #GError for error reporting, or %NULL to ignore.
1525 * Receive data (up to @size bytes) from a socket. This is mainly used by
1526 * connection oriented sockets, it is identical to g_socket_receive_from()
1527 * with @address set to %NULL.
1529 * If a message is too long to fit in @buffer, excess bytes may be discarded
1530 * depending on the type of socket the message is received from.
1532 * If the socket is in blocking mode the call will block until there is
1533 * some data to receive or there is an error. If there is no data available
1534 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1535 * will be returned. To be notified of available data, wait for the %G_IO_IN
1538 * On error -1 is returned and @error is set accordingly.
1540 * Returns: Number of bytes read, or -1 on error
1545 g_socket_receive (GSocket *socket,
1552 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1554 if (!check_socket (socket, error))
1559 if (socket->priv->blocking &&
1560 !g_socket_condition_wait (socket,
1561 G_IO_IN, NULL, error))
1564 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
1566 int errsv = get_socket_errno ();
1571 if (socket->priv->blocking)
1573 #ifdef WSAEWOULDBLOCK
1574 if (errsv == WSAEWOULDBLOCK)
1577 if (errsv == EWOULDBLOCK ||
1583 win32_unset_event_mask (socket, FD_READ);
1585 g_set_error (error, G_IO_ERROR,
1586 socket_io_error_from_errno (errsv),
1587 _("Error receiving data: %s"), socket_strerror (errsv));
1591 win32_unset_event_mask (socket, FD_READ);
1600 * g_socket_receive_from:
1601 * @socket: a #GSocket
1602 * @address: a pointer to a #GSocketAddress pointer, or %NULL
1603 * @buffer: a buffer to read data into (which should be at least @size
1605 * @size: the number of bytes that will be read from the stream
1606 * @error: #GError for error reporting, or %NULL to ignore.
1608 * Receive data (up to @size bytes) from a socket.
1610 * If @address is non-%NULL then @address will be set equal to the
1611 * source address of the received packet.
1612 * @address is owned by the caller.
1614 * If the socket is in blocking mode the call will block until there is
1615 * some data to receive or there is an error. If there is no data available
1616 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1617 * will be returned. To be notified of available data, wait for the %G_IO_IN
1620 * On error -1 is returned and @error is set accordingly.
1622 * Returns: Number of bytes read, or -1 on error
1627 g_socket_receive_from (GSocket *socket,
1628 GSocketAddress **address,
1638 return g_socket_receive_message (socket,
1647 * @socket: a #GSocket
1648 * @buffer: the buffer containing the data to send.
1649 * @size: the number of bytes to send
1650 * @error: #GError for error reporting, or %NULL to ignore.
1652 * Tries to send @size bytes from @buffer on the socket.
1653 * This is mainly used by connection oriented sockets, it is identical
1654 * to g_socket_send_to() with @address set to %NULL.
1656 * If the socket is in blocking mode the call will block until there is
1657 * space for the data in the socket queue. If there is no space available
1658 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1659 * will be returned. To be notified of available space, wait for the
1660 * %G_IO_OUT condition.
1662 * Note that on Windows you can't rely on a %G_IO_OUT condition
1663 * not producing a %G_IO_ERROR_WOULD_BLOCK error, as this is how Winsock
1664 * write notification works. However, robust apps should always be able to
1665 * handle this since it can easily appear in other cases too.
1667 * On error -1 is returned and @error is set accordingly.
1669 * Returns: Number of bytes read, or -1 on error
1674 g_socket_send (GSocket *socket,
1675 const gchar *buffer,
1681 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1683 if (!check_socket (socket, error))
1688 if (socket->priv->blocking &&
1689 !g_socket_condition_wait (socket,
1690 G_IO_OUT, NULL, error))
1693 if ((ret = send (socket->priv->fd, buffer, size, 0)) < 0)
1695 int errsv = get_socket_errno ();
1700 #ifdef WSAEWOULDBLOCK
1701 if (errsv == WSAEWOULDBLOCK)
1702 win32_unset_event_mask (socket, FD_WRITE);
1705 if (socket->priv->blocking)
1707 #ifdef WSAEWOULDBLOCK
1708 if (errsv == WSAEWOULDBLOCK)
1711 if (errsv == EWOULDBLOCK ||
1717 g_set_error (error, G_IO_ERROR,
1718 socket_io_error_from_errno (errsv),
1719 _("Error sending data: %s"), socket_strerror (errsv));
1730 * @socket: a #GSocket
1731 * @address: a #GSocketAddress, or %NULL
1732 * @buffer: the buffer containing the data to send.
1733 * @size: the number of bytes to send
1734 * @error: #GError for error reporting, or %NULL to ignore.
1736 * Tries to send @size bytes from @buffer to @address. If @address is
1737 * %NULL then the message is sent to the default receiver (set by
1738 * g_socket_connect()).
1740 * If the socket is in blocking mode the call will block until there is
1741 * space for the data in the socket queue. If there is no space available
1742 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1743 * will be returned. To be notified of available space, wait for the %G_IO_OUT
1746 * Note that on Windows you can't rely on a %G_IO_OUT condition
1747 * not producing a %G_IO_ERROR_WOULD_BLOCK error, as this is how Winsock
1748 * write notification works. However, robust apps should always be able to
1749 * handle this since it can easily appear in other cases too.
1751 * On error -1 is returned and @error is set accordingly.
1753 * Returns: Number of bytes read, or -1 on error
1758 g_socket_send_to (GSocket *socket,
1759 GSocketAddress *address,
1760 const gchar *buffer,
1769 return g_socket_send_message (socket,
1777 * g_socket_shutdown:
1778 * @socket: a #GSocket
1779 * @shutdown_read: whether to shut down the read side
1780 * @shutdown_write: whether to shut down the write side
1781 * @error: #GError for error reporting, or %NULL to ignore.
1783 * Shut down part of a full-duplex connection.
1785 * If @shutdown_read is %TRUE then the recieving side of the connection
1786 * is shut down, and further reading is disallowed.
1788 * If @shutdown_write is %TRUE then the sending side of the connection
1789 * is shut down, and further writing is disallowed.
1791 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
1793 * One example where this is used is graceful disconnect for TCP connections
1794 * where you close the sending side, then wait for the other side to close
1795 * the connection, thus ensuring that the other side saw all sent data.
1797 * Returns: %TRUE on success, %FALSE on error
1802 g_socket_shutdown (GSocket *socket,
1803 gboolean shutdown_read,
1804 gboolean shutdown_write,
1809 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
1811 if (!check_socket (socket, NULL))
1815 if (!shutdown_read && !shutdown_write)
1819 if (shutdown_read && shutdown_write)
1821 else if (shutdown_read)
1826 if (shutdown_read && shutdown_write)
1828 else if (shutdown_read)
1834 if (shutdown (socket->priv->fd, how) != 0)
1836 int errsv = get_socket_errno ();
1837 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1838 _("Unable to create socket: %s"), socket_strerror (errsv));
1842 if (shutdown_read && shutdown_write)
1843 socket->priv->connected = FALSE;
1850 * @socket: a #GSocket
1851 * @error: #GError for error reporting, or %NULL to ignore.
1853 * Closes the socket, shutting down any active connection.
1855 * Closing a socket does not wait for all outstanding I/O operations
1856 * to finish, so the caller should not rely on them to be guaranteed
1857 * to complete even if the close returns with no error.
1859 * Once the socket is closed, all other operations will return
1860 * %G_IO_ERROR_CLOSED. Closing a stream multiple times will not
1863 * Sockets will be automatically closed when the last reference
1864 * is dropped, but you might want to call this function to make sure
1865 * resources are released as early as possible.
1867 * Returns: %TRUE on success, %FALSE on error
1872 g_socket_close (GSocket *socket,
1877 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
1879 if (socket->priv->closed)
1880 return TRUE; /* Multiple close not an error */
1882 if (!check_socket (socket, NULL))
1888 res = closesocket (socket->priv->fd);
1890 res = close (socket->priv->fd);
1894 int errsv = get_socket_errno ();
1899 g_set_error (error, G_IO_ERROR,
1900 socket_io_error_from_errno (errsv),
1901 _("Error closing socket: %s"),
1902 socket_strerror (errsv));
1909 if (socket->priv->event != WSA_INVALID_EVENT)
1911 WSACloseEvent (socket->priv->event);
1912 socket->priv->event = WSA_INVALID_EVENT;
1916 socket->priv->connected = FALSE;
1917 socket->priv->closed = TRUE;
1923 * g_socket_is_closed:
1924 * @socket: a #GSocket
1926 * Checks whether a socket is closed.
1928 * Returns: %TRUE if socket is closed, %FALSE otherwise
1933 g_socket_is_closed (GSocket *socket)
1935 return socket->priv->closed;
1939 /* Broken source, used on errors */
1941 broken_prepare (GSource *source,
1948 broken_check (GSource *source)
1954 broken_dispatch (GSource *source,
1955 GSourceFunc callback,
1961 static GSourceFuncs broken_funcs =
1970 network_events_for_condition (GIOCondition condition)
1974 if (condition & G_IO_IN)
1975 event_mask |= (FD_READ | FD_ACCEPT);
1976 if (condition & G_IO_OUT)
1977 event_mask |= (FD_WRITE | FD_CONNECT);
1978 event_mask |= FD_CLOSE;
1984 ensure_event (GSocket *socket)
1986 if (socket->priv->event == WSA_INVALID_EVENT)
1987 socket->priv->event = WSACreateEvent();
1991 update_select_events (GSocket *socket)
1998 ensure_event (socket);
2001 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
2004 event_mask |= network_events_for_condition (*ptr);
2007 if (event_mask != socket->priv->selected_events)
2009 /* If no events selected, disable event so we can unset
2012 if (event_mask == 0)
2015 event = socket->priv->event;
2017 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
2018 socket->priv->selected_events = event_mask;
2023 add_condition_watch (GSocket *socket,
2024 GIOCondition *condition)
2026 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
2028 socket->priv->requested_conditions =
2029 g_list_prepend (socket->priv->requested_conditions, condition);
2031 update_select_events (socket);
2035 remove_condition_watch (GSocket *socket,
2036 GIOCondition *condition)
2038 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
2040 socket->priv->requested_conditions =
2041 g_list_remove (socket->priv->requested_conditions, condition);
2043 update_select_events (socket);
2047 update_condition (GSocket *socket)
2049 WSANETWORKEVENTS events;
2050 GIOCondition condition;
2052 if (WSAEnumNetworkEvents (socket->priv->fd,
2053 socket->priv->event,
2056 socket->priv->current_events |= events.lNetworkEvents;
2057 if (events.lNetworkEvents & FD_WRITE &&
2058 events.iErrorCode[FD_WRITE_BIT] != 0)
2059 socket->priv->current_errors |= FD_WRITE;
2060 if (events.lNetworkEvents & FD_CONNECT &&
2061 events.iErrorCode[FD_CONNECT_BIT] != 0)
2062 socket->priv->current_errors |= FD_CONNECT;
2066 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
2067 condition |= G_IO_IN;
2069 if (socket->priv->current_events & FD_CLOSE ||
2070 socket->priv->closed)
2071 condition |= G_IO_HUP;
2073 /* Never report both G_IO_OUT and HUP, these are
2074 mutually exclusive (can't write to a closed socket) */
2075 if ((condition & G_IO_HUP) == 0 &&
2076 socket->priv->current_events & FD_WRITE)
2078 if (socket->priv->current_errors & FD_WRITE)
2079 condition |= G_IO_ERR;
2081 condition |= G_IO_OUT;
2085 if (socket->priv->current_events & FD_CONNECT)
2087 if (socket->priv->current_errors & FD_CONNECT)
2088 condition |= (G_IO_HUP | G_IO_ERR);
2090 condition |= G_IO_OUT;
2101 GIOCondition condition;
2102 GCancellable *cancellable;
2103 GPollFD cancel_pollfd;
2104 GIOCondition result_condition;
2108 winsock_prepare (GSource *source,
2111 GWinsockSource *winsock_source = (GWinsockSource *)source;
2112 GIOCondition current_condition;
2114 current_condition = update_condition (winsock_source->socket);
2116 if (g_cancellable_is_cancelled (winsock_source->cancellable))
2118 winsock_source->result_condition = current_condition;
2122 if ((winsock_source->condition & current_condition) != 0)
2124 winsock_source->result_condition = current_condition;
2132 winsock_check (GSource *source)
2134 GWinsockSource *winsock_source = (GWinsockSource *)source;
2135 GIOCondition current_condition;
2137 current_condition = update_condition (winsock_source->socket);
2139 if (g_cancellable_is_cancelled (winsock_source->cancellable))
2141 winsock_source->result_condition = current_condition;
2145 if ((winsock_source->condition & current_condition) != 0)
2147 winsock_source->result_condition = current_condition;
2155 winsock_dispatch (GSource *source,
2156 GSourceFunc callback,
2159 GSocketSourceFunc func = (GSocketSourceFunc)callback;
2160 GWinsockSource *winsock_source = (GWinsockSource *)source;
2162 return (*func) (winsock_source->socket,
2163 winsock_source->result_condition & winsock_source->condition,
2168 winsock_finalize (GSource *source)
2170 GWinsockSource *winsock_source = (GWinsockSource *)source;
2173 socket = winsock_source->socket;
2175 remove_condition_watch (socket, &winsock_source->condition);
2176 g_object_unref (socket);
2178 if (winsock_source->cancellable)
2179 g_object_unref (winsock_source->cancellable);
2182 static GSourceFuncs winsock_funcs =
2191 winsock_source_new (GSocket *socket,
2192 GIOCondition condition,
2193 GCancellable *cancellable)
2196 GWinsockSource *winsock_source;
2198 ensure_event (socket);
2200 if (socket->priv->event == WSA_INVALID_EVENT)
2202 g_warning ("Failed to create WSAEvent");
2203 return g_source_new (&broken_funcs, sizeof (GSource));
2206 condition |= G_IO_HUP | G_IO_ERR;
2208 source = g_source_new (&winsock_funcs, sizeof (GWinsockSource));
2209 winsock_source = (GWinsockSource *)source;
2211 winsock_source->socket = g_object_ref (socket);
2212 winsock_source->condition = condition;
2213 add_condition_watch (socket, &winsock_source->condition);
2217 winsock_source->cancellable = g_object_ref (cancellable);
2218 g_cancellable_make_pollfd (cancellable,
2219 &winsock_source->cancel_pollfd);
2220 g_source_add_poll (source, &winsock_source->cancel_pollfd);
2223 winsock_source->pollfd.fd = (gintptr) socket->priv->event;
2224 winsock_source->pollfd.events = condition;
2225 g_source_add_poll (source, &winsock_source->pollfd);
2232 * g_socket_create_source:
2233 * @socket: a #GSocket
2234 * @condition: a #GIOCondition mask to monitor
2235 * @cancellable: a %GCancellable or %NULL
2237 * Creates a %GSource that can be attached to a %GMainContext to monitor
2238 * for the availibility of the specified @condition on the socket.
2240 * The callback on the source is of the #GSocketSourceFunc type.
2242 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2243 * these conditions will always be reported output if they are true.
2245 * @cancellable if not %NULL can be used to cancel the source, which will
2246 * cause the source to trigger, reporting the current condition (which
2247 * is likely 0 unless cancellation happened at the same time as a
2248 * condition change). You can check for this in the callback using
2249 * g_cancellable_is_cancelled().
2251 * Returns: a newly allocated %GSource, free with g_source_unref().
2256 g_socket_create_source (GSocket *socket,
2257 GIOCondition condition,
2258 GCancellable *cancellable)
2261 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
2264 source = winsock_source_new (socket, condition, cancellable);
2266 source =_g_fd_source_new_with_object (G_OBJECT (socket), socket->priv->fd,
2267 condition, cancellable);
2273 * g_socket_condition_check:
2274 * @socket: a #GSocket
2275 * @condition: a #GIOCondition mask to check
2277 * Checks on the readiness of @socket to perform operations.
2278 * The operations specified in @condition are checked for and masked
2279 * against the currently-satisfied conditions on @socket. The result
2282 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2283 * these conditions will always be set in the output if they are true.
2285 * This call never blocks.
2287 * Returns: the @GIOCondition mask of the current state
2292 g_socket_condition_check (GSocket *socket,
2293 GIOCondition condition)
2295 if (!check_socket (socket, NULL))
2300 GIOCondition current_condition;
2302 condition |= G_IO_ERR | G_IO_HUP;
2304 add_condition_watch (socket, &condition);
2305 current_condition = update_condition (socket);
2306 remove_condition_watch (socket, &condition);
2307 return condition & current_condition;
2313 poll_fd.fd = socket->priv->fd;
2314 poll_fd.events = condition;
2317 result = g_poll (&poll_fd, 1, 0);
2318 while (result == -1 && get_socket_errno () == EINTR);
2320 return poll_fd.revents;
2326 * g_socket_condition_wait:
2327 * @socket: a #GSocket
2328 * @condition: a #GIOCondition mask to wait for
2329 * @cancellable: a #GCancellable, or %NULL
2330 * @error: a #GError pointer, or %NULL
2332 * Waits for @condition to become true on @socket. When the condition
2333 * is met, %TRUE is returned.
2335 * If @cancellable is cancelled before the condition is met then %FALSE
2336 * is returned and @error, if non-%NULL, is set to %G_IO_ERROR_CANCELLED.
2338 * Returns: %TRUE if the condition was met, %FALSE otherwise
2343 g_socket_condition_wait (GSocket *socket,
2344 GIOCondition condition,
2345 GCancellable *cancellable,
2348 if (!check_socket (socket, error))
2351 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2356 GIOCondition current_condition;
2362 /* Always check these */
2363 condition |= G_IO_ERR | G_IO_HUP;
2365 add_condition_watch (socket, &condition);
2368 events[num_events++] = socket->priv->event;
2372 g_cancellable_make_pollfd (cancellable, &cancel_fd);
2373 events[num_events++] = (WSAEVENT)cancel_fd.fd;
2376 current_condition = update_condition (socket);
2377 while ((condition & current_condition) == 0)
2379 res = WSAWaitForMultipleEvents(num_events, events,
2380 FALSE, WSA_INFINITE, FALSE);
2381 if (res == WSA_WAIT_FAILED)
2383 int errsv = get_socket_errno ();
2385 g_set_error (error, G_IO_ERROR,
2386 socket_io_error_from_errno (errsv),
2387 _("Waiting for socket condition: %s"),
2388 socket_strerror (errsv));
2392 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2395 current_condition = update_condition (socket);
2397 remove_condition_watch (socket, &condition);
2399 return (condition & current_condition) != 0;
2407 poll_fd[0].fd = socket->priv->fd;
2408 poll_fd[0].events = condition;
2413 g_cancellable_make_pollfd (cancellable, &poll_fd[1]);
2418 result = g_poll (poll_fd, num, -1);
2419 while (result == -1 && get_socket_errno () == EINTR);
2421 return cancellable == NULL ||
2422 !g_cancellable_set_error_if_cancelled (cancellable, error);
2428 * g_socket_send_message:
2429 * @socket: a #GSocket
2430 * @address: a #GSocketAddress, or %NULL
2431 * @vectors: an array of #GOutputVector structs
2432 * @num_vectors: the number of elements in @vectors, or -1
2433 * @messages: a pointer to an array of #GSocketControlMessages, or
2435 * @num_messages: number of elements in @messages, or -1.
2436 * @flags: an int containing #GSocketMsgFlags flags
2437 * @error: #GError for error reporting, or %NULL to ignore.
2439 * Send data to @address on @socket. This is the most complicated and
2440 * fully-featured version of this call. For easier use, see
2441 * g_socket_send() and g_socket_send_to().
2443 * If @address is %NULL then the message is sent to the default receiver
2444 * (set by g_socket_connect()).
2446 * @vector must point to an array of #GOutputVector structs and
2447 * @num_vectors must be the length of this array. These structs
2448 * describe the buffers that the sent data will be gathered from.
2449 * If @num_vector is -1, then @vector is assumed to be terminated
2450 * by a #GOutputVector with a %NULL buffer pointer.
2452 * @messages, if non-%NULL, is taken to point to an array of @num_messages
2453 * #GSocketControlMessage instances. These correspond to the control
2454 * messages to be sent on the socket.
2455 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
2458 * @flags modify how the message sent. The commonly available arguments
2459 * for this is available in the #GSocketMsgFlags enum, but the
2460 * values there are the same as the system values, and the flags
2461 * are passed in as-is, so you can pass in system specific flags too.
2463 * If the socket is in blocking mode the call will block until there is
2464 * space for the data in the socket queue. If there is no space available
2465 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2466 * will be returned. To be notified of available space, wait for the %G_IO_OUT
2469 * Note that on Windows you can't rely on a %G_IO_OUT condition
2470 * not producing a %G_IO_ERROR_WOULD_BLOCK error, as this is how Winsock
2471 * write notification works. However, robust apps should always be able to
2472 * handle this since it can easily appear in other cases too.
2474 * On error -1 is returned and @error is set accordingly.
2476 * Returns: Number of bytes read, or -1 on error
2481 g_socket_send_message (GSocket *socket,
2482 GSocketAddress *address,
2483 GOutputVector *vectors,
2485 GSocketControlMessage **messages,
2490 GOutputVector one_vector;
2493 if (!check_socket (socket, error))
2496 if (num_vectors == -1)
2498 for (num_vectors = 0;
2499 vectors[num_vectors].buffer != NULL;
2504 if (num_messages == -1)
2506 for (num_messages = 0;
2507 messages != NULL && messages[num_messages] != NULL;
2512 if (num_vectors == 0)
2516 one_vector.buffer = &zero;
2517 one_vector.size = 1;
2519 vectors = &one_vector;
2530 msg.msg_namelen = g_socket_address_get_native_size (address);
2531 msg.msg_name = g_alloca (msg.msg_namelen);
2532 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
2538 /* this entire expression will be evaluated at compile time */
2539 if (sizeof *msg.msg_iov == sizeof *vectors &&
2540 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2541 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2542 G_STRUCT_OFFSET (GOutputVector, buffer) &&
2543 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2544 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2545 G_STRUCT_OFFSET (GOutputVector, size))
2546 /* ABI is compatible */
2548 msg.msg_iov = (struct iovec *) vectors;
2549 msg.msg_iovlen = num_vectors;
2552 /* ABI is incompatible */
2556 msg.msg_iov = g_newa (struct iovec, num_vectors);
2557 for (i = 0; i < num_vectors; i++)
2559 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
2560 msg.msg_iov[i].iov_len = vectors[i].size;
2562 msg.msg_iovlen = num_vectors;
2568 struct cmsghdr *cmsg;
2571 msg.msg_controllen = 0;
2572 for (i = 0; i < num_messages; i++)
2573 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
2575 msg.msg_control = g_alloca (msg.msg_controllen);
2577 cmsg = CMSG_FIRSTHDR (&msg);
2578 for (i = 0; i < num_messages; i++)
2580 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
2581 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
2582 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
2583 g_socket_control_message_serialize (messages[i],
2585 cmsg = CMSG_NXTHDR (&msg, cmsg);
2587 g_assert (cmsg == NULL);
2592 if (socket->priv->blocking &&
2593 !g_socket_condition_wait (socket,
2594 G_IO_OUT, NULL, error))
2597 result = sendmsg (socket->priv->fd, &msg, flags);
2600 int errsv = get_socket_errno ();
2605 if (socket->priv->blocking &&
2606 (errsv == EWOULDBLOCK ||
2610 g_set_error (error, G_IO_ERROR,
2611 socket_io_error_from_errno (errsv),
2612 _("Error sending message: %s"), socket_strerror (errsv));
2623 struct sockaddr_storage addr;
2630 /* Win32 doesn't support control messages.
2631 Actually this is possible for raw and datagram sockets
2632 via WSASendMessage on Vista or later, but that doesn't
2634 if (num_messages != 0)
2636 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2637 _("GSocketControlMessage not supported on windows"));
2642 bufs = g_newa (WSABUF, num_vectors);
2643 for (i = 0; i < num_vectors; i++)
2645 bufs[i].buf = (char *)vectors[i].buffer;
2646 bufs[i].len = (gulong)vectors[i].size;
2650 addrlen = 0; /* Avoid warning */
2653 addrlen = g_socket_address_get_native_size (address);
2654 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
2660 if (socket->priv->blocking &&
2661 !g_socket_condition_wait (socket,
2662 G_IO_OUT, NULL, error))
2666 result = WSASendTo (socket->priv->fd,
2669 (const struct sockaddr *)&addr, addrlen,
2672 result = WSASend (socket->priv->fd,
2679 int errsv = get_socket_errno ();
2681 if (errsv == WSAEINTR)
2684 if (errsv == WSAEWOULDBLOCK)
2685 win32_unset_event_mask (socket, FD_WRITE);
2687 if (socket->priv->blocking &&
2688 errsv == WSAEWOULDBLOCK)
2691 g_set_error (error, G_IO_ERROR,
2692 socket_io_error_from_errno (errsv),
2693 _("Error sending message: %s"), socket_strerror (errsv));
2706 * g_socket_receive_message:
2707 * @socket: a #GSocket
2708 * @address: a pointer to a #GSocketAddress pointer, or %NULL
2709 * @vectors: an array of #GInputVector structs
2710 * @num_vectors: the number of elements in @vectors, or -1
2711 * @messages: a pointer which will be filled with an array of
2712 * #GSocketControlMessages, or %NULL
2713 * @num_messages: a pointer which will be filled with the number of
2714 * elements in @messages, or %NULL
2715 * @flags: a pointer to an int containing #GSocketMsgFlags flags
2716 * @error: a #GError pointer, or %NULL
2718 * Receive data from a socket. This is the most complicated and
2719 * fully-featured version of this call. For easier use, see
2720 * g_socket_receive() and g_socket_receive_from().
2722 * If @address is non-%NULL then @address will be set equal to the
2723 * source address of the received packet.
2724 * @address is owned by the caller.
2726 * @vector must point to an array of #GInputVector structs and
2727 * @num_vectors must be the length of this array. These structs
2728 * describe the buffers that received data will be scattered into.
2729 * If @num_vector is -1, then @vector is assumed to be terminated
2730 * by a #GInputVector with a %NULL buffer pointer.
2732 * As a special case, if the size of the array is zero (in which case,
2733 * @vectors may of course be %NULL), then a single byte is received
2734 * and discarded. This is to facilitate the common practice of
2735 * sending a single '\0' byte for the purposes of transferring
2738 * @messages, if non-%NULL, is taken to point to a pointer that will
2739 * be set to point to a newly-allocated array of
2740 * #GSocketControlMessage instances. These correspond to the control
2741 * messages received from the kernel, one #GSocketControlMessage per
2742 * message from the kernel. This array is %NULL-terminated and must be
2743 * freed by the caller using g_free().
2745 * @num_messages, if non-%NULL, will be set to the number of control
2746 * messages received.
2748 * If both @messages and @num_messages are non-%NULL, then
2749 * @num_messages gives the number of #GSocketControlMessage instances
2750 * in @messages (ie: not including the %NULL terminator).
2752 * @flags is an in/out parameter. The commonly available arguments
2753 * for this is available in the #GSocketMsgFlags enum, but the
2754 * values there are the same as the system values, and the flags
2755 * are passed in as-is, so you can pass in system specific flags too.
2757 * If the socket is in blocking mode the call will block until there is
2758 * some data to receive or there is an error. If there is no data available
2759 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2760 * will be returned. To be notified of available data, wait for the %G_IO_IN
2763 * On error -1 is returned and @error is set accordingly.
2765 * Returns: Number of bytes read, or -1 on error
2770 g_socket_receive_message (GSocket *socket,
2771 GSocketAddress **address,
2772 GInputVector *vectors,
2774 GSocketControlMessage ***messages,
2779 GInputVector one_vector;
2782 if (!check_socket (socket, error))
2785 if (num_vectors == -1)
2787 for (num_vectors = 0;
2788 vectors[num_vectors].buffer != NULL;
2793 if (num_vectors == 0)
2795 one_vector.buffer = &one_byte;
2796 one_vector.size = 1;
2798 vectors = &one_vector;
2805 struct sockaddr_storage one_sockaddr;
2810 msg.msg_name = &one_sockaddr;
2811 msg.msg_namelen = sizeof (struct sockaddr_storage);
2815 msg.msg_name = NULL;
2816 msg.msg_namelen = 0;
2820 /* this entire expression will be evaluated at compile time */
2821 if (sizeof *msg.msg_iov == sizeof *vectors &&
2822 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2823 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2824 G_STRUCT_OFFSET (GInputVector, buffer) &&
2825 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2826 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2827 G_STRUCT_OFFSET (GInputVector, size))
2828 /* ABI is compatible */
2830 msg.msg_iov = (struct iovec *) vectors;
2831 msg.msg_iovlen = num_vectors;
2834 /* ABI is incompatible */
2838 msg.msg_iov = g_newa (struct iovec, num_vectors);
2839 for (i = 0; i < num_vectors; i++)
2841 msg.msg_iov[i].iov_base = vectors[i].buffer;
2842 msg.msg_iov[i].iov_len = vectors[i].size;
2844 msg.msg_iovlen = num_vectors;
2848 msg.msg_control = g_alloca (2048);
2849 msg.msg_controllen = 2048;
2853 msg.msg_flags = *flags;
2860 if (socket->priv->blocking &&
2861 !g_socket_condition_wait (socket,
2862 G_IO_IN, NULL, error))
2865 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
2869 int errsv = get_socket_errno ();
2874 if (socket->priv->blocking &&
2875 (errsv == EWOULDBLOCK ||
2879 g_set_error (error, G_IO_ERROR,
2880 socket_io_error_from_errno (errsv),
2881 _("Error receiving message: %s"), socket_strerror (errsv));
2888 /* decode address */
2889 if (address != NULL)
2891 if (msg.msg_namelen > 0)
2892 *address = g_socket_address_new_from_native (msg.msg_name,
2898 /* decode control messages */
2900 GSocketControlMessage **my_messages = NULL;
2901 gint allocated = 0, index = 0;
2902 const gchar *scm_pointer;
2903 struct cmsghdr *cmsg;
2906 scm_pointer = (const gchar *) msg.msg_control;
2907 scm_size = msg.msg_controllen;
2909 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
2911 GSocketControlMessage *message;
2913 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
2915 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
2917 if (message == NULL)
2918 /* We've already spewed about the problem in the
2919 deserialization code, so just continue */
2922 if (index == allocated)
2924 /* estimated 99% case: exactly 1 control message */
2925 allocated = MIN (allocated * 2, 1);
2926 my_messages = g_new (GSocketControlMessage *, (allocated + 1));
2930 my_messages[index++] = message;
2934 *num_messages = index;
2938 my_messages[index++] = NULL;
2939 *messages = my_messages;
2945 /* free all those messages we just constructed.
2946 * we have to do it this way if the user ignores the
2947 * messages so that we will close any received fds.
2949 for (i = 0; i < index; i++)
2950 g_object_unref (my_messages[i]);
2951 g_free (my_messages);
2955 /* capture the flags */
2957 *flags = msg.msg_flags;
2963 struct sockaddr_storage addr;
2965 DWORD bytes_received;
2972 bufs = g_newa (WSABUF, num_vectors);
2973 for (i = 0; i < num_vectors; i++)
2975 bufs[i].buf = (char *)vectors[i].buffer;
2976 bufs[i].len = (gulong)vectors[i].size;
2988 if (socket->priv->blocking &&
2989 !g_socket_condition_wait (socket,
2990 G_IO_IN, NULL, error))
2993 addrlen = sizeof addr;
2995 result = WSARecvFrom (socket->priv->fd,
2997 &bytes_received, &win_flags,
2998 (struct sockaddr *)&addr, &addrlen,
3001 result = WSARecv (socket->priv->fd,
3003 &bytes_received, &win_flags,
3007 int errsv = get_socket_errno ();
3009 if (errsv == WSAEINTR)
3012 win32_unset_event_mask (socket, FD_READ);
3014 if (socket->priv->blocking &&
3015 errsv == WSAEWOULDBLOCK)
3018 g_set_error (error, G_IO_ERROR,
3019 socket_io_error_from_errno (errsv),
3020 _("Error receiving message: %s"), socket_strerror (errsv));
3024 win32_unset_event_mask (socket, FD_READ);
3028 /* decode address */
3029 if (address != NULL)
3032 *address = g_socket_address_new_from_native (&addr, addrlen);
3037 /* capture the flags */
3041 return bytes_received;
3046 #define __G_SOCKET_C__
3047 #include "gioaliasdef.c"