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>
42 #include "gcancellable.h"
43 #include "gioenumtypes.h"
44 #include "ginitable.h"
45 #include "gasynchelper.h"
49 #include "gnetworkingprivate.h"
56 * @short_description: Low-level socket object
58 * @see_also: #GInitable
60 * A #GSocket is a low-level networking primitive. It is a more or less
61 * direct mapping of the BSD socket API in a portable GObject based API.
62 * It supports both the UNIX socket implementations and winsock2 on Windows.
64 * #GSocket is the platform independent base upon which the higher level
65 * network primitives are based. Applications are not typically meant to
66 * use it directly, but rather through classes like #GSocketClient,
67 * #GSocketService and #GSocketConnection. However there may be cases where
68 * direct use of #GSocket is useful.
70 * #GSocket implements the #GInitable interface, so if it is manually constructed
71 * by e.g. g_object_new() you must call g_initable_init() and check the
72 * results before using the object. This is done automatically in
73 * g_socket_new() and g_socket_new_from_fd(), so these functions can return
76 * Sockets operate in two general modes, blocking or non-blocking. When
77 * in blocking mode all operations block until the requested operation
78 * is finished or there is an error. In non-blocking mode all calls that
79 * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
80 * To know when a call would successfully run you can call g_socket_condition_check(),
81 * or g_socket_condition_wait(). You can also use g_socket_create_source() and
82 * attach it to a #GMainContext to get callbacks when I/O is possible.
83 * Note that all sockets are always set to non blocking mode in the system, and
84 * blocking mode is emulated in GSocket.
86 * When working in non-blocking mode applications should always be able to
87 * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
88 * function said that I/O was possible. This can easily happen in case
89 * of a race condition in the application, but it can also happen for other
90 * reasons. For instance, on Windows a socket is always seen as writable
91 * until a write returns %G_IO_ERROR_WOULD_BLOCK.
93 * #GSocket<!-- -->s can be either connection oriented or datagram based.
94 * For connection oriented types you must first establish a connection by
95 * either connecting to an address or accepting a connection from another
96 * address. For connectionless socket types the target/source address is
97 * specified or received in each I/O operation.
99 * All socket file descriptors are set to be close-on-exec.
101 * Note that creating a #GSocket causes the signal %SIGPIPE to be
102 * ignored for the remainder of the program. If you are writing a
103 * command-line utility that uses #GSocket, you may need to take into
104 * account the fact that your program will not automatically be killed
105 * if it tries to write to %stdout after it has been closed.
110 static void g_socket_initable_iface_init (GInitableIface *iface);
111 static gboolean g_socket_initable_init (GInitable *initable,
112 GCancellable *cancellable,
115 G_DEFINE_TYPE_WITH_CODE (GSocket, g_socket, G_TYPE_OBJECT,
116 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
117 g_socket_initable_iface_init));
133 struct _GSocketPrivate
135 GSocketFamily family;
137 GSocketProtocol protocol;
140 GError *construct_error;
152 GList *requested_conditions; /* list of requested GIOCondition * */
157 get_socket_errno (void)
162 return WSAGetLastError ();
167 socket_io_error_from_errno (int err)
170 return g_io_error_from_errno (err);
175 return G_IO_ERROR_ADDRESS_IN_USE;
177 return G_IO_ERROR_WOULD_BLOCK;
179 return G_IO_ERROR_PERMISSION_DENIED;
180 case WSA_INVALID_HANDLE:
181 case WSA_INVALID_PARAMETER:
184 return G_IO_ERROR_INVALID_ARGUMENT;
185 case WSAEPROTONOSUPPORT:
186 return G_IO_ERROR_NOT_SUPPORTED;
188 return G_IO_ERROR_CANCELLED;
189 case WSAESOCKTNOSUPPORT:
191 case WSAEPFNOSUPPORT:
192 case WSAEAFNOSUPPORT:
193 return G_IO_ERROR_NOT_SUPPORTED;
195 return G_IO_ERROR_FAILED;
201 socket_strerror (int err)
204 return g_strerror (err);
206 static GStaticPrivate msg_private = G_STATIC_PRIVATE_INIT;
209 buf = g_static_private_get (&msg_private);
212 buf = g_new (gchar, 128);
213 g_static_private_set (&msg_private, buf, g_free);
216 msg = g_win32_error_message (err);
217 strncpy (buf, msg, 128);
224 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
226 _win32_unset_event_mask (GSocket *socket, int mask)
228 socket->priv->current_events &= ~mask;
229 socket->priv->current_errors &= ~mask;
232 #define win32_unset_event_mask(_socket, _mask)
236 set_fd_nonblocking (int fd)
245 if ((arg = fcntl (fd, F_GETFL, NULL)) < 0)
247 g_warning ("Error getting socket status flags: %s", socket_strerror (errno));
251 arg = arg | O_NONBLOCK;
253 if (fcntl (fd, F_SETFL, arg) < 0)
254 g_warning ("Error setting socket status flags: %s", socket_strerror (errno));
258 if (ioctlsocket (fd, FIONBIO, &arg) == SOCKET_ERROR)
260 int errsv = get_socket_errno ();
261 g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
267 check_socket (GSocket *socket,
270 if (!socket->priv->inited)
272 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
273 _("Invalid socket, not initialized"));
277 if (socket->priv->construct_error)
279 g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
280 _("Invalid socket, initialization failed due to: %s"),
281 socket->priv->construct_error->message);
285 if (socket->priv->closed)
287 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
288 _("Socket is already closed"));
295 g_socket_details_from_fd (GSocket *socket)
297 struct sockaddr_storage address;
309 fd = socket->priv->fd;
310 optlen = sizeof value;
311 if (getsockopt (fd, SOL_SOCKET, SO_TYPE, (void *)&value, &optlen) != 0)
313 errsv = get_socket_errno ();
324 /* programmer error */
325 g_error ("creating GSocket from fd %d: %s\n",
326 fd, socket_strerror (errsv));
334 g_assert (optlen == sizeof value);
338 socket->priv->type = G_SOCKET_TYPE_STREAM;
342 socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
346 socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
350 socket->priv->type = G_SOCKET_TYPE_INVALID;
354 addrlen = sizeof address;
355 if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
357 errsv = get_socket_errno ();
361 g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
362 sizeof address.ss_family <= addrlen);
363 switch (address.ss_family)
365 case G_SOCKET_FAMILY_IPV4:
366 case G_SOCKET_FAMILY_IPV6:
367 case G_SOCKET_FAMILY_UNIX:
368 socket->priv->family = address.ss_family;
372 socket->priv->family = G_SOCKET_FAMILY_INVALID;
376 if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
378 addrlen = sizeof address;
379 if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
380 socket->priv->connected = TRUE;
383 optlen = sizeof bool_val;
384 if (getsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
385 (void *)&bool_val, &optlen) == 0)
387 g_assert (optlen == sizeof bool_val);
388 socket->priv->keepalive = !!bool_val;
392 /* Can't read, maybe not supported, assume FALSE */
393 socket->priv->keepalive = FALSE;
399 g_set_error (&socket->priv->construct_error, G_IO_ERROR,
400 socket_io_error_from_errno (errsv),
401 _("creating GSocket from fd: %s"),
402 socket_strerror (errsv));
406 g_socket_create_socket (GSocketFamily family,
416 case G_SOCKET_TYPE_STREAM:
417 native_type = SOCK_STREAM;
420 case G_SOCKET_TYPE_DATAGRAM:
421 native_type = SOCK_DGRAM;
424 case G_SOCKET_TYPE_SEQPACKET:
425 native_type = SOCK_SEQPACKET;
429 g_assert_not_reached ();
434 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
435 _("Unable to create socket: %s"), _("Unknown protocol was specified"));
440 native_type |= SOCK_CLOEXEC;
442 fd = socket (family, native_type, protocol);
446 int errsv = get_socket_errno ();
448 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
449 _("Unable to create socket: %s"), socket_strerror (errsv));
456 /* We always want to set close-on-exec to protect users. If you
457 need to so some weird inheritance to exec you can re-enable this
458 using lower level hacks with g_socket_get_fd(). */
459 flags = fcntl (fd, F_GETFD, 0);
461 (flags & FD_CLOEXEC) == 0)
464 fcntl (fd, F_SETFD, flags);
473 g_socket_constructed (GObject *object)
475 GSocket *socket = G_SOCKET (object);
477 if (socket->priv->fd >= 0)
478 /* create socket->priv info from the fd */
479 g_socket_details_from_fd (socket);
482 /* create the fd from socket->priv info */
483 socket->priv->fd = g_socket_create_socket (socket->priv->family,
485 socket->priv->protocol,
486 &socket->priv->construct_error);
488 /* Always use native nonblocking sockets, as
489 windows sets sockets to nonblocking automatically
490 in certain operations. This way we make things work
491 the same on all platforms */
492 if (socket->priv->fd != -1)
493 set_fd_nonblocking (socket->priv->fd);
497 g_socket_get_property (GObject *object,
502 GSocket *socket = G_SOCKET (object);
503 GSocketAddress *address;
508 g_value_set_enum (value, socket->priv->family);
512 g_value_set_enum (value, socket->priv->type);
516 g_value_set_enum (value, socket->priv->protocol);
520 g_value_set_int (value, socket->priv->fd);
524 g_value_set_boolean (value, socket->priv->blocking);
527 case PROP_LISTEN_BACKLOG:
528 g_value_set_int (value, socket->priv->listen_backlog);
532 g_value_set_boolean (value, socket->priv->keepalive);
535 case PROP_LOCAL_ADDRESS:
536 address = g_socket_get_local_address (socket, NULL);
537 g_value_take_object (value, address);
540 case PROP_REMOTE_ADDRESS:
541 address = g_socket_get_remote_address (socket, NULL);
542 g_value_take_object (value, address);
546 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
551 g_socket_set_property (GObject *object,
556 GSocket *socket = G_SOCKET (object);
561 socket->priv->family = g_value_get_enum (value);
565 socket->priv->type = g_value_get_enum (value);
569 socket->priv->protocol = g_value_get_enum (value);
573 socket->priv->fd = g_value_get_int (value);
577 g_socket_set_blocking (socket, g_value_get_boolean (value));
580 case PROP_LISTEN_BACKLOG:
581 g_socket_set_listen_backlog (socket, g_value_get_int (value));
585 g_socket_set_keepalive (socket, g_value_get_boolean (value));
589 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
594 g_socket_finalize (GObject *object)
596 GSocket *socket = G_SOCKET (object);
598 g_clear_error (&socket->priv->construct_error);
600 if (socket->priv->fd != -1 &&
601 !socket->priv->closed)
602 g_socket_close (socket, NULL);
605 g_assert (socket->priv->requested_conditions == NULL);
608 if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
609 (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
613 g_socket_class_init (GSocketClass *klass)
615 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
618 /* Make sure winsock has been initialized */
619 type = g_inet_address_get_type ();
622 /* There is no portable, thread-safe way to avoid having the process
623 * be killed by SIGPIPE when calling send() or sendmsg(), so we are
624 * forced to simply ignore the signal process-wide.
626 signal (SIGPIPE, SIG_IGN);
629 g_type_class_add_private (klass, sizeof (GSocketPrivate));
631 gobject_class->finalize = g_socket_finalize;
632 gobject_class->constructed = g_socket_constructed;
633 gobject_class->set_property = g_socket_set_property;
634 gobject_class->get_property = g_socket_get_property;
636 g_object_class_install_property (gobject_class, PROP_FAMILY,
637 g_param_spec_enum ("family",
639 P_("The sockets address family"),
640 G_TYPE_SOCKET_FAMILY,
641 G_SOCKET_FAMILY_INVALID,
642 G_PARAM_CONSTRUCT_ONLY |
644 G_PARAM_STATIC_STRINGS));
646 g_object_class_install_property (gobject_class, PROP_TYPE,
647 g_param_spec_enum ("type",
649 P_("The sockets type"),
651 G_SOCKET_TYPE_STREAM,
652 G_PARAM_CONSTRUCT_ONLY |
654 G_PARAM_STATIC_STRINGS));
656 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
657 g_param_spec_enum ("protocol",
658 P_("Socket protocol"),
659 P_("The id of the protocol to use, or -1 for unknown"),
660 G_TYPE_SOCKET_PROTOCOL,
661 G_SOCKET_PROTOCOL_UNKNOWN,
662 G_PARAM_CONSTRUCT_ONLY |
664 G_PARAM_STATIC_STRINGS));
666 g_object_class_install_property (gobject_class, PROP_FD,
667 g_param_spec_int ("fd",
668 P_("File descriptor"),
669 P_("The sockets file descriptor"),
673 G_PARAM_CONSTRUCT_ONLY |
675 G_PARAM_STATIC_STRINGS));
677 g_object_class_install_property (gobject_class, PROP_BLOCKING,
678 g_param_spec_boolean ("blocking",
680 P_("Whether or not I/O on this socket is blocking"),
683 G_PARAM_STATIC_STRINGS));
685 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
686 g_param_spec_int ("listen-backlog",
687 P_("Listen backlog"),
688 P_("Outstanding connections in the listen queue"),
693 G_PARAM_STATIC_STRINGS));
695 g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
696 g_param_spec_boolean ("keepalive",
697 P_("Keep connection alive"),
698 P_("Keep connection alive by sending periodic pings"),
701 G_PARAM_STATIC_STRINGS));
703 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
704 g_param_spec_object ("local-address",
706 P_("The local address the socket is bound to"),
707 G_TYPE_SOCKET_ADDRESS,
709 G_PARAM_STATIC_STRINGS));
711 g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
712 g_param_spec_object ("remote-address",
713 P_("Remote address"),
714 P_("The remote address the socket is connected to"),
715 G_TYPE_SOCKET_ADDRESS,
717 G_PARAM_STATIC_STRINGS));
721 g_socket_initable_iface_init (GInitableIface *iface)
723 iface->init = g_socket_initable_init;
727 g_socket_init (GSocket *socket)
729 socket->priv = G_TYPE_INSTANCE_GET_PRIVATE (socket, G_TYPE_SOCKET, GSocketPrivate);
731 socket->priv->fd = -1;
732 socket->priv->blocking = TRUE;
733 socket->priv->listen_backlog = 10;
734 socket->priv->construct_error = NULL;
736 socket->priv->event = WSA_INVALID_EVENT;
741 g_socket_initable_init (GInitable *initable,
742 GCancellable *cancellable,
747 g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
749 socket = G_SOCKET (initable);
751 if (cancellable != NULL)
753 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
754 _("Cancellable initialization not supported"));
758 socket->priv->inited = TRUE;
760 if (socket->priv->construct_error)
763 *error = g_error_copy (socket->priv->construct_error);
773 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
774 * @type: the socket type to use.
775 * @protocol: the id of the protocol to use, or 0 for default.
776 * @error: #GError for error reporting, or %NULL to ignore.
778 * Creates a new #GSocket with the defined family, type and protocol.
779 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
780 * for the family and type is used.
782 * The @protocol is a family and type specific int that specifies what
783 * kind of protocol to use. #GSocketProtocol lists several common ones.
784 * Many families only support one protocol, and use 0 for this, others
785 * support several and using 0 means to use the default protocol for
786 * the family and type.
788 * The protocol id is passed directly to the operating
789 * system, so you can use protocols not listed in #GSocketProtocol if you
790 * know the protocol number used for it.
792 * Returns: a #GSocket or %NULL on error.
793 * Free the returned object with g_object_unref().
798 g_socket_new (GSocketFamily family,
800 GSocketProtocol protocol,
803 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
807 "protocol", protocol,
812 * g_socket_new_from_fd:
813 * @fd: a native socket file descriptor.
814 * @error: #GError for error reporting, or %NULL to ignore.
816 * Creates a new #GSocket from a native file descriptor
817 * or winsock SOCKET handle.
819 * This reads all the settings from the file descriptor so that
820 * all properties should work. Note that the file descriptor
821 * will be set to non-blocking mode, independent on the blocking
822 * mode of the #GSocket.
824 * Returns: a #GSocket or %NULL on error.
825 * Free the returned object with g_object_unref().
830 g_socket_new_from_fd (gint fd,
833 return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
840 * g_socket_set_blocking:
841 * @socket: a #GSocket.
842 * @blocking: Whether to use blocking I/O or not.
844 * Sets the blocking mode of the socket. In blocking mode
845 * all operations block until they succeed or there is an error. In
846 * non-blocking mode all functions return results immediately or
847 * with a %G_IO_ERROR_WOULD_BLOCK error.
849 * All sockets are created in blocking mode. However, note that the
850 * platform level socket is always non-blocking, and blocking mode
851 * is a GSocket level feature.
856 g_socket_set_blocking (GSocket *socket,
859 g_return_if_fail (G_IS_SOCKET (socket));
861 blocking = !!blocking;
863 if (socket->priv->blocking == blocking)
866 socket->priv->blocking = blocking;
867 g_object_notify (G_OBJECT (socket), "blocking");
871 * g_socket_get_blocking:
872 * @socket: a #GSocket.
874 * Gets the blocking mode of the socket. For details on blocking I/O,
875 * see g_socket_set_blocking().
877 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
882 g_socket_get_blocking (GSocket *socket)
884 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
886 return socket->priv->blocking;
890 * g_socket_set_keepalive:
891 * @socket: a #GSocket.
892 * @keepalive: Value for the keepalive flag
894 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
895 * this flag is set on a socket, the system will attempt to verify that the
896 * remote socket endpoint is still present if a sufficiently long period of
897 * time passes with no data being exchanged. If the system is unable to
898 * verify the presence of the remote endpoint, it will automatically close
901 * This option is only functional on certain kinds of sockets. (Notably,
902 * %G_SOCKET_PROTOCOL_TCP sockets.)
904 * The exact time between pings is system- and protocol-dependent, but will
905 * normally be at least two hours. Most commonly, you would set this flag
906 * on a server socket if you want to allow clients to remain idle for long
907 * periods of time, but also want to ensure that connections are eventually
908 * garbage-collected if clients crash or become unreachable.
913 g_socket_set_keepalive (GSocket *socket,
918 g_return_if_fail (G_IS_SOCKET (socket));
920 keepalive = !!keepalive;
921 if (socket->priv->keepalive == keepalive)
924 value = (gint) keepalive;
925 if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_KEEPALIVE,
926 (gpointer) &value, sizeof (value)) < 0)
928 int errsv = get_socket_errno ();
929 g_warning ("error setting keepalive: %s", socket_strerror (errsv));
933 socket->priv->keepalive = keepalive;
934 g_object_notify (G_OBJECT (socket), "keepalive");
938 * g_socket_get_keepalive:
939 * @socket: a #GSocket.
941 * Gets the keepalive mode of the socket. For details on this,
942 * see g_socket_set_keepalive().
944 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
949 g_socket_get_keepalive (GSocket *socket)
951 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
953 return socket->priv->keepalive;
957 * g_socket_get_listen_backlog:
958 * @socket: a #GSocket.
960 * Gets the listen backlog setting of the socket. For details on this,
961 * see g_socket_set_listen_backlog().
963 * Returns: the maximum number of pending connections.
968 g_socket_get_listen_backlog (GSocket *socket)
970 g_return_val_if_fail (G_IS_SOCKET (socket), 0);
972 return socket->priv->listen_backlog;
976 * g_socket_set_listen_backlog:
977 * @socket: a #GSocket.
978 * @backlog: the maximum number of pending connections.
980 * Sets the maximum number of outstanding connections allowed
981 * when listening on this socket. If more clients than this are
982 * connecting to the socket and the application is not handling them
983 * on time then the new connections will be refused.
985 * Note that this must be called before g_socket_listen() and has no
986 * effect if called after that.
991 g_socket_set_listen_backlog (GSocket *socket,
994 g_return_if_fail (G_IS_SOCKET (socket));
995 g_return_if_fail (!socket->priv->listening);
997 if (backlog != socket->priv->listen_backlog)
999 socket->priv->listen_backlog = backlog;
1000 g_object_notify (G_OBJECT (socket), "listen-backlog");
1005 * g_socket_get_family:
1006 * @socket: a #GSocket.
1008 * Gets the socket family of the socket.
1010 * Returns: a #GSocketFamily
1015 g_socket_get_family (GSocket *socket)
1017 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1019 return socket->priv->family;
1023 * g_socket_get_socket_type:
1024 * @socket: a #GSocket.
1026 * Gets the socket type of the socket.
1028 * Returns: a #GSocketType
1033 g_socket_get_socket_type (GSocket *socket)
1035 g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1037 return socket->priv->type;
1041 * g_socket_get_protocol:
1042 * @socket: a #GSocket.
1044 * Gets the socket protocol id the socket was created with.
1045 * In case the protocol is unknown, -1 is returned.
1047 * Returns: a protocol id, or -1 if unknown
1052 g_socket_get_protocol (GSocket *socket)
1054 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1056 return socket->priv->protocol;
1061 * @socket: a #GSocket.
1063 * Returns the underlying OS socket object. On unix this
1064 * is a socket file descriptor, and on windows this is
1065 * a Winsock2 SOCKET handle. This may be useful for
1066 * doing platform specific or otherwise unusual operations
1069 * Returns: the file descriptor of the socket.
1074 g_socket_get_fd (GSocket *socket)
1076 g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1078 return socket->priv->fd;
1082 * g_socket_get_local_address:
1083 * @socket: a #GSocket.
1084 * @error: #GError for error reporting, or %NULL to ignore.
1086 * Try to get the local address of a bound socket. This is only
1087 * useful if the socket has been bound to a local address,
1088 * either explicitly or implicitly when connecting.
1090 * Returns: a #GSocketAddress or %NULL on error.
1091 * Free the returned object with g_object_unref().
1096 g_socket_get_local_address (GSocket *socket,
1099 struct sockaddr_storage buffer;
1100 guint32 len = sizeof (buffer);
1102 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1104 if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1106 int errsv = get_socket_errno ();
1107 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1108 _("could not get local address: %s"), socket_strerror (errsv));
1112 return g_socket_address_new_from_native (&buffer, len);
1116 * g_socket_get_remote_address:
1117 * @socket: a #GSocket.
1118 * @error: #GError for error reporting, or %NULL to ignore.
1120 * Try to get the remove address of a connected socket. This is only
1121 * useful for connection oriented sockets that have been connected.
1123 * Returns: a #GSocketAddress or %NULL on error.
1124 * Free the returned object with g_object_unref().
1129 g_socket_get_remote_address (GSocket *socket,
1132 struct sockaddr_storage buffer;
1133 guint32 len = sizeof (buffer);
1135 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1137 if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1139 int errsv = get_socket_errno ();
1140 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1141 _("could not get remote address: %s"), socket_strerror (errsv));
1145 return g_socket_address_new_from_native (&buffer, len);
1149 * g_socket_is_connected:
1150 * @socket: a #GSocket.
1152 * Check whether the socket is connected. This is only useful for
1153 * connection-oriented sockets.
1155 * Returns: %TRUE if socket is connected, %FALSE otherwise.
1160 g_socket_is_connected (GSocket *socket)
1162 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1164 return socket->priv->connected;
1169 * @socket: a #GSocket.
1170 * @error: #GError for error reporting, or %NULL to ignore.
1172 * Marks the socket as a server socket, i.e. a socket that is used
1173 * to accept incoming requests using g_socket_accept().
1175 * Before calling this the socket must be bound to a local address using
1178 * To set the maximum amount of outstanding clients, use
1179 * g_socket_set_listen_backlog().
1181 * Returns: %TRUE on success, %FALSE on error.
1186 g_socket_listen (GSocket *socket,
1189 g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1191 if (!check_socket (socket, error))
1194 if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1196 int errsv = get_socket_errno ();
1198 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1199 _("could not listen: %s"), socket_strerror (errsv));
1203 socket->priv->listening = TRUE;
1210 * @socket: a #GSocket.
1211 * @address: a #GSocketAddress specifying the local address.
1212 * @allow_reuse: whether to allow reusing this address
1213 * @error: #GError for error reporting, or %NULL to ignore.
1215 * When a socket is created it is attached to an address family, but it
1216 * doesn't have an address in this family. g_socket_bind() assigns the
1217 * address (sometimes called name) of the socket.
1219 * It is generally required to bind to a local address before you can
1220 * receive connections. (See g_socket_listen() and g_socket_accept() ).
1221 * In certain situations, you may also want to bind a socket that will be
1222 * used to initiate connections, though this is not normally required.
1224 * @allow_reuse should be %TRUE for server sockets (sockets that you will
1225 * eventually call g_socket_accept() on), and %FALSE for client sockets.
1226 * (Specifically, if it is %TRUE, then g_socket_bind() will set the
1227 * %SO_REUSEADDR flag on the socket, allowing it to bind @address even if
1228 * that address was previously used by another socket that has not yet been
1229 * fully cleaned-up by the kernel. Failing to set this flag on a server
1230 * socket may cause the bind call to return %G_IO_ERROR_ADDRESS_IN_USE if
1231 * the server program is stopped and then immediately restarted.)
1233 * Returns: %TRUE on success, %FALSE on error.
1238 g_socket_bind (GSocket *socket,
1239 GSocketAddress *address,
1240 gboolean reuse_address,
1243 struct sockaddr_storage addr;
1245 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1247 if (!check_socket (socket, error))
1250 /* SO_REUSEADDR on windows means something else and is not what we want.
1251 It always allows the unix variant of SO_REUSEADDR anyway */
1256 value = (int) !!reuse_address;
1257 /* Ignore errors here, the only likely error is "not supported", and
1258 this is a "best effort" thing mainly */
1259 setsockopt (socket->priv->fd, SOL_SOCKET, SO_REUSEADDR,
1260 (gpointer) &value, sizeof (value));
1264 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1267 if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1268 g_socket_address_get_native_size (address)) < 0)
1270 int errsv = get_socket_errno ();
1272 G_IO_ERROR, socket_io_error_from_errno (errsv),
1273 _("Error binding to address: %s"), socket_strerror (errsv));
1282 * @socket: a #GSocket.
1283 * @error: #GError for error reporting, or %NULL to ignore.
1285 * Accept incoming connections on a connection-based socket. This removes
1286 * the first outstanding connection request from the listening socket and
1287 * creates a #GSocket object for it.
1289 * The @socket must be bound to a local address with g_socket_bind() and
1290 * must be listening for incoming connections (g_socket_listen()).
1292 * If there are no outstanding connections then the operation will block
1293 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
1294 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
1296 * Returns: a new #GSocket, or %NULL on error.
1297 * Free the returned object with g_object_unref().
1302 g_socket_accept (GSocket *socket,
1305 GSocket *new_socket;
1308 g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1310 if (!check_socket (socket, error))
1315 if (socket->priv->blocking &&
1316 !g_socket_condition_wait (socket,
1317 G_IO_IN, NULL, error))
1320 if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
1322 int errsv = get_socket_errno ();
1324 win32_unset_event_mask (socket, FD_ACCEPT);
1329 if (socket->priv->blocking)
1331 #ifdef WSAEWOULDBLOCK
1332 if (errsv == WSAEWOULDBLOCK)
1335 if (errsv == EWOULDBLOCK ||
1341 g_set_error (error, G_IO_ERROR,
1342 socket_io_error_from_errno (errsv),
1343 _("Error accepting connection: %s"), socket_strerror (errsv));
1349 win32_unset_event_mask (socket, FD_ACCEPT);
1353 /* The socket inherits the accepting sockets event mask and even object,
1354 we need to remove that */
1355 WSAEventSelect (ret, NULL, 0);
1361 /* We always want to set close-on-exec to protect users. If you
1362 need to so some weird inheritance to exec you can re-enable this
1363 using lower level hacks with g_socket_get_fd(). */
1364 flags = fcntl (ret, F_GETFD, 0);
1366 (flags & FD_CLOEXEC) == 0)
1368 flags |= FD_CLOEXEC;
1369 fcntl (ret, F_SETFD, flags);
1374 new_socket = g_socket_new_from_fd (ret, error);
1375 if (new_socket == NULL)
1384 new_socket->priv->protocol = socket->priv->protocol;
1391 * @socket: a #GSocket.
1392 * @address: a #GSocketAddress specifying the remote address.
1393 * @error: #GError for error reporting, or %NULL to ignore.
1395 * Connect the socket to the specified remote address.
1397 * For connection oriented socket this generally means we attempt to make
1398 * a connection to the @address. For a connection-less socket it sets
1399 * the default address for g_socket_send() and discards all incoming datagrams
1400 * from other sources.
1402 * Generally connection oriented sockets can only connect once, but
1403 * connection-less sockets can connect multiple times to change the
1406 * If the connect call needs to do network I/O it will block, unless
1407 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
1408 * and the user can be notified of the connection finishing by waiting
1409 * for the G_IO_OUT condition. The result of the connection can then be
1410 * checked with g_socket_check_connect_result().
1412 * Returns: %TRUE if connected, %FALSE on error.
1417 g_socket_connect (GSocket *socket,
1418 GSocketAddress *address,
1421 struct sockaddr_storage buffer;
1423 g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1425 if (!check_socket (socket, error))
1428 if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
1433 if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
1434 g_socket_address_get_native_size (address)) < 0)
1436 int errsv = get_socket_errno ();
1442 if (errsv == EINPROGRESS)
1444 if (errsv == WSAEWOULDBLOCK)
1447 if (socket->priv->blocking)
1449 g_socket_condition_wait (socket, G_IO_OUT, NULL, NULL);
1450 if (g_socket_check_connect_result (socket, error))
1453 g_prefix_error (error, _("Error connecting: "));
1456 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
1457 _("Connection in progress"));
1460 g_set_error (error, G_IO_ERROR,
1461 socket_io_error_from_errno (errsv),
1462 _("Error connecting: %s"), socket_strerror (errsv));
1469 win32_unset_event_mask (socket, FD_CONNECT);
1471 socket->priv->connected = TRUE;
1477 * g_socket_check_connect_result:
1478 * @socket: a #GSocket
1479 * @error: #GError for error reporting, or %NULL to ignore.
1481 * Checks and resets the pending connect error for the socket.
1482 * This is used to check for errors when g_socket_connect() is
1483 * used in non-blocking mode.
1485 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
1490 g_socket_check_connect_result (GSocket *socket,
1496 optlen = sizeof (value);
1497 if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
1499 int errsv = get_socket_errno ();
1501 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1502 _("Unable to get pending error: %s"), socket_strerror (errsv));
1508 g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
1509 socket_strerror (value));
1517 * @socket: a #GSocket
1518 * @buffer: a buffer to read data into (which should be at least @size
1520 * @size: the number of bytes you want to read from the socket
1521 * @error: #GError for error reporting, or %NULL to ignore.
1523 * Receive data (up to @size bytes) from a socket. This is mainly used by
1524 * connection-oriented sockets; it is identical to g_socket_receive_from()
1525 * with @address set to %NULL.
1527 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
1528 * g_socket_receive() will always read either 0 or 1 complete messages from
1529 * the socket. If the received message is too large to fit in @buffer, then
1530 * the data beyond @size bytes will be discarded, without any explicit
1531 * indication that this has occurred.
1533 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
1534 * number of bytes, up to @size. If more than @size bytes have been
1535 * received, the additional data will be returned in future calls to
1536 * g_socket_receive().
1538 * If the socket is in blocking mode the call will block until there is
1539 * some data to receive or there is an error. If there is no data available
1540 * and the socket is in non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error
1541 * will be returned. To be notified when data is available, wait for the
1542 * %G_IO_IN condition.
1544 * On error -1 is returned and @error is set accordingly.
1546 * Returns: Number of bytes read, or -1 on error
1551 g_socket_receive (GSocket *socket,
1558 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1560 if (!check_socket (socket, error))
1565 if (socket->priv->blocking &&
1566 !g_socket_condition_wait (socket,
1567 G_IO_IN, NULL, error))
1570 if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
1572 int errsv = get_socket_errno ();
1577 if (socket->priv->blocking)
1579 #ifdef WSAEWOULDBLOCK
1580 if (errsv == WSAEWOULDBLOCK)
1583 if (errsv == EWOULDBLOCK ||
1589 win32_unset_event_mask (socket, FD_READ);
1591 g_set_error (error, G_IO_ERROR,
1592 socket_io_error_from_errno (errsv),
1593 _("Error receiving data: %s"), socket_strerror (errsv));
1597 win32_unset_event_mask (socket, FD_READ);
1606 * g_socket_receive_from:
1607 * @socket: a #GSocket
1608 * @address: a pointer to a #GSocketAddress pointer, or %NULL
1609 * @buffer: a buffer to read data into (which should be at least @size
1611 * @size: the number of bytes you want to read from the socket
1612 * @error: #GError for error reporting, or %NULL to ignore.
1614 * Receive data (up to @size bytes) from a socket.
1616 * If @address is non-%NULL then @address will be set equal to the
1617 * source address of the received packet.
1618 * @address is owned by the caller.
1620 * See g_socket_receive() for additional information.
1622 * Returns: Number of bytes read, or -1 on error
1627 g_socket_receive_from (GSocket *socket,
1628 GSocketAddress **address,
1638 return g_socket_receive_message (socket,
1647 * @socket: a #GSocket
1648 * @buffer: the buffer containing the data to send.
1649 * @size: the number of bytes to send
1650 * @error: #GError for error reporting, or %NULL to ignore.
1652 * Tries to send @size bytes from @buffer on the socket. This is
1653 * mainly used by connection-oriented sockets; it is identical to
1654 * g_socket_send_to() with @address set to %NULL.
1656 * If the socket is in blocking mode the call will block until there is
1657 * space for the data in the socket queue. If there is no space available
1658 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1659 * will be returned. To be notified when space is available, wait for the
1660 * %G_IO_OUT condition. Note though that you may still receive
1661 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
1662 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
1663 * very common due to the way the underlying APIs work.)
1665 * On error -1 is returned and @error is set accordingly.
1667 * Returns: Number of bytes written (which may be less than @size), or -1
1673 g_socket_send (GSocket *socket,
1674 const gchar *buffer,
1680 g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1682 if (!check_socket (socket, error))
1687 if (socket->priv->blocking &&
1688 !g_socket_condition_wait (socket,
1689 G_IO_OUT, NULL, error))
1692 if ((ret = send (socket->priv->fd, buffer, size, 0)) < 0)
1694 int errsv = get_socket_errno ();
1699 #ifdef WSAEWOULDBLOCK
1700 if (errsv == WSAEWOULDBLOCK)
1701 win32_unset_event_mask (socket, FD_WRITE);
1704 if (socket->priv->blocking)
1706 #ifdef WSAEWOULDBLOCK
1707 if (errsv == WSAEWOULDBLOCK)
1710 if (errsv == EWOULDBLOCK ||
1716 g_set_error (error, G_IO_ERROR,
1717 socket_io_error_from_errno (errsv),
1718 _("Error sending data: %s"), socket_strerror (errsv));
1729 * @socket: a #GSocket
1730 * @address: a #GSocketAddress, or %NULL
1731 * @buffer: the buffer containing the data to send.
1732 * @size: the number of bytes to send
1733 * @error: #GError for error reporting, or %NULL to ignore.
1735 * Tries to send @size bytes from @buffer to @address. If @address is
1736 * %NULL then the message is sent to the default receiver (set by
1737 * g_socket_connect()).
1739 * See g_socket_send() for additional information.
1741 * Returns: Number of bytes written (which may be less than @size), or -1
1747 g_socket_send_to (GSocket *socket,
1748 GSocketAddress *address,
1749 const gchar *buffer,
1758 return g_socket_send_message (socket,
1766 * g_socket_shutdown:
1767 * @socket: a #GSocket
1768 * @shutdown_read: whether to shut down the read side
1769 * @shutdown_write: whether to shut down the write side
1770 * @error: #GError for error reporting, or %NULL to ignore.
1772 * Shut down part of a full-duplex connection.
1774 * If @shutdown_read is %TRUE then the recieving side of the connection
1775 * is shut down, and further reading is disallowed.
1777 * If @shutdown_write is %TRUE then the sending side of the connection
1778 * is shut down, and further writing is disallowed.
1780 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
1782 * One example where this is used is graceful disconnect for TCP connections
1783 * where you close the sending side, then wait for the other side to close
1784 * the connection, thus ensuring that the other side saw all sent data.
1786 * Returns: %TRUE on success, %FALSE on error
1791 g_socket_shutdown (GSocket *socket,
1792 gboolean shutdown_read,
1793 gboolean shutdown_write,
1798 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
1800 if (!check_socket (socket, NULL))
1804 if (!shutdown_read && !shutdown_write)
1808 if (shutdown_read && shutdown_write)
1810 else if (shutdown_read)
1815 if (shutdown_read && shutdown_write)
1817 else if (shutdown_read)
1823 if (shutdown (socket->priv->fd, how) != 0)
1825 int errsv = get_socket_errno ();
1826 g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1827 _("Unable to create socket: %s"), socket_strerror (errsv));
1831 if (shutdown_read && shutdown_write)
1832 socket->priv->connected = FALSE;
1839 * @socket: a #GSocket
1840 * @error: #GError for error reporting, or %NULL to ignore.
1842 * Closes the socket, shutting down any active connection.
1844 * Closing a socket does not wait for all outstanding I/O operations
1845 * to finish, so the caller should not rely on them to be guaranteed
1846 * to complete even if the close returns with no error.
1848 * Once the socket is closed, all other operations will return
1849 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
1852 * Sockets will be automatically closed when the last reference
1853 * is dropped, but you might want to call this function to make sure
1854 * resources are released as early as possible.
1856 * Beware that due to the way that TCP works, it is possible for
1857 * recently-sent data to be lost if either you close a socket while the
1858 * %G_IO_IN condition is set, or else if the remote connection tries to
1859 * send something to you after you close the socket but before it has
1860 * finished reading all of the data you sent. There is no easy generic
1861 * way to avoid this problem; the easiest fix is to design the network
1862 * protocol such that the client will never send data "out of turn".
1863 * Another solution is for the server to half-close the connection by
1864 * calling g_socket_shutdown() with only the @shutdown_write flag set,
1865 * and then wait for the client to notice this and close its side of the
1866 * connection, after which the server can safely call g_socket_close().
1867 * (This is what #GTcpConnection does if you call
1868 * g_tcp_connection_set_graceful_disconnect(). But of course, this
1869 * only works if the client will close its connection after the server
1872 * Returns: %TRUE on success, %FALSE on error
1877 g_socket_close (GSocket *socket,
1882 g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
1884 if (socket->priv->closed)
1885 return TRUE; /* Multiple close not an error */
1887 if (!check_socket (socket, NULL))
1893 res = closesocket (socket->priv->fd);
1895 res = close (socket->priv->fd);
1899 int errsv = get_socket_errno ();
1904 g_set_error (error, G_IO_ERROR,
1905 socket_io_error_from_errno (errsv),
1906 _("Error closing socket: %s"),
1907 socket_strerror (errsv));
1914 if (socket->priv->event != WSA_INVALID_EVENT)
1916 WSACloseEvent (socket->priv->event);
1917 socket->priv->event = WSA_INVALID_EVENT;
1921 socket->priv->connected = FALSE;
1922 socket->priv->closed = TRUE;
1928 * g_socket_is_closed:
1929 * @socket: a #GSocket
1931 * Checks whether a socket is closed.
1933 * Returns: %TRUE if socket is closed, %FALSE otherwise
1938 g_socket_is_closed (GSocket *socket)
1940 return socket->priv->closed;
1944 /* Broken source, used on errors */
1946 broken_prepare (GSource *source,
1953 broken_check (GSource *source)
1959 broken_dispatch (GSource *source,
1960 GSourceFunc callback,
1966 static GSourceFuncs broken_funcs =
1975 network_events_for_condition (GIOCondition condition)
1979 if (condition & G_IO_IN)
1980 event_mask |= (FD_READ | FD_ACCEPT);
1981 if (condition & G_IO_OUT)
1982 event_mask |= (FD_WRITE | FD_CONNECT);
1983 event_mask |= FD_CLOSE;
1989 ensure_event (GSocket *socket)
1991 if (socket->priv->event == WSA_INVALID_EVENT)
1992 socket->priv->event = WSACreateEvent();
1996 update_select_events (GSocket *socket)
2003 ensure_event (socket);
2006 for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
2009 event_mask |= network_events_for_condition (*ptr);
2012 if (event_mask != socket->priv->selected_events)
2014 /* If no events selected, disable event so we can unset
2017 if (event_mask == 0)
2020 event = socket->priv->event;
2022 if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
2023 socket->priv->selected_events = event_mask;
2028 add_condition_watch (GSocket *socket,
2029 GIOCondition *condition)
2031 g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
2033 socket->priv->requested_conditions =
2034 g_list_prepend (socket->priv->requested_conditions, condition);
2036 update_select_events (socket);
2040 remove_condition_watch (GSocket *socket,
2041 GIOCondition *condition)
2043 g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
2045 socket->priv->requested_conditions =
2046 g_list_remove (socket->priv->requested_conditions, condition);
2048 update_select_events (socket);
2052 update_condition (GSocket *socket)
2054 WSANETWORKEVENTS events;
2055 GIOCondition condition;
2057 if (WSAEnumNetworkEvents (socket->priv->fd,
2058 socket->priv->event,
2061 socket->priv->current_events |= events.lNetworkEvents;
2062 if (events.lNetworkEvents & FD_WRITE &&
2063 events.iErrorCode[FD_WRITE_BIT] != 0)
2064 socket->priv->current_errors |= FD_WRITE;
2065 if (events.lNetworkEvents & FD_CONNECT &&
2066 events.iErrorCode[FD_CONNECT_BIT] != 0)
2067 socket->priv->current_errors |= FD_CONNECT;
2071 if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
2072 condition |= G_IO_IN;
2074 if (socket->priv->current_events & FD_CLOSE ||
2075 socket->priv->closed)
2076 condition |= G_IO_HUP;
2078 /* Never report both G_IO_OUT and HUP, these are
2079 mutually exclusive (can't write to a closed socket) */
2080 if ((condition & G_IO_HUP) == 0 &&
2081 socket->priv->current_events & FD_WRITE)
2083 if (socket->priv->current_errors & FD_WRITE)
2084 condition |= G_IO_ERR;
2086 condition |= G_IO_OUT;
2090 if (socket->priv->current_events & FD_CONNECT)
2092 if (socket->priv->current_errors & FD_CONNECT)
2093 condition |= (G_IO_HUP | G_IO_ERR);
2095 condition |= G_IO_OUT;
2106 GIOCondition condition;
2107 GCancellable *cancellable;
2108 GPollFD cancel_pollfd;
2109 GIOCondition result_condition;
2113 winsock_prepare (GSource *source,
2116 GWinsockSource *winsock_source = (GWinsockSource *)source;
2117 GIOCondition current_condition;
2119 current_condition = update_condition (winsock_source->socket);
2121 if (g_cancellable_is_cancelled (winsock_source->cancellable))
2123 winsock_source->result_condition = current_condition;
2127 if ((winsock_source->condition & current_condition) != 0)
2129 winsock_source->result_condition = current_condition;
2137 winsock_check (GSource *source)
2139 GWinsockSource *winsock_source = (GWinsockSource *)source;
2140 GIOCondition current_condition;
2142 current_condition = update_condition (winsock_source->socket);
2144 if (g_cancellable_is_cancelled (winsock_source->cancellable))
2146 winsock_source->result_condition = current_condition;
2150 if ((winsock_source->condition & current_condition) != 0)
2152 winsock_source->result_condition = current_condition;
2160 winsock_dispatch (GSource *source,
2161 GSourceFunc callback,
2164 GSocketSourceFunc func = (GSocketSourceFunc)callback;
2165 GWinsockSource *winsock_source = (GWinsockSource *)source;
2167 return (*func) (winsock_source->socket,
2168 winsock_source->result_condition & winsock_source->condition,
2173 winsock_finalize (GSource *source)
2175 GWinsockSource *winsock_source = (GWinsockSource *)source;
2178 socket = winsock_source->socket;
2180 remove_condition_watch (socket, &winsock_source->condition);
2181 g_object_unref (socket);
2183 if (winsock_source->cancellable)
2184 g_object_unref (winsock_source->cancellable);
2187 static GSourceFuncs winsock_funcs =
2196 winsock_source_new (GSocket *socket,
2197 GIOCondition condition,
2198 GCancellable *cancellable)
2201 GWinsockSource *winsock_source;
2203 ensure_event (socket);
2205 if (socket->priv->event == WSA_INVALID_EVENT)
2207 g_warning ("Failed to create WSAEvent");
2208 return g_source_new (&broken_funcs, sizeof (GSource));
2211 condition |= G_IO_HUP | G_IO_ERR;
2213 source = g_source_new (&winsock_funcs, sizeof (GWinsockSource));
2214 winsock_source = (GWinsockSource *)source;
2216 winsock_source->socket = g_object_ref (socket);
2217 winsock_source->condition = condition;
2218 add_condition_watch (socket, &winsock_source->condition);
2222 winsock_source->cancellable = g_object_ref (cancellable);
2223 g_cancellable_make_pollfd (cancellable,
2224 &winsock_source->cancel_pollfd);
2225 g_source_add_poll (source, &winsock_source->cancel_pollfd);
2228 winsock_source->pollfd.fd = (gintptr) socket->priv->event;
2229 winsock_source->pollfd.events = condition;
2230 g_source_add_poll (source, &winsock_source->pollfd);
2237 * g_socket_create_source:
2238 * @socket: a #GSocket
2239 * @condition: a #GIOCondition mask to monitor
2240 * @cancellable: a %GCancellable or %NULL
2242 * Creates a %GSource that can be attached to a %GMainContext to monitor
2243 * for the availibility of the specified @condition on the socket.
2245 * The callback on the source is of the #GSocketSourceFunc type.
2247 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2248 * these conditions will always be reported output if they are true.
2250 * @cancellable if not %NULL can be used to cancel the source, which will
2251 * cause the source to trigger, reporting the current condition (which
2252 * is likely 0 unless cancellation happened at the same time as a
2253 * condition change). You can check for this in the callback using
2254 * g_cancellable_is_cancelled().
2256 * Returns: a newly allocated %GSource, free with g_source_unref().
2261 g_socket_create_source (GSocket *socket,
2262 GIOCondition condition,
2263 GCancellable *cancellable)
2266 g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
2269 source = winsock_source_new (socket, condition, cancellable);
2271 source =_g_fd_source_new_with_object (G_OBJECT (socket), socket->priv->fd,
2272 condition, cancellable);
2278 * g_socket_condition_check:
2279 * @socket: a #GSocket
2280 * @condition: a #GIOCondition mask to check
2282 * Checks on the readiness of @socket to perform operations.
2283 * The operations specified in @condition are checked for and masked
2284 * against the currently-satisfied conditions on @socket. The result
2287 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2288 * these conditions will always be set in the output if they are true.
2290 * This call never blocks.
2292 * Returns: the @GIOCondition mask of the current state
2297 g_socket_condition_check (GSocket *socket,
2298 GIOCondition condition)
2300 if (!check_socket (socket, NULL))
2305 GIOCondition current_condition;
2307 condition |= G_IO_ERR | G_IO_HUP;
2309 add_condition_watch (socket, &condition);
2310 current_condition = update_condition (socket);
2311 remove_condition_watch (socket, &condition);
2312 return condition & current_condition;
2318 poll_fd.fd = socket->priv->fd;
2319 poll_fd.events = condition;
2322 result = g_poll (&poll_fd, 1, 0);
2323 while (result == -1 && get_socket_errno () == EINTR);
2325 return poll_fd.revents;
2331 * g_socket_condition_wait:
2332 * @socket: a #GSocket
2333 * @condition: a #GIOCondition mask to wait for
2334 * @cancellable: a #GCancellable, or %NULL
2335 * @error: a #GError pointer, or %NULL
2337 * Waits for @condition to become true on @socket. When the condition
2338 * is met, %TRUE is returned.
2340 * If @cancellable is cancelled before the condition is met then %FALSE
2341 * is returned and @error, if non-%NULL, is set to %G_IO_ERROR_CANCELLED.
2343 * Returns: %TRUE if the condition was met, %FALSE otherwise
2348 g_socket_condition_wait (GSocket *socket,
2349 GIOCondition condition,
2350 GCancellable *cancellable,
2353 if (!check_socket (socket, error))
2356 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2361 GIOCondition current_condition;
2367 /* Always check these */
2368 condition |= G_IO_ERR | G_IO_HUP;
2370 add_condition_watch (socket, &condition);
2373 events[num_events++] = socket->priv->event;
2377 g_cancellable_make_pollfd (cancellable, &cancel_fd);
2378 events[num_events++] = (WSAEVENT)cancel_fd.fd;
2381 current_condition = update_condition (socket);
2382 while ((condition & current_condition) == 0)
2384 res = WSAWaitForMultipleEvents(num_events, events,
2385 FALSE, WSA_INFINITE, FALSE);
2386 if (res == WSA_WAIT_FAILED)
2388 int errsv = get_socket_errno ();
2390 g_set_error (error, G_IO_ERROR,
2391 socket_io_error_from_errno (errsv),
2392 _("Waiting for socket condition: %s"),
2393 socket_strerror (errsv));
2397 if (g_cancellable_set_error_if_cancelled (cancellable, error))
2400 current_condition = update_condition (socket);
2402 remove_condition_watch (socket, &condition);
2404 return (condition & current_condition) != 0;
2412 poll_fd[0].fd = socket->priv->fd;
2413 poll_fd[0].events = condition;
2418 g_cancellable_make_pollfd (cancellable, &poll_fd[1]);
2423 result = g_poll (poll_fd, num, -1);
2424 while (result == -1 && get_socket_errno () == EINTR);
2426 return cancellable == NULL ||
2427 !g_cancellable_set_error_if_cancelled (cancellable, error);
2433 * g_socket_send_message:
2434 * @socket: a #GSocket
2435 * @address: a #GSocketAddress, or %NULL
2436 * @vectors: an array of #GOutputVector structs
2437 * @num_vectors: the number of elements in @vectors, or -1
2438 * @messages: a pointer to an array of #GSocketControlMessages, or
2440 * @num_messages: number of elements in @messages, or -1.
2441 * @flags: an int containing #GSocketMsgFlags flags
2442 * @error: #GError for error reporting, or %NULL to ignore.
2444 * Send data to @address on @socket. This is the most complicated and
2445 * fully-featured version of this call. For easier use, see
2446 * g_socket_send() and g_socket_send_to().
2448 * If @address is %NULL then the message is sent to the default receiver
2449 * (set by g_socket_connect()).
2451 * @vectors must point to an array of #GOutputVector structs and
2452 * @num_vectors must be the length of this array. (If @num_vectors is -1,
2453 * then @vectors is assumed to be terminated by a #GOutputVector with a
2454 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
2455 * that the sent data will be gathered from. Using multiple
2456 * #GOutputVector<!-- -->s is more memory-efficient than manually copying
2457 * data from multiple sources into a single buffer, and more
2458 * network-efficient than making multiple calls to g_socket_send().
2460 * @messages, if non-%NULL, is taken to point to an array of @num_messages
2461 * #GSocketControlMessage instances. These correspond to the control
2462 * messages to be sent on the socket.
2463 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
2466 * @flags modify how the message is sent. The commonly available arguments
2467 * for this are available in the #GSocketMsgFlags enum, but the
2468 * values there are the same as the system values, and the flags
2469 * are passed in as-is, so you can pass in system-specific flags too.
2471 * If the socket is in blocking mode the call will block until there is
2472 * space for the data in the socket queue. If there is no space available
2473 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2474 * will be returned. To be notified when space is available, wait for the
2475 * %G_IO_OUT condition. Note though that you may still receive
2476 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2477 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2478 * very common due to the way the underlying APIs work.)
2480 * On error -1 is returned and @error is set accordingly.
2482 * Returns: Number of bytes written (which may be less than @size), or -1
2488 g_socket_send_message (GSocket *socket,
2489 GSocketAddress *address,
2490 GOutputVector *vectors,
2492 GSocketControlMessage **messages,
2497 GOutputVector one_vector;
2500 if (!check_socket (socket, error))
2503 if (num_vectors == -1)
2505 for (num_vectors = 0;
2506 vectors[num_vectors].buffer != NULL;
2511 if (num_messages == -1)
2513 for (num_messages = 0;
2514 messages != NULL && messages[num_messages] != NULL;
2519 if (num_vectors == 0)
2523 one_vector.buffer = &zero;
2524 one_vector.size = 1;
2526 vectors = &one_vector;
2537 msg.msg_namelen = g_socket_address_get_native_size (address);
2538 msg.msg_name = g_alloca (msg.msg_namelen);
2539 if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
2545 /* this entire expression will be evaluated at compile time */
2546 if (sizeof *msg.msg_iov == sizeof *vectors &&
2547 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2548 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2549 G_STRUCT_OFFSET (GOutputVector, buffer) &&
2550 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2551 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2552 G_STRUCT_OFFSET (GOutputVector, size))
2553 /* ABI is compatible */
2555 msg.msg_iov = (struct iovec *) vectors;
2556 msg.msg_iovlen = num_vectors;
2559 /* ABI is incompatible */
2563 msg.msg_iov = g_newa (struct iovec, num_vectors);
2564 for (i = 0; i < num_vectors; i++)
2566 msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
2567 msg.msg_iov[i].iov_len = vectors[i].size;
2569 msg.msg_iovlen = num_vectors;
2575 struct cmsghdr *cmsg;
2578 msg.msg_controllen = 0;
2579 for (i = 0; i < num_messages; i++)
2580 msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
2582 msg.msg_control = g_alloca (msg.msg_controllen);
2584 cmsg = CMSG_FIRSTHDR (&msg);
2585 for (i = 0; i < num_messages; i++)
2587 cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
2588 cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
2589 cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
2590 g_socket_control_message_serialize (messages[i],
2592 cmsg = CMSG_NXTHDR (&msg, cmsg);
2594 g_assert (cmsg == NULL);
2599 if (socket->priv->blocking &&
2600 !g_socket_condition_wait (socket,
2601 G_IO_OUT, NULL, error))
2604 result = sendmsg (socket->priv->fd, &msg, flags);
2607 int errsv = get_socket_errno ();
2612 if (socket->priv->blocking &&
2613 (errsv == EWOULDBLOCK ||
2617 g_set_error (error, G_IO_ERROR,
2618 socket_io_error_from_errno (errsv),
2619 _("Error sending message: %s"), socket_strerror (errsv));
2630 struct sockaddr_storage addr;
2637 /* Win32 doesn't support control messages.
2638 Actually this is possible for raw and datagram sockets
2639 via WSASendMessage on Vista or later, but that doesn't
2641 if (num_messages != 0)
2643 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2644 _("GSocketControlMessage not supported on windows"));
2649 bufs = g_newa (WSABUF, num_vectors);
2650 for (i = 0; i < num_vectors; i++)
2652 bufs[i].buf = (char *)vectors[i].buffer;
2653 bufs[i].len = (gulong)vectors[i].size;
2657 addrlen = 0; /* Avoid warning */
2660 addrlen = g_socket_address_get_native_size (address);
2661 if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
2667 if (socket->priv->blocking &&
2668 !g_socket_condition_wait (socket,
2669 G_IO_OUT, NULL, error))
2673 result = WSASendTo (socket->priv->fd,
2676 (const struct sockaddr *)&addr, addrlen,
2679 result = WSASend (socket->priv->fd,
2686 int errsv = get_socket_errno ();
2688 if (errsv == WSAEINTR)
2691 if (errsv == WSAEWOULDBLOCK)
2692 win32_unset_event_mask (socket, FD_WRITE);
2694 if (socket->priv->blocking &&
2695 errsv == WSAEWOULDBLOCK)
2698 g_set_error (error, G_IO_ERROR,
2699 socket_io_error_from_errno (errsv),
2700 _("Error sending message: %s"), socket_strerror (errsv));
2713 * g_socket_receive_message:
2714 * @socket: a #GSocket
2715 * @address: a pointer to a #GSocketAddress pointer, or %NULL
2716 * @vectors: an array of #GInputVector structs
2717 * @num_vectors: the number of elements in @vectors, or -1
2718 * @messages: a pointer which will be filled with an array of
2719 * #GSocketControlMessages, or %NULL
2720 * @num_messages: a pointer which will be filled with the number of
2721 * elements in @messages, or %NULL
2722 * @flags: a pointer to an int containing #GSocketMsgFlags flags
2723 * @error: a #GError pointer, or %NULL
2725 * Receive data from a socket. This is the most complicated and
2726 * fully-featured version of this call. For easier use, see
2727 * g_socket_receive() and g_socket_receive_from().
2729 * If @address is non-%NULL then @address will be set equal to the
2730 * source address of the received packet.
2731 * @address is owned by the caller.
2733 * @vector must point to an array of #GInputVector structs and
2734 * @num_vectors must be the length of this array. These structs
2735 * describe the buffers that received data will be scattered into.
2736 * If @num_vectors is -1, then @vectors is assumed to be terminated
2737 * by a #GInputVector with a %NULL buffer pointer.
2739 * As a special case, if @num_vectors is 0 (in which case, @vectors
2740 * may of course be %NULL), then a single byte is received and
2741 * discarded. This is to facilitate the common practice of sending a
2742 * single '\0' byte for the purposes of transferring ancillary data.
2744 * @messages, if non-%NULL, will be set to point to a newly-allocated
2745 * array of #GSocketControlMessage instances. These correspond to the
2746 * control messages received from the kernel, one
2747 * #GSocketControlMessage per message from the kernel. This array is
2748 * %NULL-terminated and must be freed by the caller using g_free(). If
2749 * @messages is %NULL, any control messages received will be
2752 * @num_messages, if non-%NULL, will be set to the number of control
2753 * messages received.
2755 * If both @messages and @num_messages are non-%NULL, then
2756 * @num_messages gives the number of #GSocketControlMessage instances
2757 * in @messages (ie: not including the %NULL terminator).
2759 * @flags is an in/out parameter. The commonly available arguments
2760 * for this are available in the #GSocketMsgFlags enum, but the
2761 * values there are the same as the system values, and the flags
2762 * are passed in as-is, so you can pass in system-specific flags too
2763 * (and g_socket_receive_message() may pass system-specific flags out).
2765 * As with g_socket_receive(), data may be discarded if @socket is
2766 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
2767 * provide enough buffer space to read a complete message. You can pass
2768 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
2769 * removing it from the receive queue, but there is no portable way to find
2770 * out the length of the message other than by reading it into a
2771 * sufficiently-large buffer.
2773 * If the socket is in blocking mode the call will block until there
2774 * is some data to receive or there is an error. If there is no data
2775 * available and the socket is in non-blocking mode, a
2776 * %G_IO_ERROR_WOULD_BLOCK error will be returned. To be notified when
2777 * data is available, wait for the %G_IO_IN condition.
2779 * On error -1 is returned and @error is set accordingly.
2781 * Returns: Number of bytes read, or -1 on error
2786 g_socket_receive_message (GSocket *socket,
2787 GSocketAddress **address,
2788 GInputVector *vectors,
2790 GSocketControlMessage ***messages,
2795 GInputVector one_vector;
2798 if (!check_socket (socket, error))
2801 if (num_vectors == -1)
2803 for (num_vectors = 0;
2804 vectors[num_vectors].buffer != NULL;
2809 if (num_vectors == 0)
2811 one_vector.buffer = &one_byte;
2812 one_vector.size = 1;
2814 vectors = &one_vector;
2821 struct sockaddr_storage one_sockaddr;
2826 msg.msg_name = &one_sockaddr;
2827 msg.msg_namelen = sizeof (struct sockaddr_storage);
2831 msg.msg_name = NULL;
2832 msg.msg_namelen = 0;
2836 /* this entire expression will be evaluated at compile time */
2837 if (sizeof *msg.msg_iov == sizeof *vectors &&
2838 sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2839 G_STRUCT_OFFSET (struct iovec, iov_base) ==
2840 G_STRUCT_OFFSET (GInputVector, buffer) &&
2841 sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2842 G_STRUCT_OFFSET (struct iovec, iov_len) ==
2843 G_STRUCT_OFFSET (GInputVector, size))
2844 /* ABI is compatible */
2846 msg.msg_iov = (struct iovec *) vectors;
2847 msg.msg_iovlen = num_vectors;
2850 /* ABI is incompatible */
2854 msg.msg_iov = g_newa (struct iovec, num_vectors);
2855 for (i = 0; i < num_vectors; i++)
2857 msg.msg_iov[i].iov_base = vectors[i].buffer;
2858 msg.msg_iov[i].iov_len = vectors[i].size;
2860 msg.msg_iovlen = num_vectors;
2864 msg.msg_control = g_alloca (2048);
2865 msg.msg_controllen = 2048;
2869 msg.msg_flags = *flags;
2876 if (socket->priv->blocking &&
2877 !g_socket_condition_wait (socket,
2878 G_IO_IN, NULL, error))
2881 result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
2885 int errsv = get_socket_errno ();
2890 if (socket->priv->blocking &&
2891 (errsv == EWOULDBLOCK ||
2895 g_set_error (error, G_IO_ERROR,
2896 socket_io_error_from_errno (errsv),
2897 _("Error receiving message: %s"), socket_strerror (errsv));
2904 /* decode address */
2905 if (address != NULL)
2907 if (msg.msg_namelen > 0)
2908 *address = g_socket_address_new_from_native (msg.msg_name,
2914 /* decode control messages */
2916 GSocketControlMessage **my_messages = NULL;
2917 gint allocated = 0, index = 0;
2918 const gchar *scm_pointer;
2919 struct cmsghdr *cmsg;
2922 scm_pointer = (const gchar *) msg.msg_control;
2923 scm_size = msg.msg_controllen;
2925 for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
2927 GSocketControlMessage *message;
2929 message = g_socket_control_message_deserialize (cmsg->cmsg_level,
2931 cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
2933 if (message == NULL)
2934 /* We've already spewed about the problem in the
2935 deserialization code, so just continue */
2938 if (index == allocated)
2940 /* estimated 99% case: exactly 1 control message */
2941 allocated = MIN (allocated * 2, 1);
2942 my_messages = g_new (GSocketControlMessage *, (allocated + 1));
2946 my_messages[index++] = message;
2950 *num_messages = index;
2954 my_messages[index++] = NULL;
2955 *messages = my_messages;
2961 /* free all those messages we just constructed.
2962 * we have to do it this way if the user ignores the
2963 * messages so that we will close any received fds.
2965 for (i = 0; i < index; i++)
2966 g_object_unref (my_messages[i]);
2967 g_free (my_messages);
2971 /* capture the flags */
2973 *flags = msg.msg_flags;
2979 struct sockaddr_storage addr;
2981 DWORD bytes_received;
2988 bufs = g_newa (WSABUF, num_vectors);
2989 for (i = 0; i < num_vectors; i++)
2991 bufs[i].buf = (char *)vectors[i].buffer;
2992 bufs[i].len = (gulong)vectors[i].size;
3004 if (socket->priv->blocking &&
3005 !g_socket_condition_wait (socket,
3006 G_IO_IN, NULL, error))
3009 addrlen = sizeof addr;
3011 result = WSARecvFrom (socket->priv->fd,
3013 &bytes_received, &win_flags,
3014 (struct sockaddr *)&addr, &addrlen,
3017 result = WSARecv (socket->priv->fd,
3019 &bytes_received, &win_flags,
3023 int errsv = get_socket_errno ();
3025 if (errsv == WSAEINTR)
3028 win32_unset_event_mask (socket, FD_READ);
3030 if (socket->priv->blocking &&
3031 errsv == WSAEWOULDBLOCK)
3034 g_set_error (error, G_IO_ERROR,
3035 socket_io_error_from_errno (errsv),
3036 _("Error receiving message: %s"), socket_strerror (errsv));
3040 win32_unset_event_mask (socket, FD_READ);
3044 /* decode address */
3045 if (address != NULL)
3048 *address = g_socket_address_new_from_native (&addr, addrlen);
3053 /* capture the flags */
3057 return bytes_received;
3062 #define __G_SOCKET_C__
3063 #include "gioaliasdef.c"