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,
1727 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1729 if (!check_socket (socket, error))
1732 if (g_cancellable_set_error_if_cancelled (cancellable, error))
1737 if (socket->priv->blocking &&
1738 !g_socket_condition_wait (socket,
1739 G_IO_IN, cancellable, error))
1742 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
1744 int errsv = get_socket_errno ();
1749 if (socket->priv->blocking)
1751 #ifdef WSAEWOULDBLOCK
1752 if (errsv == WSAEWOULDBLOCK)
1755 if (errsv == EWOULDBLOCK ||
1761 win32_unset_event_mask (socket, FD_READ);
1763 g_set_error (error, G_IO_ERROR,
1764 socket_io_error_from_errno (errsv),
1765 _("Error receiving data: %s"), socket_strerror (errsv));
1769 win32_unset_event_mask (socket, FD_READ);
1778 * g_socket_receive_from:
1779 * @socket: a #GSocket
1780 * @address: a pointer to a #GSocketAddress pointer, or %NULL
1781 * @buffer: a buffer to read data into (which should be at least @size
1783 * @size: the number of bytes you want to read from the socket
1784 * @cancellable: a %GCancellable or %NULL
1785 * @error: #GError for error reporting, or %NULL to ignore.
1787 * Receive data (up to @size bytes) from a socket.
1789 * If @address is non-%NULL then @address will be set equal to the
1790 * source address of the received packet.
1791 * @address is owned by the caller.
1793 * See g_socket_receive() for additional information.
1795 * Returns: Number of bytes read, or -1 on error
1800 g_socket_receive_from (GSocket *socket,
1801 GSocketAddress **address,
1804 GCancellable *cancellable,
1812 return g_socket_receive_message (socket,
1820 /* Although we ignore SIGPIPE, gdb will still stop if the app receives
1821 * one, which can be confusing and annoying. So if possible, we want
1822 * to suppress the signal entirely.
1825 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
1827 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
1832 * @socket: a #GSocket
1833 * @buffer: the buffer containing the data to send.
1834 * @size: the number of bytes to send
1835 * @cancellable: a %GCancellable or %NULL
1836 * @error: #GError for error reporting, or %NULL to ignore.
1838 * Tries to send @size bytes from @buffer on the socket. This is
1839 * mainly used by connection-oriented sockets; it is identical to
1840 * g_socket_send_to() with @address set to %NULL.
1842 * If the socket is in blocking mode the call will block until there is
1843 * space for the data in the socket queue. If there is no space available
1844 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1845 * will be returned. To be notified when space is available, wait for the
1846 * %G_IO_OUT condition. Note though that you may still receive
1847 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
1848 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
1849 * very common due to the way the underlying APIs work.)
1851 * On error -1 is returned and @error is set accordingly.
1853 * Returns: Number of bytes written (which may be less than @size), or -1
1859 g_socket_send (GSocket *socket,
1860 const gchar *buffer,
1862 GCancellable *cancellable,
1867 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1869 if (!check_socket (socket, error))
1872 if (g_cancellable_set_error_if_cancelled (cancellable, error))
1877 if (socket->priv->blocking &&
1878 !g_socket_condition_wait (socket,
1879 G_IO_OUT, cancellable, error))
1882 if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
1884 int errsv = get_socket_errno ();
1889 #ifdef WSAEWOULDBLOCK
1890 if (errsv == WSAEWOULDBLOCK)
1891 win32_unset_event_mask (socket, FD_WRITE);
1894 if (socket->priv->blocking)
1896 #ifdef WSAEWOULDBLOCK
1897 if (errsv == WSAEWOULDBLOCK)
1900 if (errsv == EWOULDBLOCK ||
1906 g_set_error (error, G_IO_ERROR,
1907 socket_io_error_from_errno (errsv),
1908 _("Error sending data: %s"), socket_strerror (errsv));
1919 * @socket: a #GSocket
1920 * @address: a #GSocketAddress, or %NULL
1921 * @buffer: the buffer containing the data to send.
1922 * @size: the number of bytes to send
1923 * @cancellable: a %GCancellable or %NULL
1924 * @error: #GError for error reporting, or %NULL to ignore.
1926 * Tries to send @size bytes from @buffer to @address. If @address is
1927 * %NULL then the message is sent to the default receiver (set by
1928 * g_socket_connect()).
1930 * See g_socket_send() for additional information.
1932 * Returns: Number of bytes written (which may be less than @size), or -1
1938 g_socket_send_to (GSocket *socket,
1939 GSocketAddress *address,
1940 const gchar *buffer,
1942 GCancellable *cancellable,
1950 return g_socket_send_message (socket,
1960 * g_socket_shutdown:
1961 * @socket: a #GSocket
1962 * @shutdown_read: whether to shut down the read side
1963 * @shutdown_write: whether to shut down the write side
1964 * @error: #GError for error reporting, or %NULL to ignore.
1966 * Shut down part of a full-duplex connection.
1968 * If @shutdown_read is %TRUE then the recieving side of the connection
1969 * is shut down, and further reading is disallowed.
1971 * If @shutdown_write is %TRUE then the sending side of the connection
1972 * is shut down, and further writing is disallowed.
1974 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
1976 * One example where this is used is graceful disconnect for TCP connections
1977 * where you close the sending side, then wait for the other side to close
1978 * the connection, thus ensuring that the other side saw all sent data.
1980 * Returns: %TRUE on success, %FALSE on error
1985 g_socket_shutdown (GSocket *socket,
1986 gboolean shutdown_read,
1987 gboolean shutdown_write,
1992 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
1994 if (!check_socket (socket, NULL))
1998 if (!shutdown_read && !shutdown_write)
2002 if (shutdown_read && shutdown_write)
2004 else if (shutdown_read)
2009 if (shutdown_read && shutdown_write)
2011 else if (shutdown_read)
2017 if (shutdown (socket->priv->fd, how) != 0)
2019 int errsv = get_socket_errno ();
2020 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2021 _("Unable to create socket: %s"), socket_strerror (errsv));
2025 if (shutdown_read && shutdown_write)
2026 socket->priv->connected = FALSE;
2033 * @socket: a #GSocket
2034 * @error: #GError for error reporting, or %NULL to ignore.
2036 * Closes the socket, shutting down any active connection.
2038 * Closing a socket does not wait for all outstanding I/O operations
2039 * to finish, so the caller should not rely on them to be guaranteed
2040 * to complete even if the close returns with no error.
2042 * Once the socket is closed, all other operations will return
2043 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
2046 * Sockets will be automatically closed when the last reference
2047 * is dropped, but you might want to call this function to make sure
2048 * resources are released as early as possible.
2050 * Beware that due to the way that TCP works, it is possible for
2051 * recently-sent data to be lost if either you close a socket while the
2052 * %G_IO_IN condition is set, or else if the remote connection tries to
2053 * send something to you after you close the socket but before it has
2054 * finished reading all of the data you sent. There is no easy generic
2055 * way to avoid this problem; the easiest fix is to design the network
2056 * protocol such that the client will never send data "out of turn".
2057 * Another solution is for the server to half-close the connection by
2058 * calling g_socket_shutdown() with only the @shutdown_write flag set,
2059 * and then wait for the client to notice this and close its side of the
2060 * connection, after which the server can safely call g_socket_close().
2061 * (This is what #GTcpConnection does if you call
2062 * g_tcp_connection_set_graceful_disconnect(). But of course, this
2063 * only works if the client will close its connection after the server
2066 * Returns: %TRUE on success, %FALSE on error
2071 g_socket_close (GSocket *socket,
2076 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2078 if (socket->priv->closed)
2079 return TRUE; /* Multiple close not an error */
2081 if (!check_socket (socket, NULL))
2087 res = closesocket (socket->priv->fd);
2089 res = close (socket->priv->fd);
2093 int errsv = get_socket_errno ();
2098 g_set_error (error, G_IO_ERROR,
2099 socket_io_error_from_errno (errsv),
2100 _("Error closing socket: %s"),
2101 socket_strerror (errsv));
2107 socket->priv->connected = FALSE;
2108 socket->priv->closed = TRUE;
2114 * g_socket_is_closed:
2115 * @socket: a #GSocket
2117 * Checks whether a socket is closed.
2119 * Returns: %TRUE if socket is closed, %FALSE otherwise
2124 g_socket_is_closed (GSocket *socket)
2126 return socket->priv->closed;
2130 /* Broken source, used on errors */
2132 broken_prepare (GSource *source,
2139 broken_check (GSource *source)
2145 broken_dispatch (GSource *source,
2146 GSourceFunc callback,
2152 static GSourceFuncs broken_funcs =
2161 network_events_for_condition (GIOCondition condition)
2165 if (condition & G_IO_IN)
2166 event_mask |= (FD_READ | FD_ACCEPT);
2167 if (condition & G_IO_OUT)
2168 event_mask |= (FD_WRITE | FD_CONNECT);
2169 event_mask |= FD_CLOSE;
2175 ensure_event (GSocket *socket)
2177 if (socket->priv->event == WSA_INVALID_EVENT)
2178 socket->priv->event = WSACreateEvent();
2182 update_select_events (GSocket *socket)
2189 ensure_event (socket);
2192 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
2195 event_mask |= network_events_for_condition (*ptr);
2198 if (event_mask != socket->priv->selected_events)
2200 /* If no events selected, disable event so we can unset
2203 if (event_mask == 0)
2206 event = socket->priv->event;
2208 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
2209 socket->priv->selected_events = event_mask;
2214 add_condition_watch (GSocket *socket,
2215 GIOCondition *condition)
2217 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
2219 socket->priv->requested_conditions =
2220 g_list_prepend (socket->priv->requested_conditions, condition);
2222 update_select_events (socket);
2226 remove_condition_watch (GSocket *socket,
2227 GIOCondition *condition)
2229 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
2231 socket->priv->requested_conditions =
2232 g_list_remove (socket->priv->requested_conditions, condition);
2234 update_select_events (socket);
2238 update_condition (GSocket *socket)
2240 WSANETWORKEVENTS events;
2241 GIOCondition condition;
2243 if (WSAEnumNetworkEvents (socket->priv->fd,
2244 socket->priv->event,
2247 socket->priv->current_events |= events.lNetworkEvents;
2248 if (events.lNetworkEvents & FD_WRITE &&
2249 events.iErrorCode[FD_WRITE_BIT] != 0)
2250 socket->priv->current_errors |= FD_WRITE;
2251 if (events.lNetworkEvents & FD_CONNECT &&
2252 events.iErrorCode[FD_CONNECT_BIT] != 0)
2253 socket->priv->current_errors |= FD_CONNECT;
2257 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
2258 condition |= G_IO_IN;
2260 if (socket->priv->current_events & FD_CLOSE ||
2261 socket->priv->closed)
2262 condition |= G_IO_HUP;
2264 /* Never report both G_IO_OUT and HUP, these are
2265 mutually exclusive (can't write to a closed socket) */
2266 if ((condition & G_IO_HUP) == 0 &&
2267 socket->priv->current_events & FD_WRITE)
2269 if (socket->priv->current_errors & FD_WRITE)
2270 condition |= G_IO_ERR;
2272 condition |= G_IO_OUT;
2276 if (socket->priv->current_events & FD_CONNECT)
2278 if (socket->priv->current_errors & FD_CONNECT)
2279 condition |= (G_IO_HUP | G_IO_ERR);
2281 condition |= G_IO_OUT;
2293 GIOCondition condition;
2294 GCancellable *cancellable;
2295 GPollFD cancel_pollfd;
2296 GTimeVal timeout_time;
2300 socket_source_prepare (GSource *source,
2303 GSocketSource *socket_source = (GSocketSource *)source;
2305 if (g_cancellable_is_cancelled (socket_source->cancellable))
2308 if (socket_source->timeout_time.tv_sec)
2312 g_source_get_current_time (source, &now);
2313 *timeout = ((socket_source->timeout_time.tv_sec - now.tv_sec) * 1000 +
2314 (socket_source->timeout_time.tv_usec - now.tv_usec) / 1000);
2317 socket_source->socket->priv->timed_out = TRUE;
2318 socket_source->pollfd.revents = socket_source->condition & (G_IO_IN | G_IO_OUT);
2326 socket_source->pollfd.revents = update_condition (socket_source->socket);
2329 if ((socket_source->condition & socket_source->pollfd.revents) != 0)
2336 socket_source_check (GSource *source)
2340 return socket_source_prepare (source, &timeout);
2344 socket_source_dispatch (GSource *source,
2345 GSourceFunc callback,
2348 GSocketSourceFunc func = (GSocketSourceFunc)callback;
2349 GSocketSource *socket_source = (GSocketSource *)source;
2351 return (*func) (socket_source->socket,
2352 socket_source->pollfd.revents & socket_source->condition,
2357 socket_source_finalize (GSource *source)
2359 GSocketSource *socket_source = (GSocketSource *)source;
2362 socket = socket_source->socket;
2365 remove_condition_watch (socket, &socket_source->condition);
2368 g_object_unref (socket);
2370 if (socket_source->cancellable)
2372 g_cancellable_release_fd (socket_source->cancellable);
2373 g_object_unref (socket_source->cancellable);
2377 static GSourceFuncs socket_source_funcs =
2379 socket_source_prepare,
2380 socket_source_check,
2381 socket_source_dispatch,
2382 socket_source_finalize
2386 socket_source_new (GSocket *socket,
2387 GIOCondition condition,
2388 GCancellable *cancellable)
2391 GSocketSource *socket_source;
2394 ensure_event (socket);
2396 if (socket->priv->event == WSA_INVALID_EVENT)
2398 g_warning ("Failed to create WSAEvent");
2399 return g_source_new (&broken_funcs, sizeof (GSource));
2403 condition |= G_IO_HUP | G_IO_ERR;
2405 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
2406 g_source_set_name (source, "GSocket");
2407 socket_source = (GSocketSource *)source;
2409 socket_source->socket = g_object_ref (socket);
2410 socket_source->condition = condition;
2412 if (g_cancellable_make_pollfd (cancellable,
2413 &socket_source->cancel_pollfd))
2415 socket_source->cancellable = g_object_ref (cancellable);
2416 g_source_add_poll (source, &socket_source->cancel_pollfd);
2420 add_condition_watch (socket, &socket_source->condition);
2421 socket_source->pollfd.fd = (gintptr) socket->priv->event;
2423 socket_source->pollfd.fd = socket->priv->fd;
2426 socket_source->pollfd.events = condition;
2427 socket_source->pollfd.revents = 0;
2428 g_source_add_poll (source, &socket_source->pollfd);
2430 if (socket->priv->timeout)
2432 g_get_current_time (&socket_source->timeout_time);
2433 socket_source->timeout_time.tv_sec += socket->priv->timeout;
2437 socket_source->timeout_time.tv_sec = 0;
2438 socket_source->timeout_time.tv_usec = 0;
2445 * g_socket_create_source:
2446 * @socket: a #GSocket
2447 * @condition: a #GIOCondition mask to monitor
2448 * @cancellable: a %GCancellable or %NULL
2450 * Creates a %GSource that can be attached to a %GMainContext to monitor
2451 * for the availibility of the specified @condition on the socket.
2453 * The callback on the source is of the #GSocketSourceFunc type.
2455 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
2456 * these conditions will always be reported output if they are true.
2458 * @cancellable if not %NULL can be used to cancel the source, which will
2459 * cause the source to trigger, reporting the current condition (which
2460 * is likely 0 unless cancellation happened at the same time as a
2461 * condition change). You can check for this in the callback using
2462 * g_cancellable_is_cancelled().
2464 * If @socket has a timeout set, and it is reached before @condition
2465 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
2466 * %G_IO_OUT depending on @condition. However, @socket will have been
2467 * marked as having had a timeout, and so the next #GSocket I/O method
2468 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
2470 * Returns: a newly allocated %GSource, free with g_source_unref().
2475 g_socket_create_source (GSocket *socket,
2476 GIOCondition condition,
2477 GCancellable *cancellable)
2479 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
2481 return socket_source_new (socket, condition, cancellable);
2485 * g_socket_condition_check:
2486 * @socket: a #GSocket
2487 * @condition: a #GIOCondition mask to check
2489 * Checks on the readiness of @socket to perform operations.
2490 * The operations specified in @condition are checked for and masked
2491 * against the currently-satisfied conditions on @socket. The result
2494 * Note that on Windows, it is possible for an operation to return
2495 * %G_IO_ERROR_WOULD_BLOCK even immediately after
2496 * g_socket_condition_check() has claimed that the socket is ready for
2497 * writing. Rather than calling g_socket_condition_check() and then
2498 * writing to the socket if it succeeds, it is generally better to
2499 * simply try writing to the socket right away, and try again later if
2500 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
2502 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2503 * these conditions will always be set in the output if they are true.
2505 * This call never blocks.
2507 * Returns: the @GIOCondition mask of the current state
2512 g_socket_condition_check (GSocket *socket,
2513 GIOCondition condition)
2515 if (!check_socket (socket, NULL))
2520 GIOCondition current_condition;
2522 condition |= G_IO_ERR | G_IO_HUP;
2524 add_condition_watch (socket, &condition);
2525 current_condition = update_condition (socket);
2526 remove_condition_watch (socket, &condition);
2527 return condition & current_condition;
2533 poll_fd.fd = socket->priv->fd;
2534 poll_fd.events = condition;
2537 result = g_poll (&poll_fd, 1, 0);
2538 while (result == -1 && get_socket_errno () == EINTR);
2540 return poll_fd.revents;
2546 * g_socket_condition_wait:
2547 * @socket: a #GSocket
2548 * @condition: a #GIOCondition mask to wait for
2549 * @cancellable: a #GCancellable, or %NULL
2550 * @error: a #GError pointer, or %NULL
2552 * Waits for @condition to become true on @socket. When the condition
2553 * is met, %TRUE is returned.
2555 * If @cancellable is cancelled before the condition is met, or if the
2556 * socket has a timeout set and it is reached before the condition is
2557 * met, then %FALSE is returned and @error, if non-%NULL, is set to
2558 * the appropriate value (%G_IO_ERROR_CANCELLED or
2559 * %G_IO_ERROR_TIMED_OUT).
2561 * Returns: %TRUE if the condition was met, %FALSE otherwise
2566 g_socket_condition_wait (GSocket *socket,
2567 GIOCondition condition,
2568 GCancellable *cancellable,
2571 if (!check_socket (socket, error))
2574 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2579 GIOCondition current_condition;
2585 /* Always check these */
2586 condition |= G_IO_ERR | G_IO_HUP;
2588 add_condition_watch (socket, &condition);
2591 events[num_events++] = socket->priv->event;
2593 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
2594 events[num_events++] = (WSAEVENT)cancel_fd.fd;
2596 if (socket->priv->timeout)
2597 timeout = socket->priv->timeout * 1000;
2599 timeout = WSA_INFINITE;
2601 current_condition = update_condition (socket);
2602 while ((condition & current_condition) == 0)
2604 res = WSAWaitForMultipleEvents(num_events, events,
2605 FALSE, timeout, FALSE);
2606 if (res == WSA_WAIT_FAILED)
2608 int errsv = get_socket_errno ();
2610 g_set_error (error, G_IO_ERROR,
2611 socket_io_error_from_errno (errsv),
2612 _("Waiting for socket condition: %s"),
2613 socket_strerror (errsv));
2616 else if (res == WSA_WAIT_TIMEOUT)
2618 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
2619 _("Socket I/O timed out"));
2623 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2626 current_condition = update_condition (socket);
2628 remove_condition_watch (socket, &condition);
2630 g_cancellable_release_fd (cancellable);
2632 return (condition & current_condition) != 0;
2641 poll_fd[0].fd = socket->priv->fd;
2642 poll_fd[0].events = condition;
2645 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
2648 if (socket->priv->timeout)
2649 timeout = socket->priv->timeout * 1000;
2654 result = g_poll (poll_fd, num, timeout);
2655 while (result == -1 && get_socket_errno () == EINTR);
2658 g_cancellable_release_fd (cancellable);
2662 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
2663 _("Socket I/O timed out"));
2667 return !g_cancellable_set_error_if_cancelled (cancellable, error);
2673 * g_socket_send_message:
2674 * @socket: a #GSocket
2675 * @address: a #GSocketAddress, or %NULL
2676 * @vectors: an array of #GOutputVector structs
2677 * @num_vectors: the number of elements in @vectors, or -1
2678 * @messages: a pointer to an array of #GSocketControlMessages, or
2680 * @num_messages: number of elements in @messages, or -1.
2681 * @flags: an int containing #GSocketMsgFlags flags
2682 * @cancellable: a %GCancellable or %NULL
2683 * @error: #GError for error reporting, or %NULL to ignore.
2685 * Send data to @address on @socket. This is the most complicated and
2686 * fully-featured version of this call. For easier use, see
2687 * g_socket_send() and g_socket_send_to().
2689 * If @address is %NULL then the message is sent to the default receiver
2690 * (set by g_socket_connect()).
2692 * @vectors must point to an array of #GOutputVector structs and
2693 * @num_vectors must be the length of this array. (If @num_vectors is -1,
2694 * then @vectors is assumed to be terminated by a #GOutputVector with a
2695 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
2696 * that the sent data will be gathered from. Using multiple
2697 * #GOutputVector<!-- -->s is more memory-efficient than manually copying
2698 * data from multiple sources into a single buffer, and more
2699 * network-efficient than making multiple calls to g_socket_send().
2701 * @messages, if non-%NULL, is taken to point to an array of @num_messages
2702 * #GSocketControlMessage instances. These correspond to the control
2703 * messages to be sent on the socket.
2704 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
2707 * @flags modify how the message is sent. The commonly available arguments
2708 * for this are available in the #GSocketMsgFlags enum, but the
2709 * values there are the same as the system values, and the flags
2710 * are passed in as-is, so you can pass in system-specific flags too.
2712 * If the socket is in blocking mode the call will block until there is
2713 * space for the data in the socket queue. If there is no space available
2714 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2715 * will be returned. To be notified when space is available, wait for the
2716 * %G_IO_OUT condition. Note though that you may still receive
2717 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2718 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2719 * very common due to the way the underlying APIs work.)
2721 * On error -1 is returned and @error is set accordingly.
2723 * Returns: Number of bytes written (which may be less than @size), or -1
2729 g_socket_send_message (GSocket *socket,
2730 GSocketAddress *address,
2731 GOutputVector *vectors,
2733 GSocketControlMessage **messages,
2736 GCancellable *cancellable,
2739 GOutputVector one_vector;
2742 if (!check_socket (socket, error))
2745 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2748 if (num_vectors == -1)
2750 for (num_vectors = 0;
2751 vectors[num_vectors].buffer != NULL;
2756 if (num_messages == -1)
2758 for (num_messages = 0;
2759 messages != NULL && messages[num_messages] != NULL;
2764 if (num_vectors == 0)
2768 one_vector.buffer = &zero;
2769 one_vector.size = 1;
2771 vectors = &one_vector;
2782 msg.msg_namelen = g_socket_address_get_native_size (address);
2783 msg.msg_name = g_alloca (msg.msg_namelen);
2784 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
2789 msg.msg_name = NULL;
2790 msg.msg_namelen = 0;
2795 /* this entire expression will be evaluated at compile time */
2796 if (sizeof *msg.msg_iov == sizeof *vectors &&
2797 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2798 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2799 G_STRUCT_OFFSET (GOutputVector, buffer) &&
2800 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2801 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2802 G_STRUCT_OFFSET (GOutputVector, size))
2803 /* ABI is compatible */
2805 msg.msg_iov = (struct iovec *) vectors;
2806 msg.msg_iovlen = num_vectors;
2809 /* ABI is incompatible */
2813 msg.msg_iov = g_newa (struct iovec, num_vectors);
2814 for (i = 0; i < num_vectors; i++)
2816 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
2817 msg.msg_iov[i].iov_len = vectors[i].size;
2819 msg.msg_iovlen = num_vectors;
2825 struct cmsghdr *cmsg;
2828 msg.msg_controllen = 0;
2829 for (i = 0; i < num_messages; i++)
2830 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
2832 msg.msg_control = g_alloca (msg.msg_controllen);
2834 cmsg = CMSG_FIRSTHDR (&msg);
2835 for (i = 0; i < num_messages; i++)
2837 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
2838 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
2839 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
2840 g_socket_control_message_serialize (messages[i],
2842 cmsg = CMSG_NXTHDR (&msg, cmsg);
2844 g_assert (cmsg == NULL);
2849 if (socket->priv->blocking &&
2850 !g_socket_condition_wait (socket,
2851 G_IO_OUT, cancellable, error))
2854 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
2857 int errsv = get_socket_errno ();
2862 if (socket->priv->blocking &&
2863 (errsv == EWOULDBLOCK ||
2867 g_set_error (error, G_IO_ERROR,
2868 socket_io_error_from_errno (errsv),
2869 _("Error sending message: %s"), socket_strerror (errsv));
2880 struct sockaddr_storage addr;
2887 /* Win32 doesn't support control messages.
2888 Actually this is possible for raw and datagram sockets
2889 via WSASendMessage on Vista or later, but that doesn't
2891 if (num_messages != 0)
2893 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2894 _("GSocketControlMessage not supported on windows"));
2899 bufs = g_newa (WSABUF, num_vectors);
2900 for (i = 0; i < num_vectors; i++)
2902 bufs[i].buf = (char *)vectors[i].buffer;
2903 bufs[i].len = (gulong)vectors[i].size;
2907 addrlen = 0; /* Avoid warning */
2910 addrlen = g_socket_address_get_native_size (address);
2911 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
2917 if (socket->priv->blocking &&
2918 !g_socket_condition_wait (socket,
2919 G_IO_OUT, cancellable, error))
2923 result = WSASendTo (socket->priv->fd,
2926 (const struct sockaddr *)&addr, addrlen,
2929 result = WSASend (socket->priv->fd,
2936 int errsv = get_socket_errno ();
2938 if (errsv == WSAEINTR)
2941 if (errsv == WSAEWOULDBLOCK)
2942 win32_unset_event_mask (socket, FD_WRITE);
2944 if (socket->priv->blocking &&
2945 errsv == WSAEWOULDBLOCK)
2948 g_set_error (error, G_IO_ERROR,
2949 socket_io_error_from_errno (errsv),
2950 _("Error sending message: %s"), socket_strerror (errsv));
2963 * g_socket_receive_message:
2964 * @socket: a #GSocket
2965 * @address: a pointer to a #GSocketAddress pointer, or %NULL
2966 * @vectors: an array of #GInputVector structs
2967 * @num_vectors: the number of elements in @vectors, or -1
2968 * @messages: a pointer which may be filled with an array of
2969 * #GSocketControlMessages, or %NULL
2970 * @num_messages: a pointer which will be filled with the number of
2971 * elements in @messages, or %NULL
2972 * @flags: a pointer to an int containing #GSocketMsgFlags flags
2973 * @cancellable: a %GCancellable or %NULL
2974 * @error: a #GError pointer, or %NULL
2976 * Receive data from a socket. This is the most complicated and
2977 * fully-featured version of this call. For easier use, see
2978 * g_socket_receive() and g_socket_receive_from().
2980 * If @address is non-%NULL then @address will be set equal to the
2981 * source address of the received packet.
2982 * @address is owned by the caller.
2984 * @vector must point to an array of #GInputVector structs and
2985 * @num_vectors must be the length of this array. These structs
2986 * describe the buffers that received data will be scattered into.
2987 * If @num_vectors is -1, then @vectors is assumed to be terminated
2988 * by a #GInputVector with a %NULL buffer pointer.
2990 * As a special case, if @num_vectors is 0 (in which case, @vectors
2991 * may of course be %NULL), then a single byte is received and
2992 * discarded. This is to facilitate the common practice of sending a
2993 * single '\0' byte for the purposes of transferring ancillary data.
2995 * @messages, if non-%NULL, will be set to point to a newly-allocated
2996 * array of #GSocketControlMessage instances or %NULL if no such
2997 * messages was received. These correspond to the control messages
2998 * received from the kernel, one #GSocketControlMessage per message
2999 * from the kernel. This array is %NULL-terminated and must be freed
3000 * by the caller using g_free() after calling g_object_unref() on each
3001 * element. If @messages is %NULL, any control messages received will
3004 * @num_messages, if non-%NULL, will be set to the number of control
3005 * messages received.
3007 * If both @messages and @num_messages are non-%NULL, then
3008 * @num_messages gives the number of #GSocketControlMessage instances
3009 * in @messages (ie: not including the %NULL terminator).
3011 * @flags is an in/out parameter. The commonly available arguments
3012 * for this are available in the #GSocketMsgFlags enum, but the
3013 * values there are the same as the system values, and the flags
3014 * are passed in as-is, so you can pass in system-specific flags too
3015 * (and g_socket_receive_message() may pass system-specific flags out).
3017 * As with g_socket_receive(), data may be discarded if @socket is
3018 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
3019 * provide enough buffer space to read a complete message. You can pass
3020 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
3021 * removing it from the receive queue, but there is no portable way to find
3022 * out the length of the message other than by reading it into a
3023 * sufficiently-large buffer.
3025 * If the socket is in blocking mode the call will block until there
3026 * is some data to receive or there is an error. If there is no data
3027 * available and the socket is in non-blocking mode, a
3028 * %G_IO_ERROR_WOULD_BLOCK error will be returned. To be notified when
3029 * data is available, wait for the %G_IO_IN condition.
3031 * On error -1 is returned and @error is set accordingly.
3033 * Returns: Number of bytes read, or -1 on error
3038 g_socket_receive_message (GSocket *socket,
3039 GSocketAddress **address,
3040 GInputVector *vectors,
3042 GSocketControlMessage ***messages,
3045 GCancellable *cancellable,
3048 GInputVector one_vector;
3051 if (!check_socket (socket, error))
3054 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3057 if (num_vectors == -1)
3059 for (num_vectors = 0;
3060 vectors[num_vectors].buffer != NULL;
3065 if (num_vectors == 0)
3067 one_vector.buffer = &one_byte;
3068 one_vector.size = 1;
3070 vectors = &one_vector;
3077 struct sockaddr_storage one_sockaddr;
3082 msg.msg_name = &one_sockaddr;
3083 msg.msg_namelen = sizeof (struct sockaddr_storage);
3087 msg.msg_name = NULL;
3088 msg.msg_namelen = 0;
3092 /* this entire expression will be evaluated at compile time */
3093 if (sizeof *msg.msg_iov == sizeof *vectors &&
3094 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3095 G_STRUCT_OFFSET (struct iovec, iov_base) ==
3096 G_STRUCT_OFFSET (GInputVector, buffer) &&
3097 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3098 G_STRUCT_OFFSET (struct iovec, iov_len) ==
3099 G_STRUCT_OFFSET (GInputVector, size))
3100 /* ABI is compatible */
3102 msg.msg_iov = (struct iovec *) vectors;
3103 msg.msg_iovlen = num_vectors;
3106 /* ABI is incompatible */
3110 msg.msg_iov = g_newa (struct iovec, num_vectors);
3111 for (i = 0; i < num_vectors; i++)
3113 msg.msg_iov[i].iov_base = vectors[i].buffer;
3114 msg.msg_iov[i].iov_len = vectors[i].size;
3116 msg.msg_iovlen = num_vectors;
3120 msg.msg_control = g_alloca (2048);
3121 msg.msg_controllen = 2048;
3125 msg.msg_flags = *flags;
3132 if (socket->priv->blocking &&
3133 !g_socket_condition_wait (socket,
3134 G_IO_IN, cancellable, error))
3137 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
3141 int errsv = get_socket_errno ();
3146 if (socket->priv->blocking &&
3147 (errsv == EWOULDBLOCK ||
3151 g_set_error (error, G_IO_ERROR,
3152 socket_io_error_from_errno (errsv),
3153 _("Error receiving message: %s"), socket_strerror (errsv));
3160 /* decode address */
3161 if (address != NULL)
3163 if (msg.msg_namelen > 0)
3164 *address = g_socket_address_new_from_native (msg.msg_name,
3170 /* decode control messages */
3172 GPtrArray *my_messages = NULL;
3173 const gchar *scm_pointer;
3174 struct cmsghdr *cmsg;
3177 scm_pointer = (const gchar *) msg.msg_control;
3178 scm_size = msg.msg_controllen;
3180 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
3182 GSocketControlMessage *message;
3184 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
3186 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
3188 if (message == NULL)
3189 /* We've already spewed about the problem in the
3190 deserialization code, so just continue */
3193 if (messages == NULL)
3195 /* we have to do it this way if the user ignores the
3196 * messages so that we will close any received fds.
3198 g_object_unref (message);
3202 if (my_messages == NULL)
3203 my_messages = g_ptr_array_new ();
3204 g_ptr_array_add (my_messages, message);
3209 *num_messages = my_messages != NULL ? my_messages->len : 0;
3213 if (my_messages == NULL)
3219 g_ptr_array_add (my_messages, NULL);
3220 *messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
3225 g_assert (my_messages == NULL);
3229 /* capture the flags */
3231 *flags = msg.msg_flags;
3237 struct sockaddr_storage addr;
3239 DWORD bytes_received;
3246 bufs = g_newa (WSABUF, num_vectors);
3247 for (i = 0; i < num_vectors; i++)
3249 bufs[i].buf = (char *)vectors[i].buffer;
3250 bufs[i].len = (gulong)vectors[i].size;
3262 if (socket->priv->blocking &&
3263 !g_socket_condition_wait (socket,
3264 G_IO_IN, cancellable, error))
3267 addrlen = sizeof addr;
3269 result = WSARecvFrom (socket->priv->fd,
3271 &bytes_received, &win_flags,
3272 (struct sockaddr *)&addr, &addrlen,
3275 result = WSARecv (socket->priv->fd,
3277 &bytes_received, &win_flags,
3281 int errsv = get_socket_errno ();
3283 if (errsv == WSAEINTR)
3286 win32_unset_event_mask (socket, FD_READ);
3288 if (socket->priv->blocking &&
3289 errsv == WSAEWOULDBLOCK)
3292 g_set_error (error, G_IO_ERROR,
3293 socket_io_error_from_errno (errsv),
3294 _("Error receiving message: %s"), socket_strerror (errsv));
3298 win32_unset_event_mask (socket, FD_READ);
3302 /* decode address */
3303 if (address != NULL)
3306 *address = g_socket_address_new_from_native (&addr, addrlen);
3311 /* capture the flags */
3315 if (messages != NULL)
3317 if (num_messages != NULL)
3320 return bytes_received;
3326 * g_socket_get_credentials:
3327 * @socket: a #GSocket.
3328 * @error: #GError for error reporting, or %NULL to ignore.
3330 * Returns the credentials of the foreign process connected to this
3331 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
3334 * If this operation isn't supported on the OS, the method fails with
3335 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
3336 * by reading the %SO_PEERCRED option on the underlying socket.
3338 * Other ways to obtain credentials from a foreign peer includes the
3339 * #GUnixCredentialsMessage type and
3340 * g_unix_connection_send_credentials() /
3341 * g_unix_connection_receive_credentials() functions.
3343 * Returns: %NULL if @error is set, otherwise a #GCredentials object
3344 * that must be freed with g_object_unref().
3349 g_socket_get_credentials (GSocket *socket,
3354 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
3355 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3361 struct ucred native_creds;
3363 optlen = sizeof (struct ucred);
3364 if (getsockopt (socket->priv->fd,
3367 (void *)&native_creds,
3370 int errsv = get_socket_errno ();
3373 socket_io_error_from_errno (errsv),
3374 _("Unable to get pending error: %s"),
3375 socket_strerror (errsv));
3379 ret = g_credentials_new ();
3380 g_credentials_set_native (ret,
3381 G_CREDENTIALS_TYPE_LINUX_UCRED,
3386 g_set_error_literal (error,
3388 G_IO_ERROR_NOT_SUPPORTED,
3389 _("g_socket_get_credentials not implemented for this OS"));