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>
33 #include "glib-unix.h"
50 #include "gcancellable.h"
51 #include "gioenumtypes.h"
52 #include "ginetaddress.h"
53 #include "ginitable.h"
57 #include "gnetworkingprivate.h"
58 #include "gsocketaddress.h"
59 #include "gsocketcontrolmessage.h"
60 #include "gcredentials.h"
65 * @short_description: Low-level socket object
67 * @see_also: #GInitable
69 * A #GSocket is a low-level networking primitive. It is a more or less
70 * direct mapping of the BSD socket API in a portable GObject based API.
71 * It supports both the UNIX socket implementations and winsock2 on Windows.
73 * #GSocket is the platform independent base upon which the higher level
74 * network primitives are based. Applications are not typically meant to
75 * use it directly, but rather through classes like #GSocketClient,
76 * #GSocketService and #GSocketConnection. However there may be cases where
77 * direct use of #GSocket is useful.
79 * #GSocket implements the #GInitable interface, so if it is manually constructed
80 * by e.g. g_object_new() you must call g_initable_init() and check the
81 * results before using the object. This is done automatically in
82 * g_socket_new() and g_socket_new_from_fd(), so these functions can return
85 * Sockets operate in two general modes, blocking or non-blocking. When
86 * in blocking mode all operations block until the requested operation
87 * is finished or there is an error. In non-blocking mode all calls that
88 * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
89 * To know when a call would successfully run you can call g_socket_condition_check(),
90 * or g_socket_condition_wait(). You can also use g_socket_create_source() and
91 * attach it to a #GMainContext to get callbacks when I/O is possible.
92 * Note that all sockets are always set to non blocking mode in the system, and
93 * blocking mode is emulated in GSocket.
95 * When working in non-blocking mode applications should always be able to
96 * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
97 * function said that I/O was possible. This can easily happen in case
98 * of a race condition in the application, but it can also happen for other
99 * reasons. For instance, on Windows a socket is always seen as writable
100 * until a write returns %G_IO_ERROR_WOULD_BLOCK.
102 * #GSocket<!-- -->s can be either connection oriented or datagram based.
103 * For connection oriented types you must first establish a connection by
104 * either connecting to an address or accepting a connection from another
105 * address. For connectionless socket types the target/source address is
106 * specified or received in each I/O operation.
108 * All socket file descriptors are set to be close-on-exec.
110 * Note that creating a #GSocket causes the signal %SIGPIPE to be
111 * ignored for the remainder of the program. If you are writing a
112 * command-line utility that uses #GSocket, you may need to take into
113 * account the fact that your program will not automatically be killed
114 * if it tries to write to %stdout after it has been closed.
119 static void g_socket_initable_iface_init (GInitableIface *iface);
120 static gboolean g_socket_initable_init (GInitable *initable,
121 GCancellable *cancellable,
124 G_DEFINE_TYPE_WITH_CODE (GSocket, g_socket, G_TYPE_OBJECT,
125 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
126 g_socket_initable_iface_init));
143 struct _GSocketPrivate
145 GSocketFamily family;
147 GSocketProtocol protocol;
151 GError *construct_error;
152 GSocketAddress *remote_address;
160 guint connect_pending : 1;
166 GList *requested_conditions; /* list of requested GIOCondition * */
171 get_socket_errno (void)
176 return WSAGetLastError ();
181 socket_io_error_from_errno (int err)
184 return g_io_error_from_errno (err);
189 return G_IO_ERROR_ADDRESS_IN_USE;
191 return G_IO_ERROR_WOULD_BLOCK;
193 return G_IO_ERROR_PERMISSION_DENIED;
194 case WSA_INVALID_HANDLE:
195 case WSA_INVALID_PARAMETER:
198 return G_IO_ERROR_INVALID_ARGUMENT;
199 case WSAEPROTONOSUPPORT:
200 return G_IO_ERROR_NOT_SUPPORTED;
202 return G_IO_ERROR_CANCELLED;
203 case WSAESOCKTNOSUPPORT:
205 case WSAEPFNOSUPPORT:
206 case WSAEAFNOSUPPORT:
207 return G_IO_ERROR_NOT_SUPPORTED;
209 return G_IO_ERROR_FAILED;
215 socket_strerror (int err)
218 return g_strerror (err);
220 static GStaticPrivate last_msg = G_STATIC_PRIVATE_INIT;
223 msg = g_win32_error_message (err);
224 g_static_private_set (&last_msg, msg, g_free);
231 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
233 _win32_unset_event_mask (GSocket *socket, int mask)
235 socket->priv->current_events &= ~mask;
236 socket->priv->current_errors &= ~mask;
239 #define win32_unset_event_mask(_socket, _mask)
243 set_fd_nonblocking (int fd)
246 GError *error = NULL;
252 if (!g_unix_set_fd_nonblocking (fd, TRUE, &error))
254 g_warning ("Error setting socket nonblocking: %s", error->message);
255 g_clear_error (&error);
260 if (ioctlsocket (fd, FIONBIO, &arg) == SOCKET_ERROR)
262 int errsv = get_socket_errno ();
263 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
269 check_socket (GSocket *socket,
272 if (!socket->priv->inited)
274 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
275 _("Invalid socket, not initialized"));
279 if (socket->priv->construct_error)
281 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
282 _("Invalid socket, initialization failed due to: %s"),
283 socket->priv->construct_error->message);
287 if (socket->priv->closed)
289 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
290 _("Socket is already closed"));
294 if (socket->priv->timed_out)
296 socket->priv->timed_out = FALSE;
297 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
298 _("Socket I/O timed out"));
306 g_socket_details_from_fd (GSocket *socket)
308 struct sockaddr_storage address;
315 /* See bug #611756 */
316 BOOL bool_val = FALSE;
321 fd = socket->priv->fd;
322 optlen = sizeof value;
323 if (getsockopt (fd, SOL_SOCKET, SO_TYPE, (void *)&value, &optlen) != 0)
325 errsv = get_socket_errno ();
336 /* programmer error */
337 g_error ("creating GSocket from fd %d: %s\n",
338 fd, socket_strerror (errsv));
346 g_assert (optlen == sizeof value);
350 socket->priv->type = G_SOCKET_TYPE_STREAM;
354 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
358 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
362 socket->priv->type = G_SOCKET_TYPE_INVALID;
366 addrlen = sizeof address;
367 if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
369 errsv = get_socket_errno ();
375 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
376 sizeof address.ss_family <= addrlen);
377 family = address.ss_family;
381 /* On Solaris, this happens if the socket is not yet connected.
382 * But we can use SO_DOMAIN as a workaround there.
385 optlen = sizeof family;
386 if (getsockopt (fd, SOL_SOCKET, SO_DOMAIN, (void *)&family, &optlen) != 0)
388 errsv = get_socket_errno ();
392 /* This will translate to G_IO_ERROR_FAILED on either unix or windows */
400 case G_SOCKET_FAMILY_IPV4:
401 case G_SOCKET_FAMILY_IPV6:
402 socket->priv->family = address.ss_family;
403 switch (socket->priv->type)
405 case G_SOCKET_TYPE_STREAM:
406 socket->priv->protocol = G_SOCKET_PROTOCOL_TCP;
409 case G_SOCKET_TYPE_DATAGRAM:
410 socket->priv->protocol = G_SOCKET_PROTOCOL_UDP;
413 case G_SOCKET_TYPE_SEQPACKET:
414 socket->priv->protocol = G_SOCKET_PROTOCOL_SCTP;
422 case G_SOCKET_FAMILY_UNIX:
423 socket->priv->family = G_SOCKET_FAMILY_UNIX;
424 socket->priv->protocol = G_SOCKET_PROTOCOL_DEFAULT;
428 socket->priv->family = G_SOCKET_FAMILY_INVALID;
432 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
434 addrlen = sizeof address;
435 if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
436 socket->priv->connected = TRUE;
439 optlen = sizeof bool_val;
440 if (getsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
441 (void *)&bool_val, &optlen) == 0)
444 /* Experimentation indicates that the SO_KEEPALIVE value is
445 * actually a char on Windows, even if documentation claims it
446 * to be a BOOL which is a typedef for int. So this g_assert()
447 * fails. See bug #611756.
449 g_assert (optlen == sizeof bool_val);
451 socket->priv->keepalive = !!bool_val;
455 /* Can't read, maybe not supported, assume FALSE */
456 socket->priv->keepalive = FALSE;
462 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
463 socket_io_error_from_errno (errsv),
464 _("creating GSocket from fd: %s"),
465 socket_strerror (errsv));
469 g_socket_create_socket (GSocketFamily family,
479 case G_SOCKET_TYPE_STREAM:
480 native_type = SOCK_STREAM;
483 case G_SOCKET_TYPE_DATAGRAM:
484 native_type = SOCK_DGRAM;
487 case G_SOCKET_TYPE_SEQPACKET:
488 native_type = SOCK_SEQPACKET;
492 g_assert_not_reached ();
497 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
498 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
503 fd = socket (family, native_type | SOCK_CLOEXEC, protocol);
504 /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
505 if (fd < 0 && errno == EINVAL)
507 fd = socket (family, native_type, protocol);
511 int errsv = get_socket_errno ();
513 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
514 _("Unable to create socket: %s"), socket_strerror (errsv));
521 /* We always want to set close-on-exec to protect users. If you
522 need to so some weird inheritance to exec you can re-enable this
523 using lower level hacks with g_socket_get_fd(). */
524 flags = fcntl (fd, F_GETFD, 0);
526 (flags & FD_CLOEXEC) == 0)
529 fcntl (fd, F_SETFD, flags);
538 g_socket_constructed (GObject *object)
540 GSocket *socket = G_SOCKET (object);
542 if (socket->priv->fd >= 0)
543 /* create socket->priv info from the fd */
544 g_socket_details_from_fd (socket);
547 /* create the fd from socket->priv info */
548 socket->priv->fd = g_socket_create_socket (socket->priv->family,
550 socket->priv->protocol,
551 &socket->priv->construct_error);
553 /* Always use native nonblocking sockets, as
554 windows sets sockets to nonblocking automatically
555 in certain operations. This way we make things work
556 the same on all platforms */
557 if (socket->priv->fd != -1)
558 set_fd_nonblocking (socket->priv->fd);
562 g_socket_get_property (GObject *object,
567 GSocket *socket = G_SOCKET (object);
568 GSocketAddress *address;
573 g_value_set_enum (value, socket->priv->family);
577 g_value_set_enum (value, socket->priv->type);
581 g_value_set_enum (value, socket->priv->protocol);
585 g_value_set_int (value, socket->priv->fd);
589 g_value_set_boolean (value, socket->priv->blocking);
592 case PROP_LISTEN_BACKLOG:
593 g_value_set_int (value, socket->priv->listen_backlog);
597 g_value_set_boolean (value, socket->priv->keepalive);
600 case PROP_LOCAL_ADDRESS:
601 address = g_socket_get_local_address (socket, NULL);
602 g_value_take_object (value, address);
605 case PROP_REMOTE_ADDRESS:
606 address = g_socket_get_remote_address (socket, NULL);
607 g_value_take_object (value, address);
611 g_value_set_uint (value, socket->priv->timeout);
615 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
620 g_socket_set_property (GObject *object,
625 GSocket *socket = G_SOCKET (object);
630 socket->priv->family = g_value_get_enum (value);
634 socket->priv->type = g_value_get_enum (value);
638 socket->priv->protocol = g_value_get_enum (value);
642 socket->priv->fd = g_value_get_int (value);
646 g_socket_set_blocking (socket, g_value_get_boolean (value));
649 case PROP_LISTEN_BACKLOG:
650 g_socket_set_listen_backlog (socket, g_value_get_int (value));
654 g_socket_set_keepalive (socket, g_value_get_boolean (value));
658 g_socket_set_timeout (socket, g_value_get_uint (value));
662 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
667 g_socket_finalize (GObject *object)
669 GSocket *socket = G_SOCKET (object);
671 g_clear_error (&socket->priv->construct_error);
673 if (socket->priv->fd != -1 &&
674 !socket->priv->closed)
675 g_socket_close (socket, NULL);
677 if (socket->priv->remote_address)
678 g_object_unref (socket->priv->remote_address);
681 if (socket->priv->event != WSA_INVALID_EVENT)
683 WSACloseEvent (socket->priv->event);
684 socket->priv->event = WSA_INVALID_EVENT;
687 g_assert (socket->priv->requested_conditions == NULL);
690 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
691 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
695 g_socket_class_init (GSocketClass *klass)
697 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
700 /* Make sure winsock has been initialized */
701 type = g_inet_address_get_type ();
702 (type); /* To avoid -Wunused-but-set-variable */
705 /* There is no portable, thread-safe way to avoid having the process
706 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
707 * forced to simply ignore the signal process-wide.
709 signal (SIGPIPE, SIG_IGN);
712 g_type_class_add_private (klass, sizeof (GSocketPrivate));
714 gobject_class->finalize = g_socket_finalize;
715 gobject_class->constructed = g_socket_constructed;
716 gobject_class->set_property = g_socket_set_property;
717 gobject_class->get_property = g_socket_get_property;
719 g_object_class_install_property (gobject_class, PROP_FAMILY,
720 g_param_spec_enum ("family",
722 P_("The sockets address family"),
723 G_TYPE_SOCKET_FAMILY,
724 G_SOCKET_FAMILY_INVALID,
725 G_PARAM_CONSTRUCT_ONLY |
727 G_PARAM_STATIC_STRINGS));
729 g_object_class_install_property (gobject_class, PROP_TYPE,
730 g_param_spec_enum ("type",
732 P_("The sockets type"),
734 G_SOCKET_TYPE_STREAM,
735 G_PARAM_CONSTRUCT_ONLY |
737 G_PARAM_STATIC_STRINGS));
739 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
740 g_param_spec_enum ("protocol",
741 P_("Socket protocol"),
742 P_("The id of the protocol to use, or -1 for unknown"),
743 G_TYPE_SOCKET_PROTOCOL,
744 G_SOCKET_PROTOCOL_UNKNOWN,
745 G_PARAM_CONSTRUCT_ONLY |
747 G_PARAM_STATIC_STRINGS));
749 g_object_class_install_property (gobject_class, PROP_FD,
750 g_param_spec_int ("fd",
751 P_("File descriptor"),
752 P_("The sockets file descriptor"),
756 G_PARAM_CONSTRUCT_ONLY |
758 G_PARAM_STATIC_STRINGS));
760 g_object_class_install_property (gobject_class, PROP_BLOCKING,
761 g_param_spec_boolean ("blocking",
763 P_("Whether or not I/O on this socket is blocking"),
766 G_PARAM_STATIC_STRINGS));
768 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
769 g_param_spec_int ("listen-backlog",
770 P_("Listen backlog"),
771 P_("Outstanding connections in the listen queue"),
776 G_PARAM_STATIC_STRINGS));
778 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
779 g_param_spec_boolean ("keepalive",
780 P_("Keep connection alive"),
781 P_("Keep connection alive by sending periodic pings"),
784 G_PARAM_STATIC_STRINGS));
786 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
787 g_param_spec_object ("local-address",
789 P_("The local address the socket is bound to"),
790 G_TYPE_SOCKET_ADDRESS,
792 G_PARAM_STATIC_STRINGS));
794 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
795 g_param_spec_object ("remote-address",
796 P_("Remote address"),
797 P_("The remote address the socket is connected to"),
798 G_TYPE_SOCKET_ADDRESS,
800 G_PARAM_STATIC_STRINGS));
805 * The timeout in seconds on socket I/O
809 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
810 g_param_spec_uint ("timeout",
812 P_("The timeout in seconds on socket I/O"),
817 G_PARAM_STATIC_STRINGS));
821 g_socket_initable_iface_init (GInitableIface *iface)
823 iface->init = g_socket_initable_init;
827 g_socket_init (GSocket *socket)
829 socket->priv = G_TYPE_INSTANCE_GET_PRIVATE (socket, G_TYPE_SOCKET, GSocketPrivate);
831 socket->priv->fd = -1;
832 socket->priv->blocking = TRUE;
833 socket->priv->listen_backlog = 10;
834 socket->priv->construct_error = NULL;
836 socket->priv->event = WSA_INVALID_EVENT;
841 g_socket_initable_init (GInitable *initable,
842 GCancellable *cancellable,
847 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
849 socket = G_SOCKET (initable);
851 if (cancellable != NULL)
853 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
854 _("Cancellable initialization not supported"));
858 socket->priv->inited = TRUE;
860 if (socket->priv->construct_error)
863 *error = g_error_copy (socket->priv->construct_error);
873 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
874 * @type: the socket type to use.
875 * @protocol: the id of the protocol to use, or 0 for default.
876 * @error: #GError for error reporting, or %NULL to ignore.
878 * Creates a new #GSocket with the defined family, type and protocol.
879 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
880 * for the family and type is used.
882 * The @protocol is a family and type specific int that specifies what
883 * kind of protocol to use. #GSocketProtocol lists several common ones.
884 * Many families only support one protocol, and use 0 for this, others
885 * support several and using 0 means to use the default protocol for
886 * the family and type.
888 * The protocol id is passed directly to the operating
889 * system, so you can use protocols not listed in #GSocketProtocol if you
890 * know the protocol number used for it.
892 * Returns: a #GSocket or %NULL on error.
893 * Free the returned object with g_object_unref().
898 g_socket_new (GSocketFamily family,
900 GSocketProtocol protocol,
903 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
907 "protocol", protocol,
912 * g_socket_new_from_fd:
913 * @fd: a native socket file descriptor.
914 * @error: #GError for error reporting, or %NULL to ignore.
916 * Creates a new #GSocket from a native file descriptor
917 * or winsock SOCKET handle.
919 * This reads all the settings from the file descriptor so that
920 * all properties should work. Note that the file descriptor
921 * will be set to non-blocking mode, independent on the blocking
922 * mode of the #GSocket.
924 * Returns: a #GSocket or %NULL on error.
925 * Free the returned object with g_object_unref().
930 g_socket_new_from_fd (gint fd,
933 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
940 * g_socket_set_blocking:
941 * @socket: a #GSocket.
942 * @blocking: Whether to use blocking I/O or not.
944 * Sets the blocking mode of the socket. In blocking mode
945 * all operations block until they succeed or there is an error. In
946 * non-blocking mode all functions return results immediately or
947 * with a %G_IO_ERROR_WOULD_BLOCK error.
949 * All sockets are created in blocking mode. However, note that the
950 * platform level socket is always non-blocking, and blocking mode
951 * is a GSocket level feature.
956 g_socket_set_blocking (GSocket *socket,
959 g_return_if_fail (G_IS_SOCKET (socket));
961 blocking = !!blocking;
963 if (socket->priv->blocking == blocking)
966 socket->priv->blocking = blocking;
967 g_object_notify (G_OBJECT (socket), "blocking");
971 * g_socket_get_blocking:
972 * @socket: a #GSocket.
974 * Gets the blocking mode of the socket. For details on blocking I/O,
975 * see g_socket_set_blocking().
977 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
982 g_socket_get_blocking (GSocket *socket)
984 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
986 return socket->priv->blocking;
990 * g_socket_set_keepalive:
991 * @socket: a #GSocket.
992 * @keepalive: Value for the keepalive flag
994 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
995 * this flag is set on a socket, the system will attempt to verify that the
996 * remote socket endpoint is still present if a sufficiently long period of
997 * time passes with no data being exchanged. If the system is unable to
998 * verify the presence of the remote endpoint, it will automatically close
1001 * This option is only functional on certain kinds of sockets. (Notably,
1002 * %G_SOCKET_PROTOCOL_TCP sockets.)
1004 * The exact time between pings is system- and protocol-dependent, but will
1005 * normally be at least two hours. Most commonly, you would set this flag
1006 * on a server socket if you want to allow clients to remain idle for long
1007 * periods of time, but also want to ensure that connections are eventually
1008 * garbage-collected if clients crash or become unreachable.
1013 g_socket_set_keepalive (GSocket *socket,
1018 g_return_if_fail (G_IS_SOCKET (socket));
1020 keepalive = !!keepalive;
1021 if (socket->priv->keepalive == keepalive)
1024 value = (gint) keepalive;
1025 if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_KEEPALIVE,
1026 (gpointer) &value, sizeof (value)) < 0)
1028 int errsv = get_socket_errno ();
1029 g_warning ("error setting keepalive: %s", socket_strerror (errsv));
1033 socket->priv->keepalive = keepalive;
1034 g_object_notify (G_OBJECT (socket), "keepalive");
1038 * g_socket_get_keepalive:
1039 * @socket: a #GSocket.
1041 * Gets the keepalive mode of the socket. For details on this,
1042 * see g_socket_set_keepalive().
1044 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1049 g_socket_get_keepalive (GSocket *socket)
1051 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1053 return socket->priv->keepalive;
1057 * g_socket_get_listen_backlog:
1058 * @socket: a #GSocket.
1060 * Gets the listen backlog setting of the socket. For details on this,
1061 * see g_socket_set_listen_backlog().
1063 * Returns: the maximum number of pending connections.
1068 g_socket_get_listen_backlog (GSocket *socket)
1070 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1072 return socket->priv->listen_backlog;
1076 * g_socket_set_listen_backlog:
1077 * @socket: a #GSocket.
1078 * @backlog: the maximum number of pending connections.
1080 * Sets the maximum number of outstanding connections allowed
1081 * when listening on this socket. If more clients than this are
1082 * connecting to the socket and the application is not handling them
1083 * on time then the new connections will be refused.
1085 * Note that this must be called before g_socket_listen() and has no
1086 * effect if called after that.
1091 g_socket_set_listen_backlog (GSocket *socket,
1094 g_return_if_fail (G_IS_SOCKET (socket));
1095 g_return_if_fail (!socket->priv->listening);
1097 if (backlog != socket->priv->listen_backlog)
1099 socket->priv->listen_backlog = backlog;
1100 g_object_notify (G_OBJECT (socket), "listen-backlog");
1105 * g_socket_get_timeout:
1106 * @socket: a #GSocket.
1108 * Gets the timeout setting of the socket. For details on this, see
1109 * g_socket_set_timeout().
1111 * Returns: the timeout in seconds
1116 g_socket_get_timeout (GSocket *socket)
1118 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1120 return socket->priv->timeout;
1124 * g_socket_set_timeout:
1125 * @socket: a #GSocket.
1126 * @timeout: the timeout for @socket, in seconds, or 0 for none
1128 * Sets the time in seconds after which I/O operations on @socket will
1129 * time out if they have not yet completed.
1131 * On a blocking socket, this means that any blocking #GSocket
1132 * operation will time out after @timeout seconds of inactivity,
1133 * returning %G_IO_ERROR_TIMED_OUT.
1135 * On a non-blocking socket, calls to g_socket_condition_wait() will
1136 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1137 * created with g_socket_create_source() will trigger after
1138 * @timeout seconds of inactivity, with the requested condition
1139 * set, at which point calling g_socket_receive(), g_socket_send(),
1140 * g_socket_check_connect_result(), etc, will fail with
1141 * %G_IO_ERROR_TIMED_OUT.
1143 * If @timeout is 0 (the default), operations will never time out
1146 * Note that if an I/O operation is interrupted by a signal, this may
1147 * cause the timeout to be reset.
1152 g_socket_set_timeout (GSocket *socket,
1155 g_return_if_fail (G_IS_SOCKET (socket));
1157 if (timeout != socket->priv->timeout)
1159 socket->priv->timeout = timeout;
1160 g_object_notify (G_OBJECT (socket), "timeout");
1165 * g_socket_get_family:
1166 * @socket: a #GSocket.
1168 * Gets the socket family of the socket.
1170 * Returns: a #GSocketFamily
1175 g_socket_get_family (GSocket *socket)
1177 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1179 return socket->priv->family;
1183 * g_socket_get_socket_type:
1184 * @socket: a #GSocket.
1186 * Gets the socket type of the socket.
1188 * Returns: a #GSocketType
1193 g_socket_get_socket_type (GSocket *socket)
1195 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1197 return socket->priv->type;
1201 * g_socket_get_protocol:
1202 * @socket: a #GSocket.
1204 * Gets the socket protocol id the socket was created with.
1205 * In case the protocol is unknown, -1 is returned.
1207 * Returns: a protocol id, or -1 if unknown
1212 g_socket_get_protocol (GSocket *socket)
1214 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1216 return socket->priv->protocol;
1221 * @socket: a #GSocket.
1223 * Returns the underlying OS socket object. On unix this
1224 * is a socket file descriptor, and on windows this is
1225 * a Winsock2 SOCKET handle. This may be useful for
1226 * doing platform specific or otherwise unusual operations
1229 * Returns: the file descriptor of the socket.
1234 g_socket_get_fd (GSocket *socket)
1236 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1238 return socket->priv->fd;
1242 * g_socket_get_local_address:
1243 * @socket: a #GSocket.
1244 * @error: #GError for error reporting, or %NULL to ignore.
1246 * Try to get the local address of a bound socket. This is only
1247 * useful if the socket has been bound to a local address,
1248 * either explicitly or implicitly when connecting.
1250 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1251 * Free the returned object with g_object_unref().
1256 g_socket_get_local_address (GSocket *socket,
1259 struct sockaddr_storage buffer;
1260 guint32 len = sizeof (buffer);
1262 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1264 if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1266 int errsv = get_socket_errno ();
1267 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1268 _("could not get local address: %s"), socket_strerror (errsv));
1272 return g_socket_address_new_from_native (&buffer, len);
1276 * g_socket_get_remote_address:
1277 * @socket: a #GSocket.
1278 * @error: #GError for error reporting, or %NULL to ignore.
1280 * Try to get the remove address of a connected socket. This is only
1281 * useful for connection oriented sockets that have been connected.
1283 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1284 * Free the returned object with g_object_unref().
1289 g_socket_get_remote_address (GSocket *socket,
1292 struct sockaddr_storage buffer;
1293 guint32 len = sizeof (buffer);
1295 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1297 if (socket->priv->connect_pending)
1299 if (!g_socket_check_connect_result (socket, error))
1302 socket->priv->connect_pending = FALSE;
1305 if (!socket->priv->remote_address)
1307 if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1309 int errsv = get_socket_errno ();
1310 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1311 _("could not get remote address: %s"), socket_strerror (errsv));
1315 socket->priv->remote_address = g_socket_address_new_from_native (&buffer, len);
1318 return g_object_ref (socket->priv->remote_address);
1322 * g_socket_is_connected:
1323 * @socket: a #GSocket.
1325 * Check whether the socket is connected. This is only useful for
1326 * connection-oriented sockets.
1328 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1333 g_socket_is_connected (GSocket *socket)
1335 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1337 return socket->priv->connected;
1342 * @socket: a #GSocket.
1343 * @error: #GError for error reporting, or %NULL to ignore.
1345 * Marks the socket as a server socket, i.e. a socket that is used
1346 * to accept incoming requests using g_socket_accept().
1348 * Before calling this the socket must be bound to a local address using
1351 * To set the maximum amount of outstanding clients, use
1352 * g_socket_set_listen_backlog().
1354 * Returns: %TRUE on success, %FALSE on error.
1359 g_socket_listen (GSocket *socket,
1362 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1364 if (!check_socket (socket, error))
1367 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1369 int errsv = get_socket_errno ();
1371 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1372 _("could not listen: %s"), socket_strerror (errsv));
1376 socket->priv->listening = TRUE;
1383 * @socket: a #GSocket.
1384 * @address: a #GSocketAddress specifying the local address.
1385 * @allow_reuse: whether to allow reusing this address
1386 * @error: #GError for error reporting, or %NULL to ignore.
1388 * When a socket is created it is attached to an address family, but it
1389 * doesn't have an address in this family. g_socket_bind() assigns the
1390 * address (sometimes called name) of the socket.
1392 * It is generally required to bind to a local address before you can
1393 * receive connections. (See g_socket_listen() and g_socket_accept() ).
1394 * In certain situations, you may also want to bind a socket that will be
1395 * used to initiate connections, though this is not normally required.
1397 * @allow_reuse should be %TRUE for server sockets (sockets that you will
1398 * eventually call g_socket_accept() on), and %FALSE for client sockets.
1399 * (Specifically, if it is %TRUE, then g_socket_bind() will set the
1400 * %SO_REUSEADDR flag on the socket, allowing it to bind @address even if
1401 * that address was previously used by another socket that has not yet been
1402 * fully cleaned-up by the kernel. Failing to set this flag on a server
1403 * socket may cause the bind call to return %G_IO_ERROR_ADDRESS_IN_USE if
1404 * the server program is stopped and then immediately restarted.)
1406 * Returns: %TRUE on success, %FALSE on error.
1411 g_socket_bind (GSocket *socket,
1412 GSocketAddress *address,
1413 gboolean reuse_address,
1416 struct sockaddr_storage addr;
1418 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1420 if (!check_socket (socket, error))
1423 /* SO_REUSEADDR on windows means something else and is not what we want.
1424 It always allows the unix variant of SO_REUSEADDR anyway */
1429 value = (int) !!reuse_address;
1430 /* Ignore errors here, the only likely error is "not supported", and
1431 this is a "best effort" thing mainly */
1432 setsockopt (socket->priv->fd, SOL_SOCKET, SO_REUSEADDR,
1433 (gpointer) &value, sizeof (value));
1437 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1440 if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1441 g_socket_address_get_native_size (address)) < 0)
1443 int errsv = get_socket_errno ();
1445 G_IO_ERROR, socket_io_error_from_errno (errsv),
1446 _("Error binding to address: %s"), socket_strerror (errsv));
1454 * g_socket_speaks_ipv4:
1455 * @socket: a #GSocket
1457 * Checks if a socket is capable of speaking IPv4.
1459 * IPv4 sockets are capable of speaking IPv4. On some operating systems
1460 * and under some combinations of circumstances IPv6 sockets are also
1461 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
1464 * No other types of sockets are currently considered as being capable
1467 * Returns: %TRUE if this socket can be used with IPv4.
1472 g_socket_speaks_ipv4 (GSocket *socket)
1474 switch (socket->priv->family)
1476 case G_SOCKET_FAMILY_IPV4:
1479 case G_SOCKET_FAMILY_IPV6:
1480 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
1482 guint sizeof_int = sizeof (int);
1485 if (getsockopt (socket->priv->fd,
1486 IPPROTO_IPV6, IPV6_V6ONLY,
1487 &v6_only, &sizeof_int) != 0)
1503 * @socket: a #GSocket.
1504 * @cancellable: (allow-none): a %GCancellable or %NULL
1505 * @error: #GError for error reporting, or %NULL to ignore.
1507 * Accept incoming connections on a connection-based socket. This removes
1508 * the first outstanding connection request from the listening socket and
1509 * creates a #GSocket object for it.
1511 * The @socket must be bound to a local address with g_socket_bind() and
1512 * must be listening for incoming connections (g_socket_listen()).
1514 * If there are no outstanding connections then the operation will block
1515 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
1516 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
1518 * Returns: (transfer full): a new #GSocket, or %NULL on error.
1519 * Free the returned object with g_object_unref().
1524 g_socket_accept (GSocket *socket,
1525 GCancellable *cancellable,
1528 GSocket *new_socket;
1531 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1533 if (!check_socket (socket, error))
1538 if (socket->priv->blocking &&
1539 !g_socket_condition_wait (socket,
1540 G_IO_IN, cancellable, error))
1543 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
1545 int errsv = get_socket_errno ();
1547 win32_unset_event_mask (socket, FD_ACCEPT);
1552 if (socket->priv->blocking)
1554 #ifdef WSAEWOULDBLOCK
1555 if (errsv == WSAEWOULDBLOCK)
1558 if (errsv == EWOULDBLOCK ||
1564 g_set_error (error, G_IO_ERROR,
1565 socket_io_error_from_errno (errsv),
1566 _("Error accepting connection: %s"), socket_strerror (errsv));
1572 win32_unset_event_mask (socket, FD_ACCEPT);
1576 /* The socket inherits the accepting sockets event mask and even object,
1577 we need to remove that */
1578 WSAEventSelect (ret, NULL, 0);
1584 /* We always want to set close-on-exec to protect users. If you
1585 need to so some weird inheritance to exec you can re-enable this
1586 using lower level hacks with g_socket_get_fd(). */
1587 flags = fcntl (ret, F_GETFD, 0);
1589 (flags & FD_CLOEXEC) == 0)
1591 flags |= FD_CLOEXEC;
1592 fcntl (ret, F_SETFD, flags);
1597 new_socket = g_socket_new_from_fd (ret, error);
1598 if (new_socket == NULL)
1607 new_socket->priv->protocol = socket->priv->protocol;
1614 * @socket: a #GSocket.
1615 * @address: a #GSocketAddress specifying the remote address.
1616 * @cancellable: (allow-none): a %GCancellable or %NULL
1617 * @error: #GError for error reporting, or %NULL to ignore.
1619 * Connect the socket to the specified remote address.
1621 * For connection oriented socket this generally means we attempt to make
1622 * a connection to the @address. For a connection-less socket it sets
1623 * the default address for g_socket_send() and discards all incoming datagrams
1624 * from other sources.
1626 * Generally connection oriented sockets can only connect once, but
1627 * connection-less sockets can connect multiple times to change the
1630 * If the connect call needs to do network I/O it will block, unless
1631 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
1632 * and the user can be notified of the connection finishing by waiting
1633 * for the G_IO_OUT condition. The result of the connection must then be
1634 * checked with g_socket_check_connect_result().
1636 * Returns: %TRUE if connected, %FALSE on error.
1641 g_socket_connect (GSocket *socket,
1642 GSocketAddress *address,
1643 GCancellable *cancellable,
1646 struct sockaddr_storage buffer;
1648 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1650 if (!check_socket (socket, error))
1653 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
1656 if (socket->priv->remote_address)
1657 g_object_unref (socket->priv->remote_address);
1658 socket->priv->remote_address = g_object_ref (address);
1662 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
1663 g_socket_address_get_native_size (address)) < 0)
1665 int errsv = get_socket_errno ();
1671 if (errsv == EINPROGRESS)
1673 if (errsv == WSAEWOULDBLOCK)
1676 if (socket->priv->blocking)
1678 if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
1680 if (g_socket_check_connect_result (socket, error))
1683 g_prefix_error (error, _("Error connecting: "));
1687 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
1688 _("Connection in progress"));
1689 socket->priv->connect_pending = TRUE;
1693 g_set_error (error, G_IO_ERROR,
1694 socket_io_error_from_errno (errsv),
1695 _("Error connecting: %s"), socket_strerror (errsv));
1702 win32_unset_event_mask (socket, FD_CONNECT);
1704 socket->priv->connected = TRUE;
1710 * g_socket_check_connect_result:
1711 * @socket: a #GSocket
1712 * @error: #GError for error reporting, or %NULL to ignore.
1714 * Checks and resets the pending connect error for the socket.
1715 * This is used to check for errors when g_socket_connect() is
1716 * used in non-blocking mode.
1718 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
1723 g_socket_check_connect_result (GSocket *socket,
1729 if (!check_socket (socket, error))
1732 optlen = sizeof (value);
1733 if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
1735 int errsv = get_socket_errno ();
1737 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1738 _("Unable to get pending error: %s"), socket_strerror (errsv));
1744 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
1745 socket_strerror (value));
1746 if (socket->priv->remote_address)
1748 g_object_unref (socket->priv->remote_address);
1749 socket->priv->remote_address = NULL;
1754 socket->priv->connected = TRUE;
1760 * @socket: a #GSocket
1761 * @buffer: a buffer to read data into (which should be at least @size
1763 * @size: the number of bytes you want to read from the socket
1764 * @cancellable: (allow-none): a %GCancellable or %NULL
1765 * @error: #GError for error reporting, or %NULL to ignore.
1767 * Receive data (up to @size bytes) from a socket. This is mainly used by
1768 * connection-oriented sockets; it is identical to g_socket_receive_from()
1769 * with @address set to %NULL.
1771 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
1772 * g_socket_receive() will always read either 0 or 1 complete messages from
1773 * the socket. If the received message is too large to fit in @buffer, then
1774 * the data beyond @size bytes will be discarded, without any explicit
1775 * indication that this has occurred.
1777 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
1778 * number of bytes, up to @size. If more than @size bytes have been
1779 * received, the additional data will be returned in future calls to
1780 * g_socket_receive().
1782 * If the socket is in blocking mode the call will block until there
1783 * is some data to receive, the connection is closed, or there is an
1784 * error. If there is no data available and the socket is in
1785 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
1786 * returned. To be notified when data is available, wait for the
1787 * %G_IO_IN condition.
1789 * On error -1 is returned and @error is set accordingly.
1791 * Returns: Number of bytes read, or 0 if the connection was closed by
1792 * the peer, or -1 on error
1797 g_socket_receive (GSocket *socket,
1800 GCancellable *cancellable,
1803 return g_socket_receive_with_blocking (socket, buffer, size,
1804 socket->priv->blocking,
1805 cancellable, error);
1809 * g_socket_receive_with_blocking:
1810 * @socket: a #GSocket
1811 * @buffer: a buffer to read data into (which should be at least @size
1813 * @size: the number of bytes you want to read from the socket
1814 * @blocking: whether to do blocking or non-blocking I/O
1815 * @cancellable: (allow-none): a %GCancellable or %NULL
1816 * @error: #GError for error reporting, or %NULL to ignore.
1818 * This behaves exactly the same as g_socket_receive(), except that
1819 * the choice of blocking or non-blocking behavior is determined by
1820 * the @blocking argument rather than by @socket's properties.
1822 * Returns: Number of bytes read, or 0 if the connection was closed by
1823 * the peer, or -1 on error
1828 g_socket_receive_with_blocking (GSocket *socket,
1832 GCancellable *cancellable,
1837 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1839 if (!check_socket (socket, error))
1842 if (g_cancellable_set_error_if_cancelled (cancellable, error))
1848 !g_socket_condition_wait (socket,
1849 G_IO_IN, cancellable, error))
1852 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
1854 int errsv = get_socket_errno ();
1861 #ifdef WSAEWOULDBLOCK
1862 if (errsv == WSAEWOULDBLOCK)
1865 if (errsv == EWOULDBLOCK ||
1871 win32_unset_event_mask (socket, FD_READ);
1873 g_set_error (error, G_IO_ERROR,
1874 socket_io_error_from_errno (errsv),
1875 _("Error receiving data: %s"), socket_strerror (errsv));
1879 win32_unset_event_mask (socket, FD_READ);
1888 * g_socket_receive_from:
1889 * @socket: a #GSocket
1890 * @address: a pointer to a #GSocketAddress pointer, or %NULL
1891 * @buffer: a buffer to read data into (which should be at least @size
1893 * @size: the number of bytes you want to read from the socket
1894 * @cancellable: (allow-none): a %GCancellable or %NULL
1895 * @error: #GError for error reporting, or %NULL to ignore.
1897 * Receive data (up to @size bytes) from a socket.
1899 * If @address is non-%NULL then @address will be set equal to the
1900 * source address of the received packet.
1901 * @address is owned by the caller.
1903 * See g_socket_receive() for additional information.
1905 * Returns: Number of bytes read, or 0 if the connection was closed by
1906 * the peer, or -1 on error
1911 g_socket_receive_from (GSocket *socket,
1912 GSocketAddress **address,
1915 GCancellable *cancellable,
1923 return g_socket_receive_message (socket,
1931 /* Although we ignore SIGPIPE, gdb will still stop if the app receives
1932 * one, which can be confusing and annoying. So if possible, we want
1933 * to suppress the signal entirely.
1936 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
1938 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
1943 * @socket: a #GSocket
1944 * @buffer: (array length=size): the buffer containing the data to send.
1945 * @size: the number of bytes to send
1946 * @cancellable: (allow-none): a %GCancellable or %NULL
1947 * @error: #GError for error reporting, or %NULL to ignore.
1949 * Tries to send @size bytes from @buffer on the socket. This is
1950 * mainly used by connection-oriented sockets; it is identical to
1951 * g_socket_send_to() with @address set to %NULL.
1953 * If the socket is in blocking mode the call will block until there is
1954 * space for the data in the socket queue. If there is no space available
1955 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1956 * will be returned. To be notified when space is available, wait for the
1957 * %G_IO_OUT condition. Note though that you may still receive
1958 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
1959 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
1960 * very common due to the way the underlying APIs work.)
1962 * On error -1 is returned and @error is set accordingly.
1964 * Returns: Number of bytes written (which may be less than @size), or -1
1970 g_socket_send (GSocket *socket,
1971 const gchar *buffer,
1973 GCancellable *cancellable,
1976 return g_socket_send_with_blocking (socket, buffer, size,
1977 socket->priv->blocking,
1978 cancellable, error);
1982 * g_socket_send_with_blocking:
1983 * @socket: a #GSocket
1984 * @buffer: (array length=size): the buffer containing the data to send.
1985 * @size: the number of bytes to send
1986 * @blocking: whether to do blocking or non-blocking I/O
1987 * @cancellable: (allow-none): a %GCancellable or %NULL
1988 * @error: #GError for error reporting, or %NULL to ignore.
1990 * This behaves exactly the same as g_socket_send(), except that
1991 * the choice of blocking or non-blocking behavior is determined by
1992 * the @blocking argument rather than by @socket's properties.
1994 * Returns: Number of bytes written (which may be less than @size), or -1
2000 g_socket_send_with_blocking (GSocket *socket,
2001 const gchar *buffer,
2004 GCancellable *cancellable,
2009 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
2011 if (!check_socket (socket, error))
2014 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2020 !g_socket_condition_wait (socket,
2021 G_IO_OUT, cancellable, error))
2024 if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
2026 int errsv = get_socket_errno ();
2031 #ifdef WSAEWOULDBLOCK
2032 if (errsv == WSAEWOULDBLOCK)
2033 win32_unset_event_mask (socket, FD_WRITE);
2038 #ifdef WSAEWOULDBLOCK
2039 if (errsv == WSAEWOULDBLOCK)
2042 if (errsv == EWOULDBLOCK ||
2048 g_set_error (error, G_IO_ERROR,
2049 socket_io_error_from_errno (errsv),
2050 _("Error sending data: %s"), socket_strerror (errsv));
2061 * @socket: a #GSocket
2062 * @address: a #GSocketAddress, or %NULL
2063 * @buffer: (array length=size): the buffer containing the data to send.
2064 * @size: the number of bytes to send
2065 * @cancellable: (allow-none): a %GCancellable or %NULL
2066 * @error: #GError for error reporting, or %NULL to ignore.
2068 * Tries to send @size bytes from @buffer to @address. If @address is
2069 * %NULL then the message is sent to the default receiver (set by
2070 * g_socket_connect()).
2072 * See g_socket_send() for additional information.
2074 * Returns: Number of bytes written (which may be less than @size), or -1
2080 g_socket_send_to (GSocket *socket,
2081 GSocketAddress *address,
2082 const gchar *buffer,
2084 GCancellable *cancellable,
2092 return g_socket_send_message (socket,
2102 * g_socket_shutdown:
2103 * @socket: a #GSocket
2104 * @shutdown_read: whether to shut down the read side
2105 * @shutdown_write: whether to shut down the write side
2106 * @error: #GError for error reporting, or %NULL to ignore.
2108 * Shut down part of a full-duplex connection.
2110 * If @shutdown_read is %TRUE then the receiving side of the connection
2111 * is shut down, and further reading is disallowed.
2113 * If @shutdown_write is %TRUE then the sending side of the connection
2114 * is shut down, and further writing is disallowed.
2116 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
2118 * One example where this is used is graceful disconnect for TCP connections
2119 * where you close the sending side, then wait for the other side to close
2120 * the connection, thus ensuring that the other side saw all sent data.
2122 * Returns: %TRUE on success, %FALSE on error
2127 g_socket_shutdown (GSocket *socket,
2128 gboolean shutdown_read,
2129 gboolean shutdown_write,
2134 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2136 if (!check_socket (socket, error))
2140 if (!shutdown_read && !shutdown_write)
2144 if (shutdown_read && shutdown_write)
2146 else if (shutdown_read)
2151 if (shutdown_read && shutdown_write)
2153 else if (shutdown_read)
2159 if (shutdown (socket->priv->fd, how) != 0)
2161 int errsv = get_socket_errno ();
2162 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2163 _("Unable to shutdown socket: %s"), socket_strerror (errsv));
2167 if (shutdown_read && shutdown_write)
2168 socket->priv->connected = FALSE;
2175 * @socket: a #GSocket
2176 * @error: #GError for error reporting, or %NULL to ignore.
2178 * Closes the socket, shutting down any active connection.
2180 * Closing a socket does not wait for all outstanding I/O operations
2181 * to finish, so the caller should not rely on them to be guaranteed
2182 * to complete even if the close returns with no error.
2184 * Once the socket is closed, all other operations will return
2185 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
2188 * Sockets will be automatically closed when the last reference
2189 * is dropped, but you might want to call this function to make sure
2190 * resources are released as early as possible.
2192 * Beware that due to the way that TCP works, it is possible for
2193 * recently-sent data to be lost if either you close a socket while the
2194 * %G_IO_IN condition is set, or else if the remote connection tries to
2195 * send something to you after you close the socket but before it has
2196 * finished reading all of the data you sent. There is no easy generic
2197 * way to avoid this problem; the easiest fix is to design the network
2198 * protocol such that the client will never send data "out of turn".
2199 * Another solution is for the server to half-close the connection by
2200 * calling g_socket_shutdown() with only the @shutdown_write flag set,
2201 * and then wait for the client to notice this and close its side of the
2202 * connection, after which the server can safely call g_socket_close().
2203 * (This is what #GTcpConnection does if you call
2204 * g_tcp_connection_set_graceful_disconnect(). But of course, this
2205 * only works if the client will close its connection after the server
2208 * Returns: %TRUE on success, %FALSE on error
2213 g_socket_close (GSocket *socket,
2218 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2220 if (socket->priv->closed)
2221 return TRUE; /* Multiple close not an error */
2223 if (!check_socket (socket, error))
2229 res = closesocket (socket->priv->fd);
2231 res = close (socket->priv->fd);
2235 int errsv = get_socket_errno ();
2240 g_set_error (error, G_IO_ERROR,
2241 socket_io_error_from_errno (errsv),
2242 _("Error closing socket: %s"),
2243 socket_strerror (errsv));
2249 socket->priv->connected = FALSE;
2250 socket->priv->closed = TRUE;
2251 if (socket->priv->remote_address)
2253 g_object_unref (socket->priv->remote_address);
2254 socket->priv->remote_address = NULL;
2261 * g_socket_is_closed:
2262 * @socket: a #GSocket
2264 * Checks whether a socket is closed.
2266 * Returns: %TRUE if socket is closed, %FALSE otherwise
2271 g_socket_is_closed (GSocket *socket)
2273 return socket->priv->closed;
2277 /* Broken source, used on errors */
2279 broken_prepare (GSource *source,
2286 broken_check (GSource *source)
2292 broken_dispatch (GSource *source,
2293 GSourceFunc callback,
2299 static GSourceFuncs broken_funcs =
2308 network_events_for_condition (GIOCondition condition)
2312 if (condition & G_IO_IN)
2313 event_mask |= (FD_READ | FD_ACCEPT);
2314 if (condition & G_IO_OUT)
2315 event_mask |= (FD_WRITE | FD_CONNECT);
2316 event_mask |= FD_CLOSE;
2322 ensure_event (GSocket *socket)
2324 if (socket->priv->event == WSA_INVALID_EVENT)
2325 socket->priv->event = WSACreateEvent();
2329 update_select_events (GSocket *socket)
2336 ensure_event (socket);
2339 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
2342 event_mask |= network_events_for_condition (*ptr);
2345 if (event_mask != socket->priv->selected_events)
2347 /* If no events selected, disable event so we can unset
2350 if (event_mask == 0)
2353 event = socket->priv->event;
2355 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
2356 socket->priv->selected_events = event_mask;
2361 add_condition_watch (GSocket *socket,
2362 GIOCondition *condition)
2364 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
2366 socket->priv->requested_conditions =
2367 g_list_prepend (socket->priv->requested_conditions, condition);
2369 update_select_events (socket);
2373 remove_condition_watch (GSocket *socket,
2374 GIOCondition *condition)
2376 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
2378 socket->priv->requested_conditions =
2379 g_list_remove (socket->priv->requested_conditions, condition);
2381 update_select_events (socket);
2385 update_condition (GSocket *socket)
2387 WSANETWORKEVENTS events;
2388 GIOCondition condition;
2390 if (WSAEnumNetworkEvents (socket->priv->fd,
2391 socket->priv->event,
2394 socket->priv->current_events |= events.lNetworkEvents;
2395 if (events.lNetworkEvents & FD_WRITE &&
2396 events.iErrorCode[FD_WRITE_BIT] != 0)
2397 socket->priv->current_errors |= FD_WRITE;
2398 if (events.lNetworkEvents & FD_CONNECT &&
2399 events.iErrorCode[FD_CONNECT_BIT] != 0)
2400 socket->priv->current_errors |= FD_CONNECT;
2404 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
2405 condition |= G_IO_IN;
2407 if (socket->priv->current_events & FD_CLOSE ||
2408 socket->priv->closed)
2409 condition |= G_IO_HUP;
2411 /* Never report both G_IO_OUT and HUP, these are
2412 mutually exclusive (can't write to a closed socket) */
2413 if ((condition & G_IO_HUP) == 0 &&
2414 socket->priv->current_events & FD_WRITE)
2416 if (socket->priv->current_errors & FD_WRITE)
2417 condition |= G_IO_ERR;
2419 condition |= G_IO_OUT;
2423 if (socket->priv->current_events & FD_CONNECT)
2425 if (socket->priv->current_errors & FD_CONNECT)
2426 condition |= (G_IO_HUP | G_IO_ERR);
2428 condition |= G_IO_OUT;
2440 GIOCondition condition;
2441 GCancellable *cancellable;
2442 GPollFD cancel_pollfd;
2443 gint64 timeout_time;
2447 socket_source_prepare (GSource *source,
2450 GSocketSource *socket_source = (GSocketSource *)source;
2452 if (g_cancellable_is_cancelled (socket_source->cancellable))
2455 if (socket_source->timeout_time)
2459 now = g_source_get_time (source);
2460 /* Round up to ensure that we don't try again too early */
2461 *timeout = (socket_source->timeout_time - now + 999) / 1000;
2464 socket_source->socket->priv->timed_out = TRUE;
2473 socket_source->pollfd.revents = update_condition (socket_source->socket);
2476 if ((socket_source->condition & socket_source->pollfd.revents) != 0)
2483 socket_source_check (GSource *source)
2487 return socket_source_prepare (source, &timeout);
2491 socket_source_dispatch (GSource *source,
2492 GSourceFunc callback,
2495 GSocketSourceFunc func = (GSocketSourceFunc)callback;
2496 GSocketSource *socket_source = (GSocketSource *)source;
2499 socket_source->pollfd.revents = update_condition (socket_source->socket);
2501 if (socket_source->socket->priv->timed_out)
2502 socket_source->pollfd.revents |= socket_source->condition & (G_IO_IN | G_IO_OUT);
2504 return (*func) (socket_source->socket,
2505 socket_source->pollfd.revents & socket_source->condition,
2510 socket_source_finalize (GSource *source)
2512 GSocketSource *socket_source = (GSocketSource *)source;
2515 socket = socket_source->socket;
2518 remove_condition_watch (socket, &socket_source->condition);
2521 g_object_unref (socket);
2523 if (socket_source->cancellable)
2525 g_cancellable_release_fd (socket_source->cancellable);
2526 g_object_unref (socket_source->cancellable);
2531 socket_source_closure_callback (GSocket *socket,
2532 GIOCondition condition,
2535 GClosure *closure = data;
2537 GValue params[2] = { { 0, }, { 0, } };
2538 GValue result_value = { 0, };
2541 g_value_init (&result_value, G_TYPE_BOOLEAN);
2543 g_value_init (¶ms[0], G_TYPE_SOCKET);
2544 g_value_set_object (¶ms[0], socket);
2545 g_value_init (¶ms[1], G_TYPE_IO_CONDITION);
2546 g_value_set_flags (¶ms[1], condition);
2548 g_closure_invoke (closure, &result_value, 2, params, NULL);
2550 result = g_value_get_boolean (&result_value);
2551 g_value_unset (&result_value);
2552 g_value_unset (¶ms[0]);
2553 g_value_unset (¶ms[1]);
2558 static GSourceFuncs socket_source_funcs =
2560 socket_source_prepare,
2561 socket_source_check,
2562 socket_source_dispatch,
2563 socket_source_finalize,
2564 (GSourceFunc)socket_source_closure_callback,
2565 (GSourceDummyMarshal)g_cclosure_marshal_generic,
2569 socket_source_new (GSocket *socket,
2570 GIOCondition condition,
2571 GCancellable *cancellable)
2574 GSocketSource *socket_source;
2577 ensure_event (socket);
2579 if (socket->priv->event == WSA_INVALID_EVENT)
2581 g_warning ("Failed to create WSAEvent");
2582 return g_source_new (&broken_funcs, sizeof (GSource));
2586 condition |= G_IO_HUP | G_IO_ERR;
2588 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
2589 g_source_set_name (source, "GSocket");
2590 socket_source = (GSocketSource *)source;
2592 socket_source->socket = g_object_ref (socket);
2593 socket_source->condition = condition;
2595 if (g_cancellable_make_pollfd (cancellable,
2596 &socket_source->cancel_pollfd))
2598 socket_source->cancellable = g_object_ref (cancellable);
2599 g_source_add_poll (source, &socket_source->cancel_pollfd);
2603 add_condition_watch (socket, &socket_source->condition);
2604 socket_source->pollfd.fd = (gintptr) socket->priv->event;
2606 socket_source->pollfd.fd = socket->priv->fd;
2609 socket_source->pollfd.events = condition;
2610 socket_source->pollfd.revents = 0;
2611 g_source_add_poll (source, &socket_source->pollfd);
2613 if (socket->priv->timeout)
2614 socket_source->timeout_time = g_get_monotonic_time () +
2615 socket->priv->timeout * 1000000;
2618 socket_source->timeout_time = 0;
2624 * g_socket_create_source: (skip)
2625 * @socket: a #GSocket
2626 * @condition: a #GIOCondition mask to monitor
2627 * @cancellable: (allow-none): a %GCancellable or %NULL
2629 * Creates a %GSource that can be attached to a %GMainContext to monitor
2630 * for the availibility of the specified @condition on the socket.
2632 * The callback on the source is of the #GSocketSourceFunc type.
2634 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
2635 * these conditions will always be reported output if they are true.
2637 * @cancellable if not %NULL can be used to cancel the source, which will
2638 * cause the source to trigger, reporting the current condition (which
2639 * is likely 0 unless cancellation happened at the same time as a
2640 * condition change). You can check for this in the callback using
2641 * g_cancellable_is_cancelled().
2643 * If @socket has a timeout set, and it is reached before @condition
2644 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
2645 * %G_IO_OUT depending on @condition. However, @socket will have been
2646 * marked as having had a timeout, and so the next #GSocket I/O method
2647 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
2649 * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
2654 g_socket_create_source (GSocket *socket,
2655 GIOCondition condition,
2656 GCancellable *cancellable)
2658 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
2660 return socket_source_new (socket, condition, cancellable);
2664 * g_socket_condition_check:
2665 * @socket: a #GSocket
2666 * @condition: a #GIOCondition mask to check
2668 * Checks on the readiness of @socket to perform operations.
2669 * The operations specified in @condition are checked for and masked
2670 * against the currently-satisfied conditions on @socket. The result
2673 * Note that on Windows, it is possible for an operation to return
2674 * %G_IO_ERROR_WOULD_BLOCK even immediately after
2675 * g_socket_condition_check() has claimed that the socket is ready for
2676 * writing. Rather than calling g_socket_condition_check() and then
2677 * writing to the socket if it succeeds, it is generally better to
2678 * simply try writing to the socket right away, and try again later if
2679 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
2681 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2682 * these conditions will always be set in the output if they are true.
2684 * This call never blocks.
2686 * Returns: the @GIOCondition mask of the current state
2691 g_socket_condition_check (GSocket *socket,
2692 GIOCondition condition)
2694 if (!check_socket (socket, NULL))
2699 GIOCondition current_condition;
2701 condition |= G_IO_ERR | G_IO_HUP;
2703 add_condition_watch (socket, &condition);
2704 current_condition = update_condition (socket);
2705 remove_condition_watch (socket, &condition);
2706 return condition & current_condition;
2712 poll_fd.fd = socket->priv->fd;
2713 poll_fd.events = condition;
2716 result = g_poll (&poll_fd, 1, 0);
2717 while (result == -1 && get_socket_errno () == EINTR);
2719 return poll_fd.revents;
2725 * g_socket_condition_wait:
2726 * @socket: a #GSocket
2727 * @condition: a #GIOCondition mask to wait for
2728 * @cancellable: (allow-none): a #GCancellable, or %NULL
2729 * @error: a #GError pointer, or %NULL
2731 * Waits for @condition to become true on @socket. When the condition
2732 * is met, %TRUE is returned.
2734 * If @cancellable is cancelled before the condition is met, or if the
2735 * socket has a timeout set and it is reached before the condition is
2736 * met, then %FALSE is returned and @error, if non-%NULL, is set to
2737 * the appropriate value (%G_IO_ERROR_CANCELLED or
2738 * %G_IO_ERROR_TIMED_OUT).
2740 * Returns: %TRUE if the condition was met, %FALSE otherwise
2745 g_socket_condition_wait (GSocket *socket,
2746 GIOCondition condition,
2747 GCancellable *cancellable,
2750 if (!check_socket (socket, error))
2753 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2758 GIOCondition current_condition;
2764 /* Always check these */
2765 condition |= G_IO_ERR | G_IO_HUP;
2767 add_condition_watch (socket, &condition);
2770 events[num_events++] = socket->priv->event;
2772 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
2773 events[num_events++] = (WSAEVENT)cancel_fd.fd;
2775 if (socket->priv->timeout)
2776 timeout = socket->priv->timeout * 1000;
2778 timeout = WSA_INFINITE;
2780 current_condition = update_condition (socket);
2781 while ((condition & current_condition) == 0)
2783 res = WSAWaitForMultipleEvents(num_events, events,
2784 FALSE, timeout, FALSE);
2785 if (res == WSA_WAIT_FAILED)
2787 int errsv = get_socket_errno ();
2789 g_set_error (error, G_IO_ERROR,
2790 socket_io_error_from_errno (errsv),
2791 _("Waiting for socket condition: %s"),
2792 socket_strerror (errsv));
2795 else if (res == WSA_WAIT_TIMEOUT)
2797 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
2798 _("Socket I/O timed out"));
2802 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2805 current_condition = update_condition (socket);
2807 remove_condition_watch (socket, &condition);
2809 g_cancellable_release_fd (cancellable);
2811 return (condition & current_condition) != 0;
2820 poll_fd[0].fd = socket->priv->fd;
2821 poll_fd[0].events = condition;
2824 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
2827 if (socket->priv->timeout)
2828 timeout = socket->priv->timeout * 1000;
2833 result = g_poll (poll_fd, num, timeout);
2834 while (result == -1 && get_socket_errno () == EINTR);
2837 g_cancellable_release_fd (cancellable);
2841 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
2842 _("Socket I/O timed out"));
2846 return !g_cancellable_set_error_if_cancelled (cancellable, error);
2852 * g_socket_send_message:
2853 * @socket: a #GSocket
2854 * @address: a #GSocketAddress, or %NULL
2855 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
2856 * @num_vectors: the number of elements in @vectors, or -1
2857 * @messages: (array length=num_messages) (allow-none): a pointer to an
2858 * array of #GSocketControlMessages, or %NULL.
2859 * @num_messages: number of elements in @messages, or -1.
2860 * @flags: an int containing #GSocketMsgFlags flags
2861 * @cancellable: (allow-none): a %GCancellable or %NULL
2862 * @error: #GError for error reporting, or %NULL to ignore.
2864 * Send data to @address on @socket. This is the most complicated and
2865 * fully-featured version of this call. For easier use, see
2866 * g_socket_send() and g_socket_send_to().
2868 * If @address is %NULL then the message is sent to the default receiver
2869 * (set by g_socket_connect()).
2871 * @vectors must point to an array of #GOutputVector structs and
2872 * @num_vectors must be the length of this array. (If @num_vectors is -1,
2873 * then @vectors is assumed to be terminated by a #GOutputVector with a
2874 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
2875 * that the sent data will be gathered from. Using multiple
2876 * #GOutputVector<!-- -->s is more memory-efficient than manually copying
2877 * data from multiple sources into a single buffer, and more
2878 * network-efficient than making multiple calls to g_socket_send().
2880 * @messages, if non-%NULL, is taken to point to an array of @num_messages
2881 * #GSocketControlMessage instances. These correspond to the control
2882 * messages to be sent on the socket.
2883 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
2886 * @flags modify how the message is sent. The commonly available arguments
2887 * for this are available in the #GSocketMsgFlags enum, but the
2888 * values there are the same as the system values, and the flags
2889 * are passed in as-is, so you can pass in system-specific flags too.
2891 * If the socket is in blocking mode the call will block until there is
2892 * space for the data in the socket queue. If there is no space available
2893 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2894 * will be returned. To be notified when space is available, wait for the
2895 * %G_IO_OUT condition. Note though that you may still receive
2896 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2897 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2898 * very common due to the way the underlying APIs work.)
2900 * On error -1 is returned and @error is set accordingly.
2902 * Returns: Number of bytes written (which may be less than @size), or -1
2908 g_socket_send_message (GSocket *socket,
2909 GSocketAddress *address,
2910 GOutputVector *vectors,
2912 GSocketControlMessage **messages,
2915 GCancellable *cancellable,
2918 GOutputVector one_vector;
2921 if (!check_socket (socket, error))
2924 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2927 if (num_vectors == -1)
2929 for (num_vectors = 0;
2930 vectors[num_vectors].buffer != NULL;
2935 if (num_messages == -1)
2937 for (num_messages = 0;
2938 messages != NULL && messages[num_messages] != NULL;
2943 if (num_vectors == 0)
2947 one_vector.buffer = &zero;
2948 one_vector.size = 1;
2950 vectors = &one_vector;
2963 msg.msg_namelen = g_socket_address_get_native_size (address);
2964 msg.msg_name = g_alloca (msg.msg_namelen);
2965 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
2970 msg.msg_name = NULL;
2971 msg.msg_namelen = 0;
2976 /* this entire expression will be evaluated at compile time */
2977 if (sizeof *msg.msg_iov == sizeof *vectors &&
2978 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2979 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2980 G_STRUCT_OFFSET (GOutputVector, buffer) &&
2981 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2982 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2983 G_STRUCT_OFFSET (GOutputVector, size))
2984 /* ABI is compatible */
2986 msg.msg_iov = (struct iovec *) vectors;
2987 msg.msg_iovlen = num_vectors;
2990 /* ABI is incompatible */
2994 msg.msg_iov = g_newa (struct iovec, num_vectors);
2995 for (i = 0; i < num_vectors; i++)
2997 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
2998 msg.msg_iov[i].iov_len = vectors[i].size;
3000 msg.msg_iovlen = num_vectors;
3006 struct cmsghdr *cmsg;
3009 msg.msg_controllen = 0;
3010 for (i = 0; i < num_messages; i++)
3011 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
3013 if (msg.msg_controllen == 0)
3014 msg.msg_control = NULL;
3017 msg.msg_control = g_alloca (msg.msg_controllen);
3018 memset (msg.msg_control, '\0', msg.msg_controllen);
3021 cmsg = CMSG_FIRSTHDR (&msg);
3022 for (i = 0; i < num_messages; i++)
3024 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
3025 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
3026 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
3027 g_socket_control_message_serialize (messages[i],
3029 cmsg = CMSG_NXTHDR (&msg, cmsg);
3031 g_assert (cmsg == NULL);
3036 if (socket->priv->blocking &&
3037 !g_socket_condition_wait (socket,
3038 G_IO_OUT, cancellable, error))
3041 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
3044 int errsv = get_socket_errno ();
3049 if (socket->priv->blocking &&
3050 (errsv == EWOULDBLOCK ||
3054 g_set_error (error, G_IO_ERROR,
3055 socket_io_error_from_errno (errsv),
3056 _("Error sending message: %s"), socket_strerror (errsv));
3067 struct sockaddr_storage addr;
3074 /* Win32 doesn't support control messages.
3075 Actually this is possible for raw and datagram sockets
3076 via WSASendMessage on Vista or later, but that doesn't
3078 if (num_messages != 0)
3080 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
3081 _("GSocketControlMessage not supported on windows"));
3086 bufs = g_newa (WSABUF, num_vectors);
3087 for (i = 0; i < num_vectors; i++)
3089 bufs[i].buf = (char *)vectors[i].buffer;
3090 bufs[i].len = (gulong)vectors[i].size;
3094 addrlen = 0; /* Avoid warning */
3097 addrlen = g_socket_address_get_native_size (address);
3098 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
3104 if (socket->priv->blocking &&
3105 !g_socket_condition_wait (socket,
3106 G_IO_OUT, cancellable, error))
3110 result = WSASendTo (socket->priv->fd,
3113 (const struct sockaddr *)&addr, addrlen,
3116 result = WSASend (socket->priv->fd,
3123 int errsv = get_socket_errno ();
3125 if (errsv == WSAEINTR)
3128 if (errsv == WSAEWOULDBLOCK)
3129 win32_unset_event_mask (socket, FD_WRITE);
3131 if (socket->priv->blocking &&
3132 errsv == WSAEWOULDBLOCK)
3135 g_set_error (error, G_IO_ERROR,
3136 socket_io_error_from_errno (errsv),
3137 _("Error sending message: %s"), socket_strerror (errsv));
3150 * g_socket_receive_message:
3151 * @socket: a #GSocket
3152 * @address: a pointer to a #GSocketAddress pointer, or %NULL
3153 * @vectors: (array length=num_vectors): an array of #GInputVector structs
3154 * @num_vectors: the number of elements in @vectors, or -1
3155 * @messages: (array length=num_messages) (allow-none): a pointer which
3156 * may be filled with an array of #GSocketControlMessages, or %NULL
3157 * @num_messages: a pointer which will be filled with the number of
3158 * elements in @messages, or %NULL
3159 * @flags: a pointer to an int containing #GSocketMsgFlags flags
3160 * @cancellable: (allow-none): a %GCancellable or %NULL
3161 * @error: a #GError pointer, or %NULL
3163 * Receive data from a socket. This is the most complicated and
3164 * fully-featured version of this call. For easier use, see
3165 * g_socket_receive() and g_socket_receive_from().
3167 * If @address is non-%NULL then @address will be set equal to the
3168 * source address of the received packet.
3169 * @address is owned by the caller.
3171 * @vector must point to an array of #GInputVector structs and
3172 * @num_vectors must be the length of this array. These structs
3173 * describe the buffers that received data will be scattered into.
3174 * If @num_vectors is -1, then @vectors is assumed to be terminated
3175 * by a #GInputVector with a %NULL buffer pointer.
3177 * As a special case, if @num_vectors is 0 (in which case, @vectors
3178 * may of course be %NULL), then a single byte is received and
3179 * discarded. This is to facilitate the common practice of sending a
3180 * single '\0' byte for the purposes of transferring ancillary data.
3182 * @messages, if non-%NULL, will be set to point to a newly-allocated
3183 * array of #GSocketControlMessage instances or %NULL if no such
3184 * messages was received. These correspond to the control messages
3185 * received from the kernel, one #GSocketControlMessage per message
3186 * from the kernel. This array is %NULL-terminated and must be freed
3187 * by the caller using g_free() after calling g_object_unref() on each
3188 * element. If @messages is %NULL, any control messages received will
3191 * @num_messages, if non-%NULL, will be set to the number of control
3192 * messages received.
3194 * If both @messages and @num_messages are non-%NULL, then
3195 * @num_messages gives the number of #GSocketControlMessage instances
3196 * in @messages (ie: not including the %NULL terminator).
3198 * @flags is an in/out parameter. The commonly available arguments
3199 * for this are available in the #GSocketMsgFlags enum, but the
3200 * values there are the same as the system values, and the flags
3201 * are passed in as-is, so you can pass in system-specific flags too
3202 * (and g_socket_receive_message() may pass system-specific flags out).
3204 * As with g_socket_receive(), data may be discarded if @socket is
3205 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
3206 * provide enough buffer space to read a complete message. You can pass
3207 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
3208 * removing it from the receive queue, but there is no portable way to find
3209 * out the length of the message other than by reading it into a
3210 * sufficiently-large buffer.
3212 * If the socket is in blocking mode the call will block until there
3213 * is some data to receive, the connection is closed, or there is an
3214 * error. If there is no data available and the socket is in
3215 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
3216 * returned. To be notified when data is available, wait for the
3217 * %G_IO_IN condition.
3219 * On error -1 is returned and @error is set accordingly.
3221 * Returns: Number of bytes read, or 0 if the connection was closed by
3222 * the peer, or -1 on error
3227 g_socket_receive_message (GSocket *socket,
3228 GSocketAddress **address,
3229 GInputVector *vectors,
3231 GSocketControlMessage ***messages,
3234 GCancellable *cancellable,
3237 GInputVector one_vector;
3240 if (!check_socket (socket, error))
3243 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3246 if (num_vectors == -1)
3248 for (num_vectors = 0;
3249 vectors[num_vectors].buffer != NULL;
3254 if (num_vectors == 0)
3256 one_vector.buffer = &one_byte;
3257 one_vector.size = 1;
3259 vectors = &one_vector;
3266 struct sockaddr_storage one_sockaddr;
3271 msg.msg_name = &one_sockaddr;
3272 msg.msg_namelen = sizeof (struct sockaddr_storage);
3276 msg.msg_name = NULL;
3277 msg.msg_namelen = 0;
3281 /* this entire expression will be evaluated at compile time */
3282 if (sizeof *msg.msg_iov == sizeof *vectors &&
3283 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3284 G_STRUCT_OFFSET (struct iovec, iov_base) ==
3285 G_STRUCT_OFFSET (GInputVector, buffer) &&
3286 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3287 G_STRUCT_OFFSET (struct iovec, iov_len) ==
3288 G_STRUCT_OFFSET (GInputVector, size))
3289 /* ABI is compatible */
3291 msg.msg_iov = (struct iovec *) vectors;
3292 msg.msg_iovlen = num_vectors;
3295 /* ABI is incompatible */
3299 msg.msg_iov = g_newa (struct iovec, num_vectors);
3300 for (i = 0; i < num_vectors; i++)
3302 msg.msg_iov[i].iov_base = vectors[i].buffer;
3303 msg.msg_iov[i].iov_len = vectors[i].size;
3305 msg.msg_iovlen = num_vectors;
3309 msg.msg_control = g_alloca (2048);
3310 msg.msg_controllen = 2048;
3314 msg.msg_flags = *flags;
3318 /* We always set the close-on-exec flag so we don't leak file
3319 * descriptors into child processes. Note that gunixfdmessage.c
3320 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
3322 #ifdef MSG_CMSG_CLOEXEC
3323 msg.msg_flags |= MSG_CMSG_CLOEXEC;
3329 if (socket->priv->blocking &&
3330 !g_socket_condition_wait (socket,
3331 G_IO_IN, cancellable, error))
3334 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
3335 #ifdef MSG_CMSG_CLOEXEC
3336 if (result < 0 && get_socket_errno () == EINVAL)
3338 /* We must be running on an old kernel. Call without the flag. */
3339 msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
3340 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
3346 int errsv = get_socket_errno ();
3351 if (socket->priv->blocking &&
3352 (errsv == EWOULDBLOCK ||
3356 g_set_error (error, G_IO_ERROR,
3357 socket_io_error_from_errno (errsv),
3358 _("Error receiving message: %s"), socket_strerror (errsv));
3365 /* decode address */
3366 if (address != NULL)
3368 if (msg.msg_namelen > 0)
3369 *address = g_socket_address_new_from_native (msg.msg_name,
3375 /* decode control messages */
3377 GPtrArray *my_messages = NULL;
3378 struct cmsghdr *cmsg;
3380 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
3382 GSocketControlMessage *message;
3384 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
3386 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
3388 if (message == NULL)
3389 /* We've already spewed about the problem in the
3390 deserialization code, so just continue */
3393 if (messages == NULL)
3395 /* we have to do it this way if the user ignores the
3396 * messages so that we will close any received fds.
3398 g_object_unref (message);
3402 if (my_messages == NULL)
3403 my_messages = g_ptr_array_new ();
3404 g_ptr_array_add (my_messages, message);
3409 *num_messages = my_messages != NULL ? my_messages->len : 0;
3413 if (my_messages == NULL)
3419 g_ptr_array_add (my_messages, NULL);
3420 *messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
3425 g_assert (my_messages == NULL);
3429 /* capture the flags */
3431 *flags = msg.msg_flags;
3437 struct sockaddr_storage addr;
3439 DWORD bytes_received;
3446 bufs = g_newa (WSABUF, num_vectors);
3447 for (i = 0; i < num_vectors; i++)
3449 bufs[i].buf = (char *)vectors[i].buffer;
3450 bufs[i].len = (gulong)vectors[i].size;
3462 if (socket->priv->blocking &&
3463 !g_socket_condition_wait (socket,
3464 G_IO_IN, cancellable, error))
3467 addrlen = sizeof addr;
3469 result = WSARecvFrom (socket->priv->fd,
3471 &bytes_received, &win_flags,
3472 (struct sockaddr *)&addr, &addrlen,
3475 result = WSARecv (socket->priv->fd,
3477 &bytes_received, &win_flags,
3481 int errsv = get_socket_errno ();
3483 if (errsv == WSAEINTR)
3486 win32_unset_event_mask (socket, FD_READ);
3488 if (socket->priv->blocking &&
3489 errsv == WSAEWOULDBLOCK)
3492 g_set_error (error, G_IO_ERROR,
3493 socket_io_error_from_errno (errsv),
3494 _("Error receiving message: %s"), socket_strerror (errsv));
3498 win32_unset_event_mask (socket, FD_READ);
3502 /* decode address */
3503 if (address != NULL)
3506 *address = g_socket_address_new_from_native (&addr, addrlen);
3511 /* capture the flags */
3515 if (messages != NULL)
3517 if (num_messages != NULL)
3520 return bytes_received;
3526 * g_socket_get_credentials:
3527 * @socket: a #GSocket.
3528 * @error: #GError for error reporting, or %NULL to ignore.
3530 * Returns the credentials of the foreign process connected to this
3531 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
3534 * If this operation isn't supported on the OS, the method fails with
3535 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
3536 * by reading the %SO_PEERCRED option on the underlying socket.
3538 * Other ways to obtain credentials from a foreign peer includes the
3539 * #GUnixCredentialsMessage type and
3540 * g_unix_connection_send_credentials() /
3541 * g_unix_connection_receive_credentials() functions.
3543 * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
3544 * that must be freed with g_object_unref().
3549 g_socket_get_credentials (GSocket *socket,
3554 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
3555 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3559 #if defined(__linux__) || defined(__OpenBSD__)
3562 #if defined(__linux__)
3563 struct ucred native_creds;
3564 optlen = sizeof (struct ucred);
3565 #elif defined(__OpenBSD__)
3566 struct sockpeercred native_creds;
3567 optlen = sizeof (struct sockpeercred);
3569 if (getsockopt (socket->priv->fd,
3572 (void *)&native_creds,
3575 int errsv = get_socket_errno ();
3578 socket_io_error_from_errno (errsv),
3579 _("Unable to get pending error: %s"),
3580 socket_strerror (errsv));
3584 ret = g_credentials_new ();
3585 g_credentials_set_native (ret,
3586 #if defined(__linux__)
3587 G_CREDENTIALS_TYPE_LINUX_UCRED,
3588 #elif defined(__OpenBSD__)
3589 G_CREDENTIALS_TYPE_OPENBSD_SOCKPEERCRED,
3595 g_set_error_literal (error,
3597 G_IO_ERROR_NOT_SUPPORTED,
3598 _("g_socket_get_credentials not implemented for this OS"));