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>
46 #include "gcancellable.h"
47 #include "gioenumtypes.h"
48 #include "ginetaddress.h"
49 #include "ginitable.h"
53 #include "gnetworkingprivate.h"
54 #include "gsocketaddress.h"
55 #include "gsocketcontrolmessage.h"
56 #include "gcredentials.h"
61 * @short_description: Low-level socket object
63 * @see_also: #GInitable
65 * A #GSocket is a low-level networking primitive. It is a more or less
66 * direct mapping of the BSD socket API in a portable GObject based API.
67 * It supports both the UNIX socket implementations and winsock2 on Windows.
69 * #GSocket is the platform independent base upon which the higher level
70 * network primitives are based. Applications are not typically meant to
71 * use it directly, but rather through classes like #GSocketClient,
72 * #GSocketService and #GSocketConnection. However there may be cases where
73 * direct use of #GSocket is useful.
75 * #GSocket implements the #GInitable interface, so if it is manually constructed
76 * by e.g. g_object_new() you must call g_initable_init() and check the
77 * results before using the object. This is done automatically in
78 * g_socket_new() and g_socket_new_from_fd(), so these functions can return
81 * Sockets operate in two general modes, blocking or non-blocking. When
82 * in blocking mode all operations block until the requested operation
83 * is finished or there is an error. In non-blocking mode all calls that
84 * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
85 * To know when a call would successfully run you can call g_socket_condition_check(),
86 * or g_socket_condition_wait(). You can also use g_socket_create_source() and
87 * attach it to a #GMainContext to get callbacks when I/O is possible.
88 * Note that all sockets are always set to non blocking mode in the system, and
89 * blocking mode is emulated in GSocket.
91 * When working in non-blocking mode applications should always be able to
92 * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
93 * function said that I/O was possible. This can easily happen in case
94 * of a race condition in the application, but it can also happen for other
95 * reasons. For instance, on Windows a socket is always seen as writable
96 * until a write returns %G_IO_ERROR_WOULD_BLOCK.
98 * #GSocket<!-- -->s can be either connection oriented or datagram based.
99 * For connection oriented types you must first establish a connection by
100 * either connecting to an address or accepting a connection from another
101 * address. For connectionless socket types the target/source address is
102 * specified or received in each I/O operation.
104 * All socket file descriptors are set to be close-on-exec.
106 * Note that creating a #GSocket causes the signal %SIGPIPE to be
107 * ignored for the remainder of the program. If you are writing a
108 * command-line utility that uses #GSocket, you may need to take into
109 * account the fact that your program will not automatically be killed
110 * if it tries to write to %stdout after it has been closed.
115 static void g_socket_initable_iface_init (GInitableIface *iface);
116 static gboolean g_socket_initable_init (GInitable *initable,
117 GCancellable *cancellable,
120 G_DEFINE_TYPE_WITH_CODE (GSocket, g_socket, G_TYPE_OBJECT,
121 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
122 g_socket_initable_iface_init));
139 struct _GSocketPrivate
141 GSocketFamily family;
143 GSocketProtocol protocol;
147 GError *construct_error;
160 GList *requested_conditions; /* list of requested GIOCondition * */
165 get_socket_errno (void)
170 return WSAGetLastError ();
175 socket_io_error_from_errno (int err)
178 return g_io_error_from_errno (err);
183 return G_IO_ERROR_ADDRESS_IN_USE;
185 return G_IO_ERROR_WOULD_BLOCK;
187 return G_IO_ERROR_PERMISSION_DENIED;
188 case WSA_INVALID_HANDLE:
189 case WSA_INVALID_PARAMETER:
192 return G_IO_ERROR_INVALID_ARGUMENT;
193 case WSAEPROTONOSUPPORT:
194 return G_IO_ERROR_NOT_SUPPORTED;
196 return G_IO_ERROR_CANCELLED;
197 case WSAESOCKTNOSUPPORT:
199 case WSAEPFNOSUPPORT:
200 case WSAEAFNOSUPPORT:
201 return G_IO_ERROR_NOT_SUPPORTED;
203 return G_IO_ERROR_FAILED;
209 socket_strerror (int err)
212 return g_strerror (err);
214 static GStaticPrivate last_msg = G_STATIC_PRIVATE_INIT;
217 msg = g_win32_error_message (err);
218 g_static_private_set (&last_msg, msg, g_free);
225 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
227 _win32_unset_event_mask (GSocket *socket, int mask)
229 socket->priv->current_events &= ~mask;
230 socket->priv->current_errors &= ~mask;
233 #define win32_unset_event_mask(_socket, _mask)
237 set_fd_nonblocking (int fd)
246 if ((arg = fcntl (fd, F_GETFL, NULL)) < 0)
248 g_warning ("Error getting socket status flags: %s", socket_strerror (errno));
252 arg = arg | O_NONBLOCK;
254 if (fcntl (fd, F_SETFL, arg) < 0)
255 g_warning ("Error setting socket status flags: %s", socket_strerror (errno));
259 if (ioctlsocket (fd, FIONBIO, &arg) == SOCKET_ERROR)
261 int errsv = get_socket_errno ();
262 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
268 check_socket (GSocket *socket,
271 if (!socket->priv->inited)
273 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
274 _("Invalid socket, not initialized"));
278 if (socket->priv->construct_error)
280 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
281 _("Invalid socket, initialization failed due to: %s"),
282 socket->priv->construct_error->message);
286 if (socket->priv->closed)
288 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
289 _("Socket is already closed"));
293 if (socket->priv->timed_out)
295 socket->priv->timed_out = FALSE;
296 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
297 _("Socket I/O timed out"));
305 g_socket_details_from_fd (GSocket *socket)
307 struct sockaddr_storage address;
314 /* See bug #611756 */
315 BOOL bool_val = FALSE;
320 fd = socket->priv->fd;
321 optlen = sizeof value;
322 if (getsockopt (fd, SOL_SOCKET, SO_TYPE, (void *)&value, &optlen) != 0)
324 errsv = get_socket_errno ();
335 /* programmer error */
336 g_error ("creating GSocket from fd %d: %s\n",
337 fd, socket_strerror (errsv));
345 g_assert (optlen == sizeof value);
349 socket->priv->type = G_SOCKET_TYPE_STREAM;
353 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
357 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
361 socket->priv->type = G_SOCKET_TYPE_INVALID;
365 addrlen = sizeof address;
366 if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
368 errsv = get_socket_errno ();
372 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
373 sizeof address.ss_family <= addrlen);
374 switch (address.ss_family)
376 case G_SOCKET_FAMILY_IPV4:
377 case G_SOCKET_FAMILY_IPV6:
378 case G_SOCKET_FAMILY_UNIX:
379 socket->priv->family = address.ss_family;
383 socket->priv->family = G_SOCKET_FAMILY_INVALID;
387 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
389 addrlen = sizeof address;
390 if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
391 socket->priv->connected = TRUE;
394 optlen = sizeof bool_val;
395 if (getsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
396 (void *)&bool_val, &optlen) == 0)
399 /* Experimentation indicates that the SO_KEEPALIVE value is
400 * actually a char on Windows, even if documentation claims it
401 * to be a BOOL which is a typedef for int. So this g_assert()
402 * fails. See bug #611756.
404 g_assert (optlen == sizeof bool_val);
406 socket->priv->keepalive = !!bool_val;
410 /* Can't read, maybe not supported, assume FALSE */
411 socket->priv->keepalive = FALSE;
417 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
418 socket_io_error_from_errno (errsv),
419 _("creating GSocket from fd: %s"),
420 socket_strerror (errsv));
424 g_socket_create_socket (GSocketFamily family,
434 case G_SOCKET_TYPE_STREAM:
435 native_type = SOCK_STREAM;
438 case G_SOCKET_TYPE_DATAGRAM:
439 native_type = SOCK_DGRAM;
442 case G_SOCKET_TYPE_SEQPACKET:
443 native_type = SOCK_SEQPACKET;
447 g_assert_not_reached ();
452 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
453 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
458 fd = socket (family, native_type | SOCK_CLOEXEC, protocol);
459 /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
460 if (fd < 0 && errno == EINVAL)
462 fd = socket (family, native_type, protocol);
466 int errsv = get_socket_errno ();
468 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
469 _("Unable to create socket: %s"), socket_strerror (errsv));
476 /* We always want to set close-on-exec to protect users. If you
477 need to so some weird inheritance to exec you can re-enable this
478 using lower level hacks with g_socket_get_fd(). */
479 flags = fcntl (fd, F_GETFD, 0);
481 (flags & FD_CLOEXEC) == 0)
484 fcntl (fd, F_SETFD, flags);
493 g_socket_constructed (GObject *object)
495 GSocket *socket = G_SOCKET (object);
497 if (socket->priv->fd >= 0)
498 /* create socket->priv info from the fd */
499 g_socket_details_from_fd (socket);
502 /* create the fd from socket->priv info */
503 socket->priv->fd = g_socket_create_socket (socket->priv->family,
505 socket->priv->protocol,
506 &socket->priv->construct_error);
508 /* Always use native nonblocking sockets, as
509 windows sets sockets to nonblocking automatically
510 in certain operations. This way we make things work
511 the same on all platforms */
512 if (socket->priv->fd != -1)
513 set_fd_nonblocking (socket->priv->fd);
517 g_socket_get_property (GObject *object,
522 GSocket *socket = G_SOCKET (object);
523 GSocketAddress *address;
528 g_value_set_enum (value, socket->priv->family);
532 g_value_set_enum (value, socket->priv->type);
536 g_value_set_enum (value, socket->priv->protocol);
540 g_value_set_int (value, socket->priv->fd);
544 g_value_set_boolean (value, socket->priv->blocking);
547 case PROP_LISTEN_BACKLOG:
548 g_value_set_int (value, socket->priv->listen_backlog);
552 g_value_set_boolean (value, socket->priv->keepalive);
555 case PROP_LOCAL_ADDRESS:
556 address = g_socket_get_local_address (socket, NULL);
557 g_value_take_object (value, address);
560 case PROP_REMOTE_ADDRESS:
561 address = g_socket_get_remote_address (socket, NULL);
562 g_value_take_object (value, address);
566 g_value_set_uint (value, socket->priv->timeout);
570 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
575 g_socket_set_property (GObject *object,
580 GSocket *socket = G_SOCKET (object);
585 socket->priv->family = g_value_get_enum (value);
589 socket->priv->type = g_value_get_enum (value);
593 socket->priv->protocol = g_value_get_enum (value);
597 socket->priv->fd = g_value_get_int (value);
601 g_socket_set_blocking (socket, g_value_get_boolean (value));
604 case PROP_LISTEN_BACKLOG:
605 g_socket_set_listen_backlog (socket, g_value_get_int (value));
609 g_socket_set_keepalive (socket, g_value_get_boolean (value));
613 g_socket_set_timeout (socket, g_value_get_uint (value));
617 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
622 g_socket_finalize (GObject *object)
624 GSocket *socket = G_SOCKET (object);
626 g_clear_error (&socket->priv->construct_error);
628 if (socket->priv->fd != -1 &&
629 !socket->priv->closed)
630 g_socket_close (socket, NULL);
633 if (socket->priv->event != WSA_INVALID_EVENT)
635 WSACloseEvent (socket->priv->event);
636 socket->priv->event = WSA_INVALID_EVENT;
639 g_assert (socket->priv->requested_conditions == NULL);
642 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
643 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
647 g_socket_class_init (GSocketClass *klass)
649 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
652 /* Make sure winsock has been initialized */
653 type = g_inet_address_get_type ();
656 /* There is no portable, thread-safe way to avoid having the process
657 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
658 * forced to simply ignore the signal process-wide.
660 signal (SIGPIPE, SIG_IGN);
663 g_type_class_add_private (klass, sizeof (GSocketPrivate));
665 gobject_class->finalize = g_socket_finalize;
666 gobject_class->constructed = g_socket_constructed;
667 gobject_class->set_property = g_socket_set_property;
668 gobject_class->get_property = g_socket_get_property;
670 g_object_class_install_property (gobject_class, PROP_FAMILY,
671 g_param_spec_enum ("family",
673 P_("The sockets address family"),
674 G_TYPE_SOCKET_FAMILY,
675 G_SOCKET_FAMILY_INVALID,
676 G_PARAM_CONSTRUCT_ONLY |
678 G_PARAM_STATIC_STRINGS));
680 g_object_class_install_property (gobject_class, PROP_TYPE,
681 g_param_spec_enum ("type",
683 P_("The sockets type"),
685 G_SOCKET_TYPE_STREAM,
686 G_PARAM_CONSTRUCT_ONLY |
688 G_PARAM_STATIC_STRINGS));
690 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
691 g_param_spec_enum ("protocol",
692 P_("Socket protocol"),
693 P_("The id of the protocol to use, or -1 for unknown"),
694 G_TYPE_SOCKET_PROTOCOL,
695 G_SOCKET_PROTOCOL_UNKNOWN,
696 G_PARAM_CONSTRUCT_ONLY |
698 G_PARAM_STATIC_STRINGS));
700 g_object_class_install_property (gobject_class, PROP_FD,
701 g_param_spec_int ("fd",
702 P_("File descriptor"),
703 P_("The sockets file descriptor"),
707 G_PARAM_CONSTRUCT_ONLY |
709 G_PARAM_STATIC_STRINGS));
711 g_object_class_install_property (gobject_class, PROP_BLOCKING,
712 g_param_spec_boolean ("blocking",
714 P_("Whether or not I/O on this socket is blocking"),
717 G_PARAM_STATIC_STRINGS));
719 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
720 g_param_spec_int ("listen-backlog",
721 P_("Listen backlog"),
722 P_("Outstanding connections in the listen queue"),
727 G_PARAM_STATIC_STRINGS));
729 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
730 g_param_spec_boolean ("keepalive",
731 P_("Keep connection alive"),
732 P_("Keep connection alive by sending periodic pings"),
735 G_PARAM_STATIC_STRINGS));
737 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
738 g_param_spec_object ("local-address",
740 P_("The local address the socket is bound to"),
741 G_TYPE_SOCKET_ADDRESS,
743 G_PARAM_STATIC_STRINGS));
745 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
746 g_param_spec_object ("remote-address",
747 P_("Remote address"),
748 P_("The remote address the socket is connected to"),
749 G_TYPE_SOCKET_ADDRESS,
751 G_PARAM_STATIC_STRINGS));
756 * The timeout in seconds on socket I/O
760 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
761 g_param_spec_uint ("timeout",
763 P_("The timeout in seconds on socket I/O"),
768 G_PARAM_STATIC_STRINGS));
772 g_socket_initable_iface_init (GInitableIface *iface)
774 iface->init = g_socket_initable_init;
778 g_socket_init (GSocket *socket)
780 socket->priv = G_TYPE_INSTANCE_GET_PRIVATE (socket, G_TYPE_SOCKET, GSocketPrivate);
782 socket->priv->fd = -1;
783 socket->priv->blocking = TRUE;
784 socket->priv->listen_backlog = 10;
785 socket->priv->construct_error = NULL;
787 socket->priv->event = WSA_INVALID_EVENT;
792 g_socket_initable_init (GInitable *initable,
793 GCancellable *cancellable,
798 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
800 socket = G_SOCKET (initable);
802 if (cancellable != NULL)
804 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
805 _("Cancellable initialization not supported"));
809 socket->priv->inited = TRUE;
811 if (socket->priv->construct_error)
814 *error = g_error_copy (socket->priv->construct_error);
824 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
825 * @type: the socket type to use.
826 * @protocol: the id of the protocol to use, or 0 for default.
827 * @error: #GError for error reporting, or %NULL to ignore.
829 * Creates a new #GSocket with the defined family, type and protocol.
830 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
831 * for the family and type is used.
833 * The @protocol is a family and type specific int that specifies what
834 * kind of protocol to use. #GSocketProtocol lists several common ones.
835 * Many families only support one protocol, and use 0 for this, others
836 * support several and using 0 means to use the default protocol for
837 * the family and type.
839 * The protocol id is passed directly to the operating
840 * system, so you can use protocols not listed in #GSocketProtocol if you
841 * know the protocol number used for it.
843 * Returns: a #GSocket or %NULL on error.
844 * Free the returned object with g_object_unref().
849 g_socket_new (GSocketFamily family,
851 GSocketProtocol protocol,
854 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
858 "protocol", protocol,
863 * g_socket_new_from_fd:
864 * @fd: a native socket file descriptor.
865 * @error: #GError for error reporting, or %NULL to ignore.
867 * Creates a new #GSocket from a native file descriptor
868 * or winsock SOCKET handle.
870 * This reads all the settings from the file descriptor so that
871 * all properties should work. Note that the file descriptor
872 * will be set to non-blocking mode, independent on the blocking
873 * mode of the #GSocket.
875 * Returns: a #GSocket or %NULL on error.
876 * Free the returned object with g_object_unref().
881 g_socket_new_from_fd (gint fd,
884 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
891 * g_socket_set_blocking:
892 * @socket: a #GSocket.
893 * @blocking: Whether to use blocking I/O or not.
895 * Sets the blocking mode of the socket. In blocking mode
896 * all operations block until they succeed or there is an error. In
897 * non-blocking mode all functions return results immediately or
898 * with a %G_IO_ERROR_WOULD_BLOCK error.
900 * All sockets are created in blocking mode. However, note that the
901 * platform level socket is always non-blocking, and blocking mode
902 * is a GSocket level feature.
907 g_socket_set_blocking (GSocket *socket,
910 g_return_if_fail (G_IS_SOCKET (socket));
912 blocking = !!blocking;
914 if (socket->priv->blocking == blocking)
917 socket->priv->blocking = blocking;
918 g_object_notify (G_OBJECT (socket), "blocking");
922 * g_socket_get_blocking:
923 * @socket: a #GSocket.
925 * Gets the blocking mode of the socket. For details on blocking I/O,
926 * see g_socket_set_blocking().
928 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
933 g_socket_get_blocking (GSocket *socket)
935 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
937 return socket->priv->blocking;
941 * g_socket_set_keepalive:
942 * @socket: a #GSocket.
943 * @keepalive: Value for the keepalive flag
945 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
946 * this flag is set on a socket, the system will attempt to verify that the
947 * remote socket endpoint is still present if a sufficiently long period of
948 * time passes with no data being exchanged. If the system is unable to
949 * verify the presence of the remote endpoint, it will automatically close
952 * This option is only functional on certain kinds of sockets. (Notably,
953 * %G_SOCKET_PROTOCOL_TCP sockets.)
955 * The exact time between pings is system- and protocol-dependent, but will
956 * normally be at least two hours. Most commonly, you would set this flag
957 * on a server socket if you want to allow clients to remain idle for long
958 * periods of time, but also want to ensure that connections are eventually
959 * garbage-collected if clients crash or become unreachable.
964 g_socket_set_keepalive (GSocket *socket,
969 g_return_if_fail (G_IS_SOCKET (socket));
971 keepalive = !!keepalive;
972 if (socket->priv->keepalive == keepalive)
975 value = (gint) keepalive;
976 if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_KEEPALIVE,
977 (gpointer) &value, sizeof (value)) < 0)
979 int errsv = get_socket_errno ();
980 g_warning ("error setting keepalive: %s", socket_strerror (errsv));
984 socket->priv->keepalive = keepalive;
985 g_object_notify (G_OBJECT (socket), "keepalive");
989 * g_socket_get_keepalive:
990 * @socket: a #GSocket.
992 * Gets the keepalive mode of the socket. For details on this,
993 * see g_socket_set_keepalive().
995 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1000 g_socket_get_keepalive (GSocket *socket)
1002 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1004 return socket->priv->keepalive;
1008 * g_socket_get_listen_backlog:
1009 * @socket: a #GSocket.
1011 * Gets the listen backlog setting of the socket. For details on this,
1012 * see g_socket_set_listen_backlog().
1014 * Returns: the maximum number of pending connections.
1019 g_socket_get_listen_backlog (GSocket *socket)
1021 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1023 return socket->priv->listen_backlog;
1027 * g_socket_set_listen_backlog:
1028 * @socket: a #GSocket.
1029 * @backlog: the maximum number of pending connections.
1031 * Sets the maximum number of outstanding connections allowed
1032 * when listening on this socket. If more clients than this are
1033 * connecting to the socket and the application is not handling them
1034 * on time then the new connections will be refused.
1036 * Note that this must be called before g_socket_listen() and has no
1037 * effect if called after that.
1042 g_socket_set_listen_backlog (GSocket *socket,
1045 g_return_if_fail (G_IS_SOCKET (socket));
1046 g_return_if_fail (!socket->priv->listening);
1048 if (backlog != socket->priv->listen_backlog)
1050 socket->priv->listen_backlog = backlog;
1051 g_object_notify (G_OBJECT (socket), "listen-backlog");
1056 * g_socket_get_timeout:
1057 * @socket: a #GSocket.
1059 * Gets the timeout setting of the socket. For details on this, see
1060 * g_socket_set_timeout().
1062 * Returns: the timeout in seconds
1067 g_socket_get_timeout (GSocket *socket)
1069 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1071 return socket->priv->timeout;
1075 * g_socket_set_timeout:
1076 * @socket: a #GSocket.
1077 * @timeout: the timeout for @socket, in seconds, or 0 for none
1079 * Sets the time in seconds after which I/O operations on @socket will
1080 * time out if they have not yet completed.
1082 * On a blocking socket, this means that any blocking #GSocket
1083 * operation will time out after @timeout seconds of inactivity,
1084 * returning %G_IO_ERROR_TIMED_OUT.
1086 * On a non-blocking socket, calls to g_socket_condition_wait() will
1087 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1088 * created with g_socket_create_source() will trigger after
1089 * @timeout seconds of inactivity, with the requested condition
1090 * set, at which point calling g_socket_receive(), g_socket_send(),
1091 * g_socket_check_connect_result(), etc, will fail with
1092 * %G_IO_ERROR_TIMED_OUT.
1094 * If @timeout is 0 (the default), operations will never time out
1097 * Note that if an I/O operation is interrupted by a signal, this may
1098 * cause the timeout to be reset.
1103 g_socket_set_timeout (GSocket *socket,
1106 g_return_if_fail (G_IS_SOCKET (socket));
1108 if (timeout != socket->priv->timeout)
1110 socket->priv->timeout = timeout;
1111 g_object_notify (G_OBJECT (socket), "timeout");
1116 * g_socket_get_family:
1117 * @socket: a #GSocket.
1119 * Gets the socket family of the socket.
1121 * Returns: a #GSocketFamily
1126 g_socket_get_family (GSocket *socket)
1128 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1130 return socket->priv->family;
1134 * g_socket_get_socket_type:
1135 * @socket: a #GSocket.
1137 * Gets the socket type of the socket.
1139 * Returns: a #GSocketType
1144 g_socket_get_socket_type (GSocket *socket)
1146 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1148 return socket->priv->type;
1152 * g_socket_get_protocol:
1153 * @socket: a #GSocket.
1155 * Gets the socket protocol id the socket was created with.
1156 * In case the protocol is unknown, -1 is returned.
1158 * Returns: a protocol id, or -1 if unknown
1163 g_socket_get_protocol (GSocket *socket)
1165 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1167 return socket->priv->protocol;
1172 * @socket: a #GSocket.
1174 * Returns the underlying OS socket object. On unix this
1175 * is a socket file descriptor, and on windows this is
1176 * a Winsock2 SOCKET handle. This may be useful for
1177 * doing platform specific or otherwise unusual operations
1180 * Returns: the file descriptor of the socket.
1185 g_socket_get_fd (GSocket *socket)
1187 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1189 return socket->priv->fd;
1193 * g_socket_get_local_address:
1194 * @socket: a #GSocket.
1195 * @error: #GError for error reporting, or %NULL to ignore.
1197 * Try to get the local address of a bound socket. This is only
1198 * useful if the socket has been bound to a local address,
1199 * either explicitly or implicitly when connecting.
1201 * Returns: a #GSocketAddress or %NULL on error.
1202 * Free the returned object with g_object_unref().
1207 g_socket_get_local_address (GSocket *socket,
1210 struct sockaddr_storage buffer;
1211 guint32 len = sizeof (buffer);
1213 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1215 if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1217 int errsv = get_socket_errno ();
1218 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1219 _("could not get local address: %s"), socket_strerror (errsv));
1223 return g_socket_address_new_from_native (&buffer, len);
1227 * g_socket_get_remote_address:
1228 * @socket: a #GSocket.
1229 * @error: #GError for error reporting, or %NULL to ignore.
1231 * Try to get the remove address of a connected socket. This is only
1232 * useful for connection oriented sockets that have been connected.
1234 * Returns: a #GSocketAddress or %NULL on error.
1235 * Free the returned object with g_object_unref().
1240 g_socket_get_remote_address (GSocket *socket,
1243 struct sockaddr_storage buffer;
1244 guint32 len = sizeof (buffer);
1246 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1248 if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1250 int errsv = get_socket_errno ();
1251 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1252 _("could not get remote address: %s"), socket_strerror (errsv));
1256 return g_socket_address_new_from_native (&buffer, len);
1260 * g_socket_is_connected:
1261 * @socket: a #GSocket.
1263 * Check whether the socket is connected. This is only useful for
1264 * connection-oriented sockets.
1266 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1271 g_socket_is_connected (GSocket *socket)
1273 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1275 return socket->priv->connected;
1280 * @socket: a #GSocket.
1281 * @error: #GError for error reporting, or %NULL to ignore.
1283 * Marks the socket as a server socket, i.e. a socket that is used
1284 * to accept incoming requests using g_socket_accept().
1286 * Before calling this the socket must be bound to a local address using
1289 * To set the maximum amount of outstanding clients, use
1290 * g_socket_set_listen_backlog().
1292 * Returns: %TRUE on success, %FALSE on error.
1297 g_socket_listen (GSocket *socket,
1300 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1302 if (!check_socket (socket, error))
1305 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1307 int errsv = get_socket_errno ();
1309 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1310 _("could not listen: %s"), socket_strerror (errsv));
1314 socket->priv->listening = TRUE;
1321 * @socket: a #GSocket.
1322 * @address: a #GSocketAddress specifying the local address.
1323 * @allow_reuse: whether to allow reusing this address
1324 * @error: #GError for error reporting, or %NULL to ignore.
1326 * When a socket is created it is attached to an address family, but it
1327 * doesn't have an address in this family. g_socket_bind() assigns the
1328 * address (sometimes called name) of the socket.
1330 * It is generally required to bind to a local address before you can
1331 * receive connections. (See g_socket_listen() and g_socket_accept() ).
1332 * In certain situations, you may also want to bind a socket that will be
1333 * used to initiate connections, though this is not normally required.
1335 * @allow_reuse should be %TRUE for server sockets (sockets that you will
1336 * eventually call g_socket_accept() on), and %FALSE for client sockets.
1337 * (Specifically, if it is %TRUE, then g_socket_bind() will set the
1338 * %SO_REUSEADDR flag on the socket, allowing it to bind @address even if
1339 * that address was previously used by another socket that has not yet been
1340 * fully cleaned-up by the kernel. Failing to set this flag on a server
1341 * socket may cause the bind call to return %G_IO_ERROR_ADDRESS_IN_USE if
1342 * the server program is stopped and then immediately restarted.)
1344 * Returns: %TRUE on success, %FALSE on error.
1349 g_socket_bind (GSocket *socket,
1350 GSocketAddress *address,
1351 gboolean reuse_address,
1354 struct sockaddr_storage addr;
1356 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1358 if (!check_socket (socket, error))
1361 /* SO_REUSEADDR on windows means something else and is not what we want.
1362 It always allows the unix variant of SO_REUSEADDR anyway */
1367 value = (int) !!reuse_address;
1368 /* Ignore errors here, the only likely error is "not supported", and
1369 this is a "best effort" thing mainly */
1370 setsockopt (socket->priv->fd, SOL_SOCKET, SO_REUSEADDR,
1371 (gpointer) &value, sizeof (value));
1375 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1378 if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1379 g_socket_address_get_native_size (address)) < 0)
1381 int errsv = get_socket_errno ();
1383 G_IO_ERROR, socket_io_error_from_errno (errsv),
1384 _("Error binding to address: %s"), socket_strerror (errsv));
1392 * g_socket_speaks_ipv4:
1393 * @socket: a #GSocket
1395 * Checks if a socket is capable of speaking IPv4.
1397 * IPv4 sockets are capable of speaking IPv4. On some operating systems
1398 * and under some combinations of circumstances IPv6 sockets are also
1399 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
1402 * No other types of sockets are currently considered as being capable
1405 * Returns: %TRUE if this socket can be used with IPv4.
1410 g_socket_speaks_ipv4 (GSocket *socket)
1412 switch (socket->priv->family)
1414 case G_SOCKET_FAMILY_IPV4:
1417 case G_SOCKET_FAMILY_IPV6:
1418 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
1420 guint sizeof_int = sizeof (int);
1423 if (getsockopt (socket->priv->fd,
1424 IPPROTO_IPV6, IPV6_V6ONLY,
1425 &v6_only, &sizeof_int) != 0)
1441 * @socket: a #GSocket.
1442 * @cancellable: a %GCancellable or %NULL
1443 * @error: #GError for error reporting, or %NULL to ignore.
1445 * Accept incoming connections on a connection-based socket. This removes
1446 * the first outstanding connection request from the listening socket and
1447 * creates a #GSocket object for it.
1449 * The @socket must be bound to a local address with g_socket_bind() and
1450 * must be listening for incoming connections (g_socket_listen()).
1452 * If there are no outstanding connections then the operation will block
1453 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
1454 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
1456 * Returns: a new #GSocket, or %NULL on error.
1457 * Free the returned object with g_object_unref().
1462 g_socket_accept (GSocket *socket,
1463 GCancellable *cancellable,
1466 GSocket *new_socket;
1469 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1471 if (!check_socket (socket, error))
1476 if (socket->priv->blocking &&
1477 !g_socket_condition_wait (socket,
1478 G_IO_IN, cancellable, error))
1481 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
1483 int errsv = get_socket_errno ();
1485 win32_unset_event_mask (socket, FD_ACCEPT);
1490 if (socket->priv->blocking)
1492 #ifdef WSAEWOULDBLOCK
1493 if (errsv == WSAEWOULDBLOCK)
1496 if (errsv == EWOULDBLOCK ||
1502 g_set_error (error, G_IO_ERROR,
1503 socket_io_error_from_errno (errsv),
1504 _("Error accepting connection: %s"), socket_strerror (errsv));
1510 win32_unset_event_mask (socket, FD_ACCEPT);
1514 /* The socket inherits the accepting sockets event mask and even object,
1515 we need to remove that */
1516 WSAEventSelect (ret, NULL, 0);
1522 /* We always want to set close-on-exec to protect users. If you
1523 need to so some weird inheritance to exec you can re-enable this
1524 using lower level hacks with g_socket_get_fd(). */
1525 flags = fcntl (ret, F_GETFD, 0);
1527 (flags & FD_CLOEXEC) == 0)
1529 flags |= FD_CLOEXEC;
1530 fcntl (ret, F_SETFD, flags);
1535 new_socket = g_socket_new_from_fd (ret, error);
1536 if (new_socket == NULL)
1545 new_socket->priv->protocol = socket->priv->protocol;
1552 * @socket: a #GSocket.
1553 * @address: a #GSocketAddress specifying the remote address.
1554 * @cancellable: a %GCancellable or %NULL
1555 * @error: #GError for error reporting, or %NULL to ignore.
1557 * Connect the socket to the specified remote address.
1559 * For connection oriented socket this generally means we attempt to make
1560 * a connection to the @address. For a connection-less socket it sets
1561 * the default address for g_socket_send() and discards all incoming datagrams
1562 * from other sources.
1564 * Generally connection oriented sockets can only connect once, but
1565 * connection-less sockets can connect multiple times to change the
1568 * If the connect call needs to do network I/O it will block, unless
1569 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
1570 * and the user can be notified of the connection finishing by waiting
1571 * for the G_IO_OUT condition. The result of the connection can then be
1572 * checked with g_socket_check_connect_result().
1574 * Returns: %TRUE if connected, %FALSE on error.
1579 g_socket_connect (GSocket *socket,
1580 GSocketAddress *address,
1581 GCancellable *cancellable,
1584 struct sockaddr_storage buffer;
1586 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1588 if (!check_socket (socket, error))
1591 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
1596 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
1597 g_socket_address_get_native_size (address)) < 0)
1599 int errsv = get_socket_errno ();
1605 if (errsv == EINPROGRESS)
1607 if (errsv == WSAEWOULDBLOCK)
1610 if (socket->priv->blocking)
1612 if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
1614 if (g_socket_check_connect_result (socket, error))
1617 g_prefix_error (error, _("Error connecting: "));
1620 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
1621 _("Connection in progress"));
1624 g_set_error (error, G_IO_ERROR,
1625 socket_io_error_from_errno (errsv),
1626 _("Error connecting: %s"), socket_strerror (errsv));
1633 win32_unset_event_mask (socket, FD_CONNECT);
1635 socket->priv->connected = TRUE;
1641 * g_socket_check_connect_result:
1642 * @socket: a #GSocket
1643 * @error: #GError for error reporting, or %NULL to ignore.
1645 * Checks and resets the pending connect error for the socket.
1646 * This is used to check for errors when g_socket_connect() is
1647 * used in non-blocking mode.
1649 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
1654 g_socket_check_connect_result (GSocket *socket,
1660 if (!check_socket (socket, error))
1663 optlen = sizeof (value);
1664 if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
1666 int errsv = get_socket_errno ();
1668 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1669 _("Unable to get pending error: %s"), socket_strerror (errsv));
1675 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
1676 socket_strerror (value));
1684 * @socket: a #GSocket
1685 * @buffer: a buffer to read data into (which should be at least @size
1687 * @size: the number of bytes you want to read from the socket
1688 * @cancellable: a %GCancellable or %NULL
1689 * @error: #GError for error reporting, or %NULL to ignore.
1691 * Receive data (up to @size bytes) from a socket. This is mainly used by
1692 * connection-oriented sockets; it is identical to g_socket_receive_from()
1693 * with @address set to %NULL.
1695 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
1696 * g_socket_receive() will always read either 0 or 1 complete messages from
1697 * the socket. If the received message is too large to fit in @buffer, then
1698 * the data beyond @size bytes will be discarded, without any explicit
1699 * indication that this has occurred.
1701 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
1702 * number of bytes, up to @size. If more than @size bytes have been
1703 * received, the additional data will be returned in future calls to
1704 * g_socket_receive().
1706 * If the socket is in blocking mode the call will block until there is
1707 * some data to receive or there is an error. If there is no data available
1708 * and the socket is in non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error
1709 * will be returned. To be notified when data is available, wait for the
1710 * %G_IO_IN condition.
1712 * On error -1 is returned and @error is set accordingly.
1714 * Returns: Number of bytes read, or -1 on error
1719 g_socket_receive (GSocket *socket,
1722 GCancellable *cancellable,
1725 return g_socket_receive_with_blocking (socket, buffer, size,
1726 socket->priv->blocking,
1727 cancellable, error);
1731 * g_socket_receive_with_blocking:
1732 * @socket: a #GSocket
1733 * @buffer: a buffer to read data into (which should be at least @size
1735 * @size: the number of bytes you want to read from the socket
1736 * @blocking: whether to do blocking or non-blocking I/O
1737 * @cancellable: a %GCancellable or %NULL
1738 * @error: #GError for error reporting, or %NULL to ignore.
1740 * This behaves exactly the same as g_socket_receive(), except that
1741 * the choice of blocking or non-blocking behavior is determined by
1742 * the @blocking argument rather than by @socket's properties.
1744 * Returns: Number of bytes read, or -1 on error
1749 g_socket_receive_with_blocking (GSocket *socket,
1753 GCancellable *cancellable,
1758 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1760 if (!check_socket (socket, error))
1763 if (g_cancellable_set_error_if_cancelled (cancellable, error))
1769 !g_socket_condition_wait (socket,
1770 G_IO_IN, cancellable, error))
1773 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
1775 int errsv = get_socket_errno ();
1782 #ifdef WSAEWOULDBLOCK
1783 if (errsv == WSAEWOULDBLOCK)
1786 if (errsv == EWOULDBLOCK ||
1792 win32_unset_event_mask (socket, FD_READ);
1794 g_set_error (error, G_IO_ERROR,
1795 socket_io_error_from_errno (errsv),
1796 _("Error receiving data: %s"), socket_strerror (errsv));
1800 win32_unset_event_mask (socket, FD_READ);
1809 * g_socket_receive_from:
1810 * @socket: a #GSocket
1811 * @address: a pointer to a #GSocketAddress pointer, or %NULL
1812 * @buffer: a buffer to read data into (which should be at least @size
1814 * @size: the number of bytes you want to read from the socket
1815 * @cancellable: a %GCancellable or %NULL
1816 * @error: #GError for error reporting, or %NULL to ignore.
1818 * Receive data (up to @size bytes) from a socket.
1820 * If @address is non-%NULL then @address will be set equal to the
1821 * source address of the received packet.
1822 * @address is owned by the caller.
1824 * See g_socket_receive() for additional information.
1826 * Returns: Number of bytes read, or -1 on error
1831 g_socket_receive_from (GSocket *socket,
1832 GSocketAddress **address,
1835 GCancellable *cancellable,
1843 return g_socket_receive_message (socket,
1851 /* Although we ignore SIGPIPE, gdb will still stop if the app receives
1852 * one, which can be confusing and annoying. So if possible, we want
1853 * to suppress the signal entirely.
1856 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
1858 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
1863 * @socket: a #GSocket
1864 * @buffer: the buffer containing the data to send.
1865 * @size: the number of bytes to send
1866 * @cancellable: a %GCancellable or %NULL
1867 * @error: #GError for error reporting, or %NULL to ignore.
1869 * Tries to send @size bytes from @buffer on the socket. This is
1870 * mainly used by connection-oriented sockets; it is identical to
1871 * g_socket_send_to() with @address set to %NULL.
1873 * If the socket is in blocking mode the call will block until there is
1874 * space for the data in the socket queue. If there is no space available
1875 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1876 * will be returned. To be notified when space is available, wait for the
1877 * %G_IO_OUT condition. Note though that you may still receive
1878 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
1879 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
1880 * very common due to the way the underlying APIs work.)
1882 * On error -1 is returned and @error is set accordingly.
1884 * Returns: Number of bytes written (which may be less than @size), or -1
1890 g_socket_send (GSocket *socket,
1891 const gchar *buffer,
1893 GCancellable *cancellable,
1896 return g_socket_send_with_blocking (socket, buffer, size,
1897 socket->priv->blocking,
1898 cancellable, error);
1902 * g_socket_send_with_blocking:
1903 * @socket: a #GSocket
1904 * @buffer: the buffer containing the data to send.
1905 * @size: the number of bytes to send
1906 * @blocking: whether to do blocking or non-blocking I/O
1907 * @cancellable: a %GCancellable or %NULL
1908 * @error: #GError for error reporting, or %NULL to ignore.
1910 * This behaves exactly the same as g_socket_send(), except that
1911 * the choice of blocking or non-blocking behavior is determined by
1912 * the @blocking argument rather than by @socket's properties.
1914 * Returns: Number of bytes written (which may be less than @size), or -1
1920 g_socket_send_with_blocking (GSocket *socket,
1921 const gchar *buffer,
1924 GCancellable *cancellable,
1929 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1931 if (!check_socket (socket, error))
1934 if (g_cancellable_set_error_if_cancelled (cancellable, error))
1940 !g_socket_condition_wait (socket,
1941 G_IO_OUT, cancellable, error))
1944 if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
1946 int errsv = get_socket_errno ();
1951 #ifdef WSAEWOULDBLOCK
1952 if (errsv == WSAEWOULDBLOCK)
1953 win32_unset_event_mask (socket, FD_WRITE);
1958 #ifdef WSAEWOULDBLOCK
1959 if (errsv == WSAEWOULDBLOCK)
1962 if (errsv == EWOULDBLOCK ||
1968 g_set_error (error, G_IO_ERROR,
1969 socket_io_error_from_errno (errsv),
1970 _("Error sending data: %s"), socket_strerror (errsv));
1981 * @socket: a #GSocket
1982 * @address: a #GSocketAddress, or %NULL
1983 * @buffer: the buffer containing the data to send.
1984 * @size: the number of bytes to send
1985 * @cancellable: a %GCancellable or %NULL
1986 * @error: #GError for error reporting, or %NULL to ignore.
1988 * Tries to send @size bytes from @buffer to @address. If @address is
1989 * %NULL then the message is sent to the default receiver (set by
1990 * g_socket_connect()).
1992 * See g_socket_send() for additional information.
1994 * Returns: Number of bytes written (which may be less than @size), or -1
2000 g_socket_send_to (GSocket *socket,
2001 GSocketAddress *address,
2002 const gchar *buffer,
2004 GCancellable *cancellable,
2012 return g_socket_send_message (socket,
2022 * g_socket_shutdown:
2023 * @socket: a #GSocket
2024 * @shutdown_read: whether to shut down the read side
2025 * @shutdown_write: whether to shut down the write side
2026 * @error: #GError for error reporting, or %NULL to ignore.
2028 * Shut down part of a full-duplex connection.
2030 * If @shutdown_read is %TRUE then the recieving side of the connection
2031 * is shut down, and further reading is disallowed.
2033 * If @shutdown_write is %TRUE then the sending side of the connection
2034 * is shut down, and further writing is disallowed.
2036 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
2038 * One example where this is used is graceful disconnect for TCP connections
2039 * where you close the sending side, then wait for the other side to close
2040 * the connection, thus ensuring that the other side saw all sent data.
2042 * Returns: %TRUE on success, %FALSE on error
2047 g_socket_shutdown (GSocket *socket,
2048 gboolean shutdown_read,
2049 gboolean shutdown_write,
2054 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2056 if (!check_socket (socket, NULL))
2060 if (!shutdown_read && !shutdown_write)
2064 if (shutdown_read && shutdown_write)
2066 else if (shutdown_read)
2071 if (shutdown_read && shutdown_write)
2073 else if (shutdown_read)
2079 if (shutdown (socket->priv->fd, how) != 0)
2081 int errsv = get_socket_errno ();
2082 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2083 _("Unable to create socket: %s"), socket_strerror (errsv));
2087 if (shutdown_read && shutdown_write)
2088 socket->priv->connected = FALSE;
2095 * @socket: a #GSocket
2096 * @error: #GError for error reporting, or %NULL to ignore.
2098 * Closes the socket, shutting down any active connection.
2100 * Closing a socket does not wait for all outstanding I/O operations
2101 * to finish, so the caller should not rely on them to be guaranteed
2102 * to complete even if the close returns with no error.
2104 * Once the socket is closed, all other operations will return
2105 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
2108 * Sockets will be automatically closed when the last reference
2109 * is dropped, but you might want to call this function to make sure
2110 * resources are released as early as possible.
2112 * Beware that due to the way that TCP works, it is possible for
2113 * recently-sent data to be lost if either you close a socket while the
2114 * %G_IO_IN condition is set, or else if the remote connection tries to
2115 * send something to you after you close the socket but before it has
2116 * finished reading all of the data you sent. There is no easy generic
2117 * way to avoid this problem; the easiest fix is to design the network
2118 * protocol such that the client will never send data "out of turn".
2119 * Another solution is for the server to half-close the connection by
2120 * calling g_socket_shutdown() with only the @shutdown_write flag set,
2121 * and then wait for the client to notice this and close its side of the
2122 * connection, after which the server can safely call g_socket_close().
2123 * (This is what #GTcpConnection does if you call
2124 * g_tcp_connection_set_graceful_disconnect(). But of course, this
2125 * only works if the client will close its connection after the server
2128 * Returns: %TRUE on success, %FALSE on error
2133 g_socket_close (GSocket *socket,
2138 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2140 if (socket->priv->closed)
2141 return TRUE; /* Multiple close not an error */
2143 if (!check_socket (socket, NULL))
2149 res = closesocket (socket->priv->fd);
2151 res = close (socket->priv->fd);
2155 int errsv = get_socket_errno ();
2160 g_set_error (error, G_IO_ERROR,
2161 socket_io_error_from_errno (errsv),
2162 _("Error closing socket: %s"),
2163 socket_strerror (errsv));
2169 socket->priv->connected = FALSE;
2170 socket->priv->closed = TRUE;
2176 * g_socket_is_closed:
2177 * @socket: a #GSocket
2179 * Checks whether a socket is closed.
2181 * Returns: %TRUE if socket is closed, %FALSE otherwise
2186 g_socket_is_closed (GSocket *socket)
2188 return socket->priv->closed;
2192 /* Broken source, used on errors */
2194 broken_prepare (GSource *source,
2201 broken_check (GSource *source)
2207 broken_dispatch (GSource *source,
2208 GSourceFunc callback,
2214 static GSourceFuncs broken_funcs =
2223 network_events_for_condition (GIOCondition condition)
2227 if (condition & G_IO_IN)
2228 event_mask |= (FD_READ | FD_ACCEPT);
2229 if (condition & G_IO_OUT)
2230 event_mask |= (FD_WRITE | FD_CONNECT);
2231 event_mask |= FD_CLOSE;
2237 ensure_event (GSocket *socket)
2239 if (socket->priv->event == WSA_INVALID_EVENT)
2240 socket->priv->event = WSACreateEvent();
2244 update_select_events (GSocket *socket)
2251 ensure_event (socket);
2254 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
2257 event_mask |= network_events_for_condition (*ptr);
2260 if (event_mask != socket->priv->selected_events)
2262 /* If no events selected, disable event so we can unset
2265 if (event_mask == 0)
2268 event = socket->priv->event;
2270 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
2271 socket->priv->selected_events = event_mask;
2276 add_condition_watch (GSocket *socket,
2277 GIOCondition *condition)
2279 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
2281 socket->priv->requested_conditions =
2282 g_list_prepend (socket->priv->requested_conditions, condition);
2284 update_select_events (socket);
2288 remove_condition_watch (GSocket *socket,
2289 GIOCondition *condition)
2291 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
2293 socket->priv->requested_conditions =
2294 g_list_remove (socket->priv->requested_conditions, condition);
2296 update_select_events (socket);
2300 update_condition (GSocket *socket)
2302 WSANETWORKEVENTS events;
2303 GIOCondition condition;
2305 if (WSAEnumNetworkEvents (socket->priv->fd,
2306 socket->priv->event,
2309 socket->priv->current_events |= events.lNetworkEvents;
2310 if (events.lNetworkEvents & FD_WRITE &&
2311 events.iErrorCode[FD_WRITE_BIT] != 0)
2312 socket->priv->current_errors |= FD_WRITE;
2313 if (events.lNetworkEvents & FD_CONNECT &&
2314 events.iErrorCode[FD_CONNECT_BIT] != 0)
2315 socket->priv->current_errors |= FD_CONNECT;
2319 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
2320 condition |= G_IO_IN;
2322 if (socket->priv->current_events & FD_CLOSE ||
2323 socket->priv->closed)
2324 condition |= G_IO_HUP;
2326 /* Never report both G_IO_OUT and HUP, these are
2327 mutually exclusive (can't write to a closed socket) */
2328 if ((condition & G_IO_HUP) == 0 &&
2329 socket->priv->current_events & FD_WRITE)
2331 if (socket->priv->current_errors & FD_WRITE)
2332 condition |= G_IO_ERR;
2334 condition |= G_IO_OUT;
2338 if (socket->priv->current_events & FD_CONNECT)
2340 if (socket->priv->current_errors & FD_CONNECT)
2341 condition |= (G_IO_HUP | G_IO_ERR);
2343 condition |= G_IO_OUT;
2355 GIOCondition condition;
2356 GCancellable *cancellable;
2357 GPollFD cancel_pollfd;
2358 GTimeVal timeout_time;
2362 socket_source_prepare (GSource *source,
2365 GSocketSource *socket_source = (GSocketSource *)source;
2367 if (g_cancellable_is_cancelled (socket_source->cancellable))
2370 if (socket_source->timeout_time.tv_sec)
2374 g_source_get_current_time (source, &now);
2375 *timeout = ((socket_source->timeout_time.tv_sec - now.tv_sec) * 1000 +
2376 (socket_source->timeout_time.tv_usec - now.tv_usec) / 1000);
2379 socket_source->socket->priv->timed_out = TRUE;
2380 socket_source->pollfd.revents = socket_source->condition & (G_IO_IN | G_IO_OUT);
2388 socket_source->pollfd.revents = update_condition (socket_source->socket);
2391 if ((socket_source->condition & socket_source->pollfd.revents) != 0)
2398 socket_source_check (GSource *source)
2402 return socket_source_prepare (source, &timeout);
2406 socket_source_dispatch (GSource *source,
2407 GSourceFunc callback,
2410 GSocketSourceFunc func = (GSocketSourceFunc)callback;
2411 GSocketSource *socket_source = (GSocketSource *)source;
2413 return (*func) (socket_source->socket,
2414 socket_source->pollfd.revents & socket_source->condition,
2419 socket_source_finalize (GSource *source)
2421 GSocketSource *socket_source = (GSocketSource *)source;
2424 socket = socket_source->socket;
2427 remove_condition_watch (socket, &socket_source->condition);
2430 g_object_unref (socket);
2432 if (socket_source->cancellable)
2434 g_cancellable_release_fd (socket_source->cancellable);
2435 g_object_unref (socket_source->cancellable);
2439 static GSourceFuncs socket_source_funcs =
2441 socket_source_prepare,
2442 socket_source_check,
2443 socket_source_dispatch,
2444 socket_source_finalize
2448 socket_source_new (GSocket *socket,
2449 GIOCondition condition,
2450 GCancellable *cancellable)
2453 GSocketSource *socket_source;
2456 ensure_event (socket);
2458 if (socket->priv->event == WSA_INVALID_EVENT)
2460 g_warning ("Failed to create WSAEvent");
2461 return g_source_new (&broken_funcs, sizeof (GSource));
2465 condition |= G_IO_HUP | G_IO_ERR;
2467 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
2468 g_source_set_name (source, "GSocket");
2469 socket_source = (GSocketSource *)source;
2471 socket_source->socket = g_object_ref (socket);
2472 socket_source->condition = condition;
2474 if (g_cancellable_make_pollfd (cancellable,
2475 &socket_source->cancel_pollfd))
2477 socket_source->cancellable = g_object_ref (cancellable);
2478 g_source_add_poll (source, &socket_source->cancel_pollfd);
2482 add_condition_watch (socket, &socket_source->condition);
2483 socket_source->pollfd.fd = (gintptr) socket->priv->event;
2485 socket_source->pollfd.fd = socket->priv->fd;
2488 socket_source->pollfd.events = condition;
2489 socket_source->pollfd.revents = 0;
2490 g_source_add_poll (source, &socket_source->pollfd);
2492 if (socket->priv->timeout)
2494 g_get_current_time (&socket_source->timeout_time);
2495 socket_source->timeout_time.tv_sec += socket->priv->timeout;
2499 socket_source->timeout_time.tv_sec = 0;
2500 socket_source->timeout_time.tv_usec = 0;
2507 * g_socket_create_source:
2508 * @socket: a #GSocket
2509 * @condition: a #GIOCondition mask to monitor
2510 * @cancellable: a %GCancellable or %NULL
2512 * Creates a %GSource that can be attached to a %GMainContext to monitor
2513 * for the availibility of the specified @condition on the socket.
2515 * The callback on the source is of the #GSocketSourceFunc type.
2517 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
2518 * these conditions will always be reported output if they are true.
2520 * @cancellable if not %NULL can be used to cancel the source, which will
2521 * cause the source to trigger, reporting the current condition (which
2522 * is likely 0 unless cancellation happened at the same time as a
2523 * condition change). You can check for this in the callback using
2524 * g_cancellable_is_cancelled().
2526 * If @socket has a timeout set, and it is reached before @condition
2527 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
2528 * %G_IO_OUT depending on @condition. However, @socket will have been
2529 * marked as having had a timeout, and so the next #GSocket I/O method
2530 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
2532 * Returns: a newly allocated %GSource, free with g_source_unref().
2537 g_socket_create_source (GSocket *socket,
2538 GIOCondition condition,
2539 GCancellable *cancellable)
2541 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
2543 return socket_source_new (socket, condition, cancellable);
2547 * g_socket_condition_check:
2548 * @socket: a #GSocket
2549 * @condition: a #GIOCondition mask to check
2551 * Checks on the readiness of @socket to perform operations.
2552 * The operations specified in @condition are checked for and masked
2553 * against the currently-satisfied conditions on @socket. The result
2556 * Note that on Windows, it is possible for an operation to return
2557 * %G_IO_ERROR_WOULD_BLOCK even immediately after
2558 * g_socket_condition_check() has claimed that the socket is ready for
2559 * writing. Rather than calling g_socket_condition_check() and then
2560 * writing to the socket if it succeeds, it is generally better to
2561 * simply try writing to the socket right away, and try again later if
2562 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
2564 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2565 * these conditions will always be set in the output if they are true.
2567 * This call never blocks.
2569 * Returns: the @GIOCondition mask of the current state
2574 g_socket_condition_check (GSocket *socket,
2575 GIOCondition condition)
2577 if (!check_socket (socket, NULL))
2582 GIOCondition current_condition;
2584 condition |= G_IO_ERR | G_IO_HUP;
2586 add_condition_watch (socket, &condition);
2587 current_condition = update_condition (socket);
2588 remove_condition_watch (socket, &condition);
2589 return condition & current_condition;
2595 poll_fd.fd = socket->priv->fd;
2596 poll_fd.events = condition;
2599 result = g_poll (&poll_fd, 1, 0);
2600 while (result == -1 && get_socket_errno () == EINTR);
2602 return poll_fd.revents;
2608 * g_socket_condition_wait:
2609 * @socket: a #GSocket
2610 * @condition: a #GIOCondition mask to wait for
2611 * @cancellable: a #GCancellable, or %NULL
2612 * @error: a #GError pointer, or %NULL
2614 * Waits for @condition to become true on @socket. When the condition
2615 * is met, %TRUE is returned.
2617 * If @cancellable is cancelled before the condition is met, or if the
2618 * socket has a timeout set and it is reached before the condition is
2619 * met, then %FALSE is returned and @error, if non-%NULL, is set to
2620 * the appropriate value (%G_IO_ERROR_CANCELLED or
2621 * %G_IO_ERROR_TIMED_OUT).
2623 * Returns: %TRUE if the condition was met, %FALSE otherwise
2628 g_socket_condition_wait (GSocket *socket,
2629 GIOCondition condition,
2630 GCancellable *cancellable,
2633 if (!check_socket (socket, error))
2636 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2641 GIOCondition current_condition;
2647 /* Always check these */
2648 condition |= G_IO_ERR | G_IO_HUP;
2650 add_condition_watch (socket, &condition);
2653 events[num_events++] = socket->priv->event;
2655 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
2656 events[num_events++] = (WSAEVENT)cancel_fd.fd;
2658 if (socket->priv->timeout)
2659 timeout = socket->priv->timeout * 1000;
2661 timeout = WSA_INFINITE;
2663 current_condition = update_condition (socket);
2664 while ((condition & current_condition) == 0)
2666 res = WSAWaitForMultipleEvents(num_events, events,
2667 FALSE, timeout, FALSE);
2668 if (res == WSA_WAIT_FAILED)
2670 int errsv = get_socket_errno ();
2672 g_set_error (error, G_IO_ERROR,
2673 socket_io_error_from_errno (errsv),
2674 _("Waiting for socket condition: %s"),
2675 socket_strerror (errsv));
2678 else if (res == WSA_WAIT_TIMEOUT)
2680 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
2681 _("Socket I/O timed out"));
2685 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2688 current_condition = update_condition (socket);
2690 remove_condition_watch (socket, &condition);
2692 g_cancellable_release_fd (cancellable);
2694 return (condition & current_condition) != 0;
2703 poll_fd[0].fd = socket->priv->fd;
2704 poll_fd[0].events = condition;
2707 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
2710 if (socket->priv->timeout)
2711 timeout = socket->priv->timeout * 1000;
2716 result = g_poll (poll_fd, num, timeout);
2717 while (result == -1 && get_socket_errno () == EINTR);
2720 g_cancellable_release_fd (cancellable);
2724 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
2725 _("Socket I/O timed out"));
2729 return !g_cancellable_set_error_if_cancelled (cancellable, error);
2735 * g_socket_send_message:
2736 * @socket: a #GSocket
2737 * @address: a #GSocketAddress, or %NULL
2738 * @vectors: an array of #GOutputVector structs
2739 * @num_vectors: the number of elements in @vectors, or -1
2740 * @messages: a pointer to an array of #GSocketControlMessages, or
2742 * @num_messages: number of elements in @messages, or -1.
2743 * @flags: an int containing #GSocketMsgFlags flags
2744 * @cancellable: a %GCancellable or %NULL
2745 * @error: #GError for error reporting, or %NULL to ignore.
2747 * Send data to @address on @socket. This is the most complicated and
2748 * fully-featured version of this call. For easier use, see
2749 * g_socket_send() and g_socket_send_to().
2751 * If @address is %NULL then the message is sent to the default receiver
2752 * (set by g_socket_connect()).
2754 * @vectors must point to an array of #GOutputVector structs and
2755 * @num_vectors must be the length of this array. (If @num_vectors is -1,
2756 * then @vectors is assumed to be terminated by a #GOutputVector with a
2757 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
2758 * that the sent data will be gathered from. Using multiple
2759 * #GOutputVector<!-- -->s is more memory-efficient than manually copying
2760 * data from multiple sources into a single buffer, and more
2761 * network-efficient than making multiple calls to g_socket_send().
2763 * @messages, if non-%NULL, is taken to point to an array of @num_messages
2764 * #GSocketControlMessage instances. These correspond to the control
2765 * messages to be sent on the socket.
2766 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
2769 * @flags modify how the message is sent. The commonly available arguments
2770 * for this are available in the #GSocketMsgFlags enum, but the
2771 * values there are the same as the system values, and the flags
2772 * are passed in as-is, so you can pass in system-specific flags too.
2774 * If the socket is in blocking mode the call will block until there is
2775 * space for the data in the socket queue. If there is no space available
2776 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2777 * will be returned. To be notified when space is available, wait for the
2778 * %G_IO_OUT condition. Note though that you may still receive
2779 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2780 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2781 * very common due to the way the underlying APIs work.)
2783 * On error -1 is returned and @error is set accordingly.
2785 * Returns: Number of bytes written (which may be less than @size), or -1
2791 g_socket_send_message (GSocket *socket,
2792 GSocketAddress *address,
2793 GOutputVector *vectors,
2795 GSocketControlMessage **messages,
2798 GCancellable *cancellable,
2801 GOutputVector one_vector;
2804 if (!check_socket (socket, error))
2807 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2810 if (num_vectors == -1)
2812 for (num_vectors = 0;
2813 vectors[num_vectors].buffer != NULL;
2818 if (num_messages == -1)
2820 for (num_messages = 0;
2821 messages != NULL && messages[num_messages] != NULL;
2826 if (num_vectors == 0)
2830 one_vector.buffer = &zero;
2831 one_vector.size = 1;
2833 vectors = &one_vector;
2846 msg.msg_namelen = g_socket_address_get_native_size (address);
2847 msg.msg_name = g_alloca (msg.msg_namelen);
2848 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
2853 msg.msg_name = NULL;
2854 msg.msg_namelen = 0;
2859 /* this entire expression will be evaluated at compile time */
2860 if (sizeof *msg.msg_iov == sizeof *vectors &&
2861 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2862 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2863 G_STRUCT_OFFSET (GOutputVector, buffer) &&
2864 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2865 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2866 G_STRUCT_OFFSET (GOutputVector, size))
2867 /* ABI is compatible */
2869 msg.msg_iov = (struct iovec *) vectors;
2870 msg.msg_iovlen = num_vectors;
2873 /* ABI is incompatible */
2877 msg.msg_iov = g_newa (struct iovec, num_vectors);
2878 for (i = 0; i < num_vectors; i++)
2880 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
2881 msg.msg_iov[i].iov_len = vectors[i].size;
2883 msg.msg_iovlen = num_vectors;
2889 struct cmsghdr *cmsg;
2892 msg.msg_controllen = 0;
2893 for (i = 0; i < num_messages; i++)
2894 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
2896 msg.msg_control = g_alloca (msg.msg_controllen);
2897 memset (msg.msg_control, '\0', msg.msg_controllen);
2899 cmsg = CMSG_FIRSTHDR (&msg);
2900 for (i = 0; i < num_messages; i++)
2902 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
2903 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
2904 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
2905 g_socket_control_message_serialize (messages[i],
2907 cmsg = CMSG_NXTHDR (&msg, cmsg);
2909 g_assert (cmsg == NULL);
2914 if (socket->priv->blocking &&
2915 !g_socket_condition_wait (socket,
2916 G_IO_OUT, cancellable, error))
2919 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
2922 int errsv = get_socket_errno ();
2927 if (socket->priv->blocking &&
2928 (errsv == EWOULDBLOCK ||
2932 g_set_error (error, G_IO_ERROR,
2933 socket_io_error_from_errno (errsv),
2934 _("Error sending message: %s"), socket_strerror (errsv));
2945 struct sockaddr_storage addr;
2952 /* Win32 doesn't support control messages.
2953 Actually this is possible for raw and datagram sockets
2954 via WSASendMessage on Vista or later, but that doesn't
2956 if (num_messages != 0)
2958 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2959 _("GSocketControlMessage not supported on windows"));
2964 bufs = g_newa (WSABUF, num_vectors);
2965 for (i = 0; i < num_vectors; i++)
2967 bufs[i].buf = (char *)vectors[i].buffer;
2968 bufs[i].len = (gulong)vectors[i].size;
2972 addrlen = 0; /* Avoid warning */
2975 addrlen = g_socket_address_get_native_size (address);
2976 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
2982 if (socket->priv->blocking &&
2983 !g_socket_condition_wait (socket,
2984 G_IO_OUT, cancellable, error))
2988 result = WSASendTo (socket->priv->fd,
2991 (const struct sockaddr *)&addr, addrlen,
2994 result = WSASend (socket->priv->fd,
3001 int errsv = get_socket_errno ();
3003 if (errsv == WSAEINTR)
3006 if (errsv == WSAEWOULDBLOCK)
3007 win32_unset_event_mask (socket, FD_WRITE);
3009 if (socket->priv->blocking &&
3010 errsv == WSAEWOULDBLOCK)
3013 g_set_error (error, G_IO_ERROR,
3014 socket_io_error_from_errno (errsv),
3015 _("Error sending message: %s"), socket_strerror (errsv));
3028 * g_socket_receive_message:
3029 * @socket: a #GSocket
3030 * @address: a pointer to a #GSocketAddress pointer, or %NULL
3031 * @vectors: an array of #GInputVector structs
3032 * @num_vectors: the number of elements in @vectors, or -1
3033 * @messages: a pointer which may be filled with an array of
3034 * #GSocketControlMessages, or %NULL
3035 * @num_messages: a pointer which will be filled with the number of
3036 * elements in @messages, or %NULL
3037 * @flags: a pointer to an int containing #GSocketMsgFlags flags
3038 * @cancellable: a %GCancellable or %NULL
3039 * @error: a #GError pointer, or %NULL
3041 * Receive data from a socket. This is the most complicated and
3042 * fully-featured version of this call. For easier use, see
3043 * g_socket_receive() and g_socket_receive_from().
3045 * If @address is non-%NULL then @address will be set equal to the
3046 * source address of the received packet.
3047 * @address is owned by the caller.
3049 * @vector must point to an array of #GInputVector structs and
3050 * @num_vectors must be the length of this array. These structs
3051 * describe the buffers that received data will be scattered into.
3052 * If @num_vectors is -1, then @vectors is assumed to be terminated
3053 * by a #GInputVector with a %NULL buffer pointer.
3055 * As a special case, if @num_vectors is 0 (in which case, @vectors
3056 * may of course be %NULL), then a single byte is received and
3057 * discarded. This is to facilitate the common practice of sending a
3058 * single '\0' byte for the purposes of transferring ancillary data.
3060 * @messages, if non-%NULL, will be set to point to a newly-allocated
3061 * array of #GSocketControlMessage instances or %NULL if no such
3062 * messages was received. These correspond to the control messages
3063 * received from the kernel, one #GSocketControlMessage per message
3064 * from the kernel. This array is %NULL-terminated and must be freed
3065 * by the caller using g_free() after calling g_object_unref() on each
3066 * element. If @messages is %NULL, any control messages received will
3069 * @num_messages, if non-%NULL, will be set to the number of control
3070 * messages received.
3072 * If both @messages and @num_messages are non-%NULL, then
3073 * @num_messages gives the number of #GSocketControlMessage instances
3074 * in @messages (ie: not including the %NULL terminator).
3076 * @flags is an in/out parameter. The commonly available arguments
3077 * for this are available in the #GSocketMsgFlags enum, but the
3078 * values there are the same as the system values, and the flags
3079 * are passed in as-is, so you can pass in system-specific flags too
3080 * (and g_socket_receive_message() may pass system-specific flags out).
3082 * As with g_socket_receive(), data may be discarded if @socket is
3083 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
3084 * provide enough buffer space to read a complete message. You can pass
3085 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
3086 * removing it from the receive queue, but there is no portable way to find
3087 * out the length of the message other than by reading it into a
3088 * sufficiently-large buffer.
3090 * If the socket is in blocking mode the call will block until there
3091 * is some data to receive or there is an error. If there is no data
3092 * available and the socket is in non-blocking mode, a
3093 * %G_IO_ERROR_WOULD_BLOCK error will be returned. To be notified when
3094 * data is available, wait for the %G_IO_IN condition.
3096 * On error -1 is returned and @error is set accordingly.
3098 * Returns: Number of bytes read, or -1 on error
3103 g_socket_receive_message (GSocket *socket,
3104 GSocketAddress **address,
3105 GInputVector *vectors,
3107 GSocketControlMessage ***messages,
3110 GCancellable *cancellable,
3113 GInputVector one_vector;
3116 if (!check_socket (socket, error))
3119 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3122 if (num_vectors == -1)
3124 for (num_vectors = 0;
3125 vectors[num_vectors].buffer != NULL;
3130 if (num_vectors == 0)
3132 one_vector.buffer = &one_byte;
3133 one_vector.size = 1;
3135 vectors = &one_vector;
3142 struct sockaddr_storage one_sockaddr;
3147 msg.msg_name = &one_sockaddr;
3148 msg.msg_namelen = sizeof (struct sockaddr_storage);
3152 msg.msg_name = NULL;
3153 msg.msg_namelen = 0;
3157 /* this entire expression will be evaluated at compile time */
3158 if (sizeof *msg.msg_iov == sizeof *vectors &&
3159 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3160 G_STRUCT_OFFSET (struct iovec, iov_base) ==
3161 G_STRUCT_OFFSET (GInputVector, buffer) &&
3162 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3163 G_STRUCT_OFFSET (struct iovec, iov_len) ==
3164 G_STRUCT_OFFSET (GInputVector, size))
3165 /* ABI is compatible */
3167 msg.msg_iov = (struct iovec *) vectors;
3168 msg.msg_iovlen = num_vectors;
3171 /* ABI is incompatible */
3175 msg.msg_iov = g_newa (struct iovec, num_vectors);
3176 for (i = 0; i < num_vectors; i++)
3178 msg.msg_iov[i].iov_base = vectors[i].buffer;
3179 msg.msg_iov[i].iov_len = vectors[i].size;
3181 msg.msg_iovlen = num_vectors;
3185 msg.msg_control = g_alloca (2048);
3186 msg.msg_controllen = 2048;
3190 msg.msg_flags = *flags;
3197 if (socket->priv->blocking &&
3198 !g_socket_condition_wait (socket,
3199 G_IO_IN, cancellable, error))
3202 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
3206 int errsv = get_socket_errno ();
3211 if (socket->priv->blocking &&
3212 (errsv == EWOULDBLOCK ||
3216 g_set_error (error, G_IO_ERROR,
3217 socket_io_error_from_errno (errsv),
3218 _("Error receiving message: %s"), socket_strerror (errsv));
3225 /* decode address */
3226 if (address != NULL)
3228 if (msg.msg_namelen > 0)
3229 *address = g_socket_address_new_from_native (msg.msg_name,
3235 /* decode control messages */
3237 GPtrArray *my_messages = NULL;
3238 const gchar *scm_pointer;
3239 struct cmsghdr *cmsg;
3242 scm_pointer = (const gchar *) msg.msg_control;
3243 scm_size = msg.msg_controllen;
3245 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
3247 GSocketControlMessage *message;
3249 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
3251 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
3253 if (message == NULL)
3254 /* We've already spewed about the problem in the
3255 deserialization code, so just continue */
3258 if (messages == NULL)
3260 /* we have to do it this way if the user ignores the
3261 * messages so that we will close any received fds.
3263 g_object_unref (message);
3267 if (my_messages == NULL)
3268 my_messages = g_ptr_array_new ();
3269 g_ptr_array_add (my_messages, message);
3274 *num_messages = my_messages != NULL ? my_messages->len : 0;
3278 if (my_messages == NULL)
3284 g_ptr_array_add (my_messages, NULL);
3285 *messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
3290 g_assert (my_messages == NULL);
3294 /* capture the flags */
3296 *flags = msg.msg_flags;
3302 struct sockaddr_storage addr;
3304 DWORD bytes_received;
3311 bufs = g_newa (WSABUF, num_vectors);
3312 for (i = 0; i < num_vectors; i++)
3314 bufs[i].buf = (char *)vectors[i].buffer;
3315 bufs[i].len = (gulong)vectors[i].size;
3327 if (socket->priv->blocking &&
3328 !g_socket_condition_wait (socket,
3329 G_IO_IN, cancellable, error))
3332 addrlen = sizeof addr;
3334 result = WSARecvFrom (socket->priv->fd,
3336 &bytes_received, &win_flags,
3337 (struct sockaddr *)&addr, &addrlen,
3340 result = WSARecv (socket->priv->fd,
3342 &bytes_received, &win_flags,
3346 int errsv = get_socket_errno ();
3348 if (errsv == WSAEINTR)
3351 win32_unset_event_mask (socket, FD_READ);
3353 if (socket->priv->blocking &&
3354 errsv == WSAEWOULDBLOCK)
3357 g_set_error (error, G_IO_ERROR,
3358 socket_io_error_from_errno (errsv),
3359 _("Error receiving message: %s"), socket_strerror (errsv));
3363 win32_unset_event_mask (socket, FD_READ);
3367 /* decode address */
3368 if (address != NULL)
3371 *address = g_socket_address_new_from_native (&addr, addrlen);
3376 /* capture the flags */
3380 if (messages != NULL)
3382 if (num_messages != NULL)
3385 return bytes_received;
3391 * g_socket_get_credentials:
3392 * @socket: a #GSocket.
3393 * @error: #GError for error reporting, or %NULL to ignore.
3395 * Returns the credentials of the foreign process connected to this
3396 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
3399 * If this operation isn't supported on the OS, the method fails with
3400 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
3401 * by reading the %SO_PEERCRED option on the underlying socket.
3403 * Other ways to obtain credentials from a foreign peer includes the
3404 * #GUnixCredentialsMessage type and
3405 * g_unix_connection_send_credentials() /
3406 * g_unix_connection_receive_credentials() functions.
3408 * Returns: %NULL if @error is set, otherwise a #GCredentials object
3409 * that must be freed with g_object_unref().
3414 g_socket_get_credentials (GSocket *socket,
3419 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
3420 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3426 struct ucred native_creds;
3428 optlen = sizeof (struct ucred);
3429 if (getsockopt (socket->priv->fd,
3432 (void *)&native_creds,
3435 int errsv = get_socket_errno ();
3438 socket_io_error_from_errno (errsv),
3439 _("Unable to get pending error: %s"),
3440 socket_strerror (errsv));
3444 ret = g_credentials_new ();
3445 g_credentials_set_native (ret,
3446 G_CREDENTIALS_TYPE_LINUX_UCRED,
3451 g_set_error_literal (error,
3453 G_IO_ERROR_NOT_SUPPORTED,
3454 _("g_socket_get_credentials not implemented for this OS"));