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>
42 #include "gcancellable.h"
43 #include "gioenumtypes.h"
44 #include "ginitable.h"
45 #include "gasynchelper.h"
49 #include "gnetworkingprivate.h"
56 * @short_description: Low-level socket object
58 * @see_also: #GInitable
60 * A #GSocket is a low-level networking primitive. It is a more or less
61 * direct mapping of the BSD socket API in a portable GObject based API.
62 * It supports both the UNIX socket implementations and winsock2 on Windows.
64 * #GSocket is the platform independent base upon which the higher level
65 * network primitives are based. Applications are not typically meant to
66 * use it directly, but rather through classes like #GSocketClient,
67 * #GSocketService and #GSocketConnection. However there may be cases where
68 * direct use of #GSocket is useful.
70 * #GSocket implements the #GInitable interface, so if it is manually constructed
71 * by e.g. g_object_new() you must call g_initable_init() and check the
72 * results before using the object. This is done automatically in
73 * g_socket_new() and g_socket_new_from_fd(), so these functions can return
76 * Sockets operate in two general modes, blocking or non-blocking. When
77 * in blocking mode all operations block until the requested operation
78 * is finished or there is an error. In non-blocking mode all calls that
79 * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
80 * To know when a call would successfully run you can call g_socket_condition_check(),
81 * or g_socket_condition_wait(). You can also use g_socket_create_source() and
82 * attach it to a #GMainContext to get callbacks when I/O is possible.
83 * Note that all sockets are always set to non blocking mode in the system, and
84 * blocking mode is emulated in GSocket.
86 * When working in non-blocking mode applications should always be able to
87 * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
88 * function said that I/O was possible. This can easily happen in case
89 * of a race condition in the application, but it can also happen for other
90 * reasons. For instance, on Windows a socket is always seen as writable
91 * until a write returns %G_IO_ERROR_WOULD_BLOCK.
93 * #GSocket<!-- -->s can be either connection oriented or datagram based.
94 * For connection oriented types you must first establish a connection by
95 * either connecting to an address or accepting a connection from another
96 * address. For connectionless socket types the target/source address is
97 * specified or received in each I/O operation.
99 * All socket file descriptors are set to be close-on-exec.
101 * Note that creating a #GSocket causes the signal %SIGPIPE to be
102 * ignored for the remainder of the program. If you are writing a
103 * command-line utility that uses #GSocket, you may need to take into
104 * account the fact that your program will not automatically be killed
105 * if it tries to write to %stdout after it has been closed.
110 static void g_socket_initable_iface_init (GInitableIface *iface);
111 static gboolean g_socket_initable_init (GInitable *initable,
112 GCancellable *cancellable,
115 G_DEFINE_TYPE_WITH_CODE (GSocket, g_socket, G_TYPE_OBJECT,
116 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
117 g_socket_initable_iface_init));
133 struct _GSocketPrivate
135 GSocketFamily family;
137 GSocketProtocol protocol;
140 GError *construct_error;
152 GList *requested_conditions; /* list of requested GIOCondition * */
157 get_socket_errno (void)
162 return WSAGetLastError ();
167 socket_io_error_from_errno (int err)
170 return g_io_error_from_errno (err);
175 return G_IO_ERROR_ADDRESS_IN_USE;
177 return G_IO_ERROR_WOULD_BLOCK;
179 return G_IO_ERROR_PERMISSION_DENIED;
180 case WSA_INVALID_HANDLE:
181 case WSA_INVALID_PARAMETER:
184 return G_IO_ERROR_INVALID_ARGUMENT;
185 case WSAEPROTONOSUPPORT:
186 return G_IO_ERROR_NOT_SUPPORTED;
188 return G_IO_ERROR_CANCELLED;
189 case WSAESOCKTNOSUPPORT:
191 case WSAEPFNOSUPPORT:
192 case WSAEAFNOSUPPORT:
193 return G_IO_ERROR_NOT_SUPPORTED;
195 return G_IO_ERROR_FAILED;
201 socket_strerror (int err)
204 return g_strerror (err);
206 static GStaticPrivate msg_private = G_STATIC_PRIVATE_INIT;
209 buf = g_static_private_get (&msg_private);
212 buf = g_new (gchar, 128);
213 g_static_private_set (&msg_private, buf, g_free);
216 msg = g_win32_error_message (err);
217 strncpy (buf, msg, 128);
224 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
226 _win32_unset_event_mask (GSocket *socket, int mask)
228 socket->priv->current_events &= ~mask;
229 socket->priv->current_errors &= ~mask;
232 #define win32_unset_event_mask(_socket, _mask)
236 set_fd_nonblocking (int fd)
245 if ((arg = fcntl (fd, F_GETFL, NULL)) < 0)
247 g_warning ("Error getting socket status flags: %s", socket_strerror (errno));
251 arg = arg | O_NONBLOCK;
253 if (fcntl (fd, F_SETFL, arg) < 0)
254 g_warning ("Error setting socket status flags: %s", socket_strerror (errno));
258 if (ioctlsocket (fd, FIONBIO, &arg) == SOCKET_ERROR)
260 int errsv = get_socket_errno ();
261 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
267 check_socket (GSocket *socket,
270 if (!socket->priv->inited)
272 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
273 _("Invalid socket, not initialized"));
277 if (socket->priv->construct_error)
279 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
280 _("Invalid socket, initialization failed due to: %s"),
281 socket->priv->construct_error->message);
285 if (socket->priv->closed)
287 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
288 _("Socket is already closed"));
295 g_socket_details_from_fd (GSocket *socket)
297 struct sockaddr_storage address;
309 fd = socket->priv->fd;
310 optlen = sizeof value;
311 if (getsockopt (fd, SOL_SOCKET, SO_TYPE, (void *)&value, &optlen) != 0)
313 errsv = get_socket_errno ();
324 /* programmer error */
325 g_error ("creating GSocket from fd %d: %s\n",
326 fd, socket_strerror (errsv));
334 g_assert (optlen == sizeof value);
338 socket->priv->type = G_SOCKET_TYPE_STREAM;
342 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
346 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
350 socket->priv->type = G_SOCKET_TYPE_INVALID;
354 addrlen = sizeof address;
355 if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
357 errsv = get_socket_errno ();
361 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
362 sizeof address.ss_family <= addrlen);
363 switch (address.ss_family)
365 case G_SOCKET_FAMILY_IPV4:
366 case G_SOCKET_FAMILY_IPV6:
367 case G_SOCKET_FAMILY_UNIX:
368 socket->priv->family = address.ss_family;
372 socket->priv->family = G_SOCKET_FAMILY_INVALID;
376 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
378 addrlen = sizeof address;
379 if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
380 socket->priv->connected = TRUE;
383 optlen = sizeof bool_val;
384 if (getsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
385 (void *)&bool_val, &optlen) == 0)
387 g_assert (optlen == sizeof bool_val);
388 socket->priv->keepalive = !!bool_val;
392 /* Can't read, maybe not supported, assume FALSE */
393 socket->priv->keepalive = FALSE;
399 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
400 socket_io_error_from_errno (errsv),
401 _("creating GSocket from fd: %s"),
402 socket_strerror (errsv));
406 g_socket_create_socket (GSocketFamily family,
416 case G_SOCKET_TYPE_STREAM:
417 native_type = SOCK_STREAM;
420 case G_SOCKET_TYPE_DATAGRAM:
421 native_type = SOCK_DGRAM;
424 case G_SOCKET_TYPE_SEQPACKET:
425 native_type = SOCK_SEQPACKET;
429 g_assert_not_reached ();
434 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
435 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
440 native_type |= SOCK_CLOEXEC;
442 fd = socket (family, native_type, protocol);
446 int errsv = get_socket_errno ();
448 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
449 _("Unable to create socket: %s"), socket_strerror (errsv));
456 /* We always want to set close-on-exec to protect users. If you
457 need to so some weird inheritance to exec you can re-enable this
458 using lower level hacks with g_socket_get_fd(). */
459 flags = fcntl (fd, F_GETFD, 0);
461 (flags & FD_CLOEXEC) == 0)
464 fcntl (fd, F_SETFD, flags);
473 g_socket_constructed (GObject *object)
475 GSocket *socket = G_SOCKET (object);
477 if (socket->priv->fd >= 0)
478 /* create socket->priv info from the fd */
479 g_socket_details_from_fd (socket);
482 /* create the fd from socket->priv info */
483 socket->priv->fd = g_socket_create_socket (socket->priv->family,
485 socket->priv->protocol,
486 &socket->priv->construct_error);
488 /* Always use native nonblocking sockets, as
489 windows sets sockets to nonblocking automatically
490 in certain operations. This way we make things work
491 the same on all platforms */
492 if (socket->priv->fd != -1)
493 set_fd_nonblocking (socket->priv->fd);
497 g_socket_get_property (GObject *object,
502 GSocket *socket = G_SOCKET (object);
503 GSocketAddress *address;
508 g_value_set_enum (value, socket->priv->family);
512 g_value_set_enum (value, socket->priv->type);
516 g_value_set_enum (value, socket->priv->protocol);
520 g_value_set_int (value, socket->priv->fd);
524 g_value_set_boolean (value, socket->priv->blocking);
527 case PROP_LISTEN_BACKLOG:
528 g_value_set_int (value, socket->priv->listen_backlog);
532 g_value_set_boolean (value, socket->priv->keepalive);
535 case PROP_LOCAL_ADDRESS:
536 address = g_socket_get_local_address (socket, NULL);
537 g_value_take_object (value, address);
540 case PROP_REMOTE_ADDRESS:
541 address = g_socket_get_remote_address (socket, NULL);
542 g_value_take_object (value, address);
546 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
551 g_socket_set_property (GObject *object,
556 GSocket *socket = G_SOCKET (object);
561 socket->priv->family = g_value_get_enum (value);
565 socket->priv->type = g_value_get_enum (value);
569 socket->priv->protocol = g_value_get_enum (value);
573 socket->priv->fd = g_value_get_int (value);
577 g_socket_set_blocking (socket, g_value_get_boolean (value));
580 case PROP_LISTEN_BACKLOG:
581 g_socket_set_listen_backlog (socket, g_value_get_int (value));
585 g_socket_set_keepalive (socket, g_value_get_boolean (value));
589 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
594 g_socket_finalize (GObject *object)
596 GSocket *socket = G_SOCKET (object);
598 g_clear_error (&socket->priv->construct_error);
600 if (socket->priv->fd != -1 &&
601 !socket->priv->closed)
602 g_socket_close (socket, NULL);
605 g_assert (socket->priv->requested_conditions == NULL);
608 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
609 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
613 g_socket_class_init (GSocketClass *klass)
615 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
618 /* Make sure winsock has been initialized */
619 type = g_inet_address_get_type ();
622 /* There is no portable, thread-safe way to avoid having the process
623 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
624 * forced to simply ignore the signal process-wide.
626 signal (SIGPIPE, SIG_IGN);
629 g_type_class_add_private (klass, sizeof (GSocketPrivate));
631 gobject_class->finalize = g_socket_finalize;
632 gobject_class->constructed = g_socket_constructed;
633 gobject_class->set_property = g_socket_set_property;
634 gobject_class->get_property = g_socket_get_property;
636 g_object_class_install_property (gobject_class, PROP_FAMILY,
637 g_param_spec_enum ("family",
639 P_("The sockets address family"),
640 G_TYPE_SOCKET_FAMILY,
641 G_SOCKET_FAMILY_INVALID,
642 G_PARAM_CONSTRUCT_ONLY |
644 G_PARAM_STATIC_STRINGS));
646 g_object_class_install_property (gobject_class, PROP_TYPE,
647 g_param_spec_enum ("type",
649 P_("The sockets type"),
651 G_SOCKET_TYPE_STREAM,
652 G_PARAM_CONSTRUCT_ONLY |
654 G_PARAM_STATIC_STRINGS));
656 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
657 g_param_spec_enum ("protocol",
658 P_("Socket protocol"),
659 P_("The id of the protocol to use, or -1 for unknown"),
660 G_TYPE_SOCKET_PROTOCOL,
661 G_SOCKET_PROTOCOL_UNKNOWN,
662 G_PARAM_CONSTRUCT_ONLY |
664 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 |
675 G_PARAM_STATIC_STRINGS));
677 g_object_class_install_property (gobject_class, PROP_BLOCKING,
678 g_param_spec_boolean ("blocking",
680 P_("Whether or not I/O on this socket is blocking"),
683 G_PARAM_STATIC_STRINGS));
685 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
686 g_param_spec_int ("listen-backlog",
687 P_("Listen backlog"),
688 P_("Outstanding connections in the listen queue"),
693 G_PARAM_STATIC_STRINGS));
695 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
696 g_param_spec_boolean ("keepalive",
697 P_("Keep connection alive"),
698 P_("Keep connection alive by sending periodic pings"),
701 G_PARAM_STATIC_STRINGS));
703 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
704 g_param_spec_object ("local-address",
706 P_("The local address the socket is bound to"),
707 G_TYPE_SOCKET_ADDRESS,
709 G_PARAM_STATIC_STRINGS));
711 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
712 g_param_spec_object ("remote-address",
713 P_("Remote address"),
714 P_("The remote address the socket is connected to"),
715 G_TYPE_SOCKET_ADDRESS,
717 G_PARAM_STATIC_STRINGS));
721 g_socket_initable_iface_init (GInitableIface *iface)
723 iface->init = g_socket_initable_init;
727 g_socket_init (GSocket *socket)
729 socket->priv = G_TYPE_INSTANCE_GET_PRIVATE (socket, G_TYPE_SOCKET, GSocketPrivate);
731 socket->priv->fd = -1;
732 socket->priv->blocking = TRUE;
733 socket->priv->listen_backlog = 10;
734 socket->priv->construct_error = NULL;
736 socket->priv->event = WSA_INVALID_EVENT;
741 g_socket_initable_init (GInitable *initable,
742 GCancellable *cancellable,
747 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
749 socket = G_SOCKET (initable);
751 if (cancellable != NULL)
753 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
754 _("Cancellable initialization not supported"));
758 socket->priv->inited = TRUE;
760 if (socket->priv->construct_error)
763 *error = g_error_copy (socket->priv->construct_error);
773 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
774 * @type: the socket type to use.
775 * @protocol: the id of the protocol to use, or 0 for default.
776 * @error: #GError for error reporting, or %NULL to ignore.
778 * Creates a new #GSocket with the defined family, type and protocol.
779 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
780 * for the family and type is used.
782 * The @protocol is a family and type specific int that specifies what
783 * kind of protocol to use. #GSocketProtocol lists several common ones.
784 * Many families only support one protocol, and use 0 for this, others
785 * support several and using 0 means to use the default protocol for
786 * the family and type.
788 * The protocol id is passed directly to the operating
789 * system, so you can use protocols not listed in #GSocketProtocol if you
790 * know the protocol number used for it.
792 * Returns: a #GSocket or %NULL on error.
793 * Free the returned object with g_object_unref().
798 g_socket_new (GSocketFamily family,
800 GSocketProtocol protocol,
803 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
807 "protocol", protocol,
812 * g_socket_new_from_fd:
813 * @fd: a native socket file descriptor.
814 * @error: #GError for error reporting, or %NULL to ignore.
816 * Creates a new #GSocket from a native file descriptor
817 * or winsock SOCKET handle.
819 * This reads all the settings from the file descriptor so that
820 * all properties should work. Note that the file descriptor
821 * will be set to non-blocking mode, independent on the blocking
822 * mode of the #GSocket.
824 * Returns: a #GSocket or %NULL on error.
825 * Free the returned object with g_object_unref().
830 g_socket_new_from_fd (gint fd,
833 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
840 * g_socket_set_blocking:
841 * @socket: a #GSocket.
842 * @blocking: Whether to use blocking I/O or not.
844 * Sets the blocking mode of the socket. In blocking mode
845 * all operations block until they succeed or there is an error. In
846 * non-blocking mode all functions return results immediately or
847 * with a %G_IO_ERROR_WOULD_BLOCK error.
849 * All sockets are created in blocking mode. However, note that the
850 * platform level socket is always non-blocking, and blocking mode
851 * is a GSocket level feature.
856 g_socket_set_blocking (GSocket *socket,
859 g_return_if_fail (G_IS_SOCKET (socket));
861 blocking = !!blocking;
863 if (socket->priv->blocking == blocking)
866 socket->priv->blocking = blocking;
867 g_object_notify (G_OBJECT (socket), "blocking");
871 * g_socket_get_blocking:
872 * @socket: a #GSocket.
874 * Gets the blocking mode of the socket. For details on blocking I/O,
875 * see g_socket_set_blocking().
877 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
882 g_socket_get_blocking (GSocket *socket)
884 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
886 return socket->priv->blocking;
890 * g_socket_set_keepalive:
891 * @socket: a #GSocket.
892 * @keepalive: Whether to use try to keep the connection alive or not.
894 * Setting @keepalive to %TRUE enables the sending of periodic ping requests
895 * on idle connections in order to keep the connection alive. This is only
896 * useful for connection oriented sockets. The exact period used between
897 * each ping is system and protocol dependent.
899 * Sending keepalive requests like this has a few disadvantages. For instance,
900 * it uses more network bandwidth, and it makes your application more sensitive
901 * to temporary outages in the network (i.e. if a cable is pulled your otherwise
902 * idle connection could be terminated, whereas otherwise it would survive unless
903 * actually used before the cable was reinserted). However, it is sometimes
904 * useful to ensure that connections are eventually terminated if e.g. the
905 * remote side is disconnected, so as to avoid leaking resources forever.
910 g_socket_set_keepalive (GSocket *socket,
915 g_return_if_fail (G_IS_SOCKET (socket));
917 keepalive = !!keepalive;
918 if (socket->priv->keepalive == keepalive)
921 value = (gint) keepalive;
922 if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_KEEPALIVE,
923 (gpointer) &value, sizeof (value)) < 0)
925 int errsv = get_socket_errno ();
926 g_warning ("error setting keepalive: %s", socket_strerror (errsv));
930 socket->priv->keepalive = keepalive;
931 g_object_notify (G_OBJECT (socket), "keepalive");
935 * g_socket_get_keepalive:
936 * @socket: a #GSocket.
938 * Gets the keepalive mode of the socket. For details on this,
939 * see g_socket_set_keepalive().
941 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
946 g_socket_get_keepalive (GSocket *socket)
948 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
950 return socket->priv->keepalive;
954 * g_socket_get_listen_backlog:
955 * @socket: a #GSocket.
957 * Gets the listen backlog setting of the socket. For details on this,
958 * see g_socket_set_listen_backlog().
960 * Returns: the maximum number of pending connections.
965 g_socket_get_listen_backlog (GSocket *socket)
967 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
969 return socket->priv->listen_backlog;
973 * g_socket_set_listen_backlog:
974 * @socket: a #GSocket.
975 * @backlog: the maximum number of pending connections.
977 * Sets the maximum number of outstanding connections allowed
978 * when listening on this socket. If more clients than this are
979 * connecting to the socket and the application is not handling them
980 * on time then the new connections will be refused.
982 * Note that this must be called before g_socket_listen() and has no
983 * effect if called after that.
988 g_socket_set_listen_backlog (GSocket *socket,
991 g_return_if_fail (G_IS_SOCKET (socket));
992 g_return_if_fail (!socket->priv->listening);
994 if (backlog != socket->priv->listen_backlog)
996 socket->priv->listen_backlog = backlog;
997 g_object_notify (G_OBJECT (socket), "listen-backlog");
1002 * g_socket_get_family:
1003 * @socket: a #GSocket.
1005 * Gets the socket family of the socket.
1007 * Returns: a #GSocketFamily
1012 g_socket_get_family (GSocket *socket)
1014 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1016 return socket->priv->family;
1020 * g_socket_get_socket_type:
1021 * @socket: a #GSocket.
1023 * Gets the socket type of the socket.
1025 * Returns: a #GSocketType
1030 g_socket_get_socket_type (GSocket *socket)
1032 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1034 return socket->priv->type;
1038 * g_socket_get_protocol:
1039 * @socket: a #GSocket.
1041 * Gets the socket protocol id the socket was created with.
1042 * In case the protocol is unknown, -1 is returned.
1044 * Returns: a protocol id, or -1 if unknown
1049 g_socket_get_protocol (GSocket *socket)
1051 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1053 return socket->priv->protocol;
1058 * @socket: a #GSocket.
1060 * Returns the underlying OS socket object. On unix this
1061 * is a socket file descriptor, and on windows this is
1062 * a Winsock2 SOCKET handle. This may be useful for
1063 * doing platform specific or otherwise unusual operations
1066 * Returns: the file descriptor of the socket.
1071 g_socket_get_fd (GSocket *socket)
1073 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1075 return socket->priv->fd;
1079 * g_socket_get_local_address:
1080 * @socket: a #GSocket.
1081 * @error: #GError for error reporting, or %NULL to ignore.
1083 * Try to get the local address of a bound socket. This is only
1084 * useful if the socket has been bound to a local address,
1085 * either explicitly or implicitly when connecting.
1087 * Returns: a #GSocketAddress or %NULL on error.
1088 * Free the returned object with g_object_unref().
1093 g_socket_get_local_address (GSocket *socket,
1096 struct sockaddr_storage buffer;
1097 guint32 len = sizeof (buffer);
1099 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1101 if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1103 int errsv = get_socket_errno ();
1104 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1105 _("could not get local address: %s"), socket_strerror (errsv));
1109 return g_socket_address_new_from_native (&buffer, len);
1113 * g_socket_get_remote_address:
1114 * @socket: a #GSocket.
1115 * @error: #GError for error reporting, or %NULL to ignore.
1117 * Try to get the remove address of a connected socket. This is only
1118 * useful for connection oriented sockets that have been connected.
1120 * Returns: a #GSocketAddress or %NULL on error.
1121 * Free the returned object with g_object_unref().
1126 g_socket_get_remote_address (GSocket *socket,
1129 struct sockaddr_storage buffer;
1130 guint32 len = sizeof (buffer);
1132 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1134 if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1136 int errsv = get_socket_errno ();
1137 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1138 _("could not get remote address: %s"), socket_strerror (errsv));
1142 return g_socket_address_new_from_native (&buffer, len);
1146 * g_socket_is_connected:
1147 * @socket: a #GSocket.
1149 * Check whether the socket is connected. This is only useful for
1150 * connection-oriented sockets.
1152 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1157 g_socket_is_connected (GSocket *socket)
1159 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1161 return socket->priv->connected;
1166 * @socket: a #GSocket.
1167 * @error: #GError for error reporting, or %NULL to ignore.
1169 * Marks the socket as a server socket, i.e. a socket that is used
1170 * to accept incoming requests using g_socket_accept().
1172 * Before calling this the socket must be bound to a local address using
1175 * To set the maximum amount of outstanding clients, use
1176 * g_socket_set_listen_backlog().
1178 * Returns: %TRUE on success, %FALSE on error.
1183 g_socket_listen (GSocket *socket,
1186 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1188 if (!check_socket (socket, error))
1191 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1193 int errsv = get_socket_errno ();
1195 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1196 _("could not listen: %s"), socket_strerror (errsv));
1200 socket->priv->listening = TRUE;
1207 * @socket: a #GSocket.
1208 * @address: a #GSocketAddress specifying the local address.
1209 * @allow_reuse: whether to allow reusing this address
1210 * @error: #GError for error reporting, or %NULL to ignore.
1212 * When a socket is created it is attached to an address family, but it
1213 * doesn't have an address in this family. g_socket_bind() assigns the
1214 * address (sometimes called name) of the socket.
1216 * It is generally required to bind to a local address before you can
1217 * receive connections. (See g_socket_listen() and g_socket_accept() ).
1219 * If @allow_reuse is %TRUE this allows the bind call to succeed in some
1220 * situation where it would otherwise return a %G_IO_ERROR_ADDRESS_IN_USE
1221 * error. The main example is for a TCP server socket where there are
1222 * outstanding connections in the WAIT state, which are generally safe
1223 * to ignore. However, setting it to %TRUE doesn't mean the call will
1224 * succeed if there is a socket actively bound to the address.
1226 * In general, pass %TRUE if the socket will be used to accept connections,
1227 * otherwise pass %FALSE.
1229 * Returns: %TRUE on success, %FALSE on error.
1234 g_socket_bind (GSocket *socket,
1235 GSocketAddress *address,
1236 gboolean reuse_address,
1239 struct sockaddr_storage addr;
1241 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1243 if (!check_socket (socket, error))
1246 /* SO_REUSEADDR on windows means something else and is not what we want.
1247 It always allows the unix variant of SO_REUSEADDR anyway */
1252 value = (int) !!reuse_address;
1253 /* Ignore errors here, the only likely error is "not supported", and
1254 this is a "best effort" thing mainly */
1255 setsockopt (socket->priv->fd, SOL_SOCKET, SO_REUSEADDR,
1256 (gpointer) &value, sizeof (value));
1260 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1263 if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1264 g_socket_address_get_native_size (address)) < 0)
1266 int errsv = get_socket_errno ();
1268 G_IO_ERROR, socket_io_error_from_errno (errsv),
1269 _("Error binding to address: %s"), socket_strerror (errsv));
1278 * @socket: a #GSocket.
1279 * @error: #GError for error reporting, or %NULL to ignore.
1281 * Accept incoming connections on a connection-based socket. This removes
1282 * the first outstanding connection request from the listening socket and
1283 * creates a #GSocket object for it.
1285 * The @socket must be bound to a local address with g_socket_bind() and
1286 * must be listening for incoming connections (g_socket_listen()).
1288 * If there are no outstanding connections then the operation will block
1289 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
1290 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
1292 * Returns: a new #GSocket, or %NULL on error.
1293 * Free the returned object with g_object_unref().
1298 g_socket_accept (GSocket *socket,
1301 GSocket *new_socket;
1304 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1306 if (!check_socket (socket, error))
1311 if (socket->priv->blocking &&
1312 !g_socket_condition_wait (socket,
1313 G_IO_IN, NULL, error))
1316 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
1318 int errsv = get_socket_errno ();
1320 win32_unset_event_mask (socket, FD_ACCEPT);
1325 if (socket->priv->blocking)
1327 #ifdef WSAEWOULDBLOCK
1328 if (errsv == WSAEWOULDBLOCK)
1331 if (errsv == EWOULDBLOCK ||
1337 g_set_error (error, G_IO_ERROR,
1338 socket_io_error_from_errno (errsv),
1339 _("Error accepting connection: %s"), socket_strerror (errsv));
1345 win32_unset_event_mask (socket, FD_ACCEPT);
1349 /* The socket inherits the accepting sockets event mask and even object,
1350 we need to remove that */
1351 WSAEventSelect (ret, NULL, 0);
1357 /* We always want to set close-on-exec to protect users. If you
1358 need to so some weird inheritance to exec you can re-enable this
1359 using lower level hacks with g_socket_get_fd(). */
1360 flags = fcntl (ret, F_GETFD, 0);
1362 (flags & FD_CLOEXEC) == 0)
1364 flags |= FD_CLOEXEC;
1365 fcntl (ret, F_SETFD, flags);
1370 new_socket = g_socket_new_from_fd (ret, error);
1371 if (new_socket == NULL)
1380 new_socket->priv->protocol = socket->priv->protocol;
1387 * @socket: a #GSocket.
1388 * @address: a #GSocketAddress specifying the remote address.
1389 * @error: #GError for error reporting, or %NULL to ignore.
1391 * Connect the socket to the specified remote address.
1393 * For connection oriented socket this generally means we attempt to make
1394 * a connection to the @address. For a connection-less socket it sets
1395 * the default address for g_socket_send() and discards all incoming datagrams
1396 * from other sources.
1398 * Generally connection oriented sockets can only connect once, but
1399 * connection-less sockets can connect multiple times to change the
1402 * If the connect call needs to do network I/O it will block, unless
1403 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
1404 * and the user can be notified of the connection finishing by waiting
1405 * for the G_IO_OUT condition. The result of the connection can then be
1406 * checked with g_socket_check_connect_result().
1408 * Returns: %TRUE if connected, %FALSE on error.
1413 g_socket_connect (GSocket *socket,
1414 GSocketAddress *address,
1417 struct sockaddr_storage buffer;
1419 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1421 if (!check_socket (socket, error))
1424 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
1429 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
1430 g_socket_address_get_native_size (address)) < 0)
1432 int errsv = get_socket_errno ();
1438 if (errsv == EINPROGRESS)
1440 if (errsv == WSAEWOULDBLOCK)
1443 if (socket->priv->blocking)
1445 g_socket_condition_wait (socket, G_IO_OUT, NULL, NULL);
1446 if (g_socket_check_connect_result (socket, error))
1449 g_prefix_error (error, _("Error connecting: "));
1452 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
1453 _("Connection in progress"));
1456 g_set_error (error, G_IO_ERROR,
1457 socket_io_error_from_errno (errsv),
1458 _("Error connecting: %s"), socket_strerror (errsv));
1465 win32_unset_event_mask (socket, FD_CONNECT);
1467 socket->priv->connected = TRUE;
1473 * g_socket_check_connect_result:
1474 * @socket: a #GSocket
1475 * @error: #GError for error reporting, or %NULL to ignore.
1477 * Checks and resets the pending connect error for the socket.
1478 * This is used to check for errors when g_socket_connect() is
1479 * used in non-blocking mode.
1481 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
1486 g_socket_check_connect_result (GSocket *socket,
1492 optlen = sizeof (value);
1493 if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
1495 int errsv = get_socket_errno ();
1497 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1498 _("Unable to get pending error: %s"), socket_strerror (errsv));
1504 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
1505 socket_strerror (value));
1513 * @socket: a #GSocket
1514 * @buffer: a buffer to read data into (which should be at least @size
1516 * @size: the number of bytes that will be read from the stream
1517 * @error: #GError for error reporting, or %NULL to ignore.
1519 * Receive data (up to @size bytes) from a socket. This is mainly used by
1520 * connection oriented sockets, it is identical to g_socket_receive_from()
1521 * with @address set to %NULL.
1523 * If a message is too long to fit in @buffer, excess bytes may be discarded
1524 * depending on the type of socket the message is received from.
1526 * If the socket is in blocking mode the call will block until there is
1527 * some data to receive or there is an error. If there is no data available
1528 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1529 * will be returned. To be notified of available data, wait for the %G_IO_IN
1532 * On error -1 is returned and @error is set accordingly.
1534 * Returns: Number of bytes read, or -1 on error
1539 g_socket_receive (GSocket *socket,
1546 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1548 if (!check_socket (socket, error))
1553 if (socket->priv->blocking &&
1554 !g_socket_condition_wait (socket,
1555 G_IO_IN, NULL, error))
1558 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
1560 int errsv = get_socket_errno ();
1565 if (socket->priv->blocking)
1567 #ifdef WSAEWOULDBLOCK
1568 if (errsv == WSAEWOULDBLOCK)
1571 if (errsv == EWOULDBLOCK ||
1577 win32_unset_event_mask (socket, FD_READ);
1579 g_set_error (error, G_IO_ERROR,
1580 socket_io_error_from_errno (errsv),
1581 _("Error receiving data: %s"), socket_strerror (errsv));
1585 win32_unset_event_mask (socket, FD_READ);
1594 * g_socket_receive_from:
1595 * @socket: a #GSocket
1596 * @address: a pointer to a #GSocketAddress pointer, or %NULL
1597 * @buffer: a buffer to read data into (which should be at least @size
1599 * @size: the number of bytes that will be read from the stream
1600 * @error: #GError for error reporting, or %NULL to ignore.
1602 * Receive data (up to @size bytes) from a socket.
1604 * If @address is non-%NULL then @address will be set equal to the
1605 * source address of the received packet.
1606 * @address is owned by the caller.
1608 * If the socket is in blocking mode the call will block until there is
1609 * some data to receive or there is an error. If there is no data available
1610 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1611 * will be returned. To be notified of available data, wait for the %G_IO_IN
1614 * On error -1 is returned and @error is set accordingly.
1616 * Returns: Number of bytes read, or -1 on error
1621 g_socket_receive_from (GSocket *socket,
1622 GSocketAddress **address,
1632 return g_socket_receive_message (socket,
1641 * @socket: a #GSocket
1642 * @buffer: the buffer containing the data to send.
1643 * @size: the number of bytes to send
1644 * @error: #GError for error reporting, or %NULL to ignore.
1646 * Tries to send @size bytes from @buffer on the socket.
1647 * This is mainly used by connection oriented sockets, it is identical
1648 * to g_socket_send_to() with @address set to %NULL.
1650 * If the socket is in blocking mode the call will block until there is
1651 * space for the data in the socket queue. If there is no space available
1652 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1653 * will be returned. To be notified of available space, wait for the
1654 * %G_IO_OUT condition.
1656 * Note that on Windows you can't rely on a %G_IO_OUT condition
1657 * not producing a %G_IO_ERROR_WOULD_BLOCK error, as this is how Winsock
1658 * write notification works. However, robust apps should always be able to
1659 * handle this since it can easily appear in other cases too.
1661 * On error -1 is returned and @error is set accordingly.
1663 * Returns: Number of bytes read, or -1 on error
1668 g_socket_send (GSocket *socket,
1669 const gchar *buffer,
1675 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1677 if (!check_socket (socket, error))
1682 if (socket->priv->blocking &&
1683 !g_socket_condition_wait (socket,
1684 G_IO_OUT, NULL, error))
1687 if ((ret = send (socket->priv->fd, buffer, size, 0)) < 0)
1689 int errsv = get_socket_errno ();
1694 #ifdef WSAEWOULDBLOCK
1695 if (errsv == WSAEWOULDBLOCK)
1696 win32_unset_event_mask (socket, FD_WRITE);
1699 if (socket->priv->blocking)
1701 #ifdef WSAEWOULDBLOCK
1702 if (errsv == WSAEWOULDBLOCK)
1705 if (errsv == EWOULDBLOCK ||
1711 g_set_error (error, G_IO_ERROR,
1712 socket_io_error_from_errno (errsv),
1713 _("Error sending data: %s"), socket_strerror (errsv));
1724 * @socket: a #GSocket
1725 * @address: a #GSocketAddress, or %NULL
1726 * @buffer: the buffer containing the data to send.
1727 * @size: the number of bytes to send
1728 * @error: #GError for error reporting, or %NULL to ignore.
1730 * Tries to send @size bytes from @buffer to @address. If @address is
1731 * %NULL then the message is sent to the default receiver (set by
1732 * g_socket_connect()).
1734 * If the socket is in blocking mode the call will block until there is
1735 * space for the data in the socket queue. If there is no space available
1736 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1737 * will be returned. To be notified of available space, wait for the %G_IO_OUT
1740 * Note that on Windows you can't rely on a %G_IO_OUT condition
1741 * not producing a %G_IO_ERROR_WOULD_BLOCK error, as this is how Winsock
1742 * write notification works. However, robust apps should always be able to
1743 * handle this since it can easily appear in other cases too.
1745 * On error -1 is returned and @error is set accordingly.
1747 * Returns: Number of bytes read, or -1 on error
1752 g_socket_send_to (GSocket *socket,
1753 GSocketAddress *address,
1754 const gchar *buffer,
1763 return g_socket_send_message (socket,
1771 * g_socket_shutdown:
1772 * @socket: a #GSocket
1773 * @shutdown_read: whether to shut down the read side
1774 * @shutdown_write: whether to shut down the write side
1775 * @error: #GError for error reporting, or %NULL to ignore.
1777 * Shut down part of a full-duplex connection.
1779 * If @shutdown_read is %TRUE then the recieving side of the connection
1780 * is shut down, and further reading is disallowed.
1782 * If @shutdown_write is %TRUE then the sending side of the connection
1783 * is shut down, and further writing is disallowed.
1785 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
1787 * One example where this is used is graceful disconnect for TCP connections
1788 * where you close the sending side, then wait for the other side to close
1789 * the connection, thus ensuring that the other side saw all sent data.
1791 * Returns: %TRUE on success, %FALSE on error
1796 g_socket_shutdown (GSocket *socket,
1797 gboolean shutdown_read,
1798 gboolean shutdown_write,
1803 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
1805 if (!check_socket (socket, NULL))
1809 if (!shutdown_read && !shutdown_write)
1813 if (shutdown_read && shutdown_write)
1815 else if (shutdown_read)
1820 if (shutdown_read && shutdown_write)
1822 else if (shutdown_read)
1828 if (shutdown (socket->priv->fd, how) != 0)
1830 int errsv = get_socket_errno ();
1831 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1832 _("Unable to create socket: %s"), socket_strerror (errsv));
1836 if (shutdown_read && shutdown_write)
1837 socket->priv->connected = FALSE;
1844 * @socket: a #GSocket
1845 * @error: #GError for error reporting, or %NULL to ignore.
1847 * Closes the socket, shutting down any active connection.
1849 * Closing a socket does not wait for all outstanding I/O operations
1850 * to finish, so the caller should not rely on them to be guaranteed
1851 * to complete even if the close returns with no error.
1853 * Once the socket is closed, all other operations will return
1854 * %G_IO_ERROR_CLOSED. Closing a stream multiple times will not
1857 * Sockets will be automatically closed when the last reference
1858 * is dropped, but you might want to call this function to make sure
1859 * resources are released as early as possible.
1861 * Returns: %TRUE on success, %FALSE on error
1866 g_socket_close (GSocket *socket,
1871 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
1873 if (socket->priv->closed)
1874 return TRUE; /* Multiple close not an error */
1876 if (!check_socket (socket, NULL))
1882 res = closesocket (socket->priv->fd);
1884 res = close (socket->priv->fd);
1888 int errsv = get_socket_errno ();
1893 g_set_error (error, G_IO_ERROR,
1894 socket_io_error_from_errno (errsv),
1895 _("Error closing socket: %s"),
1896 socket_strerror (errsv));
1903 if (socket->priv->event != WSA_INVALID_EVENT)
1905 WSACloseEvent (socket->priv->event);
1906 socket->priv->event = WSA_INVALID_EVENT;
1910 socket->priv->connected = FALSE;
1911 socket->priv->closed = TRUE;
1917 * g_socket_is_closed:
1918 * @socket: a #GSocket
1920 * Checks whether a socket is closed.
1922 * Returns: %TRUE if socket is closed, %FALSE otherwise
1927 g_socket_is_closed (GSocket *socket)
1929 return socket->priv->closed;
1933 /* Broken source, used on errors */
1935 broken_prepare (GSource *source,
1942 broken_check (GSource *source)
1948 broken_dispatch (GSource *source,
1949 GSourceFunc callback,
1955 static GSourceFuncs broken_funcs =
1964 network_events_for_condition (GIOCondition condition)
1968 if (condition & G_IO_IN)
1969 event_mask |= (FD_READ | FD_ACCEPT);
1970 if (condition & G_IO_OUT)
1971 event_mask |= (FD_WRITE | FD_CONNECT);
1972 event_mask |= FD_CLOSE;
1978 ensure_event (GSocket *socket)
1980 if (socket->priv->event == WSA_INVALID_EVENT)
1981 socket->priv->event = WSACreateEvent();
1985 update_select_events (GSocket *socket)
1992 ensure_event (socket);
1995 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
1998 event_mask |= network_events_for_condition (*ptr);
2001 if (event_mask != socket->priv->selected_events)
2003 /* If no events selected, disable event so we can unset
2006 if (event_mask == 0)
2009 event = socket->priv->event;
2011 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
2012 socket->priv->selected_events = event_mask;
2017 add_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_prepend (socket->priv->requested_conditions, condition);
2025 update_select_events (socket);
2029 remove_condition_watch (GSocket *socket,
2030 GIOCondition *condition)
2032 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
2034 socket->priv->requested_conditions =
2035 g_list_remove (socket->priv->requested_conditions, condition);
2037 update_select_events (socket);
2041 update_condition (GSocket *socket)
2043 WSANETWORKEVENTS events;
2044 GIOCondition condition;
2046 if (WSAEnumNetworkEvents (socket->priv->fd,
2047 socket->priv->event,
2050 socket->priv->current_events |= events.lNetworkEvents;
2051 if (events.lNetworkEvents & FD_WRITE &&
2052 events.iErrorCode[FD_WRITE_BIT] != 0)
2053 socket->priv->current_errors |= FD_WRITE;
2054 if (events.lNetworkEvents & FD_CONNECT &&
2055 events.iErrorCode[FD_CONNECT_BIT] != 0)
2056 socket->priv->current_errors |= FD_CONNECT;
2060 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
2061 condition |= G_IO_IN;
2063 if (socket->priv->current_events & FD_CLOSE ||
2064 socket->priv->closed)
2065 condition |= G_IO_HUP;
2067 /* Never report both G_IO_OUT and HUP, these are
2068 mutually exclusive (can't write to a closed socket) */
2069 if ((condition & G_IO_HUP) == 0 &&
2070 socket->priv->current_events & FD_WRITE)
2072 if (socket->priv->current_errors & FD_WRITE)
2073 condition |= G_IO_ERR;
2075 condition |= G_IO_OUT;
2079 if (socket->priv->current_events & FD_CONNECT)
2081 if (socket->priv->current_errors & FD_CONNECT)
2082 condition |= (G_IO_HUP | G_IO_ERR);
2084 condition |= G_IO_OUT;
2095 GIOCondition condition;
2096 GCancellable *cancellable;
2097 GPollFD cancel_pollfd;
2098 GIOCondition result_condition;
2102 winsock_prepare (GSource *source,
2105 GWinsockSource *winsock_source = (GWinsockSource *)source;
2106 GIOCondition current_condition;
2108 current_condition = update_condition (winsock_source->socket);
2110 if (g_cancellable_is_cancelled (winsock_source->cancellable))
2112 winsock_source->result_condition = current_condition;
2116 if ((winsock_source->condition & current_condition) != 0)
2118 winsock_source->result_condition = current_condition;
2126 winsock_check (GSource *source)
2128 GWinsockSource *winsock_source = (GWinsockSource *)source;
2129 GIOCondition current_condition;
2131 current_condition = update_condition (winsock_source->socket);
2133 if (g_cancellable_is_cancelled (winsock_source->cancellable))
2135 winsock_source->result_condition = current_condition;
2139 if ((winsock_source->condition & current_condition) != 0)
2141 winsock_source->result_condition = current_condition;
2149 winsock_dispatch (GSource *source,
2150 GSourceFunc callback,
2153 GSocketSourceFunc func = (GSocketSourceFunc)callback;
2154 GWinsockSource *winsock_source = (GWinsockSource *)source;
2156 return (*func) (winsock_source->socket,
2157 winsock_source->result_condition & winsock_source->condition,
2162 winsock_finalize (GSource *source)
2164 GWinsockSource *winsock_source = (GWinsockSource *)source;
2167 socket = winsock_source->socket;
2169 remove_condition_watch (socket, &winsock_source->condition);
2170 g_object_unref (socket);
2172 if (winsock_source->cancellable)
2173 g_object_unref (winsock_source->cancellable);
2176 static GSourceFuncs winsock_funcs =
2185 winsock_source_new (GSocket *socket,
2186 GIOCondition condition,
2187 GCancellable *cancellable)
2190 GWinsockSource *winsock_source;
2192 ensure_event (socket);
2194 if (socket->priv->event == WSA_INVALID_EVENT)
2196 g_warning ("Failed to create WSAEvent");
2197 return g_source_new (&broken_funcs, sizeof (GSource));
2200 condition |= G_IO_HUP | G_IO_ERR;
2202 source = g_source_new (&winsock_funcs, sizeof (GWinsockSource));
2203 winsock_source = (GWinsockSource *)source;
2205 winsock_source->socket = g_object_ref (socket);
2206 winsock_source->condition = condition;
2207 add_condition_watch (socket, &winsock_source->condition);
2211 winsock_source->cancellable = g_object_ref (cancellable);
2212 g_cancellable_make_pollfd (cancellable,
2213 &winsock_source->cancel_pollfd);
2214 g_source_add_poll (source, &winsock_source->cancel_pollfd);
2217 winsock_source->pollfd.fd = (gintptr) socket->priv->event;
2218 winsock_source->pollfd.events = condition;
2219 g_source_add_poll (source, &winsock_source->pollfd);
2226 * g_socket_create_source:
2227 * @socket: a #GSocket
2228 * @condition: a #GIOCondition mask to monitor
2229 * @cancellable: a %GCancellable or %NULL
2231 * Creates a %GSource that can be attached to a %GMainContext to monitor
2232 * for the availibility of the specified @condition on the socket.
2234 * The callback on the source is of the #GSocketSourceFunc type.
2236 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2237 * these conditions will always be reported output if they are true.
2239 * @cancellable if not %NULL can be used to cancel the source, which will
2240 * cause the source to trigger, reporting the current condition (which
2241 * is likely 0 unless cancellation happened at the same time as a
2242 * condition change). You can check for this in the callback using
2243 * g_cancellable_is_cancelled().
2245 * Returns: a newly allocated %GSource, free with g_source_unref().
2250 g_socket_create_source (GSocket *socket,
2251 GIOCondition condition,
2252 GCancellable *cancellable)
2255 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
2258 source = winsock_source_new (socket, condition, cancellable);
2260 source =_g_fd_source_new_with_object (G_OBJECT (socket), socket->priv->fd,
2261 condition, cancellable);
2267 * g_socket_condition_check:
2268 * @socket: a #GSocket
2269 * @condition: a #GIOCondition mask to check
2271 * Checks on the readiness of @socket to perform operations.
2272 * The operations specified in @condition are checked for and masked
2273 * against the currently-satisfied conditions on @socket. The result
2276 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2277 * these conditions will always be set in the output if they are true.
2279 * This call never blocks.
2281 * Returns: the @GIOCondition mask of the current state
2286 g_socket_condition_check (GSocket *socket,
2287 GIOCondition condition)
2289 if (!check_socket (socket, NULL))
2294 GIOCondition current_condition;
2296 condition |= G_IO_ERR | G_IO_HUP;
2298 add_condition_watch (socket, &condition);
2299 current_condition = update_condition (socket);
2300 remove_condition_watch (socket, &condition);
2301 return condition & current_condition;
2307 poll_fd.fd = socket->priv->fd;
2308 poll_fd.events = condition;
2311 result = g_poll (&poll_fd, 1, 0);
2312 while (result == -1 && get_socket_errno () == EINTR);
2314 return poll_fd.revents;
2320 * g_socket_condition_wait:
2321 * @socket: a #GSocket
2322 * @condition: a #GIOCondition mask to wait for
2323 * @cancellable: a #GCancellable, or %NULL
2324 * @error: a #GError pointer, or %NULL
2326 * Waits for @condition to become true on @socket. When the condition
2327 * is met, %TRUE is returned.
2329 * If @cancellable is cancelled before the condition is met then %FALSE
2330 * is returned and @error, if non-%NULL, is set to %G_IO_ERROR_CANCELLED.
2332 * Returns: %TRUE if the condition was met, %FALSE otherwise
2337 g_socket_condition_wait (GSocket *socket,
2338 GIOCondition condition,
2339 GCancellable *cancellable,
2342 if (!check_socket (socket, error))
2345 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2350 GIOCondition current_condition;
2356 /* Always check these */
2357 condition |= G_IO_ERR | G_IO_HUP;
2359 add_condition_watch (socket, &condition);
2362 events[num_events++] = socket->priv->event;
2366 g_cancellable_make_pollfd (cancellable, &cancel_fd);
2367 events[num_events++] = (WSAEVENT)cancel_fd.fd;
2370 current_condition = update_condition (socket);
2371 while ((condition & current_condition) == 0)
2373 res = WSAWaitForMultipleEvents(num_events, events,
2374 FALSE, WSA_INFINITE, FALSE);
2375 if (res == WSA_WAIT_FAILED)
2377 int errsv = get_socket_errno ();
2379 g_set_error (error, G_IO_ERROR,
2380 socket_io_error_from_errno (errsv),
2381 _("Waiting for socket condition: %s"),
2382 socket_strerror (errsv));
2386 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2389 current_condition = update_condition (socket);
2391 remove_condition_watch (socket, &condition);
2393 return (condition & current_condition) != 0;
2401 poll_fd[0].fd = socket->priv->fd;
2402 poll_fd[0].events = condition;
2407 g_cancellable_make_pollfd (cancellable, &poll_fd[1]);
2412 result = g_poll (poll_fd, num, -1);
2413 while (result == -1 && get_socket_errno () == EINTR);
2415 return cancellable == NULL ||
2416 !g_cancellable_set_error_if_cancelled (cancellable, error);
2422 * g_socket_send_message:
2423 * @socket: a #GSocket
2424 * @address: a #GSocketAddress, or %NULL
2425 * @vectors: an array of #GOutputVector structs
2426 * @num_vectors: the number of elements in @vectors, or -1
2427 * @messages: a pointer to an array of #GSocketControlMessages, or
2429 * @num_messages: number of elements in @messages, or -1.
2430 * @flags: an int containing #GSocketMsgFlags flags
2431 * @error: #GError for error reporting, or %NULL to ignore.
2433 * Send data to @address on @socket. This is the most complicated and
2434 * fully-featured version of this call. For easier use, see
2435 * g_socket_send() and g_socket_send_to().
2437 * If @address is %NULL then the message is sent to the default receiver
2438 * (set by g_socket_connect()).
2440 * @vector must point to an array of #GOutputVector structs and
2441 * @num_vectors must be the length of this array. These structs
2442 * describe the buffers that the sent data will be gathered from.
2443 * If @num_vector is -1, then @vector is assumed to be terminated
2444 * by a #GOutputVector with a %NULL buffer pointer.
2446 * @messages, if non-%NULL, is taken to point to an array of @num_messages
2447 * #GSocketControlMessage instances. These correspond to the control
2448 * messages to be sent on the socket.
2449 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
2452 * @flags modify how the message sent. The commonly available arguments
2453 * for this is available in the #GSocketMsgFlags enum, but the
2454 * values there are the same as the system values, and the flags
2455 * are passed in as-is, so you can pass in system specific flags too.
2457 * If the socket is in blocking mode the call will block until there is
2458 * space for the data in the socket queue. If there is no space available
2459 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2460 * will be returned. To be notified of available space, wait for the %G_IO_OUT
2463 * Note that on Windows you can't rely on a %G_IO_OUT condition
2464 * not producing a %G_IO_ERROR_WOULD_BLOCK error, as this is how Winsock
2465 * write notification works. However, robust apps should always be able to
2466 * handle this since it can easily appear in other cases too.
2468 * On error -1 is returned and @error is set accordingly.
2470 * Returns: Number of bytes read, or -1 on error
2475 g_socket_send_message (GSocket *socket,
2476 GSocketAddress *address,
2477 GOutputVector *vectors,
2479 GSocketControlMessage **messages,
2484 GOutputVector one_vector;
2487 if (!check_socket (socket, error))
2490 if (num_vectors == -1)
2492 for (num_vectors = 0;
2493 vectors[num_vectors].buffer != NULL;
2498 if (num_messages == -1)
2500 for (num_messages = 0;
2501 messages != NULL && messages[num_messages] != NULL;
2506 if (num_vectors == 0)
2510 one_vector.buffer = &zero;
2511 one_vector.size = 1;
2513 vectors = &one_vector;
2524 msg.msg_namelen = g_socket_address_get_native_size (address);
2525 msg.msg_name = g_alloca (msg.msg_namelen);
2526 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
2532 /* this entire expression will be evaluated at compile time */
2533 if (sizeof *msg.msg_iov == sizeof *vectors &&
2534 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2535 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2536 G_STRUCT_OFFSET (GOutputVector, buffer) &&
2537 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2538 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2539 G_STRUCT_OFFSET (GOutputVector, size))
2540 /* ABI is compatible */
2542 msg.msg_iov = (struct iovec *) vectors;
2543 msg.msg_iovlen = num_vectors;
2546 /* ABI is incompatible */
2550 msg.msg_iov = g_newa (struct iovec, num_vectors);
2551 for (i = 0; i < num_vectors; i++)
2553 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
2554 msg.msg_iov[i].iov_len = vectors[i].size;
2556 msg.msg_iovlen = num_vectors;
2562 struct cmsghdr *cmsg;
2565 msg.msg_controllen = 0;
2566 for (i = 0; i < num_messages; i++)
2567 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
2569 msg.msg_control = g_alloca (msg.msg_controllen);
2571 cmsg = CMSG_FIRSTHDR (&msg);
2572 for (i = 0; i < num_messages; i++)
2574 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
2575 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
2576 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
2577 g_socket_control_message_serialize (messages[i],
2579 cmsg = CMSG_NXTHDR (&msg, cmsg);
2581 g_assert (cmsg == NULL);
2586 if (socket->priv->blocking &&
2587 !g_socket_condition_wait (socket,
2588 G_IO_OUT, NULL, error))
2591 result = sendmsg (socket->priv->fd, &msg, flags);
2594 int errsv = get_socket_errno ();
2599 if (socket->priv->blocking &&
2600 (errsv == EWOULDBLOCK ||
2604 g_set_error (error, G_IO_ERROR,
2605 socket_io_error_from_errno (errsv),
2606 _("Error sending message: %s"), socket_strerror (errsv));
2617 struct sockaddr_storage addr;
2624 /* Win32 doesn't support control messages.
2625 Actually this is possible for raw and datagram sockets
2626 via WSASendMessage on Vista or later, but that doesn't
2628 if (num_messages != 0)
2630 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2631 _("GSocketControlMessage not supported on windows"));
2636 bufs = g_newa (WSABUF, num_vectors);
2637 for (i = 0; i < num_vectors; i++)
2639 bufs[i].buf = (char *)vectors[i].buffer;
2640 bufs[i].len = (gulong)vectors[i].size;
2644 addrlen = 0; /* Avoid warning */
2647 addrlen = g_socket_address_get_native_size (address);
2648 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
2654 if (socket->priv->blocking &&
2655 !g_socket_condition_wait (socket,
2656 G_IO_OUT, NULL, error))
2660 result = WSASendTo (socket->priv->fd,
2663 (const struct sockaddr *)&addr, addrlen,
2666 result = WSASend (socket->priv->fd,
2673 int errsv = get_socket_errno ();
2675 if (errsv == WSAEINTR)
2678 if (errsv == WSAEWOULDBLOCK)
2679 win32_unset_event_mask (socket, FD_WRITE);
2681 if (socket->priv->blocking &&
2682 errsv == WSAEWOULDBLOCK)
2685 g_set_error (error, G_IO_ERROR,
2686 socket_io_error_from_errno (errsv),
2687 _("Error sending message: %s"), socket_strerror (errsv));
2700 * g_socket_receive_message:
2701 * @socket: a #GSocket
2702 * @address: a pointer to a #GSocketAddress pointer, or %NULL
2703 * @vectors: an array of #GInputVector structs
2704 * @num_vectors: the number of elements in @vectors, or -1
2705 * @messages: a pointer which will be filled with an array of
2706 * #GSocketControlMessages, or %NULL
2707 * @num_messages: a pointer which will be filled with the number of
2708 * elements in @messages, or %NULL
2709 * @flags: a pointer to an int containing #GSocketMsgFlags flags
2710 * @error: a #GError pointer, or %NULL
2712 * Receive data from a socket. This is the most complicated and
2713 * fully-featured version of this call. For easier use, see
2714 * g_socket_receive() and g_socket_receive_from().
2716 * If @address is non-%NULL then @address will be set equal to the
2717 * source address of the received packet.
2718 * @address is owned by the caller.
2720 * @vector must point to an array of #GInputVector structs and
2721 * @num_vectors must be the length of this array. These structs
2722 * describe the buffers that received data will be scattered into.
2723 * If @num_vector is -1, then @vector is assumed to be terminated
2724 * by a #GInputVector with a %NULL buffer pointer.
2726 * As a special case, if the size of the array is zero (in which case,
2727 * @vectors may of course be %NULL), then a single byte is received
2728 * and discarded. This is to facilitate the common practice of
2729 * sending a single '\0' byte for the purposes of transferring
2732 * @messages, if non-%NULL, is taken to point to a pointer that will
2733 * be set to point to a newly-allocated array of
2734 * #GSocketControlMessage instances. These correspond to the control
2735 * messages received from the kernel, one #GSocketControlMessage per
2736 * message from the kernel. This array is %NULL-terminated and must be
2737 * freed by the caller using g_free().
2739 * @num_messages, if non-%NULL, will be set to the number of control
2740 * messages received.
2742 * If both @messages and @num_messages are non-%NULL, then
2743 * @num_messages gives the number of #GSocketControlMessage instances
2744 * in @messages (ie: not including the %NULL terminator).
2746 * @flags is an in/out parameter. The commonly available arguments
2747 * for this is available in the #GSocketMsgFlags enum, but the
2748 * values there are the same as the system values, and the flags
2749 * are passed in as-is, so you can pass in system specific flags too.
2751 * If the socket is in blocking mode the call will block until there is
2752 * some data to receive or there is an error. If there is no data available
2753 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2754 * will be returned. To be notified of available data, wait for the %G_IO_IN
2757 * On error -1 is returned and @error is set accordingly.
2759 * Returns: Number of bytes read, or -1 on error
2764 g_socket_receive_message (GSocket *socket,
2765 GSocketAddress **address,
2766 GInputVector *vectors,
2768 GSocketControlMessage ***messages,
2773 GInputVector one_vector;
2776 if (!check_socket (socket, error))
2779 if (num_vectors == -1)
2781 for (num_vectors = 0;
2782 vectors[num_vectors].buffer != NULL;
2787 if (num_vectors == 0)
2789 one_vector.buffer = &one_byte;
2790 one_vector.size = 1;
2792 vectors = &one_vector;
2799 struct sockaddr_storage one_sockaddr;
2804 msg.msg_name = &one_sockaddr;
2805 msg.msg_namelen = sizeof (struct sockaddr_storage);
2809 msg.msg_name = NULL;
2810 msg.msg_namelen = 0;
2814 /* this entire expression will be evaluated at compile time */
2815 if (sizeof *msg.msg_iov == sizeof *vectors &&
2816 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2817 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2818 G_STRUCT_OFFSET (GInputVector, buffer) &&
2819 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2820 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2821 G_STRUCT_OFFSET (GInputVector, size))
2822 /* ABI is compatible */
2824 msg.msg_iov = (struct iovec *) vectors;
2825 msg.msg_iovlen = num_vectors;
2828 /* ABI is incompatible */
2832 msg.msg_iov = g_newa (struct iovec, num_vectors);
2833 for (i = 0; i < num_vectors; i++)
2835 msg.msg_iov[i].iov_base = vectors[i].buffer;
2836 msg.msg_iov[i].iov_len = vectors[i].size;
2838 msg.msg_iovlen = num_vectors;
2842 msg.msg_control = g_alloca (2048);
2843 msg.msg_controllen = 2048;
2847 msg.msg_flags = *flags;
2854 if (socket->priv->blocking &&
2855 !g_socket_condition_wait (socket,
2856 G_IO_IN, NULL, error))
2859 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
2863 int errsv = get_socket_errno ();
2868 if (socket->priv->blocking &&
2869 (errsv == EWOULDBLOCK ||
2873 g_set_error (error, G_IO_ERROR,
2874 socket_io_error_from_errno (errsv),
2875 _("Error receiving message: %s"), socket_strerror (errsv));
2882 /* decode address */
2883 if (address != NULL)
2885 if (msg.msg_namelen > 0)
2886 *address = g_socket_address_new_from_native (msg.msg_name,
2892 /* decode control messages */
2894 GSocketControlMessage **my_messages = NULL;
2895 gint allocated = 0, index = 0;
2896 const gchar *scm_pointer;
2897 struct cmsghdr *cmsg;
2900 scm_pointer = (const gchar *) msg.msg_control;
2901 scm_size = msg.msg_controllen;
2903 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
2905 GSocketControlMessage *message;
2907 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
2909 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
2911 if (message == NULL)
2912 /* We've already spewed about the problem in the
2913 deserialization code, so just continue */
2916 if (index == allocated)
2918 /* estimated 99% case: exactly 1 control message */
2919 allocated = MIN (allocated * 2, 1);
2920 my_messages = g_new (GSocketControlMessage *, (allocated + 1));
2924 my_messages[index++] = message;
2928 *num_messages = index;
2932 my_messages[index++] = NULL;
2933 *messages = my_messages;
2939 /* free all those messages we just constructed.
2940 * we have to do it this way if the user ignores the
2941 * messages so that we will close any received fds.
2943 for (i = 0; i < index; i++)
2944 g_object_unref (my_messages[i]);
2945 g_free (my_messages);
2949 /* capture the flags */
2951 *flags = msg.msg_flags;
2957 struct sockaddr_storage addr;
2959 DWORD bytes_received;
2966 bufs = g_newa (WSABUF, num_vectors);
2967 for (i = 0; i < num_vectors; i++)
2969 bufs[i].buf = (char *)vectors[i].buffer;
2970 bufs[i].len = (gulong)vectors[i].size;
2982 if (socket->priv->blocking &&
2983 !g_socket_condition_wait (socket,
2984 G_IO_IN, NULL, error))
2987 addrlen = sizeof addr;
2989 result = WSARecvFrom (socket->priv->fd,
2991 &bytes_received, &win_flags,
2992 (struct sockaddr *)&addr, &addrlen,
2995 result = WSARecv (socket->priv->fd,
2997 &bytes_received, &win_flags,
3001 int errsv = get_socket_errno ();
3003 if (errsv == WSAEINTR)
3006 win32_unset_event_mask (socket, FD_READ);
3008 if (socket->priv->blocking &&
3009 errsv == WSAEWOULDBLOCK)
3012 g_set_error (error, G_IO_ERROR,
3013 socket_io_error_from_errno (errsv),
3014 _("Error receiving message: %s"), socket_strerror (errsv));
3018 win32_unset_event_mask (socket, FD_READ);
3022 /* decode address */
3023 if (address != NULL)
3026 *address = g_socket_address_new_from_native (&addr, addrlen);
3031 /* capture the flags */
3035 return bytes_received;
3040 #define __G_SOCKET_C__
3041 #include "gioaliasdef.c"