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 ();
399 case G_SOCKET_FAMILY_IPV4:
400 case G_SOCKET_FAMILY_IPV6:
401 socket->priv->family = address.ss_family;
402 switch (socket->priv->type)
404 case G_SOCKET_TYPE_STREAM:
405 socket->priv->protocol = G_SOCKET_PROTOCOL_TCP;
408 case G_SOCKET_TYPE_DATAGRAM:
409 socket->priv->protocol = G_SOCKET_PROTOCOL_UDP;
412 case G_SOCKET_TYPE_SEQPACKET:
413 socket->priv->protocol = G_SOCKET_PROTOCOL_SCTP;
421 case G_SOCKET_FAMILY_UNIX:
422 socket->priv->family = G_SOCKET_FAMILY_UNIX;
423 socket->priv->protocol = G_SOCKET_PROTOCOL_DEFAULT;
427 socket->priv->family = G_SOCKET_FAMILY_INVALID;
431 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
433 addrlen = sizeof address;
434 if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
435 socket->priv->connected = TRUE;
438 optlen = sizeof bool_val;
439 if (getsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
440 (void *)&bool_val, &optlen) == 0)
443 /* Experimentation indicates that the SO_KEEPALIVE value is
444 * actually a char on Windows, even if documentation claims it
445 * to be a BOOL which is a typedef for int. So this g_assert()
446 * fails. See bug #611756.
448 g_assert (optlen == sizeof bool_val);
450 socket->priv->keepalive = !!bool_val;
454 /* Can't read, maybe not supported, assume FALSE */
455 socket->priv->keepalive = FALSE;
461 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
462 socket_io_error_from_errno (errsv),
463 _("creating GSocket from fd: %s"),
464 socket_strerror (errsv));
468 g_socket_create_socket (GSocketFamily family,
478 case G_SOCKET_TYPE_STREAM:
479 native_type = SOCK_STREAM;
482 case G_SOCKET_TYPE_DATAGRAM:
483 native_type = SOCK_DGRAM;
486 case G_SOCKET_TYPE_SEQPACKET:
487 native_type = SOCK_SEQPACKET;
491 g_assert_not_reached ();
496 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
497 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
502 fd = socket (family, native_type | SOCK_CLOEXEC, protocol);
503 /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
504 if (fd < 0 && errno == EINVAL)
506 fd = socket (family, native_type, protocol);
510 int errsv = get_socket_errno ();
512 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
513 _("Unable to create socket: %s"), socket_strerror (errsv));
520 /* We always want to set close-on-exec to protect users. If you
521 need to so some weird inheritance to exec you can re-enable this
522 using lower level hacks with g_socket_get_fd(). */
523 flags = fcntl (fd, F_GETFD, 0);
525 (flags & FD_CLOEXEC) == 0)
528 fcntl (fd, F_SETFD, flags);
537 g_socket_constructed (GObject *object)
539 GSocket *socket = G_SOCKET (object);
541 if (socket->priv->fd >= 0)
542 /* create socket->priv info from the fd */
543 g_socket_details_from_fd (socket);
546 /* create the fd from socket->priv info */
547 socket->priv->fd = g_socket_create_socket (socket->priv->family,
549 socket->priv->protocol,
550 &socket->priv->construct_error);
552 /* Always use native nonblocking sockets, as
553 windows sets sockets to nonblocking automatically
554 in certain operations. This way we make things work
555 the same on all platforms */
556 if (socket->priv->fd != -1)
557 set_fd_nonblocking (socket->priv->fd);
561 g_socket_get_property (GObject *object,
566 GSocket *socket = G_SOCKET (object);
567 GSocketAddress *address;
572 g_value_set_enum (value, socket->priv->family);
576 g_value_set_enum (value, socket->priv->type);
580 g_value_set_enum (value, socket->priv->protocol);
584 g_value_set_int (value, socket->priv->fd);
588 g_value_set_boolean (value, socket->priv->blocking);
591 case PROP_LISTEN_BACKLOG:
592 g_value_set_int (value, socket->priv->listen_backlog);
596 g_value_set_boolean (value, socket->priv->keepalive);
599 case PROP_LOCAL_ADDRESS:
600 address = g_socket_get_local_address (socket, NULL);
601 g_value_take_object (value, address);
604 case PROP_REMOTE_ADDRESS:
605 address = g_socket_get_remote_address (socket, NULL);
606 g_value_take_object (value, address);
610 g_value_set_uint (value, socket->priv->timeout);
614 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
619 g_socket_set_property (GObject *object,
624 GSocket *socket = G_SOCKET (object);
629 socket->priv->family = g_value_get_enum (value);
633 socket->priv->type = g_value_get_enum (value);
637 socket->priv->protocol = g_value_get_enum (value);
641 socket->priv->fd = g_value_get_int (value);
645 g_socket_set_blocking (socket, g_value_get_boolean (value));
648 case PROP_LISTEN_BACKLOG:
649 g_socket_set_listen_backlog (socket, g_value_get_int (value));
653 g_socket_set_keepalive (socket, g_value_get_boolean (value));
657 g_socket_set_timeout (socket, g_value_get_uint (value));
661 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
666 g_socket_finalize (GObject *object)
668 GSocket *socket = G_SOCKET (object);
670 g_clear_error (&socket->priv->construct_error);
672 if (socket->priv->fd != -1 &&
673 !socket->priv->closed)
674 g_socket_close (socket, NULL);
676 if (socket->priv->remote_address)
677 g_object_unref (socket->priv->remote_address);
680 if (socket->priv->event != WSA_INVALID_EVENT)
682 WSACloseEvent (socket->priv->event);
683 socket->priv->event = WSA_INVALID_EVENT;
686 g_assert (socket->priv->requested_conditions == NULL);
689 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
690 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
694 g_socket_class_init (GSocketClass *klass)
696 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
699 /* Make sure winsock has been initialized */
700 type = g_inet_address_get_type ();
701 (type); /* To avoid -Wunused-but-set-variable */
704 /* There is no portable, thread-safe way to avoid having the process
705 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
706 * forced to simply ignore the signal process-wide.
708 signal (SIGPIPE, SIG_IGN);
711 g_type_class_add_private (klass, sizeof (GSocketPrivate));
713 gobject_class->finalize = g_socket_finalize;
714 gobject_class->constructed = g_socket_constructed;
715 gobject_class->set_property = g_socket_set_property;
716 gobject_class->get_property = g_socket_get_property;
718 g_object_class_install_property (gobject_class, PROP_FAMILY,
719 g_param_spec_enum ("family",
721 P_("The sockets address family"),
722 G_TYPE_SOCKET_FAMILY,
723 G_SOCKET_FAMILY_INVALID,
724 G_PARAM_CONSTRUCT_ONLY |
726 G_PARAM_STATIC_STRINGS));
728 g_object_class_install_property (gobject_class, PROP_TYPE,
729 g_param_spec_enum ("type",
731 P_("The sockets type"),
733 G_SOCKET_TYPE_STREAM,
734 G_PARAM_CONSTRUCT_ONLY |
736 G_PARAM_STATIC_STRINGS));
738 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
739 g_param_spec_enum ("protocol",
740 P_("Socket protocol"),
741 P_("The id of the protocol to use, or -1 for unknown"),
742 G_TYPE_SOCKET_PROTOCOL,
743 G_SOCKET_PROTOCOL_UNKNOWN,
744 G_PARAM_CONSTRUCT_ONLY |
746 G_PARAM_STATIC_STRINGS));
748 g_object_class_install_property (gobject_class, PROP_FD,
749 g_param_spec_int ("fd",
750 P_("File descriptor"),
751 P_("The sockets file descriptor"),
755 G_PARAM_CONSTRUCT_ONLY |
757 G_PARAM_STATIC_STRINGS));
759 g_object_class_install_property (gobject_class, PROP_BLOCKING,
760 g_param_spec_boolean ("blocking",
762 P_("Whether or not I/O on this socket is blocking"),
765 G_PARAM_STATIC_STRINGS));
767 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
768 g_param_spec_int ("listen-backlog",
769 P_("Listen backlog"),
770 P_("Outstanding connections in the listen queue"),
775 G_PARAM_STATIC_STRINGS));
777 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
778 g_param_spec_boolean ("keepalive",
779 P_("Keep connection alive"),
780 P_("Keep connection alive by sending periodic pings"),
783 G_PARAM_STATIC_STRINGS));
785 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
786 g_param_spec_object ("local-address",
788 P_("The local address the socket is bound to"),
789 G_TYPE_SOCKET_ADDRESS,
791 G_PARAM_STATIC_STRINGS));
793 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
794 g_param_spec_object ("remote-address",
795 P_("Remote address"),
796 P_("The remote address the socket is connected to"),
797 G_TYPE_SOCKET_ADDRESS,
799 G_PARAM_STATIC_STRINGS));
804 * The timeout in seconds on socket I/O
808 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
809 g_param_spec_uint ("timeout",
811 P_("The timeout in seconds on socket I/O"),
816 G_PARAM_STATIC_STRINGS));
820 g_socket_initable_iface_init (GInitableIface *iface)
822 iface->init = g_socket_initable_init;
826 g_socket_init (GSocket *socket)
828 socket->priv = G_TYPE_INSTANCE_GET_PRIVATE (socket, G_TYPE_SOCKET, GSocketPrivate);
830 socket->priv->fd = -1;
831 socket->priv->blocking = TRUE;
832 socket->priv->listen_backlog = 10;
833 socket->priv->construct_error = NULL;
835 socket->priv->event = WSA_INVALID_EVENT;
840 g_socket_initable_init (GInitable *initable,
841 GCancellable *cancellable,
846 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
848 socket = G_SOCKET (initable);
850 if (cancellable != NULL)
852 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
853 _("Cancellable initialization not supported"));
857 socket->priv->inited = TRUE;
859 if (socket->priv->construct_error)
862 *error = g_error_copy (socket->priv->construct_error);
872 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
873 * @type: the socket type to use.
874 * @protocol: the id of the protocol to use, or 0 for default.
875 * @error: #GError for error reporting, or %NULL to ignore.
877 * Creates a new #GSocket with the defined family, type and protocol.
878 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
879 * for the family and type is used.
881 * The @protocol is a family and type specific int that specifies what
882 * kind of protocol to use. #GSocketProtocol lists several common ones.
883 * Many families only support one protocol, and use 0 for this, others
884 * support several and using 0 means to use the default protocol for
885 * the family and type.
887 * The protocol id is passed directly to the operating
888 * system, so you can use protocols not listed in #GSocketProtocol if you
889 * know the protocol number used for it.
891 * Returns: a #GSocket or %NULL on error.
892 * Free the returned object with g_object_unref().
897 g_socket_new (GSocketFamily family,
899 GSocketProtocol protocol,
902 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
906 "protocol", protocol,
911 * g_socket_new_from_fd:
912 * @fd: a native socket file descriptor.
913 * @error: #GError for error reporting, or %NULL to ignore.
915 * Creates a new #GSocket from a native file descriptor
916 * or winsock SOCKET handle.
918 * This reads all the settings from the file descriptor so that
919 * all properties should work. Note that the file descriptor
920 * will be set to non-blocking mode, independent on the blocking
921 * mode of the #GSocket.
923 * Returns: a #GSocket or %NULL on error.
924 * Free the returned object with g_object_unref().
929 g_socket_new_from_fd (gint fd,
932 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
939 * g_socket_set_blocking:
940 * @socket: a #GSocket.
941 * @blocking: Whether to use blocking I/O or not.
943 * Sets the blocking mode of the socket. In blocking mode
944 * all operations block until they succeed or there is an error. In
945 * non-blocking mode all functions return results immediately or
946 * with a %G_IO_ERROR_WOULD_BLOCK error.
948 * All sockets are created in blocking mode. However, note that the
949 * platform level socket is always non-blocking, and blocking mode
950 * is a GSocket level feature.
955 g_socket_set_blocking (GSocket *socket,
958 g_return_if_fail (G_IS_SOCKET (socket));
960 blocking = !!blocking;
962 if (socket->priv->blocking == blocking)
965 socket->priv->blocking = blocking;
966 g_object_notify (G_OBJECT (socket), "blocking");
970 * g_socket_get_blocking:
971 * @socket: a #GSocket.
973 * Gets the blocking mode of the socket. For details on blocking I/O,
974 * see g_socket_set_blocking().
976 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
981 g_socket_get_blocking (GSocket *socket)
983 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
985 return socket->priv->blocking;
989 * g_socket_set_keepalive:
990 * @socket: a #GSocket.
991 * @keepalive: Value for the keepalive flag
993 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
994 * this flag is set on a socket, the system will attempt to verify that the
995 * remote socket endpoint is still present if a sufficiently long period of
996 * time passes with no data being exchanged. If the system is unable to
997 * verify the presence of the remote endpoint, it will automatically close
1000 * This option is only functional on certain kinds of sockets. (Notably,
1001 * %G_SOCKET_PROTOCOL_TCP sockets.)
1003 * The exact time between pings is system- and protocol-dependent, but will
1004 * normally be at least two hours. Most commonly, you would set this flag
1005 * on a server socket if you want to allow clients to remain idle for long
1006 * periods of time, but also want to ensure that connections are eventually
1007 * garbage-collected if clients crash or become unreachable.
1012 g_socket_set_keepalive (GSocket *socket,
1017 g_return_if_fail (G_IS_SOCKET (socket));
1019 keepalive = !!keepalive;
1020 if (socket->priv->keepalive == keepalive)
1023 value = (gint) keepalive;
1024 if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_KEEPALIVE,
1025 (gpointer) &value, sizeof (value)) < 0)
1027 int errsv = get_socket_errno ();
1028 g_warning ("error setting keepalive: %s", socket_strerror (errsv));
1032 socket->priv->keepalive = keepalive;
1033 g_object_notify (G_OBJECT (socket), "keepalive");
1037 * g_socket_get_keepalive:
1038 * @socket: a #GSocket.
1040 * Gets the keepalive mode of the socket. For details on this,
1041 * see g_socket_set_keepalive().
1043 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1048 g_socket_get_keepalive (GSocket *socket)
1050 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1052 return socket->priv->keepalive;
1056 * g_socket_get_listen_backlog:
1057 * @socket: a #GSocket.
1059 * Gets the listen backlog setting of the socket. For details on this,
1060 * see g_socket_set_listen_backlog().
1062 * Returns: the maximum number of pending connections.
1067 g_socket_get_listen_backlog (GSocket *socket)
1069 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1071 return socket->priv->listen_backlog;
1075 * g_socket_set_listen_backlog:
1076 * @socket: a #GSocket.
1077 * @backlog: the maximum number of pending connections.
1079 * Sets the maximum number of outstanding connections allowed
1080 * when listening on this socket. If more clients than this are
1081 * connecting to the socket and the application is not handling them
1082 * on time then the new connections will be refused.
1084 * Note that this must be called before g_socket_listen() and has no
1085 * effect if called after that.
1090 g_socket_set_listen_backlog (GSocket *socket,
1093 g_return_if_fail (G_IS_SOCKET (socket));
1094 g_return_if_fail (!socket->priv->listening);
1096 if (backlog != socket->priv->listen_backlog)
1098 socket->priv->listen_backlog = backlog;
1099 g_object_notify (G_OBJECT (socket), "listen-backlog");
1104 * g_socket_get_timeout:
1105 * @socket: a #GSocket.
1107 * Gets the timeout setting of the socket. For details on this, see
1108 * g_socket_set_timeout().
1110 * Returns: the timeout in seconds
1115 g_socket_get_timeout (GSocket *socket)
1117 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1119 return socket->priv->timeout;
1123 * g_socket_set_timeout:
1124 * @socket: a #GSocket.
1125 * @timeout: the timeout for @socket, in seconds, or 0 for none
1127 * Sets the time in seconds after which I/O operations on @socket will
1128 * time out if they have not yet completed.
1130 * On a blocking socket, this means that any blocking #GSocket
1131 * operation will time out after @timeout seconds of inactivity,
1132 * returning %G_IO_ERROR_TIMED_OUT.
1134 * On a non-blocking socket, calls to g_socket_condition_wait() will
1135 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1136 * created with g_socket_create_source() will trigger after
1137 * @timeout seconds of inactivity, with the requested condition
1138 * set, at which point calling g_socket_receive(), g_socket_send(),
1139 * g_socket_check_connect_result(), etc, will fail with
1140 * %G_IO_ERROR_TIMED_OUT.
1142 * If @timeout is 0 (the default), operations will never time out
1145 * Note that if an I/O operation is interrupted by a signal, this may
1146 * cause the timeout to be reset.
1151 g_socket_set_timeout (GSocket *socket,
1154 g_return_if_fail (G_IS_SOCKET (socket));
1156 if (timeout != socket->priv->timeout)
1158 socket->priv->timeout = timeout;
1159 g_object_notify (G_OBJECT (socket), "timeout");
1164 * g_socket_get_family:
1165 * @socket: a #GSocket.
1167 * Gets the socket family of the socket.
1169 * Returns: a #GSocketFamily
1174 g_socket_get_family (GSocket *socket)
1176 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1178 return socket->priv->family;
1182 * g_socket_get_socket_type:
1183 * @socket: a #GSocket.
1185 * Gets the socket type of the socket.
1187 * Returns: a #GSocketType
1192 g_socket_get_socket_type (GSocket *socket)
1194 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1196 return socket->priv->type;
1200 * g_socket_get_protocol:
1201 * @socket: a #GSocket.
1203 * Gets the socket protocol id the socket was created with.
1204 * In case the protocol is unknown, -1 is returned.
1206 * Returns: a protocol id, or -1 if unknown
1211 g_socket_get_protocol (GSocket *socket)
1213 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1215 return socket->priv->protocol;
1220 * @socket: a #GSocket.
1222 * Returns the underlying OS socket object. On unix this
1223 * is a socket file descriptor, and on windows this is
1224 * a Winsock2 SOCKET handle. This may be useful for
1225 * doing platform specific or otherwise unusual operations
1228 * Returns: the file descriptor of the socket.
1233 g_socket_get_fd (GSocket *socket)
1235 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1237 return socket->priv->fd;
1241 * g_socket_get_local_address:
1242 * @socket: a #GSocket.
1243 * @error: #GError for error reporting, or %NULL to ignore.
1245 * Try to get the local address of a bound socket. This is only
1246 * useful if the socket has been bound to a local address,
1247 * either explicitly or implicitly when connecting.
1249 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1250 * Free the returned object with g_object_unref().
1255 g_socket_get_local_address (GSocket *socket,
1258 struct sockaddr_storage buffer;
1259 guint32 len = sizeof (buffer);
1261 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1263 if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1265 int errsv = get_socket_errno ();
1266 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1267 _("could not get local address: %s"), socket_strerror (errsv));
1271 return g_socket_address_new_from_native (&buffer, len);
1275 * g_socket_get_remote_address:
1276 * @socket: a #GSocket.
1277 * @error: #GError for error reporting, or %NULL to ignore.
1279 * Try to get the remove address of a connected socket. This is only
1280 * useful for connection oriented sockets that have been connected.
1282 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1283 * Free the returned object with g_object_unref().
1288 g_socket_get_remote_address (GSocket *socket,
1291 struct sockaddr_storage buffer;
1292 guint32 len = sizeof (buffer);
1294 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1296 if (socket->priv->connect_pending)
1298 if (!g_socket_check_connect_result (socket, error))
1301 socket->priv->connect_pending = FALSE;
1304 if (!socket->priv->remote_address)
1306 if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1308 int errsv = get_socket_errno ();
1309 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1310 _("could not get remote address: %s"), socket_strerror (errsv));
1314 socket->priv->remote_address = g_socket_address_new_from_native (&buffer, len);
1317 return g_object_ref (socket->priv->remote_address);
1321 * g_socket_is_connected:
1322 * @socket: a #GSocket.
1324 * Check whether the socket is connected. This is only useful for
1325 * connection-oriented sockets.
1327 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1332 g_socket_is_connected (GSocket *socket)
1334 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1336 return socket->priv->connected;
1341 * @socket: a #GSocket.
1342 * @error: #GError for error reporting, or %NULL to ignore.
1344 * Marks the socket as a server socket, i.e. a socket that is used
1345 * to accept incoming requests using g_socket_accept().
1347 * Before calling this the socket must be bound to a local address using
1350 * To set the maximum amount of outstanding clients, use
1351 * g_socket_set_listen_backlog().
1353 * Returns: %TRUE on success, %FALSE on error.
1358 g_socket_listen (GSocket *socket,
1361 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1363 if (!check_socket (socket, error))
1366 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1368 int errsv = get_socket_errno ();
1370 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1371 _("could not listen: %s"), socket_strerror (errsv));
1375 socket->priv->listening = TRUE;
1382 * @socket: a #GSocket.
1383 * @address: a #GSocketAddress specifying the local address.
1384 * @allow_reuse: whether to allow reusing this address
1385 * @error: #GError for error reporting, or %NULL to ignore.
1387 * When a socket is created it is attached to an address family, but it
1388 * doesn't have an address in this family. g_socket_bind() assigns the
1389 * address (sometimes called name) of the socket.
1391 * It is generally required to bind to a local address before you can
1392 * receive connections. (See g_socket_listen() and g_socket_accept() ).
1393 * In certain situations, you may also want to bind a socket that will be
1394 * used to initiate connections, though this is not normally required.
1396 * @allow_reuse should be %TRUE for server sockets (sockets that you will
1397 * eventually call g_socket_accept() on), and %FALSE for client sockets.
1398 * (Specifically, if it is %TRUE, then g_socket_bind() will set the
1399 * %SO_REUSEADDR flag on the socket, allowing it to bind @address even if
1400 * that address was previously used by another socket that has not yet been
1401 * fully cleaned-up by the kernel. Failing to set this flag on a server
1402 * socket may cause the bind call to return %G_IO_ERROR_ADDRESS_IN_USE if
1403 * the server program is stopped and then immediately restarted.)
1405 * Returns: %TRUE on success, %FALSE on error.
1410 g_socket_bind (GSocket *socket,
1411 GSocketAddress *address,
1412 gboolean reuse_address,
1415 struct sockaddr_storage addr;
1417 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1419 if (!check_socket (socket, error))
1422 /* SO_REUSEADDR on windows means something else and is not what we want.
1423 It always allows the unix variant of SO_REUSEADDR anyway */
1428 value = (int) !!reuse_address;
1429 /* Ignore errors here, the only likely error is "not supported", and
1430 this is a "best effort" thing mainly */
1431 setsockopt (socket->priv->fd, SOL_SOCKET, SO_REUSEADDR,
1432 (gpointer) &value, sizeof (value));
1436 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1439 if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1440 g_socket_address_get_native_size (address)) < 0)
1442 int errsv = get_socket_errno ();
1444 G_IO_ERROR, socket_io_error_from_errno (errsv),
1445 _("Error binding to address: %s"), socket_strerror (errsv));
1453 * g_socket_speaks_ipv4:
1454 * @socket: a #GSocket
1456 * Checks if a socket is capable of speaking IPv4.
1458 * IPv4 sockets are capable of speaking IPv4. On some operating systems
1459 * and under some combinations of circumstances IPv6 sockets are also
1460 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
1463 * No other types of sockets are currently considered as being capable
1466 * Returns: %TRUE if this socket can be used with IPv4.
1471 g_socket_speaks_ipv4 (GSocket *socket)
1473 switch (socket->priv->family)
1475 case G_SOCKET_FAMILY_IPV4:
1478 case G_SOCKET_FAMILY_IPV6:
1479 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
1481 guint sizeof_int = sizeof (int);
1484 if (getsockopt (socket->priv->fd,
1485 IPPROTO_IPV6, IPV6_V6ONLY,
1486 &v6_only, &sizeof_int) != 0)
1502 * @socket: a #GSocket.
1503 * @cancellable: (allow-none): a %GCancellable or %NULL
1504 * @error: #GError for error reporting, or %NULL to ignore.
1506 * Accept incoming connections on a connection-based socket. This removes
1507 * the first outstanding connection request from the listening socket and
1508 * creates a #GSocket object for it.
1510 * The @socket must be bound to a local address with g_socket_bind() and
1511 * must be listening for incoming connections (g_socket_listen()).
1513 * If there are no outstanding connections then the operation will block
1514 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
1515 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
1517 * Returns: (transfer full): a new #GSocket, or %NULL on error.
1518 * Free the returned object with g_object_unref().
1523 g_socket_accept (GSocket *socket,
1524 GCancellable *cancellable,
1527 GSocket *new_socket;
1530 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1532 if (!check_socket (socket, error))
1537 if (socket->priv->blocking &&
1538 !g_socket_condition_wait (socket,
1539 G_IO_IN, cancellable, error))
1542 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
1544 int errsv = get_socket_errno ();
1546 win32_unset_event_mask (socket, FD_ACCEPT);
1551 if (socket->priv->blocking)
1553 #ifdef WSAEWOULDBLOCK
1554 if (errsv == WSAEWOULDBLOCK)
1557 if (errsv == EWOULDBLOCK ||
1563 g_set_error (error, G_IO_ERROR,
1564 socket_io_error_from_errno (errsv),
1565 _("Error accepting connection: %s"), socket_strerror (errsv));
1571 win32_unset_event_mask (socket, FD_ACCEPT);
1575 /* The socket inherits the accepting sockets event mask and even object,
1576 we need to remove that */
1577 WSAEventSelect (ret, NULL, 0);
1583 /* We always want to set close-on-exec to protect users. If you
1584 need to so some weird inheritance to exec you can re-enable this
1585 using lower level hacks with g_socket_get_fd(). */
1586 flags = fcntl (ret, F_GETFD, 0);
1588 (flags & FD_CLOEXEC) == 0)
1590 flags |= FD_CLOEXEC;
1591 fcntl (ret, F_SETFD, flags);
1596 new_socket = g_socket_new_from_fd (ret, error);
1597 if (new_socket == NULL)
1606 new_socket->priv->protocol = socket->priv->protocol;
1613 * @socket: a #GSocket.
1614 * @address: a #GSocketAddress specifying the remote address.
1615 * @cancellable: (allow-none): a %GCancellable or %NULL
1616 * @error: #GError for error reporting, or %NULL to ignore.
1618 * Connect the socket to the specified remote address.
1620 * For connection oriented socket this generally means we attempt to make
1621 * a connection to the @address. For a connection-less socket it sets
1622 * the default address for g_socket_send() and discards all incoming datagrams
1623 * from other sources.
1625 * Generally connection oriented sockets can only connect once, but
1626 * connection-less sockets can connect multiple times to change the
1629 * If the connect call needs to do network I/O it will block, unless
1630 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
1631 * and the user can be notified of the connection finishing by waiting
1632 * for the G_IO_OUT condition. The result of the connection must then be
1633 * checked with g_socket_check_connect_result().
1635 * Returns: %TRUE if connected, %FALSE on error.
1640 g_socket_connect (GSocket *socket,
1641 GSocketAddress *address,
1642 GCancellable *cancellable,
1645 struct sockaddr_storage buffer;
1647 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1649 if (!check_socket (socket, error))
1652 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
1655 if (socket->priv->remote_address)
1656 g_object_unref (socket->priv->remote_address);
1657 socket->priv->remote_address = g_object_ref (address);
1661 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
1662 g_socket_address_get_native_size (address)) < 0)
1664 int errsv = get_socket_errno ();
1670 if (errsv == EINPROGRESS)
1672 if (errsv == WSAEWOULDBLOCK)
1675 if (socket->priv->blocking)
1677 if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
1679 if (g_socket_check_connect_result (socket, error))
1682 g_prefix_error (error, _("Error connecting: "));
1686 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
1687 _("Connection in progress"));
1688 socket->priv->connect_pending = TRUE;
1692 g_set_error (error, G_IO_ERROR,
1693 socket_io_error_from_errno (errsv),
1694 _("Error connecting: %s"), socket_strerror (errsv));
1701 win32_unset_event_mask (socket, FD_CONNECT);
1703 socket->priv->connected = TRUE;
1709 * g_socket_check_connect_result:
1710 * @socket: a #GSocket
1711 * @error: #GError for error reporting, or %NULL to ignore.
1713 * Checks and resets the pending connect error for the socket.
1714 * This is used to check for errors when g_socket_connect() is
1715 * used in non-blocking mode.
1717 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
1722 g_socket_check_connect_result (GSocket *socket,
1728 if (!check_socket (socket, error))
1731 optlen = sizeof (value);
1732 if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
1734 int errsv = get_socket_errno ();
1736 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1737 _("Unable to get pending error: %s"), socket_strerror (errsv));
1743 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
1744 socket_strerror (value));
1745 if (socket->priv->remote_address)
1747 g_object_unref (socket->priv->remote_address);
1748 socket->priv->remote_address = NULL;
1753 socket->priv->connected = TRUE;
1759 * @socket: a #GSocket
1760 * @buffer: a buffer to read data into (which should be at least @size
1762 * @size: the number of bytes you want to read from the socket
1763 * @cancellable: (allow-none): a %GCancellable or %NULL
1764 * @error: #GError for error reporting, or %NULL to ignore.
1766 * Receive data (up to @size bytes) from a socket. This is mainly used by
1767 * connection-oriented sockets; it is identical to g_socket_receive_from()
1768 * with @address set to %NULL.
1770 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
1771 * g_socket_receive() will always read either 0 or 1 complete messages from
1772 * the socket. If the received message is too large to fit in @buffer, then
1773 * the data beyond @size bytes will be discarded, without any explicit
1774 * indication that this has occurred.
1776 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
1777 * number of bytes, up to @size. If more than @size bytes have been
1778 * received, the additional data will be returned in future calls to
1779 * g_socket_receive().
1781 * If the socket is in blocking mode the call will block until there
1782 * is some data to receive, the connection is closed, or there is an
1783 * error. If there is no data available and the socket is in
1784 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
1785 * returned. To be notified when data is available, wait for the
1786 * %G_IO_IN condition.
1788 * On error -1 is returned and @error is set accordingly.
1790 * Returns: Number of bytes read, or 0 if the connection was closed by
1791 * the peer, or -1 on error
1796 g_socket_receive (GSocket *socket,
1799 GCancellable *cancellable,
1802 return g_socket_receive_with_blocking (socket, buffer, size,
1803 socket->priv->blocking,
1804 cancellable, error);
1808 * g_socket_receive_with_blocking:
1809 * @socket: a #GSocket
1810 * @buffer: a buffer to read data into (which should be at least @size
1812 * @size: the number of bytes you want to read from the socket
1813 * @blocking: whether to do blocking or non-blocking I/O
1814 * @cancellable: (allow-none): a %GCancellable or %NULL
1815 * @error: #GError for error reporting, or %NULL to ignore.
1817 * This behaves exactly the same as g_socket_receive(), except that
1818 * the choice of blocking or non-blocking behavior is determined by
1819 * the @blocking argument rather than by @socket's properties.
1821 * Returns: Number of bytes read, or 0 if the connection was closed by
1822 * the peer, or -1 on error
1827 g_socket_receive_with_blocking (GSocket *socket,
1831 GCancellable *cancellable,
1836 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1838 if (!check_socket (socket, error))
1841 if (g_cancellable_set_error_if_cancelled (cancellable, error))
1847 !g_socket_condition_wait (socket,
1848 G_IO_IN, cancellable, error))
1851 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
1853 int errsv = get_socket_errno ();
1860 #ifdef WSAEWOULDBLOCK
1861 if (errsv == WSAEWOULDBLOCK)
1864 if (errsv == EWOULDBLOCK ||
1870 win32_unset_event_mask (socket, FD_READ);
1872 g_set_error (error, G_IO_ERROR,
1873 socket_io_error_from_errno (errsv),
1874 _("Error receiving data: %s"), socket_strerror (errsv));
1878 win32_unset_event_mask (socket, FD_READ);
1887 * g_socket_receive_from:
1888 * @socket: a #GSocket
1889 * @address: a pointer to a #GSocketAddress pointer, or %NULL
1890 * @buffer: a buffer to read data into (which should be at least @size
1892 * @size: the number of bytes you want to read from the socket
1893 * @cancellable: (allow-none): a %GCancellable or %NULL
1894 * @error: #GError for error reporting, or %NULL to ignore.
1896 * Receive data (up to @size bytes) from a socket.
1898 * If @address is non-%NULL then @address will be set equal to the
1899 * source address of the received packet.
1900 * @address is owned by the caller.
1902 * See g_socket_receive() for additional information.
1904 * Returns: Number of bytes read, or 0 if the connection was closed by
1905 * the peer, or -1 on error
1910 g_socket_receive_from (GSocket *socket,
1911 GSocketAddress **address,
1914 GCancellable *cancellable,
1922 return g_socket_receive_message (socket,
1930 /* Although we ignore SIGPIPE, gdb will still stop if the app receives
1931 * one, which can be confusing and annoying. So if possible, we want
1932 * to suppress the signal entirely.
1935 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
1937 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
1942 * @socket: a #GSocket
1943 * @buffer: (array length=size): the buffer containing the data to send.
1944 * @size: the number of bytes to send
1945 * @cancellable: (allow-none): a %GCancellable or %NULL
1946 * @error: #GError for error reporting, or %NULL to ignore.
1948 * Tries to send @size bytes from @buffer on the socket. This is
1949 * mainly used by connection-oriented sockets; it is identical to
1950 * g_socket_send_to() with @address set to %NULL.
1952 * If the socket is in blocking mode the call will block until there is
1953 * space for the data in the socket queue. If there is no space available
1954 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1955 * will be returned. To be notified when space is available, wait for the
1956 * %G_IO_OUT condition. Note though that you may still receive
1957 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
1958 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
1959 * very common due to the way the underlying APIs work.)
1961 * On error -1 is returned and @error is set accordingly.
1963 * Returns: Number of bytes written (which may be less than @size), or -1
1969 g_socket_send (GSocket *socket,
1970 const gchar *buffer,
1972 GCancellable *cancellable,
1975 return g_socket_send_with_blocking (socket, buffer, size,
1976 socket->priv->blocking,
1977 cancellable, error);
1981 * g_socket_send_with_blocking:
1982 * @socket: a #GSocket
1983 * @buffer: (array length=size): the buffer containing the data to send.
1984 * @size: the number of bytes to send
1985 * @blocking: whether to do blocking or non-blocking I/O
1986 * @cancellable: (allow-none): a %GCancellable or %NULL
1987 * @error: #GError for error reporting, or %NULL to ignore.
1989 * This behaves exactly the same as g_socket_send(), except that
1990 * the choice of blocking or non-blocking behavior is determined by
1991 * the @blocking argument rather than by @socket's properties.
1993 * Returns: Number of bytes written (which may be less than @size), or -1
1999 g_socket_send_with_blocking (GSocket *socket,
2000 const gchar *buffer,
2003 GCancellable *cancellable,
2008 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
2010 if (!check_socket (socket, error))
2013 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2019 !g_socket_condition_wait (socket,
2020 G_IO_OUT, cancellable, error))
2023 if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
2025 int errsv = get_socket_errno ();
2030 #ifdef WSAEWOULDBLOCK
2031 if (errsv == WSAEWOULDBLOCK)
2032 win32_unset_event_mask (socket, FD_WRITE);
2037 #ifdef WSAEWOULDBLOCK
2038 if (errsv == WSAEWOULDBLOCK)
2041 if (errsv == EWOULDBLOCK ||
2047 g_set_error (error, G_IO_ERROR,
2048 socket_io_error_from_errno (errsv),
2049 _("Error sending data: %s"), socket_strerror (errsv));
2060 * @socket: a #GSocket
2061 * @address: a #GSocketAddress, or %NULL
2062 * @buffer: (array length=size): the buffer containing the data to send.
2063 * @size: the number of bytes to send
2064 * @cancellable: (allow-none): a %GCancellable or %NULL
2065 * @error: #GError for error reporting, or %NULL to ignore.
2067 * Tries to send @size bytes from @buffer to @address. If @address is
2068 * %NULL then the message is sent to the default receiver (set by
2069 * g_socket_connect()).
2071 * See g_socket_send() for additional information.
2073 * Returns: Number of bytes written (which may be less than @size), or -1
2079 g_socket_send_to (GSocket *socket,
2080 GSocketAddress *address,
2081 const gchar *buffer,
2083 GCancellable *cancellable,
2091 return g_socket_send_message (socket,
2101 * g_socket_shutdown:
2102 * @socket: a #GSocket
2103 * @shutdown_read: whether to shut down the read side
2104 * @shutdown_write: whether to shut down the write side
2105 * @error: #GError for error reporting, or %NULL to ignore.
2107 * Shut down part of a full-duplex connection.
2109 * If @shutdown_read is %TRUE then the receiving side of the connection
2110 * is shut down, and further reading is disallowed.
2112 * If @shutdown_write is %TRUE then the sending side of the connection
2113 * is shut down, and further writing is disallowed.
2115 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
2117 * One example where this is used is graceful disconnect for TCP connections
2118 * where you close the sending side, then wait for the other side to close
2119 * the connection, thus ensuring that the other side saw all sent data.
2121 * Returns: %TRUE on success, %FALSE on error
2126 g_socket_shutdown (GSocket *socket,
2127 gboolean shutdown_read,
2128 gboolean shutdown_write,
2133 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2135 if (!check_socket (socket, error))
2139 if (!shutdown_read && !shutdown_write)
2143 if (shutdown_read && shutdown_write)
2145 else if (shutdown_read)
2150 if (shutdown_read && shutdown_write)
2152 else if (shutdown_read)
2158 if (shutdown (socket->priv->fd, how) != 0)
2160 int errsv = get_socket_errno ();
2161 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2162 _("Unable to shutdown socket: %s"), socket_strerror (errsv));
2166 if (shutdown_read && shutdown_write)
2167 socket->priv->connected = FALSE;
2174 * @socket: a #GSocket
2175 * @error: #GError for error reporting, or %NULL to ignore.
2177 * Closes the socket, shutting down any active connection.
2179 * Closing a socket does not wait for all outstanding I/O operations
2180 * to finish, so the caller should not rely on them to be guaranteed
2181 * to complete even if the close returns with no error.
2183 * Once the socket is closed, all other operations will return
2184 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
2187 * Sockets will be automatically closed when the last reference
2188 * is dropped, but you might want to call this function to make sure
2189 * resources are released as early as possible.
2191 * Beware that due to the way that TCP works, it is possible for
2192 * recently-sent data to be lost if either you close a socket while the
2193 * %G_IO_IN condition is set, or else if the remote connection tries to
2194 * send something to you after you close the socket but before it has
2195 * finished reading all of the data you sent. There is no easy generic
2196 * way to avoid this problem; the easiest fix is to design the network
2197 * protocol such that the client will never send data "out of turn".
2198 * Another solution is for the server to half-close the connection by
2199 * calling g_socket_shutdown() with only the @shutdown_write flag set,
2200 * and then wait for the client to notice this and close its side of the
2201 * connection, after which the server can safely call g_socket_close().
2202 * (This is what #GTcpConnection does if you call
2203 * g_tcp_connection_set_graceful_disconnect(). But of course, this
2204 * only works if the client will close its connection after the server
2207 * Returns: %TRUE on success, %FALSE on error
2212 g_socket_close (GSocket *socket,
2217 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2219 if (socket->priv->closed)
2220 return TRUE; /* Multiple close not an error */
2222 if (!check_socket (socket, error))
2228 res = closesocket (socket->priv->fd);
2230 res = close (socket->priv->fd);
2234 int errsv = get_socket_errno ();
2239 g_set_error (error, G_IO_ERROR,
2240 socket_io_error_from_errno (errsv),
2241 _("Error closing socket: %s"),
2242 socket_strerror (errsv));
2248 socket->priv->connected = FALSE;
2249 socket->priv->closed = TRUE;
2250 if (socket->priv->remote_address)
2252 g_object_unref (socket->priv->remote_address);
2253 socket->priv->remote_address = NULL;
2260 * g_socket_is_closed:
2261 * @socket: a #GSocket
2263 * Checks whether a socket is closed.
2265 * Returns: %TRUE if socket is closed, %FALSE otherwise
2270 g_socket_is_closed (GSocket *socket)
2272 return socket->priv->closed;
2276 /* Broken source, used on errors */
2278 broken_prepare (GSource *source,
2285 broken_check (GSource *source)
2291 broken_dispatch (GSource *source,
2292 GSourceFunc callback,
2298 static GSourceFuncs broken_funcs =
2307 network_events_for_condition (GIOCondition condition)
2311 if (condition & G_IO_IN)
2312 event_mask |= (FD_READ | FD_ACCEPT);
2313 if (condition & G_IO_OUT)
2314 event_mask |= (FD_WRITE | FD_CONNECT);
2315 event_mask |= FD_CLOSE;
2321 ensure_event (GSocket *socket)
2323 if (socket->priv->event == WSA_INVALID_EVENT)
2324 socket->priv->event = WSACreateEvent();
2328 update_select_events (GSocket *socket)
2335 ensure_event (socket);
2338 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
2341 event_mask |= network_events_for_condition (*ptr);
2344 if (event_mask != socket->priv->selected_events)
2346 /* If no events selected, disable event so we can unset
2349 if (event_mask == 0)
2352 event = socket->priv->event;
2354 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
2355 socket->priv->selected_events = event_mask;
2360 add_condition_watch (GSocket *socket,
2361 GIOCondition *condition)
2363 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
2365 socket->priv->requested_conditions =
2366 g_list_prepend (socket->priv->requested_conditions, condition);
2368 update_select_events (socket);
2372 remove_condition_watch (GSocket *socket,
2373 GIOCondition *condition)
2375 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
2377 socket->priv->requested_conditions =
2378 g_list_remove (socket->priv->requested_conditions, condition);
2380 update_select_events (socket);
2384 update_condition (GSocket *socket)
2386 WSANETWORKEVENTS events;
2387 GIOCondition condition;
2389 if (WSAEnumNetworkEvents (socket->priv->fd,
2390 socket->priv->event,
2393 socket->priv->current_events |= events.lNetworkEvents;
2394 if (events.lNetworkEvents & FD_WRITE &&
2395 events.iErrorCode[FD_WRITE_BIT] != 0)
2396 socket->priv->current_errors |= FD_WRITE;
2397 if (events.lNetworkEvents & FD_CONNECT &&
2398 events.iErrorCode[FD_CONNECT_BIT] != 0)
2399 socket->priv->current_errors |= FD_CONNECT;
2403 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
2404 condition |= G_IO_IN;
2406 if (socket->priv->current_events & FD_CLOSE ||
2407 socket->priv->closed)
2408 condition |= G_IO_HUP;
2410 /* Never report both G_IO_OUT and HUP, these are
2411 mutually exclusive (can't write to a closed socket) */
2412 if ((condition & G_IO_HUP) == 0 &&
2413 socket->priv->current_events & FD_WRITE)
2415 if (socket->priv->current_errors & FD_WRITE)
2416 condition |= G_IO_ERR;
2418 condition |= G_IO_OUT;
2422 if (socket->priv->current_events & FD_CONNECT)
2424 if (socket->priv->current_errors & FD_CONNECT)
2425 condition |= (G_IO_HUP | G_IO_ERR);
2427 condition |= G_IO_OUT;
2439 GIOCondition condition;
2440 GCancellable *cancellable;
2441 GPollFD cancel_pollfd;
2442 gint64 timeout_time;
2446 socket_source_prepare (GSource *source,
2449 GSocketSource *socket_source = (GSocketSource *)source;
2451 if (g_cancellable_is_cancelled (socket_source->cancellable))
2454 if (socket_source->timeout_time)
2458 now = g_source_get_time (source);
2459 /* Round up to ensure that we don't try again too early */
2460 *timeout = (socket_source->timeout_time - now + 999) / 1000;
2463 socket_source->socket->priv->timed_out = TRUE;
2472 socket_source->pollfd.revents = update_condition (socket_source->socket);
2475 if ((socket_source->condition & socket_source->pollfd.revents) != 0)
2482 socket_source_check (GSource *source)
2486 return socket_source_prepare (source, &timeout);
2490 socket_source_dispatch (GSource *source,
2491 GSourceFunc callback,
2494 GSocketSourceFunc func = (GSocketSourceFunc)callback;
2495 GSocketSource *socket_source = (GSocketSource *)source;
2498 socket_source->pollfd.revents = update_condition (socket_source->socket);
2500 if (socket_source->socket->priv->timed_out)
2501 socket_source->pollfd.revents |= socket_source->condition & (G_IO_IN | G_IO_OUT);
2503 return (*func) (socket_source->socket,
2504 socket_source->pollfd.revents & socket_source->condition,
2509 socket_source_finalize (GSource *source)
2511 GSocketSource *socket_source = (GSocketSource *)source;
2514 socket = socket_source->socket;
2517 remove_condition_watch (socket, &socket_source->condition);
2520 g_object_unref (socket);
2522 if (socket_source->cancellable)
2524 g_cancellable_release_fd (socket_source->cancellable);
2525 g_object_unref (socket_source->cancellable);
2530 socket_source_closure_callback (GSocket *socket,
2531 GIOCondition condition,
2534 GClosure *closure = data;
2536 GValue params[2] = { { 0, }, { 0, } };
2537 GValue result_value = { 0, };
2540 g_value_init (&result_value, G_TYPE_BOOLEAN);
2542 g_value_init (¶ms[0], G_TYPE_SOCKET);
2543 g_value_set_object (¶ms[0], socket);
2544 g_value_init (¶ms[1], G_TYPE_IO_CONDITION);
2545 g_value_set_flags (¶ms[1], condition);
2547 g_closure_invoke (closure, &result_value, 2, params, NULL);
2549 result = g_value_get_boolean (&result_value);
2550 g_value_unset (&result_value);
2551 g_value_unset (¶ms[0]);
2552 g_value_unset (¶ms[1]);
2557 static GSourceFuncs socket_source_funcs =
2559 socket_source_prepare,
2560 socket_source_check,
2561 socket_source_dispatch,
2562 socket_source_finalize,
2563 (GSourceFunc)socket_source_closure_callback,
2564 (GSourceDummyMarshal)g_cclosure_marshal_generic,
2568 socket_source_new (GSocket *socket,
2569 GIOCondition condition,
2570 GCancellable *cancellable)
2573 GSocketSource *socket_source;
2576 ensure_event (socket);
2578 if (socket->priv->event == WSA_INVALID_EVENT)
2580 g_warning ("Failed to create WSAEvent");
2581 return g_source_new (&broken_funcs, sizeof (GSource));
2585 condition |= G_IO_HUP | G_IO_ERR;
2587 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
2588 g_source_set_name (source, "GSocket");
2589 socket_source = (GSocketSource *)source;
2591 socket_source->socket = g_object_ref (socket);
2592 socket_source->condition = condition;
2594 if (g_cancellable_make_pollfd (cancellable,
2595 &socket_source->cancel_pollfd))
2597 socket_source->cancellable = g_object_ref (cancellable);
2598 g_source_add_poll (source, &socket_source->cancel_pollfd);
2602 add_condition_watch (socket, &socket_source->condition);
2603 socket_source->pollfd.fd = (gintptr) socket->priv->event;
2605 socket_source->pollfd.fd = socket->priv->fd;
2608 socket_source->pollfd.events = condition;
2609 socket_source->pollfd.revents = 0;
2610 g_source_add_poll (source, &socket_source->pollfd);
2612 if (socket->priv->timeout)
2613 socket_source->timeout_time = g_get_monotonic_time () +
2614 socket->priv->timeout * 1000000;
2617 socket_source->timeout_time = 0;
2623 * g_socket_create_source: (skip)
2624 * @socket: a #GSocket
2625 * @condition: a #GIOCondition mask to monitor
2626 * @cancellable: (allow-none): a %GCancellable or %NULL
2628 * Creates a %GSource that can be attached to a %GMainContext to monitor
2629 * for the availibility of the specified @condition on the socket.
2631 * The callback on the source is of the #GSocketSourceFunc type.
2633 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
2634 * these conditions will always be reported output if they are true.
2636 * @cancellable if not %NULL can be used to cancel the source, which will
2637 * cause the source to trigger, reporting the current condition (which
2638 * is likely 0 unless cancellation happened at the same time as a
2639 * condition change). You can check for this in the callback using
2640 * g_cancellable_is_cancelled().
2642 * If @socket has a timeout set, and it is reached before @condition
2643 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
2644 * %G_IO_OUT depending on @condition. However, @socket will have been
2645 * marked as having had a timeout, and so the next #GSocket I/O method
2646 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
2648 * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
2653 g_socket_create_source (GSocket *socket,
2654 GIOCondition condition,
2655 GCancellable *cancellable)
2657 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
2659 return socket_source_new (socket, condition, cancellable);
2663 * g_socket_condition_check:
2664 * @socket: a #GSocket
2665 * @condition: a #GIOCondition mask to check
2667 * Checks on the readiness of @socket to perform operations.
2668 * The operations specified in @condition are checked for and masked
2669 * against the currently-satisfied conditions on @socket. The result
2672 * Note that on Windows, it is possible for an operation to return
2673 * %G_IO_ERROR_WOULD_BLOCK even immediately after
2674 * g_socket_condition_check() has claimed that the socket is ready for
2675 * writing. Rather than calling g_socket_condition_check() and then
2676 * writing to the socket if it succeeds, it is generally better to
2677 * simply try writing to the socket right away, and try again later if
2678 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
2680 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2681 * these conditions will always be set in the output if they are true.
2683 * This call never blocks.
2685 * Returns: the @GIOCondition mask of the current state
2690 g_socket_condition_check (GSocket *socket,
2691 GIOCondition condition)
2693 if (!check_socket (socket, NULL))
2698 GIOCondition current_condition;
2700 condition |= G_IO_ERR | G_IO_HUP;
2702 add_condition_watch (socket, &condition);
2703 current_condition = update_condition (socket);
2704 remove_condition_watch (socket, &condition);
2705 return condition & current_condition;
2711 poll_fd.fd = socket->priv->fd;
2712 poll_fd.events = condition;
2715 result = g_poll (&poll_fd, 1, 0);
2716 while (result == -1 && get_socket_errno () == EINTR);
2718 return poll_fd.revents;
2724 * g_socket_condition_wait:
2725 * @socket: a #GSocket
2726 * @condition: a #GIOCondition mask to wait for
2727 * @cancellable: (allow-none): a #GCancellable, or %NULL
2728 * @error: a #GError pointer, or %NULL
2730 * Waits for @condition to become true on @socket. When the condition
2731 * is met, %TRUE is returned.
2733 * If @cancellable is cancelled before the condition is met, or if the
2734 * socket has a timeout set and it is reached before the condition is
2735 * met, then %FALSE is returned and @error, if non-%NULL, is set to
2736 * the appropriate value (%G_IO_ERROR_CANCELLED or
2737 * %G_IO_ERROR_TIMED_OUT).
2739 * Returns: %TRUE if the condition was met, %FALSE otherwise
2744 g_socket_condition_wait (GSocket *socket,
2745 GIOCondition condition,
2746 GCancellable *cancellable,
2749 if (!check_socket (socket, error))
2752 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2757 GIOCondition current_condition;
2763 /* Always check these */
2764 condition |= G_IO_ERR | G_IO_HUP;
2766 add_condition_watch (socket, &condition);
2769 events[num_events++] = socket->priv->event;
2771 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
2772 events[num_events++] = (WSAEVENT)cancel_fd.fd;
2774 if (socket->priv->timeout)
2775 timeout = socket->priv->timeout * 1000;
2777 timeout = WSA_INFINITE;
2779 current_condition = update_condition (socket);
2780 while ((condition & current_condition) == 0)
2782 res = WSAWaitForMultipleEvents(num_events, events,
2783 FALSE, timeout, FALSE);
2784 if (res == WSA_WAIT_FAILED)
2786 int errsv = get_socket_errno ();
2788 g_set_error (error, G_IO_ERROR,
2789 socket_io_error_from_errno (errsv),
2790 _("Waiting for socket condition: %s"),
2791 socket_strerror (errsv));
2794 else if (res == WSA_WAIT_TIMEOUT)
2796 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
2797 _("Socket I/O timed out"));
2801 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2804 current_condition = update_condition (socket);
2806 remove_condition_watch (socket, &condition);
2808 g_cancellable_release_fd (cancellable);
2810 return (condition & current_condition) != 0;
2819 poll_fd[0].fd = socket->priv->fd;
2820 poll_fd[0].events = condition;
2823 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
2826 if (socket->priv->timeout)
2827 timeout = socket->priv->timeout * 1000;
2832 result = g_poll (poll_fd, num, timeout);
2833 while (result == -1 && get_socket_errno () == EINTR);
2836 g_cancellable_release_fd (cancellable);
2840 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
2841 _("Socket I/O timed out"));
2845 return !g_cancellable_set_error_if_cancelled (cancellable, error);
2851 * g_socket_send_message:
2852 * @socket: a #GSocket
2853 * @address: a #GSocketAddress, or %NULL
2854 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
2855 * @num_vectors: the number of elements in @vectors, or -1
2856 * @messages: (array length=num_messages) (allow-none): a pointer to an
2857 * array of #GSocketControlMessages, or %NULL.
2858 * @num_messages: number of elements in @messages, or -1.
2859 * @flags: an int containing #GSocketMsgFlags flags
2860 * @cancellable: (allow-none): a %GCancellable or %NULL
2861 * @error: #GError for error reporting, or %NULL to ignore.
2863 * Send data to @address on @socket. This is the most complicated and
2864 * fully-featured version of this call. For easier use, see
2865 * g_socket_send() and g_socket_send_to().
2867 * If @address is %NULL then the message is sent to the default receiver
2868 * (set by g_socket_connect()).
2870 * @vectors must point to an array of #GOutputVector structs and
2871 * @num_vectors must be the length of this array. (If @num_vectors is -1,
2872 * then @vectors is assumed to be terminated by a #GOutputVector with a
2873 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
2874 * that the sent data will be gathered from. Using multiple
2875 * #GOutputVector<!-- -->s is more memory-efficient than manually copying
2876 * data from multiple sources into a single buffer, and more
2877 * network-efficient than making multiple calls to g_socket_send().
2879 * @messages, if non-%NULL, is taken to point to an array of @num_messages
2880 * #GSocketControlMessage instances. These correspond to the control
2881 * messages to be sent on the socket.
2882 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
2885 * @flags modify how the message is sent. The commonly available arguments
2886 * for this are available in the #GSocketMsgFlags enum, but the
2887 * values there are the same as the system values, and the flags
2888 * are passed in as-is, so you can pass in system-specific flags too.
2890 * If the socket is in blocking mode the call will block until there is
2891 * space for the data in the socket queue. If there is no space available
2892 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2893 * will be returned. To be notified when space is available, wait for the
2894 * %G_IO_OUT condition. Note though that you may still receive
2895 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2896 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2897 * very common due to the way the underlying APIs work.)
2899 * On error -1 is returned and @error is set accordingly.
2901 * Returns: Number of bytes written (which may be less than @size), or -1
2907 g_socket_send_message (GSocket *socket,
2908 GSocketAddress *address,
2909 GOutputVector *vectors,
2911 GSocketControlMessage **messages,
2914 GCancellable *cancellable,
2917 GOutputVector one_vector;
2920 if (!check_socket (socket, error))
2923 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2926 if (num_vectors == -1)
2928 for (num_vectors = 0;
2929 vectors[num_vectors].buffer != NULL;
2934 if (num_messages == -1)
2936 for (num_messages = 0;
2937 messages != NULL && messages[num_messages] != NULL;
2942 if (num_vectors == 0)
2946 one_vector.buffer = &zero;
2947 one_vector.size = 1;
2949 vectors = &one_vector;
2962 msg.msg_namelen = g_socket_address_get_native_size (address);
2963 msg.msg_name = g_alloca (msg.msg_namelen);
2964 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
2969 msg.msg_name = NULL;
2970 msg.msg_namelen = 0;
2975 /* this entire expression will be evaluated at compile time */
2976 if (sizeof *msg.msg_iov == sizeof *vectors &&
2977 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2978 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2979 G_STRUCT_OFFSET (GOutputVector, buffer) &&
2980 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2981 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2982 G_STRUCT_OFFSET (GOutputVector, size))
2983 /* ABI is compatible */
2985 msg.msg_iov = (struct iovec *) vectors;
2986 msg.msg_iovlen = num_vectors;
2989 /* ABI is incompatible */
2993 msg.msg_iov = g_newa (struct iovec, num_vectors);
2994 for (i = 0; i < num_vectors; i++)
2996 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
2997 msg.msg_iov[i].iov_len = vectors[i].size;
2999 msg.msg_iovlen = num_vectors;
3005 struct cmsghdr *cmsg;
3008 msg.msg_controllen = 0;
3009 for (i = 0; i < num_messages; i++)
3010 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
3012 if (msg.msg_controllen == 0)
3013 msg.msg_control = NULL;
3016 msg.msg_control = g_alloca (msg.msg_controllen);
3017 memset (msg.msg_control, '\0', msg.msg_controllen);
3020 cmsg = CMSG_FIRSTHDR (&msg);
3021 for (i = 0; i < num_messages; i++)
3023 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
3024 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
3025 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
3026 g_socket_control_message_serialize (messages[i],
3028 cmsg = CMSG_NXTHDR (&msg, cmsg);
3030 g_assert (cmsg == NULL);
3035 if (socket->priv->blocking &&
3036 !g_socket_condition_wait (socket,
3037 G_IO_OUT, cancellable, error))
3040 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
3043 int errsv = get_socket_errno ();
3048 if (socket->priv->blocking &&
3049 (errsv == EWOULDBLOCK ||
3053 g_set_error (error, G_IO_ERROR,
3054 socket_io_error_from_errno (errsv),
3055 _("Error sending message: %s"), socket_strerror (errsv));
3066 struct sockaddr_storage addr;
3073 /* Win32 doesn't support control messages.
3074 Actually this is possible for raw and datagram sockets
3075 via WSASendMessage on Vista or later, but that doesn't
3077 if (num_messages != 0)
3079 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
3080 _("GSocketControlMessage not supported on windows"));
3085 bufs = g_newa (WSABUF, num_vectors);
3086 for (i = 0; i < num_vectors; i++)
3088 bufs[i].buf = (char *)vectors[i].buffer;
3089 bufs[i].len = (gulong)vectors[i].size;
3093 addrlen = 0; /* Avoid warning */
3096 addrlen = g_socket_address_get_native_size (address);
3097 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
3103 if (socket->priv->blocking &&
3104 !g_socket_condition_wait (socket,
3105 G_IO_OUT, cancellable, error))
3109 result = WSASendTo (socket->priv->fd,
3112 (const struct sockaddr *)&addr, addrlen,
3115 result = WSASend (socket->priv->fd,
3122 int errsv = get_socket_errno ();
3124 if (errsv == WSAEINTR)
3127 if (errsv == WSAEWOULDBLOCK)
3128 win32_unset_event_mask (socket, FD_WRITE);
3130 if (socket->priv->blocking &&
3131 errsv == WSAEWOULDBLOCK)
3134 g_set_error (error, G_IO_ERROR,
3135 socket_io_error_from_errno (errsv),
3136 _("Error sending message: %s"), socket_strerror (errsv));
3149 * g_socket_receive_message:
3150 * @socket: a #GSocket
3151 * @address: a pointer to a #GSocketAddress pointer, or %NULL
3152 * @vectors: (array length=num_vectors): an array of #GInputVector structs
3153 * @num_vectors: the number of elements in @vectors, or -1
3154 * @messages: (array length=num_messages) (allow-none): a pointer which
3155 * may be filled with an array of #GSocketControlMessages, or %NULL
3156 * @num_messages: a pointer which will be filled with the number of
3157 * elements in @messages, or %NULL
3158 * @flags: a pointer to an int containing #GSocketMsgFlags flags
3159 * @cancellable: (allow-none): a %GCancellable or %NULL
3160 * @error: a #GError pointer, or %NULL
3162 * Receive data from a socket. This is the most complicated and
3163 * fully-featured version of this call. For easier use, see
3164 * g_socket_receive() and g_socket_receive_from().
3166 * If @address is non-%NULL then @address will be set equal to the
3167 * source address of the received packet.
3168 * @address is owned by the caller.
3170 * @vector must point to an array of #GInputVector structs and
3171 * @num_vectors must be the length of this array. These structs
3172 * describe the buffers that received data will be scattered into.
3173 * If @num_vectors is -1, then @vectors is assumed to be terminated
3174 * by a #GInputVector with a %NULL buffer pointer.
3176 * As a special case, if @num_vectors is 0 (in which case, @vectors
3177 * may of course be %NULL), then a single byte is received and
3178 * discarded. This is to facilitate the common practice of sending a
3179 * single '\0' byte for the purposes of transferring ancillary data.
3181 * @messages, if non-%NULL, will be set to point to a newly-allocated
3182 * array of #GSocketControlMessage instances or %NULL if no such
3183 * messages was received. These correspond to the control messages
3184 * received from the kernel, one #GSocketControlMessage per message
3185 * from the kernel. This array is %NULL-terminated and must be freed
3186 * by the caller using g_free() after calling g_object_unref() on each
3187 * element. If @messages is %NULL, any control messages received will
3190 * @num_messages, if non-%NULL, will be set to the number of control
3191 * messages received.
3193 * If both @messages and @num_messages are non-%NULL, then
3194 * @num_messages gives the number of #GSocketControlMessage instances
3195 * in @messages (ie: not including the %NULL terminator).
3197 * @flags is an in/out parameter. The commonly available arguments
3198 * for this are available in the #GSocketMsgFlags enum, but the
3199 * values there are the same as the system values, and the flags
3200 * are passed in as-is, so you can pass in system-specific flags too
3201 * (and g_socket_receive_message() may pass system-specific flags out).
3203 * As with g_socket_receive(), data may be discarded if @socket is
3204 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
3205 * provide enough buffer space to read a complete message. You can pass
3206 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
3207 * removing it from the receive queue, but there is no portable way to find
3208 * out the length of the message other than by reading it into a
3209 * sufficiently-large buffer.
3211 * If the socket is in blocking mode the call will block until there
3212 * is some data to receive, the connection is closed, or there is an
3213 * error. If there is no data available and the socket is in
3214 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
3215 * returned. To be notified when data is available, wait for the
3216 * %G_IO_IN condition.
3218 * On error -1 is returned and @error is set accordingly.
3220 * Returns: Number of bytes read, or 0 if the connection was closed by
3221 * the peer, or -1 on error
3226 g_socket_receive_message (GSocket *socket,
3227 GSocketAddress **address,
3228 GInputVector *vectors,
3230 GSocketControlMessage ***messages,
3233 GCancellable *cancellable,
3236 GInputVector one_vector;
3239 if (!check_socket (socket, error))
3242 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3245 if (num_vectors == -1)
3247 for (num_vectors = 0;
3248 vectors[num_vectors].buffer != NULL;
3253 if (num_vectors == 0)
3255 one_vector.buffer = &one_byte;
3256 one_vector.size = 1;
3258 vectors = &one_vector;
3265 struct sockaddr_storage one_sockaddr;
3270 msg.msg_name = &one_sockaddr;
3271 msg.msg_namelen = sizeof (struct sockaddr_storage);
3275 msg.msg_name = NULL;
3276 msg.msg_namelen = 0;
3280 /* this entire expression will be evaluated at compile time */
3281 if (sizeof *msg.msg_iov == sizeof *vectors &&
3282 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3283 G_STRUCT_OFFSET (struct iovec, iov_base) ==
3284 G_STRUCT_OFFSET (GInputVector, buffer) &&
3285 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3286 G_STRUCT_OFFSET (struct iovec, iov_len) ==
3287 G_STRUCT_OFFSET (GInputVector, size))
3288 /* ABI is compatible */
3290 msg.msg_iov = (struct iovec *) vectors;
3291 msg.msg_iovlen = num_vectors;
3294 /* ABI is incompatible */
3298 msg.msg_iov = g_newa (struct iovec, num_vectors);
3299 for (i = 0; i < num_vectors; i++)
3301 msg.msg_iov[i].iov_base = vectors[i].buffer;
3302 msg.msg_iov[i].iov_len = vectors[i].size;
3304 msg.msg_iovlen = num_vectors;
3308 msg.msg_control = g_alloca (2048);
3309 msg.msg_controllen = 2048;
3313 msg.msg_flags = *flags;
3317 /* We always set the close-on-exec flag so we don't leak file
3318 * descriptors into child processes. Note that gunixfdmessage.c
3319 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
3321 #ifdef MSG_CMSG_CLOEXEC
3322 msg.msg_flags |= MSG_CMSG_CLOEXEC;
3328 if (socket->priv->blocking &&
3329 !g_socket_condition_wait (socket,
3330 G_IO_IN, cancellable, error))
3333 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
3334 #ifdef MSG_CMSG_CLOEXEC
3335 if (result < 0 && get_socket_errno () == EINVAL)
3337 /* We must be running on an old kernel. Call without the flag. */
3338 msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
3339 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
3345 int errsv = get_socket_errno ();
3350 if (socket->priv->blocking &&
3351 (errsv == EWOULDBLOCK ||
3355 g_set_error (error, G_IO_ERROR,
3356 socket_io_error_from_errno (errsv),
3357 _("Error receiving message: %s"), socket_strerror (errsv));
3364 /* decode address */
3365 if (address != NULL)
3367 if (msg.msg_namelen > 0)
3368 *address = g_socket_address_new_from_native (msg.msg_name,
3374 /* decode control messages */
3376 GPtrArray *my_messages = NULL;
3377 struct cmsghdr *cmsg;
3379 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
3381 GSocketControlMessage *message;
3383 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
3385 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
3387 if (message == NULL)
3388 /* We've already spewed about the problem in the
3389 deserialization code, so just continue */
3392 if (messages == NULL)
3394 /* we have to do it this way if the user ignores the
3395 * messages so that we will close any received fds.
3397 g_object_unref (message);
3401 if (my_messages == NULL)
3402 my_messages = g_ptr_array_new ();
3403 g_ptr_array_add (my_messages, message);
3408 *num_messages = my_messages != NULL ? my_messages->len : 0;
3412 if (my_messages == NULL)
3418 g_ptr_array_add (my_messages, NULL);
3419 *messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
3424 g_assert (my_messages == NULL);
3428 /* capture the flags */
3430 *flags = msg.msg_flags;
3436 struct sockaddr_storage addr;
3438 DWORD bytes_received;
3445 bufs = g_newa (WSABUF, num_vectors);
3446 for (i = 0; i < num_vectors; i++)
3448 bufs[i].buf = (char *)vectors[i].buffer;
3449 bufs[i].len = (gulong)vectors[i].size;
3461 if (socket->priv->blocking &&
3462 !g_socket_condition_wait (socket,
3463 G_IO_IN, cancellable, error))
3466 addrlen = sizeof addr;
3468 result = WSARecvFrom (socket->priv->fd,
3470 &bytes_received, &win_flags,
3471 (struct sockaddr *)&addr, &addrlen,
3474 result = WSARecv (socket->priv->fd,
3476 &bytes_received, &win_flags,
3480 int errsv = get_socket_errno ();
3482 if (errsv == WSAEINTR)
3485 win32_unset_event_mask (socket, FD_READ);
3487 if (socket->priv->blocking &&
3488 errsv == WSAEWOULDBLOCK)
3491 g_set_error (error, G_IO_ERROR,
3492 socket_io_error_from_errno (errsv),
3493 _("Error receiving message: %s"), socket_strerror (errsv));
3497 win32_unset_event_mask (socket, FD_READ);
3501 /* decode address */
3502 if (address != NULL)
3505 *address = g_socket_address_new_from_native (&addr, addrlen);
3510 /* capture the flags */
3514 if (messages != NULL)
3516 if (num_messages != NULL)
3519 return bytes_received;
3525 * g_socket_get_credentials:
3526 * @socket: a #GSocket.
3527 * @error: #GError for error reporting, or %NULL to ignore.
3529 * Returns the credentials of the foreign process connected to this
3530 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
3533 * If this operation isn't supported on the OS, the method fails with
3534 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
3535 * by reading the %SO_PEERCRED option on the underlying socket.
3537 * Other ways to obtain credentials from a foreign peer includes the
3538 * #GUnixCredentialsMessage type and
3539 * g_unix_connection_send_credentials() /
3540 * g_unix_connection_receive_credentials() functions.
3542 * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
3543 * that must be freed with g_object_unref().
3548 g_socket_get_credentials (GSocket *socket,
3553 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
3554 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3558 #if defined(__linux__) || defined(__OpenBSD__)
3561 #if defined(__linux__)
3562 struct ucred native_creds;
3563 optlen = sizeof (struct ucred);
3564 #elif defined(__OpenBSD__)
3565 struct sockpeercred native_creds;
3566 optlen = sizeof (struct sockpeercred);
3568 if (getsockopt (socket->priv->fd,
3571 (void *)&native_creds,
3574 int errsv = get_socket_errno ();
3577 socket_io_error_from_errno (errsv),
3578 _("Unable to get pending error: %s"),
3579 socket_strerror (errsv));
3583 ret = g_credentials_new ();
3584 g_credentials_set_native (ret,
3585 #if defined(__linux__)
3586 G_CREDENTIALS_TYPE_LINUX_UCRED,
3587 #elif defined(__OpenBSD__)
3588 G_CREDENTIALS_TYPE_OPENBSD_SOCKPEERCRED,
3594 g_set_error_literal (error,
3596 G_IO_ERROR_NOT_SUPPORTED,
3597 _("g_socket_get_credentials not implemented for this OS"));