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 "ginitable.h"
49 #include "gasynchelper.h"
53 #include "gnetworkingprivate.h"
60 * @short_description: Low-level socket object
62 * @see_also: #GInitable
64 * A #GSocket is a low-level networking primitive. It is a more or less
65 * direct mapping of the BSD socket API in a portable GObject based API.
66 * It supports both the UNIX socket implementations and winsock2 on Windows.
68 * #GSocket is the platform independent base upon which the higher level
69 * network primitives are based. Applications are not typically meant to
70 * use it directly, but rather through classes like #GSocketClient,
71 * #GSocketService and #GSocketConnection. However there may be cases where
72 * direct use of #GSocket is useful.
74 * #GSocket implements the #GInitable interface, so if it is manually constructed
75 * by e.g. g_object_new() you must call g_initable_init() and check the
76 * results before using the object. This is done automatically in
77 * g_socket_new() and g_socket_new_from_fd(), so these functions can return
80 * Sockets operate in two general modes, blocking or non-blocking. When
81 * in blocking mode all operations block until the requested operation
82 * is finished or there is an error. In non-blocking mode all calls that
83 * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
84 * To know when a call would successfully run you can call g_socket_condition_check(),
85 * or g_socket_condition_wait(). You can also use g_socket_create_source() and
86 * attach it to a #GMainContext to get callbacks when I/O is possible.
87 * Note that all sockets are always set to non blocking mode in the system, and
88 * blocking mode is emulated in GSocket.
90 * When working in non-blocking mode applications should always be able to
91 * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
92 * function said that I/O was possible. This can easily happen in case
93 * of a race condition in the application, but it can also happen for other
94 * reasons. For instance, on Windows a socket is always seen as writable
95 * until a write returns %G_IO_ERROR_WOULD_BLOCK.
97 * #GSocket<!-- -->s can be either connection oriented or datagram based.
98 * For connection oriented types you must first establish a connection by
99 * either connecting to an address or accepting a connection from another
100 * address. For connectionless socket types the target/source address is
101 * specified or received in each I/O operation.
103 * All socket file descriptors are set to be close-on-exec.
105 * Note that creating a #GSocket causes the signal %SIGPIPE to be
106 * ignored for the remainder of the program. If you are writing a
107 * command-line utility that uses #GSocket, you may need to take into
108 * account the fact that your program will not automatically be killed
109 * if it tries to write to %stdout after it has been closed.
114 static void g_socket_initable_iface_init (GInitableIface *iface);
115 static gboolean g_socket_initable_init (GInitable *initable,
116 GCancellable *cancellable,
119 G_DEFINE_TYPE_WITH_CODE (GSocket, g_socket, G_TYPE_OBJECT,
120 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
121 g_socket_initable_iface_init));
137 struct _GSocketPrivate
139 GSocketFamily family;
141 GSocketProtocol protocol;
144 GError *construct_error;
156 GList *requested_conditions; /* list of requested GIOCondition * */
161 get_socket_errno (void)
166 return WSAGetLastError ();
171 socket_io_error_from_errno (int err)
174 return g_io_error_from_errno (err);
179 return G_IO_ERROR_ADDRESS_IN_USE;
181 return G_IO_ERROR_WOULD_BLOCK;
183 return G_IO_ERROR_PERMISSION_DENIED;
184 case WSA_INVALID_HANDLE:
185 case WSA_INVALID_PARAMETER:
188 return G_IO_ERROR_INVALID_ARGUMENT;
189 case WSAEPROTONOSUPPORT:
190 return G_IO_ERROR_NOT_SUPPORTED;
192 return G_IO_ERROR_CANCELLED;
193 case WSAESOCKTNOSUPPORT:
195 case WSAEPFNOSUPPORT:
196 case WSAEAFNOSUPPORT:
197 return G_IO_ERROR_NOT_SUPPORTED;
199 return G_IO_ERROR_FAILED;
205 socket_strerror (int err)
208 return g_strerror (err);
210 static GStaticPrivate msg_private = G_STATIC_PRIVATE_INIT;
213 buf = g_static_private_get (&msg_private);
216 buf = g_new (gchar, 128);
217 g_static_private_set (&msg_private, buf, g_free);
220 msg = g_win32_error_message (err);
221 strncpy (buf, msg, 128);
228 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
230 _win32_unset_event_mask (GSocket *socket, int mask)
232 socket->priv->current_events &= ~mask;
233 socket->priv->current_errors &= ~mask;
236 #define win32_unset_event_mask(_socket, _mask)
240 set_fd_nonblocking (int fd)
249 if ((arg = fcntl (fd, F_GETFL, NULL)) < 0)
251 g_warning ("Error getting socket status flags: %s", socket_strerror (errno));
255 arg = arg | O_NONBLOCK;
257 if (fcntl (fd, F_SETFL, arg) < 0)
258 g_warning ("Error setting socket status flags: %s", socket_strerror (errno));
262 if (ioctlsocket (fd, FIONBIO, &arg) == SOCKET_ERROR)
264 int errsv = get_socket_errno ();
265 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
271 check_socket (GSocket *socket,
274 if (!socket->priv->inited)
276 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
277 _("Invalid socket, not initialized"));
281 if (socket->priv->construct_error)
283 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
284 _("Invalid socket, initialization failed due to: %s"),
285 socket->priv->construct_error->message);
289 if (socket->priv->closed)
291 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
292 _("Socket is already closed"));
299 g_socket_details_from_fd (GSocket *socket)
301 struct sockaddr_storage address;
308 /* See bug #611756 */
309 BOOL bool_val = FALSE;
314 fd = socket->priv->fd;
315 optlen = sizeof value;
316 if (getsockopt (fd, SOL_SOCKET, SO_TYPE, (void *)&value, &optlen) != 0)
318 errsv = get_socket_errno ();
329 /* programmer error */
330 g_error ("creating GSocket from fd %d: %s\n",
331 fd, socket_strerror (errsv));
339 g_assert (optlen == sizeof value);
343 socket->priv->type = G_SOCKET_TYPE_STREAM;
347 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
351 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
355 socket->priv->type = G_SOCKET_TYPE_INVALID;
359 addrlen = sizeof address;
360 if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
362 errsv = get_socket_errno ();
366 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
367 sizeof address.ss_family <= addrlen);
368 switch (address.ss_family)
370 case G_SOCKET_FAMILY_IPV4:
371 case G_SOCKET_FAMILY_IPV6:
372 case G_SOCKET_FAMILY_UNIX:
373 socket->priv->family = address.ss_family;
377 socket->priv->family = G_SOCKET_FAMILY_INVALID;
381 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
383 addrlen = sizeof address;
384 if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
385 socket->priv->connected = TRUE;
388 optlen = sizeof bool_val;
389 if (getsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
390 (void *)&bool_val, &optlen) == 0)
393 /* Experimentation indicates that the SO_KEEPALIVE value is
394 * actually a char on Windows, even if documentation claims it
395 * to be a BOOL which is a typedef for int. So this g_assert()
396 * fails. See bug #611756.
398 g_assert (optlen == sizeof bool_val);
400 socket->priv->keepalive = !!bool_val;
404 /* Can't read, maybe not supported, assume FALSE */
405 socket->priv->keepalive = FALSE;
411 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
412 socket_io_error_from_errno (errsv),
413 _("creating GSocket from fd: %s"),
414 socket_strerror (errsv));
418 g_socket_create_socket (GSocketFamily family,
428 case G_SOCKET_TYPE_STREAM:
429 native_type = SOCK_STREAM;
432 case G_SOCKET_TYPE_DATAGRAM:
433 native_type = SOCK_DGRAM;
436 case G_SOCKET_TYPE_SEQPACKET:
437 native_type = SOCK_SEQPACKET;
441 g_assert_not_reached ();
446 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
447 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
452 native_type |= SOCK_CLOEXEC;
454 fd = socket (family, native_type, protocol);
458 int errsv = get_socket_errno ();
460 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
461 _("Unable to create socket: %s"), socket_strerror (errsv));
468 /* We always want to set close-on-exec to protect users. If you
469 need to so some weird inheritance to exec you can re-enable this
470 using lower level hacks with g_socket_get_fd(). */
471 flags = fcntl (fd, F_GETFD, 0);
473 (flags & FD_CLOEXEC) == 0)
476 fcntl (fd, F_SETFD, flags);
485 g_socket_constructed (GObject *object)
487 GSocket *socket = G_SOCKET (object);
489 if (socket->priv->fd >= 0)
490 /* create socket->priv info from the fd */
491 g_socket_details_from_fd (socket);
494 /* create the fd from socket->priv info */
495 socket->priv->fd = g_socket_create_socket (socket->priv->family,
497 socket->priv->protocol,
498 &socket->priv->construct_error);
500 /* Always use native nonblocking sockets, as
501 windows sets sockets to nonblocking automatically
502 in certain operations. This way we make things work
503 the same on all platforms */
504 if (socket->priv->fd != -1)
505 set_fd_nonblocking (socket->priv->fd);
509 g_socket_get_property (GObject *object,
514 GSocket *socket = G_SOCKET (object);
515 GSocketAddress *address;
520 g_value_set_enum (value, socket->priv->family);
524 g_value_set_enum (value, socket->priv->type);
528 g_value_set_enum (value, socket->priv->protocol);
532 g_value_set_int (value, socket->priv->fd);
536 g_value_set_boolean (value, socket->priv->blocking);
539 case PROP_LISTEN_BACKLOG:
540 g_value_set_int (value, socket->priv->listen_backlog);
544 g_value_set_boolean (value, socket->priv->keepalive);
547 case PROP_LOCAL_ADDRESS:
548 address = g_socket_get_local_address (socket, NULL);
549 g_value_take_object (value, address);
552 case PROP_REMOTE_ADDRESS:
553 address = g_socket_get_remote_address (socket, NULL);
554 g_value_take_object (value, address);
558 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
563 g_socket_set_property (GObject *object,
568 GSocket *socket = G_SOCKET (object);
573 socket->priv->family = g_value_get_enum (value);
577 socket->priv->type = g_value_get_enum (value);
581 socket->priv->protocol = g_value_get_enum (value);
585 socket->priv->fd = g_value_get_int (value);
589 g_socket_set_blocking (socket, g_value_get_boolean (value));
592 case PROP_LISTEN_BACKLOG:
593 g_socket_set_listen_backlog (socket, g_value_get_int (value));
597 g_socket_set_keepalive (socket, g_value_get_boolean (value));
601 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
606 g_socket_finalize (GObject *object)
608 GSocket *socket = G_SOCKET (object);
610 g_clear_error (&socket->priv->construct_error);
612 if (socket->priv->fd != -1 &&
613 !socket->priv->closed)
614 g_socket_close (socket, NULL);
617 if (socket->priv->event != WSA_INVALID_EVENT)
619 WSACloseEvent (socket->priv->event);
620 socket->priv->event = WSA_INVALID_EVENT;
623 g_assert (socket->priv->requested_conditions == NULL);
626 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
627 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
631 g_socket_class_init (GSocketClass *klass)
633 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
636 /* Make sure winsock has been initialized */
637 type = g_inet_address_get_type ();
640 /* There is no portable, thread-safe way to avoid having the process
641 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
642 * forced to simply ignore the signal process-wide.
644 signal (SIGPIPE, SIG_IGN);
647 g_type_class_add_private (klass, sizeof (GSocketPrivate));
649 gobject_class->finalize = g_socket_finalize;
650 gobject_class->constructed = g_socket_constructed;
651 gobject_class->set_property = g_socket_set_property;
652 gobject_class->get_property = g_socket_get_property;
654 g_object_class_install_property (gobject_class, PROP_FAMILY,
655 g_param_spec_enum ("family",
657 P_("The sockets address family"),
658 G_TYPE_SOCKET_FAMILY,
659 G_SOCKET_FAMILY_INVALID,
660 G_PARAM_CONSTRUCT_ONLY |
662 G_PARAM_STATIC_STRINGS));
664 g_object_class_install_property (gobject_class, PROP_TYPE,
665 g_param_spec_enum ("type",
667 P_("The sockets type"),
669 G_SOCKET_TYPE_STREAM,
670 G_PARAM_CONSTRUCT_ONLY |
672 G_PARAM_STATIC_STRINGS));
674 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
675 g_param_spec_enum ("protocol",
676 P_("Socket protocol"),
677 P_("The id of the protocol to use, or -1 for unknown"),
678 G_TYPE_SOCKET_PROTOCOL,
679 G_SOCKET_PROTOCOL_UNKNOWN,
680 G_PARAM_CONSTRUCT_ONLY |
682 G_PARAM_STATIC_STRINGS));
684 g_object_class_install_property (gobject_class, PROP_FD,
685 g_param_spec_int ("fd",
686 P_("File descriptor"),
687 P_("The sockets file descriptor"),
691 G_PARAM_CONSTRUCT_ONLY |
693 G_PARAM_STATIC_STRINGS));
695 g_object_class_install_property (gobject_class, PROP_BLOCKING,
696 g_param_spec_boolean ("blocking",
698 P_("Whether or not I/O on this socket is blocking"),
701 G_PARAM_STATIC_STRINGS));
703 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
704 g_param_spec_int ("listen-backlog",
705 P_("Listen backlog"),
706 P_("Outstanding connections in the listen queue"),
711 G_PARAM_STATIC_STRINGS));
713 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
714 g_param_spec_boolean ("keepalive",
715 P_("Keep connection alive"),
716 P_("Keep connection alive by sending periodic pings"),
719 G_PARAM_STATIC_STRINGS));
721 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
722 g_param_spec_object ("local-address",
724 P_("The local address the socket is bound to"),
725 G_TYPE_SOCKET_ADDRESS,
727 G_PARAM_STATIC_STRINGS));
729 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
730 g_param_spec_object ("remote-address",
731 P_("Remote address"),
732 P_("The remote address the socket is connected to"),
733 G_TYPE_SOCKET_ADDRESS,
735 G_PARAM_STATIC_STRINGS));
739 g_socket_initable_iface_init (GInitableIface *iface)
741 iface->init = g_socket_initable_init;
745 g_socket_init (GSocket *socket)
747 socket->priv = G_TYPE_INSTANCE_GET_PRIVATE (socket, G_TYPE_SOCKET, GSocketPrivate);
749 socket->priv->fd = -1;
750 socket->priv->blocking = TRUE;
751 socket->priv->listen_backlog = 10;
752 socket->priv->construct_error = NULL;
754 socket->priv->event = WSA_INVALID_EVENT;
759 g_socket_initable_init (GInitable *initable,
760 GCancellable *cancellable,
765 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
767 socket = G_SOCKET (initable);
769 if (cancellable != NULL)
771 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
772 _("Cancellable initialization not supported"));
776 socket->priv->inited = TRUE;
778 if (socket->priv->construct_error)
781 *error = g_error_copy (socket->priv->construct_error);
791 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
792 * @type: the socket type to use.
793 * @protocol: the id of the protocol to use, or 0 for default.
794 * @error: #GError for error reporting, or %NULL to ignore.
796 * Creates a new #GSocket with the defined family, type and protocol.
797 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
798 * for the family and type is used.
800 * The @protocol is a family and type specific int that specifies what
801 * kind of protocol to use. #GSocketProtocol lists several common ones.
802 * Many families only support one protocol, and use 0 for this, others
803 * support several and using 0 means to use the default protocol for
804 * the family and type.
806 * The protocol id is passed directly to the operating
807 * system, so you can use protocols not listed in #GSocketProtocol if you
808 * know the protocol number used for it.
810 * Returns: a #GSocket or %NULL on error.
811 * Free the returned object with g_object_unref().
816 g_socket_new (GSocketFamily family,
818 GSocketProtocol protocol,
821 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
825 "protocol", protocol,
830 * g_socket_new_from_fd:
831 * @fd: a native socket file descriptor.
832 * @error: #GError for error reporting, or %NULL to ignore.
834 * Creates a new #GSocket from a native file descriptor
835 * or winsock SOCKET handle.
837 * This reads all the settings from the file descriptor so that
838 * all properties should work. Note that the file descriptor
839 * will be set to non-blocking mode, independent on the blocking
840 * mode of the #GSocket.
842 * Returns: a #GSocket or %NULL on error.
843 * Free the returned object with g_object_unref().
848 g_socket_new_from_fd (gint fd,
851 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
858 * g_socket_set_blocking:
859 * @socket: a #GSocket.
860 * @blocking: Whether to use blocking I/O or not.
862 * Sets the blocking mode of the socket. In blocking mode
863 * all operations block until they succeed or there is an error. In
864 * non-blocking mode all functions return results immediately or
865 * with a %G_IO_ERROR_WOULD_BLOCK error.
867 * All sockets are created in blocking mode. However, note that the
868 * platform level socket is always non-blocking, and blocking mode
869 * is a GSocket level feature.
874 g_socket_set_blocking (GSocket *socket,
877 g_return_if_fail (G_IS_SOCKET (socket));
879 blocking = !!blocking;
881 if (socket->priv->blocking == blocking)
884 socket->priv->blocking = blocking;
885 g_object_notify (G_OBJECT (socket), "blocking");
889 * g_socket_get_blocking:
890 * @socket: a #GSocket.
892 * Gets the blocking mode of the socket. For details on blocking I/O,
893 * see g_socket_set_blocking().
895 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
900 g_socket_get_blocking (GSocket *socket)
902 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
904 return socket->priv->blocking;
908 * g_socket_set_keepalive:
909 * @socket: a #GSocket.
910 * @keepalive: Value for the keepalive flag
912 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
913 * this flag is set on a socket, the system will attempt to verify that the
914 * remote socket endpoint is still present if a sufficiently long period of
915 * time passes with no data being exchanged. If the system is unable to
916 * verify the presence of the remote endpoint, it will automatically close
919 * This option is only functional on certain kinds of sockets. (Notably,
920 * %G_SOCKET_PROTOCOL_TCP sockets.)
922 * The exact time between pings is system- and protocol-dependent, but will
923 * normally be at least two hours. Most commonly, you would set this flag
924 * on a server socket if you want to allow clients to remain idle for long
925 * periods of time, but also want to ensure that connections are eventually
926 * garbage-collected if clients crash or become unreachable.
931 g_socket_set_keepalive (GSocket *socket,
936 g_return_if_fail (G_IS_SOCKET (socket));
938 keepalive = !!keepalive;
939 if (socket->priv->keepalive == keepalive)
942 value = (gint) keepalive;
943 if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_KEEPALIVE,
944 (gpointer) &value, sizeof (value)) < 0)
946 int errsv = get_socket_errno ();
947 g_warning ("error setting keepalive: %s", socket_strerror (errsv));
951 socket->priv->keepalive = keepalive;
952 g_object_notify (G_OBJECT (socket), "keepalive");
956 * g_socket_get_keepalive:
957 * @socket: a #GSocket.
959 * Gets the keepalive mode of the socket. For details on this,
960 * see g_socket_set_keepalive().
962 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
967 g_socket_get_keepalive (GSocket *socket)
969 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
971 return socket->priv->keepalive;
975 * g_socket_get_listen_backlog:
976 * @socket: a #GSocket.
978 * Gets the listen backlog setting of the socket. For details on this,
979 * see g_socket_set_listen_backlog().
981 * Returns: the maximum number of pending connections.
986 g_socket_get_listen_backlog (GSocket *socket)
988 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
990 return socket->priv->listen_backlog;
994 * g_socket_set_listen_backlog:
995 * @socket: a #GSocket.
996 * @backlog: the maximum number of pending connections.
998 * Sets the maximum number of outstanding connections allowed
999 * when listening on this socket. If more clients than this are
1000 * connecting to the socket and the application is not handling them
1001 * on time then the new connections will be refused.
1003 * Note that this must be called before g_socket_listen() and has no
1004 * effect if called after that.
1009 g_socket_set_listen_backlog (GSocket *socket,
1012 g_return_if_fail (G_IS_SOCKET (socket));
1013 g_return_if_fail (!socket->priv->listening);
1015 if (backlog != socket->priv->listen_backlog)
1017 socket->priv->listen_backlog = backlog;
1018 g_object_notify (G_OBJECT (socket), "listen-backlog");
1023 * g_socket_get_family:
1024 * @socket: a #GSocket.
1026 * Gets the socket family of the socket.
1028 * Returns: a #GSocketFamily
1033 g_socket_get_family (GSocket *socket)
1035 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1037 return socket->priv->family;
1041 * g_socket_get_socket_type:
1042 * @socket: a #GSocket.
1044 * Gets the socket type of the socket.
1046 * Returns: a #GSocketType
1051 g_socket_get_socket_type (GSocket *socket)
1053 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1055 return socket->priv->type;
1059 * g_socket_get_protocol:
1060 * @socket: a #GSocket.
1062 * Gets the socket protocol id the socket was created with.
1063 * In case the protocol is unknown, -1 is returned.
1065 * Returns: a protocol id, or -1 if unknown
1070 g_socket_get_protocol (GSocket *socket)
1072 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1074 return socket->priv->protocol;
1079 * @socket: a #GSocket.
1081 * Returns the underlying OS socket object. On unix this
1082 * is a socket file descriptor, and on windows this is
1083 * a Winsock2 SOCKET handle. This may be useful for
1084 * doing platform specific or otherwise unusual operations
1087 * Returns: the file descriptor of the socket.
1092 g_socket_get_fd (GSocket *socket)
1094 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1096 return socket->priv->fd;
1100 * g_socket_get_local_address:
1101 * @socket: a #GSocket.
1102 * @error: #GError for error reporting, or %NULL to ignore.
1104 * Try to get the local address of a bound socket. This is only
1105 * useful if the socket has been bound to a local address,
1106 * either explicitly or implicitly when connecting.
1108 * Returns: a #GSocketAddress or %NULL on error.
1109 * Free the returned object with g_object_unref().
1114 g_socket_get_local_address (GSocket *socket,
1117 struct sockaddr_storage buffer;
1118 guint32 len = sizeof (buffer);
1120 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1122 if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1124 int errsv = get_socket_errno ();
1125 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1126 _("could not get local address: %s"), socket_strerror (errsv));
1130 return g_socket_address_new_from_native (&buffer, len);
1134 * g_socket_get_remote_address:
1135 * @socket: a #GSocket.
1136 * @error: #GError for error reporting, or %NULL to ignore.
1138 * Try to get the remove address of a connected socket. This is only
1139 * useful for connection oriented sockets that have been connected.
1141 * Returns: a #GSocketAddress or %NULL on error.
1142 * Free the returned object with g_object_unref().
1147 g_socket_get_remote_address (GSocket *socket,
1150 struct sockaddr_storage buffer;
1151 guint32 len = sizeof (buffer);
1153 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1155 if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1157 int errsv = get_socket_errno ();
1158 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1159 _("could not get remote address: %s"), socket_strerror (errsv));
1163 return g_socket_address_new_from_native (&buffer, len);
1167 * g_socket_is_connected:
1168 * @socket: a #GSocket.
1170 * Check whether the socket is connected. This is only useful for
1171 * connection-oriented sockets.
1173 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1178 g_socket_is_connected (GSocket *socket)
1180 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1182 return socket->priv->connected;
1187 * @socket: a #GSocket.
1188 * @error: #GError for error reporting, or %NULL to ignore.
1190 * Marks the socket as a server socket, i.e. a socket that is used
1191 * to accept incoming requests using g_socket_accept().
1193 * Before calling this the socket must be bound to a local address using
1196 * To set the maximum amount of outstanding clients, use
1197 * g_socket_set_listen_backlog().
1199 * Returns: %TRUE on success, %FALSE on error.
1204 g_socket_listen (GSocket *socket,
1207 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1209 if (!check_socket (socket, error))
1212 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1214 int errsv = get_socket_errno ();
1216 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1217 _("could not listen: %s"), socket_strerror (errsv));
1221 socket->priv->listening = TRUE;
1228 * @socket: a #GSocket.
1229 * @address: a #GSocketAddress specifying the local address.
1230 * @allow_reuse: whether to allow reusing this address
1231 * @error: #GError for error reporting, or %NULL to ignore.
1233 * When a socket is created it is attached to an address family, but it
1234 * doesn't have an address in this family. g_socket_bind() assigns the
1235 * address (sometimes called name) of the socket.
1237 * It is generally required to bind to a local address before you can
1238 * receive connections. (See g_socket_listen() and g_socket_accept() ).
1239 * In certain situations, you may also want to bind a socket that will be
1240 * used to initiate connections, though this is not normally required.
1242 * @allow_reuse should be %TRUE for server sockets (sockets that you will
1243 * eventually call g_socket_accept() on), and %FALSE for client sockets.
1244 * (Specifically, if it is %TRUE, then g_socket_bind() will set the
1245 * %SO_REUSEADDR flag on the socket, allowing it to bind @address even if
1246 * that address was previously used by another socket that has not yet been
1247 * fully cleaned-up by the kernel. Failing to set this flag on a server
1248 * socket may cause the bind call to return %G_IO_ERROR_ADDRESS_IN_USE if
1249 * the server program is stopped and then immediately restarted.)
1251 * Returns: %TRUE on success, %FALSE on error.
1256 g_socket_bind (GSocket *socket,
1257 GSocketAddress *address,
1258 gboolean reuse_address,
1261 struct sockaddr_storage addr;
1263 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1265 if (!check_socket (socket, error))
1268 /* SO_REUSEADDR on windows means something else and is not what we want.
1269 It always allows the unix variant of SO_REUSEADDR anyway */
1274 value = (int) !!reuse_address;
1275 /* Ignore errors here, the only likely error is "not supported", and
1276 this is a "best effort" thing mainly */
1277 setsockopt (socket->priv->fd, SOL_SOCKET, SO_REUSEADDR,
1278 (gpointer) &value, sizeof (value));
1282 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1285 if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1286 g_socket_address_get_native_size (address)) < 0)
1288 int errsv = get_socket_errno ();
1290 G_IO_ERROR, socket_io_error_from_errno (errsv),
1291 _("Error binding to address: %s"), socket_strerror (errsv));
1299 * g_socket_speaks_ipv4:
1300 * @socket: a #GSocket
1302 * Checks if a socket is capable of speaking IPv4.
1304 * IPv4 sockets are capable of speaking IPv4. On some operating systems
1305 * and under some combinations of circumstances IPv6 sockets are also
1306 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
1309 * No other types of sockets are currently considered as being capable
1312 * Returns: %TRUE if this socket can be used with IPv4.
1317 g_socket_speaks_ipv4 (GSocket *socket)
1319 switch (socket->priv->family)
1321 case G_SOCKET_FAMILY_IPV4:
1324 case G_SOCKET_FAMILY_IPV6:
1325 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
1327 guint sizeof_int = sizeof (int);
1330 if (getsockopt (socket->priv->fd,
1331 IPPROTO_IPV6, IPV6_V6ONLY,
1332 &v6_only, &sizeof_int) != 0)
1348 * @socket: a #GSocket.
1349 * @cancellable: a %GCancellable or %NULL
1350 * @error: #GError for error reporting, or %NULL to ignore.
1352 * Accept incoming connections on a connection-based socket. This removes
1353 * the first outstanding connection request from the listening socket and
1354 * creates a #GSocket object for it.
1356 * The @socket must be bound to a local address with g_socket_bind() and
1357 * must be listening for incoming connections (g_socket_listen()).
1359 * If there are no outstanding connections then the operation will block
1360 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
1361 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
1363 * Returns: a new #GSocket, or %NULL on error.
1364 * Free the returned object with g_object_unref().
1369 g_socket_accept (GSocket *socket,
1370 GCancellable *cancellable,
1373 GSocket *new_socket;
1376 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1378 if (!check_socket (socket, error))
1383 if (socket->priv->blocking &&
1384 !g_socket_condition_wait (socket,
1385 G_IO_IN, cancellable, error))
1388 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
1390 int errsv = get_socket_errno ();
1392 win32_unset_event_mask (socket, FD_ACCEPT);
1397 if (socket->priv->blocking)
1399 #ifdef WSAEWOULDBLOCK
1400 if (errsv == WSAEWOULDBLOCK)
1403 if (errsv == EWOULDBLOCK ||
1409 g_set_error (error, G_IO_ERROR,
1410 socket_io_error_from_errno (errsv),
1411 _("Error accepting connection: %s"), socket_strerror (errsv));
1417 win32_unset_event_mask (socket, FD_ACCEPT);
1421 /* The socket inherits the accepting sockets event mask and even object,
1422 we need to remove that */
1423 WSAEventSelect (ret, NULL, 0);
1429 /* We always want to set close-on-exec to protect users. If you
1430 need to so some weird inheritance to exec you can re-enable this
1431 using lower level hacks with g_socket_get_fd(). */
1432 flags = fcntl (ret, F_GETFD, 0);
1434 (flags & FD_CLOEXEC) == 0)
1436 flags |= FD_CLOEXEC;
1437 fcntl (ret, F_SETFD, flags);
1442 new_socket = g_socket_new_from_fd (ret, error);
1443 if (new_socket == NULL)
1452 new_socket->priv->protocol = socket->priv->protocol;
1459 * @socket: a #GSocket.
1460 * @address: a #GSocketAddress specifying the remote address.
1461 * @cancellable: a %GCancellable or %NULL
1462 * @error: #GError for error reporting, or %NULL to ignore.
1464 * Connect the socket to the specified remote address.
1466 * For connection oriented socket this generally means we attempt to make
1467 * a connection to the @address. For a connection-less socket it sets
1468 * the default address for g_socket_send() and discards all incoming datagrams
1469 * from other sources.
1471 * Generally connection oriented sockets can only connect once, but
1472 * connection-less sockets can connect multiple times to change the
1475 * If the connect call needs to do network I/O it will block, unless
1476 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
1477 * and the user can be notified of the connection finishing by waiting
1478 * for the G_IO_OUT condition. The result of the connection can then be
1479 * checked with g_socket_check_connect_result().
1481 * Returns: %TRUE if connected, %FALSE on error.
1486 g_socket_connect (GSocket *socket,
1487 GSocketAddress *address,
1488 GCancellable *cancellable,
1491 struct sockaddr_storage buffer;
1493 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1495 if (!check_socket (socket, error))
1498 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
1503 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
1504 g_socket_address_get_native_size (address)) < 0)
1506 int errsv = get_socket_errno ();
1512 if (errsv == EINPROGRESS)
1514 if (errsv == WSAEWOULDBLOCK)
1517 if (socket->priv->blocking)
1519 if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
1521 if (g_socket_check_connect_result (socket, error))
1524 g_prefix_error (error, _("Error connecting: "));
1527 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
1528 _("Connection in progress"));
1531 g_set_error (error, G_IO_ERROR,
1532 socket_io_error_from_errno (errsv),
1533 _("Error connecting: %s"), socket_strerror (errsv));
1540 win32_unset_event_mask (socket, FD_CONNECT);
1542 socket->priv->connected = TRUE;
1548 * g_socket_check_connect_result:
1549 * @socket: a #GSocket
1550 * @error: #GError for error reporting, or %NULL to ignore.
1552 * Checks and resets the pending connect error for the socket.
1553 * This is used to check for errors when g_socket_connect() is
1554 * used in non-blocking mode.
1556 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
1561 g_socket_check_connect_result (GSocket *socket,
1567 optlen = sizeof (value);
1568 if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
1570 int errsv = get_socket_errno ();
1572 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1573 _("Unable to get pending error: %s"), socket_strerror (errsv));
1579 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
1580 socket_strerror (value));
1588 * @socket: a #GSocket
1589 * @buffer: a buffer to read data into (which should be at least @size
1591 * @size: the number of bytes you want to read from the socket
1592 * @cancellable: a %GCancellable or %NULL
1593 * @error: #GError for error reporting, or %NULL to ignore.
1595 * Receive data (up to @size bytes) from a socket. This is mainly used by
1596 * connection-oriented sockets; it is identical to g_socket_receive_from()
1597 * with @address set to %NULL.
1599 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
1600 * g_socket_receive() will always read either 0 or 1 complete messages from
1601 * the socket. If the received message is too large to fit in @buffer, then
1602 * the data beyond @size bytes will be discarded, without any explicit
1603 * indication that this has occurred.
1605 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
1606 * number of bytes, up to @size. If more than @size bytes have been
1607 * received, the additional data will be returned in future calls to
1608 * g_socket_receive().
1610 * If the socket is in blocking mode the call will block until there is
1611 * some data to receive or there is an error. If there is no data available
1612 * and the socket is in non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error
1613 * will be returned. To be notified when data is available, wait for the
1614 * %G_IO_IN condition.
1616 * On error -1 is returned and @error is set accordingly.
1618 * Returns: Number of bytes read, or -1 on error
1623 g_socket_receive (GSocket *socket,
1626 GCancellable *cancellable,
1631 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1633 if (!check_socket (socket, error))
1636 if (g_cancellable_set_error_if_cancelled (cancellable, error))
1641 if (socket->priv->blocking &&
1642 !g_socket_condition_wait (socket,
1643 G_IO_IN, cancellable, error))
1646 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
1648 int errsv = get_socket_errno ();
1653 if (socket->priv->blocking)
1655 #ifdef WSAEWOULDBLOCK
1656 if (errsv == WSAEWOULDBLOCK)
1659 if (errsv == EWOULDBLOCK ||
1665 win32_unset_event_mask (socket, FD_READ);
1667 g_set_error (error, G_IO_ERROR,
1668 socket_io_error_from_errno (errsv),
1669 _("Error receiving data: %s"), socket_strerror (errsv));
1673 win32_unset_event_mask (socket, FD_READ);
1682 * g_socket_receive_from:
1683 * @socket: a #GSocket
1684 * @address: a pointer to a #GSocketAddress pointer, or %NULL
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.
1693 * If @address is non-%NULL then @address will be set equal to the
1694 * source address of the received packet.
1695 * @address is owned by the caller.
1697 * See g_socket_receive() for additional information.
1699 * Returns: Number of bytes read, or -1 on error
1704 g_socket_receive_from (GSocket *socket,
1705 GSocketAddress **address,
1708 GCancellable *cancellable,
1716 return g_socket_receive_message (socket,
1724 /* Although we ignore SIGPIPE, gdb will still stop if the app receives
1725 * one, which can be confusing and annoying. So if possible, we want
1726 * to suppress the signal entirely.
1729 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
1731 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
1736 * @socket: a #GSocket
1737 * @buffer: the buffer containing the data to send.
1738 * @size: the number of bytes to send
1739 * @cancellable: a %GCancellable or %NULL
1740 * @error: #GError for error reporting, or %NULL to ignore.
1742 * Tries to send @size bytes from @buffer on the socket. This is
1743 * mainly used by connection-oriented sockets; it is identical to
1744 * g_socket_send_to() with @address set to %NULL.
1746 * If the socket is in blocking mode the call will block until there is
1747 * space for the data in the socket queue. If there is no space available
1748 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1749 * will be returned. To be notified when space is available, wait for the
1750 * %G_IO_OUT condition. Note though that you may still receive
1751 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
1752 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
1753 * very common due to the way the underlying APIs work.)
1755 * On error -1 is returned and @error is set accordingly.
1757 * Returns: Number of bytes written (which may be less than @size), or -1
1763 g_socket_send (GSocket *socket,
1764 const gchar *buffer,
1766 GCancellable *cancellable,
1771 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1773 if (!check_socket (socket, error))
1776 if (g_cancellable_set_error_if_cancelled (cancellable, error))
1781 if (socket->priv->blocking &&
1782 !g_socket_condition_wait (socket,
1783 G_IO_OUT, cancellable, error))
1786 if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
1788 int errsv = get_socket_errno ();
1793 #ifdef WSAEWOULDBLOCK
1794 if (errsv == WSAEWOULDBLOCK)
1795 win32_unset_event_mask (socket, FD_WRITE);
1798 if (socket->priv->blocking)
1800 #ifdef WSAEWOULDBLOCK
1801 if (errsv == WSAEWOULDBLOCK)
1804 if (errsv == EWOULDBLOCK ||
1810 g_set_error (error, G_IO_ERROR,
1811 socket_io_error_from_errno (errsv),
1812 _("Error sending data: %s"), socket_strerror (errsv));
1823 * @socket: a #GSocket
1824 * @address: a #GSocketAddress, or %NULL
1825 * @buffer: the buffer containing the data to send.
1826 * @size: the number of bytes to send
1827 * @cancellable: a %GCancellable or %NULL
1828 * @error: #GError for error reporting, or %NULL to ignore.
1830 * Tries to send @size bytes from @buffer to @address. If @address is
1831 * %NULL then the message is sent to the default receiver (set by
1832 * g_socket_connect()).
1834 * See g_socket_send() for additional information.
1836 * Returns: Number of bytes written (which may be less than @size), or -1
1842 g_socket_send_to (GSocket *socket,
1843 GSocketAddress *address,
1844 const gchar *buffer,
1846 GCancellable *cancellable,
1854 return g_socket_send_message (socket,
1864 * g_socket_shutdown:
1865 * @socket: a #GSocket
1866 * @shutdown_read: whether to shut down the read side
1867 * @shutdown_write: whether to shut down the write side
1868 * @error: #GError for error reporting, or %NULL to ignore.
1870 * Shut down part of a full-duplex connection.
1872 * If @shutdown_read is %TRUE then the recieving side of the connection
1873 * is shut down, and further reading is disallowed.
1875 * If @shutdown_write is %TRUE then the sending side of the connection
1876 * is shut down, and further writing is disallowed.
1878 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
1880 * One example where this is used is graceful disconnect for TCP connections
1881 * where you close the sending side, then wait for the other side to close
1882 * the connection, thus ensuring that the other side saw all sent data.
1884 * Returns: %TRUE on success, %FALSE on error
1889 g_socket_shutdown (GSocket *socket,
1890 gboolean shutdown_read,
1891 gboolean shutdown_write,
1896 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
1898 if (!check_socket (socket, NULL))
1902 if (!shutdown_read && !shutdown_write)
1906 if (shutdown_read && shutdown_write)
1908 else if (shutdown_read)
1913 if (shutdown_read && shutdown_write)
1915 else if (shutdown_read)
1921 if (shutdown (socket->priv->fd, how) != 0)
1923 int errsv = get_socket_errno ();
1924 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1925 _("Unable to create socket: %s"), socket_strerror (errsv));
1929 if (shutdown_read && shutdown_write)
1930 socket->priv->connected = FALSE;
1937 * @socket: a #GSocket
1938 * @error: #GError for error reporting, or %NULL to ignore.
1940 * Closes the socket, shutting down any active connection.
1942 * Closing a socket does not wait for all outstanding I/O operations
1943 * to finish, so the caller should not rely on them to be guaranteed
1944 * to complete even if the close returns with no error.
1946 * Once the socket is closed, all other operations will return
1947 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
1950 * Sockets will be automatically closed when the last reference
1951 * is dropped, but you might want to call this function to make sure
1952 * resources are released as early as possible.
1954 * Beware that due to the way that TCP works, it is possible for
1955 * recently-sent data to be lost if either you close a socket while the
1956 * %G_IO_IN condition is set, or else if the remote connection tries to
1957 * send something to you after you close the socket but before it has
1958 * finished reading all of the data you sent. There is no easy generic
1959 * way to avoid this problem; the easiest fix is to design the network
1960 * protocol such that the client will never send data "out of turn".
1961 * Another solution is for the server to half-close the connection by
1962 * calling g_socket_shutdown() with only the @shutdown_write flag set,
1963 * and then wait for the client to notice this and close its side of the
1964 * connection, after which the server can safely call g_socket_close().
1965 * (This is what #GTcpConnection does if you call
1966 * g_tcp_connection_set_graceful_disconnect(). But of course, this
1967 * only works if the client will close its connection after the server
1970 * Returns: %TRUE on success, %FALSE on error
1975 g_socket_close (GSocket *socket,
1980 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
1982 if (socket->priv->closed)
1983 return TRUE; /* Multiple close not an error */
1985 if (!check_socket (socket, NULL))
1991 res = closesocket (socket->priv->fd);
1993 res = close (socket->priv->fd);
1997 int errsv = get_socket_errno ();
2002 g_set_error (error, G_IO_ERROR,
2003 socket_io_error_from_errno (errsv),
2004 _("Error closing socket: %s"),
2005 socket_strerror (errsv));
2011 socket->priv->connected = FALSE;
2012 socket->priv->closed = TRUE;
2018 * g_socket_is_closed:
2019 * @socket: a #GSocket
2021 * Checks whether a socket is closed.
2023 * Returns: %TRUE if socket is closed, %FALSE otherwise
2028 g_socket_is_closed (GSocket *socket)
2030 return socket->priv->closed;
2034 /* Broken source, used on errors */
2036 broken_prepare (GSource *source,
2043 broken_check (GSource *source)
2049 broken_dispatch (GSource *source,
2050 GSourceFunc callback,
2056 static GSourceFuncs broken_funcs =
2065 network_events_for_condition (GIOCondition condition)
2069 if (condition & G_IO_IN)
2070 event_mask |= (FD_READ | FD_ACCEPT);
2071 if (condition & G_IO_OUT)
2072 event_mask |= (FD_WRITE | FD_CONNECT);
2073 event_mask |= FD_CLOSE;
2079 ensure_event (GSocket *socket)
2081 if (socket->priv->event == WSA_INVALID_EVENT)
2082 socket->priv->event = WSACreateEvent();
2086 update_select_events (GSocket *socket)
2093 ensure_event (socket);
2096 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
2099 event_mask |= network_events_for_condition (*ptr);
2102 if (event_mask != socket->priv->selected_events)
2104 /* If no events selected, disable event so we can unset
2107 if (event_mask == 0)
2110 event = socket->priv->event;
2112 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
2113 socket->priv->selected_events = event_mask;
2118 add_condition_watch (GSocket *socket,
2119 GIOCondition *condition)
2121 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
2123 socket->priv->requested_conditions =
2124 g_list_prepend (socket->priv->requested_conditions, condition);
2126 update_select_events (socket);
2130 remove_condition_watch (GSocket *socket,
2131 GIOCondition *condition)
2133 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
2135 socket->priv->requested_conditions =
2136 g_list_remove (socket->priv->requested_conditions, condition);
2138 update_select_events (socket);
2142 update_condition (GSocket *socket)
2144 WSANETWORKEVENTS events;
2145 GIOCondition condition;
2147 if (WSAEnumNetworkEvents (socket->priv->fd,
2148 socket->priv->event,
2151 socket->priv->current_events |= events.lNetworkEvents;
2152 if (events.lNetworkEvents & FD_WRITE &&
2153 events.iErrorCode[FD_WRITE_BIT] != 0)
2154 socket->priv->current_errors |= FD_WRITE;
2155 if (events.lNetworkEvents & FD_CONNECT &&
2156 events.iErrorCode[FD_CONNECT_BIT] != 0)
2157 socket->priv->current_errors |= FD_CONNECT;
2161 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
2162 condition |= G_IO_IN;
2164 if (socket->priv->current_events & FD_CLOSE ||
2165 socket->priv->closed)
2166 condition |= G_IO_HUP;
2168 /* Never report both G_IO_OUT and HUP, these are
2169 mutually exclusive (can't write to a closed socket) */
2170 if ((condition & G_IO_HUP) == 0 &&
2171 socket->priv->current_events & FD_WRITE)
2173 if (socket->priv->current_errors & FD_WRITE)
2174 condition |= G_IO_ERR;
2176 condition |= G_IO_OUT;
2180 if (socket->priv->current_events & FD_CONNECT)
2182 if (socket->priv->current_errors & FD_CONNECT)
2183 condition |= (G_IO_HUP | G_IO_ERR);
2185 condition |= G_IO_OUT;
2196 GIOCondition condition;
2197 GCancellable *cancellable;
2198 GPollFD cancel_pollfd;
2199 GIOCondition result_condition;
2203 winsock_prepare (GSource *source,
2206 GWinsockSource *winsock_source = (GWinsockSource *)source;
2207 GIOCondition current_condition;
2209 current_condition = update_condition (winsock_source->socket);
2211 if (g_cancellable_is_cancelled (winsock_source->cancellable))
2213 winsock_source->result_condition = current_condition;
2217 if ((winsock_source->condition & current_condition) != 0)
2219 winsock_source->result_condition = current_condition;
2227 winsock_check (GSource *source)
2229 GWinsockSource *winsock_source = (GWinsockSource *)source;
2230 GIOCondition current_condition;
2232 current_condition = update_condition (winsock_source->socket);
2234 if (g_cancellable_is_cancelled (winsock_source->cancellable))
2236 winsock_source->result_condition = current_condition;
2240 if ((winsock_source->condition & current_condition) != 0)
2242 winsock_source->result_condition = current_condition;
2250 winsock_dispatch (GSource *source,
2251 GSourceFunc callback,
2254 GSocketSourceFunc func = (GSocketSourceFunc)callback;
2255 GWinsockSource *winsock_source = (GWinsockSource *)source;
2257 return (*func) (winsock_source->socket,
2258 winsock_source->result_condition & winsock_source->condition,
2263 winsock_finalize (GSource *source)
2265 GWinsockSource *winsock_source = (GWinsockSource *)source;
2268 socket = winsock_source->socket;
2270 remove_condition_watch (socket, &winsock_source->condition);
2271 g_object_unref (socket);
2273 if (winsock_source->cancellable)
2275 g_cancellable_release_fd (winsock_source->cancellable);
2276 g_object_unref (winsock_source->cancellable);
2280 static GSourceFuncs winsock_funcs =
2289 winsock_source_new (GSocket *socket,
2290 GIOCondition condition,
2291 GCancellable *cancellable)
2294 GWinsockSource *winsock_source;
2296 ensure_event (socket);
2298 if (socket->priv->event == WSA_INVALID_EVENT)
2300 g_warning ("Failed to create WSAEvent");
2301 return g_source_new (&broken_funcs, sizeof (GSource));
2304 condition |= G_IO_HUP | G_IO_ERR;
2306 source = g_source_new (&winsock_funcs, sizeof (GWinsockSource));
2307 winsock_source = (GWinsockSource *)source;
2309 winsock_source->socket = g_object_ref (socket);
2310 winsock_source->condition = condition;
2311 add_condition_watch (socket, &winsock_source->condition);
2313 if (g_cancellable_make_pollfd (cancellable,
2314 &winsock_source->cancel_pollfd))
2316 winsock_source->cancellable = g_object_ref (cancellable);
2317 g_source_add_poll (source, &winsock_source->cancel_pollfd);
2320 winsock_source->pollfd.fd = (gintptr) socket->priv->event;
2321 winsock_source->pollfd.events = condition;
2322 g_source_add_poll (source, &winsock_source->pollfd);
2329 * g_socket_create_source:
2330 * @socket: a #GSocket
2331 * @condition: a #GIOCondition mask to monitor
2332 * @cancellable: a %GCancellable or %NULL
2334 * Creates a %GSource that can be attached to a %GMainContext to monitor
2335 * for the availibility of the specified @condition on the socket.
2337 * The callback on the source is of the #GSocketSourceFunc type.
2339 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2340 * these conditions will always be reported output if they are true.
2342 * @cancellable if not %NULL can be used to cancel the source, which will
2343 * cause the source to trigger, reporting the current condition (which
2344 * is likely 0 unless cancellation happened at the same time as a
2345 * condition change). You can check for this in the callback using
2346 * g_cancellable_is_cancelled().
2348 * Returns: a newly allocated %GSource, free with g_source_unref().
2353 g_socket_create_source (GSocket *socket,
2354 GIOCondition condition,
2355 GCancellable *cancellable)
2358 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
2361 source = winsock_source_new (socket, condition, cancellable);
2363 source =_g_fd_source_new_with_object (G_OBJECT (socket), socket->priv->fd,
2364 condition, cancellable);
2370 * g_socket_condition_check:
2371 * @socket: a #GSocket
2372 * @condition: a #GIOCondition mask to check
2374 * Checks on the readiness of @socket to perform operations.
2375 * The operations specified in @condition are checked for and masked
2376 * against the currently-satisfied conditions on @socket. The result
2379 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2380 * these conditions will always be set in the output if they are true.
2382 * This call never blocks.
2384 * Returns: the @GIOCondition mask of the current state
2389 g_socket_condition_check (GSocket *socket,
2390 GIOCondition condition)
2392 if (!check_socket (socket, NULL))
2397 GIOCondition current_condition;
2399 condition |= G_IO_ERR | G_IO_HUP;
2401 add_condition_watch (socket, &condition);
2402 current_condition = update_condition (socket);
2403 remove_condition_watch (socket, &condition);
2404 return condition & current_condition;
2410 poll_fd.fd = socket->priv->fd;
2411 poll_fd.events = condition;
2414 result = g_poll (&poll_fd, 1, 0);
2415 while (result == -1 && get_socket_errno () == EINTR);
2417 return poll_fd.revents;
2423 * g_socket_condition_wait:
2424 * @socket: a #GSocket
2425 * @condition: a #GIOCondition mask to wait for
2426 * @cancellable: a #GCancellable, or %NULL
2427 * @error: a #GError pointer, or %NULL
2429 * Waits for @condition to become true on @socket. When the condition
2430 * is met, %TRUE is returned.
2432 * If @cancellable is cancelled before the condition is met then %FALSE
2433 * is returned and @error, if non-%NULL, is set to %G_IO_ERROR_CANCELLED.
2435 * Returns: %TRUE if the condition was met, %FALSE otherwise
2440 g_socket_condition_wait (GSocket *socket,
2441 GIOCondition condition,
2442 GCancellable *cancellable,
2445 if (!check_socket (socket, error))
2448 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2453 GIOCondition current_condition;
2459 /* Always check these */
2460 condition |= G_IO_ERR | G_IO_HUP;
2462 add_condition_watch (socket, &condition);
2465 events[num_events++] = socket->priv->event;
2467 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
2468 events[num_events++] = (WSAEVENT)cancel_fd.fd;
2470 current_condition = update_condition (socket);
2471 while ((condition & current_condition) == 0)
2473 res = WSAWaitForMultipleEvents(num_events, events,
2474 FALSE, WSA_INFINITE, FALSE);
2475 if (res == WSA_WAIT_FAILED)
2477 int errsv = get_socket_errno ();
2479 g_set_error (error, G_IO_ERROR,
2480 socket_io_error_from_errno (errsv),
2481 _("Waiting for socket condition: %s"),
2482 socket_strerror (errsv));
2486 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2489 current_condition = update_condition (socket);
2491 remove_condition_watch (socket, &condition);
2493 g_cancellable_release_fd (cancellable);
2495 return (condition & current_condition) != 0;
2503 poll_fd[0].fd = socket->priv->fd;
2504 poll_fd[0].events = condition;
2507 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
2511 result = g_poll (poll_fd, num, -1);
2512 while (result == -1 && get_socket_errno () == EINTR);
2515 g_cancellable_release_fd (cancellable);
2517 return cancellable == NULL ||
2518 !g_cancellable_set_error_if_cancelled (cancellable, error);
2524 * g_socket_send_message:
2525 * @socket: a #GSocket
2526 * @address: a #GSocketAddress, or %NULL
2527 * @vectors: an array of #GOutputVector structs
2528 * @num_vectors: the number of elements in @vectors, or -1
2529 * @messages: a pointer to an array of #GSocketControlMessages, or
2531 * @num_messages: number of elements in @messages, or -1.
2532 * @flags: an int containing #GSocketMsgFlags flags
2533 * @cancellable: a %GCancellable or %NULL
2534 * @error: #GError for error reporting, or %NULL to ignore.
2536 * Send data to @address on @socket. This is the most complicated and
2537 * fully-featured version of this call. For easier use, see
2538 * g_socket_send() and g_socket_send_to().
2540 * If @address is %NULL then the message is sent to the default receiver
2541 * (set by g_socket_connect()).
2543 * @vectors must point to an array of #GOutputVector structs and
2544 * @num_vectors must be the length of this array. (If @num_vectors is -1,
2545 * then @vectors is assumed to be terminated by a #GOutputVector with a
2546 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
2547 * that the sent data will be gathered from. Using multiple
2548 * #GOutputVector<!-- -->s is more memory-efficient than manually copying
2549 * data from multiple sources into a single buffer, and more
2550 * network-efficient than making multiple calls to g_socket_send().
2552 * @messages, if non-%NULL, is taken to point to an array of @num_messages
2553 * #GSocketControlMessage instances. These correspond to the control
2554 * messages to be sent on the socket.
2555 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
2558 * @flags modify how the message is sent. The commonly available arguments
2559 * for this are available in the #GSocketMsgFlags enum, but the
2560 * values there are the same as the system values, and the flags
2561 * are passed in as-is, so you can pass in system-specific flags too.
2563 * If the socket is in blocking mode the call will block until there is
2564 * space for the data in the socket queue. If there is no space available
2565 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2566 * will be returned. To be notified when space is available, wait for the
2567 * %G_IO_OUT condition. Note though that you may still receive
2568 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2569 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2570 * very common due to the way the underlying APIs work.)
2572 * On error -1 is returned and @error is set accordingly.
2574 * Returns: Number of bytes written (which may be less than @size), or -1
2580 g_socket_send_message (GSocket *socket,
2581 GSocketAddress *address,
2582 GOutputVector *vectors,
2584 GSocketControlMessage **messages,
2587 GCancellable *cancellable,
2590 GOutputVector one_vector;
2593 if (!check_socket (socket, error))
2596 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2599 if (num_vectors == -1)
2601 for (num_vectors = 0;
2602 vectors[num_vectors].buffer != NULL;
2607 if (num_messages == -1)
2609 for (num_messages = 0;
2610 messages != NULL && messages[num_messages] != NULL;
2615 if (num_vectors == 0)
2619 one_vector.buffer = &zero;
2620 one_vector.size = 1;
2622 vectors = &one_vector;
2633 msg.msg_namelen = g_socket_address_get_native_size (address);
2634 msg.msg_name = g_alloca (msg.msg_namelen);
2635 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
2640 msg.msg_name = NULL;
2641 msg.msg_namelen = 0;
2646 /* this entire expression will be evaluated at compile time */
2647 if (sizeof *msg.msg_iov == sizeof *vectors &&
2648 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2649 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2650 G_STRUCT_OFFSET (GOutputVector, buffer) &&
2651 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2652 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2653 G_STRUCT_OFFSET (GOutputVector, size))
2654 /* ABI is compatible */
2656 msg.msg_iov = (struct iovec *) vectors;
2657 msg.msg_iovlen = num_vectors;
2660 /* ABI is incompatible */
2664 msg.msg_iov = g_newa (struct iovec, num_vectors);
2665 for (i = 0; i < num_vectors; i++)
2667 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
2668 msg.msg_iov[i].iov_len = vectors[i].size;
2670 msg.msg_iovlen = num_vectors;
2676 struct cmsghdr *cmsg;
2679 msg.msg_controllen = 0;
2680 for (i = 0; i < num_messages; i++)
2681 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
2683 msg.msg_control = g_alloca (msg.msg_controllen);
2685 cmsg = CMSG_FIRSTHDR (&msg);
2686 for (i = 0; i < num_messages; i++)
2688 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
2689 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
2690 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
2691 g_socket_control_message_serialize (messages[i],
2693 cmsg = CMSG_NXTHDR (&msg, cmsg);
2695 g_assert (cmsg == NULL);
2700 if (socket->priv->blocking &&
2701 !g_socket_condition_wait (socket,
2702 G_IO_OUT, cancellable, error))
2705 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
2708 int errsv = get_socket_errno ();
2713 if (socket->priv->blocking &&
2714 (errsv == EWOULDBLOCK ||
2718 g_set_error (error, G_IO_ERROR,
2719 socket_io_error_from_errno (errsv),
2720 _("Error sending message: %s"), socket_strerror (errsv));
2731 struct sockaddr_storage addr;
2738 /* Win32 doesn't support control messages.
2739 Actually this is possible for raw and datagram sockets
2740 via WSASendMessage on Vista or later, but that doesn't
2742 if (num_messages != 0)
2744 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2745 _("GSocketControlMessage not supported on windows"));
2750 bufs = g_newa (WSABUF, num_vectors);
2751 for (i = 0; i < num_vectors; i++)
2753 bufs[i].buf = (char *)vectors[i].buffer;
2754 bufs[i].len = (gulong)vectors[i].size;
2758 addrlen = 0; /* Avoid warning */
2761 addrlen = g_socket_address_get_native_size (address);
2762 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
2768 if (socket->priv->blocking &&
2769 !g_socket_condition_wait (socket,
2770 G_IO_OUT, cancellable, error))
2774 result = WSASendTo (socket->priv->fd,
2777 (const struct sockaddr *)&addr, addrlen,
2780 result = WSASend (socket->priv->fd,
2787 int errsv = get_socket_errno ();
2789 if (errsv == WSAEINTR)
2792 if (errsv == WSAEWOULDBLOCK)
2793 win32_unset_event_mask (socket, FD_WRITE);
2795 if (socket->priv->blocking &&
2796 errsv == WSAEWOULDBLOCK)
2799 g_set_error (error, G_IO_ERROR,
2800 socket_io_error_from_errno (errsv),
2801 _("Error sending message: %s"), socket_strerror (errsv));
2814 * g_socket_receive_message:
2815 * @socket: a #GSocket
2816 * @address: a pointer to a #GSocketAddress pointer, or %NULL
2817 * @vectors: an array of #GInputVector structs
2818 * @num_vectors: the number of elements in @vectors, or -1
2819 * @messages: a pointer which will be filled with an array of
2820 * #GSocketControlMessages, or %NULL
2821 * @num_messages: a pointer which will be filled with the number of
2822 * elements in @messages, or %NULL
2823 * @flags: a pointer to an int containing #GSocketMsgFlags flags
2824 * @cancellable: a %GCancellable or %NULL
2825 * @error: a #GError pointer, or %NULL
2827 * Receive data from a socket. This is the most complicated and
2828 * fully-featured version of this call. For easier use, see
2829 * g_socket_receive() and g_socket_receive_from().
2831 * If @address is non-%NULL then @address will be set equal to the
2832 * source address of the received packet.
2833 * @address is owned by the caller.
2835 * @vector must point to an array of #GInputVector structs and
2836 * @num_vectors must be the length of this array. These structs
2837 * describe the buffers that received data will be scattered into.
2838 * If @num_vectors is -1, then @vectors is assumed to be terminated
2839 * by a #GInputVector with a %NULL buffer pointer.
2841 * As a special case, if @num_vectors is 0 (in which case, @vectors
2842 * may of course be %NULL), then a single byte is received and
2843 * discarded. This is to facilitate the common practice of sending a
2844 * single '\0' byte for the purposes of transferring ancillary data.
2846 * @messages, if non-%NULL, will be set to point to a newly-allocated
2847 * array of #GSocketControlMessage instances. These correspond to the
2848 * control messages received from the kernel, one
2849 * #GSocketControlMessage per message from the kernel. This array is
2850 * %NULL-terminated and must be freed by the caller using g_free(). If
2851 * @messages is %NULL, any control messages received will be
2854 * @num_messages, if non-%NULL, will be set to the number of control
2855 * messages received.
2857 * If both @messages and @num_messages are non-%NULL, then
2858 * @num_messages gives the number of #GSocketControlMessage instances
2859 * in @messages (ie: not including the %NULL terminator).
2861 * @flags is an in/out parameter. The commonly available arguments
2862 * for this are available in the #GSocketMsgFlags enum, but the
2863 * values there are the same as the system values, and the flags
2864 * are passed in as-is, so you can pass in system-specific flags too
2865 * (and g_socket_receive_message() may pass system-specific flags out).
2867 * As with g_socket_receive(), data may be discarded if @socket is
2868 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
2869 * provide enough buffer space to read a complete message. You can pass
2870 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
2871 * removing it from the receive queue, but there is no portable way to find
2872 * out the length of the message other than by reading it into a
2873 * sufficiently-large buffer.
2875 * If the socket is in blocking mode the call will block until there
2876 * is some data to receive or there is an error. If there is no data
2877 * available and the socket is in non-blocking mode, a
2878 * %G_IO_ERROR_WOULD_BLOCK error will be returned. To be notified when
2879 * data is available, wait for the %G_IO_IN condition.
2881 * On error -1 is returned and @error is set accordingly.
2883 * Returns: Number of bytes read, or -1 on error
2888 g_socket_receive_message (GSocket *socket,
2889 GSocketAddress **address,
2890 GInputVector *vectors,
2892 GSocketControlMessage ***messages,
2895 GCancellable *cancellable,
2898 GInputVector one_vector;
2901 if (!check_socket (socket, error))
2904 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2907 if (num_vectors == -1)
2909 for (num_vectors = 0;
2910 vectors[num_vectors].buffer != NULL;
2915 if (num_vectors == 0)
2917 one_vector.buffer = &one_byte;
2918 one_vector.size = 1;
2920 vectors = &one_vector;
2927 struct sockaddr_storage one_sockaddr;
2932 msg.msg_name = &one_sockaddr;
2933 msg.msg_namelen = sizeof (struct sockaddr_storage);
2937 msg.msg_name = NULL;
2938 msg.msg_namelen = 0;
2942 /* this entire expression will be evaluated at compile time */
2943 if (sizeof *msg.msg_iov == sizeof *vectors &&
2944 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2945 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2946 G_STRUCT_OFFSET (GInputVector, buffer) &&
2947 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2948 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2949 G_STRUCT_OFFSET (GInputVector, size))
2950 /* ABI is compatible */
2952 msg.msg_iov = (struct iovec *) vectors;
2953 msg.msg_iovlen = num_vectors;
2956 /* ABI is incompatible */
2960 msg.msg_iov = g_newa (struct iovec, num_vectors);
2961 for (i = 0; i < num_vectors; i++)
2963 msg.msg_iov[i].iov_base = vectors[i].buffer;
2964 msg.msg_iov[i].iov_len = vectors[i].size;
2966 msg.msg_iovlen = num_vectors;
2970 msg.msg_control = g_alloca (2048);
2971 msg.msg_controllen = 2048;
2975 msg.msg_flags = *flags;
2982 if (socket->priv->blocking &&
2983 !g_socket_condition_wait (socket,
2984 G_IO_IN, cancellable, error))
2987 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
2991 int errsv = get_socket_errno ();
2996 if (socket->priv->blocking &&
2997 (errsv == EWOULDBLOCK ||
3001 g_set_error (error, G_IO_ERROR,
3002 socket_io_error_from_errno (errsv),
3003 _("Error receiving message: %s"), socket_strerror (errsv));
3010 /* decode address */
3011 if (address != NULL)
3013 if (msg.msg_namelen > 0)
3014 *address = g_socket_address_new_from_native (msg.msg_name,
3020 /* decode control messages */
3022 GSocketControlMessage **my_messages = NULL;
3023 gint allocated = 0, index = 0;
3024 const gchar *scm_pointer;
3025 struct cmsghdr *cmsg;
3028 scm_pointer = (const gchar *) msg.msg_control;
3029 scm_size = msg.msg_controllen;
3031 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
3033 GSocketControlMessage *message;
3035 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
3037 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
3039 if (message == NULL)
3040 /* We've already spewed about the problem in the
3041 deserialization code, so just continue */
3044 if (index == allocated)
3046 /* estimated 99% case: exactly 1 control message */
3047 allocated = MAX (allocated * 2, 1);
3048 my_messages = g_new (GSocketControlMessage *, (allocated + 1));
3051 my_messages[index++] = message;
3055 *num_messages = index;
3059 my_messages[index++] = NULL;
3060 *messages = my_messages;
3066 /* free all those messages we just constructed.
3067 * we have to do it this way if the user ignores the
3068 * messages so that we will close any received fds.
3070 for (i = 0; i < index; i++)
3071 g_object_unref (my_messages[i]);
3072 g_free (my_messages);
3076 /* capture the flags */
3078 *flags = msg.msg_flags;
3084 struct sockaddr_storage addr;
3086 DWORD bytes_received;
3093 bufs = g_newa (WSABUF, num_vectors);
3094 for (i = 0; i < num_vectors; i++)
3096 bufs[i].buf = (char *)vectors[i].buffer;
3097 bufs[i].len = (gulong)vectors[i].size;
3109 if (socket->priv->blocking &&
3110 !g_socket_condition_wait (socket,
3111 G_IO_IN, cancellable, error))
3114 addrlen = sizeof addr;
3116 result = WSARecvFrom (socket->priv->fd,
3118 &bytes_received, &win_flags,
3119 (struct sockaddr *)&addr, &addrlen,
3122 result = WSARecv (socket->priv->fd,
3124 &bytes_received, &win_flags,
3128 int errsv = get_socket_errno ();
3130 if (errsv == WSAEINTR)
3133 win32_unset_event_mask (socket, FD_READ);
3135 if (socket->priv->blocking &&
3136 errsv == WSAEWOULDBLOCK)
3139 g_set_error (error, G_IO_ERROR,
3140 socket_io_error_from_errno (errsv),
3141 _("Error receiving message: %s"), socket_strerror (errsv));
3145 win32_unset_event_mask (socket, FD_READ);
3149 /* decode address */
3150 if (address != NULL)
3153 *address = g_socket_address_new_from_native (&addr, addrlen);
3158 /* capture the flags */
3162 return bytes_received;
3167 #define __G_SOCKET_C__
3168 #include "gioaliasdef.c"