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 ();
373 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
374 sizeof address.ss_family <= addrlen);
375 switch (address.ss_family)
377 case G_SOCKET_FAMILY_IPV4:
378 case G_SOCKET_FAMILY_IPV6:
379 socket->priv->family = address.ss_family;
380 switch (socket->priv->type)
382 case G_SOCKET_TYPE_STREAM:
383 socket->priv->protocol = G_SOCKET_PROTOCOL_TCP;
386 case G_SOCKET_TYPE_DATAGRAM:
387 socket->priv->protocol = G_SOCKET_PROTOCOL_UDP;
390 case G_SOCKET_TYPE_SEQPACKET:
391 socket->priv->protocol = G_SOCKET_PROTOCOL_SCTP;
399 case G_SOCKET_FAMILY_UNIX:
400 socket->priv->family = G_SOCKET_FAMILY_UNIX;
401 socket->priv->protocol = G_SOCKET_PROTOCOL_DEFAULT;
405 socket->priv->family = G_SOCKET_FAMILY_INVALID;
409 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
411 addrlen = sizeof address;
412 if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
413 socket->priv->connected = TRUE;
416 optlen = sizeof bool_val;
417 if (getsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
418 (void *)&bool_val, &optlen) == 0)
421 /* Experimentation indicates that the SO_KEEPALIVE value is
422 * actually a char on Windows, even if documentation claims it
423 * to be a BOOL which is a typedef for int. So this g_assert()
424 * fails. See bug #611756.
426 g_assert (optlen == sizeof bool_val);
428 socket->priv->keepalive = !!bool_val;
432 /* Can't read, maybe not supported, assume FALSE */
433 socket->priv->keepalive = FALSE;
439 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
440 socket_io_error_from_errno (errsv),
441 _("creating GSocket from fd: %s"),
442 socket_strerror (errsv));
446 g_socket_create_socket (GSocketFamily family,
456 case G_SOCKET_TYPE_STREAM:
457 native_type = SOCK_STREAM;
460 case G_SOCKET_TYPE_DATAGRAM:
461 native_type = SOCK_DGRAM;
464 case G_SOCKET_TYPE_SEQPACKET:
465 native_type = SOCK_SEQPACKET;
469 g_assert_not_reached ();
474 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
475 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
480 fd = socket (family, native_type | SOCK_CLOEXEC, protocol);
481 /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
482 if (fd < 0 && errno == EINVAL)
484 fd = socket (family, native_type, protocol);
488 int errsv = get_socket_errno ();
490 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
491 _("Unable to create socket: %s"), socket_strerror (errsv));
498 /* We always want to set close-on-exec to protect users. If you
499 need to so some weird inheritance to exec you can re-enable this
500 using lower level hacks with g_socket_get_fd(). */
501 flags = fcntl (fd, F_GETFD, 0);
503 (flags & FD_CLOEXEC) == 0)
506 fcntl (fd, F_SETFD, flags);
515 g_socket_constructed (GObject *object)
517 GSocket *socket = G_SOCKET (object);
519 if (socket->priv->fd >= 0)
520 /* create socket->priv info from the fd */
521 g_socket_details_from_fd (socket);
524 /* create the fd from socket->priv info */
525 socket->priv->fd = g_socket_create_socket (socket->priv->family,
527 socket->priv->protocol,
528 &socket->priv->construct_error);
530 /* Always use native nonblocking sockets, as
531 windows sets sockets to nonblocking automatically
532 in certain operations. This way we make things work
533 the same on all platforms */
534 if (socket->priv->fd != -1)
535 set_fd_nonblocking (socket->priv->fd);
539 g_socket_get_property (GObject *object,
544 GSocket *socket = G_SOCKET (object);
545 GSocketAddress *address;
550 g_value_set_enum (value, socket->priv->family);
554 g_value_set_enum (value, socket->priv->type);
558 g_value_set_enum (value, socket->priv->protocol);
562 g_value_set_int (value, socket->priv->fd);
566 g_value_set_boolean (value, socket->priv->blocking);
569 case PROP_LISTEN_BACKLOG:
570 g_value_set_int (value, socket->priv->listen_backlog);
574 g_value_set_boolean (value, socket->priv->keepalive);
577 case PROP_LOCAL_ADDRESS:
578 address = g_socket_get_local_address (socket, NULL);
579 g_value_take_object (value, address);
582 case PROP_REMOTE_ADDRESS:
583 address = g_socket_get_remote_address (socket, NULL);
584 g_value_take_object (value, address);
588 g_value_set_uint (value, socket->priv->timeout);
592 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
597 g_socket_set_property (GObject *object,
602 GSocket *socket = G_SOCKET (object);
607 socket->priv->family = g_value_get_enum (value);
611 socket->priv->type = g_value_get_enum (value);
615 socket->priv->protocol = g_value_get_enum (value);
619 socket->priv->fd = g_value_get_int (value);
623 g_socket_set_blocking (socket, g_value_get_boolean (value));
626 case PROP_LISTEN_BACKLOG:
627 g_socket_set_listen_backlog (socket, g_value_get_int (value));
631 g_socket_set_keepalive (socket, g_value_get_boolean (value));
635 g_socket_set_timeout (socket, g_value_get_uint (value));
639 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
644 g_socket_finalize (GObject *object)
646 GSocket *socket = G_SOCKET (object);
648 g_clear_error (&socket->priv->construct_error);
650 if (socket->priv->fd != -1 &&
651 !socket->priv->closed)
652 g_socket_close (socket, NULL);
654 if (socket->priv->remote_address)
655 g_object_unref (socket->priv->remote_address);
658 if (socket->priv->event != WSA_INVALID_EVENT)
660 WSACloseEvent (socket->priv->event);
661 socket->priv->event = WSA_INVALID_EVENT;
664 g_assert (socket->priv->requested_conditions == NULL);
667 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
668 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
672 g_socket_class_init (GSocketClass *klass)
674 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
677 /* Make sure winsock has been initialized */
678 type = g_inet_address_get_type ();
679 (type); /* To avoid -Wunused-but-set-variable */
682 /* There is no portable, thread-safe way to avoid having the process
683 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
684 * forced to simply ignore the signal process-wide.
686 signal (SIGPIPE, SIG_IGN);
689 g_type_class_add_private (klass, sizeof (GSocketPrivate));
691 gobject_class->finalize = g_socket_finalize;
692 gobject_class->constructed = g_socket_constructed;
693 gobject_class->set_property = g_socket_set_property;
694 gobject_class->get_property = g_socket_get_property;
696 g_object_class_install_property (gobject_class, PROP_FAMILY,
697 g_param_spec_enum ("family",
699 P_("The sockets address family"),
700 G_TYPE_SOCKET_FAMILY,
701 G_SOCKET_FAMILY_INVALID,
702 G_PARAM_CONSTRUCT_ONLY |
704 G_PARAM_STATIC_STRINGS));
706 g_object_class_install_property (gobject_class, PROP_TYPE,
707 g_param_spec_enum ("type",
709 P_("The sockets type"),
711 G_SOCKET_TYPE_STREAM,
712 G_PARAM_CONSTRUCT_ONLY |
714 G_PARAM_STATIC_STRINGS));
716 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
717 g_param_spec_enum ("protocol",
718 P_("Socket protocol"),
719 P_("The id of the protocol to use, or -1 for unknown"),
720 G_TYPE_SOCKET_PROTOCOL,
721 G_SOCKET_PROTOCOL_UNKNOWN,
722 G_PARAM_CONSTRUCT_ONLY |
724 G_PARAM_STATIC_STRINGS));
726 g_object_class_install_property (gobject_class, PROP_FD,
727 g_param_spec_int ("fd",
728 P_("File descriptor"),
729 P_("The sockets file descriptor"),
733 G_PARAM_CONSTRUCT_ONLY |
735 G_PARAM_STATIC_STRINGS));
737 g_object_class_install_property (gobject_class, PROP_BLOCKING,
738 g_param_spec_boolean ("blocking",
740 P_("Whether or not I/O on this socket is blocking"),
743 G_PARAM_STATIC_STRINGS));
745 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
746 g_param_spec_int ("listen-backlog",
747 P_("Listen backlog"),
748 P_("Outstanding connections in the listen queue"),
753 G_PARAM_STATIC_STRINGS));
755 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
756 g_param_spec_boolean ("keepalive",
757 P_("Keep connection alive"),
758 P_("Keep connection alive by sending periodic pings"),
761 G_PARAM_STATIC_STRINGS));
763 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
764 g_param_spec_object ("local-address",
766 P_("The local address the socket is bound to"),
767 G_TYPE_SOCKET_ADDRESS,
769 G_PARAM_STATIC_STRINGS));
771 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
772 g_param_spec_object ("remote-address",
773 P_("Remote address"),
774 P_("The remote address the socket is connected to"),
775 G_TYPE_SOCKET_ADDRESS,
777 G_PARAM_STATIC_STRINGS));
782 * The timeout in seconds on socket I/O
786 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
787 g_param_spec_uint ("timeout",
789 P_("The timeout in seconds on socket I/O"),
794 G_PARAM_STATIC_STRINGS));
798 g_socket_initable_iface_init (GInitableIface *iface)
800 iface->init = g_socket_initable_init;
804 g_socket_init (GSocket *socket)
806 socket->priv = G_TYPE_INSTANCE_GET_PRIVATE (socket, G_TYPE_SOCKET, GSocketPrivate);
808 socket->priv->fd = -1;
809 socket->priv->blocking = TRUE;
810 socket->priv->listen_backlog = 10;
811 socket->priv->construct_error = NULL;
813 socket->priv->event = WSA_INVALID_EVENT;
818 g_socket_initable_init (GInitable *initable,
819 GCancellable *cancellable,
824 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
826 socket = G_SOCKET (initable);
828 if (cancellable != NULL)
830 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
831 _("Cancellable initialization not supported"));
835 socket->priv->inited = TRUE;
837 if (socket->priv->construct_error)
840 *error = g_error_copy (socket->priv->construct_error);
850 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
851 * @type: the socket type to use.
852 * @protocol: the id of the protocol to use, or 0 for default.
853 * @error: #GError for error reporting, or %NULL to ignore.
855 * Creates a new #GSocket with the defined family, type and protocol.
856 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
857 * for the family and type is used.
859 * The @protocol is a family and type specific int that specifies what
860 * kind of protocol to use. #GSocketProtocol lists several common ones.
861 * Many families only support one protocol, and use 0 for this, others
862 * support several and using 0 means to use the default protocol for
863 * the family and type.
865 * The protocol id is passed directly to the operating
866 * system, so you can use protocols not listed in #GSocketProtocol if you
867 * know the protocol number used for it.
869 * Returns: a #GSocket or %NULL on error.
870 * Free the returned object with g_object_unref().
875 g_socket_new (GSocketFamily family,
877 GSocketProtocol protocol,
880 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
884 "protocol", protocol,
889 * g_socket_new_from_fd:
890 * @fd: a native socket file descriptor.
891 * @error: #GError for error reporting, or %NULL to ignore.
893 * Creates a new #GSocket from a native file descriptor
894 * or winsock SOCKET handle.
896 * This reads all the settings from the file descriptor so that
897 * all properties should work. Note that the file descriptor
898 * will be set to non-blocking mode, independent on the blocking
899 * mode of the #GSocket.
901 * Returns: a #GSocket or %NULL on error.
902 * Free the returned object with g_object_unref().
907 g_socket_new_from_fd (gint fd,
910 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
917 * g_socket_set_blocking:
918 * @socket: a #GSocket.
919 * @blocking: Whether to use blocking I/O or not.
921 * Sets the blocking mode of the socket. In blocking mode
922 * all operations block until they succeed or there is an error. In
923 * non-blocking mode all functions return results immediately or
924 * with a %G_IO_ERROR_WOULD_BLOCK error.
926 * All sockets are created in blocking mode. However, note that the
927 * platform level socket is always non-blocking, and blocking mode
928 * is a GSocket level feature.
933 g_socket_set_blocking (GSocket *socket,
936 g_return_if_fail (G_IS_SOCKET (socket));
938 blocking = !!blocking;
940 if (socket->priv->blocking == blocking)
943 socket->priv->blocking = blocking;
944 g_object_notify (G_OBJECT (socket), "blocking");
948 * g_socket_get_blocking:
949 * @socket: a #GSocket.
951 * Gets the blocking mode of the socket. For details on blocking I/O,
952 * see g_socket_set_blocking().
954 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
959 g_socket_get_blocking (GSocket *socket)
961 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
963 return socket->priv->blocking;
967 * g_socket_set_keepalive:
968 * @socket: a #GSocket.
969 * @keepalive: Value for the keepalive flag
971 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
972 * this flag is set on a socket, the system will attempt to verify that the
973 * remote socket endpoint is still present if a sufficiently long period of
974 * time passes with no data being exchanged. If the system is unable to
975 * verify the presence of the remote endpoint, it will automatically close
978 * This option is only functional on certain kinds of sockets. (Notably,
979 * %G_SOCKET_PROTOCOL_TCP sockets.)
981 * The exact time between pings is system- and protocol-dependent, but will
982 * normally be at least two hours. Most commonly, you would set this flag
983 * on a server socket if you want to allow clients to remain idle for long
984 * periods of time, but also want to ensure that connections are eventually
985 * garbage-collected if clients crash or become unreachable.
990 g_socket_set_keepalive (GSocket *socket,
995 g_return_if_fail (G_IS_SOCKET (socket));
997 keepalive = !!keepalive;
998 if (socket->priv->keepalive == keepalive)
1001 value = (gint) keepalive;
1002 if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_KEEPALIVE,
1003 (gpointer) &value, sizeof (value)) < 0)
1005 int errsv = get_socket_errno ();
1006 g_warning ("error setting keepalive: %s", socket_strerror (errsv));
1010 socket->priv->keepalive = keepalive;
1011 g_object_notify (G_OBJECT (socket), "keepalive");
1015 * g_socket_get_keepalive:
1016 * @socket: a #GSocket.
1018 * Gets the keepalive mode of the socket. For details on this,
1019 * see g_socket_set_keepalive().
1021 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1026 g_socket_get_keepalive (GSocket *socket)
1028 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1030 return socket->priv->keepalive;
1034 * g_socket_get_listen_backlog:
1035 * @socket: a #GSocket.
1037 * Gets the listen backlog setting of the socket. For details on this,
1038 * see g_socket_set_listen_backlog().
1040 * Returns: the maximum number of pending connections.
1045 g_socket_get_listen_backlog (GSocket *socket)
1047 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1049 return socket->priv->listen_backlog;
1053 * g_socket_set_listen_backlog:
1054 * @socket: a #GSocket.
1055 * @backlog: the maximum number of pending connections.
1057 * Sets the maximum number of outstanding connections allowed
1058 * when listening on this socket. If more clients than this are
1059 * connecting to the socket and the application is not handling them
1060 * on time then the new connections will be refused.
1062 * Note that this must be called before g_socket_listen() and has no
1063 * effect if called after that.
1068 g_socket_set_listen_backlog (GSocket *socket,
1071 g_return_if_fail (G_IS_SOCKET (socket));
1072 g_return_if_fail (!socket->priv->listening);
1074 if (backlog != socket->priv->listen_backlog)
1076 socket->priv->listen_backlog = backlog;
1077 g_object_notify (G_OBJECT (socket), "listen-backlog");
1082 * g_socket_get_timeout:
1083 * @socket: a #GSocket.
1085 * Gets the timeout setting of the socket. For details on this, see
1086 * g_socket_set_timeout().
1088 * Returns: the timeout in seconds
1093 g_socket_get_timeout (GSocket *socket)
1095 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1097 return socket->priv->timeout;
1101 * g_socket_set_timeout:
1102 * @socket: a #GSocket.
1103 * @timeout: the timeout for @socket, in seconds, or 0 for none
1105 * Sets the time in seconds after which I/O operations on @socket will
1106 * time out if they have not yet completed.
1108 * On a blocking socket, this means that any blocking #GSocket
1109 * operation will time out after @timeout seconds of inactivity,
1110 * returning %G_IO_ERROR_TIMED_OUT.
1112 * On a non-blocking socket, calls to g_socket_condition_wait() will
1113 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1114 * created with g_socket_create_source() will trigger after
1115 * @timeout seconds of inactivity, with the requested condition
1116 * set, at which point calling g_socket_receive(), g_socket_send(),
1117 * g_socket_check_connect_result(), etc, will fail with
1118 * %G_IO_ERROR_TIMED_OUT.
1120 * If @timeout is 0 (the default), operations will never time out
1123 * Note that if an I/O operation is interrupted by a signal, this may
1124 * cause the timeout to be reset.
1129 g_socket_set_timeout (GSocket *socket,
1132 g_return_if_fail (G_IS_SOCKET (socket));
1134 if (timeout != socket->priv->timeout)
1136 socket->priv->timeout = timeout;
1137 g_object_notify (G_OBJECT (socket), "timeout");
1142 * g_socket_get_family:
1143 * @socket: a #GSocket.
1145 * Gets the socket family of the socket.
1147 * Returns: a #GSocketFamily
1152 g_socket_get_family (GSocket *socket)
1154 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1156 return socket->priv->family;
1160 * g_socket_get_socket_type:
1161 * @socket: a #GSocket.
1163 * Gets the socket type of the socket.
1165 * Returns: a #GSocketType
1170 g_socket_get_socket_type (GSocket *socket)
1172 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1174 return socket->priv->type;
1178 * g_socket_get_protocol:
1179 * @socket: a #GSocket.
1181 * Gets the socket protocol id the socket was created with.
1182 * In case the protocol is unknown, -1 is returned.
1184 * Returns: a protocol id, or -1 if unknown
1189 g_socket_get_protocol (GSocket *socket)
1191 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1193 return socket->priv->protocol;
1198 * @socket: a #GSocket.
1200 * Returns the underlying OS socket object. On unix this
1201 * is a socket file descriptor, and on windows this is
1202 * a Winsock2 SOCKET handle. This may be useful for
1203 * doing platform specific or otherwise unusual operations
1206 * Returns: the file descriptor of the socket.
1211 g_socket_get_fd (GSocket *socket)
1213 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1215 return socket->priv->fd;
1219 * g_socket_get_local_address:
1220 * @socket: a #GSocket.
1221 * @error: #GError for error reporting, or %NULL to ignore.
1223 * Try to get the local address of a bound socket. This is only
1224 * useful if the socket has been bound to a local address,
1225 * either explicitly or implicitly when connecting.
1227 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1228 * Free the returned object with g_object_unref().
1233 g_socket_get_local_address (GSocket *socket,
1236 struct sockaddr_storage buffer;
1237 guint32 len = sizeof (buffer);
1239 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1241 if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1243 int errsv = get_socket_errno ();
1244 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1245 _("could not get local address: %s"), socket_strerror (errsv));
1249 return g_socket_address_new_from_native (&buffer, len);
1253 * g_socket_get_remote_address:
1254 * @socket: a #GSocket.
1255 * @error: #GError for error reporting, or %NULL to ignore.
1257 * Try to get the remove address of a connected socket. This is only
1258 * useful for connection oriented sockets that have been connected.
1260 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1261 * Free the returned object with g_object_unref().
1266 g_socket_get_remote_address (GSocket *socket,
1269 struct sockaddr_storage buffer;
1270 guint32 len = sizeof (buffer);
1272 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1274 if (socket->priv->connect_pending)
1276 if (!g_socket_check_connect_result (socket, error))
1279 socket->priv->connect_pending = FALSE;
1282 if (!socket->priv->remote_address)
1284 if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1286 int errsv = get_socket_errno ();
1287 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1288 _("could not get remote address: %s"), socket_strerror (errsv));
1292 socket->priv->remote_address = g_socket_address_new_from_native (&buffer, len);
1295 return g_object_ref (socket->priv->remote_address);
1299 * g_socket_is_connected:
1300 * @socket: a #GSocket.
1302 * Check whether the socket is connected. This is only useful for
1303 * connection-oriented sockets.
1305 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1310 g_socket_is_connected (GSocket *socket)
1312 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1314 return socket->priv->connected;
1319 * @socket: a #GSocket.
1320 * @error: #GError for error reporting, or %NULL to ignore.
1322 * Marks the socket as a server socket, i.e. a socket that is used
1323 * to accept incoming requests using g_socket_accept().
1325 * Before calling this the socket must be bound to a local address using
1328 * To set the maximum amount of outstanding clients, use
1329 * g_socket_set_listen_backlog().
1331 * Returns: %TRUE on success, %FALSE on error.
1336 g_socket_listen (GSocket *socket,
1339 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1341 if (!check_socket (socket, error))
1344 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1346 int errsv = get_socket_errno ();
1348 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1349 _("could not listen: %s"), socket_strerror (errsv));
1353 socket->priv->listening = TRUE;
1360 * @socket: a #GSocket.
1361 * @address: a #GSocketAddress specifying the local address.
1362 * @allow_reuse: whether to allow reusing this address
1363 * @error: #GError for error reporting, or %NULL to ignore.
1365 * When a socket is created it is attached to an address family, but it
1366 * doesn't have an address in this family. g_socket_bind() assigns the
1367 * address (sometimes called name) of the socket.
1369 * It is generally required to bind to a local address before you can
1370 * receive connections. (See g_socket_listen() and g_socket_accept() ).
1371 * In certain situations, you may also want to bind a socket that will be
1372 * used to initiate connections, though this is not normally required.
1374 * @allow_reuse should be %TRUE for server sockets (sockets that you will
1375 * eventually call g_socket_accept() on), and %FALSE for client sockets.
1376 * (Specifically, if it is %TRUE, then g_socket_bind() will set the
1377 * %SO_REUSEADDR flag on the socket, allowing it to bind @address even if
1378 * that address was previously used by another socket that has not yet been
1379 * fully cleaned-up by the kernel. Failing to set this flag on a server
1380 * socket may cause the bind call to return %G_IO_ERROR_ADDRESS_IN_USE if
1381 * the server program is stopped and then immediately restarted.)
1383 * Returns: %TRUE on success, %FALSE on error.
1388 g_socket_bind (GSocket *socket,
1389 GSocketAddress *address,
1390 gboolean reuse_address,
1393 struct sockaddr_storage addr;
1395 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1397 if (!check_socket (socket, error))
1400 /* SO_REUSEADDR on windows means something else and is not what we want.
1401 It always allows the unix variant of SO_REUSEADDR anyway */
1406 value = (int) !!reuse_address;
1407 /* Ignore errors here, the only likely error is "not supported", and
1408 this is a "best effort" thing mainly */
1409 setsockopt (socket->priv->fd, SOL_SOCKET, SO_REUSEADDR,
1410 (gpointer) &value, sizeof (value));
1414 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1417 if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1418 g_socket_address_get_native_size (address)) < 0)
1420 int errsv = get_socket_errno ();
1422 G_IO_ERROR, socket_io_error_from_errno (errsv),
1423 _("Error binding to address: %s"), socket_strerror (errsv));
1431 * g_socket_speaks_ipv4:
1432 * @socket: a #GSocket
1434 * Checks if a socket is capable of speaking IPv4.
1436 * IPv4 sockets are capable of speaking IPv4. On some operating systems
1437 * and under some combinations of circumstances IPv6 sockets are also
1438 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
1441 * No other types of sockets are currently considered as being capable
1444 * Returns: %TRUE if this socket can be used with IPv4.
1449 g_socket_speaks_ipv4 (GSocket *socket)
1451 switch (socket->priv->family)
1453 case G_SOCKET_FAMILY_IPV4:
1456 case G_SOCKET_FAMILY_IPV6:
1457 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
1459 guint sizeof_int = sizeof (int);
1462 if (getsockopt (socket->priv->fd,
1463 IPPROTO_IPV6, IPV6_V6ONLY,
1464 &v6_only, &sizeof_int) != 0)
1480 * @socket: a #GSocket.
1481 * @cancellable: (allow-none): a %GCancellable or %NULL
1482 * @error: #GError for error reporting, or %NULL to ignore.
1484 * Accept incoming connections on a connection-based socket. This removes
1485 * the first outstanding connection request from the listening socket and
1486 * creates a #GSocket object for it.
1488 * The @socket must be bound to a local address with g_socket_bind() and
1489 * must be listening for incoming connections (g_socket_listen()).
1491 * If there are no outstanding connections then the operation will block
1492 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
1493 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
1495 * Returns: (transfer full): a new #GSocket, or %NULL on error.
1496 * Free the returned object with g_object_unref().
1501 g_socket_accept (GSocket *socket,
1502 GCancellable *cancellable,
1505 GSocket *new_socket;
1508 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1510 if (!check_socket (socket, error))
1515 if (socket->priv->blocking &&
1516 !g_socket_condition_wait (socket,
1517 G_IO_IN, cancellable, error))
1520 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
1522 int errsv = get_socket_errno ();
1524 win32_unset_event_mask (socket, FD_ACCEPT);
1529 if (socket->priv->blocking)
1531 #ifdef WSAEWOULDBLOCK
1532 if (errsv == WSAEWOULDBLOCK)
1535 if (errsv == EWOULDBLOCK ||
1541 g_set_error (error, G_IO_ERROR,
1542 socket_io_error_from_errno (errsv),
1543 _("Error accepting connection: %s"), socket_strerror (errsv));
1549 win32_unset_event_mask (socket, FD_ACCEPT);
1553 /* The socket inherits the accepting sockets event mask and even object,
1554 we need to remove that */
1555 WSAEventSelect (ret, NULL, 0);
1561 /* We always want to set close-on-exec to protect users. If you
1562 need to so some weird inheritance to exec you can re-enable this
1563 using lower level hacks with g_socket_get_fd(). */
1564 flags = fcntl (ret, F_GETFD, 0);
1566 (flags & FD_CLOEXEC) == 0)
1568 flags |= FD_CLOEXEC;
1569 fcntl (ret, F_SETFD, flags);
1574 new_socket = g_socket_new_from_fd (ret, error);
1575 if (new_socket == NULL)
1584 new_socket->priv->protocol = socket->priv->protocol;
1591 * @socket: a #GSocket.
1592 * @address: a #GSocketAddress specifying the remote address.
1593 * @cancellable: (allow-none): a %GCancellable or %NULL
1594 * @error: #GError for error reporting, or %NULL to ignore.
1596 * Connect the socket to the specified remote address.
1598 * For connection oriented socket this generally means we attempt to make
1599 * a connection to the @address. For a connection-less socket it sets
1600 * the default address for g_socket_send() and discards all incoming datagrams
1601 * from other sources.
1603 * Generally connection oriented sockets can only connect once, but
1604 * connection-less sockets can connect multiple times to change the
1607 * If the connect call needs to do network I/O it will block, unless
1608 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
1609 * and the user can be notified of the connection finishing by waiting
1610 * for the G_IO_OUT condition. The result of the connection must then be
1611 * checked with g_socket_check_connect_result().
1613 * Returns: %TRUE if connected, %FALSE on error.
1618 g_socket_connect (GSocket *socket,
1619 GSocketAddress *address,
1620 GCancellable *cancellable,
1623 struct sockaddr_storage buffer;
1625 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1627 if (!check_socket (socket, error))
1630 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
1633 if (socket->priv->remote_address)
1634 g_object_unref (socket->priv->remote_address);
1635 socket->priv->remote_address = g_object_ref (address);
1639 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
1640 g_socket_address_get_native_size (address)) < 0)
1642 int errsv = get_socket_errno ();
1648 if (errsv == EINPROGRESS)
1650 if (errsv == WSAEWOULDBLOCK)
1653 if (socket->priv->blocking)
1655 if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
1657 if (g_socket_check_connect_result (socket, error))
1660 g_prefix_error (error, _("Error connecting: "));
1664 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
1665 _("Connection in progress"));
1666 socket->priv->connect_pending = TRUE;
1670 g_set_error (error, G_IO_ERROR,
1671 socket_io_error_from_errno (errsv),
1672 _("Error connecting: %s"), socket_strerror (errsv));
1679 win32_unset_event_mask (socket, FD_CONNECT);
1681 socket->priv->connected = TRUE;
1687 * g_socket_check_connect_result:
1688 * @socket: a #GSocket
1689 * @error: #GError for error reporting, or %NULL to ignore.
1691 * Checks and resets the pending connect error for the socket.
1692 * This is used to check for errors when g_socket_connect() is
1693 * used in non-blocking mode.
1695 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
1700 g_socket_check_connect_result (GSocket *socket,
1706 if (!check_socket (socket, error))
1709 optlen = sizeof (value);
1710 if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
1712 int errsv = get_socket_errno ();
1714 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1715 _("Unable to get pending error: %s"), socket_strerror (errsv));
1721 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
1722 socket_strerror (value));
1723 if (socket->priv->remote_address)
1725 g_object_unref (socket->priv->remote_address);
1726 socket->priv->remote_address = NULL;
1731 socket->priv->connected = TRUE;
1737 * @socket: a #GSocket
1738 * @buffer: a buffer to read data into (which should be at least @size
1740 * @size: the number of bytes you want to read from the socket
1741 * @cancellable: (allow-none): a %GCancellable or %NULL
1742 * @error: #GError for error reporting, or %NULL to ignore.
1744 * Receive data (up to @size bytes) from a socket. This is mainly used by
1745 * connection-oriented sockets; it is identical to g_socket_receive_from()
1746 * with @address set to %NULL.
1748 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
1749 * g_socket_receive() will always read either 0 or 1 complete messages from
1750 * the socket. If the received message is too large to fit in @buffer, then
1751 * the data beyond @size bytes will be discarded, without any explicit
1752 * indication that this has occurred.
1754 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
1755 * number of bytes, up to @size. If more than @size bytes have been
1756 * received, the additional data will be returned in future calls to
1757 * g_socket_receive().
1759 * If the socket is in blocking mode the call will block until there
1760 * is some data to receive, the connection is closed, or there is an
1761 * error. If there is no data available and the socket is in
1762 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
1763 * returned. To be notified when data is available, wait for the
1764 * %G_IO_IN condition.
1766 * On error -1 is returned and @error is set accordingly.
1768 * Returns: Number of bytes read, or 0 if the connection was closed by
1769 * the peer, or -1 on error
1774 g_socket_receive (GSocket *socket,
1777 GCancellable *cancellable,
1780 return g_socket_receive_with_blocking (socket, buffer, size,
1781 socket->priv->blocking,
1782 cancellable, error);
1786 * g_socket_receive_with_blocking:
1787 * @socket: a #GSocket
1788 * @buffer: a buffer to read data into (which should be at least @size
1790 * @size: the number of bytes you want to read from the socket
1791 * @blocking: whether to do blocking or non-blocking I/O
1792 * @cancellable: (allow-none): a %GCancellable or %NULL
1793 * @error: #GError for error reporting, or %NULL to ignore.
1795 * This behaves exactly the same as g_socket_receive(), except that
1796 * the choice of blocking or non-blocking behavior is determined by
1797 * the @blocking argument rather than by @socket's properties.
1799 * Returns: Number of bytes read, or 0 if the connection was closed by
1800 * the peer, or -1 on error
1805 g_socket_receive_with_blocking (GSocket *socket,
1809 GCancellable *cancellable,
1814 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1816 if (!check_socket (socket, error))
1819 if (g_cancellable_set_error_if_cancelled (cancellable, error))
1825 !g_socket_condition_wait (socket,
1826 G_IO_IN, cancellable, error))
1829 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
1831 int errsv = get_socket_errno ();
1838 #ifdef WSAEWOULDBLOCK
1839 if (errsv == WSAEWOULDBLOCK)
1842 if (errsv == EWOULDBLOCK ||
1848 win32_unset_event_mask (socket, FD_READ);
1850 g_set_error (error, G_IO_ERROR,
1851 socket_io_error_from_errno (errsv),
1852 _("Error receiving data: %s"), socket_strerror (errsv));
1856 win32_unset_event_mask (socket, FD_READ);
1865 * g_socket_receive_from:
1866 * @socket: a #GSocket
1867 * @address: a pointer to a #GSocketAddress pointer, or %NULL
1868 * @buffer: a buffer to read data into (which should be at least @size
1870 * @size: the number of bytes you want to read from the socket
1871 * @cancellable: (allow-none): a %GCancellable or %NULL
1872 * @error: #GError for error reporting, or %NULL to ignore.
1874 * Receive data (up to @size bytes) from a socket.
1876 * If @address is non-%NULL then @address will be set equal to the
1877 * source address of the received packet.
1878 * @address is owned by the caller.
1880 * See g_socket_receive() for additional information.
1882 * Returns: Number of bytes read, or 0 if the connection was closed by
1883 * the peer, or -1 on error
1888 g_socket_receive_from (GSocket *socket,
1889 GSocketAddress **address,
1892 GCancellable *cancellable,
1900 return g_socket_receive_message (socket,
1908 /* Although we ignore SIGPIPE, gdb will still stop if the app receives
1909 * one, which can be confusing and annoying. So if possible, we want
1910 * to suppress the signal entirely.
1913 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
1915 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
1920 * @socket: a #GSocket
1921 * @buffer: (array length=size): the buffer containing the data to send.
1922 * @size: the number of bytes to send
1923 * @cancellable: (allow-none): a %GCancellable or %NULL
1924 * @error: #GError for error reporting, or %NULL to ignore.
1926 * Tries to send @size bytes from @buffer on the socket. This is
1927 * mainly used by connection-oriented sockets; it is identical to
1928 * g_socket_send_to() with @address set to %NULL.
1930 * If the socket is in blocking mode the call will block until there is
1931 * space for the data in the socket queue. If there is no space available
1932 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1933 * will be returned. To be notified when space is available, wait for the
1934 * %G_IO_OUT condition. Note though that you may still receive
1935 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
1936 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
1937 * very common due to the way the underlying APIs work.)
1939 * On error -1 is returned and @error is set accordingly.
1941 * Returns: Number of bytes written (which may be less than @size), or -1
1947 g_socket_send (GSocket *socket,
1948 const gchar *buffer,
1950 GCancellable *cancellable,
1953 return g_socket_send_with_blocking (socket, buffer, size,
1954 socket->priv->blocking,
1955 cancellable, error);
1959 * g_socket_send_with_blocking:
1960 * @socket: a #GSocket
1961 * @buffer: (array length=size): the buffer containing the data to send.
1962 * @size: the number of bytes to send
1963 * @blocking: whether to do blocking or non-blocking I/O
1964 * @cancellable: (allow-none): a %GCancellable or %NULL
1965 * @error: #GError for error reporting, or %NULL to ignore.
1967 * This behaves exactly the same as g_socket_send(), except that
1968 * the choice of blocking or non-blocking behavior is determined by
1969 * the @blocking argument rather than by @socket's properties.
1971 * Returns: Number of bytes written (which may be less than @size), or -1
1977 g_socket_send_with_blocking (GSocket *socket,
1978 const gchar *buffer,
1981 GCancellable *cancellable,
1986 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1988 if (!check_socket (socket, error))
1991 if (g_cancellable_set_error_if_cancelled (cancellable, error))
1997 !g_socket_condition_wait (socket,
1998 G_IO_OUT, cancellable, error))
2001 if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
2003 int errsv = get_socket_errno ();
2008 #ifdef WSAEWOULDBLOCK
2009 if (errsv == WSAEWOULDBLOCK)
2010 win32_unset_event_mask (socket, FD_WRITE);
2015 #ifdef WSAEWOULDBLOCK
2016 if (errsv == WSAEWOULDBLOCK)
2019 if (errsv == EWOULDBLOCK ||
2025 g_set_error (error, G_IO_ERROR,
2026 socket_io_error_from_errno (errsv),
2027 _("Error sending data: %s"), socket_strerror (errsv));
2038 * @socket: a #GSocket
2039 * @address: a #GSocketAddress, or %NULL
2040 * @buffer: (array length=size): the buffer containing the data to send.
2041 * @size: the number of bytes to send
2042 * @cancellable: (allow-none): a %GCancellable or %NULL
2043 * @error: #GError for error reporting, or %NULL to ignore.
2045 * Tries to send @size bytes from @buffer to @address. If @address is
2046 * %NULL then the message is sent to the default receiver (set by
2047 * g_socket_connect()).
2049 * See g_socket_send() for additional information.
2051 * Returns: Number of bytes written (which may be less than @size), or -1
2057 g_socket_send_to (GSocket *socket,
2058 GSocketAddress *address,
2059 const gchar *buffer,
2061 GCancellable *cancellable,
2069 return g_socket_send_message (socket,
2079 * g_socket_shutdown:
2080 * @socket: a #GSocket
2081 * @shutdown_read: whether to shut down the read side
2082 * @shutdown_write: whether to shut down the write side
2083 * @error: #GError for error reporting, or %NULL to ignore.
2085 * Shut down part of a full-duplex connection.
2087 * If @shutdown_read is %TRUE then the receiving side of the connection
2088 * is shut down, and further reading is disallowed.
2090 * If @shutdown_write is %TRUE then the sending side of the connection
2091 * is shut down, and further writing is disallowed.
2093 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
2095 * One example where this is used is graceful disconnect for TCP connections
2096 * where you close the sending side, then wait for the other side to close
2097 * the connection, thus ensuring that the other side saw all sent data.
2099 * Returns: %TRUE on success, %FALSE on error
2104 g_socket_shutdown (GSocket *socket,
2105 gboolean shutdown_read,
2106 gboolean shutdown_write,
2111 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2113 if (!check_socket (socket, error))
2117 if (!shutdown_read && !shutdown_write)
2121 if (shutdown_read && shutdown_write)
2123 else if (shutdown_read)
2128 if (shutdown_read && shutdown_write)
2130 else if (shutdown_read)
2136 if (shutdown (socket->priv->fd, how) != 0)
2138 int errsv = get_socket_errno ();
2139 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2140 _("Unable to shutdown socket: %s"), socket_strerror (errsv));
2144 if (shutdown_read && shutdown_write)
2145 socket->priv->connected = FALSE;
2152 * @socket: a #GSocket
2153 * @error: #GError for error reporting, or %NULL to ignore.
2155 * Closes the socket, shutting down any active connection.
2157 * Closing a socket does not wait for all outstanding I/O operations
2158 * to finish, so the caller should not rely on them to be guaranteed
2159 * to complete even if the close returns with no error.
2161 * Once the socket is closed, all other operations will return
2162 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
2165 * Sockets will be automatically closed when the last reference
2166 * is dropped, but you might want to call this function to make sure
2167 * resources are released as early as possible.
2169 * Beware that due to the way that TCP works, it is possible for
2170 * recently-sent data to be lost if either you close a socket while the
2171 * %G_IO_IN condition is set, or else if the remote connection tries to
2172 * send something to you after you close the socket but before it has
2173 * finished reading all of the data you sent. There is no easy generic
2174 * way to avoid this problem; the easiest fix is to design the network
2175 * protocol such that the client will never send data "out of turn".
2176 * Another solution is for the server to half-close the connection by
2177 * calling g_socket_shutdown() with only the @shutdown_write flag set,
2178 * and then wait for the client to notice this and close its side of the
2179 * connection, after which the server can safely call g_socket_close().
2180 * (This is what #GTcpConnection does if you call
2181 * g_tcp_connection_set_graceful_disconnect(). But of course, this
2182 * only works if the client will close its connection after the server
2185 * Returns: %TRUE on success, %FALSE on error
2190 g_socket_close (GSocket *socket,
2195 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2197 if (socket->priv->closed)
2198 return TRUE; /* Multiple close not an error */
2200 if (!check_socket (socket, error))
2206 res = closesocket (socket->priv->fd);
2208 res = close (socket->priv->fd);
2212 int errsv = get_socket_errno ();
2217 g_set_error (error, G_IO_ERROR,
2218 socket_io_error_from_errno (errsv),
2219 _("Error closing socket: %s"),
2220 socket_strerror (errsv));
2226 socket->priv->connected = FALSE;
2227 socket->priv->closed = TRUE;
2228 if (socket->priv->remote_address)
2230 g_object_unref (socket->priv->remote_address);
2231 socket->priv->remote_address = NULL;
2238 * g_socket_is_closed:
2239 * @socket: a #GSocket
2241 * Checks whether a socket is closed.
2243 * Returns: %TRUE if socket is closed, %FALSE otherwise
2248 g_socket_is_closed (GSocket *socket)
2250 return socket->priv->closed;
2254 /* Broken source, used on errors */
2256 broken_prepare (GSource *source,
2263 broken_check (GSource *source)
2269 broken_dispatch (GSource *source,
2270 GSourceFunc callback,
2276 static GSourceFuncs broken_funcs =
2285 network_events_for_condition (GIOCondition condition)
2289 if (condition & G_IO_IN)
2290 event_mask |= (FD_READ | FD_ACCEPT);
2291 if (condition & G_IO_OUT)
2292 event_mask |= (FD_WRITE | FD_CONNECT);
2293 event_mask |= FD_CLOSE;
2299 ensure_event (GSocket *socket)
2301 if (socket->priv->event == WSA_INVALID_EVENT)
2302 socket->priv->event = WSACreateEvent();
2306 update_select_events (GSocket *socket)
2313 ensure_event (socket);
2316 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
2319 event_mask |= network_events_for_condition (*ptr);
2322 if (event_mask != socket->priv->selected_events)
2324 /* If no events selected, disable event so we can unset
2327 if (event_mask == 0)
2330 event = socket->priv->event;
2332 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
2333 socket->priv->selected_events = event_mask;
2338 add_condition_watch (GSocket *socket,
2339 GIOCondition *condition)
2341 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
2343 socket->priv->requested_conditions =
2344 g_list_prepend (socket->priv->requested_conditions, condition);
2346 update_select_events (socket);
2350 remove_condition_watch (GSocket *socket,
2351 GIOCondition *condition)
2353 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
2355 socket->priv->requested_conditions =
2356 g_list_remove (socket->priv->requested_conditions, condition);
2358 update_select_events (socket);
2362 update_condition (GSocket *socket)
2364 WSANETWORKEVENTS events;
2365 GIOCondition condition;
2367 if (WSAEnumNetworkEvents (socket->priv->fd,
2368 socket->priv->event,
2371 socket->priv->current_events |= events.lNetworkEvents;
2372 if (events.lNetworkEvents & FD_WRITE &&
2373 events.iErrorCode[FD_WRITE_BIT] != 0)
2374 socket->priv->current_errors |= FD_WRITE;
2375 if (events.lNetworkEvents & FD_CONNECT &&
2376 events.iErrorCode[FD_CONNECT_BIT] != 0)
2377 socket->priv->current_errors |= FD_CONNECT;
2381 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
2382 condition |= G_IO_IN;
2384 if (socket->priv->current_events & FD_CLOSE ||
2385 socket->priv->closed)
2386 condition |= G_IO_HUP;
2388 /* Never report both G_IO_OUT and HUP, these are
2389 mutually exclusive (can't write to a closed socket) */
2390 if ((condition & G_IO_HUP) == 0 &&
2391 socket->priv->current_events & FD_WRITE)
2393 if (socket->priv->current_errors & FD_WRITE)
2394 condition |= G_IO_ERR;
2396 condition |= G_IO_OUT;
2400 if (socket->priv->current_events & FD_CONNECT)
2402 if (socket->priv->current_errors & FD_CONNECT)
2403 condition |= (G_IO_HUP | G_IO_ERR);
2405 condition |= G_IO_OUT;
2417 GIOCondition condition;
2418 GCancellable *cancellable;
2419 GPollFD cancel_pollfd;
2420 gint64 timeout_time;
2424 socket_source_prepare (GSource *source,
2427 GSocketSource *socket_source = (GSocketSource *)source;
2429 if (g_cancellable_is_cancelled (socket_source->cancellable))
2432 if (socket_source->timeout_time)
2436 now = g_source_get_time (source);
2437 /* Round up to ensure that we don't try again too early */
2438 *timeout = (socket_source->timeout_time - now + 999) / 1000;
2441 socket_source->socket->priv->timed_out = TRUE;
2450 socket_source->pollfd.revents = update_condition (socket_source->socket);
2453 if ((socket_source->condition & socket_source->pollfd.revents) != 0)
2460 socket_source_check (GSource *source)
2464 return socket_source_prepare (source, &timeout);
2468 socket_source_dispatch (GSource *source,
2469 GSourceFunc callback,
2472 GSocketSourceFunc func = (GSocketSourceFunc)callback;
2473 GSocketSource *socket_source = (GSocketSource *)source;
2476 socket_source->pollfd.revents = update_condition (socket_source->socket);
2478 if (socket_source->socket->priv->timed_out)
2479 socket_source->pollfd.revents |= socket_source->condition & (G_IO_IN | G_IO_OUT);
2481 return (*func) (socket_source->socket,
2482 socket_source->pollfd.revents & socket_source->condition,
2487 socket_source_finalize (GSource *source)
2489 GSocketSource *socket_source = (GSocketSource *)source;
2492 socket = socket_source->socket;
2495 remove_condition_watch (socket, &socket_source->condition);
2498 g_object_unref (socket);
2500 if (socket_source->cancellable)
2502 g_cancellable_release_fd (socket_source->cancellable);
2503 g_object_unref (socket_source->cancellable);
2508 socket_source_closure_callback (GSocket *socket,
2509 GIOCondition condition,
2512 GClosure *closure = data;
2514 GValue params[2] = { { 0, }, { 0, } };
2515 GValue result_value = { 0, };
2518 g_value_init (&result_value, G_TYPE_BOOLEAN);
2520 g_value_init (¶ms[0], G_TYPE_SOCKET);
2521 g_value_set_object (¶ms[0], socket);
2522 g_value_init (¶ms[1], G_TYPE_IO_CONDITION);
2523 g_value_set_flags (¶ms[1], condition);
2525 g_closure_invoke (closure, &result_value, 2, params, NULL);
2527 result = g_value_get_boolean (&result_value);
2528 g_value_unset (&result_value);
2529 g_value_unset (¶ms[0]);
2530 g_value_unset (¶ms[1]);
2535 static GSourceFuncs socket_source_funcs =
2537 socket_source_prepare,
2538 socket_source_check,
2539 socket_source_dispatch,
2540 socket_source_finalize,
2541 (GSourceFunc)socket_source_closure_callback,
2542 (GSourceDummyMarshal)g_cclosure_marshal_generic,
2546 socket_source_new (GSocket *socket,
2547 GIOCondition condition,
2548 GCancellable *cancellable)
2551 GSocketSource *socket_source;
2554 ensure_event (socket);
2556 if (socket->priv->event == WSA_INVALID_EVENT)
2558 g_warning ("Failed to create WSAEvent");
2559 return g_source_new (&broken_funcs, sizeof (GSource));
2563 condition |= G_IO_HUP | G_IO_ERR;
2565 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
2566 g_source_set_name (source, "GSocket");
2567 socket_source = (GSocketSource *)source;
2569 socket_source->socket = g_object_ref (socket);
2570 socket_source->condition = condition;
2572 if (g_cancellable_make_pollfd (cancellable,
2573 &socket_source->cancel_pollfd))
2575 socket_source->cancellable = g_object_ref (cancellable);
2576 g_source_add_poll (source, &socket_source->cancel_pollfd);
2580 add_condition_watch (socket, &socket_source->condition);
2581 socket_source->pollfd.fd = (gintptr) socket->priv->event;
2583 socket_source->pollfd.fd = socket->priv->fd;
2586 socket_source->pollfd.events = condition;
2587 socket_source->pollfd.revents = 0;
2588 g_source_add_poll (source, &socket_source->pollfd);
2590 if (socket->priv->timeout)
2591 socket_source->timeout_time = g_get_monotonic_time () +
2592 socket->priv->timeout * 1000000;
2595 socket_source->timeout_time = 0;
2601 * g_socket_create_source: (skip)
2602 * @socket: a #GSocket
2603 * @condition: a #GIOCondition mask to monitor
2604 * @cancellable: (allow-none): a %GCancellable or %NULL
2606 * Creates a %GSource that can be attached to a %GMainContext to monitor
2607 * for the availibility of the specified @condition on the socket.
2609 * The callback on the source is of the #GSocketSourceFunc type.
2611 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
2612 * these conditions will always be reported output if they are true.
2614 * @cancellable if not %NULL can be used to cancel the source, which will
2615 * cause the source to trigger, reporting the current condition (which
2616 * is likely 0 unless cancellation happened at the same time as a
2617 * condition change). You can check for this in the callback using
2618 * g_cancellable_is_cancelled().
2620 * If @socket has a timeout set, and it is reached before @condition
2621 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
2622 * %G_IO_OUT depending on @condition. However, @socket will have been
2623 * marked as having had a timeout, and so the next #GSocket I/O method
2624 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
2626 * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
2631 g_socket_create_source (GSocket *socket,
2632 GIOCondition condition,
2633 GCancellable *cancellable)
2635 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
2637 return socket_source_new (socket, condition, cancellable);
2641 * g_socket_condition_check:
2642 * @socket: a #GSocket
2643 * @condition: a #GIOCondition mask to check
2645 * Checks on the readiness of @socket to perform operations.
2646 * The operations specified in @condition are checked for and masked
2647 * against the currently-satisfied conditions on @socket. The result
2650 * Note that on Windows, it is possible for an operation to return
2651 * %G_IO_ERROR_WOULD_BLOCK even immediately after
2652 * g_socket_condition_check() has claimed that the socket is ready for
2653 * writing. Rather than calling g_socket_condition_check() and then
2654 * writing to the socket if it succeeds, it is generally better to
2655 * simply try writing to the socket right away, and try again later if
2656 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
2658 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2659 * these conditions will always be set in the output if they are true.
2661 * This call never blocks.
2663 * Returns: the @GIOCondition mask of the current state
2668 g_socket_condition_check (GSocket *socket,
2669 GIOCondition condition)
2671 if (!check_socket (socket, NULL))
2676 GIOCondition current_condition;
2678 condition |= G_IO_ERR | G_IO_HUP;
2680 add_condition_watch (socket, &condition);
2681 current_condition = update_condition (socket);
2682 remove_condition_watch (socket, &condition);
2683 return condition & current_condition;
2689 poll_fd.fd = socket->priv->fd;
2690 poll_fd.events = condition;
2693 result = g_poll (&poll_fd, 1, 0);
2694 while (result == -1 && get_socket_errno () == EINTR);
2696 return poll_fd.revents;
2702 * g_socket_condition_wait:
2703 * @socket: a #GSocket
2704 * @condition: a #GIOCondition mask to wait for
2705 * @cancellable: (allow-none): a #GCancellable, or %NULL
2706 * @error: a #GError pointer, or %NULL
2708 * Waits for @condition to become true on @socket. When the condition
2709 * is met, %TRUE is returned.
2711 * If @cancellable is cancelled before the condition is met, or if the
2712 * socket has a timeout set and it is reached before the condition is
2713 * met, then %FALSE is returned and @error, if non-%NULL, is set to
2714 * the appropriate value (%G_IO_ERROR_CANCELLED or
2715 * %G_IO_ERROR_TIMED_OUT).
2717 * Returns: %TRUE if the condition was met, %FALSE otherwise
2722 g_socket_condition_wait (GSocket *socket,
2723 GIOCondition condition,
2724 GCancellable *cancellable,
2727 if (!check_socket (socket, error))
2730 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2735 GIOCondition current_condition;
2741 /* Always check these */
2742 condition |= G_IO_ERR | G_IO_HUP;
2744 add_condition_watch (socket, &condition);
2747 events[num_events++] = socket->priv->event;
2749 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
2750 events[num_events++] = (WSAEVENT)cancel_fd.fd;
2752 if (socket->priv->timeout)
2753 timeout = socket->priv->timeout * 1000;
2755 timeout = WSA_INFINITE;
2757 current_condition = update_condition (socket);
2758 while ((condition & current_condition) == 0)
2760 res = WSAWaitForMultipleEvents(num_events, events,
2761 FALSE, timeout, FALSE);
2762 if (res == WSA_WAIT_FAILED)
2764 int errsv = get_socket_errno ();
2766 g_set_error (error, G_IO_ERROR,
2767 socket_io_error_from_errno (errsv),
2768 _("Waiting for socket condition: %s"),
2769 socket_strerror (errsv));
2772 else if (res == WSA_WAIT_TIMEOUT)
2774 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
2775 _("Socket I/O timed out"));
2779 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2782 current_condition = update_condition (socket);
2784 remove_condition_watch (socket, &condition);
2786 g_cancellable_release_fd (cancellable);
2788 return (condition & current_condition) != 0;
2797 poll_fd[0].fd = socket->priv->fd;
2798 poll_fd[0].events = condition;
2801 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
2804 if (socket->priv->timeout)
2805 timeout = socket->priv->timeout * 1000;
2810 result = g_poll (poll_fd, num, timeout);
2811 while (result == -1 && get_socket_errno () == EINTR);
2814 g_cancellable_release_fd (cancellable);
2818 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
2819 _("Socket I/O timed out"));
2823 return !g_cancellable_set_error_if_cancelled (cancellable, error);
2829 * g_socket_send_message:
2830 * @socket: a #GSocket
2831 * @address: a #GSocketAddress, or %NULL
2832 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
2833 * @num_vectors: the number of elements in @vectors, or -1
2834 * @messages: (array length=num_messages) (allow-none): a pointer to an
2835 * array of #GSocketControlMessages, or %NULL.
2836 * @num_messages: number of elements in @messages, or -1.
2837 * @flags: an int containing #GSocketMsgFlags flags
2838 * @cancellable: (allow-none): a %GCancellable or %NULL
2839 * @error: #GError for error reporting, or %NULL to ignore.
2841 * Send data to @address on @socket. This is the most complicated and
2842 * fully-featured version of this call. For easier use, see
2843 * g_socket_send() and g_socket_send_to().
2845 * If @address is %NULL then the message is sent to the default receiver
2846 * (set by g_socket_connect()).
2848 * @vectors must point to an array of #GOutputVector structs and
2849 * @num_vectors must be the length of this array. (If @num_vectors is -1,
2850 * then @vectors is assumed to be terminated by a #GOutputVector with a
2851 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
2852 * that the sent data will be gathered from. Using multiple
2853 * #GOutputVector<!-- -->s is more memory-efficient than manually copying
2854 * data from multiple sources into a single buffer, and more
2855 * network-efficient than making multiple calls to g_socket_send().
2857 * @messages, if non-%NULL, is taken to point to an array of @num_messages
2858 * #GSocketControlMessage instances. These correspond to the control
2859 * messages to be sent on the socket.
2860 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
2863 * @flags modify how the message is sent. The commonly available arguments
2864 * for this are available in the #GSocketMsgFlags enum, but the
2865 * values there are the same as the system values, and the flags
2866 * are passed in as-is, so you can pass in system-specific flags too.
2868 * If the socket is in blocking mode the call will block until there is
2869 * space for the data in the socket queue. If there is no space available
2870 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2871 * will be returned. To be notified when space is available, wait for the
2872 * %G_IO_OUT condition. Note though that you may still receive
2873 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2874 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2875 * very common due to the way the underlying APIs work.)
2877 * On error -1 is returned and @error is set accordingly.
2879 * Returns: Number of bytes written (which may be less than @size), or -1
2885 g_socket_send_message (GSocket *socket,
2886 GSocketAddress *address,
2887 GOutputVector *vectors,
2889 GSocketControlMessage **messages,
2892 GCancellable *cancellable,
2895 GOutputVector one_vector;
2898 if (!check_socket (socket, error))
2901 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2904 if (num_vectors == -1)
2906 for (num_vectors = 0;
2907 vectors[num_vectors].buffer != NULL;
2912 if (num_messages == -1)
2914 for (num_messages = 0;
2915 messages != NULL && messages[num_messages] != NULL;
2920 if (num_vectors == 0)
2924 one_vector.buffer = &zero;
2925 one_vector.size = 1;
2927 vectors = &one_vector;
2940 msg.msg_namelen = g_socket_address_get_native_size (address);
2941 msg.msg_name = g_alloca (msg.msg_namelen);
2942 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
2947 msg.msg_name = NULL;
2948 msg.msg_namelen = 0;
2953 /* this entire expression will be evaluated at compile time */
2954 if (sizeof *msg.msg_iov == sizeof *vectors &&
2955 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2956 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2957 G_STRUCT_OFFSET (GOutputVector, buffer) &&
2958 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2959 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2960 G_STRUCT_OFFSET (GOutputVector, size))
2961 /* ABI is compatible */
2963 msg.msg_iov = (struct iovec *) vectors;
2964 msg.msg_iovlen = num_vectors;
2967 /* ABI is incompatible */
2971 msg.msg_iov = g_newa (struct iovec, num_vectors);
2972 for (i = 0; i < num_vectors; i++)
2974 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
2975 msg.msg_iov[i].iov_len = vectors[i].size;
2977 msg.msg_iovlen = num_vectors;
2983 struct cmsghdr *cmsg;
2986 msg.msg_controllen = 0;
2987 for (i = 0; i < num_messages; i++)
2988 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
2990 if (msg.msg_controllen == 0)
2991 msg.msg_control = NULL;
2994 msg.msg_control = g_alloca (msg.msg_controllen);
2995 memset (msg.msg_control, '\0', msg.msg_controllen);
2998 cmsg = CMSG_FIRSTHDR (&msg);
2999 for (i = 0; i < num_messages; i++)
3001 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
3002 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
3003 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
3004 g_socket_control_message_serialize (messages[i],
3006 cmsg = CMSG_NXTHDR (&msg, cmsg);
3008 g_assert (cmsg == NULL);
3013 if (socket->priv->blocking &&
3014 !g_socket_condition_wait (socket,
3015 G_IO_OUT, cancellable, error))
3018 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
3021 int errsv = get_socket_errno ();
3026 if (socket->priv->blocking &&
3027 (errsv == EWOULDBLOCK ||
3031 g_set_error (error, G_IO_ERROR,
3032 socket_io_error_from_errno (errsv),
3033 _("Error sending message: %s"), socket_strerror (errsv));
3044 struct sockaddr_storage addr;
3051 /* Win32 doesn't support control messages.
3052 Actually this is possible for raw and datagram sockets
3053 via WSASendMessage on Vista or later, but that doesn't
3055 if (num_messages != 0)
3057 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
3058 _("GSocketControlMessage not supported on windows"));
3063 bufs = g_newa (WSABUF, num_vectors);
3064 for (i = 0; i < num_vectors; i++)
3066 bufs[i].buf = (char *)vectors[i].buffer;
3067 bufs[i].len = (gulong)vectors[i].size;
3071 addrlen = 0; /* Avoid warning */
3074 addrlen = g_socket_address_get_native_size (address);
3075 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
3081 if (socket->priv->blocking &&
3082 !g_socket_condition_wait (socket,
3083 G_IO_OUT, cancellable, error))
3087 result = WSASendTo (socket->priv->fd,
3090 (const struct sockaddr *)&addr, addrlen,
3093 result = WSASend (socket->priv->fd,
3100 int errsv = get_socket_errno ();
3102 if (errsv == WSAEINTR)
3105 if (errsv == WSAEWOULDBLOCK)
3106 win32_unset_event_mask (socket, FD_WRITE);
3108 if (socket->priv->blocking &&
3109 errsv == WSAEWOULDBLOCK)
3112 g_set_error (error, G_IO_ERROR,
3113 socket_io_error_from_errno (errsv),
3114 _("Error sending message: %s"), socket_strerror (errsv));
3127 * g_socket_receive_message:
3128 * @socket: a #GSocket
3129 * @address: a pointer to a #GSocketAddress pointer, or %NULL
3130 * @vectors: (array length=num_vectors): an array of #GInputVector structs
3131 * @num_vectors: the number of elements in @vectors, or -1
3132 * @messages: (array length=num_messages) (allow-none): a pointer which
3133 * may be filled with an array of #GSocketControlMessages, or %NULL
3134 * @num_messages: a pointer which will be filled with the number of
3135 * elements in @messages, or %NULL
3136 * @flags: a pointer to an int containing #GSocketMsgFlags flags
3137 * @cancellable: (allow-none): a %GCancellable or %NULL
3138 * @error: a #GError pointer, or %NULL
3140 * Receive data from a socket. This is the most complicated and
3141 * fully-featured version of this call. For easier use, see
3142 * g_socket_receive() and g_socket_receive_from().
3144 * If @address is non-%NULL then @address will be set equal to the
3145 * source address of the received packet.
3146 * @address is owned by the caller.
3148 * @vector must point to an array of #GInputVector structs and
3149 * @num_vectors must be the length of this array. These structs
3150 * describe the buffers that received data will be scattered into.
3151 * If @num_vectors is -1, then @vectors is assumed to be terminated
3152 * by a #GInputVector with a %NULL buffer pointer.
3154 * As a special case, if @num_vectors is 0 (in which case, @vectors
3155 * may of course be %NULL), then a single byte is received and
3156 * discarded. This is to facilitate the common practice of sending a
3157 * single '\0' byte for the purposes of transferring ancillary data.
3159 * @messages, if non-%NULL, will be set to point to a newly-allocated
3160 * array of #GSocketControlMessage instances or %NULL if no such
3161 * messages was received. These correspond to the control messages
3162 * received from the kernel, one #GSocketControlMessage per message
3163 * from the kernel. This array is %NULL-terminated and must be freed
3164 * by the caller using g_free() after calling g_object_unref() on each
3165 * element. If @messages is %NULL, any control messages received will
3168 * @num_messages, if non-%NULL, will be set to the number of control
3169 * messages received.
3171 * If both @messages and @num_messages are non-%NULL, then
3172 * @num_messages gives the number of #GSocketControlMessage instances
3173 * in @messages (ie: not including the %NULL terminator).
3175 * @flags is an in/out parameter. The commonly available arguments
3176 * for this are available in the #GSocketMsgFlags enum, but the
3177 * values there are the same as the system values, and the flags
3178 * are passed in as-is, so you can pass in system-specific flags too
3179 * (and g_socket_receive_message() may pass system-specific flags out).
3181 * As with g_socket_receive(), data may be discarded if @socket is
3182 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
3183 * provide enough buffer space to read a complete message. You can pass
3184 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
3185 * removing it from the receive queue, but there is no portable way to find
3186 * out the length of the message other than by reading it into a
3187 * sufficiently-large buffer.
3189 * If the socket is in blocking mode the call will block until there
3190 * is some data to receive, the connection is closed, or there is an
3191 * error. If there is no data available and the socket is in
3192 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
3193 * returned. To be notified when data is available, wait for the
3194 * %G_IO_IN condition.
3196 * On error -1 is returned and @error is set accordingly.
3198 * Returns: Number of bytes read, or 0 if the connection was closed by
3199 * the peer, or -1 on error
3204 g_socket_receive_message (GSocket *socket,
3205 GSocketAddress **address,
3206 GInputVector *vectors,
3208 GSocketControlMessage ***messages,
3211 GCancellable *cancellable,
3214 GInputVector one_vector;
3217 if (!check_socket (socket, error))
3220 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3223 if (num_vectors == -1)
3225 for (num_vectors = 0;
3226 vectors[num_vectors].buffer != NULL;
3231 if (num_vectors == 0)
3233 one_vector.buffer = &one_byte;
3234 one_vector.size = 1;
3236 vectors = &one_vector;
3243 struct sockaddr_storage one_sockaddr;
3248 msg.msg_name = &one_sockaddr;
3249 msg.msg_namelen = sizeof (struct sockaddr_storage);
3253 msg.msg_name = NULL;
3254 msg.msg_namelen = 0;
3258 /* this entire expression will be evaluated at compile time */
3259 if (sizeof *msg.msg_iov == sizeof *vectors &&
3260 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3261 G_STRUCT_OFFSET (struct iovec, iov_base) ==
3262 G_STRUCT_OFFSET (GInputVector, buffer) &&
3263 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3264 G_STRUCT_OFFSET (struct iovec, iov_len) ==
3265 G_STRUCT_OFFSET (GInputVector, size))
3266 /* ABI is compatible */
3268 msg.msg_iov = (struct iovec *) vectors;
3269 msg.msg_iovlen = num_vectors;
3272 /* ABI is incompatible */
3276 msg.msg_iov = g_newa (struct iovec, num_vectors);
3277 for (i = 0; i < num_vectors; i++)
3279 msg.msg_iov[i].iov_base = vectors[i].buffer;
3280 msg.msg_iov[i].iov_len = vectors[i].size;
3282 msg.msg_iovlen = num_vectors;
3286 msg.msg_control = g_alloca (2048);
3287 msg.msg_controllen = 2048;
3291 msg.msg_flags = *flags;
3295 /* We always set the close-on-exec flag so we don't leak file
3296 * descriptors into child processes. Note that gunixfdmessage.c
3297 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
3299 #ifdef MSG_CMSG_CLOEXEC
3300 msg.msg_flags |= MSG_CMSG_CLOEXEC;
3306 if (socket->priv->blocking &&
3307 !g_socket_condition_wait (socket,
3308 G_IO_IN, cancellable, error))
3311 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
3312 #ifdef MSG_CMSG_CLOEXEC
3313 if (result < 0 && get_socket_errno () == EINVAL)
3315 /* We must be running on an old kernel. Call without the flag. */
3316 msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
3317 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
3323 int errsv = get_socket_errno ();
3328 if (socket->priv->blocking &&
3329 (errsv == EWOULDBLOCK ||
3333 g_set_error (error, G_IO_ERROR,
3334 socket_io_error_from_errno (errsv),
3335 _("Error receiving message: %s"), socket_strerror (errsv));
3342 /* decode address */
3343 if (address != NULL)
3345 if (msg.msg_namelen > 0)
3346 *address = g_socket_address_new_from_native (msg.msg_name,
3352 /* decode control messages */
3354 GPtrArray *my_messages = NULL;
3355 struct cmsghdr *cmsg;
3357 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
3359 GSocketControlMessage *message;
3361 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
3363 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
3365 if (message == NULL)
3366 /* We've already spewed about the problem in the
3367 deserialization code, so just continue */
3370 if (messages == NULL)
3372 /* we have to do it this way if the user ignores the
3373 * messages so that we will close any received fds.
3375 g_object_unref (message);
3379 if (my_messages == NULL)
3380 my_messages = g_ptr_array_new ();
3381 g_ptr_array_add (my_messages, message);
3386 *num_messages = my_messages != NULL ? my_messages->len : 0;
3390 if (my_messages == NULL)
3396 g_ptr_array_add (my_messages, NULL);
3397 *messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
3402 g_assert (my_messages == NULL);
3406 /* capture the flags */
3408 *flags = msg.msg_flags;
3414 struct sockaddr_storage addr;
3416 DWORD bytes_received;
3423 bufs = g_newa (WSABUF, num_vectors);
3424 for (i = 0; i < num_vectors; i++)
3426 bufs[i].buf = (char *)vectors[i].buffer;
3427 bufs[i].len = (gulong)vectors[i].size;
3439 if (socket->priv->blocking &&
3440 !g_socket_condition_wait (socket,
3441 G_IO_IN, cancellable, error))
3444 addrlen = sizeof addr;
3446 result = WSARecvFrom (socket->priv->fd,
3448 &bytes_received, &win_flags,
3449 (struct sockaddr *)&addr, &addrlen,
3452 result = WSARecv (socket->priv->fd,
3454 &bytes_received, &win_flags,
3458 int errsv = get_socket_errno ();
3460 if (errsv == WSAEINTR)
3463 win32_unset_event_mask (socket, FD_READ);
3465 if (socket->priv->blocking &&
3466 errsv == WSAEWOULDBLOCK)
3469 g_set_error (error, G_IO_ERROR,
3470 socket_io_error_from_errno (errsv),
3471 _("Error receiving message: %s"), socket_strerror (errsv));
3475 win32_unset_event_mask (socket, FD_READ);
3479 /* decode address */
3480 if (address != NULL)
3483 *address = g_socket_address_new_from_native (&addr, addrlen);
3488 /* capture the flags */
3492 if (messages != NULL)
3494 if (num_messages != NULL)
3497 return bytes_received;
3503 * g_socket_get_credentials:
3504 * @socket: a #GSocket.
3505 * @error: #GError for error reporting, or %NULL to ignore.
3507 * Returns the credentials of the foreign process connected to this
3508 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
3511 * If this operation isn't supported on the OS, the method fails with
3512 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
3513 * by reading the %SO_PEERCRED option on the underlying socket.
3515 * Other ways to obtain credentials from a foreign peer includes the
3516 * #GUnixCredentialsMessage type and
3517 * g_unix_connection_send_credentials() /
3518 * g_unix_connection_receive_credentials() functions.
3520 * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
3521 * that must be freed with g_object_unref().
3526 g_socket_get_credentials (GSocket *socket,
3531 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
3532 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3536 #if defined(__linux__) || defined(__OpenBSD__)
3539 #if defined(__linux__)
3540 struct ucred native_creds;
3541 optlen = sizeof (struct ucred);
3542 #elif defined(__OpenBSD__)
3543 struct sockpeercred native_creds;
3544 optlen = sizeof (struct sockpeercred);
3546 if (getsockopt (socket->priv->fd,
3549 (void *)&native_creds,
3552 int errsv = get_socket_errno ();
3555 socket_io_error_from_errno (errsv),
3556 _("Unable to get pending error: %s"),
3557 socket_strerror (errsv));
3561 ret = g_credentials_new ();
3562 g_credentials_set_native (ret,
3563 #if defined(__linux__)
3564 G_CREDENTIALS_TYPE_LINUX_UCRED,
3565 #elif defined(__OpenBSD__)
3566 G_CREDENTIALS_TYPE_OPENBSD_SOCKPEERCRED,
3572 g_set_error_literal (error,
3574 G_IO_ERROR_NOT_SUPPORTED,
3575 _("g_socket_get_credentials not implemented for this OS"));