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);
223 msg = g_win32_error_message (err);
225 msg_ret = g_intern_string (msg);
233 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
235 _win32_unset_event_mask (GSocket *socket, int mask)
237 socket->priv->current_events &= ~mask;
238 socket->priv->current_errors &= ~mask;
241 #define win32_unset_event_mask(_socket, _mask)
245 set_fd_nonblocking (int fd)
248 GError *error = NULL;
254 if (!g_unix_set_fd_nonblocking (fd, TRUE, &error))
256 g_warning ("Error setting socket nonblocking: %s", error->message);
257 g_clear_error (&error);
262 if (ioctlsocket (fd, FIONBIO, &arg) == SOCKET_ERROR)
264 int errsv = get_socket_errno ();
265 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
271 check_socket (GSocket *socket,
274 if (!socket->priv->inited)
276 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
277 _("Invalid socket, not initialized"));
281 if (socket->priv->construct_error)
283 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
284 _("Invalid socket, initialization failed due to: %s"),
285 socket->priv->construct_error->message);
289 if (socket->priv->closed)
291 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
292 _("Socket is already closed"));
296 if (socket->priv->timed_out)
298 socket->priv->timed_out = FALSE;
299 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
300 _("Socket I/O timed out"));
308 g_socket_details_from_fd (GSocket *socket)
310 struct sockaddr_storage address;
317 /* See bug #611756 */
318 BOOL bool_val = FALSE;
323 fd = socket->priv->fd;
324 optlen = sizeof value;
325 if (getsockopt (fd, SOL_SOCKET, SO_TYPE, (void *)&value, &optlen) != 0)
327 errsv = get_socket_errno ();
338 /* programmer error */
339 g_error ("creating GSocket from fd %d: %s\n",
340 fd, socket_strerror (errsv));
348 g_assert (optlen == sizeof value);
352 socket->priv->type = G_SOCKET_TYPE_STREAM;
356 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
360 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
364 socket->priv->type = G_SOCKET_TYPE_INVALID;
368 addrlen = sizeof address;
369 if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
371 errsv = get_socket_errno ();
377 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
378 sizeof address.ss_family <= addrlen);
379 family = address.ss_family;
383 /* On Solaris, this happens if the socket is not yet connected.
384 * But we can use SO_DOMAIN as a workaround there.
387 optlen = sizeof family;
388 if (getsockopt (fd, SOL_SOCKET, SO_DOMAIN, (void *)&family, &optlen) != 0)
390 errsv = get_socket_errno ();
394 /* This will translate to G_IO_ERROR_FAILED on either unix or windows */
402 case G_SOCKET_FAMILY_IPV4:
403 case G_SOCKET_FAMILY_IPV6:
404 socket->priv->family = address.ss_family;
405 switch (socket->priv->type)
407 case G_SOCKET_TYPE_STREAM:
408 socket->priv->protocol = G_SOCKET_PROTOCOL_TCP;
411 case G_SOCKET_TYPE_DATAGRAM:
412 socket->priv->protocol = G_SOCKET_PROTOCOL_UDP;
415 case G_SOCKET_TYPE_SEQPACKET:
416 socket->priv->protocol = G_SOCKET_PROTOCOL_SCTP;
424 case G_SOCKET_FAMILY_UNIX:
425 socket->priv->family = G_SOCKET_FAMILY_UNIX;
426 socket->priv->protocol = G_SOCKET_PROTOCOL_DEFAULT;
430 socket->priv->family = G_SOCKET_FAMILY_INVALID;
434 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
436 addrlen = sizeof address;
437 if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
438 socket->priv->connected = TRUE;
441 optlen = sizeof bool_val;
442 if (getsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
443 (void *)&bool_val, &optlen) == 0)
446 /* Experimentation indicates that the SO_KEEPALIVE value is
447 * actually a char on Windows, even if documentation claims it
448 * to be a BOOL which is a typedef for int. So this g_assert()
449 * fails. See bug #611756.
451 g_assert (optlen == sizeof bool_val);
453 socket->priv->keepalive = !!bool_val;
457 /* Can't read, maybe not supported, assume FALSE */
458 socket->priv->keepalive = FALSE;
464 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
465 socket_io_error_from_errno (errsv),
466 _("creating GSocket from fd: %s"),
467 socket_strerror (errsv));
471 g_socket_create_socket (GSocketFamily family,
481 case G_SOCKET_TYPE_STREAM:
482 native_type = SOCK_STREAM;
485 case G_SOCKET_TYPE_DATAGRAM:
486 native_type = SOCK_DGRAM;
489 case G_SOCKET_TYPE_SEQPACKET:
490 native_type = SOCK_SEQPACKET;
494 g_assert_not_reached ();
499 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
500 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
505 fd = socket (family, native_type | SOCK_CLOEXEC, protocol);
506 /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
507 if (fd < 0 && errno == EINVAL)
509 fd = socket (family, native_type, protocol);
513 int errsv = get_socket_errno ();
515 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
516 _("Unable to create socket: %s"), socket_strerror (errsv));
523 /* We always want to set close-on-exec to protect users. If you
524 need to so some weird inheritance to exec you can re-enable this
525 using lower level hacks with g_socket_get_fd(). */
526 flags = fcntl (fd, F_GETFD, 0);
528 (flags & FD_CLOEXEC) == 0)
531 fcntl (fd, F_SETFD, flags);
540 g_socket_constructed (GObject *object)
542 GSocket *socket = G_SOCKET (object);
544 if (socket->priv->fd >= 0)
545 /* create socket->priv info from the fd */
546 g_socket_details_from_fd (socket);
549 /* create the fd from socket->priv info */
550 socket->priv->fd = g_socket_create_socket (socket->priv->family,
552 socket->priv->protocol,
553 &socket->priv->construct_error);
555 /* Always use native nonblocking sockets, as
556 windows sets sockets to nonblocking automatically
557 in certain operations. This way we make things work
558 the same on all platforms */
559 if (socket->priv->fd != -1)
560 set_fd_nonblocking (socket->priv->fd);
564 g_socket_get_property (GObject *object,
569 GSocket *socket = G_SOCKET (object);
570 GSocketAddress *address;
575 g_value_set_enum (value, socket->priv->family);
579 g_value_set_enum (value, socket->priv->type);
583 g_value_set_enum (value, socket->priv->protocol);
587 g_value_set_int (value, socket->priv->fd);
591 g_value_set_boolean (value, socket->priv->blocking);
594 case PROP_LISTEN_BACKLOG:
595 g_value_set_int (value, socket->priv->listen_backlog);
599 g_value_set_boolean (value, socket->priv->keepalive);
602 case PROP_LOCAL_ADDRESS:
603 address = g_socket_get_local_address (socket, NULL);
604 g_value_take_object (value, address);
607 case PROP_REMOTE_ADDRESS:
608 address = g_socket_get_remote_address (socket, NULL);
609 g_value_take_object (value, address);
613 g_value_set_uint (value, socket->priv->timeout);
617 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
622 g_socket_set_property (GObject *object,
627 GSocket *socket = G_SOCKET (object);
632 socket->priv->family = g_value_get_enum (value);
636 socket->priv->type = g_value_get_enum (value);
640 socket->priv->protocol = g_value_get_enum (value);
644 socket->priv->fd = g_value_get_int (value);
648 g_socket_set_blocking (socket, g_value_get_boolean (value));
651 case PROP_LISTEN_BACKLOG:
652 g_socket_set_listen_backlog (socket, g_value_get_int (value));
656 g_socket_set_keepalive (socket, g_value_get_boolean (value));
660 g_socket_set_timeout (socket, g_value_get_uint (value));
664 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
669 g_socket_finalize (GObject *object)
671 GSocket *socket = G_SOCKET (object);
673 g_clear_error (&socket->priv->construct_error);
675 if (socket->priv->fd != -1 &&
676 !socket->priv->closed)
677 g_socket_close (socket, NULL);
679 if (socket->priv->remote_address)
680 g_object_unref (socket->priv->remote_address);
683 if (socket->priv->event != WSA_INVALID_EVENT)
685 WSACloseEvent (socket->priv->event);
686 socket->priv->event = WSA_INVALID_EVENT;
689 g_assert (socket->priv->requested_conditions == NULL);
692 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
693 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
697 g_socket_class_init (GSocketClass *klass)
699 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
702 /* Make sure winsock has been initialized */
703 type = g_inet_address_get_type ();
704 (type); /* To avoid -Wunused-but-set-variable */
707 /* There is no portable, thread-safe way to avoid having the process
708 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
709 * forced to simply ignore the signal process-wide.
711 signal (SIGPIPE, SIG_IGN);
714 g_type_class_add_private (klass, sizeof (GSocketPrivate));
716 gobject_class->finalize = g_socket_finalize;
717 gobject_class->constructed = g_socket_constructed;
718 gobject_class->set_property = g_socket_set_property;
719 gobject_class->get_property = g_socket_get_property;
721 g_object_class_install_property (gobject_class, PROP_FAMILY,
722 g_param_spec_enum ("family",
724 P_("The sockets address family"),
725 G_TYPE_SOCKET_FAMILY,
726 G_SOCKET_FAMILY_INVALID,
727 G_PARAM_CONSTRUCT_ONLY |
729 G_PARAM_STATIC_STRINGS));
731 g_object_class_install_property (gobject_class, PROP_TYPE,
732 g_param_spec_enum ("type",
734 P_("The sockets type"),
736 G_SOCKET_TYPE_STREAM,
737 G_PARAM_CONSTRUCT_ONLY |
739 G_PARAM_STATIC_STRINGS));
741 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
742 g_param_spec_enum ("protocol",
743 P_("Socket protocol"),
744 P_("The id of the protocol to use, or -1 for unknown"),
745 G_TYPE_SOCKET_PROTOCOL,
746 G_SOCKET_PROTOCOL_UNKNOWN,
747 G_PARAM_CONSTRUCT_ONLY |
749 G_PARAM_STATIC_STRINGS));
751 g_object_class_install_property (gobject_class, PROP_FD,
752 g_param_spec_int ("fd",
753 P_("File descriptor"),
754 P_("The sockets file descriptor"),
758 G_PARAM_CONSTRUCT_ONLY |
760 G_PARAM_STATIC_STRINGS));
762 g_object_class_install_property (gobject_class, PROP_BLOCKING,
763 g_param_spec_boolean ("blocking",
765 P_("Whether or not I/O on this socket is blocking"),
768 G_PARAM_STATIC_STRINGS));
770 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
771 g_param_spec_int ("listen-backlog",
772 P_("Listen backlog"),
773 P_("Outstanding connections in the listen queue"),
778 G_PARAM_STATIC_STRINGS));
780 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
781 g_param_spec_boolean ("keepalive",
782 P_("Keep connection alive"),
783 P_("Keep connection alive by sending periodic pings"),
786 G_PARAM_STATIC_STRINGS));
788 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
789 g_param_spec_object ("local-address",
791 P_("The local address the socket is bound to"),
792 G_TYPE_SOCKET_ADDRESS,
794 G_PARAM_STATIC_STRINGS));
796 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
797 g_param_spec_object ("remote-address",
798 P_("Remote address"),
799 P_("The remote address the socket is connected to"),
800 G_TYPE_SOCKET_ADDRESS,
802 G_PARAM_STATIC_STRINGS));
807 * The timeout in seconds on socket I/O
811 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
812 g_param_spec_uint ("timeout",
814 P_("The timeout in seconds on socket I/O"),
819 G_PARAM_STATIC_STRINGS));
823 g_socket_initable_iface_init (GInitableIface *iface)
825 iface->init = g_socket_initable_init;
829 g_socket_init (GSocket *socket)
831 socket->priv = G_TYPE_INSTANCE_GET_PRIVATE (socket, G_TYPE_SOCKET, GSocketPrivate);
833 socket->priv->fd = -1;
834 socket->priv->blocking = TRUE;
835 socket->priv->listen_backlog = 10;
836 socket->priv->construct_error = NULL;
838 socket->priv->event = WSA_INVALID_EVENT;
843 g_socket_initable_init (GInitable *initable,
844 GCancellable *cancellable,
849 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
851 socket = G_SOCKET (initable);
853 if (cancellable != NULL)
855 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
856 _("Cancellable initialization not supported"));
860 socket->priv->inited = TRUE;
862 if (socket->priv->construct_error)
865 *error = g_error_copy (socket->priv->construct_error);
875 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
876 * @type: the socket type to use.
877 * @protocol: the id of the protocol to use, or 0 for default.
878 * @error: #GError for error reporting, or %NULL to ignore.
880 * Creates a new #GSocket with the defined family, type and protocol.
881 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
882 * for the family and type is used.
884 * The @protocol is a family and type specific int that specifies what
885 * kind of protocol to use. #GSocketProtocol lists several common ones.
886 * Many families only support one protocol, and use 0 for this, others
887 * support several and using 0 means to use the default protocol for
888 * the family and type.
890 * The protocol id is passed directly to the operating
891 * system, so you can use protocols not listed in #GSocketProtocol if you
892 * know the protocol number used for it.
894 * Returns: a #GSocket or %NULL on error.
895 * Free the returned object with g_object_unref().
900 g_socket_new (GSocketFamily family,
902 GSocketProtocol protocol,
905 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
909 "protocol", protocol,
914 * g_socket_new_from_fd:
915 * @fd: a native socket file descriptor.
916 * @error: #GError for error reporting, or %NULL to ignore.
918 * Creates a new #GSocket from a native file descriptor
919 * or winsock SOCKET handle.
921 * This reads all the settings from the file descriptor so that
922 * all properties should work. Note that the file descriptor
923 * will be set to non-blocking mode, independent on the blocking
924 * mode of the #GSocket.
926 * Returns: a #GSocket or %NULL on error.
927 * Free the returned object with g_object_unref().
932 g_socket_new_from_fd (gint fd,
935 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
942 * g_socket_set_blocking:
943 * @socket: a #GSocket.
944 * @blocking: Whether to use blocking I/O or not.
946 * Sets the blocking mode of the socket. In blocking mode
947 * all operations block until they succeed or there is an error. In
948 * non-blocking mode all functions return results immediately or
949 * with a %G_IO_ERROR_WOULD_BLOCK error.
951 * All sockets are created in blocking mode. However, note that the
952 * platform level socket is always non-blocking, and blocking mode
953 * is a GSocket level feature.
958 g_socket_set_blocking (GSocket *socket,
961 g_return_if_fail (G_IS_SOCKET (socket));
963 blocking = !!blocking;
965 if (socket->priv->blocking == blocking)
968 socket->priv->blocking = blocking;
969 g_object_notify (G_OBJECT (socket), "blocking");
973 * g_socket_get_blocking:
974 * @socket: a #GSocket.
976 * Gets the blocking mode of the socket. For details on blocking I/O,
977 * see g_socket_set_blocking().
979 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
984 g_socket_get_blocking (GSocket *socket)
986 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
988 return socket->priv->blocking;
992 * g_socket_set_keepalive:
993 * @socket: a #GSocket.
994 * @keepalive: Value for the keepalive flag
996 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
997 * this flag is set on a socket, the system will attempt to verify that the
998 * remote socket endpoint is still present if a sufficiently long period of
999 * time passes with no data being exchanged. If the system is unable to
1000 * verify the presence of the remote endpoint, it will automatically close
1003 * This option is only functional on certain kinds of sockets. (Notably,
1004 * %G_SOCKET_PROTOCOL_TCP sockets.)
1006 * The exact time between pings is system- and protocol-dependent, but will
1007 * normally be at least two hours. Most commonly, you would set this flag
1008 * on a server socket if you want to allow clients to remain idle for long
1009 * periods of time, but also want to ensure that connections are eventually
1010 * garbage-collected if clients crash or become unreachable.
1015 g_socket_set_keepalive (GSocket *socket,
1020 g_return_if_fail (G_IS_SOCKET (socket));
1022 keepalive = !!keepalive;
1023 if (socket->priv->keepalive == keepalive)
1026 value = (gint) keepalive;
1027 if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_KEEPALIVE,
1028 (gpointer) &value, sizeof (value)) < 0)
1030 int errsv = get_socket_errno ();
1031 g_warning ("error setting keepalive: %s", socket_strerror (errsv));
1035 socket->priv->keepalive = keepalive;
1036 g_object_notify (G_OBJECT (socket), "keepalive");
1040 * g_socket_get_keepalive:
1041 * @socket: a #GSocket.
1043 * Gets the keepalive mode of the socket. For details on this,
1044 * see g_socket_set_keepalive().
1046 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1051 g_socket_get_keepalive (GSocket *socket)
1053 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1055 return socket->priv->keepalive;
1059 * g_socket_get_listen_backlog:
1060 * @socket: a #GSocket.
1062 * Gets the listen backlog setting of the socket. For details on this,
1063 * see g_socket_set_listen_backlog().
1065 * Returns: the maximum number of pending connections.
1070 g_socket_get_listen_backlog (GSocket *socket)
1072 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1074 return socket->priv->listen_backlog;
1078 * g_socket_set_listen_backlog:
1079 * @socket: a #GSocket.
1080 * @backlog: the maximum number of pending connections.
1082 * Sets the maximum number of outstanding connections allowed
1083 * when listening on this socket. If more clients than this are
1084 * connecting to the socket and the application is not handling them
1085 * on time then the new connections will be refused.
1087 * Note that this must be called before g_socket_listen() and has no
1088 * effect if called after that.
1093 g_socket_set_listen_backlog (GSocket *socket,
1096 g_return_if_fail (G_IS_SOCKET (socket));
1097 g_return_if_fail (!socket->priv->listening);
1099 if (backlog != socket->priv->listen_backlog)
1101 socket->priv->listen_backlog = backlog;
1102 g_object_notify (G_OBJECT (socket), "listen-backlog");
1107 * g_socket_get_timeout:
1108 * @socket: a #GSocket.
1110 * Gets the timeout setting of the socket. For details on this, see
1111 * g_socket_set_timeout().
1113 * Returns: the timeout in seconds
1118 g_socket_get_timeout (GSocket *socket)
1120 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1122 return socket->priv->timeout;
1126 * g_socket_set_timeout:
1127 * @socket: a #GSocket.
1128 * @timeout: the timeout for @socket, in seconds, or 0 for none
1130 * Sets the time in seconds after which I/O operations on @socket will
1131 * time out if they have not yet completed.
1133 * On a blocking socket, this means that any blocking #GSocket
1134 * operation will time out after @timeout seconds of inactivity,
1135 * returning %G_IO_ERROR_TIMED_OUT.
1137 * On a non-blocking socket, calls to g_socket_condition_wait() will
1138 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1139 * created with g_socket_create_source() will trigger after
1140 * @timeout seconds of inactivity, with the requested condition
1141 * set, at which point calling g_socket_receive(), g_socket_send(),
1142 * g_socket_check_connect_result(), etc, will fail with
1143 * %G_IO_ERROR_TIMED_OUT.
1145 * If @timeout is 0 (the default), operations will never time out
1148 * Note that if an I/O operation is interrupted by a signal, this may
1149 * cause the timeout to be reset.
1154 g_socket_set_timeout (GSocket *socket,
1157 g_return_if_fail (G_IS_SOCKET (socket));
1159 if (timeout != socket->priv->timeout)
1161 socket->priv->timeout = timeout;
1162 g_object_notify (G_OBJECT (socket), "timeout");
1167 * g_socket_get_family:
1168 * @socket: a #GSocket.
1170 * Gets the socket family of the socket.
1172 * Returns: a #GSocketFamily
1177 g_socket_get_family (GSocket *socket)
1179 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1181 return socket->priv->family;
1185 * g_socket_get_socket_type:
1186 * @socket: a #GSocket.
1188 * Gets the socket type of the socket.
1190 * Returns: a #GSocketType
1195 g_socket_get_socket_type (GSocket *socket)
1197 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1199 return socket->priv->type;
1203 * g_socket_get_protocol:
1204 * @socket: a #GSocket.
1206 * Gets the socket protocol id the socket was created with.
1207 * In case the protocol is unknown, -1 is returned.
1209 * Returns: a protocol id, or -1 if unknown
1214 g_socket_get_protocol (GSocket *socket)
1216 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1218 return socket->priv->protocol;
1223 * @socket: a #GSocket.
1225 * Returns the underlying OS socket object. On unix this
1226 * is a socket file descriptor, and on windows this is
1227 * a Winsock2 SOCKET handle. This may be useful for
1228 * doing platform specific or otherwise unusual operations
1231 * Returns: the file descriptor of the socket.
1236 g_socket_get_fd (GSocket *socket)
1238 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1240 return socket->priv->fd;
1244 * g_socket_get_local_address:
1245 * @socket: a #GSocket.
1246 * @error: #GError for error reporting, or %NULL to ignore.
1248 * Try to get the local address of a bound socket. This is only
1249 * useful if the socket has been bound to a local address,
1250 * either explicitly or implicitly when connecting.
1252 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1253 * Free the returned object with g_object_unref().
1258 g_socket_get_local_address (GSocket *socket,
1261 struct sockaddr_storage buffer;
1262 guint32 len = sizeof (buffer);
1264 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1266 if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1268 int errsv = get_socket_errno ();
1269 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1270 _("could not get local address: %s"), socket_strerror (errsv));
1274 return g_socket_address_new_from_native (&buffer, len);
1278 * g_socket_get_remote_address:
1279 * @socket: a #GSocket.
1280 * @error: #GError for error reporting, or %NULL to ignore.
1282 * Try to get the remove address of a connected socket. This is only
1283 * useful for connection oriented sockets that have been connected.
1285 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1286 * Free the returned object with g_object_unref().
1291 g_socket_get_remote_address (GSocket *socket,
1294 struct sockaddr_storage buffer;
1295 guint32 len = sizeof (buffer);
1297 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1299 if (socket->priv->connect_pending)
1301 if (!g_socket_check_connect_result (socket, error))
1304 socket->priv->connect_pending = FALSE;
1307 if (!socket->priv->remote_address)
1309 if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1311 int errsv = get_socket_errno ();
1312 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1313 _("could not get remote address: %s"), socket_strerror (errsv));
1317 socket->priv->remote_address = g_socket_address_new_from_native (&buffer, len);
1320 return g_object_ref (socket->priv->remote_address);
1324 * g_socket_is_connected:
1325 * @socket: a #GSocket.
1327 * Check whether the socket is connected. This is only useful for
1328 * connection-oriented sockets.
1330 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1335 g_socket_is_connected (GSocket *socket)
1337 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1339 return socket->priv->connected;
1344 * @socket: a #GSocket.
1345 * @error: #GError for error reporting, or %NULL to ignore.
1347 * Marks the socket as a server socket, i.e. a socket that is used
1348 * to accept incoming requests using g_socket_accept().
1350 * Before calling this the socket must be bound to a local address using
1353 * To set the maximum amount of outstanding clients, use
1354 * g_socket_set_listen_backlog().
1356 * Returns: %TRUE on success, %FALSE on error.
1361 g_socket_listen (GSocket *socket,
1364 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1366 if (!check_socket (socket, error))
1369 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1371 int errsv = get_socket_errno ();
1373 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1374 _("could not listen: %s"), socket_strerror (errsv));
1378 socket->priv->listening = TRUE;
1385 * @socket: a #GSocket.
1386 * @address: a #GSocketAddress specifying the local address.
1387 * @allow_reuse: whether to allow reusing this address
1388 * @error: #GError for error reporting, or %NULL to ignore.
1390 * When a socket is created it is attached to an address family, but it
1391 * doesn't have an address in this family. g_socket_bind() assigns the
1392 * address (sometimes called name) of the socket.
1394 * It is generally required to bind to a local address before you can
1395 * receive connections. (See g_socket_listen() and g_socket_accept() ).
1396 * In certain situations, you may also want to bind a socket that will be
1397 * used to initiate connections, though this is not normally required.
1399 * @allow_reuse should be %TRUE for server sockets (sockets that you will
1400 * eventually call g_socket_accept() on), and %FALSE for client sockets.
1401 * (Specifically, if it is %TRUE, then g_socket_bind() will set the
1402 * %SO_REUSEADDR flag on the socket, allowing it to bind @address even if
1403 * that address was previously used by another socket that has not yet been
1404 * fully cleaned-up by the kernel. Failing to set this flag on a server
1405 * socket may cause the bind call to return %G_IO_ERROR_ADDRESS_IN_USE if
1406 * the server program is stopped and then immediately restarted.)
1408 * Returns: %TRUE on success, %FALSE on error.
1413 g_socket_bind (GSocket *socket,
1414 GSocketAddress *address,
1415 gboolean reuse_address,
1418 struct sockaddr_storage addr;
1420 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1422 if (!check_socket (socket, error))
1425 /* SO_REUSEADDR on windows means something else and is not what we want.
1426 It always allows the unix variant of SO_REUSEADDR anyway */
1431 value = (int) !!reuse_address;
1432 /* Ignore errors here, the only likely error is "not supported", and
1433 this is a "best effort" thing mainly */
1434 setsockopt (socket->priv->fd, SOL_SOCKET, SO_REUSEADDR,
1435 (gpointer) &value, sizeof (value));
1439 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1442 if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1443 g_socket_address_get_native_size (address)) < 0)
1445 int errsv = get_socket_errno ();
1447 G_IO_ERROR, socket_io_error_from_errno (errsv),
1448 _("Error binding to address: %s"), socket_strerror (errsv));
1456 * g_socket_speaks_ipv4:
1457 * @socket: a #GSocket
1459 * Checks if a socket is capable of speaking IPv4.
1461 * IPv4 sockets are capable of speaking IPv4. On some operating systems
1462 * and under some combinations of circumstances IPv6 sockets are also
1463 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
1466 * No other types of sockets are currently considered as being capable
1469 * Returns: %TRUE if this socket can be used with IPv4.
1474 g_socket_speaks_ipv4 (GSocket *socket)
1476 switch (socket->priv->family)
1478 case G_SOCKET_FAMILY_IPV4:
1481 case G_SOCKET_FAMILY_IPV6:
1482 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
1484 guint sizeof_int = sizeof (int);
1487 if (getsockopt (socket->priv->fd,
1488 IPPROTO_IPV6, IPV6_V6ONLY,
1489 &v6_only, &sizeof_int) != 0)
1505 * @socket: a #GSocket.
1506 * @cancellable: (allow-none): a %GCancellable or %NULL
1507 * @error: #GError for error reporting, or %NULL to ignore.
1509 * Accept incoming connections on a connection-based socket. This removes
1510 * the first outstanding connection request from the listening socket and
1511 * creates a #GSocket object for it.
1513 * The @socket must be bound to a local address with g_socket_bind() and
1514 * must be listening for incoming connections (g_socket_listen()).
1516 * If there are no outstanding connections then the operation will block
1517 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
1518 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
1520 * Returns: (transfer full): a new #GSocket, or %NULL on error.
1521 * Free the returned object with g_object_unref().
1526 g_socket_accept (GSocket *socket,
1527 GCancellable *cancellable,
1530 GSocket *new_socket;
1533 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1535 if (!check_socket (socket, error))
1540 if (socket->priv->blocking &&
1541 !g_socket_condition_wait (socket,
1542 G_IO_IN, cancellable, error))
1545 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
1547 int errsv = get_socket_errno ();
1549 win32_unset_event_mask (socket, FD_ACCEPT);
1554 if (socket->priv->blocking)
1556 #ifdef WSAEWOULDBLOCK
1557 if (errsv == WSAEWOULDBLOCK)
1560 if (errsv == EWOULDBLOCK ||
1566 g_set_error (error, G_IO_ERROR,
1567 socket_io_error_from_errno (errsv),
1568 _("Error accepting connection: %s"), socket_strerror (errsv));
1574 win32_unset_event_mask (socket, FD_ACCEPT);
1578 /* The socket inherits the accepting sockets event mask and even object,
1579 we need to remove that */
1580 WSAEventSelect (ret, NULL, 0);
1586 /* We always want to set close-on-exec to protect users. If you
1587 need to so some weird inheritance to exec you can re-enable this
1588 using lower level hacks with g_socket_get_fd(). */
1589 flags = fcntl (ret, F_GETFD, 0);
1591 (flags & FD_CLOEXEC) == 0)
1593 flags |= FD_CLOEXEC;
1594 fcntl (ret, F_SETFD, flags);
1599 new_socket = g_socket_new_from_fd (ret, error);
1600 if (new_socket == NULL)
1609 new_socket->priv->protocol = socket->priv->protocol;
1616 * @socket: a #GSocket.
1617 * @address: a #GSocketAddress specifying the remote address.
1618 * @cancellable: (allow-none): a %GCancellable or %NULL
1619 * @error: #GError for error reporting, or %NULL to ignore.
1621 * Connect the socket to the specified remote address.
1623 * For connection oriented socket this generally means we attempt to make
1624 * a connection to the @address. For a connection-less socket it sets
1625 * the default address for g_socket_send() and discards all incoming datagrams
1626 * from other sources.
1628 * Generally connection oriented sockets can only connect once, but
1629 * connection-less sockets can connect multiple times to change the
1632 * If the connect call needs to do network I/O it will block, unless
1633 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
1634 * and the user can be notified of the connection finishing by waiting
1635 * for the G_IO_OUT condition. The result of the connection must then be
1636 * checked with g_socket_check_connect_result().
1638 * Returns: %TRUE if connected, %FALSE on error.
1643 g_socket_connect (GSocket *socket,
1644 GSocketAddress *address,
1645 GCancellable *cancellable,
1648 struct sockaddr_storage buffer;
1650 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1652 if (!check_socket (socket, error))
1655 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
1658 if (socket->priv->remote_address)
1659 g_object_unref (socket->priv->remote_address);
1660 socket->priv->remote_address = g_object_ref (address);
1664 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
1665 g_socket_address_get_native_size (address)) < 0)
1667 int errsv = get_socket_errno ();
1673 if (errsv == EINPROGRESS)
1675 if (errsv == WSAEWOULDBLOCK)
1678 if (socket->priv->blocking)
1680 if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
1682 if (g_socket_check_connect_result (socket, error))
1685 g_prefix_error (error, _("Error connecting: "));
1689 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
1690 _("Connection in progress"));
1691 socket->priv->connect_pending = TRUE;
1695 g_set_error (error, G_IO_ERROR,
1696 socket_io_error_from_errno (errsv),
1697 _("Error connecting: %s"), socket_strerror (errsv));
1704 win32_unset_event_mask (socket, FD_CONNECT);
1706 socket->priv->connected = TRUE;
1712 * g_socket_check_connect_result:
1713 * @socket: a #GSocket
1714 * @error: #GError for error reporting, or %NULL to ignore.
1716 * Checks and resets the pending connect error for the socket.
1717 * This is used to check for errors when g_socket_connect() is
1718 * used in non-blocking mode.
1720 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
1725 g_socket_check_connect_result (GSocket *socket,
1731 if (!check_socket (socket, error))
1734 optlen = sizeof (value);
1735 if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
1737 int errsv = get_socket_errno ();
1739 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1740 _("Unable to get pending error: %s"), socket_strerror (errsv));
1746 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
1747 socket_strerror (value));
1748 if (socket->priv->remote_address)
1750 g_object_unref (socket->priv->remote_address);
1751 socket->priv->remote_address = NULL;
1756 socket->priv->connected = TRUE;
1762 * @socket: a #GSocket
1763 * @buffer: a buffer to read data into (which should be at least @size
1765 * @size: the number of bytes you want to read from the socket
1766 * @cancellable: (allow-none): a %GCancellable or %NULL
1767 * @error: #GError for error reporting, or %NULL to ignore.
1769 * Receive data (up to @size bytes) from a socket. This is mainly used by
1770 * connection-oriented sockets; it is identical to g_socket_receive_from()
1771 * with @address set to %NULL.
1773 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
1774 * g_socket_receive() will always read either 0 or 1 complete messages from
1775 * the socket. If the received message is too large to fit in @buffer, then
1776 * the data beyond @size bytes will be discarded, without any explicit
1777 * indication that this has occurred.
1779 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
1780 * number of bytes, up to @size. If more than @size bytes have been
1781 * received, the additional data will be returned in future calls to
1782 * g_socket_receive().
1784 * If the socket is in blocking mode the call will block until there
1785 * is some data to receive, the connection is closed, or there is an
1786 * error. If there is no data available and the socket is in
1787 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
1788 * returned. To be notified when data is available, wait for the
1789 * %G_IO_IN condition.
1791 * On error -1 is returned and @error is set accordingly.
1793 * Returns: Number of bytes read, or 0 if the connection was closed by
1794 * the peer, or -1 on error
1799 g_socket_receive (GSocket *socket,
1802 GCancellable *cancellable,
1805 return g_socket_receive_with_blocking (socket, buffer, size,
1806 socket->priv->blocking,
1807 cancellable, error);
1811 * g_socket_receive_with_blocking:
1812 * @socket: a #GSocket
1813 * @buffer: a buffer to read data into (which should be at least @size
1815 * @size: the number of bytes you want to read from the socket
1816 * @blocking: whether to do blocking or non-blocking I/O
1817 * @cancellable: (allow-none): a %GCancellable or %NULL
1818 * @error: #GError for error reporting, or %NULL to ignore.
1820 * This behaves exactly the same as g_socket_receive(), except that
1821 * the choice of blocking or non-blocking behavior is determined by
1822 * the @blocking argument rather than by @socket's properties.
1824 * Returns: Number of bytes read, or 0 if the connection was closed by
1825 * the peer, or -1 on error
1830 g_socket_receive_with_blocking (GSocket *socket,
1834 GCancellable *cancellable,
1839 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1841 if (!check_socket (socket, error))
1844 if (g_cancellable_set_error_if_cancelled (cancellable, error))
1850 !g_socket_condition_wait (socket,
1851 G_IO_IN, cancellable, error))
1854 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
1856 int errsv = get_socket_errno ();
1863 #ifdef WSAEWOULDBLOCK
1864 if (errsv == WSAEWOULDBLOCK)
1867 if (errsv == EWOULDBLOCK ||
1873 win32_unset_event_mask (socket, FD_READ);
1875 g_set_error (error, G_IO_ERROR,
1876 socket_io_error_from_errno (errsv),
1877 _("Error receiving data: %s"), socket_strerror (errsv));
1881 win32_unset_event_mask (socket, FD_READ);
1890 * g_socket_receive_from:
1891 * @socket: a #GSocket
1892 * @address: a pointer to a #GSocketAddress pointer, or %NULL
1893 * @buffer: a buffer to read data into (which should be at least @size
1895 * @size: the number of bytes you want to read from the socket
1896 * @cancellable: (allow-none): a %GCancellable or %NULL
1897 * @error: #GError for error reporting, or %NULL to ignore.
1899 * Receive data (up to @size bytes) from a socket.
1901 * If @address is non-%NULL then @address will be set equal to the
1902 * source address of the received packet.
1903 * @address is owned by the caller.
1905 * See g_socket_receive() for additional information.
1907 * Returns: Number of bytes read, or 0 if the connection was closed by
1908 * the peer, or -1 on error
1913 g_socket_receive_from (GSocket *socket,
1914 GSocketAddress **address,
1917 GCancellable *cancellable,
1925 return g_socket_receive_message (socket,
1933 /* Although we ignore SIGPIPE, gdb will still stop if the app receives
1934 * one, which can be confusing and annoying. So if possible, we want
1935 * to suppress the signal entirely.
1938 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
1940 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
1945 * @socket: a #GSocket
1946 * @buffer: (array length=size): the buffer containing the data to send.
1947 * @size: the number of bytes to send
1948 * @cancellable: (allow-none): a %GCancellable or %NULL
1949 * @error: #GError for error reporting, or %NULL to ignore.
1951 * Tries to send @size bytes from @buffer on the socket. This is
1952 * mainly used by connection-oriented sockets; it is identical to
1953 * g_socket_send_to() with @address set to %NULL.
1955 * If the socket is in blocking mode the call will block until there is
1956 * space for the data in the socket queue. If there is no space available
1957 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1958 * will be returned. To be notified when space is available, wait for the
1959 * %G_IO_OUT condition. Note though that you may still receive
1960 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
1961 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
1962 * very common due to the way the underlying APIs work.)
1964 * On error -1 is returned and @error is set accordingly.
1966 * Returns: Number of bytes written (which may be less than @size), or -1
1972 g_socket_send (GSocket *socket,
1973 const gchar *buffer,
1975 GCancellable *cancellable,
1978 return g_socket_send_with_blocking (socket, buffer, size,
1979 socket->priv->blocking,
1980 cancellable, error);
1984 * g_socket_send_with_blocking:
1985 * @socket: a #GSocket
1986 * @buffer: (array length=size): the buffer containing the data to send.
1987 * @size: the number of bytes to send
1988 * @blocking: whether to do blocking or non-blocking I/O
1989 * @cancellable: (allow-none): a %GCancellable or %NULL
1990 * @error: #GError for error reporting, or %NULL to ignore.
1992 * This behaves exactly the same as g_socket_send(), except that
1993 * the choice of blocking or non-blocking behavior is determined by
1994 * the @blocking argument rather than by @socket's properties.
1996 * Returns: Number of bytes written (which may be less than @size), or -1
2002 g_socket_send_with_blocking (GSocket *socket,
2003 const gchar *buffer,
2006 GCancellable *cancellable,
2011 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
2013 if (!check_socket (socket, error))
2016 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2022 !g_socket_condition_wait (socket,
2023 G_IO_OUT, cancellable, error))
2026 if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
2028 int errsv = get_socket_errno ();
2033 #ifdef WSAEWOULDBLOCK
2034 if (errsv == WSAEWOULDBLOCK)
2035 win32_unset_event_mask (socket, FD_WRITE);
2040 #ifdef WSAEWOULDBLOCK
2041 if (errsv == WSAEWOULDBLOCK)
2044 if (errsv == EWOULDBLOCK ||
2050 g_set_error (error, G_IO_ERROR,
2051 socket_io_error_from_errno (errsv),
2052 _("Error sending data: %s"), socket_strerror (errsv));
2063 * @socket: a #GSocket
2064 * @address: a #GSocketAddress, or %NULL
2065 * @buffer: (array length=size): the buffer containing the data to send.
2066 * @size: the number of bytes to send
2067 * @cancellable: (allow-none): a %GCancellable or %NULL
2068 * @error: #GError for error reporting, or %NULL to ignore.
2070 * Tries to send @size bytes from @buffer to @address. If @address is
2071 * %NULL then the message is sent to the default receiver (set by
2072 * g_socket_connect()).
2074 * See g_socket_send() for additional information.
2076 * Returns: Number of bytes written (which may be less than @size), or -1
2082 g_socket_send_to (GSocket *socket,
2083 GSocketAddress *address,
2084 const gchar *buffer,
2086 GCancellable *cancellable,
2094 return g_socket_send_message (socket,
2104 * g_socket_shutdown:
2105 * @socket: a #GSocket
2106 * @shutdown_read: whether to shut down the read side
2107 * @shutdown_write: whether to shut down the write side
2108 * @error: #GError for error reporting, or %NULL to ignore.
2110 * Shut down part of a full-duplex connection.
2112 * If @shutdown_read is %TRUE then the receiving side of the connection
2113 * is shut down, and further reading is disallowed.
2115 * If @shutdown_write is %TRUE then the sending side of the connection
2116 * is shut down, and further writing is disallowed.
2118 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
2120 * One example where this is used is graceful disconnect for TCP connections
2121 * where you close the sending side, then wait for the other side to close
2122 * the connection, thus ensuring that the other side saw all sent data.
2124 * Returns: %TRUE on success, %FALSE on error
2129 g_socket_shutdown (GSocket *socket,
2130 gboolean shutdown_read,
2131 gboolean shutdown_write,
2136 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2138 if (!check_socket (socket, error))
2142 if (!shutdown_read && !shutdown_write)
2146 if (shutdown_read && shutdown_write)
2148 else if (shutdown_read)
2153 if (shutdown_read && shutdown_write)
2155 else if (shutdown_read)
2161 if (shutdown (socket->priv->fd, how) != 0)
2163 int errsv = get_socket_errno ();
2164 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2165 _("Unable to shutdown socket: %s"), socket_strerror (errsv));
2169 if (shutdown_read && shutdown_write)
2170 socket->priv->connected = FALSE;
2177 * @socket: a #GSocket
2178 * @error: #GError for error reporting, or %NULL to ignore.
2180 * Closes the socket, shutting down any active connection.
2182 * Closing a socket does not wait for all outstanding I/O operations
2183 * to finish, so the caller should not rely on them to be guaranteed
2184 * to complete even if the close returns with no error.
2186 * Once the socket is closed, all other operations will return
2187 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
2190 * Sockets will be automatically closed when the last reference
2191 * is dropped, but you might want to call this function to make sure
2192 * resources are released as early as possible.
2194 * Beware that due to the way that TCP works, it is possible for
2195 * recently-sent data to be lost if either you close a socket while the
2196 * %G_IO_IN condition is set, or else if the remote connection tries to
2197 * send something to you after you close the socket but before it has
2198 * finished reading all of the data you sent. There is no easy generic
2199 * way to avoid this problem; the easiest fix is to design the network
2200 * protocol such that the client will never send data "out of turn".
2201 * Another solution is for the server to half-close the connection by
2202 * calling g_socket_shutdown() with only the @shutdown_write flag set,
2203 * and then wait for the client to notice this and close its side of the
2204 * connection, after which the server can safely call g_socket_close().
2205 * (This is what #GTcpConnection does if you call
2206 * g_tcp_connection_set_graceful_disconnect(). But of course, this
2207 * only works if the client will close its connection after the server
2210 * Returns: %TRUE on success, %FALSE on error
2215 g_socket_close (GSocket *socket,
2220 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2222 if (socket->priv->closed)
2223 return TRUE; /* Multiple close not an error */
2225 if (!check_socket (socket, error))
2231 res = closesocket (socket->priv->fd);
2233 res = close (socket->priv->fd);
2237 int errsv = get_socket_errno ();
2242 g_set_error (error, G_IO_ERROR,
2243 socket_io_error_from_errno (errsv),
2244 _("Error closing socket: %s"),
2245 socket_strerror (errsv));
2251 socket->priv->connected = FALSE;
2252 socket->priv->closed = TRUE;
2253 if (socket->priv->remote_address)
2255 g_object_unref (socket->priv->remote_address);
2256 socket->priv->remote_address = NULL;
2263 * g_socket_is_closed:
2264 * @socket: a #GSocket
2266 * Checks whether a socket is closed.
2268 * Returns: %TRUE if socket is closed, %FALSE otherwise
2273 g_socket_is_closed (GSocket *socket)
2275 return socket->priv->closed;
2279 /* Broken source, used on errors */
2281 broken_prepare (GSource *source,
2288 broken_check (GSource *source)
2294 broken_dispatch (GSource *source,
2295 GSourceFunc callback,
2301 static GSourceFuncs broken_funcs =
2310 network_events_for_condition (GIOCondition condition)
2314 if (condition & G_IO_IN)
2315 event_mask |= (FD_READ | FD_ACCEPT);
2316 if (condition & G_IO_OUT)
2317 event_mask |= (FD_WRITE | FD_CONNECT);
2318 event_mask |= FD_CLOSE;
2324 ensure_event (GSocket *socket)
2326 if (socket->priv->event == WSA_INVALID_EVENT)
2327 socket->priv->event = WSACreateEvent();
2331 update_select_events (GSocket *socket)
2338 ensure_event (socket);
2341 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
2344 event_mask |= network_events_for_condition (*ptr);
2347 if (event_mask != socket->priv->selected_events)
2349 /* If no events selected, disable event so we can unset
2352 if (event_mask == 0)
2355 event = socket->priv->event;
2357 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
2358 socket->priv->selected_events = event_mask;
2363 add_condition_watch (GSocket *socket,
2364 GIOCondition *condition)
2366 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
2368 socket->priv->requested_conditions =
2369 g_list_prepend (socket->priv->requested_conditions, condition);
2371 update_select_events (socket);
2375 remove_condition_watch (GSocket *socket,
2376 GIOCondition *condition)
2378 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
2380 socket->priv->requested_conditions =
2381 g_list_remove (socket->priv->requested_conditions, condition);
2383 update_select_events (socket);
2387 update_condition (GSocket *socket)
2389 WSANETWORKEVENTS events;
2390 GIOCondition condition;
2392 if (WSAEnumNetworkEvents (socket->priv->fd,
2393 socket->priv->event,
2396 socket->priv->current_events |= events.lNetworkEvents;
2397 if (events.lNetworkEvents & FD_WRITE &&
2398 events.iErrorCode[FD_WRITE_BIT] != 0)
2399 socket->priv->current_errors |= FD_WRITE;
2400 if (events.lNetworkEvents & FD_CONNECT &&
2401 events.iErrorCode[FD_CONNECT_BIT] != 0)
2402 socket->priv->current_errors |= FD_CONNECT;
2406 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
2407 condition |= G_IO_IN;
2409 if (socket->priv->current_events & FD_CLOSE ||
2410 socket->priv->closed)
2411 condition |= G_IO_HUP;
2413 /* Never report both G_IO_OUT and HUP, these are
2414 mutually exclusive (can't write to a closed socket) */
2415 if ((condition & G_IO_HUP) == 0 &&
2416 socket->priv->current_events & FD_WRITE)
2418 if (socket->priv->current_errors & FD_WRITE)
2419 condition |= G_IO_ERR;
2421 condition |= G_IO_OUT;
2425 if (socket->priv->current_events & FD_CONNECT)
2427 if (socket->priv->current_errors & FD_CONNECT)
2428 condition |= (G_IO_HUP | G_IO_ERR);
2430 condition |= G_IO_OUT;
2442 GIOCondition condition;
2443 GCancellable *cancellable;
2444 GPollFD cancel_pollfd;
2445 gint64 timeout_time;
2449 socket_source_prepare (GSource *source,
2452 GSocketSource *socket_source = (GSocketSource *)source;
2454 if (g_cancellable_is_cancelled (socket_source->cancellable))
2457 if (socket_source->timeout_time)
2461 now = g_source_get_time (source);
2462 /* Round up to ensure that we don't try again too early */
2463 *timeout = (socket_source->timeout_time - now + 999) / 1000;
2466 socket_source->socket->priv->timed_out = TRUE;
2475 socket_source->pollfd.revents = update_condition (socket_source->socket);
2478 if ((socket_source->condition & socket_source->pollfd.revents) != 0)
2485 socket_source_check (GSource *source)
2489 return socket_source_prepare (source, &timeout);
2493 socket_source_dispatch (GSource *source,
2494 GSourceFunc callback,
2497 GSocketSourceFunc func = (GSocketSourceFunc)callback;
2498 GSocketSource *socket_source = (GSocketSource *)source;
2501 socket_source->pollfd.revents = update_condition (socket_source->socket);
2503 if (socket_source->socket->priv->timed_out)
2504 socket_source->pollfd.revents |= socket_source->condition & (G_IO_IN | G_IO_OUT);
2506 return (*func) (socket_source->socket,
2507 socket_source->pollfd.revents & socket_source->condition,
2512 socket_source_finalize (GSource *source)
2514 GSocketSource *socket_source = (GSocketSource *)source;
2517 socket = socket_source->socket;
2520 remove_condition_watch (socket, &socket_source->condition);
2523 g_object_unref (socket);
2525 if (socket_source->cancellable)
2527 g_cancellable_release_fd (socket_source->cancellable);
2528 g_object_unref (socket_source->cancellable);
2533 socket_source_closure_callback (GSocket *socket,
2534 GIOCondition condition,
2537 GClosure *closure = data;
2539 GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
2540 GValue result_value = G_VALUE_INIT;
2543 g_value_init (&result_value, G_TYPE_BOOLEAN);
2545 g_value_init (¶ms[0], G_TYPE_SOCKET);
2546 g_value_set_object (¶ms[0], socket);
2547 g_value_init (¶ms[1], G_TYPE_IO_CONDITION);
2548 g_value_set_flags (¶ms[1], condition);
2550 g_closure_invoke (closure, &result_value, 2, params, NULL);
2552 result = g_value_get_boolean (&result_value);
2553 g_value_unset (&result_value);
2554 g_value_unset (¶ms[0]);
2555 g_value_unset (¶ms[1]);
2560 static GSourceFuncs socket_source_funcs =
2562 socket_source_prepare,
2563 socket_source_check,
2564 socket_source_dispatch,
2565 socket_source_finalize,
2566 (GSourceFunc)socket_source_closure_callback,
2567 (GSourceDummyMarshal)g_cclosure_marshal_generic,
2571 socket_source_new (GSocket *socket,
2572 GIOCondition condition,
2573 GCancellable *cancellable)
2576 GSocketSource *socket_source;
2579 ensure_event (socket);
2581 if (socket->priv->event == WSA_INVALID_EVENT)
2583 g_warning ("Failed to create WSAEvent");
2584 return g_source_new (&broken_funcs, sizeof (GSource));
2588 condition |= G_IO_HUP | G_IO_ERR;
2590 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
2591 g_source_set_name (source, "GSocket");
2592 socket_source = (GSocketSource *)source;
2594 socket_source->socket = g_object_ref (socket);
2595 socket_source->condition = condition;
2597 if (g_cancellable_make_pollfd (cancellable,
2598 &socket_source->cancel_pollfd))
2600 socket_source->cancellable = g_object_ref (cancellable);
2601 g_source_add_poll (source, &socket_source->cancel_pollfd);
2605 add_condition_watch (socket, &socket_source->condition);
2606 socket_source->pollfd.fd = (gintptr) socket->priv->event;
2608 socket_source->pollfd.fd = socket->priv->fd;
2611 socket_source->pollfd.events = condition;
2612 socket_source->pollfd.revents = 0;
2613 g_source_add_poll (source, &socket_source->pollfd);
2615 if (socket->priv->timeout)
2616 socket_source->timeout_time = g_get_monotonic_time () +
2617 socket->priv->timeout * 1000000;
2620 socket_source->timeout_time = 0;
2626 * g_socket_create_source: (skip)
2627 * @socket: a #GSocket
2628 * @condition: a #GIOCondition mask to monitor
2629 * @cancellable: (allow-none): a %GCancellable or %NULL
2631 * Creates a %GSource that can be attached to a %GMainContext to monitor
2632 * for the availibility of the specified @condition on the socket.
2634 * The callback on the source is of the #GSocketSourceFunc type.
2636 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
2637 * these conditions will always be reported output if they are true.
2639 * @cancellable if not %NULL can be used to cancel the source, which will
2640 * cause the source to trigger, reporting the current condition (which
2641 * is likely 0 unless cancellation happened at the same time as a
2642 * condition change). You can check for this in the callback using
2643 * g_cancellable_is_cancelled().
2645 * If @socket has a timeout set, and it is reached before @condition
2646 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
2647 * %G_IO_OUT depending on @condition. However, @socket will have been
2648 * marked as having had a timeout, and so the next #GSocket I/O method
2649 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
2651 * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
2656 g_socket_create_source (GSocket *socket,
2657 GIOCondition condition,
2658 GCancellable *cancellable)
2660 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
2662 return socket_source_new (socket, condition, cancellable);
2666 * g_socket_condition_check:
2667 * @socket: a #GSocket
2668 * @condition: a #GIOCondition mask to check
2670 * Checks on the readiness of @socket to perform operations.
2671 * The operations specified in @condition are checked for and masked
2672 * against the currently-satisfied conditions on @socket. The result
2675 * Note that on Windows, it is possible for an operation to return
2676 * %G_IO_ERROR_WOULD_BLOCK even immediately after
2677 * g_socket_condition_check() has claimed that the socket is ready for
2678 * writing. Rather than calling g_socket_condition_check() and then
2679 * writing to the socket if it succeeds, it is generally better to
2680 * simply try writing to the socket right away, and try again later if
2681 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
2683 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2684 * these conditions will always be set in the output if they are true.
2686 * This call never blocks.
2688 * Returns: the @GIOCondition mask of the current state
2693 g_socket_condition_check (GSocket *socket,
2694 GIOCondition condition)
2696 if (!check_socket (socket, NULL))
2701 GIOCondition current_condition;
2703 condition |= G_IO_ERR | G_IO_HUP;
2705 add_condition_watch (socket, &condition);
2706 current_condition = update_condition (socket);
2707 remove_condition_watch (socket, &condition);
2708 return condition & current_condition;
2714 poll_fd.fd = socket->priv->fd;
2715 poll_fd.events = condition;
2718 result = g_poll (&poll_fd, 1, 0);
2719 while (result == -1 && get_socket_errno () == EINTR);
2721 return poll_fd.revents;
2727 * g_socket_condition_wait:
2728 * @socket: a #GSocket
2729 * @condition: a #GIOCondition mask to wait for
2730 * @cancellable: (allow-none): a #GCancellable, or %NULL
2731 * @error: a #GError pointer, or %NULL
2733 * Waits for @condition to become true on @socket. When the condition
2734 * is met, %TRUE is returned.
2736 * If @cancellable is cancelled before the condition is met, or if the
2737 * socket has a timeout set and it is reached before the condition is
2738 * met, then %FALSE is returned and @error, if non-%NULL, is set to
2739 * the appropriate value (%G_IO_ERROR_CANCELLED or
2740 * %G_IO_ERROR_TIMED_OUT).
2742 * Returns: %TRUE if the condition was met, %FALSE otherwise
2747 g_socket_condition_wait (GSocket *socket,
2748 GIOCondition condition,
2749 GCancellable *cancellable,
2752 if (!check_socket (socket, error))
2755 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2760 GIOCondition current_condition;
2766 /* Always check these */
2767 condition |= G_IO_ERR | G_IO_HUP;
2769 add_condition_watch (socket, &condition);
2772 events[num_events++] = socket->priv->event;
2774 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
2775 events[num_events++] = (WSAEVENT)cancel_fd.fd;
2777 if (socket->priv->timeout)
2778 timeout = socket->priv->timeout * 1000;
2780 timeout = WSA_INFINITE;
2782 current_condition = update_condition (socket);
2783 while ((condition & current_condition) == 0)
2785 res = WSAWaitForMultipleEvents(num_events, events,
2786 FALSE, timeout, FALSE);
2787 if (res == WSA_WAIT_FAILED)
2789 int errsv = get_socket_errno ();
2791 g_set_error (error, G_IO_ERROR,
2792 socket_io_error_from_errno (errsv),
2793 _("Waiting for socket condition: %s"),
2794 socket_strerror (errsv));
2797 else if (res == WSA_WAIT_TIMEOUT)
2799 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
2800 _("Socket I/O timed out"));
2804 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2807 current_condition = update_condition (socket);
2809 remove_condition_watch (socket, &condition);
2811 g_cancellable_release_fd (cancellable);
2813 return (condition & current_condition) != 0;
2822 poll_fd[0].fd = socket->priv->fd;
2823 poll_fd[0].events = condition;
2826 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
2829 if (socket->priv->timeout)
2830 timeout = socket->priv->timeout * 1000;
2835 result = g_poll (poll_fd, num, timeout);
2836 while (result == -1 && get_socket_errno () == EINTR);
2839 g_cancellable_release_fd (cancellable);
2843 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
2844 _("Socket I/O timed out"));
2848 return !g_cancellable_set_error_if_cancelled (cancellable, error);
2854 * g_socket_send_message:
2855 * @socket: a #GSocket
2856 * @address: a #GSocketAddress, or %NULL
2857 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
2858 * @num_vectors: the number of elements in @vectors, or -1
2859 * @messages: (array length=num_messages) (allow-none): a pointer to an
2860 * array of #GSocketControlMessages, or %NULL.
2861 * @num_messages: number of elements in @messages, or -1.
2862 * @flags: an int containing #GSocketMsgFlags flags
2863 * @cancellable: (allow-none): a %GCancellable or %NULL
2864 * @error: #GError for error reporting, or %NULL to ignore.
2866 * Send data to @address on @socket. This is the most complicated and
2867 * fully-featured version of this call. For easier use, see
2868 * g_socket_send() and g_socket_send_to().
2870 * If @address is %NULL then the message is sent to the default receiver
2871 * (set by g_socket_connect()).
2873 * @vectors must point to an array of #GOutputVector structs and
2874 * @num_vectors must be the length of this array. (If @num_vectors is -1,
2875 * then @vectors is assumed to be terminated by a #GOutputVector with a
2876 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
2877 * that the sent data will be gathered from. Using multiple
2878 * #GOutputVector<!-- -->s is more memory-efficient than manually copying
2879 * data from multiple sources into a single buffer, and more
2880 * network-efficient than making multiple calls to g_socket_send().
2882 * @messages, if non-%NULL, is taken to point to an array of @num_messages
2883 * #GSocketControlMessage instances. These correspond to the control
2884 * messages to be sent on the socket.
2885 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
2888 * @flags modify how the message is sent. The commonly available arguments
2889 * for this are available in the #GSocketMsgFlags enum, but the
2890 * values there are the same as the system values, and the flags
2891 * are passed in as-is, so you can pass in system-specific flags too.
2893 * If the socket is in blocking mode the call will block until there is
2894 * space for the data in the socket queue. If there is no space available
2895 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2896 * will be returned. To be notified when space is available, wait for the
2897 * %G_IO_OUT condition. Note though that you may still receive
2898 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2899 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2900 * very common due to the way the underlying APIs work.)
2902 * On error -1 is returned and @error is set accordingly.
2904 * Returns: Number of bytes written (which may be less than @size), or -1
2910 g_socket_send_message (GSocket *socket,
2911 GSocketAddress *address,
2912 GOutputVector *vectors,
2914 GSocketControlMessage **messages,
2917 GCancellable *cancellable,
2920 GOutputVector one_vector;
2923 if (!check_socket (socket, error))
2926 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2929 if (num_vectors == -1)
2931 for (num_vectors = 0;
2932 vectors[num_vectors].buffer != NULL;
2937 if (num_messages == -1)
2939 for (num_messages = 0;
2940 messages != NULL && messages[num_messages] != NULL;
2945 if (num_vectors == 0)
2949 one_vector.buffer = &zero;
2950 one_vector.size = 1;
2952 vectors = &one_vector;
2965 msg.msg_namelen = g_socket_address_get_native_size (address);
2966 msg.msg_name = g_alloca (msg.msg_namelen);
2967 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
2972 msg.msg_name = NULL;
2973 msg.msg_namelen = 0;
2978 /* this entire expression will be evaluated at compile time */
2979 if (sizeof *msg.msg_iov == sizeof *vectors &&
2980 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2981 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2982 G_STRUCT_OFFSET (GOutputVector, buffer) &&
2983 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2984 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2985 G_STRUCT_OFFSET (GOutputVector, size))
2986 /* ABI is compatible */
2988 msg.msg_iov = (struct iovec *) vectors;
2989 msg.msg_iovlen = num_vectors;
2992 /* ABI is incompatible */
2996 msg.msg_iov = g_newa (struct iovec, num_vectors);
2997 for (i = 0; i < num_vectors; i++)
2999 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
3000 msg.msg_iov[i].iov_len = vectors[i].size;
3002 msg.msg_iovlen = num_vectors;
3008 struct cmsghdr *cmsg;
3011 msg.msg_controllen = 0;
3012 for (i = 0; i < num_messages; i++)
3013 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
3015 if (msg.msg_controllen == 0)
3016 msg.msg_control = NULL;
3019 msg.msg_control = g_alloca (msg.msg_controllen);
3020 memset (msg.msg_control, '\0', msg.msg_controllen);
3023 cmsg = CMSG_FIRSTHDR (&msg);
3024 for (i = 0; i < num_messages; i++)
3026 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
3027 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
3028 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
3029 g_socket_control_message_serialize (messages[i],
3031 cmsg = CMSG_NXTHDR (&msg, cmsg);
3033 g_assert (cmsg == NULL);
3038 if (socket->priv->blocking &&
3039 !g_socket_condition_wait (socket,
3040 G_IO_OUT, cancellable, error))
3043 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
3046 int errsv = get_socket_errno ();
3051 if (socket->priv->blocking &&
3052 (errsv == EWOULDBLOCK ||
3056 g_set_error (error, G_IO_ERROR,
3057 socket_io_error_from_errno (errsv),
3058 _("Error sending message: %s"), socket_strerror (errsv));
3069 struct sockaddr_storage addr;
3076 /* Win32 doesn't support control messages.
3077 Actually this is possible for raw and datagram sockets
3078 via WSASendMessage on Vista or later, but that doesn't
3080 if (num_messages != 0)
3082 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
3083 _("GSocketControlMessage not supported on windows"));
3088 bufs = g_newa (WSABUF, num_vectors);
3089 for (i = 0; i < num_vectors; i++)
3091 bufs[i].buf = (char *)vectors[i].buffer;
3092 bufs[i].len = (gulong)vectors[i].size;
3096 addrlen = 0; /* Avoid warning */
3099 addrlen = g_socket_address_get_native_size (address);
3100 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
3106 if (socket->priv->blocking &&
3107 !g_socket_condition_wait (socket,
3108 G_IO_OUT, cancellable, error))
3112 result = WSASendTo (socket->priv->fd,
3115 (const struct sockaddr *)&addr, addrlen,
3118 result = WSASend (socket->priv->fd,
3125 int errsv = get_socket_errno ();
3127 if (errsv == WSAEINTR)
3130 if (errsv == WSAEWOULDBLOCK)
3131 win32_unset_event_mask (socket, FD_WRITE);
3133 if (socket->priv->blocking &&
3134 errsv == WSAEWOULDBLOCK)
3137 g_set_error (error, G_IO_ERROR,
3138 socket_io_error_from_errno (errsv),
3139 _("Error sending message: %s"), socket_strerror (errsv));
3152 * g_socket_receive_message:
3153 * @socket: a #GSocket
3154 * @address: a pointer to a #GSocketAddress pointer, or %NULL
3155 * @vectors: (array length=num_vectors): an array of #GInputVector structs
3156 * @num_vectors: the number of elements in @vectors, or -1
3157 * @messages: (array length=num_messages) (allow-none): a pointer which
3158 * may be filled with an array of #GSocketControlMessages, or %NULL
3159 * @num_messages: a pointer which will be filled with the number of
3160 * elements in @messages, or %NULL
3161 * @flags: a pointer to an int containing #GSocketMsgFlags flags
3162 * @cancellable: (allow-none): a %GCancellable or %NULL
3163 * @error: a #GError pointer, or %NULL
3165 * Receive data from a socket. This is the most complicated and
3166 * fully-featured version of this call. For easier use, see
3167 * g_socket_receive() and g_socket_receive_from().
3169 * If @address is non-%NULL then @address will be set equal to the
3170 * source address of the received packet.
3171 * @address is owned by the caller.
3173 * @vector must point to an array of #GInputVector structs and
3174 * @num_vectors must be the length of this array. These structs
3175 * describe the buffers that received data will be scattered into.
3176 * If @num_vectors is -1, then @vectors is assumed to be terminated
3177 * by a #GInputVector with a %NULL buffer pointer.
3179 * As a special case, if @num_vectors is 0 (in which case, @vectors
3180 * may of course be %NULL), then a single byte is received and
3181 * discarded. This is to facilitate the common practice of sending a
3182 * single '\0' byte for the purposes of transferring ancillary data.
3184 * @messages, if non-%NULL, will be set to point to a newly-allocated
3185 * array of #GSocketControlMessage instances or %NULL if no such
3186 * messages was received. These correspond to the control messages
3187 * received from the kernel, one #GSocketControlMessage per message
3188 * from the kernel. This array is %NULL-terminated and must be freed
3189 * by the caller using g_free() after calling g_object_unref() on each
3190 * element. If @messages is %NULL, any control messages received will
3193 * @num_messages, if non-%NULL, will be set to the number of control
3194 * messages received.
3196 * If both @messages and @num_messages are non-%NULL, then
3197 * @num_messages gives the number of #GSocketControlMessage instances
3198 * in @messages (ie: not including the %NULL terminator).
3200 * @flags is an in/out parameter. The commonly available arguments
3201 * for this are available in the #GSocketMsgFlags enum, but the
3202 * values there are the same as the system values, and the flags
3203 * are passed in as-is, so you can pass in system-specific flags too
3204 * (and g_socket_receive_message() may pass system-specific flags out).
3206 * As with g_socket_receive(), data may be discarded if @socket is
3207 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
3208 * provide enough buffer space to read a complete message. You can pass
3209 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
3210 * removing it from the receive queue, but there is no portable way to find
3211 * out the length of the message other than by reading it into a
3212 * sufficiently-large buffer.
3214 * If the socket is in blocking mode the call will block until there
3215 * is some data to receive, the connection is closed, or there is an
3216 * error. If there is no data available and the socket is in
3217 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
3218 * returned. To be notified when data is available, wait for the
3219 * %G_IO_IN condition.
3221 * On error -1 is returned and @error is set accordingly.
3223 * Returns: Number of bytes read, or 0 if the connection was closed by
3224 * the peer, or -1 on error
3229 g_socket_receive_message (GSocket *socket,
3230 GSocketAddress **address,
3231 GInputVector *vectors,
3233 GSocketControlMessage ***messages,
3236 GCancellable *cancellable,
3239 GInputVector one_vector;
3242 if (!check_socket (socket, error))
3245 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3248 if (num_vectors == -1)
3250 for (num_vectors = 0;
3251 vectors[num_vectors].buffer != NULL;
3256 if (num_vectors == 0)
3258 one_vector.buffer = &one_byte;
3259 one_vector.size = 1;
3261 vectors = &one_vector;
3268 struct sockaddr_storage one_sockaddr;
3273 msg.msg_name = &one_sockaddr;
3274 msg.msg_namelen = sizeof (struct sockaddr_storage);
3278 msg.msg_name = NULL;
3279 msg.msg_namelen = 0;
3283 /* this entire expression will be evaluated at compile time */
3284 if (sizeof *msg.msg_iov == sizeof *vectors &&
3285 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3286 G_STRUCT_OFFSET (struct iovec, iov_base) ==
3287 G_STRUCT_OFFSET (GInputVector, buffer) &&
3288 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3289 G_STRUCT_OFFSET (struct iovec, iov_len) ==
3290 G_STRUCT_OFFSET (GInputVector, size))
3291 /* ABI is compatible */
3293 msg.msg_iov = (struct iovec *) vectors;
3294 msg.msg_iovlen = num_vectors;
3297 /* ABI is incompatible */
3301 msg.msg_iov = g_newa (struct iovec, num_vectors);
3302 for (i = 0; i < num_vectors; i++)
3304 msg.msg_iov[i].iov_base = vectors[i].buffer;
3305 msg.msg_iov[i].iov_len = vectors[i].size;
3307 msg.msg_iovlen = num_vectors;
3311 msg.msg_control = g_alloca (2048);
3312 msg.msg_controllen = 2048;
3316 msg.msg_flags = *flags;
3320 /* We always set the close-on-exec flag so we don't leak file
3321 * descriptors into child processes. Note that gunixfdmessage.c
3322 * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
3324 #ifdef MSG_CMSG_CLOEXEC
3325 msg.msg_flags |= MSG_CMSG_CLOEXEC;
3331 if (socket->priv->blocking &&
3332 !g_socket_condition_wait (socket,
3333 G_IO_IN, cancellable, error))
3336 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
3337 #ifdef MSG_CMSG_CLOEXEC
3338 if (result < 0 && get_socket_errno () == EINVAL)
3340 /* We must be running on an old kernel. Call without the flag. */
3341 msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
3342 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
3348 int errsv = get_socket_errno ();
3353 if (socket->priv->blocking &&
3354 (errsv == EWOULDBLOCK ||
3358 g_set_error (error, G_IO_ERROR,
3359 socket_io_error_from_errno (errsv),
3360 _("Error receiving message: %s"), socket_strerror (errsv));
3367 /* decode address */
3368 if (address != NULL)
3370 if (msg.msg_namelen > 0)
3371 *address = g_socket_address_new_from_native (msg.msg_name,
3377 /* decode control messages */
3379 GPtrArray *my_messages = NULL;
3380 struct cmsghdr *cmsg;
3382 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
3384 GSocketControlMessage *message;
3386 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
3388 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
3390 if (message == NULL)
3391 /* We've already spewed about the problem in the
3392 deserialization code, so just continue */
3395 if (messages == NULL)
3397 /* we have to do it this way if the user ignores the
3398 * messages so that we will close any received fds.
3400 g_object_unref (message);
3404 if (my_messages == NULL)
3405 my_messages = g_ptr_array_new ();
3406 g_ptr_array_add (my_messages, message);
3411 *num_messages = my_messages != NULL ? my_messages->len : 0;
3415 if (my_messages == NULL)
3421 g_ptr_array_add (my_messages, NULL);
3422 *messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
3427 g_assert (my_messages == NULL);
3431 /* capture the flags */
3433 *flags = msg.msg_flags;
3439 struct sockaddr_storage addr;
3441 DWORD bytes_received;
3448 bufs = g_newa (WSABUF, num_vectors);
3449 for (i = 0; i < num_vectors; i++)
3451 bufs[i].buf = (char *)vectors[i].buffer;
3452 bufs[i].len = (gulong)vectors[i].size;
3464 if (socket->priv->blocking &&
3465 !g_socket_condition_wait (socket,
3466 G_IO_IN, cancellable, error))
3469 addrlen = sizeof addr;
3471 result = WSARecvFrom (socket->priv->fd,
3473 &bytes_received, &win_flags,
3474 (struct sockaddr *)&addr, &addrlen,
3477 result = WSARecv (socket->priv->fd,
3479 &bytes_received, &win_flags,
3483 int errsv = get_socket_errno ();
3485 if (errsv == WSAEINTR)
3488 win32_unset_event_mask (socket, FD_READ);
3490 if (socket->priv->blocking &&
3491 errsv == WSAEWOULDBLOCK)
3494 g_set_error (error, G_IO_ERROR,
3495 socket_io_error_from_errno (errsv),
3496 _("Error receiving message: %s"), socket_strerror (errsv));
3500 win32_unset_event_mask (socket, FD_READ);
3504 /* decode address */
3505 if (address != NULL)
3508 *address = g_socket_address_new_from_native (&addr, addrlen);
3513 /* capture the flags */
3517 if (messages != NULL)
3519 if (num_messages != NULL)
3522 return bytes_received;
3528 * g_socket_get_credentials:
3529 * @socket: a #GSocket.
3530 * @error: #GError for error reporting, or %NULL to ignore.
3532 * Returns the credentials of the foreign process connected to this
3533 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
3536 * If this operation isn't supported on the OS, the method fails with
3537 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
3538 * by reading the %SO_PEERCRED option on the underlying socket.
3540 * Other ways to obtain credentials from a foreign peer includes the
3541 * #GUnixCredentialsMessage type and
3542 * g_unix_connection_send_credentials() /
3543 * g_unix_connection_receive_credentials() functions.
3545 * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
3546 * that must be freed with g_object_unref().
3551 g_socket_get_credentials (GSocket *socket,
3556 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
3557 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3561 #if defined(__linux__) || defined(__OpenBSD__)
3564 #if defined(__linux__)
3565 struct ucred native_creds;
3566 optlen = sizeof (struct ucred);
3567 #elif defined(__OpenBSD__)
3568 struct sockpeercred native_creds;
3569 optlen = sizeof (struct sockpeercred);
3571 if (getsockopt (socket->priv->fd,
3574 (void *)&native_creds,
3577 int errsv = get_socket_errno ();
3580 socket_io_error_from_errno (errsv),
3581 _("Unable to get pending error: %s"),
3582 socket_strerror (errsv));
3586 ret = g_credentials_new ();
3587 g_credentials_set_native (ret,
3588 #if defined(__linux__)
3589 G_CREDENTIALS_TYPE_LINUX_UCRED,
3590 #elif defined(__OpenBSD__)
3591 G_CREDENTIALS_TYPE_OPENBSD_SOCKPEERCRED,
3597 g_set_error_literal (error,
3599 G_IO_ERROR_NOT_SUPPORTED,
3600 _("g_socket_get_credentials not implemented for this OS"));