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"
62 * @short_description: Low-level socket object
64 * @see_also: #GInitable
66 * A #GSocket is a low-level networking primitive. It is a more or less
67 * direct mapping of the BSD socket API in a portable GObject based API.
68 * It supports both the UNIX socket implementations and winsock2 on Windows.
70 * #GSocket is the platform independent base upon which the higher level
71 * network primitives are based. Applications are not typically meant to
72 * use it directly, but rather through classes like #GSocketClient,
73 * #GSocketService and #GSocketConnection. However there may be cases where
74 * direct use of #GSocket is useful.
76 * #GSocket implements the #GInitable interface, so if it is manually constructed
77 * by e.g. g_object_new() you must call g_initable_init() and check the
78 * results before using the object. This is done automatically in
79 * g_socket_new() and g_socket_new_from_fd(), so these functions can return
82 * Sockets operate in two general modes, blocking or non-blocking. When
83 * in blocking mode all operations block until the requested operation
84 * is finished or there is an error. In non-blocking mode all calls that
85 * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
86 * To know when a call would successfully run you can call g_socket_condition_check(),
87 * or g_socket_condition_wait(). You can also use g_socket_create_source() and
88 * attach it to a #GMainContext to get callbacks when I/O is possible.
89 * Note that all sockets are always set to non blocking mode in the system, and
90 * blocking mode is emulated in GSocket.
92 * When working in non-blocking mode applications should always be able to
93 * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
94 * function said that I/O was possible. This can easily happen in case
95 * of a race condition in the application, but it can also happen for other
96 * reasons. For instance, on Windows a socket is always seen as writable
97 * until a write returns %G_IO_ERROR_WOULD_BLOCK.
99 * #GSocket<!-- -->s can be either connection oriented or datagram based.
100 * For connection oriented types you must first establish a connection by
101 * either connecting to an address or accepting a connection from another
102 * address. For connectionless socket types the target/source address is
103 * specified or received in each I/O operation.
105 * All socket file descriptors are set to be close-on-exec.
107 * Note that creating a #GSocket causes the signal %SIGPIPE to be
108 * ignored for the remainder of the program. If you are writing a
109 * command-line utility that uses #GSocket, you may need to take into
110 * account the fact that your program will not automatically be killed
111 * if it tries to write to %stdout after it has been closed.
116 static void g_socket_initable_iface_init (GInitableIface *iface);
117 static gboolean g_socket_initable_init (GInitable *initable,
118 GCancellable *cancellable,
121 G_DEFINE_TYPE_WITH_CODE (GSocket, g_socket, G_TYPE_OBJECT,
122 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
123 g_socket_initable_iface_init));
139 struct _GSocketPrivate
141 GSocketFamily family;
143 GSocketProtocol protocol;
146 GError *construct_error;
158 GList *requested_conditions; /* list of requested GIOCondition * */
163 get_socket_errno (void)
168 return WSAGetLastError ();
173 socket_io_error_from_errno (int err)
176 return g_io_error_from_errno (err);
181 return G_IO_ERROR_ADDRESS_IN_USE;
183 return G_IO_ERROR_WOULD_BLOCK;
185 return G_IO_ERROR_PERMISSION_DENIED;
186 case WSA_INVALID_HANDLE:
187 case WSA_INVALID_PARAMETER:
190 return G_IO_ERROR_INVALID_ARGUMENT;
191 case WSAEPROTONOSUPPORT:
192 return G_IO_ERROR_NOT_SUPPORTED;
194 return G_IO_ERROR_CANCELLED;
195 case WSAESOCKTNOSUPPORT:
197 case WSAEPFNOSUPPORT:
198 case WSAEAFNOSUPPORT:
199 return G_IO_ERROR_NOT_SUPPORTED;
201 return G_IO_ERROR_FAILED;
207 socket_strerror (int err)
210 return g_strerror (err);
212 static GStaticPrivate msg_private = G_STATIC_PRIVATE_INIT;
215 buf = g_static_private_get (&msg_private);
218 buf = g_new (gchar, 128);
219 g_static_private_set (&msg_private, buf, g_free);
222 msg = g_win32_error_message (err);
223 strncpy (buf, msg, 128);
230 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
232 _win32_unset_event_mask (GSocket *socket, int mask)
234 socket->priv->current_events &= ~mask;
235 socket->priv->current_errors &= ~mask;
238 #define win32_unset_event_mask(_socket, _mask)
242 set_fd_nonblocking (int fd)
251 if ((arg = fcntl (fd, F_GETFL, NULL)) < 0)
253 g_warning ("Error getting socket status flags: %s", socket_strerror (errno));
257 arg = arg | O_NONBLOCK;
259 if (fcntl (fd, F_SETFL, arg) < 0)
260 g_warning ("Error setting socket status flags: %s", socket_strerror (errno));
264 if (ioctlsocket (fd, FIONBIO, &arg) == SOCKET_ERROR)
266 int errsv = get_socket_errno ();
267 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
273 check_socket (GSocket *socket,
276 if (!socket->priv->inited)
278 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
279 _("Invalid socket, not initialized"));
283 if (socket->priv->construct_error)
285 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
286 _("Invalid socket, initialization failed due to: %s"),
287 socket->priv->construct_error->message);
291 if (socket->priv->closed)
293 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
294 _("Socket is already closed"));
301 g_socket_details_from_fd (GSocket *socket)
303 struct sockaddr_storage address;
310 /* See bug #611756 */
311 BOOL bool_val = FALSE;
316 fd = socket->priv->fd;
317 optlen = sizeof value;
318 if (getsockopt (fd, SOL_SOCKET, SO_TYPE, (void *)&value, &optlen) != 0)
320 errsv = get_socket_errno ();
331 /* programmer error */
332 g_error ("creating GSocket from fd %d: %s\n",
333 fd, socket_strerror (errsv));
341 g_assert (optlen == sizeof value);
345 socket->priv->type = G_SOCKET_TYPE_STREAM;
349 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
353 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
357 socket->priv->type = G_SOCKET_TYPE_INVALID;
361 addrlen = sizeof address;
362 if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
364 errsv = get_socket_errno ();
368 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
369 sizeof address.ss_family <= addrlen);
370 switch (address.ss_family)
372 case G_SOCKET_FAMILY_IPV4:
373 case G_SOCKET_FAMILY_IPV6:
374 case G_SOCKET_FAMILY_UNIX:
375 socket->priv->family = address.ss_family;
379 socket->priv->family = G_SOCKET_FAMILY_INVALID;
383 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
385 addrlen = sizeof address;
386 if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
387 socket->priv->connected = TRUE;
390 optlen = sizeof bool_val;
391 if (getsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
392 (void *)&bool_val, &optlen) == 0)
395 /* Experimentation indicates that the SO_KEEPALIVE value is
396 * actually a char on Windows, even if documentation claims it
397 * to be a BOOL which is a typedef for int. So this g_assert()
398 * fails. See bug #611756.
400 g_assert (optlen == sizeof bool_val);
402 socket->priv->keepalive = !!bool_val;
406 /* Can't read, maybe not supported, assume FALSE */
407 socket->priv->keepalive = FALSE;
413 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
414 socket_io_error_from_errno (errsv),
415 _("creating GSocket from fd: %s"),
416 socket_strerror (errsv));
420 g_socket_create_socket (GSocketFamily family,
430 case G_SOCKET_TYPE_STREAM:
431 native_type = SOCK_STREAM;
434 case G_SOCKET_TYPE_DATAGRAM:
435 native_type = SOCK_DGRAM;
438 case G_SOCKET_TYPE_SEQPACKET:
439 native_type = SOCK_SEQPACKET;
443 g_assert_not_reached ();
448 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
449 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
454 native_type |= SOCK_CLOEXEC;
456 fd = socket (family, native_type, protocol);
460 int errsv = get_socket_errno ();
462 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
463 _("Unable to create socket: %s"), socket_strerror (errsv));
470 /* We always want to set close-on-exec to protect users. If you
471 need to so some weird inheritance to exec you can re-enable this
472 using lower level hacks with g_socket_get_fd(). */
473 flags = fcntl (fd, F_GETFD, 0);
475 (flags & FD_CLOEXEC) == 0)
478 fcntl (fd, F_SETFD, flags);
487 g_socket_constructed (GObject *object)
489 GSocket *socket = G_SOCKET (object);
491 if (socket->priv->fd >= 0)
492 /* create socket->priv info from the fd */
493 g_socket_details_from_fd (socket);
496 /* create the fd from socket->priv info */
497 socket->priv->fd = g_socket_create_socket (socket->priv->family,
499 socket->priv->protocol,
500 &socket->priv->construct_error);
502 /* Always use native nonblocking sockets, as
503 windows sets sockets to nonblocking automatically
504 in certain operations. This way we make things work
505 the same on all platforms */
506 if (socket->priv->fd != -1)
507 set_fd_nonblocking (socket->priv->fd);
511 g_socket_get_property (GObject *object,
516 GSocket *socket = G_SOCKET (object);
517 GSocketAddress *address;
522 g_value_set_enum (value, socket->priv->family);
526 g_value_set_enum (value, socket->priv->type);
530 g_value_set_enum (value, socket->priv->protocol);
534 g_value_set_int (value, socket->priv->fd);
538 g_value_set_boolean (value, socket->priv->blocking);
541 case PROP_LISTEN_BACKLOG:
542 g_value_set_int (value, socket->priv->listen_backlog);
546 g_value_set_boolean (value, socket->priv->keepalive);
549 case PROP_LOCAL_ADDRESS:
550 address = g_socket_get_local_address (socket, NULL);
551 g_value_take_object (value, address);
554 case PROP_REMOTE_ADDRESS:
555 address = g_socket_get_remote_address (socket, NULL);
556 g_value_take_object (value, address);
560 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
565 g_socket_set_property (GObject *object,
570 GSocket *socket = G_SOCKET (object);
575 socket->priv->family = g_value_get_enum (value);
579 socket->priv->type = g_value_get_enum (value);
583 socket->priv->protocol = g_value_get_enum (value);
587 socket->priv->fd = g_value_get_int (value);
591 g_socket_set_blocking (socket, g_value_get_boolean (value));
594 case PROP_LISTEN_BACKLOG:
595 g_socket_set_listen_backlog (socket, g_value_get_int (value));
599 g_socket_set_keepalive (socket, g_value_get_boolean (value));
603 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
608 g_socket_finalize (GObject *object)
610 GSocket *socket = G_SOCKET (object);
612 g_clear_error (&socket->priv->construct_error);
614 if (socket->priv->fd != -1 &&
615 !socket->priv->closed)
616 g_socket_close (socket, NULL);
619 if (socket->priv->event != WSA_INVALID_EVENT)
621 WSACloseEvent (socket->priv->event);
622 socket->priv->event = WSA_INVALID_EVENT;
625 g_assert (socket->priv->requested_conditions == NULL);
628 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
629 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
633 g_socket_class_init (GSocketClass *klass)
635 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
638 /* Make sure winsock has been initialized */
639 type = g_inet_address_get_type ();
642 /* There is no portable, thread-safe way to avoid having the process
643 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
644 * forced to simply ignore the signal process-wide.
646 signal (SIGPIPE, SIG_IGN);
649 g_type_class_add_private (klass, sizeof (GSocketPrivate));
651 gobject_class->finalize = g_socket_finalize;
652 gobject_class->constructed = g_socket_constructed;
653 gobject_class->set_property = g_socket_set_property;
654 gobject_class->get_property = g_socket_get_property;
656 g_object_class_install_property (gobject_class, PROP_FAMILY,
657 g_param_spec_enum ("family",
659 P_("The sockets address family"),
660 G_TYPE_SOCKET_FAMILY,
661 G_SOCKET_FAMILY_INVALID,
662 G_PARAM_CONSTRUCT_ONLY |
664 G_PARAM_STATIC_STRINGS));
666 g_object_class_install_property (gobject_class, PROP_TYPE,
667 g_param_spec_enum ("type",
669 P_("The sockets type"),
671 G_SOCKET_TYPE_STREAM,
672 G_PARAM_CONSTRUCT_ONLY |
674 G_PARAM_STATIC_STRINGS));
676 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
677 g_param_spec_enum ("protocol",
678 P_("Socket protocol"),
679 P_("The id of the protocol to use, or -1 for unknown"),
680 G_TYPE_SOCKET_PROTOCOL,
681 G_SOCKET_PROTOCOL_UNKNOWN,
682 G_PARAM_CONSTRUCT_ONLY |
684 G_PARAM_STATIC_STRINGS));
686 g_object_class_install_property (gobject_class, PROP_FD,
687 g_param_spec_int ("fd",
688 P_("File descriptor"),
689 P_("The sockets file descriptor"),
693 G_PARAM_CONSTRUCT_ONLY |
695 G_PARAM_STATIC_STRINGS));
697 g_object_class_install_property (gobject_class, PROP_BLOCKING,
698 g_param_spec_boolean ("blocking",
700 P_("Whether or not I/O on this socket is blocking"),
703 G_PARAM_STATIC_STRINGS));
705 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
706 g_param_spec_int ("listen-backlog",
707 P_("Listen backlog"),
708 P_("Outstanding connections in the listen queue"),
713 G_PARAM_STATIC_STRINGS));
715 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
716 g_param_spec_boolean ("keepalive",
717 P_("Keep connection alive"),
718 P_("Keep connection alive by sending periodic pings"),
721 G_PARAM_STATIC_STRINGS));
723 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
724 g_param_spec_object ("local-address",
726 P_("The local address the socket is bound to"),
727 G_TYPE_SOCKET_ADDRESS,
729 G_PARAM_STATIC_STRINGS));
731 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
732 g_param_spec_object ("remote-address",
733 P_("Remote address"),
734 P_("The remote address the socket is connected to"),
735 G_TYPE_SOCKET_ADDRESS,
737 G_PARAM_STATIC_STRINGS));
741 g_socket_initable_iface_init (GInitableIface *iface)
743 iface->init = g_socket_initable_init;
747 g_socket_init (GSocket *socket)
749 socket->priv = G_TYPE_INSTANCE_GET_PRIVATE (socket, G_TYPE_SOCKET, GSocketPrivate);
751 socket->priv->fd = -1;
752 socket->priv->blocking = TRUE;
753 socket->priv->listen_backlog = 10;
754 socket->priv->construct_error = NULL;
756 socket->priv->event = WSA_INVALID_EVENT;
761 g_socket_initable_init (GInitable *initable,
762 GCancellable *cancellable,
767 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
769 socket = G_SOCKET (initable);
771 if (cancellable != NULL)
773 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
774 _("Cancellable initialization not supported"));
778 socket->priv->inited = TRUE;
780 if (socket->priv->construct_error)
783 *error = g_error_copy (socket->priv->construct_error);
793 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
794 * @type: the socket type to use.
795 * @protocol: the id of the protocol to use, or 0 for default.
796 * @error: #GError for error reporting, or %NULL to ignore.
798 * Creates a new #GSocket with the defined family, type and protocol.
799 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
800 * for the family and type is used.
802 * The @protocol is a family and type specific int that specifies what
803 * kind of protocol to use. #GSocketProtocol lists several common ones.
804 * Many families only support one protocol, and use 0 for this, others
805 * support several and using 0 means to use the default protocol for
806 * the family and type.
808 * The protocol id is passed directly to the operating
809 * system, so you can use protocols not listed in #GSocketProtocol if you
810 * know the protocol number used for it.
812 * Returns: a #GSocket or %NULL on error.
813 * Free the returned object with g_object_unref().
818 g_socket_new (GSocketFamily family,
820 GSocketProtocol protocol,
823 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
827 "protocol", protocol,
832 * g_socket_new_from_fd:
833 * @fd: a native socket file descriptor.
834 * @error: #GError for error reporting, or %NULL to ignore.
836 * Creates a new #GSocket from a native file descriptor
837 * or winsock SOCKET handle.
839 * This reads all the settings from the file descriptor so that
840 * all properties should work. Note that the file descriptor
841 * will be set to non-blocking mode, independent on the blocking
842 * mode of the #GSocket.
844 * Returns: a #GSocket or %NULL on error.
845 * Free the returned object with g_object_unref().
850 g_socket_new_from_fd (gint fd,
853 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
860 * g_socket_set_blocking:
861 * @socket: a #GSocket.
862 * @blocking: Whether to use blocking I/O or not.
864 * Sets the blocking mode of the socket. In blocking mode
865 * all operations block until they succeed or there is an error. In
866 * non-blocking mode all functions return results immediately or
867 * with a %G_IO_ERROR_WOULD_BLOCK error.
869 * All sockets are created in blocking mode. However, note that the
870 * platform level socket is always non-blocking, and blocking mode
871 * is a GSocket level feature.
876 g_socket_set_blocking (GSocket *socket,
879 g_return_if_fail (G_IS_SOCKET (socket));
881 blocking = !!blocking;
883 if (socket->priv->blocking == blocking)
886 socket->priv->blocking = blocking;
887 g_object_notify (G_OBJECT (socket), "blocking");
891 * g_socket_get_blocking:
892 * @socket: a #GSocket.
894 * Gets the blocking mode of the socket. For details on blocking I/O,
895 * see g_socket_set_blocking().
897 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
902 g_socket_get_blocking (GSocket *socket)
904 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
906 return socket->priv->blocking;
910 * g_socket_set_keepalive:
911 * @socket: a #GSocket.
912 * @keepalive: Value for the keepalive flag
914 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
915 * this flag is set on a socket, the system will attempt to verify that the
916 * remote socket endpoint is still present if a sufficiently long period of
917 * time passes with no data being exchanged. If the system is unable to
918 * verify the presence of the remote endpoint, it will automatically close
921 * This option is only functional on certain kinds of sockets. (Notably,
922 * %G_SOCKET_PROTOCOL_TCP sockets.)
924 * The exact time between pings is system- and protocol-dependent, but will
925 * normally be at least two hours. Most commonly, you would set this flag
926 * on a server socket if you want to allow clients to remain idle for long
927 * periods of time, but also want to ensure that connections are eventually
928 * garbage-collected if clients crash or become unreachable.
933 g_socket_set_keepalive (GSocket *socket,
938 g_return_if_fail (G_IS_SOCKET (socket));
940 keepalive = !!keepalive;
941 if (socket->priv->keepalive == keepalive)
944 value = (gint) keepalive;
945 if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_KEEPALIVE,
946 (gpointer) &value, sizeof (value)) < 0)
948 int errsv = get_socket_errno ();
949 g_warning ("error setting keepalive: %s", socket_strerror (errsv));
953 socket->priv->keepalive = keepalive;
954 g_object_notify (G_OBJECT (socket), "keepalive");
958 * g_socket_get_keepalive:
959 * @socket: a #GSocket.
961 * Gets the keepalive mode of the socket. For details on this,
962 * see g_socket_set_keepalive().
964 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
969 g_socket_get_keepalive (GSocket *socket)
971 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
973 return socket->priv->keepalive;
977 * g_socket_get_listen_backlog:
978 * @socket: a #GSocket.
980 * Gets the listen backlog setting of the socket. For details on this,
981 * see g_socket_set_listen_backlog().
983 * Returns: the maximum number of pending connections.
988 g_socket_get_listen_backlog (GSocket *socket)
990 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
992 return socket->priv->listen_backlog;
996 * g_socket_set_listen_backlog:
997 * @socket: a #GSocket.
998 * @backlog: the maximum number of pending connections.
1000 * Sets the maximum number of outstanding connections allowed
1001 * when listening on this socket. If more clients than this are
1002 * connecting to the socket and the application is not handling them
1003 * on time then the new connections will be refused.
1005 * Note that this must be called before g_socket_listen() and has no
1006 * effect if called after that.
1011 g_socket_set_listen_backlog (GSocket *socket,
1014 g_return_if_fail (G_IS_SOCKET (socket));
1015 g_return_if_fail (!socket->priv->listening);
1017 if (backlog != socket->priv->listen_backlog)
1019 socket->priv->listen_backlog = backlog;
1020 g_object_notify (G_OBJECT (socket), "listen-backlog");
1025 * g_socket_get_family:
1026 * @socket: a #GSocket.
1028 * Gets the socket family of the socket.
1030 * Returns: a #GSocketFamily
1035 g_socket_get_family (GSocket *socket)
1037 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1039 return socket->priv->family;
1043 * g_socket_get_socket_type:
1044 * @socket: a #GSocket.
1046 * Gets the socket type of the socket.
1048 * Returns: a #GSocketType
1053 g_socket_get_socket_type (GSocket *socket)
1055 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1057 return socket->priv->type;
1061 * g_socket_get_protocol:
1062 * @socket: a #GSocket.
1064 * Gets the socket protocol id the socket was created with.
1065 * In case the protocol is unknown, -1 is returned.
1067 * Returns: a protocol id, or -1 if unknown
1072 g_socket_get_protocol (GSocket *socket)
1074 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1076 return socket->priv->protocol;
1081 * @socket: a #GSocket.
1083 * Returns the underlying OS socket object. On unix this
1084 * is a socket file descriptor, and on windows this is
1085 * a Winsock2 SOCKET handle. This may be useful for
1086 * doing platform specific or otherwise unusual operations
1089 * Returns: the file descriptor of the socket.
1094 g_socket_get_fd (GSocket *socket)
1096 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1098 return socket->priv->fd;
1102 * g_socket_get_local_address:
1103 * @socket: a #GSocket.
1104 * @error: #GError for error reporting, or %NULL to ignore.
1106 * Try to get the local address of a bound socket. This is only
1107 * useful if the socket has been bound to a local address,
1108 * either explicitly or implicitly when connecting.
1110 * Returns: a #GSocketAddress or %NULL on error.
1111 * Free the returned object with g_object_unref().
1116 g_socket_get_local_address (GSocket *socket,
1119 struct sockaddr_storage buffer;
1120 guint32 len = sizeof (buffer);
1122 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1124 if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1126 int errsv = get_socket_errno ();
1127 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1128 _("could not get local address: %s"), socket_strerror (errsv));
1132 return g_socket_address_new_from_native (&buffer, len);
1136 * g_socket_get_remote_address:
1137 * @socket: a #GSocket.
1138 * @error: #GError for error reporting, or %NULL to ignore.
1140 * Try to get the remove address of a connected socket. This is only
1141 * useful for connection oriented sockets that have been connected.
1143 * Returns: a #GSocketAddress or %NULL on error.
1144 * Free the returned object with g_object_unref().
1149 g_socket_get_remote_address (GSocket *socket,
1152 struct sockaddr_storage buffer;
1153 guint32 len = sizeof (buffer);
1155 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1157 if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1159 int errsv = get_socket_errno ();
1160 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1161 _("could not get remote address: %s"), socket_strerror (errsv));
1165 return g_socket_address_new_from_native (&buffer, len);
1169 * g_socket_is_connected:
1170 * @socket: a #GSocket.
1172 * Check whether the socket is connected. This is only useful for
1173 * connection-oriented sockets.
1175 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1180 g_socket_is_connected (GSocket *socket)
1182 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1184 return socket->priv->connected;
1189 * @socket: a #GSocket.
1190 * @error: #GError for error reporting, or %NULL to ignore.
1192 * Marks the socket as a server socket, i.e. a socket that is used
1193 * to accept incoming requests using g_socket_accept().
1195 * Before calling this the socket must be bound to a local address using
1198 * To set the maximum amount of outstanding clients, use
1199 * g_socket_set_listen_backlog().
1201 * Returns: %TRUE on success, %FALSE on error.
1206 g_socket_listen (GSocket *socket,
1209 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1211 if (!check_socket (socket, error))
1214 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1216 int errsv = get_socket_errno ();
1218 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1219 _("could not listen: %s"), socket_strerror (errsv));
1223 socket->priv->listening = TRUE;
1230 * @socket: a #GSocket.
1231 * @address: a #GSocketAddress specifying the local address.
1232 * @allow_reuse: whether to allow reusing this address
1233 * @error: #GError for error reporting, or %NULL to ignore.
1235 * When a socket is created it is attached to an address family, but it
1236 * doesn't have an address in this family. g_socket_bind() assigns the
1237 * address (sometimes called name) of the socket.
1239 * It is generally required to bind to a local address before you can
1240 * receive connections. (See g_socket_listen() and g_socket_accept() ).
1241 * In certain situations, you may also want to bind a socket that will be
1242 * used to initiate connections, though this is not normally required.
1244 * @allow_reuse should be %TRUE for server sockets (sockets that you will
1245 * eventually call g_socket_accept() on), and %FALSE for client sockets.
1246 * (Specifically, if it is %TRUE, then g_socket_bind() will set the
1247 * %SO_REUSEADDR flag on the socket, allowing it to bind @address even if
1248 * that address was previously used by another socket that has not yet been
1249 * fully cleaned-up by the kernel. Failing to set this flag on a server
1250 * socket may cause the bind call to return %G_IO_ERROR_ADDRESS_IN_USE if
1251 * the server program is stopped and then immediately restarted.)
1253 * Returns: %TRUE on success, %FALSE on error.
1258 g_socket_bind (GSocket *socket,
1259 GSocketAddress *address,
1260 gboolean reuse_address,
1263 struct sockaddr_storage addr;
1265 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1267 if (!check_socket (socket, error))
1270 /* SO_REUSEADDR on windows means something else and is not what we want.
1271 It always allows the unix variant of SO_REUSEADDR anyway */
1276 value = (int) !!reuse_address;
1277 /* Ignore errors here, the only likely error is "not supported", and
1278 this is a "best effort" thing mainly */
1279 setsockopt (socket->priv->fd, SOL_SOCKET, SO_REUSEADDR,
1280 (gpointer) &value, sizeof (value));
1284 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1287 if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1288 g_socket_address_get_native_size (address)) < 0)
1290 int errsv = get_socket_errno ();
1292 G_IO_ERROR, socket_io_error_from_errno (errsv),
1293 _("Error binding to address: %s"), socket_strerror (errsv));
1301 * g_socket_speaks_ipv4:
1302 * @socket: a #GSocket
1304 * Checks if a socket is capable of speaking IPv4.
1306 * IPv4 sockets are capable of speaking IPv4. On some operating systems
1307 * and under some combinations of circumstances IPv6 sockets are also
1308 * capable of speaking IPv4. See RFC 3493 section 3.7 for more
1311 * No other types of sockets are currently considered as being capable
1314 * Returns: %TRUE if this socket can be used with IPv4.
1319 g_socket_speaks_ipv4 (GSocket *socket)
1321 switch (socket->priv->family)
1323 case G_SOCKET_FAMILY_IPV4:
1326 case G_SOCKET_FAMILY_IPV6:
1327 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
1329 guint sizeof_int = sizeof (int);
1332 if (getsockopt (socket->priv->fd,
1333 IPPROTO_IPV6, IPV6_V6ONLY,
1334 &v6_only, &sizeof_int) != 0)
1350 * @socket: a #GSocket.
1351 * @cancellable: a %GCancellable or %NULL
1352 * @error: #GError for error reporting, or %NULL to ignore.
1354 * Accept incoming connections on a connection-based socket. This removes
1355 * the first outstanding connection request from the listening socket and
1356 * creates a #GSocket object for it.
1358 * The @socket must be bound to a local address with g_socket_bind() and
1359 * must be listening for incoming connections (g_socket_listen()).
1361 * If there are no outstanding connections then the operation will block
1362 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
1363 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
1365 * Returns: a new #GSocket, or %NULL on error.
1366 * Free the returned object with g_object_unref().
1371 g_socket_accept (GSocket *socket,
1372 GCancellable *cancellable,
1375 GSocket *new_socket;
1378 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1380 if (!check_socket (socket, error))
1385 if (socket->priv->blocking &&
1386 !g_socket_condition_wait (socket,
1387 G_IO_IN, cancellable, error))
1390 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
1392 int errsv = get_socket_errno ();
1394 win32_unset_event_mask (socket, FD_ACCEPT);
1399 if (socket->priv->blocking)
1401 #ifdef WSAEWOULDBLOCK
1402 if (errsv == WSAEWOULDBLOCK)
1405 if (errsv == EWOULDBLOCK ||
1411 g_set_error (error, G_IO_ERROR,
1412 socket_io_error_from_errno (errsv),
1413 _("Error accepting connection: %s"), socket_strerror (errsv));
1419 win32_unset_event_mask (socket, FD_ACCEPT);
1423 /* The socket inherits the accepting sockets event mask and even object,
1424 we need to remove that */
1425 WSAEventSelect (ret, NULL, 0);
1431 /* We always want to set close-on-exec to protect users. If you
1432 need to so some weird inheritance to exec you can re-enable this
1433 using lower level hacks with g_socket_get_fd(). */
1434 flags = fcntl (ret, F_GETFD, 0);
1436 (flags & FD_CLOEXEC) == 0)
1438 flags |= FD_CLOEXEC;
1439 fcntl (ret, F_SETFD, flags);
1444 new_socket = g_socket_new_from_fd (ret, error);
1445 if (new_socket == NULL)
1454 new_socket->priv->protocol = socket->priv->protocol;
1461 * @socket: a #GSocket.
1462 * @address: a #GSocketAddress specifying the remote address.
1463 * @cancellable: a %GCancellable or %NULL
1464 * @error: #GError for error reporting, or %NULL to ignore.
1466 * Connect the socket to the specified remote address.
1468 * For connection oriented socket this generally means we attempt to make
1469 * a connection to the @address. For a connection-less socket it sets
1470 * the default address for g_socket_send() and discards all incoming datagrams
1471 * from other sources.
1473 * Generally connection oriented sockets can only connect once, but
1474 * connection-less sockets can connect multiple times to change the
1477 * If the connect call needs to do network I/O it will block, unless
1478 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
1479 * and the user can be notified of the connection finishing by waiting
1480 * for the G_IO_OUT condition. The result of the connection can then be
1481 * checked with g_socket_check_connect_result().
1483 * Returns: %TRUE if connected, %FALSE on error.
1488 g_socket_connect (GSocket *socket,
1489 GSocketAddress *address,
1490 GCancellable *cancellable,
1493 struct sockaddr_storage buffer;
1495 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1497 if (!check_socket (socket, error))
1500 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
1505 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
1506 g_socket_address_get_native_size (address)) < 0)
1508 int errsv = get_socket_errno ();
1514 if (errsv == EINPROGRESS)
1516 if (errsv == WSAEWOULDBLOCK)
1519 if (socket->priv->blocking)
1521 if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
1523 if (g_socket_check_connect_result (socket, error))
1526 g_prefix_error (error, _("Error connecting: "));
1529 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
1530 _("Connection in progress"));
1533 g_set_error (error, G_IO_ERROR,
1534 socket_io_error_from_errno (errsv),
1535 _("Error connecting: %s"), socket_strerror (errsv));
1542 win32_unset_event_mask (socket, FD_CONNECT);
1544 socket->priv->connected = TRUE;
1550 * g_socket_check_connect_result:
1551 * @socket: a #GSocket
1552 * @error: #GError for error reporting, or %NULL to ignore.
1554 * Checks and resets the pending connect error for the socket.
1555 * This is used to check for errors when g_socket_connect() is
1556 * used in non-blocking mode.
1558 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
1563 g_socket_check_connect_result (GSocket *socket,
1569 optlen = sizeof (value);
1570 if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
1572 int errsv = get_socket_errno ();
1574 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1575 _("Unable to get pending error: %s"), socket_strerror (errsv));
1581 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
1582 socket_strerror (value));
1590 * @socket: a #GSocket
1591 * @buffer: a buffer to read data into (which should be at least @size
1593 * @size: the number of bytes you want to read from the socket
1594 * @cancellable: a %GCancellable or %NULL
1595 * @error: #GError for error reporting, or %NULL to ignore.
1597 * Receive data (up to @size bytes) from a socket. This is mainly used by
1598 * connection-oriented sockets; it is identical to g_socket_receive_from()
1599 * with @address set to %NULL.
1601 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
1602 * g_socket_receive() will always read either 0 or 1 complete messages from
1603 * the socket. If the received message is too large to fit in @buffer, then
1604 * the data beyond @size bytes will be discarded, without any explicit
1605 * indication that this has occurred.
1607 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
1608 * number of bytes, up to @size. If more than @size bytes have been
1609 * received, the additional data will be returned in future calls to
1610 * g_socket_receive().
1612 * If the socket is in blocking mode the call will block until there is
1613 * some data to receive or there is an error. If there is no data available
1614 * and the socket is in non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error
1615 * will be returned. To be notified when data is available, wait for the
1616 * %G_IO_IN condition.
1618 * On error -1 is returned and @error is set accordingly.
1620 * Returns: Number of bytes read, or -1 on error
1625 g_socket_receive (GSocket *socket,
1628 GCancellable *cancellable,
1633 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1635 if (!check_socket (socket, error))
1638 if (g_cancellable_set_error_if_cancelled (cancellable, error))
1643 if (socket->priv->blocking &&
1644 !g_socket_condition_wait (socket,
1645 G_IO_IN, cancellable, error))
1648 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
1650 int errsv = get_socket_errno ();
1655 if (socket->priv->blocking)
1657 #ifdef WSAEWOULDBLOCK
1658 if (errsv == WSAEWOULDBLOCK)
1661 if (errsv == EWOULDBLOCK ||
1667 win32_unset_event_mask (socket, FD_READ);
1669 g_set_error (error, G_IO_ERROR,
1670 socket_io_error_from_errno (errsv),
1671 _("Error receiving data: %s"), socket_strerror (errsv));
1675 win32_unset_event_mask (socket, FD_READ);
1684 * g_socket_receive_from:
1685 * @socket: a #GSocket
1686 * @address: a pointer to a #GSocketAddress pointer, or %NULL
1687 * @buffer: a buffer to read data into (which should be at least @size
1689 * @size: the number of bytes you want to read from the socket
1690 * @cancellable: a %GCancellable or %NULL
1691 * @error: #GError for error reporting, or %NULL to ignore.
1693 * Receive data (up to @size bytes) from a socket.
1695 * If @address is non-%NULL then @address will be set equal to the
1696 * source address of the received packet.
1697 * @address is owned by the caller.
1699 * See g_socket_receive() for additional information.
1701 * Returns: Number of bytes read, or -1 on error
1706 g_socket_receive_from (GSocket *socket,
1707 GSocketAddress **address,
1710 GCancellable *cancellable,
1718 return g_socket_receive_message (socket,
1726 /* Although we ignore SIGPIPE, gdb will still stop if the app receives
1727 * one, which can be confusing and annoying. So if possible, we want
1728 * to suppress the signal entirely.
1731 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
1733 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
1738 * @socket: a #GSocket
1739 * @buffer: the buffer containing the data to send.
1740 * @size: the number of bytes to send
1741 * @cancellable: a %GCancellable or %NULL
1742 * @error: #GError for error reporting, or %NULL to ignore.
1744 * Tries to send @size bytes from @buffer on the socket. This is
1745 * mainly used by connection-oriented sockets; it is identical to
1746 * g_socket_send_to() with @address set to %NULL.
1748 * If the socket is in blocking mode the call will block until there is
1749 * space for the data in the socket queue. If there is no space available
1750 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1751 * will be returned. To be notified when space is available, wait for the
1752 * %G_IO_OUT condition. Note though that you may still receive
1753 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
1754 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
1755 * very common due to the way the underlying APIs work.)
1757 * On error -1 is returned and @error is set accordingly.
1759 * Returns: Number of bytes written (which may be less than @size), or -1
1765 g_socket_send (GSocket *socket,
1766 const gchar *buffer,
1768 GCancellable *cancellable,
1773 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1775 if (!check_socket (socket, error))
1778 if (g_cancellable_set_error_if_cancelled (cancellable, error))
1783 if (socket->priv->blocking &&
1784 !g_socket_condition_wait (socket,
1785 G_IO_OUT, cancellable, error))
1788 if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
1790 int errsv = get_socket_errno ();
1795 #ifdef WSAEWOULDBLOCK
1796 if (errsv == WSAEWOULDBLOCK)
1797 win32_unset_event_mask (socket, FD_WRITE);
1800 if (socket->priv->blocking)
1802 #ifdef WSAEWOULDBLOCK
1803 if (errsv == WSAEWOULDBLOCK)
1806 if (errsv == EWOULDBLOCK ||
1812 g_set_error (error, G_IO_ERROR,
1813 socket_io_error_from_errno (errsv),
1814 _("Error sending data: %s"), socket_strerror (errsv));
1825 * @socket: a #GSocket
1826 * @address: a #GSocketAddress, or %NULL
1827 * @buffer: the buffer containing the data to send.
1828 * @size: the number of bytes to send
1829 * @cancellable: a %GCancellable or %NULL
1830 * @error: #GError for error reporting, or %NULL to ignore.
1832 * Tries to send @size bytes from @buffer to @address. If @address is
1833 * %NULL then the message is sent to the default receiver (set by
1834 * g_socket_connect()).
1836 * See g_socket_send() for additional information.
1838 * Returns: Number of bytes written (which may be less than @size), or -1
1844 g_socket_send_to (GSocket *socket,
1845 GSocketAddress *address,
1846 const gchar *buffer,
1848 GCancellable *cancellable,
1856 return g_socket_send_message (socket,
1866 * g_socket_shutdown:
1867 * @socket: a #GSocket
1868 * @shutdown_read: whether to shut down the read side
1869 * @shutdown_write: whether to shut down the write side
1870 * @error: #GError for error reporting, or %NULL to ignore.
1872 * Shut down part of a full-duplex connection.
1874 * If @shutdown_read is %TRUE then the recieving side of the connection
1875 * is shut down, and further reading is disallowed.
1877 * If @shutdown_write is %TRUE then the sending side of the connection
1878 * is shut down, and further writing is disallowed.
1880 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
1882 * One example where this is used is graceful disconnect for TCP connections
1883 * where you close the sending side, then wait for the other side to close
1884 * the connection, thus ensuring that the other side saw all sent data.
1886 * Returns: %TRUE on success, %FALSE on error
1891 g_socket_shutdown (GSocket *socket,
1892 gboolean shutdown_read,
1893 gboolean shutdown_write,
1898 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
1900 if (!check_socket (socket, NULL))
1904 if (!shutdown_read && !shutdown_write)
1908 if (shutdown_read && shutdown_write)
1910 else if (shutdown_read)
1915 if (shutdown_read && shutdown_write)
1917 else if (shutdown_read)
1923 if (shutdown (socket->priv->fd, how) != 0)
1925 int errsv = get_socket_errno ();
1926 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1927 _("Unable to create socket: %s"), socket_strerror (errsv));
1931 if (shutdown_read && shutdown_write)
1932 socket->priv->connected = FALSE;
1939 * @socket: a #GSocket
1940 * @error: #GError for error reporting, or %NULL to ignore.
1942 * Closes the socket, shutting down any active connection.
1944 * Closing a socket does not wait for all outstanding I/O operations
1945 * to finish, so the caller should not rely on them to be guaranteed
1946 * to complete even if the close returns with no error.
1948 * Once the socket is closed, all other operations will return
1949 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
1952 * Sockets will be automatically closed when the last reference
1953 * is dropped, but you might want to call this function to make sure
1954 * resources are released as early as possible.
1956 * Beware that due to the way that TCP works, it is possible for
1957 * recently-sent data to be lost if either you close a socket while the
1958 * %G_IO_IN condition is set, or else if the remote connection tries to
1959 * send something to you after you close the socket but before it has
1960 * finished reading all of the data you sent. There is no easy generic
1961 * way to avoid this problem; the easiest fix is to design the network
1962 * protocol such that the client will never send data "out of turn".
1963 * Another solution is for the server to half-close the connection by
1964 * calling g_socket_shutdown() with only the @shutdown_write flag set,
1965 * and then wait for the client to notice this and close its side of the
1966 * connection, after which the server can safely call g_socket_close().
1967 * (This is what #GTcpConnection does if you call
1968 * g_tcp_connection_set_graceful_disconnect(). But of course, this
1969 * only works if the client will close its connection after the server
1972 * Returns: %TRUE on success, %FALSE on error
1977 g_socket_close (GSocket *socket,
1982 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
1984 if (socket->priv->closed)
1985 return TRUE; /* Multiple close not an error */
1987 if (!check_socket (socket, NULL))
1993 res = closesocket (socket->priv->fd);
1995 res = close (socket->priv->fd);
1999 int errsv = get_socket_errno ();
2004 g_set_error (error, G_IO_ERROR,
2005 socket_io_error_from_errno (errsv),
2006 _("Error closing socket: %s"),
2007 socket_strerror (errsv));
2013 socket->priv->connected = FALSE;
2014 socket->priv->closed = TRUE;
2020 * g_socket_is_closed:
2021 * @socket: a #GSocket
2023 * Checks whether a socket is closed.
2025 * Returns: %TRUE if socket is closed, %FALSE otherwise
2030 g_socket_is_closed (GSocket *socket)
2032 return socket->priv->closed;
2036 /* Broken source, used on errors */
2038 broken_prepare (GSource *source,
2045 broken_check (GSource *source)
2051 broken_dispatch (GSource *source,
2052 GSourceFunc callback,
2058 static GSourceFuncs broken_funcs =
2067 network_events_for_condition (GIOCondition condition)
2071 if (condition & G_IO_IN)
2072 event_mask |= (FD_READ | FD_ACCEPT);
2073 if (condition & G_IO_OUT)
2074 event_mask |= (FD_WRITE | FD_CONNECT);
2075 event_mask |= FD_CLOSE;
2081 ensure_event (GSocket *socket)
2083 if (socket->priv->event == WSA_INVALID_EVENT)
2084 socket->priv->event = WSACreateEvent();
2088 update_select_events (GSocket *socket)
2095 ensure_event (socket);
2098 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
2101 event_mask |= network_events_for_condition (*ptr);
2104 if (event_mask != socket->priv->selected_events)
2106 /* If no events selected, disable event so we can unset
2109 if (event_mask == 0)
2112 event = socket->priv->event;
2114 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
2115 socket->priv->selected_events = event_mask;
2120 add_condition_watch (GSocket *socket,
2121 GIOCondition *condition)
2123 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
2125 socket->priv->requested_conditions =
2126 g_list_prepend (socket->priv->requested_conditions, condition);
2128 update_select_events (socket);
2132 remove_condition_watch (GSocket *socket,
2133 GIOCondition *condition)
2135 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
2137 socket->priv->requested_conditions =
2138 g_list_remove (socket->priv->requested_conditions, condition);
2140 update_select_events (socket);
2144 update_condition (GSocket *socket)
2146 WSANETWORKEVENTS events;
2147 GIOCondition condition;
2149 if (WSAEnumNetworkEvents (socket->priv->fd,
2150 socket->priv->event,
2153 socket->priv->current_events |= events.lNetworkEvents;
2154 if (events.lNetworkEvents & FD_WRITE &&
2155 events.iErrorCode[FD_WRITE_BIT] != 0)
2156 socket->priv->current_errors |= FD_WRITE;
2157 if (events.lNetworkEvents & FD_CONNECT &&
2158 events.iErrorCode[FD_CONNECT_BIT] != 0)
2159 socket->priv->current_errors |= FD_CONNECT;
2163 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
2164 condition |= G_IO_IN;
2166 if (socket->priv->current_events & FD_CLOSE ||
2167 socket->priv->closed)
2168 condition |= G_IO_HUP;
2170 /* Never report both G_IO_OUT and HUP, these are
2171 mutually exclusive (can't write to a closed socket) */
2172 if ((condition & G_IO_HUP) == 0 &&
2173 socket->priv->current_events & FD_WRITE)
2175 if (socket->priv->current_errors & FD_WRITE)
2176 condition |= G_IO_ERR;
2178 condition |= G_IO_OUT;
2182 if (socket->priv->current_events & FD_CONNECT)
2184 if (socket->priv->current_errors & FD_CONNECT)
2185 condition |= (G_IO_HUP | G_IO_ERR);
2187 condition |= G_IO_OUT;
2199 GIOCondition condition;
2200 GCancellable *cancellable;
2201 GPollFD cancel_pollfd;
2205 socket_source_prepare (GSource *source,
2208 GSocketSource *socket_source = (GSocketSource *)source;
2211 socket_source->pollfd.revents = update_condition (socket_source->socket);
2215 if (g_cancellable_is_cancelled (socket_source->cancellable))
2218 if ((socket_source->condition & socket_source->pollfd.revents) != 0)
2225 socket_source_check (GSource *source)
2229 return socket_source_prepare (source, &timeout);
2233 socket_source_dispatch (GSource *source,
2234 GSourceFunc callback,
2237 GSocketSourceFunc func = (GSocketSourceFunc)callback;
2238 GSocketSource *socket_source = (GSocketSource *)source;
2240 return (*func) (socket_source->socket,
2241 socket_source->pollfd.revents & socket_source->condition,
2246 socket_source_finalize (GSource *source)
2248 GSocketSource *socket_source = (GSocketSource *)source;
2251 socket = socket_source->socket;
2254 remove_condition_watch (socket, &socket_source->condition);
2257 g_object_unref (socket);
2259 if (socket_source->cancellable)
2261 g_cancellable_release_fd (socket_source->cancellable);
2262 g_object_unref (socket_source->cancellable);
2266 static GSourceFuncs socket_source_funcs =
2268 socket_source_prepare,
2269 socket_source_check,
2270 socket_source_dispatch,
2271 socket_source_finalize
2275 socket_source_new (GSocket *socket,
2276 GIOCondition condition,
2277 GCancellable *cancellable)
2280 GSocketSource *socket_source;
2283 ensure_event (socket);
2285 if (socket->priv->event == WSA_INVALID_EVENT)
2287 g_warning ("Failed to create WSAEvent");
2288 return g_source_new (&broken_funcs, sizeof (GSource));
2292 condition |= G_IO_HUP | G_IO_ERR;
2294 source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
2295 socket_source = (GSocketSource *)source;
2297 socket_source->socket = g_object_ref (socket);
2298 socket_source->condition = condition;
2300 if (g_cancellable_make_pollfd (cancellable,
2301 &socket_source->cancel_pollfd))
2303 socket_source->cancellable = g_object_ref (cancellable);
2304 g_source_add_poll (source, &socket_source->cancel_pollfd);
2308 add_condition_watch (socket, &socket_source->condition);
2309 socket_source->pollfd.fd = (gintptr) socket->priv->event;
2311 socket_source->pollfd.fd = socket->priv->fd;
2314 socket_source->pollfd.events = condition;
2315 socket_source->pollfd.revents = 0;
2316 g_source_add_poll (source, &socket_source->pollfd);
2322 * g_socket_create_source:
2323 * @socket: a #GSocket
2324 * @condition: a #GIOCondition mask to monitor
2325 * @cancellable: a %GCancellable or %NULL
2327 * Creates a %GSource that can be attached to a %GMainContext to monitor
2328 * for the availibility of the specified @condition on the socket.
2330 * The callback on the source is of the #GSocketSourceFunc type.
2332 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
2333 * these conditions will always be reported output if they are true.
2335 * @cancellable if not %NULL can be used to cancel the source, which will
2336 * cause the source to trigger, reporting the current condition (which
2337 * is likely 0 unless cancellation happened at the same time as a
2338 * condition change). You can check for this in the callback using
2339 * g_cancellable_is_cancelled().
2341 * Returns: a newly allocated %GSource, free with g_source_unref().
2346 g_socket_create_source (GSocket *socket,
2347 GIOCondition condition,
2348 GCancellable *cancellable)
2350 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
2352 return socket_source_new (socket, condition, cancellable);
2356 * g_socket_condition_check:
2357 * @socket: a #GSocket
2358 * @condition: a #GIOCondition mask to check
2360 * Checks on the readiness of @socket to perform operations.
2361 * The operations specified in @condition are checked for and masked
2362 * against the currently-satisfied conditions on @socket. The result
2365 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2366 * these conditions will always be set in the output if they are true.
2368 * This call never blocks.
2370 * Returns: the @GIOCondition mask of the current state
2375 g_socket_condition_check (GSocket *socket,
2376 GIOCondition condition)
2378 if (!check_socket (socket, NULL))
2383 GIOCondition current_condition;
2385 condition |= G_IO_ERR | G_IO_HUP;
2387 add_condition_watch (socket, &condition);
2388 current_condition = update_condition (socket);
2389 remove_condition_watch (socket, &condition);
2390 return condition & current_condition;
2396 poll_fd.fd = socket->priv->fd;
2397 poll_fd.events = condition;
2400 result = g_poll (&poll_fd, 1, 0);
2401 while (result == -1 && get_socket_errno () == EINTR);
2403 return poll_fd.revents;
2409 * g_socket_condition_wait:
2410 * @socket: a #GSocket
2411 * @condition: a #GIOCondition mask to wait for
2412 * @cancellable: a #GCancellable, or %NULL
2413 * @error: a #GError pointer, or %NULL
2415 * Waits for @condition to become true on @socket. When the condition
2416 * is met, %TRUE is returned.
2418 * If @cancellable is cancelled before the condition is met then %FALSE
2419 * is returned and @error, if non-%NULL, is set to %G_IO_ERROR_CANCELLED.
2421 * Returns: %TRUE if the condition was met, %FALSE otherwise
2426 g_socket_condition_wait (GSocket *socket,
2427 GIOCondition condition,
2428 GCancellable *cancellable,
2431 if (!check_socket (socket, error))
2434 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2439 GIOCondition current_condition;
2445 /* Always check these */
2446 condition |= G_IO_ERR | G_IO_HUP;
2448 add_condition_watch (socket, &condition);
2451 events[num_events++] = socket->priv->event;
2453 if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
2454 events[num_events++] = (WSAEVENT)cancel_fd.fd;
2456 current_condition = update_condition (socket);
2457 while ((condition & current_condition) == 0)
2459 res = WSAWaitForMultipleEvents(num_events, events,
2460 FALSE, WSA_INFINITE, FALSE);
2461 if (res == WSA_WAIT_FAILED)
2463 int errsv = get_socket_errno ();
2465 g_set_error (error, G_IO_ERROR,
2466 socket_io_error_from_errno (errsv),
2467 _("Waiting for socket condition: %s"),
2468 socket_strerror (errsv));
2472 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2475 current_condition = update_condition (socket);
2477 remove_condition_watch (socket, &condition);
2479 g_cancellable_release_fd (cancellable);
2481 return (condition & current_condition) != 0;
2489 poll_fd[0].fd = socket->priv->fd;
2490 poll_fd[0].events = condition;
2493 if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
2497 result = g_poll (poll_fd, num, -1);
2498 while (result == -1 && get_socket_errno () == EINTR);
2501 g_cancellable_release_fd (cancellable);
2503 return cancellable == NULL ||
2504 !g_cancellable_set_error_if_cancelled (cancellable, error);
2510 * g_socket_send_message:
2511 * @socket: a #GSocket
2512 * @address: a #GSocketAddress, or %NULL
2513 * @vectors: an array of #GOutputVector structs
2514 * @num_vectors: the number of elements in @vectors, or -1
2515 * @messages: a pointer to an array of #GSocketControlMessages, or
2517 * @num_messages: number of elements in @messages, or -1.
2518 * @flags: an int containing #GSocketMsgFlags flags
2519 * @cancellable: a %GCancellable or %NULL
2520 * @error: #GError for error reporting, or %NULL to ignore.
2522 * Send data to @address on @socket. This is the most complicated and
2523 * fully-featured version of this call. For easier use, see
2524 * g_socket_send() and g_socket_send_to().
2526 * If @address is %NULL then the message is sent to the default receiver
2527 * (set by g_socket_connect()).
2529 * @vectors must point to an array of #GOutputVector structs and
2530 * @num_vectors must be the length of this array. (If @num_vectors is -1,
2531 * then @vectors is assumed to be terminated by a #GOutputVector with a
2532 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
2533 * that the sent data will be gathered from. Using multiple
2534 * #GOutputVector<!-- -->s is more memory-efficient than manually copying
2535 * data from multiple sources into a single buffer, and more
2536 * network-efficient than making multiple calls to g_socket_send().
2538 * @messages, if non-%NULL, is taken to point to an array of @num_messages
2539 * #GSocketControlMessage instances. These correspond to the control
2540 * messages to be sent on the socket.
2541 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
2544 * @flags modify how the message is sent. The commonly available arguments
2545 * for this are available in the #GSocketMsgFlags enum, but the
2546 * values there are the same as the system values, and the flags
2547 * are passed in as-is, so you can pass in system-specific flags too.
2549 * If the socket is in blocking mode the call will block until there is
2550 * space for the data in the socket queue. If there is no space available
2551 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2552 * will be returned. To be notified when space is available, wait for the
2553 * %G_IO_OUT condition. Note though that you may still receive
2554 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2555 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2556 * very common due to the way the underlying APIs work.)
2558 * On error -1 is returned and @error is set accordingly.
2560 * Returns: Number of bytes written (which may be less than @size), or -1
2566 g_socket_send_message (GSocket *socket,
2567 GSocketAddress *address,
2568 GOutputVector *vectors,
2570 GSocketControlMessage **messages,
2573 GCancellable *cancellable,
2576 GOutputVector one_vector;
2579 if (!check_socket (socket, error))
2582 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2585 if (num_vectors == -1)
2587 for (num_vectors = 0;
2588 vectors[num_vectors].buffer != NULL;
2593 if (num_messages == -1)
2595 for (num_messages = 0;
2596 messages != NULL && messages[num_messages] != NULL;
2601 if (num_vectors == 0)
2605 one_vector.buffer = &zero;
2606 one_vector.size = 1;
2608 vectors = &one_vector;
2619 msg.msg_namelen = g_socket_address_get_native_size (address);
2620 msg.msg_name = g_alloca (msg.msg_namelen);
2621 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
2626 msg.msg_name = NULL;
2627 msg.msg_namelen = 0;
2632 /* this entire expression will be evaluated at compile time */
2633 if (sizeof *msg.msg_iov == sizeof *vectors &&
2634 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2635 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2636 G_STRUCT_OFFSET (GOutputVector, buffer) &&
2637 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2638 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2639 G_STRUCT_OFFSET (GOutputVector, size))
2640 /* ABI is compatible */
2642 msg.msg_iov = (struct iovec *) vectors;
2643 msg.msg_iovlen = num_vectors;
2646 /* ABI is incompatible */
2650 msg.msg_iov = g_newa (struct iovec, num_vectors);
2651 for (i = 0; i < num_vectors; i++)
2653 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
2654 msg.msg_iov[i].iov_len = vectors[i].size;
2656 msg.msg_iovlen = num_vectors;
2662 struct cmsghdr *cmsg;
2665 msg.msg_controllen = 0;
2666 for (i = 0; i < num_messages; i++)
2667 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
2669 msg.msg_control = g_alloca (msg.msg_controllen);
2671 cmsg = CMSG_FIRSTHDR (&msg);
2672 for (i = 0; i < num_messages; i++)
2674 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
2675 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
2676 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
2677 g_socket_control_message_serialize (messages[i],
2679 cmsg = CMSG_NXTHDR (&msg, cmsg);
2681 g_assert (cmsg == NULL);
2686 if (socket->priv->blocking &&
2687 !g_socket_condition_wait (socket,
2688 G_IO_OUT, cancellable, error))
2691 result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
2694 int errsv = get_socket_errno ();
2699 if (socket->priv->blocking &&
2700 (errsv == EWOULDBLOCK ||
2704 g_set_error (error, G_IO_ERROR,
2705 socket_io_error_from_errno (errsv),
2706 _("Error sending message: %s"), socket_strerror (errsv));
2717 struct sockaddr_storage addr;
2724 /* Win32 doesn't support control messages.
2725 Actually this is possible for raw and datagram sockets
2726 via WSASendMessage on Vista or later, but that doesn't
2728 if (num_messages != 0)
2730 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2731 _("GSocketControlMessage not supported on windows"));
2736 bufs = g_newa (WSABUF, num_vectors);
2737 for (i = 0; i < num_vectors; i++)
2739 bufs[i].buf = (char *)vectors[i].buffer;
2740 bufs[i].len = (gulong)vectors[i].size;
2744 addrlen = 0; /* Avoid warning */
2747 addrlen = g_socket_address_get_native_size (address);
2748 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
2754 if (socket->priv->blocking &&
2755 !g_socket_condition_wait (socket,
2756 G_IO_OUT, cancellable, error))
2760 result = WSASendTo (socket->priv->fd,
2763 (const struct sockaddr *)&addr, addrlen,
2766 result = WSASend (socket->priv->fd,
2773 int errsv = get_socket_errno ();
2775 if (errsv == WSAEINTR)
2778 if (errsv == WSAEWOULDBLOCK)
2779 win32_unset_event_mask (socket, FD_WRITE);
2781 if (socket->priv->blocking &&
2782 errsv == WSAEWOULDBLOCK)
2785 g_set_error (error, G_IO_ERROR,
2786 socket_io_error_from_errno (errsv),
2787 _("Error sending message: %s"), socket_strerror (errsv));
2800 * g_socket_receive_message:
2801 * @socket: a #GSocket
2802 * @address: a pointer to a #GSocketAddress pointer, or %NULL
2803 * @vectors: an array of #GInputVector structs
2804 * @num_vectors: the number of elements in @vectors, or -1
2805 * @messages: a pointer which will be filled with an array of
2806 * #GSocketControlMessages, or %NULL
2807 * @num_messages: a pointer which will be filled with the number of
2808 * elements in @messages, or %NULL
2809 * @flags: a pointer to an int containing #GSocketMsgFlags flags
2810 * @cancellable: a %GCancellable or %NULL
2811 * @error: a #GError pointer, or %NULL
2813 * Receive data from a socket. This is the most complicated and
2814 * fully-featured version of this call. For easier use, see
2815 * g_socket_receive() and g_socket_receive_from().
2817 * If @address is non-%NULL then @address will be set equal to the
2818 * source address of the received packet.
2819 * @address is owned by the caller.
2821 * @vector must point to an array of #GInputVector structs and
2822 * @num_vectors must be the length of this array. These structs
2823 * describe the buffers that received data will be scattered into.
2824 * If @num_vectors is -1, then @vectors is assumed to be terminated
2825 * by a #GInputVector with a %NULL buffer pointer.
2827 * As a special case, if @num_vectors is 0 (in which case, @vectors
2828 * may of course be %NULL), then a single byte is received and
2829 * discarded. This is to facilitate the common practice of sending a
2830 * single '\0' byte for the purposes of transferring ancillary data.
2832 * @messages, if non-%NULL, will be set to point to a newly-allocated
2833 * array of #GSocketControlMessage instances. These correspond to the
2834 * control messages received from the kernel, one
2835 * #GSocketControlMessage per message from the kernel. This array is
2836 * %NULL-terminated and must be freed by the caller using g_free(). If
2837 * @messages is %NULL, any control messages received will be
2840 * @num_messages, if non-%NULL, will be set to the number of control
2841 * messages received.
2843 * If both @messages and @num_messages are non-%NULL, then
2844 * @num_messages gives the number of #GSocketControlMessage instances
2845 * in @messages (ie: not including the %NULL terminator).
2847 * @flags is an in/out parameter. The commonly available arguments
2848 * for this are available in the #GSocketMsgFlags enum, but the
2849 * values there are the same as the system values, and the flags
2850 * are passed in as-is, so you can pass in system-specific flags too
2851 * (and g_socket_receive_message() may pass system-specific flags out).
2853 * As with g_socket_receive(), data may be discarded if @socket is
2854 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
2855 * provide enough buffer space to read a complete message. You can pass
2856 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
2857 * removing it from the receive queue, but there is no portable way to find
2858 * out the length of the message other than by reading it into a
2859 * sufficiently-large buffer.
2861 * If the socket is in blocking mode the call will block until there
2862 * is some data to receive or there is an error. If there is no data
2863 * available and the socket is in non-blocking mode, a
2864 * %G_IO_ERROR_WOULD_BLOCK error will be returned. To be notified when
2865 * data is available, wait for the %G_IO_IN condition.
2867 * On error -1 is returned and @error is set accordingly.
2869 * Returns: Number of bytes read, or -1 on error
2874 g_socket_receive_message (GSocket *socket,
2875 GSocketAddress **address,
2876 GInputVector *vectors,
2878 GSocketControlMessage ***messages,
2881 GCancellable *cancellable,
2884 GInputVector one_vector;
2887 if (!check_socket (socket, error))
2890 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2893 if (num_vectors == -1)
2895 for (num_vectors = 0;
2896 vectors[num_vectors].buffer != NULL;
2901 if (num_vectors == 0)
2903 one_vector.buffer = &one_byte;
2904 one_vector.size = 1;
2906 vectors = &one_vector;
2913 struct sockaddr_storage one_sockaddr;
2918 msg.msg_name = &one_sockaddr;
2919 msg.msg_namelen = sizeof (struct sockaddr_storage);
2923 msg.msg_name = NULL;
2924 msg.msg_namelen = 0;
2928 /* this entire expression will be evaluated at compile time */
2929 if (sizeof *msg.msg_iov == sizeof *vectors &&
2930 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2931 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2932 G_STRUCT_OFFSET (GInputVector, buffer) &&
2933 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2934 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2935 G_STRUCT_OFFSET (GInputVector, size))
2936 /* ABI is compatible */
2938 msg.msg_iov = (struct iovec *) vectors;
2939 msg.msg_iovlen = num_vectors;
2942 /* ABI is incompatible */
2946 msg.msg_iov = g_newa (struct iovec, num_vectors);
2947 for (i = 0; i < num_vectors; i++)
2949 msg.msg_iov[i].iov_base = vectors[i].buffer;
2950 msg.msg_iov[i].iov_len = vectors[i].size;
2952 msg.msg_iovlen = num_vectors;
2956 msg.msg_control = g_alloca (2048);
2957 msg.msg_controllen = 2048;
2961 msg.msg_flags = *flags;
2968 if (socket->priv->blocking &&
2969 !g_socket_condition_wait (socket,
2970 G_IO_IN, cancellable, error))
2973 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
2977 int errsv = get_socket_errno ();
2982 if (socket->priv->blocking &&
2983 (errsv == EWOULDBLOCK ||
2987 g_set_error (error, G_IO_ERROR,
2988 socket_io_error_from_errno (errsv),
2989 _("Error receiving message: %s"), socket_strerror (errsv));
2996 /* decode address */
2997 if (address != NULL)
2999 if (msg.msg_namelen > 0)
3000 *address = g_socket_address_new_from_native (msg.msg_name,
3006 /* decode control messages */
3008 GSocketControlMessage **my_messages = NULL;
3009 gint allocated = 0, index = 0;
3010 const gchar *scm_pointer;
3011 struct cmsghdr *cmsg;
3014 scm_pointer = (const gchar *) msg.msg_control;
3015 scm_size = msg.msg_controllen;
3017 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
3019 GSocketControlMessage *message;
3021 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
3023 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
3025 if (message == NULL)
3026 /* We've already spewed about the problem in the
3027 deserialization code, so just continue */
3030 if (index == allocated)
3032 /* estimated 99% case: exactly 1 control message */
3033 allocated = MAX (allocated * 2, 1);
3034 my_messages = g_new (GSocketControlMessage *, (allocated + 1));
3037 my_messages[index++] = message;
3041 *num_messages = index;
3045 my_messages[index++] = NULL;
3046 *messages = my_messages;
3052 /* free all those messages we just constructed.
3053 * we have to do it this way if the user ignores the
3054 * messages so that we will close any received fds.
3056 for (i = 0; i < index; i++)
3057 g_object_unref (my_messages[i]);
3058 g_free (my_messages);
3062 /* capture the flags */
3064 *flags = msg.msg_flags;
3070 struct sockaddr_storage addr;
3072 DWORD bytes_received;
3079 bufs = g_newa (WSABUF, num_vectors);
3080 for (i = 0; i < num_vectors; i++)
3082 bufs[i].buf = (char *)vectors[i].buffer;
3083 bufs[i].len = (gulong)vectors[i].size;
3095 if (socket->priv->blocking &&
3096 !g_socket_condition_wait (socket,
3097 G_IO_IN, cancellable, error))
3100 addrlen = sizeof addr;
3102 result = WSARecvFrom (socket->priv->fd,
3104 &bytes_received, &win_flags,
3105 (struct sockaddr *)&addr, &addrlen,
3108 result = WSARecv (socket->priv->fd,
3110 &bytes_received, &win_flags,
3114 int errsv = get_socket_errno ();
3116 if (errsv == WSAEINTR)
3119 win32_unset_event_mask (socket, FD_READ);
3121 if (socket->priv->blocking &&
3122 errsv == WSAEWOULDBLOCK)
3125 g_set_error (error, G_IO_ERROR,
3126 socket_io_error_from_errno (errsv),
3127 _("Error receiving message: %s"), socket_strerror (errsv));
3131 win32_unset_event_mask (socket, FD_READ);
3135 /* decode address */
3136 if (address != NULL)
3139 *address = g_socket_address_new_from_native (&addr, addrlen);
3144 /* capture the flags */
3148 return bytes_received;
3153 #define __G_SOCKET_C__
3154 #include "gioaliasdef.c"