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;
148 GSocketAddress *remote_address;
156 guint connect_pending : 1;
162 GList *requested_conditions; /* list of requested GIOCondition * */
167 get_socket_errno (void)
172 return WSAGetLastError ();
177 socket_io_error_from_errno (int err)
180 return g_io_error_from_errno (err);
185 return G_IO_ERROR_ADDRESS_IN_USE;
187 return G_IO_ERROR_WOULD_BLOCK;
189 return G_IO_ERROR_PERMISSION_DENIED;
190 case WSA_INVALID_HANDLE:
191 case WSA_INVALID_PARAMETER:
194 return G_IO_ERROR_INVALID_ARGUMENT;
195 case WSAEPROTONOSUPPORT:
196 return G_IO_ERROR_NOT_SUPPORTED;
198 return G_IO_ERROR_CANCELLED;
199 case WSAESOCKTNOSUPPORT:
201 case WSAEPFNOSUPPORT:
202 case WSAEAFNOSUPPORT:
203 return G_IO_ERROR_NOT_SUPPORTED;
205 return G_IO_ERROR_FAILED;
211 socket_strerror (int err)
214 return g_strerror (err);
216 static GStaticPrivate last_msg = G_STATIC_PRIVATE_INIT;
219 msg = g_win32_error_message (err);
220 g_static_private_set (&last_msg, msg, g_free);
227 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
229 _win32_unset_event_mask (GSocket *socket, int mask)
231 socket->priv->current_events &= ~mask;
232 socket->priv->current_errors &= ~mask;
235 #define win32_unset_event_mask(_socket, _mask)
239 set_fd_nonblocking (int fd)
248 if ((arg = fcntl (fd, F_GETFL, NULL)) < 0)
250 g_warning ("Error getting socket status flags: %s", socket_strerror (errno));
254 arg = arg | O_NONBLOCK;
256 if (fcntl (fd, F_SETFL, arg) < 0)
257 g_warning ("Error setting socket status flags: %s", socket_strerror (errno));
261 if (ioctlsocket (fd, FIONBIO, &arg) == SOCKET_ERROR)
263 int errsv = get_socket_errno ();
264 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
270 check_socket (GSocket *socket,
273 if (!socket->priv->inited)
275 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
276 _("Invalid socket, not initialized"));
280 if (socket->priv->construct_error)
282 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
283 _("Invalid socket, initialization failed due to: %s"),
284 socket->priv->construct_error->message);
288 if (socket->priv->closed)
290 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
291 _("Socket is already closed"));
295 if (socket->priv->timed_out)
297 socket->priv->timed_out = FALSE;
298 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
299 _("Socket I/O timed out"));
307 g_socket_details_from_fd (GSocket *socket)
309 struct sockaddr_storage address;
316 /* See bug #611756 */
317 BOOL bool_val = FALSE;
322 fd = socket->priv->fd;
323 optlen = sizeof value;
324 if (getsockopt (fd, SOL_SOCKET, SO_TYPE, (void *)&value, &optlen) != 0)
326 errsv = get_socket_errno ();
337 /* programmer error */
338 g_error ("creating GSocket from fd %d: %s\n",
339 fd, socket_strerror (errsv));
347 g_assert (optlen == sizeof value);
351 socket->priv->type = G_SOCKET_TYPE_STREAM;
355 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
359 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
363 socket->priv->type = G_SOCKET_TYPE_INVALID;
367 addrlen = sizeof address;
368 if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
370 errsv = get_socket_errno ();
374 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
375 sizeof address.ss_family <= addrlen);
376 switch (address.ss_family)
378 case G_SOCKET_FAMILY_IPV4:
379 case G_SOCKET_FAMILY_IPV6:
380 case G_SOCKET_FAMILY_UNIX:
381 socket->priv->family = address.ss_family;
385 socket->priv->family = G_SOCKET_FAMILY_INVALID;
389 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
391 addrlen = sizeof address;
392 if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
393 socket->priv->connected = TRUE;
396 optlen = sizeof bool_val;
397 if (getsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
398 (void *)&bool_val, &optlen) == 0)
401 /* Experimentation indicates that the SO_KEEPALIVE value is
402 * actually a char on Windows, even if documentation claims it
403 * to be a BOOL which is a typedef for int. So this g_assert()
404 * fails. See bug #611756.
406 g_assert (optlen == sizeof bool_val);
408 socket->priv->keepalive = !!bool_val;
412 /* Can't read, maybe not supported, assume FALSE */
413 socket->priv->keepalive = FALSE;
419 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
420 socket_io_error_from_errno (errsv),
421 _("creating GSocket from fd: %s"),
422 socket_strerror (errsv));
426 g_socket_create_socket (GSocketFamily family,
436 case G_SOCKET_TYPE_STREAM:
437 native_type = SOCK_STREAM;
440 case G_SOCKET_TYPE_DATAGRAM:
441 native_type = SOCK_DGRAM;
444 case G_SOCKET_TYPE_SEQPACKET:
445 native_type = SOCK_SEQPACKET;
449 g_assert_not_reached ();
454 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
455 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
460 fd = socket (family, native_type | SOCK_CLOEXEC, protocol);
461 /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
462 if (fd < 0 && errno == EINVAL)
464 fd = socket (family, native_type, protocol);
468 int errsv = get_socket_errno ();
470 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
471 _("Unable to create socket: %s"), socket_strerror (errsv));
478 /* We always want to set close-on-exec to protect users. If you
479 need to so some weird inheritance to exec you can re-enable this
480 using lower level hacks with g_socket_get_fd(). */
481 flags = fcntl (fd, F_GETFD, 0);
483 (flags & FD_CLOEXEC) == 0)
486 fcntl (fd, F_SETFD, flags);
495 g_socket_constructed (GObject *object)
497 GSocket *socket = G_SOCKET (object);
499 if (socket->priv->fd >= 0)
500 /* create socket->priv info from the fd */
501 g_socket_details_from_fd (socket);
504 /* create the fd from socket->priv info */
505 socket->priv->fd = g_socket_create_socket (socket->priv->family,
507 socket->priv->protocol,
508 &socket->priv->construct_error);
510 /* Always use native nonblocking sockets, as
511 windows sets sockets to nonblocking automatically
512 in certain operations. This way we make things work
513 the same on all platforms */
514 if (socket->priv->fd != -1)
515 set_fd_nonblocking (socket->priv->fd);
519 g_socket_get_property (GObject *object,
524 GSocket *socket = G_SOCKET (object);
525 GSocketAddress *address;
530 g_value_set_enum (value, socket->priv->family);
534 g_value_set_enum (value, socket->priv->type);
538 g_value_set_enum (value, socket->priv->protocol);
542 g_value_set_int (value, socket->priv->fd);
546 g_value_set_boolean (value, socket->priv->blocking);
549 case PROP_LISTEN_BACKLOG:
550 g_value_set_int (value, socket->priv->listen_backlog);
554 g_value_set_boolean (value, socket->priv->keepalive);
557 case PROP_LOCAL_ADDRESS:
558 address = g_socket_get_local_address (socket, NULL);
559 g_value_take_object (value, address);
562 case PROP_REMOTE_ADDRESS:
563 address = g_socket_get_remote_address (socket, NULL);
564 g_value_take_object (value, address);
568 g_value_set_uint (value, socket->priv->timeout);
572 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
577 g_socket_set_property (GObject *object,
582 GSocket *socket = G_SOCKET (object);
587 socket->priv->family = g_value_get_enum (value);
591 socket->priv->type = g_value_get_enum (value);
595 socket->priv->protocol = g_value_get_enum (value);
599 socket->priv->fd = g_value_get_int (value);
603 g_socket_set_blocking (socket, g_value_get_boolean (value));
606 case PROP_LISTEN_BACKLOG:
607 g_socket_set_listen_backlog (socket, g_value_get_int (value));
611 g_socket_set_keepalive (socket, g_value_get_boolean (value));
615 g_socket_set_timeout (socket, g_value_get_uint (value));
619 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
624 g_socket_finalize (GObject *object)
626 GSocket *socket = G_SOCKET (object);
628 g_clear_error (&socket->priv->construct_error);
630 if (socket->priv->fd != -1 &&
631 !socket->priv->closed)
632 g_socket_close (socket, NULL);
634 if (socket->priv->remote_address)
635 g_object_unref (socket->priv->remote_address);
638 if (socket->priv->event != WSA_INVALID_EVENT)
640 WSACloseEvent (socket->priv->event);
641 socket->priv->event = WSA_INVALID_EVENT;
644 g_assert (socket->priv->requested_conditions == NULL);
647 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
648 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
652 g_socket_class_init (GSocketClass *klass)
654 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
657 /* Make sure winsock has been initialized */
658 type = g_inet_address_get_type ();
661 /* There is no portable, thread-safe way to avoid having the process
662 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
663 * forced to simply ignore the signal process-wide.
665 signal (SIGPIPE, SIG_IGN);
668 g_type_class_add_private (klass, sizeof (GSocketPrivate));
670 gobject_class->finalize = g_socket_finalize;
671 gobject_class->constructed = g_socket_constructed;
672 gobject_class->set_property = g_socket_set_property;
673 gobject_class->get_property = g_socket_get_property;
675 g_object_class_install_property (gobject_class, PROP_FAMILY,
676 g_param_spec_enum ("family",
678 P_("The sockets address family"),
679 G_TYPE_SOCKET_FAMILY,
680 G_SOCKET_FAMILY_INVALID,
681 G_PARAM_CONSTRUCT_ONLY |
683 G_PARAM_STATIC_STRINGS));
685 g_object_class_install_property (gobject_class, PROP_TYPE,
686 g_param_spec_enum ("type",
688 P_("The sockets type"),
690 G_SOCKET_TYPE_STREAM,
691 G_PARAM_CONSTRUCT_ONLY |
693 G_PARAM_STATIC_STRINGS));
695 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
696 g_param_spec_enum ("protocol",
697 P_("Socket protocol"),
698 P_("The id of the protocol to use, or -1 for unknown"),
699 G_TYPE_SOCKET_PROTOCOL,
700 G_SOCKET_PROTOCOL_UNKNOWN,
701 G_PARAM_CONSTRUCT_ONLY |
703 G_PARAM_STATIC_STRINGS));
705 g_object_class_install_property (gobject_class, PROP_FD,
706 g_param_spec_int ("fd",
707 P_("File descriptor"),
708 P_("The sockets file descriptor"),
712 G_PARAM_CONSTRUCT_ONLY |
714 G_PARAM_STATIC_STRINGS));
716 g_object_class_install_property (gobject_class, PROP_BLOCKING,
717 g_param_spec_boolean ("blocking",
719 P_("Whether or not I/O on this socket is blocking"),
722 G_PARAM_STATIC_STRINGS));
724 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
725 g_param_spec_int ("listen-backlog",
726 P_("Listen backlog"),
727 P_("Outstanding connections in the listen queue"),
732 G_PARAM_STATIC_STRINGS));
734 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
735 g_param_spec_boolean ("keepalive",
736 P_("Keep connection alive"),
737 P_("Keep connection alive by sending periodic pings"),
740 G_PARAM_STATIC_STRINGS));
742 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
743 g_param_spec_object ("local-address",
745 P_("The local address the socket is bound to"),
746 G_TYPE_SOCKET_ADDRESS,
748 G_PARAM_STATIC_STRINGS));
750 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
751 g_param_spec_object ("remote-address",
752 P_("Remote address"),
753 P_("The remote address the socket is connected to"),
754 G_TYPE_SOCKET_ADDRESS,
756 G_PARAM_STATIC_STRINGS));
761 * The timeout in seconds on socket I/O
765 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
766 g_param_spec_uint ("timeout",
768 P_("The timeout in seconds on socket I/O"),
773 G_PARAM_STATIC_STRINGS));
777 g_socket_initable_iface_init (GInitableIface *iface)
779 iface->init = g_socket_initable_init;
783 g_socket_init (GSocket *socket)
785 socket->priv = G_TYPE_INSTANCE_GET_PRIVATE (socket, G_TYPE_SOCKET, GSocketPrivate);
787 socket->priv->fd = -1;
788 socket->priv->blocking = TRUE;
789 socket->priv->listen_backlog = 10;
790 socket->priv->construct_error = NULL;
792 socket->priv->event = WSA_INVALID_EVENT;
797 g_socket_initable_init (GInitable *initable,
798 GCancellable *cancellable,
803 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
805 socket = G_SOCKET (initable);
807 if (cancellable != NULL)
809 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
810 _("Cancellable initialization not supported"));
814 socket->priv->inited = TRUE;
816 if (socket->priv->construct_error)
819 *error = g_error_copy (socket->priv->construct_error);
829 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
830 * @type: the socket type to use.
831 * @protocol: the id of the protocol to use, or 0 for default.
832 * @error: #GError for error reporting, or %NULL to ignore.
834 * Creates a new #GSocket with the defined family, type and protocol.
835 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
836 * for the family and type is used.
838 * The @protocol is a family and type specific int that specifies what
839 * kind of protocol to use. #GSocketProtocol lists several common ones.
840 * Many families only support one protocol, and use 0 for this, others
841 * support several and using 0 means to use the default protocol for
842 * the family and type.
844 * The protocol id is passed directly to the operating
845 * system, so you can use protocols not listed in #GSocketProtocol if you
846 * know the protocol number used for it.
848 * Returns: a #GSocket or %NULL on error.
849 * Free the returned object with g_object_unref().
854 g_socket_new (GSocketFamily family,
856 GSocketProtocol protocol,
859 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
863 "protocol", protocol,
868 * g_socket_new_from_fd:
869 * @fd: a native socket file descriptor.
870 * @error: #GError for error reporting, or %NULL to ignore.
872 * Creates a new #GSocket from a native file descriptor
873 * or winsock SOCKET handle.
875 * This reads all the settings from the file descriptor so that
876 * all properties should work. Note that the file descriptor
877 * will be set to non-blocking mode, independent on the blocking
878 * mode of the #GSocket.
880 * Returns: a #GSocket or %NULL on error.
881 * Free the returned object with g_object_unref().
886 g_socket_new_from_fd (gint fd,
889 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
896 * g_socket_set_blocking:
897 * @socket: a #GSocket.
898 * @blocking: Whether to use blocking I/O or not.
900 * Sets the blocking mode of the socket. In blocking mode
901 * all operations block until they succeed or there is an error. In
902 * non-blocking mode all functions return results immediately or
903 * with a %G_IO_ERROR_WOULD_BLOCK error.
905 * All sockets are created in blocking mode. However, note that the
906 * platform level socket is always non-blocking, and blocking mode
907 * is a GSocket level feature.
912 g_socket_set_blocking (GSocket *socket,
915 g_return_if_fail (G_IS_SOCKET (socket));
917 blocking = !!blocking;
919 if (socket->priv->blocking == blocking)
922 socket->priv->blocking = blocking;
923 g_object_notify (G_OBJECT (socket), "blocking");
927 * g_socket_get_blocking:
928 * @socket: a #GSocket.
930 * Gets the blocking mode of the socket. For details on blocking I/O,
931 * see g_socket_set_blocking().
933 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
938 g_socket_get_blocking (GSocket *socket)
940 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
942 return socket->priv->blocking;
946 * g_socket_set_keepalive:
947 * @socket: a #GSocket.
948 * @keepalive: Value for the keepalive flag
950 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
951 * this flag is set on a socket, the system will attempt to verify that the
952 * remote socket endpoint is still present if a sufficiently long period of
953 * time passes with no data being exchanged. If the system is unable to
954 * verify the presence of the remote endpoint, it will automatically close
957 * This option is only functional on certain kinds of sockets. (Notably,
958 * %G_SOCKET_PROTOCOL_TCP sockets.)
960 * The exact time between pings is system- and protocol-dependent, but will
961 * normally be at least two hours. Most commonly, you would set this flag
962 * on a server socket if you want to allow clients to remain idle for long
963 * periods of time, but also want to ensure that connections are eventually
964 * garbage-collected if clients crash or become unreachable.
969 g_socket_set_keepalive (GSocket *socket,
974 g_return_if_fail (G_IS_SOCKET (socket));
976 keepalive = !!keepalive;
977 if (socket->priv->keepalive == keepalive)
980 value = (gint) keepalive;
981 if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_KEEPALIVE,
982 (gpointer) &value, sizeof (value)) < 0)
984 int errsv = get_socket_errno ();
985 g_warning ("error setting keepalive: %s", socket_strerror (errsv));
989 socket->priv->keepalive = keepalive;
990 g_object_notify (G_OBJECT (socket), "keepalive");
994 * g_socket_get_keepalive:
995 * @socket: a #GSocket.
997 * Gets the keepalive mode of the socket. For details on this,
998 * see g_socket_set_keepalive().
1000 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1005 g_socket_get_keepalive (GSocket *socket)
1007 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1009 return socket->priv->keepalive;
1013 * g_socket_get_listen_backlog:
1014 * @socket: a #GSocket.
1016 * Gets the listen backlog setting of the socket. For details on this,
1017 * see g_socket_set_listen_backlog().
1019 * Returns: the maximum number of pending connections.
1024 g_socket_get_listen_backlog (GSocket *socket)
1026 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1028 return socket->priv->listen_backlog;
1032 * g_socket_set_listen_backlog:
1033 * @socket: a #GSocket.
1034 * @backlog: the maximum number of pending connections.
1036 * Sets the maximum number of outstanding connections allowed
1037 * when listening on this socket. If more clients than this are
1038 * connecting to the socket and the application is not handling them
1039 * on time then the new connections will be refused.
1041 * Note that this must be called before g_socket_listen() and has no
1042 * effect if called after that.
1047 g_socket_set_listen_backlog (GSocket *socket,
1050 g_return_if_fail (G_IS_SOCKET (socket));
1051 g_return_if_fail (!socket->priv->listening);
1053 if (backlog != socket->priv->listen_backlog)
1055 socket->priv->listen_backlog = backlog;
1056 g_object_notify (G_OBJECT (socket), "listen-backlog");
1061 * g_socket_get_timeout:
1062 * @socket: a #GSocket.
1064 * Gets the timeout setting of the socket. For details on this, see
1065 * g_socket_set_timeout().
1067 * Returns: the timeout in seconds
1072 g_socket_get_timeout (GSocket *socket)
1074 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1076 return socket->priv->timeout;
1080 * g_socket_set_timeout:
1081 * @socket: a #GSocket.
1082 * @timeout: the timeout for @socket, in seconds, or 0 for none
1084 * Sets the time in seconds after which I/O operations on @socket will
1085 * time out if they have not yet completed.
1087 * On a blocking socket, this means that any blocking #GSocket
1088 * operation will time out after @timeout seconds of inactivity,
1089 * returning %G_IO_ERROR_TIMED_OUT.
1091 * On a non-blocking socket, calls to g_socket_condition_wait() will
1092 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1093 * created with g_socket_create_source() will trigger after
1094 * @timeout seconds of inactivity, with the requested condition
1095 * set, at which point calling g_socket_receive(), g_socket_send(),
1096 * g_socket_check_connect_result(), etc, will fail with
1097 * %G_IO_ERROR_TIMED_OUT.
1099 * If @timeout is 0 (the default), operations will never time out
1102 * Note that if an I/O operation is interrupted by a signal, this may
1103 * cause the timeout to be reset.
1108 g_socket_set_timeout (GSocket *socket,
1111 g_return_if_fail (G_IS_SOCKET (socket));
1113 if (timeout != socket->priv->timeout)
1115 socket->priv->timeout = timeout;
1116 g_object_notify (G_OBJECT (socket), "timeout");
1121 * g_socket_get_family:
1122 * @socket: a #GSocket.
1124 * Gets the socket family of the socket.
1126 * Returns: a #GSocketFamily
1131 g_socket_get_family (GSocket *socket)
1133 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1135 return socket->priv->family;
1139 * g_socket_get_socket_type:
1140 * @socket: a #GSocket.
1142 * Gets the socket type of the socket.
1144 * Returns: a #GSocketType
1149 g_socket_get_socket_type (GSocket *socket)
1151 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1153 return socket->priv->type;
1157 * g_socket_get_protocol:
1158 * @socket: a #GSocket.
1160 * Gets the socket protocol id the socket was created with.
1161 * In case the protocol is unknown, -1 is returned.
1163 * Returns: a protocol id, or -1 if unknown
1168 g_socket_get_protocol (GSocket *socket)
1170 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1172 return socket->priv->protocol;
1177 * @socket: a #GSocket.
1179 * Returns the underlying OS socket object. On unix this
1180 * is a socket file descriptor, and on windows this is
1181 * a Winsock2 SOCKET handle. This may be useful for
1182 * doing platform specific or otherwise unusual operations
1185 * Returns: the file descriptor of the socket.
1190 g_socket_get_fd (GSocket *socket)
1192 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1194 return socket->priv->fd;
1198 * g_socket_get_local_address:
1199 * @socket: a #GSocket.
1200 * @error: #GError for error reporting, or %NULL to ignore.
1202 * Try to get the local address of a bound socket. This is only
1203 * useful if the socket has been bound to a local address,
1204 * either explicitly or implicitly when connecting.
1206 * Returns: a #GSocketAddress or %NULL on error.
1207 * Free the returned object with g_object_unref().
1212 g_socket_get_local_address (GSocket *socket,
1215 struct sockaddr_storage buffer;
1216 guint32 len = sizeof (buffer);
1218 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1220 if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1222 int errsv = get_socket_errno ();
1223 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1224 _("could not get local address: %s"), socket_strerror (errsv));
1228 return g_socket_address_new_from_native (&buffer, len);
1232 * g_socket_get_remote_address:
1233 * @socket: a #GSocket.
1234 * @error: #GError for error reporting, or %NULL to ignore.
1236 * Try to get the remove address of a connected socket. This is only
1237 * useful for connection oriented sockets that have been connected.
1239 * Returns: a #GSocketAddress or %NULL on error.
1240 * Free the returned object with g_object_unref().
1245 g_socket_get_remote_address (GSocket *socket,
1248 struct sockaddr_storage buffer;
1249 guint32 len = sizeof (buffer);
1251 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1253 if (socket->priv->connect_pending)
1255 if (!g_socket_check_connect_result (socket, error))
1258 socket->priv->connect_pending = FALSE;
1261 if (!socket->priv->remote_address)
1263 if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1265 int errsv = get_socket_errno ();
1266 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1267 _("could not get remote address: %s"), socket_strerror (errsv));
1271 socket->priv->remote_address = g_socket_address_new_from_native (&buffer, len);
1274 return g_object_ref (socket->priv->remote_address);
1278 * g_socket_is_connected:
1279 * @socket: a #GSocket.
1281 * Check whether the socket is connected. This is only useful for
1282 * connection-oriented sockets.
1284 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1289 g_socket_is_connected (GSocket *socket)
1291 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1293 return socket->priv->connected;
1298 * @socket: a #GSocket.
1299 * @error: #GError for error reporting, or %NULL to ignore.
1301 * Marks the socket as a server socket, i.e. a socket that is used
1302 * to accept incoming requests using g_socket_accept().
1304 * Before calling this the socket must be bound to a local address using
1307 * To set the maximum amount of outstanding clients, use
1308 * g_socket_set_listen_backlog().
1310 * Returns: %TRUE on success, %FALSE on error.
1315 g_socket_listen (GSocket *socket,
1318 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1320 if (!check_socket (socket, error))
1323 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1325 int errsv = get_socket_errno ();
1327 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1328 _("could not listen: %s"), socket_strerror (errsv));
1332 socket->priv->listening = TRUE;
1339 * @socket: a #GSocket.
1340 * @address: a #GSocketAddress specifying the local address.
1341 * @allow_reuse: whether to allow reusing this address
1342 * @error: #GError for error reporting, or %NULL to ignore.
1344 * When a socket is created it is attached to an address family, but it
1345 * doesn't have an address in this family. g_socket_bind() assigns the
1346 * address (sometimes called name) of the socket.
1348 * It is generally required to bind to a local address before you can
1349 * receive connections. (See g_socket_listen() and g_socket_accept() ).
1350 * In certain situations, you may also want to bind a socket that will be
1351 * used to initiate connections, though this is not normally required.
1353 * @allow_reuse should be %TRUE for server sockets (sockets that you will
1354 * eventually call g_socket_accept() on), and %FALSE for client sockets.
1355 * (Specifically, if it is %TRUE, then g_socket_bind() will set the
1356 * %SO_REUSEADDR flag on the socket, allowing it to bind @address even if
1357 * that address was previously used by another socket that has not yet been
1358 * fully cleaned-up by the kernel. Failing to set this flag on a server
1359 * socket may cause the bind call to return %G_IO_ERROR_ADDRESS_IN_USE if
1360 * the server program is stopped and then immediately restarted.)
1362 * Returns: %TRUE on success, %FALSE on error.
1367 g_socket_bind (GSocket *socket,
1368 GSocketAddress *address,
1369 gboolean reuse_address,
1372 struct sockaddr_storage addr;
1374 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1376 if (!check_socket (socket, error))
1379 /* SO_REUSEADDR on windows means something else and is not what we want.
1380 It always allows the unix variant of SO_REUSEADDR anyway */
1385 value = (int) !!reuse_address;
1386 /* Ignore errors here, the only likely error is "not supported", and
1387 this is a "best effort" thing mainly */
1388 setsockopt (socket->priv->fd, SOL_SOCKET, SO_REUSEADDR,
1389 (gpointer) &value, sizeof (value));
1393 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1396 if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1397 g_socket_address_get_native_size (address)) < 0)
1399 int errsv = get_socket_errno ();
1401 G_IO_ERROR, socket_io_error_from_errno (errsv),
1402 _("Error binding to address: %s"), socket_strerror (errsv));
1410 * g_socket_speaks_ipv4:
1411 * @socket: a #GSocket
1413 * Checks if a socket is capable of speaking IPv4.
1415 * IPv4 sockets are capable of speaking IPv4. On some operating systems
1416 * and under some combinations of circumstances IPv6 sockets are also
1417 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
1420 * No other types of sockets are currently considered as being capable
1423 * Returns: %TRUE if this socket can be used with IPv4.
1428 g_socket_speaks_ipv4 (GSocket *socket)
1430 switch (socket->priv->family)
1432 case G_SOCKET_FAMILY_IPV4:
1435 case G_SOCKET_FAMILY_IPV6:
1436 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
1438 guint sizeof_int = sizeof (int);
1441 if (getsockopt (socket->priv->fd,
1442 IPPROTO_IPV6, IPV6_V6ONLY,
1443 &v6_only, &sizeof_int) != 0)
1459 * @socket: a #GSocket.
1460 * @cancellable: a %GCancellable or %NULL
1461 * @error: #GError for error reporting, or %NULL to ignore.
1463 * Accept incoming connections on a connection-based socket. This removes
1464 * the first outstanding connection request from the listening socket and
1465 * creates a #GSocket object for it.
1467 * The @socket must be bound to a local address with g_socket_bind() and
1468 * must be listening for incoming connections (g_socket_listen()).
1470 * If there are no outstanding connections then the operation will block
1471 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
1472 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
1474 * Returns: a new #GSocket, or %NULL on error.
1475 * Free the returned object with g_object_unref().
1480 g_socket_accept (GSocket *socket,
1481 GCancellable *cancellable,
1484 GSocket *new_socket;
1487 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1489 if (!check_socket (socket, error))
1494 if (socket->priv->blocking &&
1495 !g_socket_condition_wait (socket,
1496 G_IO_IN, cancellable, error))
1499 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
1501 int errsv = get_socket_errno ();
1503 win32_unset_event_mask (socket, FD_ACCEPT);
1508 if (socket->priv->blocking)
1510 #ifdef WSAEWOULDBLOCK
1511 if (errsv == WSAEWOULDBLOCK)
1514 if (errsv == EWOULDBLOCK ||
1520 g_set_error (error, G_IO_ERROR,
1521 socket_io_error_from_errno (errsv),
1522 _("Error accepting connection: %s"), socket_strerror (errsv));
1528 win32_unset_event_mask (socket, FD_ACCEPT);
1532 /* The socket inherits the accepting sockets event mask and even object,
1533 we need to remove that */
1534 WSAEventSelect (ret, NULL, 0);
1540 /* We always want to set close-on-exec to protect users. If you
1541 need to so some weird inheritance to exec you can re-enable this
1542 using lower level hacks with g_socket_get_fd(). */
1543 flags = fcntl (ret, F_GETFD, 0);
1545 (flags & FD_CLOEXEC) == 0)
1547 flags |= FD_CLOEXEC;
1548 fcntl (ret, F_SETFD, flags);
1553 new_socket = g_socket_new_from_fd (ret, error);
1554 if (new_socket == NULL)
1563 new_socket->priv->protocol = socket->priv->protocol;
1570 * @socket: a #GSocket.
1571 * @address: a #GSocketAddress specifying the remote address.
1572 * @cancellable: a %GCancellable or %NULL
1573 * @error: #GError for error reporting, or %NULL to ignore.
1575 * Connect the socket to the specified remote address.
1577 * For connection oriented socket this generally means we attempt to make
1578 * a connection to the @address. For a connection-less socket it sets
1579 * the default address for g_socket_send() and discards all incoming datagrams
1580 * from other sources.
1582 * Generally connection oriented sockets can only connect once, but
1583 * connection-less sockets can connect multiple times to change the
1586 * If the connect call needs to do network I/O it will block, unless
1587 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
1588 * and the user can be notified of the connection finishing by waiting
1589 * for the G_IO_OUT condition. The result of the connection can then be
1590 * checked with g_socket_check_connect_result().
1592 * Returns: %TRUE if connected, %FALSE on error.
1597 g_socket_connect (GSocket *socket,
1598 GSocketAddress *address,
1599 GCancellable *cancellable,
1602 struct sockaddr_storage buffer;
1604 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1606 if (!check_socket (socket, error))
1609 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
1612 if (socket->priv->remote_address)
1613 g_object_unref (socket->priv->remote_address);
1614 socket->priv->remote_address = g_object_ref (address);
1618 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
1619 g_socket_address_get_native_size (address)) < 0)
1621 int errsv = get_socket_errno ();
1627 if (errsv == EINPROGRESS)
1629 if (errsv == WSAEWOULDBLOCK)
1632 if (socket->priv->blocking)
1634 if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
1636 if (g_socket_check_connect_result (socket, error))
1639 g_prefix_error (error, _("Error connecting: "));
1643 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
1644 _("Connection in progress"));
1645 socket->priv->connect_pending = TRUE;
1649 g_set_error (error, G_IO_ERROR,
1650 socket_io_error_from_errno (errsv),
1651 _("Error connecting: %s"), socket_strerror (errsv));
1658 win32_unset_event_mask (socket, FD_CONNECT);
1660 socket->priv->connected = TRUE;
1666 * g_socket_check_connect_result:
1667 * @socket: a #GSocket
1668 * @error: #GError for error reporting, or %NULL to ignore.
1670 * Checks and resets the pending connect error for the socket.
1671 * This is used to check for errors when g_socket_connect() is
1672 * used in non-blocking mode.
1674 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
1679 g_socket_check_connect_result (GSocket *socket,
1685 if (!check_socket (socket, error))
1688 optlen = sizeof (value);
1689 if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
1691 int errsv = get_socket_errno ();
1693 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1694 _("Unable to get pending error: %s"), socket_strerror (errsv));
1700 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
1701 socket_strerror (value));
1702 if (socket->priv->remote_address)
1704 g_object_unref (socket->priv->remote_address);
1705 socket->priv->remote_address = NULL;
1714 * @socket: a #GSocket
1715 * @buffer: a buffer to read data into (which should be at least @size
1717 * @size: the number of bytes you want to read from the socket
1718 * @cancellable: a %GCancellable or %NULL
1719 * @error: #GError for error reporting, or %NULL to ignore.
1721 * Receive data (up to @size bytes) from a socket. This is mainly used by
1722 * connection-oriented sockets; it is identical to g_socket_receive_from()
1723 * with @address set to %NULL.
1725 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
1726 * g_socket_receive() will always read either 0 or 1 complete messages from
1727 * the socket. If the received message is too large to fit in @buffer, then
1728 * the data beyond @size bytes will be discarded, without any explicit
1729 * indication that this has occurred.
1731 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
1732 * number of bytes, up to @size. If more than @size bytes have been
1733 * received, the additional data will be returned in future calls to
1734 * g_socket_receive().
1736 * If the socket is in blocking mode the call will block until there is
1737 * some data to receive or there is an error. If there is no data available
1738 * and the socket is in non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error
1739 * will be returned. To be notified when data is available, wait for the
1740 * %G_IO_IN condition.
1742 * On error -1 is returned and @error is set accordingly.
1744 * Returns: Number of bytes read, or -1 on error
1749 g_socket_receive (GSocket *socket,
1752 GCancellable *cancellable,
1755 return g_socket_receive_with_blocking (socket, buffer, size,
1756 socket->priv->blocking,
1757 cancellable, error);
1761 * g_socket_receive_with_blocking:
1762 * @socket: a #GSocket
1763 * @buffer: a buffer to read data into (which should be at least @size
1765 * @size: the number of bytes you want to read from the socket
1766 * @blocking: whether to do blocking or non-blocking I/O
1767 * @cancellable: a %GCancellable or %NULL
1768 * @error: #GError for error reporting, or %NULL to ignore.
1770 * This behaves exactly the same as g_socket_receive(), except that
1771 * the choice of blocking or non-blocking behavior is determined by
1772 * the @blocking argument rather than by @socket's properties.
1774 * Returns: Number of bytes read, or -1 on error
1779 g_socket_receive_with_blocking (GSocket *socket,
1783 GCancellable *cancellable,
1788 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1790 if (!check_socket (socket, error))
1793 if (g_cancellable_set_error_if_cancelled (cancellable, error))
1799 !g_socket_condition_wait (socket,
1800 G_IO_IN, cancellable, error))
1803 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
1805 int errsv = get_socket_errno ();
1812 #ifdef WSAEWOULDBLOCK
1813 if (errsv == WSAEWOULDBLOCK)
1816 if (errsv == EWOULDBLOCK ||
1822 win32_unset_event_mask (socket, FD_READ);
1824 g_set_error (error, G_IO_ERROR,
1825 socket_io_error_from_errno (errsv),
1826 _("Error receiving data: %s"), socket_strerror (errsv));
1830 win32_unset_event_mask (socket, FD_READ);
1839 * g_socket_receive_from:
1840 * @socket: a #GSocket
1841 * @address: a pointer to a #GSocketAddress pointer, or %NULL
1842 * @buffer: a buffer to read data into (which should be at least @size
1844 * @size: the number of bytes you want to read from the socket
1845 * @cancellable: a %GCancellable or %NULL
1846 * @error: #GError for error reporting, or %NULL to ignore.
1848 * Receive data (up to @size bytes) from a socket.
1850 * If @address is non-%NULL then @address will be set equal to the
1851 * source address of the received packet.
1852 * @address is owned by the caller.
1854 * See g_socket_receive() for additional information.
1856 * Returns: Number of bytes read, or -1 on error
1861 g_socket_receive_from (GSocket *socket,
1862 GSocketAddress **address,
1865 GCancellable *cancellable,
1873 return g_socket_receive_message (socket,
1881 /* Although we ignore SIGPIPE, gdb will still stop if the app receives
1882 * one, which can be confusing and annoying. So if possible, we want
1883 * to suppress the signal entirely.
1886 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
1888 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
1893 * @socket: a #GSocket
1894 * @buffer: the buffer containing the data to send.
1895 * @size: the number of bytes to send
1896 * @cancellable: a %GCancellable or %NULL
1897 * @error: #GError for error reporting, or %NULL to ignore.
1899 * Tries to send @size bytes from @buffer on the socket. This is
1900 * mainly used by connection-oriented sockets; it is identical to
1901 * g_socket_send_to() with @address set to %NULL.
1903 * If the socket is in blocking mode the call will block until there is
1904 * space for the data in the socket queue. If there is no space available
1905 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1906 * will be returned. To be notified when space is available, wait for the
1907 * %G_IO_OUT condition. Note though that you may still receive
1908 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
1909 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
1910 * very common due to the way the underlying APIs work.)
1912 * On error -1 is returned and @error is set accordingly.
1914 * Returns: Number of bytes written (which may be less than @size), or -1
1920 g_socket_send (GSocket *socket,
1921 const gchar *buffer,
1923 GCancellable *cancellable,
1926 return g_socket_send_with_blocking (socket, buffer, size,
1927 socket->priv->blocking,
1928 cancellable, error);
1932 * g_socket_send_with_blocking:
1933 * @socket: a #GSocket
1934 * @buffer: the buffer containing the data to send.
1935 * @size: the number of bytes to send
1936 * @blocking: whether to do blocking or non-blocking I/O
1937 * @cancellable: a %GCancellable or %NULL
1938 * @error: #GError for error reporting, or %NULL to ignore.
1940 * This behaves exactly the same as g_socket_send(), except that
1941 * the choice of blocking or non-blocking behavior is determined by
1942 * the @blocking argument rather than by @socket's properties.
1944 * Returns: Number of bytes written (which may be less than @size), or -1
1950 g_socket_send_with_blocking (GSocket *socket,
1951 const gchar *buffer,
1954 GCancellable *cancellable,
1959 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1961 if (!check_socket (socket, error))
1964 if (g_cancellable_set_error_if_cancelled (cancellable, error))
1970 !g_socket_condition_wait (socket,
1971 G_IO_OUT, cancellable, error))
1974 if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
1976 int errsv = get_socket_errno ();
1981 #ifdef WSAEWOULDBLOCK
1982 if (errsv == WSAEWOULDBLOCK)
1983 win32_unset_event_mask (socket, FD_WRITE);
1988 #ifdef WSAEWOULDBLOCK
1989 if (errsv == WSAEWOULDBLOCK)
1992 if (errsv == EWOULDBLOCK ||
1998 g_set_error (error, G_IO_ERROR,
1999 socket_io_error_from_errno (errsv),
2000 _("Error sending data: %s"), socket_strerror (errsv));
2011 * @socket: a #GSocket
2012 * @address: a #GSocketAddress, or %NULL
2013 * @buffer: the buffer containing the data to send.
2014 * @size: the number of bytes to send
2015 * @cancellable: a %GCancellable or %NULL
2016 * @error: #GError for error reporting, or %NULL to ignore.
2018 * Tries to send @size bytes from @buffer to @address. If @address is
2019 * %NULL then the message is sent to the default receiver (set by
2020 * g_socket_connect()).
2022 * See g_socket_send() for additional information.
2024 * Returns: Number of bytes written (which may be less than @size), or -1
2030 g_socket_send_to (GSocket *socket,
2031 GSocketAddress *address,
2032 const gchar *buffer,
2034 GCancellable *cancellable,
2042 return g_socket_send_message (socket,
2052 * g_socket_shutdown:
2053 * @socket: a #GSocket
2054 * @shutdown_read: whether to shut down the read side
2055 * @shutdown_write: whether to shut down the write side
2056 * @error: #GError for error reporting, or %NULL to ignore.
2058 * Shut down part of a full-duplex connection.
2060 * If @shutdown_read is %TRUE then the recieving side of the connection
2061 * is shut down, and further reading is disallowed.
2063 * If @shutdown_write is %TRUE then the sending side of the connection
2064 * is shut down, and further writing is disallowed.
2066 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
2068 * One example where this is used is graceful disconnect for TCP connections
2069 * where you close the sending side, then wait for the other side to close
2070 * the connection, thus ensuring that the other side saw all sent data.
2072 * Returns: %TRUE on success, %FALSE on error
2077 g_socket_shutdown (GSocket *socket,
2078 gboolean shutdown_read,
2079 gboolean shutdown_write,
2084 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2086 if (!check_socket (socket, NULL))
2090 if (!shutdown_read && !shutdown_write)
2094 if (shutdown_read && shutdown_write)
2096 else if (shutdown_read)
2101 if (shutdown_read && shutdown_write)
2103 else if (shutdown_read)
2109 if (shutdown (socket->priv->fd, how) != 0)
2111 int errsv = get_socket_errno ();
2112 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2113 _("Unable to create socket: %s"), socket_strerror (errsv));
2117 if (shutdown_read && shutdown_write)
2118 socket->priv->connected = FALSE;
2125 * @socket: a #GSocket
2126 * @error: #GError for error reporting, or %NULL to ignore.
2128 * Closes the socket, shutting down any active connection.
2130 * Closing a socket does not wait for all outstanding I/O operations
2131 * to finish, so the caller should not rely on them to be guaranteed
2132 * to complete even if the close returns with no error.
2134 * Once the socket is closed, all other operations will return
2135 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
2138 * Sockets will be automatically closed when the last reference
2139 * is dropped, but you might want to call this function to make sure
2140 * resources are released as early as possible.
2142 * Beware that due to the way that TCP works, it is possible for
2143 * recently-sent data to be lost if either you close a socket while the
2144 * %G_IO_IN condition is set, or else if the remote connection tries to
2145 * send something to you after you close the socket but before it has
2146 * finished reading all of the data you sent. There is no easy generic
2147 * way to avoid this problem; the easiest fix is to design the network
2148 * protocol such that the client will never send data "out of turn".
2149 * Another solution is for the server to half-close the connection by
2150 * calling g_socket_shutdown() with only the @shutdown_write flag set,
2151 * and then wait for the client to notice this and close its side of the
2152 * connection, after which the server can safely call g_socket_close().
2153 * (This is what #GTcpConnection does if you call
2154 * g_tcp_connection_set_graceful_disconnect(). But of course, this
2155 * only works if the client will close its connection after the server
2158 * Returns: %TRUE on success, %FALSE on error
2163 g_socket_close (GSocket *socket,
2168 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2170 if (socket->priv->closed)
2171 return TRUE; /* Multiple close not an error */
2173 if (!check_socket (socket, NULL))
2179 res = closesocket (socket->priv->fd);
2181 res = close (socket->priv->fd);
2185 int errsv = get_socket_errno ();
2190 g_set_error (error, G_IO_ERROR,
2191 socket_io_error_from_errno (errsv),
2192 _("Error closing socket: %s"),
2193 socket_strerror (errsv));
2199 socket->priv->connected = FALSE;
2200 socket->priv->closed = TRUE;
2201 if (socket->priv->remote_address)
2203 g_object_unref (socket->priv->remote_address);
2204 socket->priv->remote_address = NULL;
2211 * g_socket_is_closed:
2212 * @socket: a #GSocket
2214 * Checks whether a socket is closed.
2216 * Returns: %TRUE if socket is closed, %FALSE otherwise
2221 g_socket_is_closed (GSocket *socket)
2223 return socket->priv->closed;
2227 /* Broken source, used on errors */
2229 broken_prepare (GSource *source,
2236 broken_check (GSource *source)
2242 broken_dispatch (GSource *source,
2243 GSourceFunc callback,
2249 static GSourceFuncs broken_funcs =
2258 network_events_for_condition (GIOCondition condition)
2262 if (condition & G_IO_IN)
2263 event_mask |= (FD_READ | FD_ACCEPT);
2264 if (condition & G_IO_OUT)
2265 event_mask |= (FD_WRITE | FD_CONNECT);
2266 event_mask |= FD_CLOSE;
2272 ensure_event (GSocket *socket)
2274 if (socket->priv->event == WSA_INVALID_EVENT)
2275 socket->priv->event = WSACreateEvent();
2279 update_select_events (GSocket *socket)
2286 ensure_event (socket);
2289 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
2292 event_mask |= network_events_for_condition (*ptr);
2295 if (event_mask != socket->priv->selected_events)
2297 /* If no events selected, disable event so we can unset
2300 if (event_mask == 0)
2303 event = socket->priv->event;
2305 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
2306 socket->priv->selected_events = event_mask;
2311 add_condition_watch (GSocket *socket,
2312 GIOCondition *condition)
2314 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
2316 socket->priv->requested_conditions =
2317 g_list_prepend (socket->priv->requested_conditions, condition);
2319 update_select_events (socket);
2323 remove_condition_watch (GSocket *socket,
2324 GIOCondition *condition)
2326 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
2328 socket->priv->requested_conditions =
2329 g_list_remove (socket->priv->requested_conditions, condition);
2331 update_select_events (socket);
2335 update_condition (GSocket *socket)
2337 WSANETWORKEVENTS events;
2338 GIOCondition condition;
2340 if (WSAEnumNetworkEvents (socket->priv->fd,
2341 socket->priv->event,
2344 socket->priv->current_events |= events.lNetworkEvents;
2345 if (events.lNetworkEvents & FD_WRITE &&
2346 events.iErrorCode[FD_WRITE_BIT] != 0)
2347 socket->priv->current_errors |= FD_WRITE;
2348 if (events.lNetworkEvents & FD_CONNECT &&
2349 events.iErrorCode[FD_CONNECT_BIT] != 0)
2350 socket->priv->current_errors |= FD_CONNECT;
2354 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
2355 condition |= G_IO_IN;
2357 if (socket->priv->current_events & FD_CLOSE ||
2358 socket->priv->closed)
2359 condition |= G_IO_HUP;
2361 /* Never report both G_IO_OUT and HUP, these are
2362 mutually exclusive (can't write to a closed socket) */
2363 if ((condition & G_IO_HUP) == 0 &&
2364 socket->priv->current_events & FD_WRITE)
2366 if (socket->priv->current_errors & FD_WRITE)
2367 condition |= G_IO_ERR;
2369 condition |= G_IO_OUT;
2373 if (socket->priv->current_events & FD_CONNECT)
2375 if (socket->priv->current_errors & FD_CONNECT)
2376 condition |= (G_IO_HUP | G_IO_ERR);
2378 condition |= G_IO_OUT;
2390 GIOCondition condition;
2391 GCancellable *cancellable;
2392 GPollFD cancel_pollfd;
2393 GTimeVal timeout_time;
2397 socket_source_prepare (GSource *source,
2400 GSocketSource *socket_source = (GSocketSource *)source;
2402 if (g_cancellable_is_cancelled (socket_source->cancellable))
2405 if (socket_source->timeout_time.tv_sec)
2409 g_source_get_current_time (source, &now);
2410 *timeout = ((socket_source->timeout_time.tv_sec - now.tv_sec) * 1000 +
2411 (socket_source->timeout_time.tv_usec - now.tv_usec) / 1000);
2414 socket_source->socket->priv->timed_out = TRUE;
2415 socket_source->pollfd.revents = socket_source->condition & (G_IO_IN | G_IO_OUT);
2423 socket_source->pollfd.revents = update_condition (socket_source->socket);
2426 if ((socket_source->condition & socket_source->pollfd.revents) != 0)
2433 socket_source_check (GSource *source)
2437 return socket_source_prepare (source, &timeout);
2441 socket_source_dispatch (GSource *source,
2442 GSourceFunc callback,
2445 GSocketSourceFunc func = (GSocketSourceFunc)callback;
2446 GSocketSource *socket_source = (GSocketSource *)source;
2448 return (*func) (socket_source->socket,
2449 socket_source->pollfd.revents & socket_source->condition,
2454 socket_source_finalize (GSource *source)
2456 GSocketSource *socket_source = (GSocketSource *)source;
2459 socket = socket_source->socket;
2462 remove_condition_watch (socket, &socket_source->condition);
2465 g_object_unref (socket);
2467 if (socket_source->cancellable)
2469 g_cancellable_release_fd (socket_source->cancellable);
2470 g_object_unref (socket_source->cancellable);
2474 static GSourceFuncs socket_source_funcs =
2476 socket_source_prepare,
2477 socket_source_check,
2478 socket_source_dispatch,
2479 socket_source_finalize
2483 socket_source_new (GSocket *socket,
2484 GIOCondition condition,
2485 GCancellable *cancellable)
2488 GSocketSource *socket_source;
2491 ensure_event (socket);
2493 if (socket->priv->event == WSA_INVALID_EVENT)
2495 g_warning ("Failed to create WSAEvent");
2496 return g_source_new (&broken_funcs, sizeof (GSource));
2500 condition |= G_IO_HUP | G_IO_ERR;
2502 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
2503 g_source_set_name (source, "GSocket");
2504 socket_source = (GSocketSource *)source;
2506 socket_source->socket = g_object_ref (socket);
2507 socket_source->condition = condition;
2509 if (g_cancellable_make_pollfd (cancellable,
2510 &socket_source->cancel_pollfd))
2512 socket_source->cancellable = g_object_ref (cancellable);
2513 g_source_add_poll (source, &socket_source->cancel_pollfd);
2517 add_condition_watch (socket, &socket_source->condition);
2518 socket_source->pollfd.fd = (gintptr) socket->priv->event;
2520 socket_source->pollfd.fd = socket->priv->fd;
2523 socket_source->pollfd.events = condition;
2524 socket_source->pollfd.revents = 0;
2525 g_source_add_poll (source, &socket_source->pollfd);
2527 if (socket->priv->timeout)
2529 g_get_current_time (&socket_source->timeout_time);
2530 socket_source->timeout_time.tv_sec += socket->priv->timeout;
2534 socket_source->timeout_time.tv_sec = 0;
2535 socket_source->timeout_time.tv_usec = 0;
2542 * g_socket_create_source:
2543 * @socket: a #GSocket
2544 * @condition: a #GIOCondition mask to monitor
2545 * @cancellable: a %GCancellable or %NULL
2547 * Creates a %GSource that can be attached to a %GMainContext to monitor
2548 * for the availibility of the specified @condition on the socket.
2550 * The callback on the source is of the #GSocketSourceFunc type.
2552 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
2553 * these conditions will always be reported output if they are true.
2555 * @cancellable if not %NULL can be used to cancel the source, which will
2556 * cause the source to trigger, reporting the current condition (which
2557 * is likely 0 unless cancellation happened at the same time as a
2558 * condition change). You can check for this in the callback using
2559 * g_cancellable_is_cancelled().
2561 * If @socket has a timeout set, and it is reached before @condition
2562 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
2563 * %G_IO_OUT depending on @condition. However, @socket will have been
2564 * marked as having had a timeout, and so the next #GSocket I/O method
2565 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
2567 * Returns: a newly allocated %GSource, free with g_source_unref().
2572 g_socket_create_source (GSocket *socket,
2573 GIOCondition condition,
2574 GCancellable *cancellable)
2576 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
2578 return socket_source_new (socket, condition, cancellable);
2582 * g_socket_condition_check:
2583 * @socket: a #GSocket
2584 * @condition: a #GIOCondition mask to check
2586 * Checks on the readiness of @socket to perform operations.
2587 * The operations specified in @condition are checked for and masked
2588 * against the currently-satisfied conditions on @socket. The result
2591 * Note that on Windows, it is possible for an operation to return
2592 * %G_IO_ERROR_WOULD_BLOCK even immediately after
2593 * g_socket_condition_check() has claimed that the socket is ready for
2594 * writing. Rather than calling g_socket_condition_check() and then
2595 * writing to the socket if it succeeds, it is generally better to
2596 * simply try writing to the socket right away, and try again later if
2597 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
2599 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2600 * these conditions will always be set in the output if they are true.
2602 * This call never blocks.
2604 * Returns: the @GIOCondition mask of the current state
2609 g_socket_condition_check (GSocket *socket,
2610 GIOCondition condition)
2612 if (!check_socket (socket, NULL))
2617 GIOCondition current_condition;
2619 condition |= G_IO_ERR | G_IO_HUP;
2621 add_condition_watch (socket, &condition);
2622 current_condition = update_condition (socket);
2623 remove_condition_watch (socket, &condition);
2624 return condition & current_condition;
2630 poll_fd.fd = socket->priv->fd;
2631 poll_fd.events = condition;
2634 result = g_poll (&poll_fd, 1, 0);
2635 while (result == -1 && get_socket_errno () == EINTR);
2637 return poll_fd.revents;
2643 * g_socket_condition_wait:
2644 * @socket: a #GSocket
2645 * @condition: a #GIOCondition mask to wait for
2646 * @cancellable: a #GCancellable, or %NULL
2647 * @error: a #GError pointer, or %NULL
2649 * Waits for @condition to become true on @socket. When the condition
2650 * is met, %TRUE is returned.
2652 * If @cancellable is cancelled before the condition is met, or if the
2653 * socket has a timeout set and it is reached before the condition is
2654 * met, then %FALSE is returned and @error, if non-%NULL, is set to
2655 * the appropriate value (%G_IO_ERROR_CANCELLED or
2656 * %G_IO_ERROR_TIMED_OUT).
2658 * Returns: %TRUE if the condition was met, %FALSE otherwise
2663 g_socket_condition_wait (GSocket *socket,
2664 GIOCondition condition,
2665 GCancellable *cancellable,
2668 if (!check_socket (socket, error))
2671 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2676 GIOCondition current_condition;
2682 /* Always check these */
2683 condition |= G_IO_ERR | G_IO_HUP;
2685 add_condition_watch (socket, &condition);
2688 events[num_events++] = socket->priv->event;
2690 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
2691 events[num_events++] = (WSAEVENT)cancel_fd.fd;
2693 if (socket->priv->timeout)
2694 timeout = socket->priv->timeout * 1000;
2696 timeout = WSA_INFINITE;
2698 current_condition = update_condition (socket);
2699 while ((condition & current_condition) == 0)
2701 res = WSAWaitForMultipleEvents(num_events, events,
2702 FALSE, timeout, FALSE);
2703 if (res == WSA_WAIT_FAILED)
2705 int errsv = get_socket_errno ();
2707 g_set_error (error, G_IO_ERROR,
2708 socket_io_error_from_errno (errsv),
2709 _("Waiting for socket condition: %s"),
2710 socket_strerror (errsv));
2713 else if (res == WSA_WAIT_TIMEOUT)
2715 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
2716 _("Socket I/O timed out"));
2720 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2723 current_condition = update_condition (socket);
2725 remove_condition_watch (socket, &condition);
2727 g_cancellable_release_fd (cancellable);
2729 return (condition & current_condition) != 0;
2738 poll_fd[0].fd = socket->priv->fd;
2739 poll_fd[0].events = condition;
2742 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
2745 if (socket->priv->timeout)
2746 timeout = socket->priv->timeout * 1000;
2751 result = g_poll (poll_fd, num, timeout);
2752 while (result == -1 && get_socket_errno () == EINTR);
2755 g_cancellable_release_fd (cancellable);
2759 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
2760 _("Socket I/O timed out"));
2764 return !g_cancellable_set_error_if_cancelled (cancellable, error);
2770 * g_socket_send_message:
2771 * @socket: a #GSocket
2772 * @address: a #GSocketAddress, or %NULL
2773 * @vectors: an array of #GOutputVector structs
2774 * @num_vectors: the number of elements in @vectors, or -1
2775 * @messages: a pointer to an array of #GSocketControlMessages, or
2777 * @num_messages: number of elements in @messages, or -1.
2778 * @flags: an int containing #GSocketMsgFlags flags
2779 * @cancellable: a %GCancellable or %NULL
2780 * @error: #GError for error reporting, or %NULL to ignore.
2782 * Send data to @address on @socket. This is the most complicated and
2783 * fully-featured version of this call. For easier use, see
2784 * g_socket_send() and g_socket_send_to().
2786 * If @address is %NULL then the message is sent to the default receiver
2787 * (set by g_socket_connect()).
2789 * @vectors must point to an array of #GOutputVector structs and
2790 * @num_vectors must be the length of this array. (If @num_vectors is -1,
2791 * then @vectors is assumed to be terminated by a #GOutputVector with a
2792 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
2793 * that the sent data will be gathered from. Using multiple
2794 * #GOutputVector<!-- -->s is more memory-efficient than manually copying
2795 * data from multiple sources into a single buffer, and more
2796 * network-efficient than making multiple calls to g_socket_send().
2798 * @messages, if non-%NULL, is taken to point to an array of @num_messages
2799 * #GSocketControlMessage instances. These correspond to the control
2800 * messages to be sent on the socket.
2801 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
2804 * @flags modify how the message is sent. The commonly available arguments
2805 * for this are available in the #GSocketMsgFlags enum, but the
2806 * values there are the same as the system values, and the flags
2807 * are passed in as-is, so you can pass in system-specific flags too.
2809 * If the socket is in blocking mode the call will block until there is
2810 * space for the data in the socket queue. If there is no space available
2811 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2812 * will be returned. To be notified when space is available, wait for the
2813 * %G_IO_OUT condition. Note though that you may still receive
2814 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2815 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2816 * very common due to the way the underlying APIs work.)
2818 * On error -1 is returned and @error is set accordingly.
2820 * Returns: Number of bytes written (which may be less than @size), or -1
2826 g_socket_send_message (GSocket *socket,
2827 GSocketAddress *address,
2828 GOutputVector *vectors,
2830 GSocketControlMessage **messages,
2833 GCancellable *cancellable,
2836 GOutputVector one_vector;
2839 if (!check_socket (socket, error))
2842 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2845 if (num_vectors == -1)
2847 for (num_vectors = 0;
2848 vectors[num_vectors].buffer != NULL;
2853 if (num_messages == -1)
2855 for (num_messages = 0;
2856 messages != NULL && messages[num_messages] != NULL;
2861 if (num_vectors == 0)
2865 one_vector.buffer = &zero;
2866 one_vector.size = 1;
2868 vectors = &one_vector;
2881 msg.msg_namelen = g_socket_address_get_native_size (address);
2882 msg.msg_name = g_alloca (msg.msg_namelen);
2883 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
2888 msg.msg_name = NULL;
2889 msg.msg_namelen = 0;
2894 /* this entire expression will be evaluated at compile time */
2895 if (sizeof *msg.msg_iov == sizeof *vectors &&
2896 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2897 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2898 G_STRUCT_OFFSET (GOutputVector, buffer) &&
2899 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2900 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2901 G_STRUCT_OFFSET (GOutputVector, size))
2902 /* ABI is compatible */
2904 msg.msg_iov = (struct iovec *) vectors;
2905 msg.msg_iovlen = num_vectors;
2908 /* ABI is incompatible */
2912 msg.msg_iov = g_newa (struct iovec, num_vectors);
2913 for (i = 0; i < num_vectors; i++)
2915 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
2916 msg.msg_iov[i].iov_len = vectors[i].size;
2918 msg.msg_iovlen = num_vectors;
2924 struct cmsghdr *cmsg;
2927 msg.msg_controllen = 0;
2928 for (i = 0; i < num_messages; i++)
2929 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
2931 if (msg.msg_controllen == 0)
2932 msg.msg_control = NULL;
2935 msg.msg_control = g_alloca (msg.msg_controllen);
2936 memset (msg.msg_control, '\0', msg.msg_controllen);
2939 cmsg = CMSG_FIRSTHDR (&msg);
2940 for (i = 0; i < num_messages; i++)
2942 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
2943 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
2944 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
2945 g_socket_control_message_serialize (messages[i],
2947 cmsg = CMSG_NXTHDR (&msg, cmsg);
2949 g_assert (cmsg == NULL);
2954 if (socket->priv->blocking &&
2955 !g_socket_condition_wait (socket,
2956 G_IO_OUT, cancellable, error))
2959 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
2962 int errsv = get_socket_errno ();
2967 if (socket->priv->blocking &&
2968 (errsv == EWOULDBLOCK ||
2972 g_set_error (error, G_IO_ERROR,
2973 socket_io_error_from_errno (errsv),
2974 _("Error sending message: %s"), socket_strerror (errsv));
2985 struct sockaddr_storage addr;
2992 /* Win32 doesn't support control messages.
2993 Actually this is possible for raw and datagram sockets
2994 via WSASendMessage on Vista or later, but that doesn't
2996 if (num_messages != 0)
2998 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2999 _("GSocketControlMessage not supported on windows"));
3004 bufs = g_newa (WSABUF, num_vectors);
3005 for (i = 0; i < num_vectors; i++)
3007 bufs[i].buf = (char *)vectors[i].buffer;
3008 bufs[i].len = (gulong)vectors[i].size;
3012 addrlen = 0; /* Avoid warning */
3015 addrlen = g_socket_address_get_native_size (address);
3016 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
3022 if (socket->priv->blocking &&
3023 !g_socket_condition_wait (socket,
3024 G_IO_OUT, cancellable, error))
3028 result = WSASendTo (socket->priv->fd,
3031 (const struct sockaddr *)&addr, addrlen,
3034 result = WSASend (socket->priv->fd,
3041 int errsv = get_socket_errno ();
3043 if (errsv == WSAEINTR)
3046 if (errsv == WSAEWOULDBLOCK)
3047 win32_unset_event_mask (socket, FD_WRITE);
3049 if (socket->priv->blocking &&
3050 errsv == WSAEWOULDBLOCK)
3053 g_set_error (error, G_IO_ERROR,
3054 socket_io_error_from_errno (errsv),
3055 _("Error sending message: %s"), socket_strerror (errsv));
3068 * g_socket_receive_message:
3069 * @socket: a #GSocket
3070 * @address: a pointer to a #GSocketAddress pointer, or %NULL
3071 * @vectors: an array of #GInputVector structs
3072 * @num_vectors: the number of elements in @vectors, or -1
3073 * @messages: a pointer which may be filled with an array of
3074 * #GSocketControlMessages, or %NULL
3075 * @num_messages: a pointer which will be filled with the number of
3076 * elements in @messages, or %NULL
3077 * @flags: a pointer to an int containing #GSocketMsgFlags flags
3078 * @cancellable: a %GCancellable or %NULL
3079 * @error: a #GError pointer, or %NULL
3081 * Receive data from a socket. This is the most complicated and
3082 * fully-featured version of this call. For easier use, see
3083 * g_socket_receive() and g_socket_receive_from().
3085 * If @address is non-%NULL then @address will be set equal to the
3086 * source address of the received packet.
3087 * @address is owned by the caller.
3089 * @vector must point to an array of #GInputVector structs and
3090 * @num_vectors must be the length of this array. These structs
3091 * describe the buffers that received data will be scattered into.
3092 * If @num_vectors is -1, then @vectors is assumed to be terminated
3093 * by a #GInputVector with a %NULL buffer pointer.
3095 * As a special case, if @num_vectors is 0 (in which case, @vectors
3096 * may of course be %NULL), then a single byte is received and
3097 * discarded. This is to facilitate the common practice of sending a
3098 * single '\0' byte for the purposes of transferring ancillary data.
3100 * @messages, if non-%NULL, will be set to point to a newly-allocated
3101 * array of #GSocketControlMessage instances or %NULL if no such
3102 * messages was received. These correspond to the control messages
3103 * received from the kernel, one #GSocketControlMessage per message
3104 * from the kernel. This array is %NULL-terminated and must be freed
3105 * by the caller using g_free() after calling g_object_unref() on each
3106 * element. If @messages is %NULL, any control messages received will
3109 * @num_messages, if non-%NULL, will be set to the number of control
3110 * messages received.
3112 * If both @messages and @num_messages are non-%NULL, then
3113 * @num_messages gives the number of #GSocketControlMessage instances
3114 * in @messages (ie: not including the %NULL terminator).
3116 * @flags is an in/out parameter. The commonly available arguments
3117 * for this are available in the #GSocketMsgFlags enum, but the
3118 * values there are the same as the system values, and the flags
3119 * are passed in as-is, so you can pass in system-specific flags too
3120 * (and g_socket_receive_message() may pass system-specific flags out).
3122 * As with g_socket_receive(), data may be discarded if @socket is
3123 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
3124 * provide enough buffer space to read a complete message. You can pass
3125 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
3126 * removing it from the receive queue, but there is no portable way to find
3127 * out the length of the message other than by reading it into a
3128 * sufficiently-large buffer.
3130 * If the socket is in blocking mode the call will block until there
3131 * is some data to receive or there is an error. If there is no data
3132 * available and the socket is in non-blocking mode, a
3133 * %G_IO_ERROR_WOULD_BLOCK error will be returned. To be notified when
3134 * data is available, wait for the %G_IO_IN condition.
3136 * On error -1 is returned and @error is set accordingly.
3138 * Returns: Number of bytes read, or -1 on error
3143 g_socket_receive_message (GSocket *socket,
3144 GSocketAddress **address,
3145 GInputVector *vectors,
3147 GSocketControlMessage ***messages,
3150 GCancellable *cancellable,
3153 GInputVector one_vector;
3156 if (!check_socket (socket, error))
3159 if (g_cancellable_set_error_if_cancelled (cancellable, error))
3162 if (num_vectors == -1)
3164 for (num_vectors = 0;
3165 vectors[num_vectors].buffer != NULL;
3170 if (num_vectors == 0)
3172 one_vector.buffer = &one_byte;
3173 one_vector.size = 1;
3175 vectors = &one_vector;
3182 struct sockaddr_storage one_sockaddr;
3187 msg.msg_name = &one_sockaddr;
3188 msg.msg_namelen = sizeof (struct sockaddr_storage);
3192 msg.msg_name = NULL;
3193 msg.msg_namelen = 0;
3197 /* this entire expression will be evaluated at compile time */
3198 if (sizeof *msg.msg_iov == sizeof *vectors &&
3199 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3200 G_STRUCT_OFFSET (struct iovec, iov_base) ==
3201 G_STRUCT_OFFSET (GInputVector, buffer) &&
3202 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3203 G_STRUCT_OFFSET (struct iovec, iov_len) ==
3204 G_STRUCT_OFFSET (GInputVector, size))
3205 /* ABI is compatible */
3207 msg.msg_iov = (struct iovec *) vectors;
3208 msg.msg_iovlen = num_vectors;
3211 /* ABI is incompatible */
3215 msg.msg_iov = g_newa (struct iovec, num_vectors);
3216 for (i = 0; i < num_vectors; i++)
3218 msg.msg_iov[i].iov_base = vectors[i].buffer;
3219 msg.msg_iov[i].iov_len = vectors[i].size;
3221 msg.msg_iovlen = num_vectors;
3225 msg.msg_control = g_alloca (2048);
3226 msg.msg_controllen = 2048;
3230 msg.msg_flags = *flags;
3237 if (socket->priv->blocking &&
3238 !g_socket_condition_wait (socket,
3239 G_IO_IN, cancellable, error))
3242 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
3246 int errsv = get_socket_errno ();
3251 if (socket->priv->blocking &&
3252 (errsv == EWOULDBLOCK ||
3256 g_set_error (error, G_IO_ERROR,
3257 socket_io_error_from_errno (errsv),
3258 _("Error receiving message: %s"), socket_strerror (errsv));
3265 /* decode address */
3266 if (address != NULL)
3268 if (msg.msg_namelen > 0)
3269 *address = g_socket_address_new_from_native (msg.msg_name,
3275 /* decode control messages */
3277 GPtrArray *my_messages = NULL;
3278 const gchar *scm_pointer;
3279 struct cmsghdr *cmsg;
3282 scm_pointer = (const gchar *) msg.msg_control;
3283 scm_size = msg.msg_controllen;
3285 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
3287 GSocketControlMessage *message;
3289 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
3291 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
3293 if (message == NULL)
3294 /* We've already spewed about the problem in the
3295 deserialization code, so just continue */
3298 if (messages == NULL)
3300 /* we have to do it this way if the user ignores the
3301 * messages so that we will close any received fds.
3303 g_object_unref (message);
3307 if (my_messages == NULL)
3308 my_messages = g_ptr_array_new ();
3309 g_ptr_array_add (my_messages, message);
3314 *num_messages = my_messages != NULL ? my_messages->len : 0;
3318 if (my_messages == NULL)
3324 g_ptr_array_add (my_messages, NULL);
3325 *messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
3330 g_assert (my_messages == NULL);
3334 /* capture the flags */
3336 *flags = msg.msg_flags;
3342 struct sockaddr_storage addr;
3344 DWORD bytes_received;
3351 bufs = g_newa (WSABUF, num_vectors);
3352 for (i = 0; i < num_vectors; i++)
3354 bufs[i].buf = (char *)vectors[i].buffer;
3355 bufs[i].len = (gulong)vectors[i].size;
3367 if (socket->priv->blocking &&
3368 !g_socket_condition_wait (socket,
3369 G_IO_IN, cancellable, error))
3372 addrlen = sizeof addr;
3374 result = WSARecvFrom (socket->priv->fd,
3376 &bytes_received, &win_flags,
3377 (struct sockaddr *)&addr, &addrlen,
3380 result = WSARecv (socket->priv->fd,
3382 &bytes_received, &win_flags,
3386 int errsv = get_socket_errno ();
3388 if (errsv == WSAEINTR)
3391 win32_unset_event_mask (socket, FD_READ);
3393 if (socket->priv->blocking &&
3394 errsv == WSAEWOULDBLOCK)
3397 g_set_error (error, G_IO_ERROR,
3398 socket_io_error_from_errno (errsv),
3399 _("Error receiving message: %s"), socket_strerror (errsv));
3403 win32_unset_event_mask (socket, FD_READ);
3407 /* decode address */
3408 if (address != NULL)
3411 *address = g_socket_address_new_from_native (&addr, addrlen);
3416 /* capture the flags */
3420 if (messages != NULL)
3422 if (num_messages != NULL)
3425 return bytes_received;
3431 * g_socket_get_credentials:
3432 * @socket: a #GSocket.
3433 * @error: #GError for error reporting, or %NULL to ignore.
3435 * Returns the credentials of the foreign process connected to this
3436 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
3439 * If this operation isn't supported on the OS, the method fails with
3440 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
3441 * by reading the %SO_PEERCRED option on the underlying socket.
3443 * Other ways to obtain credentials from a foreign peer includes the
3444 * #GUnixCredentialsMessage type and
3445 * g_unix_connection_send_credentials() /
3446 * g_unix_connection_receive_credentials() functions.
3448 * Returns: %NULL if @error is set, otherwise a #GCredentials object
3449 * that must be freed with g_object_unref().
3454 g_socket_get_credentials (GSocket *socket,
3459 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
3460 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3466 struct ucred native_creds;
3468 optlen = sizeof (struct ucred);
3469 if (getsockopt (socket->priv->fd,
3472 (void *)&native_creds,
3475 int errsv = get_socket_errno ();
3478 socket_io_error_from_errno (errsv),
3479 _("Unable to get pending error: %s"),
3480 socket_strerror (errsv));
3484 ret = g_credentials_new ();
3485 g_credentials_set_native (ret,
3486 G_CREDENTIALS_TYPE_LINUX_UCRED,
3491 g_set_error_literal (error,
3493 G_IO_ERROR_NOT_SUPPORTED,
3494 _("g_socket_get_credentials not implemented for this OS"));