GSocket: Add function to set/get the broadcast setting on a socket
[platform/upstream/glib.git] / gio / gsocket.c
1 /* GIO - GLib Input, Output and Streaming Library
2  *
3  * Copyright (C) 2008 Christian Kellner, Samuel Cormier-Iijima
4  * Copyright © 2009 Codethink Limited
5  * Copyright © 2009 Red Hat, Inc
6  *
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.
11  *
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.
16  *
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.
21  *
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>
26  */
27
28 #include "config.h"
29
30 #include "gsocket.h"
31
32 #ifdef G_OS_UNIX
33 #include "glib-unix.h"
34 #endif
35
36 #include <errno.h>
37 #include <signal.h>
38 #include <string.h>
39 #include <stdlib.h>
40
41 #ifndef G_OS_WIN32
42 # include <fcntl.h>
43 # include <unistd.h>
44 #endif
45
46 #ifdef HAVE_SYS_UIO_H
47 #include <sys/uio.h>
48 #endif
49
50 #include "gcancellable.h"
51 #include "gioenumtypes.h"
52 #include "ginetaddress.h"
53 #include "ginitable.h"
54 #include "gioerror.h"
55 #include "gioenums.h"
56 #include "gioerror.h"
57 #include "gnetworkingprivate.h"
58 #include "gsocketaddress.h"
59 #include "gsocketcontrolmessage.h"
60 #include "gcredentials.h"
61 #include "glibintl.h"
62
63 /**
64  * SECTION:gsocket
65  * @short_description: Low-level socket object
66  * @include: gio/gio.h
67  * @see_also: #GInitable
68  *
69  * A #GSocket is a low-level networking primitive. It is a more or less
70  * direct mapping of the BSD socket API in a portable GObject based API.
71  * It supports both the UNIX socket implementations and winsock2 on Windows.
72  *
73  * #GSocket is the platform independent base upon which the higher level
74  * network primitives are based. Applications are not typically meant to
75  * use it directly, but rather through classes like #GSocketClient,
76  * #GSocketService and #GSocketConnection. However there may be cases where
77  * direct use of #GSocket is useful.
78  *
79  * #GSocket implements the #GInitable interface, so if it is manually constructed
80  * by e.g. g_object_new() you must call g_initable_init() and check the
81  * results before using the object. This is done automatically in
82  * g_socket_new() and g_socket_new_from_fd(), so these functions can return
83  * %NULL.
84  *
85  * Sockets operate in two general modes, blocking or non-blocking. When
86  * in blocking mode all operations block until the requested operation
87  * is finished or there is an error. In non-blocking mode all calls that
88  * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
89  * To know when a call would successfully run you can call g_socket_condition_check(),
90  * or g_socket_condition_wait(). You can also use g_socket_create_source() and
91  * attach it to a #GMainContext to get callbacks when I/O is possible.
92  * Note that all sockets are always set to non blocking mode in the system, and
93  * blocking mode is emulated in GSocket.
94  *
95  * When working in non-blocking mode applications should always be able to
96  * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
97  * function said that I/O was possible. This can easily happen in case
98  * of a race condition in the application, but it can also happen for other
99  * reasons. For instance, on Windows a socket is always seen as writable
100  * until a write returns %G_IO_ERROR_WOULD_BLOCK.
101  *
102  * #GSocket<!-- -->s can be either connection oriented or datagram based.
103  * For connection oriented types you must first establish a connection by
104  * either connecting to an address or accepting a connection from another
105  * address. For connectionless socket types the target/source address is
106  * specified or received in each I/O operation.
107  *
108  * All socket file descriptors are set to be close-on-exec.
109  *
110  * Note that creating a #GSocket causes the signal %SIGPIPE to be
111  * ignored for the remainder of the program. If you are writing a
112  * command-line utility that uses #GSocket, you may need to take into
113  * account the fact that your program will not automatically be killed
114  * if it tries to write to %stdout after it has been closed.
115  *
116  * Since: 2.22
117  */
118
119 static void     g_socket_initable_iface_init (GInitableIface  *iface);
120 static gboolean g_socket_initable_init       (GInitable       *initable,
121                                               GCancellable    *cancellable,
122                                               GError         **error);
123
124 G_DEFINE_TYPE_WITH_CODE (GSocket, g_socket, G_TYPE_OBJECT,
125                          G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
126                                                 g_socket_initable_iface_init));
127
128 enum
129 {
130   PROP_0,
131   PROP_FAMILY,
132   PROP_TYPE,
133   PROP_PROTOCOL,
134   PROP_FD,
135   PROP_BLOCKING,
136   PROP_LISTEN_BACKLOG,
137   PROP_KEEPALIVE,
138   PROP_LOCAL_ADDRESS,
139   PROP_REMOTE_ADDRESS,
140   PROP_TIMEOUT,
141   PROP_TTL,
142   PROP_BROADCAST,
143   PROP_MULTICAST_LOOPBACK,
144   PROP_MULTICAST_TTL
145 };
146
147 struct _GSocketPrivate
148 {
149   GSocketFamily   family;
150   GSocketType     type;
151   GSocketProtocol protocol;
152   gint            fd;
153   gint            listen_backlog;
154   guint           timeout;
155   GError         *construct_error;
156   GSocketAddress *remote_address;
157   guint           inited : 1;
158   guint           blocking : 1;
159   guint           keepalive : 1;
160   guint           closed : 1;
161   guint           connected : 1;
162   guint           listening : 1;
163   guint           timed_out : 1;
164   guint           connect_pending : 1;
165 #ifdef G_OS_WIN32
166   WSAEVENT        event;
167   int             current_events;
168   int             current_errors;
169   int             selected_events;
170   GList          *requested_conditions; /* list of requested GIOCondition * */
171 #endif
172 };
173
174 static int
175 get_socket_errno (void)
176 {
177 #ifndef G_OS_WIN32
178   return errno;
179 #else
180   return WSAGetLastError ();
181 #endif
182 }
183
184 static GIOErrorEnum
185 socket_io_error_from_errno (int err)
186 {
187 #ifndef G_OS_WIN32
188   return g_io_error_from_errno (err);
189 #else
190   switch (err)
191     {
192     case WSAEADDRINUSE:
193       return G_IO_ERROR_ADDRESS_IN_USE;
194     case WSAEWOULDBLOCK:
195       return G_IO_ERROR_WOULD_BLOCK;
196     case WSAEACCES:
197       return G_IO_ERROR_PERMISSION_DENIED;
198     case WSA_INVALID_HANDLE:
199     case WSA_INVALID_PARAMETER:
200     case WSAEBADF:
201     case WSAENOTSOCK:
202       return G_IO_ERROR_INVALID_ARGUMENT;
203     case WSAEPROTONOSUPPORT:
204       return G_IO_ERROR_NOT_SUPPORTED;
205     case WSAECANCELLED:
206       return G_IO_ERROR_CANCELLED;
207     case WSAESOCKTNOSUPPORT:
208     case WSAEOPNOTSUPP:
209     case WSAEPFNOSUPPORT:
210     case WSAEAFNOSUPPORT:
211       return G_IO_ERROR_NOT_SUPPORTED;
212     default:
213       return G_IO_ERROR_FAILED;
214     }
215 #endif
216 }
217
218 static const char *
219 socket_strerror (int err)
220 {
221 #ifndef G_OS_WIN32
222   return g_strerror (err);
223 #else
224   const char *msg_ret;
225   char *msg;
226
227   msg = g_win32_error_message (err);
228
229   msg_ret = g_intern_string (msg);
230   g_free (msg);
231
232   return msg_ret;
233 #endif
234 }
235
236 #ifdef G_OS_WIN32
237 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
238 static void
239 _win32_unset_event_mask (GSocket *socket, int mask)
240 {
241   socket->priv->current_events &= ~mask;
242   socket->priv->current_errors &= ~mask;
243 }
244 #else
245 #define win32_unset_event_mask(_socket, _mask)
246 #endif
247
248 static void
249 set_fd_nonblocking (int fd)
250 {
251 #ifndef G_OS_WIN32
252   GError *error = NULL;
253 #else
254   gulong arg;
255 #endif
256
257 #ifndef G_OS_WIN32
258   if (!g_unix_set_fd_nonblocking (fd, TRUE, &error))
259     {
260       g_warning ("Error setting socket nonblocking: %s", error->message);
261       g_clear_error (&error);
262     }
263 #else
264   arg = TRUE;
265
266   if (ioctlsocket (fd, FIONBIO, &arg) == SOCKET_ERROR)
267     {
268       int errsv = get_socket_errno ();
269       g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
270     }
271 #endif
272 }
273
274 static gboolean
275 check_socket (GSocket *socket,
276               GError **error)
277 {
278   if (!socket->priv->inited)
279     {
280       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
281                            _("Invalid socket, not initialized"));
282       return FALSE;
283     }
284
285   if (socket->priv->construct_error)
286     {
287       g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
288                    _("Invalid socket, initialization failed due to: %s"),
289                    socket->priv->construct_error->message);
290       return FALSE;
291     }
292
293   if (socket->priv->closed)
294     {
295       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
296                            _("Socket is already closed"));
297       return FALSE;
298     }
299
300   if (socket->priv->timed_out)
301     {
302       socket->priv->timed_out = FALSE;
303       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
304                            _("Socket I/O timed out"));
305       return FALSE;
306     }
307
308   return TRUE;
309 }
310
311 static void
312 g_socket_details_from_fd (GSocket *socket)
313 {
314   struct sockaddr_storage address;
315   gint fd;
316   guint addrlen;
317   guint optlen;
318   int value, family;
319   int errsv;
320 #ifdef G_OS_WIN32
321   /* See bug #611756 */
322   BOOL bool_val = FALSE;
323 #else
324   int bool_val;
325 #endif
326
327   fd = socket->priv->fd;
328   optlen = sizeof value;
329   if (getsockopt (fd, SOL_SOCKET, SO_TYPE, (void *)&value, &optlen) != 0)
330     {
331       errsv = get_socket_errno ();
332
333       switch (errsv)
334         {
335 #ifdef ENOTSOCK
336          case ENOTSOCK:
337 #endif
338 #ifdef WSAENOTSOCK
339          case WSAENOTSOCK:
340 #endif
341          case EBADF:
342           /* programmer error */
343           g_error ("creating GSocket from fd %d: %s\n",
344                    fd, socket_strerror (errsv));
345          default:
346            break;
347         }
348
349       goto err;
350     }
351
352   g_assert (optlen == sizeof value);
353   switch (value)
354     {
355      case SOCK_STREAM:
356       socket->priv->type = G_SOCKET_TYPE_STREAM;
357       break;
358
359      case SOCK_DGRAM:
360       socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
361       break;
362
363      case SOCK_SEQPACKET:
364       socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
365       break;
366
367      default:
368       socket->priv->type = G_SOCKET_TYPE_INVALID;
369       break;
370     }
371
372   addrlen = sizeof address;
373   if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
374     {
375       errsv = get_socket_errno ();
376       goto err;
377     }
378
379   if (addrlen > 0)
380     {
381       g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
382                 sizeof address.ss_family <= addrlen);
383       family = address.ss_family;
384     }
385   else
386     {
387       /* On Solaris, this happens if the socket is not yet connected.
388        * But we can use SO_DOMAIN as a workaround there.
389        */
390 #ifdef SO_DOMAIN
391       optlen = sizeof family;
392       if (getsockopt (fd, SOL_SOCKET, SO_DOMAIN, (void *)&family, &optlen) != 0)
393         {
394           errsv = get_socket_errno ();
395           goto err;
396         }
397 #else
398       /* This will translate to G_IO_ERROR_FAILED on either unix or windows */
399       errsv = -1;
400       goto err;
401 #endif
402     }
403
404   switch (family)
405     {
406      case G_SOCKET_FAMILY_IPV4:
407      case G_SOCKET_FAMILY_IPV6:
408        socket->priv->family = address.ss_family;
409        switch (socket->priv->type)
410          {
411          case G_SOCKET_TYPE_STREAM:
412            socket->priv->protocol = G_SOCKET_PROTOCOL_TCP;
413            break;
414
415          case G_SOCKET_TYPE_DATAGRAM:
416            socket->priv->protocol = G_SOCKET_PROTOCOL_UDP;
417            break;
418
419          case G_SOCKET_TYPE_SEQPACKET:
420            socket->priv->protocol = G_SOCKET_PROTOCOL_SCTP;
421            break;
422
423          default:
424            break;
425          }
426        break;
427
428      case G_SOCKET_FAMILY_UNIX:
429        socket->priv->family = G_SOCKET_FAMILY_UNIX;
430        socket->priv->protocol = G_SOCKET_PROTOCOL_DEFAULT;
431        break;
432
433      default:
434        socket->priv->family = G_SOCKET_FAMILY_INVALID;
435        break;
436     }
437
438   if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
439     {
440       addrlen = sizeof address;
441       if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
442         socket->priv->connected = TRUE;
443     }
444
445   optlen = sizeof bool_val;
446   if (getsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
447                   (void *)&bool_val, &optlen) == 0)
448     {
449 #ifndef G_OS_WIN32
450       /* Experimentation indicates that the SO_KEEPALIVE value is
451        * actually a char on Windows, even if documentation claims it
452        * to be a BOOL which is a typedef for int. So this g_assert()
453        * fails. See bug #611756.
454        */
455       g_assert (optlen == sizeof bool_val);
456 #endif
457       socket->priv->keepalive = !!bool_val;
458     }
459   else
460     {
461       /* Can't read, maybe not supported, assume FALSE */
462       socket->priv->keepalive = FALSE;
463     }
464
465   return;
466
467  err:
468   g_set_error (&socket->priv->construct_error, G_IO_ERROR,
469                socket_io_error_from_errno (errsv),
470                _("creating GSocket from fd: %s"),
471                socket_strerror (errsv));
472 }
473
474 static gint
475 g_socket_create_socket (GSocketFamily   family,
476                         GSocketType     type,
477                         int             protocol,
478                         GError        **error)
479 {
480   gint native_type;
481   gint fd;
482
483   switch (type)
484     {
485      case G_SOCKET_TYPE_STREAM:
486       native_type = SOCK_STREAM;
487       break;
488
489      case G_SOCKET_TYPE_DATAGRAM:
490       native_type = SOCK_DGRAM;
491       break;
492
493      case G_SOCKET_TYPE_SEQPACKET:
494       native_type = SOCK_SEQPACKET;
495       break;
496
497      default:
498       g_assert_not_reached ();
499     }
500
501   if (protocol == -1)
502     {
503       g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
504                    _("Unable to create socket: %s"), _("Unknown protocol was specified"));
505       return -1;
506     }
507
508 #ifdef SOCK_CLOEXEC
509   fd = socket (family, native_type | SOCK_CLOEXEC, protocol);
510   /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
511   if (fd < 0 && errno == EINVAL)
512 #endif
513     fd = socket (family, native_type, protocol);
514
515   if (fd < 0)
516     {
517       int errsv = get_socket_errno ();
518
519       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
520                    _("Unable to create socket: %s"), socket_strerror (errsv));
521     }
522
523 #ifndef G_OS_WIN32
524   {
525     int flags;
526
527     /* We always want to set close-on-exec to protect users. If you
528        need to so some weird inheritance to exec you can re-enable this
529        using lower level hacks with g_socket_get_fd(). */
530     flags = fcntl (fd, F_GETFD, 0);
531     if (flags != -1 &&
532         (flags & FD_CLOEXEC) == 0)
533       {
534         flags |= FD_CLOEXEC;
535         fcntl (fd, F_SETFD, flags);
536       }
537   }
538 #endif
539
540   return fd;
541 }
542
543 static void
544 g_socket_constructed (GObject *object)
545 {
546   GSocket *socket = G_SOCKET (object);
547
548   if (socket->priv->fd >= 0)
549     /* create socket->priv info from the fd */
550     g_socket_details_from_fd (socket);
551
552   else
553     /* create the fd from socket->priv info */
554     socket->priv->fd = g_socket_create_socket (socket->priv->family,
555                                                socket->priv->type,
556                                                socket->priv->protocol,
557                                                &socket->priv->construct_error);
558
559   /* Always use native nonblocking sockets, as
560      windows sets sockets to nonblocking automatically
561      in certain operations. This way we make things work
562      the same on all platforms */
563   if (socket->priv->fd != -1)
564     set_fd_nonblocking (socket->priv->fd);
565 }
566
567 static void
568 g_socket_get_property (GObject    *object,
569                        guint       prop_id,
570                        GValue     *value,
571                        GParamSpec *pspec)
572 {
573   GSocket *socket = G_SOCKET (object);
574   GSocketAddress *address;
575
576   switch (prop_id)
577     {
578       case PROP_FAMILY:
579         g_value_set_enum (value, socket->priv->family);
580         break;
581
582       case PROP_TYPE:
583         g_value_set_enum (value, socket->priv->type);
584         break;
585
586       case PROP_PROTOCOL:
587         g_value_set_enum (value, socket->priv->protocol);
588         break;
589
590       case PROP_FD:
591         g_value_set_int (value, socket->priv->fd);
592         break;
593
594       case PROP_BLOCKING:
595         g_value_set_boolean (value, socket->priv->blocking);
596         break;
597
598       case PROP_LISTEN_BACKLOG:
599         g_value_set_int (value, socket->priv->listen_backlog);
600         break;
601
602       case PROP_KEEPALIVE:
603         g_value_set_boolean (value, socket->priv->keepalive);
604         break;
605
606       case PROP_LOCAL_ADDRESS:
607         address = g_socket_get_local_address (socket, NULL);
608         g_value_take_object (value, address);
609         break;
610
611       case PROP_REMOTE_ADDRESS:
612         address = g_socket_get_remote_address (socket, NULL);
613         g_value_take_object (value, address);
614         break;
615
616       case PROP_TIMEOUT:
617         g_value_set_uint (value, socket->priv->timeout);
618         break;
619
620       case PROP_TTL:
621         g_value_set_uint (value, g_socket_get_ttl (socket));
622         break;
623
624       case PROP_BROADCAST:
625         g_value_set_boolean (value, g_socket_get_broadcast (socket));
626         break;
627
628       case PROP_MULTICAST_LOOPBACK:
629         g_value_set_boolean (value, g_socket_get_multicast_loopback (socket));
630         break;
631
632       case PROP_MULTICAST_TTL:
633         g_value_set_uint (value, g_socket_get_multicast_ttl (socket));
634         break;
635
636       default:
637         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
638     }
639 }
640
641 static void
642 g_socket_set_property (GObject      *object,
643                        guint         prop_id,
644                        const GValue *value,
645                        GParamSpec   *pspec)
646 {
647   GSocket *socket = G_SOCKET (object);
648
649   switch (prop_id)
650     {
651       case PROP_FAMILY:
652         socket->priv->family = g_value_get_enum (value);
653         break;
654
655       case PROP_TYPE:
656         socket->priv->type = g_value_get_enum (value);
657         break;
658
659       case PROP_PROTOCOL:
660         socket->priv->protocol = g_value_get_enum (value);
661         break;
662
663       case PROP_FD:
664         socket->priv->fd = g_value_get_int (value);
665         break;
666
667       case PROP_BLOCKING:
668         g_socket_set_blocking (socket, g_value_get_boolean (value));
669         break;
670
671       case PROP_LISTEN_BACKLOG:
672         g_socket_set_listen_backlog (socket, g_value_get_int (value));
673         break;
674
675       case PROP_KEEPALIVE:
676         g_socket_set_keepalive (socket, g_value_get_boolean (value));
677         break;
678
679       case PROP_TIMEOUT:
680         g_socket_set_timeout (socket, g_value_get_uint (value));
681         break;
682
683       case PROP_TTL:
684         g_socket_set_ttl (socket, g_value_get_uint (value));
685         break;
686
687       case PROP_BROADCAST:
688         g_socket_set_broadcast (socket, g_value_get_boolean (value));
689         break;
690
691       case PROP_MULTICAST_LOOPBACK:
692         g_socket_set_multicast_loopback (socket, g_value_get_boolean (value));
693         break;
694
695       case PROP_MULTICAST_TTL:
696         g_socket_set_multicast_ttl (socket, g_value_get_uint (value));
697         break;
698
699       default:
700         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
701     }
702 }
703
704 static void
705 g_socket_finalize (GObject *object)
706 {
707   GSocket *socket = G_SOCKET (object);
708
709   g_clear_error (&socket->priv->construct_error);
710
711   if (socket->priv->fd != -1 &&
712       !socket->priv->closed)
713     g_socket_close (socket, NULL);
714
715   if (socket->priv->remote_address)
716     g_object_unref (socket->priv->remote_address);
717
718 #ifdef G_OS_WIN32
719   if (socket->priv->event != WSA_INVALID_EVENT)
720     {
721       WSACloseEvent (socket->priv->event);
722       socket->priv->event = WSA_INVALID_EVENT;
723     }
724
725   g_assert (socket->priv->requested_conditions == NULL);
726 #endif
727
728   if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
729     (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
730 }
731
732 static void
733 g_socket_class_init (GSocketClass *klass)
734 {
735   GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
736   volatile GType type;
737
738   /* Make sure winsock has been initialized */
739   type = g_inet_address_get_type ();
740   (type); /* To avoid -Wunused-but-set-variable */
741
742 #ifdef SIGPIPE
743   /* There is no portable, thread-safe way to avoid having the process
744    * be killed by SIGPIPE when calling send() or sendmsg(), so we are
745    * forced to simply ignore the signal process-wide.
746    */
747   signal (SIGPIPE, SIG_IGN);
748 #endif
749
750   g_type_class_add_private (klass, sizeof (GSocketPrivate));
751
752   gobject_class->finalize = g_socket_finalize;
753   gobject_class->constructed = g_socket_constructed;
754   gobject_class->set_property = g_socket_set_property;
755   gobject_class->get_property = g_socket_get_property;
756
757   g_object_class_install_property (gobject_class, PROP_FAMILY,
758                                    g_param_spec_enum ("family",
759                                                       P_("Socket family"),
760                                                       P_("The sockets address family"),
761                                                       G_TYPE_SOCKET_FAMILY,
762                                                       G_SOCKET_FAMILY_INVALID,
763                                                       G_PARAM_CONSTRUCT_ONLY |
764                                                       G_PARAM_READWRITE |
765                                                       G_PARAM_STATIC_STRINGS));
766
767   g_object_class_install_property (gobject_class, PROP_TYPE,
768                                    g_param_spec_enum ("type",
769                                                       P_("Socket type"),
770                                                       P_("The sockets type"),
771                                                       G_TYPE_SOCKET_TYPE,
772                                                       G_SOCKET_TYPE_STREAM,
773                                                       G_PARAM_CONSTRUCT_ONLY |
774                                                       G_PARAM_READWRITE |
775                                                       G_PARAM_STATIC_STRINGS));
776
777   g_object_class_install_property (gobject_class, PROP_PROTOCOL,
778                                    g_param_spec_enum ("protocol",
779                                                       P_("Socket protocol"),
780                                                       P_("The id of the protocol to use, or -1 for unknown"),
781                                                       G_TYPE_SOCKET_PROTOCOL,
782                                                       G_SOCKET_PROTOCOL_UNKNOWN,
783                                                       G_PARAM_CONSTRUCT_ONLY |
784                                                       G_PARAM_READWRITE |
785                                                       G_PARAM_STATIC_STRINGS));
786
787   g_object_class_install_property (gobject_class, PROP_FD,
788                                    g_param_spec_int ("fd",
789                                                      P_("File descriptor"),
790                                                      P_("The sockets file descriptor"),
791                                                      G_MININT,
792                                                      G_MAXINT,
793                                                      -1,
794                                                      G_PARAM_CONSTRUCT_ONLY |
795                                                      G_PARAM_READWRITE |
796                                                      G_PARAM_STATIC_STRINGS));
797
798   g_object_class_install_property (gobject_class, PROP_BLOCKING,
799                                    g_param_spec_boolean ("blocking",
800                                                          P_("blocking"),
801                                                          P_("Whether or not I/O on this socket is blocking"),
802                                                          TRUE,
803                                                          G_PARAM_READWRITE |
804                                                          G_PARAM_STATIC_STRINGS));
805
806   g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
807                                    g_param_spec_int ("listen-backlog",
808                                                      P_("Listen backlog"),
809                                                      P_("Outstanding connections in the listen queue"),
810                                                      0,
811                                                      SOMAXCONN,
812                                                      10,
813                                                      G_PARAM_READWRITE |
814                                                      G_PARAM_STATIC_STRINGS));
815
816   g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
817                                    g_param_spec_boolean ("keepalive",
818                                                          P_("Keep connection alive"),
819                                                          P_("Keep connection alive by sending periodic pings"),
820                                                          FALSE,
821                                                          G_PARAM_READWRITE |
822                                                          G_PARAM_STATIC_STRINGS));
823
824   g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
825                                    g_param_spec_object ("local-address",
826                                                         P_("Local address"),
827                                                         P_("The local address the socket is bound to"),
828                                                         G_TYPE_SOCKET_ADDRESS,
829                                                         G_PARAM_READABLE |
830                                                         G_PARAM_STATIC_STRINGS));
831
832   g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
833                                    g_param_spec_object ("remote-address",
834                                                         P_("Remote address"),
835                                                         P_("The remote address the socket is connected to"),
836                                                         G_TYPE_SOCKET_ADDRESS,
837                                                         G_PARAM_READABLE |
838                                                         G_PARAM_STATIC_STRINGS));
839
840   /**
841    * GSocket:timeout:
842    *
843    * The timeout in seconds on socket I/O
844    *
845    * Since: 2.26
846    */
847   g_object_class_install_property (gobject_class, PROP_TIMEOUT,
848                                    g_param_spec_uint ("timeout",
849                                                       P_("Timeout"),
850                                                       P_("The timeout in seconds on socket I/O"),
851                                                       0,
852                                                       G_MAXUINT,
853                                                       0,
854                                                       G_PARAM_READWRITE |
855                                                       G_PARAM_STATIC_STRINGS));
856
857   /**
858    * GSocket:broadcast:
859    *
860    * Whether the socket should allow sending to and receiving from broadcast addresses.
861    *
862    * Since: 2.32
863    */
864   g_object_class_install_property (gobject_class, PROP_BROADCAST,
865                                    g_param_spec_boolean ("broadcast",
866                                                          P_("Broadcast"),
867                                                          P_("Whether to allow sending to and receiving from broadcast addresses"),
868                                                          FALSE,
869                                                          G_PARAM_READWRITE |
870                                                          G_PARAM_STATIC_STRINGS));
871
872   /**
873    * GSocket:ttl:
874    *
875    * Time-to-live for outgoing unicast packets
876    *
877    * Since: 2.32
878    */
879   g_object_class_install_property (gobject_class, PROP_TTL,
880                                    g_param_spec_uint ("ttl",
881                                                       P_("TTL"),
882                                                       P_("Time-to-live of outgoing unicast packets"),
883                                                       0, G_MAXUINT, 0,
884                                                       G_PARAM_READWRITE |
885                                                       G_PARAM_STATIC_STRINGS));
886
887   /**
888    * GSocket:multicast-loopback:
889    *
890    * Whether outgoing multicast packets loop back to the local host.
891    *
892    * Since: 2.32
893    */
894   g_object_class_install_property (gobject_class, PROP_MULTICAST_LOOPBACK,
895                                    g_param_spec_boolean ("multicast-loopback",
896                                                          P_("Multicast loopback"),
897                                                          P_("Whether outgoing multicast packets loop back to the local host"),
898                                                          TRUE,
899                                                          G_PARAM_READWRITE |
900                                                          G_PARAM_STATIC_STRINGS));
901
902   /**
903    * GSocket:multicast-ttl:
904    *
905    * Time-to-live out outgoing multicast packets
906    *
907    * Since: 2.32
908    */
909   g_object_class_install_property (gobject_class, PROP_MULTICAST_TTL,
910                                    g_param_spec_uint ("multicast-ttl",
911                                                       P_("Multicast TTL"),
912                                                       P_("Time-to-live of outgoing multicast packets"),
913                                                       0, G_MAXUINT, 1,
914                                                       G_PARAM_READWRITE |
915                                                       G_PARAM_STATIC_STRINGS));
916 }
917
918 static void
919 g_socket_initable_iface_init (GInitableIface *iface)
920 {
921   iface->init = g_socket_initable_init;
922 }
923
924 static void
925 g_socket_init (GSocket *socket)
926 {
927   socket->priv = G_TYPE_INSTANCE_GET_PRIVATE (socket, G_TYPE_SOCKET, GSocketPrivate);
928
929   socket->priv->fd = -1;
930   socket->priv->blocking = TRUE;
931   socket->priv->listen_backlog = 10;
932   socket->priv->construct_error = NULL;
933 #ifdef G_OS_WIN32
934   socket->priv->event = WSA_INVALID_EVENT;
935 #endif
936 }
937
938 static gboolean
939 g_socket_initable_init (GInitable *initable,
940                         GCancellable *cancellable,
941                         GError  **error)
942 {
943   GSocket  *socket;
944
945   g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
946
947   socket = G_SOCKET (initable);
948
949   if (cancellable != NULL)
950     {
951       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
952                            _("Cancellable initialization not supported"));
953       return FALSE;
954     }
955
956   socket->priv->inited = TRUE;
957
958   if (socket->priv->construct_error)
959     {
960       if (error)
961         *error = g_error_copy (socket->priv->construct_error);
962       return FALSE;
963     }
964
965
966   return TRUE;
967 }
968
969 /**
970  * g_socket_new:
971  * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
972  * @type: the socket type to use.
973  * @protocol: the id of the protocol to use, or 0 for default.
974  * @error: #GError for error reporting, or %NULL to ignore.
975  *
976  * Creates a new #GSocket with the defined family, type and protocol.
977  * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
978  * for the family and type is used.
979  *
980  * The @protocol is a family and type specific int that specifies what
981  * kind of protocol to use. #GSocketProtocol lists several common ones.
982  * Many families only support one protocol, and use 0 for this, others
983  * support several and using 0 means to use the default protocol for
984  * the family and type.
985  *
986  * The protocol id is passed directly to the operating
987  * system, so you can use protocols not listed in #GSocketProtocol if you
988  * know the protocol number used for it.
989  *
990  * Returns: a #GSocket or %NULL on error.
991  *     Free the returned object with g_object_unref().
992  *
993  * Since: 2.22
994  */
995 GSocket *
996 g_socket_new (GSocketFamily     family,
997               GSocketType       type,
998               GSocketProtocol   protocol,
999               GError          **error)
1000 {
1001   return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1002                                    NULL, error,
1003                                    "family", family,
1004                                    "type", type,
1005                                    "protocol", protocol,
1006                                    NULL));
1007 }
1008
1009 /**
1010  * g_socket_new_from_fd:
1011  * @fd: a native socket file descriptor.
1012  * @error: #GError for error reporting, or %NULL to ignore.
1013  *
1014  * Creates a new #GSocket from a native file descriptor
1015  * or winsock SOCKET handle.
1016  *
1017  * This reads all the settings from the file descriptor so that
1018  * all properties should work. Note that the file descriptor
1019  * will be set to non-blocking mode, independent on the blocking
1020  * mode of the #GSocket.
1021  *
1022  * Returns: a #GSocket or %NULL on error.
1023  *     Free the returned object with g_object_unref().
1024  *
1025  * Since: 2.22
1026  */
1027 GSocket *
1028 g_socket_new_from_fd (gint     fd,
1029                       GError **error)
1030 {
1031   return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1032                                    NULL, error,
1033                                    "fd", fd,
1034                                    NULL));
1035 }
1036
1037 /**
1038  * g_socket_set_blocking:
1039  * @socket: a #GSocket.
1040  * @blocking: Whether to use blocking I/O or not.
1041  *
1042  * Sets the blocking mode of the socket. In blocking mode
1043  * all operations block until they succeed or there is an error. In
1044  * non-blocking mode all functions return results immediately or
1045  * with a %G_IO_ERROR_WOULD_BLOCK error.
1046  *
1047  * All sockets are created in blocking mode. However, note that the
1048  * platform level socket is always non-blocking, and blocking mode
1049  * is a GSocket level feature.
1050  *
1051  * Since: 2.22
1052  */
1053 void
1054 g_socket_set_blocking (GSocket  *socket,
1055                        gboolean  blocking)
1056 {
1057   g_return_if_fail (G_IS_SOCKET (socket));
1058
1059   blocking = !!blocking;
1060
1061   if (socket->priv->blocking == blocking)
1062     return;
1063
1064   socket->priv->blocking = blocking;
1065   g_object_notify (G_OBJECT (socket), "blocking");
1066 }
1067
1068 /**
1069  * g_socket_get_blocking:
1070  * @socket: a #GSocket.
1071  *
1072  * Gets the blocking mode of the socket. For details on blocking I/O,
1073  * see g_socket_set_blocking().
1074  *
1075  * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
1076  *
1077  * Since: 2.22
1078  */
1079 gboolean
1080 g_socket_get_blocking (GSocket *socket)
1081 {
1082   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1083
1084   return socket->priv->blocking;
1085 }
1086
1087 /**
1088  * g_socket_set_keepalive:
1089  * @socket: a #GSocket.
1090  * @keepalive: Value for the keepalive flag
1091  *
1092  * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
1093  * this flag is set on a socket, the system will attempt to verify that the
1094  * remote socket endpoint is still present if a sufficiently long period of
1095  * time passes with no data being exchanged. If the system is unable to
1096  * verify the presence of the remote endpoint, it will automatically close
1097  * the connection.
1098  *
1099  * This option is only functional on certain kinds of sockets. (Notably,
1100  * %G_SOCKET_PROTOCOL_TCP sockets.)
1101  *
1102  * The exact time between pings is system- and protocol-dependent, but will
1103  * normally be at least two hours. Most commonly, you would set this flag
1104  * on a server socket if you want to allow clients to remain idle for long
1105  * periods of time, but also want to ensure that connections are eventually
1106  * garbage-collected if clients crash or become unreachable.
1107  *
1108  * Since: 2.22
1109  */
1110 void
1111 g_socket_set_keepalive (GSocket  *socket,
1112                         gboolean  keepalive)
1113 {
1114   int value;
1115
1116   g_return_if_fail (G_IS_SOCKET (socket));
1117
1118   keepalive = !!keepalive;
1119   if (socket->priv->keepalive == keepalive)
1120     return;
1121
1122   value = (gint) keepalive;
1123   if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_KEEPALIVE,
1124                   (gpointer) &value, sizeof (value)) < 0)
1125     {
1126       int errsv = get_socket_errno ();
1127       g_warning ("error setting keepalive: %s", socket_strerror (errsv));
1128       return;
1129     }
1130
1131   socket->priv->keepalive = keepalive;
1132   g_object_notify (G_OBJECT (socket), "keepalive");
1133 }
1134
1135 /**
1136  * g_socket_get_keepalive:
1137  * @socket: a #GSocket.
1138  *
1139  * Gets the keepalive mode of the socket. For details on this,
1140  * see g_socket_set_keepalive().
1141  *
1142  * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1143  *
1144  * Since: 2.22
1145  */
1146 gboolean
1147 g_socket_get_keepalive (GSocket *socket)
1148 {
1149   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1150
1151   return socket->priv->keepalive;
1152 }
1153
1154 /**
1155  * g_socket_get_listen_backlog:
1156  * @socket: a #GSocket.
1157  *
1158  * Gets the listen backlog setting of the socket. For details on this,
1159  * see g_socket_set_listen_backlog().
1160  *
1161  * Returns: the maximum number of pending connections.
1162  *
1163  * Since: 2.22
1164  */
1165 gint
1166 g_socket_get_listen_backlog  (GSocket *socket)
1167 {
1168   g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1169
1170   return socket->priv->listen_backlog;
1171 }
1172
1173 /**
1174  * g_socket_set_listen_backlog:
1175  * @socket: a #GSocket.
1176  * @backlog: the maximum number of pending connections.
1177  *
1178  * Sets the maximum number of outstanding connections allowed
1179  * when listening on this socket. If more clients than this are
1180  * connecting to the socket and the application is not handling them
1181  * on time then the new connections will be refused.
1182  *
1183  * Note that this must be called before g_socket_listen() and has no
1184  * effect if called after that.
1185  *
1186  * Since: 2.22
1187  */
1188 void
1189 g_socket_set_listen_backlog (GSocket *socket,
1190                              gint     backlog)
1191 {
1192   g_return_if_fail (G_IS_SOCKET (socket));
1193   g_return_if_fail (!socket->priv->listening);
1194
1195   if (backlog != socket->priv->listen_backlog)
1196     {
1197       socket->priv->listen_backlog = backlog;
1198       g_object_notify (G_OBJECT (socket), "listen-backlog");
1199     }
1200 }
1201
1202 /**
1203  * g_socket_get_timeout:
1204  * @socket: a #GSocket.
1205  *
1206  * Gets the timeout setting of the socket. For details on this, see
1207  * g_socket_set_timeout().
1208  *
1209  * Returns: the timeout in seconds
1210  *
1211  * Since: 2.26
1212  */
1213 guint
1214 g_socket_get_timeout (GSocket *socket)
1215 {
1216   g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1217
1218   return socket->priv->timeout;
1219 }
1220
1221 /**
1222  * g_socket_set_timeout:
1223  * @socket: a #GSocket.
1224  * @timeout: the timeout for @socket, in seconds, or 0 for none
1225  *
1226  * Sets the time in seconds after which I/O operations on @socket will
1227  * time out if they have not yet completed.
1228  *
1229  * On a blocking socket, this means that any blocking #GSocket
1230  * operation will time out after @timeout seconds of inactivity,
1231  * returning %G_IO_ERROR_TIMED_OUT.
1232  *
1233  * On a non-blocking socket, calls to g_socket_condition_wait() will
1234  * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1235  * created with g_socket_create_source() will trigger after
1236  * @timeout seconds of inactivity, with the requested condition
1237  * set, at which point calling g_socket_receive(), g_socket_send(),
1238  * g_socket_check_connect_result(), etc, will fail with
1239  * %G_IO_ERROR_TIMED_OUT.
1240  *
1241  * If @timeout is 0 (the default), operations will never time out
1242  * on their own.
1243  *
1244  * Note that if an I/O operation is interrupted by a signal, this may
1245  * cause the timeout to be reset.
1246  *
1247  * Since: 2.26
1248  */
1249 void
1250 g_socket_set_timeout (GSocket *socket,
1251                       guint    timeout)
1252 {
1253   g_return_if_fail (G_IS_SOCKET (socket));
1254
1255   if (timeout != socket->priv->timeout)
1256     {
1257       socket->priv->timeout = timeout;
1258       g_object_notify (G_OBJECT (socket), "timeout");
1259     }
1260 }
1261
1262 /**
1263  * g_socket_get_ttl:
1264  * @socket: a #GSocket.
1265  *
1266  * Gets the unicast time-to-live setting on @socket; see
1267  * g_socket_set_ttl() for more details.
1268  *
1269  * Returns: the time-to-live setting on @socket
1270  *
1271  * Since: 2.32
1272  */
1273 guint
1274 g_socket_get_ttl (GSocket *socket)
1275 {
1276   int result;
1277   guint value, optlen;
1278
1279   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1280
1281   if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1282     {
1283       guchar optval;
1284
1285       optlen = sizeof (optval);
1286       result = getsockopt (socket->priv->fd, IPPROTO_IP, IP_TTL,
1287                            &optval, &optlen);
1288       value = optval;
1289     }
1290   else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1291     {
1292       optlen = sizeof (value);
1293       result = getsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1294                            &value, &optlen);
1295     }
1296   else
1297     g_return_val_if_reached (FALSE);
1298
1299   if (result < 0)
1300     {
1301       int errsv = get_socket_errno ();
1302       g_warning ("error getting unicast ttl: %s", socket_strerror (errsv));
1303       return FALSE;
1304     }
1305
1306   return value;
1307 }
1308
1309 /**
1310  * g_socket_set_ttl:
1311  * @socket: a #GSocket.
1312  * @ttl: the time-to-live value for all unicast packets on @socket
1313  *
1314  * Sets the time-to-live for outgoing unicast packets on @socket.
1315  * By default the platform-specific default value is used.
1316  *
1317  * Since: 2.32
1318  */
1319 void
1320 g_socket_set_ttl (GSocket  *socket,
1321                   guint     ttl)
1322 {
1323   int result;
1324
1325   g_return_if_fail (G_IS_SOCKET (socket));
1326
1327   if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1328     {
1329       guchar optval = (guchar)ttl;
1330
1331       result = setsockopt (socket->priv->fd, IPPROTO_IP, IP_TTL,
1332                            &optval, sizeof (optval));
1333     }
1334   else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1335     {
1336       result = setsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1337                            &ttl, sizeof (ttl));
1338     }
1339   else
1340     g_return_if_reached ();
1341
1342   if (result < 0)
1343     {
1344       int errsv = get_socket_errno ();
1345       g_warning ("error setting unicast ttl: %s", socket_strerror (errsv));
1346       return;
1347     }
1348
1349   g_object_notify (G_OBJECT (socket), "ttl");
1350 }
1351
1352 /**
1353  * g_socket_get_broadcast:
1354  * @socket: a #GSocket.
1355  *
1356  * Gets the broadcast setting on @socket; if %TRUE,
1357  * it is possible to send packets to broadcast
1358  * addresses or receive from broadcast addresses.
1359  *
1360  * Returns: the broadcast setting on @socket
1361  *
1362  * Since: 2.32
1363  */
1364 gboolean
1365 g_socket_get_broadcast (GSocket *socket)
1366 {
1367   int result;
1368   guint value = 0, optlen;
1369
1370   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1371
1372   optlen = sizeof (guchar);
1373   result = getsockopt (socket->priv->fd, SOL_SOCKET, SO_BROADCAST,
1374                        &value, &optlen);
1375
1376   if (result < 0)
1377     {
1378       int errsv = get_socket_errno ();
1379       g_warning ("error getting broadcast: %s", socket_strerror (errsv));
1380       return FALSE;
1381     }
1382
1383   return !!value;
1384 }
1385
1386 /**
1387  * g_socket_set_broadcast:
1388  * @socket: a #GSocket.
1389  * @loopback: whether @socket should allow sending to and receiving
1390  *     from broadcast addresses
1391  *
1392  * Sets whether @socket should allow sending to and receiving from
1393  * broadcast addresses. This is %FALSE by default.
1394  *
1395  * Since: 2.32
1396  */
1397 void
1398 g_socket_set_broadcast (GSocket    *socket,
1399                         gboolean    broadcast)
1400 {
1401   int result;
1402   guchar value;
1403
1404   g_return_if_fail (G_IS_SOCKET (socket));
1405
1406   broadcast = !!broadcast;
1407   value = (guchar)broadcast;
1408
1409   result = setsockopt (socket->priv->fd, SOL_SOCKET, SO_BROADCAST,
1410                        &value, sizeof (value));
1411
1412   if (result < 0)
1413     {
1414       int errsv = get_socket_errno ();
1415       g_warning ("error setting broadcast: %s", socket_strerror (errsv));
1416       return;
1417     }
1418
1419   g_object_notify (G_OBJECT (socket), "broadcast");
1420 }
1421
1422 /**
1423  * g_socket_get_multicast_loopback:
1424  * @socket: a #GSocket.
1425  *
1426  * Gets the multicast loopback setting on @socket; if %TRUE (the
1427  * default), outgoing multicast packets will be looped back to
1428  * multicast listeners on the same host.
1429  *
1430  * Returns: the multicast loopback setting on @socket
1431  *
1432  * Since: 2.32
1433  */
1434 gboolean
1435 g_socket_get_multicast_loopback (GSocket *socket)
1436 {
1437   int result;
1438   guint value = 0, optlen;
1439
1440   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1441
1442   if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1443     {
1444       optlen = sizeof (guchar);
1445       result = getsockopt (socket->priv->fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1446                            &value, &optlen);
1447     }
1448   else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1449     {
1450       optlen = sizeof (guint);
1451       result = getsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1452                            &value, &optlen);
1453     }
1454   else
1455     g_return_val_if_reached (FALSE);
1456
1457   if (result < 0)
1458     {
1459       int errsv = get_socket_errno ();
1460       g_warning ("error getting multicast loopback: %s", socket_strerror (errsv));
1461       return FALSE;
1462     }
1463
1464   return !!value;
1465 }
1466
1467 /**
1468  * g_socket_set_multicast_loopback:
1469  * @socket: a #GSocket.
1470  * @loopback: whether @socket should receive messages sent to its
1471  *   multicast groups from the local host
1472  *
1473  * Sets whether outgoing multicast packets will be received by sockets
1474  * listening on that multicast address on the same host. This is %TRUE
1475  * by default.
1476  *
1477  * Since: 2.32
1478  */
1479 void
1480 g_socket_set_multicast_loopback (GSocket    *socket,
1481                                  gboolean    loopback)
1482 {
1483   int result;
1484
1485   g_return_if_fail (G_IS_SOCKET (socket));
1486
1487   loopback = !!loopback;
1488
1489   if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1490     {
1491       guchar value = (guchar)loopback;
1492
1493       result = setsockopt (socket->priv->fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1494                            &value, sizeof (value));
1495     }
1496   else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1497     {
1498       guint value = (guint)loopback;
1499
1500       result = setsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1501                            &value, sizeof (value));
1502     }
1503   else
1504     g_return_if_reached ();
1505
1506   if (result < 0)
1507     {
1508       int errsv = get_socket_errno ();
1509       g_warning ("error setting multicast loopback: %s", socket_strerror (errsv));
1510       return;
1511     }
1512
1513   g_object_notify (G_OBJECT (socket), "multicast-loopback");
1514 }
1515
1516 /**
1517  * g_socket_get_multicast_ttl:
1518  * @socket: a #GSocket.
1519  *
1520  * Gets the multicast time-to-live setting on @socket; see
1521  * g_socket_set_multicast_ttl() for more details.
1522  *
1523  * Returns: the multicast time-to-live setting on @socket
1524  *
1525  * Since: 2.32
1526  */
1527 guint
1528 g_socket_get_multicast_ttl (GSocket *socket)
1529 {
1530   int result;
1531   guint value, optlen;
1532
1533   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1534
1535   if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1536     {
1537       guchar optval;
1538
1539       optlen = sizeof (optval);
1540       result = getsockopt (socket->priv->fd, IPPROTO_IP, IP_MULTICAST_TTL,
1541                            &optval, &optlen);
1542       value = optval;
1543     }
1544   else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1545     {
1546       optlen = sizeof (value);
1547       result = getsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1548                            &value, &optlen);
1549     }
1550   else
1551     g_return_val_if_reached (FALSE);
1552
1553   if (result < 0)
1554     {
1555       int errsv = get_socket_errno ();
1556       g_warning ("error getting multicast ttl: %s", socket_strerror (errsv));
1557       return FALSE;
1558     }
1559
1560   return value;
1561 }
1562
1563 /**
1564  * g_socket_set_multicast_ttl:
1565  * @socket: a #GSocket.
1566  * @ttl: the time-to-live value for all multicast datagrams on @socket
1567  *
1568  * Sets the time-to-live for outgoing multicast datagrams on @socket.
1569  * By default, this is 1, meaning that multicast packets will not leave
1570  * the local network.
1571  *
1572  * Since: 2.32
1573  */
1574 void
1575 g_socket_set_multicast_ttl (GSocket  *socket,
1576                             guint     ttl)
1577 {
1578   int result;
1579
1580   g_return_if_fail (G_IS_SOCKET (socket));
1581
1582   if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1583     {
1584       guchar optval = (guchar)ttl;
1585
1586       result = setsockopt (socket->priv->fd, IPPROTO_IP, IP_MULTICAST_TTL,
1587                            &optval, sizeof (optval));
1588     }
1589   else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1590     {
1591       result = setsockopt (socket->priv->fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1592                            &ttl, sizeof (ttl));
1593     }
1594   else
1595     g_return_if_reached ();
1596
1597   if (result < 0)
1598     {
1599       int errsv = get_socket_errno ();
1600       g_warning ("error setting multicast ttl: %s", socket_strerror (errsv));
1601       return;
1602     }
1603
1604   g_object_notify (G_OBJECT (socket), "multicast-ttl");
1605 }
1606
1607 /**
1608  * g_socket_get_family:
1609  * @socket: a #GSocket.
1610  *
1611  * Gets the socket family of the socket.
1612  *
1613  * Returns: a #GSocketFamily
1614  *
1615  * Since: 2.22
1616  */
1617 GSocketFamily
1618 g_socket_get_family (GSocket *socket)
1619 {
1620   g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1621
1622   return socket->priv->family;
1623 }
1624
1625 /**
1626  * g_socket_get_socket_type:
1627  * @socket: a #GSocket.
1628  *
1629  * Gets the socket type of the socket.
1630  *
1631  * Returns: a #GSocketType
1632  *
1633  * Since: 2.22
1634  */
1635 GSocketType
1636 g_socket_get_socket_type (GSocket *socket)
1637 {
1638   g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1639
1640   return socket->priv->type;
1641 }
1642
1643 /**
1644  * g_socket_get_protocol:
1645  * @socket: a #GSocket.
1646  *
1647  * Gets the socket protocol id the socket was created with.
1648  * In case the protocol is unknown, -1 is returned.
1649  *
1650  * Returns: a protocol id, or -1 if unknown
1651  *
1652  * Since: 2.22
1653  */
1654 GSocketProtocol
1655 g_socket_get_protocol (GSocket *socket)
1656 {
1657   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1658
1659   return socket->priv->protocol;
1660 }
1661
1662 /**
1663  * g_socket_get_fd:
1664  * @socket: a #GSocket.
1665  *
1666  * Returns the underlying OS socket object. On unix this
1667  * is a socket file descriptor, and on windows this is
1668  * a Winsock2 SOCKET handle. This may be useful for
1669  * doing platform specific or otherwise unusual operations
1670  * on the socket.
1671  *
1672  * Returns: the file descriptor of the socket.
1673  *
1674  * Since: 2.22
1675  */
1676 int
1677 g_socket_get_fd (GSocket *socket)
1678 {
1679   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1680
1681   return socket->priv->fd;
1682 }
1683
1684 /**
1685  * g_socket_get_local_address:
1686  * @socket: a #GSocket.
1687  * @error: #GError for error reporting, or %NULL to ignore.
1688  *
1689  * Try to get the local address of a bound socket. This is only
1690  * useful if the socket has been bound to a local address,
1691  * either explicitly or implicitly when connecting.
1692  *
1693  * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1694  *     Free the returned object with g_object_unref().
1695  *
1696  * Since: 2.22
1697  */
1698 GSocketAddress *
1699 g_socket_get_local_address (GSocket  *socket,
1700                             GError  **error)
1701 {
1702   struct sockaddr_storage buffer;
1703   guint32 len = sizeof (buffer);
1704
1705   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1706
1707   if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1708     {
1709       int errsv = get_socket_errno ();
1710       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1711                    _("could not get local address: %s"), socket_strerror (errsv));
1712       return NULL;
1713     }
1714
1715   return g_socket_address_new_from_native (&buffer, len);
1716 }
1717
1718 /**
1719  * g_socket_get_remote_address:
1720  * @socket: a #GSocket.
1721  * @error: #GError for error reporting, or %NULL to ignore.
1722  *
1723  * Try to get the remove address of a connected socket. This is only
1724  * useful for connection oriented sockets that have been connected.
1725  *
1726  * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1727  *     Free the returned object with g_object_unref().
1728  *
1729  * Since: 2.22
1730  */
1731 GSocketAddress *
1732 g_socket_get_remote_address (GSocket  *socket,
1733                              GError  **error)
1734 {
1735   struct sockaddr_storage buffer;
1736   guint32 len = sizeof (buffer);
1737
1738   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1739
1740   if (socket->priv->connect_pending)
1741     {
1742       if (!g_socket_check_connect_result (socket, error))
1743         return NULL;
1744       else
1745         socket->priv->connect_pending = FALSE;
1746     }
1747
1748   if (!socket->priv->remote_address)
1749     {
1750       if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1751         {
1752           int errsv = get_socket_errno ();
1753           g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1754                        _("could not get remote address: %s"), socket_strerror (errsv));
1755           return NULL;
1756         }
1757
1758       socket->priv->remote_address = g_socket_address_new_from_native (&buffer, len);
1759     }
1760
1761   return g_object_ref (socket->priv->remote_address);
1762 }
1763
1764 /**
1765  * g_socket_is_connected:
1766  * @socket: a #GSocket.
1767  *
1768  * Check whether the socket is connected. This is only useful for
1769  * connection-oriented sockets.
1770  *
1771  * Returns: %TRUE if socket is connected, %FALSE otherwise.
1772  *
1773  * Since: 2.22
1774  */
1775 gboolean
1776 g_socket_is_connected (GSocket *socket)
1777 {
1778   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1779
1780   return socket->priv->connected;
1781 }
1782
1783 /**
1784  * g_socket_listen:
1785  * @socket: a #GSocket.
1786  * @error: #GError for error reporting, or %NULL to ignore.
1787  *
1788  * Marks the socket as a server socket, i.e. a socket that is used
1789  * to accept incoming requests using g_socket_accept().
1790  *
1791  * Before calling this the socket must be bound to a local address using
1792  * g_socket_bind().
1793  *
1794  * To set the maximum amount of outstanding clients, use
1795  * g_socket_set_listen_backlog().
1796  *
1797  * Returns: %TRUE on success, %FALSE on error.
1798  *
1799  * Since: 2.22
1800  */
1801 gboolean
1802 g_socket_listen (GSocket  *socket,
1803                  GError  **error)
1804 {
1805   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1806
1807   if (!check_socket (socket, error))
1808     return FALSE;
1809
1810   if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1811     {
1812       int errsv = get_socket_errno ();
1813
1814       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1815                    _("could not listen: %s"), socket_strerror (errsv));
1816       return FALSE;
1817     }
1818
1819   socket->priv->listening = TRUE;
1820
1821   return TRUE;
1822 }
1823
1824 /**
1825  * g_socket_bind:
1826  * @socket: a #GSocket.
1827  * @address: a #GSocketAddress specifying the local address.
1828  * @allow_reuse: whether to allow reusing this address
1829  * @error: #GError for error reporting, or %NULL to ignore.
1830  *
1831  * When a socket is created it is attached to an address family, but it
1832  * doesn't have an address in this family. g_socket_bind() assigns the
1833  * address (sometimes called name) of the socket.
1834  *
1835  * It is generally required to bind to a local address before you can
1836  * receive connections. (See g_socket_listen() and g_socket_accept() ).
1837  * In certain situations, you may also want to bind a socket that will be
1838  * used to initiate connections, though this is not normally required.
1839  *
1840  * @allow_reuse should be %TRUE for server sockets (sockets that you will
1841  * eventually call g_socket_accept() on), and %FALSE for client sockets.
1842  * (Specifically, if it is %TRUE, then g_socket_bind() will set the
1843  * %SO_REUSEADDR flag on the socket, allowing it to bind @address even if
1844  * that address was previously used by another socket that has not yet been
1845  * fully cleaned-up by the kernel. Failing to set this flag on a server
1846  * socket may cause the bind call to return %G_IO_ERROR_ADDRESS_IN_USE if
1847  * the server program is stopped and then immediately restarted.)
1848  *
1849  * Returns: %TRUE on success, %FALSE on error.
1850  *
1851  * Since: 2.22
1852  */
1853 gboolean
1854 g_socket_bind (GSocket         *socket,
1855                GSocketAddress  *address,
1856                gboolean         reuse_address,
1857                GError         **error)
1858 {
1859   struct sockaddr_storage addr;
1860
1861   g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1862
1863   if (!check_socket (socket, error))
1864     return FALSE;
1865
1866   /* SO_REUSEADDR on windows means something else and is not what we want.
1867      It always allows the unix variant of SO_REUSEADDR anyway */
1868 #ifndef G_OS_WIN32
1869   {
1870     int value;
1871
1872     value = (int) !!reuse_address;
1873     /* Ignore errors here, the only likely error is "not supported", and
1874        this is a "best effort" thing mainly */
1875     setsockopt (socket->priv->fd, SOL_SOCKET, SO_REUSEADDR,
1876                 (gpointer) &value, sizeof (value));
1877   }
1878 #endif
1879
1880   if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1881     return FALSE;
1882
1883   if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1884             g_socket_address_get_native_size (address)) < 0)
1885     {
1886       int errsv = get_socket_errno ();
1887       g_set_error (error,
1888                    G_IO_ERROR, socket_io_error_from_errno (errsv),
1889                    _("Error binding to address: %s"), socket_strerror (errsv));
1890       return FALSE;
1891     }
1892
1893   return TRUE;
1894 }
1895
1896 static gboolean
1897 g_socket_multicast_group_operation (GSocket       *socket,
1898                                     GInetAddress  *group,
1899                                     gboolean       source_specific,
1900                                     const gchar   *interface,
1901                                     gboolean       join_group,
1902                                     GError       **error)
1903 {
1904   const guint8 *native_addr;
1905   gint optname, result;
1906
1907   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1908   g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
1909   g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
1910   g_return_val_if_fail (g_inet_address_get_family (group) == socket->priv->family, FALSE);
1911
1912   if (!check_socket (socket, error))
1913     return FALSE;
1914
1915   native_addr = g_inet_address_to_bytes (group);
1916   if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1917     {
1918 #ifdef HAVE_IP_MREQN
1919       struct ip_mreqn mc_req;
1920 #else
1921       struct ip_mreq mc_req;
1922 #endif
1923
1924       memcpy (&mc_req.imr_multiaddr, native_addr, sizeof (struct in_addr));
1925
1926 #ifdef HAVE_IP_MREQN
1927       if (interface)
1928         mc_req.imr_ifindex = if_nametoindex (interface);
1929       else
1930         mc_req.imr_ifindex = 0;  /* Pick any.  */
1931 #else
1932       mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
1933 #endif
1934
1935       if (source_specific)
1936         optname = join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
1937       else
1938         optname = join_group ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP;
1939       result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
1940                            &mc_req, sizeof (mc_req));
1941     }
1942   else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1943     {
1944       struct ipv6_mreq mc_req_ipv6;
1945
1946       memcpy (&mc_req_ipv6.ipv6mr_multiaddr, native_addr, sizeof (struct in6_addr));
1947       if (interface)
1948         mc_req_ipv6.ipv6mr_interface = if_nametoindex (interface);
1949       else
1950         mc_req_ipv6.ipv6mr_interface = 0;
1951
1952       optname = join_group ? IPV6_ADD_MEMBERSHIP : IPV6_DROP_MEMBERSHIP;
1953       result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
1954                            &mc_req_ipv6, sizeof (mc_req_ipv6));
1955     }
1956   else
1957     g_return_val_if_reached (FALSE);
1958
1959   if (result < 0)
1960     {
1961       int errsv = get_socket_errno ();
1962
1963       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1964                    join_group ?
1965                    _("Error joining multicast group: %s") :
1966                    _("Error leaving multicast group: %s"),
1967                    socket_strerror (errsv));
1968       return FALSE;
1969     }
1970
1971   return TRUE;
1972 }
1973
1974 /**
1975  * g_socket_join_multicast_group:
1976  * @socket: a #GSocket.
1977  * @group: a #GInetAddress specifying the group address to join.
1978  * @interface: Interface to use
1979  * @source_specific: %TRUE if source-specific multicast should be used
1980  * @error: #GError for error reporting, or %NULL to ignore.
1981  *
1982  * Registers @socket to receive multicast messages sent to @group.
1983  * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
1984  * been bound to an appropriate interface and port with
1985  * g_socket_bind().
1986  *
1987  * If @source_specific is %TRUE, source-specific multicast as defined
1988  * in RFC 4604 is used.
1989  *
1990  * Returns: %TRUE on success, %FALSE on error.
1991  *
1992  * Since: 2.32
1993  */
1994 gboolean
1995 g_socket_join_multicast_group (GSocket       *socket,
1996                                GInetAddress  *group,
1997                                gboolean       source_specific,
1998                                const gchar   *interface,
1999                                GError       **error)
2000 {
2001   return g_socket_multicast_group_operation (socket, group, source_specific, interface, TRUE, error);
2002 }
2003
2004 /**
2005  * g_socket_leave_multicast_group:
2006  * @socket: a #GSocket.
2007  * @group: a #GInetAddress specifying the group address to leave.
2008  * @interface: Interface to use
2009  * @source_specific: %TRUE if source-specific multicast should be used
2010  * @error: #GError for error reporting, or %NULL to ignore.
2011  *
2012  * Removes @socket from the multicast group @group (while still
2013  * allowing it to receive unicast messages).
2014  *
2015  * If @source_specific is %TRUE, source-specific multicast as defined
2016  * in RFC 4604 is used.
2017  *
2018  * Returns: %TRUE on success, %FALSE on error.
2019  *
2020  * Since: 2.32
2021  */
2022 gboolean
2023 g_socket_leave_multicast_group (GSocket       *socket,
2024                                 GInetAddress  *group,
2025                                 gboolean       source_specific,
2026                                 const gchar   *interface,
2027                                 GError       **error)
2028 {
2029   return g_socket_multicast_group_operation (socket, group, source_specific, interface, FALSE, error);
2030 }
2031
2032 /**
2033  * g_socket_speaks_ipv4:
2034  * @socket: a #GSocket
2035  *
2036  * Checks if a socket is capable of speaking IPv4.
2037  *
2038  * IPv4 sockets are capable of speaking IPv4.  On some operating systems
2039  * and under some combinations of circumstances IPv6 sockets are also
2040  * capable of speaking IPv4.  See RFC 3493 section 3.7 for more
2041  * information.
2042  *
2043  * No other types of sockets are currently considered as being capable
2044  * of speaking IPv4.
2045  *
2046  * Returns: %TRUE if this socket can be used with IPv4.
2047  *
2048  * Since: 2.22
2049  **/
2050 gboolean
2051 g_socket_speaks_ipv4 (GSocket *socket)
2052 {
2053   switch (socket->priv->family)
2054     {
2055     case G_SOCKET_FAMILY_IPV4:
2056       return TRUE;
2057
2058     case G_SOCKET_FAMILY_IPV6:
2059 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
2060       {
2061         guint sizeof_int = sizeof (int);
2062         gint v6_only;
2063
2064         if (getsockopt (socket->priv->fd,
2065                         IPPROTO_IPV6, IPV6_V6ONLY,
2066                         &v6_only, &sizeof_int) != 0)
2067           return FALSE;
2068
2069         return !v6_only;
2070       }
2071 #else
2072       return FALSE;
2073 #endif
2074
2075     default:
2076       return FALSE;
2077     }
2078 }
2079
2080 /**
2081  * g_socket_accept:
2082  * @socket: a #GSocket.
2083  * @cancellable: (allow-none): a %GCancellable or %NULL
2084  * @error: #GError for error reporting, or %NULL to ignore.
2085  *
2086  * Accept incoming connections on a connection-based socket. This removes
2087  * the first outstanding connection request from the listening socket and
2088  * creates a #GSocket object for it.
2089  *
2090  * The @socket must be bound to a local address with g_socket_bind() and
2091  * must be listening for incoming connections (g_socket_listen()).
2092  *
2093  * If there are no outstanding connections then the operation will block
2094  * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
2095  * To be notified of an incoming connection, wait for the %G_IO_IN condition.
2096  *
2097  * Returns: (transfer full): a new #GSocket, or %NULL on error.
2098  *     Free the returned object with g_object_unref().
2099  *
2100  * Since: 2.22
2101  */
2102 GSocket *
2103 g_socket_accept (GSocket       *socket,
2104                  GCancellable  *cancellable,
2105                  GError       **error)
2106 {
2107   GSocket *new_socket;
2108   gint ret;
2109
2110   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
2111
2112   if (!check_socket (socket, error))
2113     return NULL;
2114
2115   while (TRUE)
2116     {
2117       if (socket->priv->blocking &&
2118           !g_socket_condition_wait (socket,
2119                                     G_IO_IN, cancellable, error))
2120         return NULL;
2121
2122       if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
2123         {
2124           int errsv = get_socket_errno ();
2125
2126           win32_unset_event_mask (socket, FD_ACCEPT);
2127
2128           if (errsv == EINTR)
2129             continue;
2130
2131           if (socket->priv->blocking)
2132             {
2133 #ifdef WSAEWOULDBLOCK
2134               if (errsv == WSAEWOULDBLOCK)
2135                 continue;
2136 #else
2137               if (errsv == EWOULDBLOCK ||
2138                   errsv == EAGAIN)
2139                 continue;
2140 #endif
2141             }
2142
2143           g_set_error (error, G_IO_ERROR,
2144                        socket_io_error_from_errno (errsv),
2145                        _("Error accepting connection: %s"), socket_strerror (errsv));
2146           return NULL;
2147         }
2148       break;
2149     }
2150
2151   win32_unset_event_mask (socket, FD_ACCEPT);
2152
2153 #ifdef G_OS_WIN32
2154   {
2155     /* The socket inherits the accepting sockets event mask and even object,
2156        we need to remove that */
2157     WSAEventSelect (ret, NULL, 0);
2158   }
2159 #else
2160   {
2161     int flags;
2162
2163     /* We always want to set close-on-exec to protect users. If you
2164        need to so some weird inheritance to exec you can re-enable this
2165        using lower level hacks with g_socket_get_fd(). */
2166     flags = fcntl (ret, F_GETFD, 0);
2167     if (flags != -1 &&
2168         (flags & FD_CLOEXEC) == 0)
2169       {
2170         flags |= FD_CLOEXEC;
2171         fcntl (ret, F_SETFD, flags);
2172       }
2173   }
2174 #endif
2175
2176   new_socket = g_socket_new_from_fd (ret, error);
2177   if (new_socket == NULL)
2178     {
2179 #ifdef G_OS_WIN32
2180       closesocket (ret);
2181 #else
2182       close (ret);
2183 #endif
2184     }
2185   else
2186     new_socket->priv->protocol = socket->priv->protocol;
2187
2188   return new_socket;
2189 }
2190
2191 /**
2192  * g_socket_connect:
2193  * @socket: a #GSocket.
2194  * @address: a #GSocketAddress specifying the remote address.
2195  * @cancellable: (allow-none): a %GCancellable or %NULL
2196  * @error: #GError for error reporting, or %NULL to ignore.
2197  *
2198  * Connect the socket to the specified remote address.
2199  *
2200  * For connection oriented socket this generally means we attempt to make
2201  * a connection to the @address. For a connection-less socket it sets
2202  * the default address for g_socket_send() and discards all incoming datagrams
2203  * from other sources.
2204  *
2205  * Generally connection oriented sockets can only connect once, but
2206  * connection-less sockets can connect multiple times to change the
2207  * default address.
2208  *
2209  * If the connect call needs to do network I/O it will block, unless
2210  * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
2211  * and the user can be notified of the connection finishing by waiting
2212  * for the G_IO_OUT condition. The result of the connection must then be
2213  * checked with g_socket_check_connect_result().
2214  *
2215  * Returns: %TRUE if connected, %FALSE on error.
2216  *
2217  * Since: 2.22
2218  */
2219 gboolean
2220 g_socket_connect (GSocket         *socket,
2221                   GSocketAddress  *address,
2222                   GCancellable    *cancellable,
2223                   GError         **error)
2224 {
2225   struct sockaddr_storage buffer;
2226
2227   g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2228
2229   if (!check_socket (socket, error))
2230     return FALSE;
2231
2232   if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
2233     return FALSE;
2234
2235   if (socket->priv->remote_address)
2236     g_object_unref (socket->priv->remote_address);
2237   socket->priv->remote_address = g_object_ref (address);
2238
2239   while (1)
2240     {
2241       if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
2242                    g_socket_address_get_native_size (address)) < 0)
2243         {
2244           int errsv = get_socket_errno ();
2245
2246           if (errsv == EINTR)
2247             continue;
2248
2249 #ifndef G_OS_WIN32
2250           if (errsv == EINPROGRESS)
2251 #else
2252           if (errsv == WSAEWOULDBLOCK)
2253 #endif
2254             {
2255               if (socket->priv->blocking)
2256                 {
2257                   if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
2258                     {
2259                       if (g_socket_check_connect_result (socket, error))
2260                         break;
2261                     }
2262                 }
2263               else
2264                 {
2265                   g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
2266                                        _("Connection in progress"));
2267                   socket->priv->connect_pending = TRUE;
2268                 }
2269             }
2270           else
2271             g_set_error_literal (error, G_IO_ERROR,
2272                                  socket_io_error_from_errno (errsv),
2273                                  socket_strerror (errsv));
2274
2275           return FALSE;
2276         }
2277       break;
2278     }
2279
2280   win32_unset_event_mask (socket, FD_CONNECT);
2281
2282   socket->priv->connected = TRUE;
2283
2284   return TRUE;
2285 }
2286
2287 /**
2288  * g_socket_check_connect_result:
2289  * @socket: a #GSocket
2290  * @error: #GError for error reporting, or %NULL to ignore.
2291  *
2292  * Checks and resets the pending connect error for the socket.
2293  * This is used to check for errors when g_socket_connect() is
2294  * used in non-blocking mode.
2295  *
2296  * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
2297  *
2298  * Since: 2.22
2299  */
2300 gboolean
2301 g_socket_check_connect_result (GSocket  *socket,
2302                                GError  **error)
2303 {
2304   guint optlen;
2305   int value;
2306
2307   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2308
2309   if (!check_socket (socket, error))
2310     return FALSE;
2311
2312   optlen = sizeof (value);
2313   if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
2314     {
2315       int errsv = get_socket_errno ();
2316
2317       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2318                    _("Unable to get pending error: %s"), socket_strerror (errsv));
2319       return FALSE;
2320     }
2321
2322   if (value != 0)
2323     {
2324       g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
2325                            socket_strerror (value));
2326       if (socket->priv->remote_address)
2327         {
2328           g_object_unref (socket->priv->remote_address);
2329           socket->priv->remote_address = NULL;
2330         }
2331       return FALSE;
2332     }
2333
2334   socket->priv->connected = TRUE;
2335   return TRUE;
2336 }
2337
2338 /**
2339  * g_socket_receive:
2340  * @socket: a #GSocket
2341  * @buffer: a buffer to read data into (which should be at least @size
2342  *     bytes long).
2343  * @size: the number of bytes you want to read from the socket
2344  * @cancellable: (allow-none): a %GCancellable or %NULL
2345  * @error: #GError for error reporting, or %NULL to ignore.
2346  *
2347  * Receive data (up to @size bytes) from a socket. This is mainly used by
2348  * connection-oriented sockets; it is identical to g_socket_receive_from()
2349  * with @address set to %NULL.
2350  *
2351  * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
2352  * g_socket_receive() will always read either 0 or 1 complete messages from
2353  * the socket. If the received message is too large to fit in @buffer, then
2354  * the data beyond @size bytes will be discarded, without any explicit
2355  * indication that this has occurred.
2356  *
2357  * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
2358  * number of bytes, up to @size. If more than @size bytes have been
2359  * received, the additional data will be returned in future calls to
2360  * g_socket_receive().
2361  *
2362  * If the socket is in blocking mode the call will block until there
2363  * is some data to receive, the connection is closed, or there is an
2364  * error. If there is no data available and the socket is in
2365  * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
2366  * returned. To be notified when data is available, wait for the
2367  * %G_IO_IN condition.
2368  *
2369  * On error -1 is returned and @error is set accordingly.
2370  *
2371  * Returns: Number of bytes read, or 0 if the connection was closed by
2372  * the peer, or -1 on error
2373  *
2374  * Since: 2.22
2375  */
2376 gssize
2377 g_socket_receive (GSocket       *socket,
2378                   gchar         *buffer,
2379                   gsize          size,
2380                   GCancellable  *cancellable,
2381                   GError       **error)
2382 {
2383   return g_socket_receive_with_blocking (socket, buffer, size,
2384                                          socket->priv->blocking,
2385                                          cancellable, error);
2386 }
2387
2388 /**
2389  * g_socket_receive_with_blocking:
2390  * @socket: a #GSocket
2391  * @buffer: a buffer to read data into (which should be at least @size
2392  *     bytes long).
2393  * @size: the number of bytes you want to read from the socket
2394  * @blocking: whether to do blocking or non-blocking I/O
2395  * @cancellable: (allow-none): a %GCancellable or %NULL
2396  * @error: #GError for error reporting, or %NULL to ignore.
2397  *
2398  * This behaves exactly the same as g_socket_receive(), except that
2399  * the choice of blocking or non-blocking behavior is determined by
2400  * the @blocking argument rather than by @socket's properties.
2401  *
2402  * Returns: Number of bytes read, or 0 if the connection was closed by
2403  * the peer, or -1 on error
2404  *
2405  * Since: 2.26
2406  */
2407 gssize
2408 g_socket_receive_with_blocking (GSocket       *socket,
2409                                 gchar         *buffer,
2410                                 gsize          size,
2411                                 gboolean       blocking,
2412                                 GCancellable  *cancellable,
2413                                 GError       **error)
2414 {
2415   gssize ret;
2416
2417   g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2418
2419   if (!check_socket (socket, error))
2420     return -1;
2421
2422   if (g_cancellable_set_error_if_cancelled (cancellable, error))
2423     return -1;
2424
2425   while (1)
2426     {
2427       if (blocking &&
2428           !g_socket_condition_wait (socket,
2429                                     G_IO_IN, cancellable, error))
2430         return -1;
2431
2432       if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
2433         {
2434           int errsv = get_socket_errno ();
2435
2436           if (errsv == EINTR)
2437             continue;
2438
2439           if (blocking)
2440             {
2441 #ifdef WSAEWOULDBLOCK
2442               if (errsv == WSAEWOULDBLOCK)
2443                 continue;
2444 #else
2445               if (errsv == EWOULDBLOCK ||
2446                   errsv == EAGAIN)
2447                 continue;
2448 #endif
2449             }
2450
2451           win32_unset_event_mask (socket, FD_READ);
2452
2453           g_set_error (error, G_IO_ERROR,
2454                        socket_io_error_from_errno (errsv),
2455                        _("Error receiving data: %s"), socket_strerror (errsv));
2456           return -1;
2457         }
2458
2459       win32_unset_event_mask (socket, FD_READ);
2460
2461       break;
2462     }
2463
2464   return ret;
2465 }
2466
2467 /**
2468  * g_socket_receive_from:
2469  * @socket: a #GSocket
2470  * @address: (out) (allow-none): a pointer to a #GSocketAddress
2471  *     pointer, or %NULL
2472  * @buffer: (array length=size) (element-type guint8): a buffer to
2473  *     read data into (which should be at least @size bytes long).
2474  * @size: the number of bytes you want to read from the socket
2475  * @cancellable: (allow-none): a %GCancellable or %NULL
2476  * @error: #GError for error reporting, or %NULL to ignore.
2477  *
2478  * Receive data (up to @size bytes) from a socket.
2479  *
2480  * If @address is non-%NULL then @address will be set equal to the
2481  * source address of the received packet.
2482  * @address is owned by the caller.
2483  *
2484  * See g_socket_receive() for additional information.
2485  *
2486  * Returns: Number of bytes read, or 0 if the connection was closed by
2487  * the peer, or -1 on error
2488  *
2489  * Since: 2.22
2490  */
2491 gssize
2492 g_socket_receive_from (GSocket         *socket,
2493                        GSocketAddress **address,
2494                        gchar           *buffer,
2495                        gsize            size,
2496                        GCancellable    *cancellable,
2497                        GError         **error)
2498 {
2499   GInputVector v;
2500
2501   v.buffer = buffer;
2502   v.size = size;
2503
2504   return g_socket_receive_message (socket,
2505                                    address,
2506                                    &v, 1,
2507                                    NULL, 0, NULL,
2508                                    cancellable,
2509                                    error);
2510 }
2511
2512 /* Although we ignore SIGPIPE, gdb will still stop if the app receives
2513  * one, which can be confusing and annoying. So if possible, we want
2514  * to suppress the signal entirely.
2515  */
2516 #ifdef MSG_NOSIGNAL
2517 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
2518 #else
2519 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
2520 #endif
2521
2522 /**
2523  * g_socket_send:
2524  * @socket: a #GSocket
2525  * @buffer: (array length=size) (element-type guint8): the buffer
2526  *     containing the data to send.
2527  * @size: the number of bytes to send
2528  * @cancellable: (allow-none): a %GCancellable or %NULL
2529  * @error: #GError for error reporting, or %NULL to ignore.
2530  *
2531  * Tries to send @size bytes from @buffer on the socket. This is
2532  * mainly used by connection-oriented sockets; it is identical to
2533  * g_socket_send_to() with @address set to %NULL.
2534  *
2535  * If the socket is in blocking mode the call will block until there is
2536  * space for the data in the socket queue. If there is no space available
2537  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2538  * will be returned. To be notified when space is available, wait for the
2539  * %G_IO_OUT condition. Note though that you may still receive
2540  * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2541  * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2542  * very common due to the way the underlying APIs work.)
2543  *
2544  * On error -1 is returned and @error is set accordingly.
2545  *
2546  * Returns: Number of bytes written (which may be less than @size), or -1
2547  * on error
2548  *
2549  * Since: 2.22
2550  */
2551 gssize
2552 g_socket_send (GSocket       *socket,
2553                const gchar   *buffer,
2554                gsize          size,
2555                GCancellable  *cancellable,
2556                GError       **error)
2557 {
2558   return g_socket_send_with_blocking (socket, buffer, size,
2559                                       socket->priv->blocking,
2560                                       cancellable, error);
2561 }
2562
2563 /**
2564  * g_socket_send_with_blocking:
2565  * @socket: a #GSocket
2566  * @buffer: (array length=size) (element-type guint8): the buffer
2567  *     containing the data to send.
2568  * @size: the number of bytes to send
2569  * @blocking: whether to do blocking or non-blocking I/O
2570  * @cancellable: (allow-none): a %GCancellable or %NULL
2571  * @error: #GError for error reporting, or %NULL to ignore.
2572  *
2573  * This behaves exactly the same as g_socket_send(), except that
2574  * the choice of blocking or non-blocking behavior is determined by
2575  * the @blocking argument rather than by @socket's properties.
2576  *
2577  * Returns: Number of bytes written (which may be less than @size), or -1
2578  * on error
2579  *
2580  * Since: 2.26
2581  */
2582 gssize
2583 g_socket_send_with_blocking (GSocket       *socket,
2584                              const gchar   *buffer,
2585                              gsize          size,
2586                              gboolean       blocking,
2587                              GCancellable  *cancellable,
2588                              GError       **error)
2589 {
2590   gssize ret;
2591
2592   g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2593
2594   if (!check_socket (socket, error))
2595     return -1;
2596
2597   if (g_cancellable_set_error_if_cancelled (cancellable, error))
2598     return -1;
2599
2600   while (1)
2601     {
2602       if (blocking &&
2603           !g_socket_condition_wait (socket,
2604                                     G_IO_OUT, cancellable, error))
2605         return -1;
2606
2607       if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
2608         {
2609           int errsv = get_socket_errno ();
2610
2611           if (errsv == EINTR)
2612             continue;
2613
2614 #ifdef WSAEWOULDBLOCK
2615           if (errsv == WSAEWOULDBLOCK)
2616             win32_unset_event_mask (socket, FD_WRITE);
2617 #endif
2618
2619           if (blocking)
2620             {
2621 #ifdef WSAEWOULDBLOCK
2622               if (errsv == WSAEWOULDBLOCK)
2623                 continue;
2624 #else
2625               if (errsv == EWOULDBLOCK ||
2626                   errsv == EAGAIN)
2627                 continue;
2628 #endif
2629             }
2630
2631           g_set_error (error, G_IO_ERROR,
2632                        socket_io_error_from_errno (errsv),
2633                        _("Error sending data: %s"), socket_strerror (errsv));
2634           return -1;
2635         }
2636       break;
2637     }
2638
2639   return ret;
2640 }
2641
2642 /**
2643  * g_socket_send_to:
2644  * @socket: a #GSocket
2645  * @address: a #GSocketAddress, or %NULL
2646  * @buffer: (array length=size) (element-type guint8): the buffer
2647  *     containing the data to send.
2648  * @size: the number of bytes to send
2649  * @cancellable: (allow-none): a %GCancellable or %NULL
2650  * @error: #GError for error reporting, or %NULL to ignore.
2651  *
2652  * Tries to send @size bytes from @buffer to @address. If @address is
2653  * %NULL then the message is sent to the default receiver (set by
2654  * g_socket_connect()).
2655  *
2656  * See g_socket_send() for additional information.
2657  *
2658  * Returns: Number of bytes written (which may be less than @size), or -1
2659  * on error
2660  *
2661  * Since: 2.22
2662  */
2663 gssize
2664 g_socket_send_to (GSocket         *socket,
2665                   GSocketAddress  *address,
2666                   const gchar     *buffer,
2667                   gsize            size,
2668                   GCancellable    *cancellable,
2669                   GError         **error)
2670 {
2671   GOutputVector v;
2672
2673   v.buffer = buffer;
2674   v.size = size;
2675
2676   return g_socket_send_message (socket,
2677                                 address,
2678                                 &v, 1,
2679                                 NULL, 0,
2680                                 0,
2681                                 cancellable,
2682                                 error);
2683 }
2684
2685 /**
2686  * g_socket_shutdown:
2687  * @socket: a #GSocket
2688  * @shutdown_read: whether to shut down the read side
2689  * @shutdown_write: whether to shut down the write side
2690  * @error: #GError for error reporting, or %NULL to ignore.
2691  *
2692  * Shut down part of a full-duplex connection.
2693  *
2694  * If @shutdown_read is %TRUE then the receiving side of the connection
2695  * is shut down, and further reading is disallowed.
2696  *
2697  * If @shutdown_write is %TRUE then the sending side of the connection
2698  * is shut down, and further writing is disallowed.
2699  *
2700  * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
2701  *
2702  * One example where this is used is graceful disconnect for TCP connections
2703  * where you close the sending side, then wait for the other side to close
2704  * the connection, thus ensuring that the other side saw all sent data.
2705  *
2706  * Returns: %TRUE on success, %FALSE on error
2707  *
2708  * Since: 2.22
2709  */
2710 gboolean
2711 g_socket_shutdown (GSocket   *socket,
2712                    gboolean   shutdown_read,
2713                    gboolean   shutdown_write,
2714                    GError   **error)
2715 {
2716   int how;
2717
2718   g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2719
2720   if (!check_socket (socket, error))
2721     return FALSE;
2722
2723   /* Do nothing? */
2724   if (!shutdown_read && !shutdown_write)
2725     return TRUE;
2726
2727 #ifndef G_OS_WIN32
2728   if (shutdown_read && shutdown_write)
2729     how = SHUT_RDWR;
2730   else if (shutdown_read)
2731     how = SHUT_RD;
2732   else
2733     how = SHUT_WR;
2734 #else
2735   if (shutdown_read && shutdown_write)
2736     how = SD_BOTH;
2737   else if (shutdown_read)
2738     how = SD_RECEIVE;
2739   else
2740     how = SD_SEND;
2741 #endif
2742
2743   if (shutdown (socket->priv->fd, how) != 0)
2744     {
2745       int errsv = get_socket_errno ();
2746       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2747                    _("Unable to shutdown socket: %s"), socket_strerror (errsv));
2748       return FALSE;
2749     }
2750
2751   if (shutdown_read && shutdown_write)
2752     socket->priv->connected = FALSE;
2753
2754   return TRUE;
2755 }
2756
2757 /**
2758  * g_socket_close:
2759  * @socket: a #GSocket
2760  * @error: #GError for error reporting, or %NULL to ignore.
2761  *
2762  * Closes the socket, shutting down any active connection.
2763  *
2764  * Closing a socket does not wait for all outstanding I/O operations
2765  * to finish, so the caller should not rely on them to be guaranteed
2766  * to complete even if the close returns with no error.
2767  *
2768  * Once the socket is closed, all other operations will return
2769  * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
2770  * return an error.
2771  *
2772  * Sockets will be automatically closed when the last reference
2773  * is dropped, but you might want to call this function to make sure
2774  * resources are released as early as possible.
2775  *
2776  * Beware that due to the way that TCP works, it is possible for
2777  * recently-sent data to be lost if either you close a socket while the
2778  * %G_IO_IN condition is set, or else if the remote connection tries to
2779  * send something to you after you close the socket but before it has
2780  * finished reading all of the data you sent. There is no easy generic
2781  * way to avoid this problem; the easiest fix is to design the network
2782  * protocol such that the client will never send data "out of turn".
2783  * Another solution is for the server to half-close the connection by
2784  * calling g_socket_shutdown() with only the @shutdown_write flag set,
2785  * and then wait for the client to notice this and close its side of the
2786  * connection, after which the server can safely call g_socket_close().
2787  * (This is what #GTcpConnection does if you call
2788  * g_tcp_connection_set_graceful_disconnect(). But of course, this
2789  * only works if the client will close its connection after the server
2790  * does.)
2791  *
2792  * Returns: %TRUE on success, %FALSE on error
2793  *
2794  * Since: 2.22
2795  */
2796 gboolean
2797 g_socket_close (GSocket  *socket,
2798                 GError  **error)
2799 {
2800   int res;
2801
2802   g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2803
2804   if (socket->priv->closed)
2805     return TRUE; /* Multiple close not an error */
2806
2807   if (!check_socket (socket, error))
2808     return FALSE;
2809
2810   while (1)
2811     {
2812 #ifdef G_OS_WIN32
2813       res = closesocket (socket->priv->fd);
2814 #else
2815       res = close (socket->priv->fd);
2816 #endif
2817       if (res == -1)
2818         {
2819           int errsv = get_socket_errno ();
2820
2821           if (errsv == EINTR)
2822             continue;
2823
2824           g_set_error (error, G_IO_ERROR,
2825                        socket_io_error_from_errno (errsv),
2826                        _("Error closing socket: %s"),
2827                        socket_strerror (errsv));
2828           return FALSE;
2829         }
2830       break;
2831     }
2832
2833   socket->priv->connected = FALSE;
2834   socket->priv->closed = TRUE;
2835   if (socket->priv->remote_address)
2836     {
2837       g_object_unref (socket->priv->remote_address);
2838       socket->priv->remote_address = NULL;
2839     }
2840
2841   return TRUE;
2842 }
2843
2844 /**
2845  * g_socket_is_closed:
2846  * @socket: a #GSocket
2847  *
2848  * Checks whether a socket is closed.
2849  *
2850  * Returns: %TRUE if socket is closed, %FALSE otherwise
2851  *
2852  * Since: 2.22
2853  */
2854 gboolean
2855 g_socket_is_closed (GSocket *socket)
2856 {
2857   return socket->priv->closed;
2858 }
2859
2860 #ifdef G_OS_WIN32
2861 /* Broken source, used on errors */
2862 static gboolean
2863 broken_prepare  (GSource *source,
2864                  gint    *timeout)
2865 {
2866   return FALSE;
2867 }
2868
2869 static gboolean
2870 broken_check (GSource *source)
2871 {
2872   return FALSE;
2873 }
2874
2875 static gboolean
2876 broken_dispatch (GSource     *source,
2877                  GSourceFunc  callback,
2878                  gpointer     user_data)
2879 {
2880   return TRUE;
2881 }
2882
2883 static GSourceFuncs broken_funcs =
2884 {
2885   broken_prepare,
2886   broken_check,
2887   broken_dispatch,
2888   NULL
2889 };
2890
2891 static gint
2892 network_events_for_condition (GIOCondition condition)
2893 {
2894   int event_mask = 0;
2895
2896   if (condition & G_IO_IN)
2897     event_mask |= (FD_READ | FD_ACCEPT);
2898   if (condition & G_IO_OUT)
2899     event_mask |= (FD_WRITE | FD_CONNECT);
2900   event_mask |= FD_CLOSE;
2901
2902   return event_mask;
2903 }
2904
2905 static void
2906 ensure_event (GSocket *socket)
2907 {
2908   if (socket->priv->event == WSA_INVALID_EVENT)
2909     socket->priv->event = WSACreateEvent();
2910 }
2911
2912 static void
2913 update_select_events (GSocket *socket)
2914 {
2915   int event_mask;
2916   GIOCondition *ptr;
2917   GList *l;
2918   WSAEVENT event;
2919
2920   ensure_event (socket);
2921
2922   event_mask = 0;
2923   for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
2924     {
2925       ptr = l->data;
2926       event_mask |= network_events_for_condition (*ptr);
2927     }
2928
2929   if (event_mask != socket->priv->selected_events)
2930     {
2931       /* If no events selected, disable event so we can unset
2932          nonblocking mode */
2933
2934       if (event_mask == 0)
2935         event = NULL;
2936       else
2937         event = socket->priv->event;
2938
2939       if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
2940         socket->priv->selected_events = event_mask;
2941     }
2942 }
2943
2944 static void
2945 add_condition_watch (GSocket      *socket,
2946                      GIOCondition *condition)
2947 {
2948   g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
2949
2950   socket->priv->requested_conditions =
2951     g_list_prepend (socket->priv->requested_conditions, condition);
2952
2953   update_select_events (socket);
2954 }
2955
2956 static void
2957 remove_condition_watch (GSocket      *socket,
2958                         GIOCondition *condition)
2959 {
2960   g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
2961
2962   socket->priv->requested_conditions =
2963     g_list_remove (socket->priv->requested_conditions, condition);
2964
2965   update_select_events (socket);
2966 }
2967
2968 static GIOCondition
2969 update_condition (GSocket *socket)
2970 {
2971   WSANETWORKEVENTS events;
2972   GIOCondition condition;
2973
2974   if (WSAEnumNetworkEvents (socket->priv->fd,
2975                             socket->priv->event,
2976                             &events) == 0)
2977     {
2978       socket->priv->current_events |= events.lNetworkEvents;
2979       if (events.lNetworkEvents & FD_WRITE &&
2980           events.iErrorCode[FD_WRITE_BIT] != 0)
2981         socket->priv->current_errors |= FD_WRITE;
2982       if (events.lNetworkEvents & FD_CONNECT &&
2983           events.iErrorCode[FD_CONNECT_BIT] != 0)
2984         socket->priv->current_errors |= FD_CONNECT;
2985     }
2986
2987   condition = 0;
2988   if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
2989     condition |= G_IO_IN;
2990
2991   if (socket->priv->current_events & FD_CLOSE ||
2992       socket->priv->closed)
2993     condition |= G_IO_HUP;
2994
2995   /* Never report both G_IO_OUT and HUP, these are
2996      mutually exclusive (can't write to a closed socket) */
2997   if ((condition & G_IO_HUP) == 0 &&
2998       socket->priv->current_events & FD_WRITE)
2999     {
3000       if (socket->priv->current_errors & FD_WRITE)
3001         condition |= G_IO_ERR;
3002       else
3003         condition |= G_IO_OUT;
3004     }
3005   else
3006     {
3007       if (socket->priv->current_events & FD_CONNECT)
3008         {
3009           if (socket->priv->current_errors & FD_CONNECT)
3010             condition |= (G_IO_HUP | G_IO_ERR);
3011           else
3012             condition |= G_IO_OUT;
3013         }
3014     }
3015
3016   return condition;
3017 }
3018 #endif
3019
3020 typedef struct {
3021   GSource       source;
3022   GPollFD       pollfd;
3023   GSocket      *socket;
3024   GIOCondition  condition;
3025   GCancellable *cancellable;
3026   GPollFD       cancel_pollfd;
3027   gint64        timeout_time;
3028 } GSocketSource;
3029
3030 static gboolean
3031 socket_source_prepare (GSource *source,
3032                        gint    *timeout)
3033 {
3034   GSocketSource *socket_source = (GSocketSource *)source;
3035
3036   if (g_cancellable_is_cancelled (socket_source->cancellable))
3037     return TRUE;
3038
3039   if (socket_source->timeout_time)
3040     {
3041       gint64 now;
3042
3043       now = g_source_get_time (source);
3044       /* Round up to ensure that we don't try again too early */
3045       *timeout = (socket_source->timeout_time - now + 999) / 1000;
3046       if (*timeout < 0)
3047         {
3048           socket_source->socket->priv->timed_out = TRUE;
3049           *timeout = 0;
3050           return TRUE;
3051         }
3052     }
3053   else
3054     *timeout = -1;
3055
3056 #ifdef G_OS_WIN32
3057   socket_source->pollfd.revents = update_condition (socket_source->socket);
3058 #endif
3059
3060   if ((socket_source->condition & socket_source->pollfd.revents) != 0)
3061     return TRUE;
3062
3063   return FALSE;
3064 }
3065
3066 static gboolean
3067 socket_source_check (GSource *source)
3068 {
3069   int timeout;
3070
3071   return socket_source_prepare (source, &timeout);
3072 }
3073
3074 static gboolean
3075 socket_source_dispatch (GSource     *source,
3076                         GSourceFunc  callback,
3077                         gpointer     user_data)
3078 {
3079   GSocketSourceFunc func = (GSocketSourceFunc)callback;
3080   GSocketSource *socket_source = (GSocketSource *)source;
3081
3082 #ifdef G_OS_WIN32
3083   socket_source->pollfd.revents = update_condition (socket_source->socket);
3084 #endif
3085   if (socket_source->socket->priv->timed_out)
3086     socket_source->pollfd.revents |= socket_source->condition & (G_IO_IN | G_IO_OUT);
3087
3088   return (*func) (socket_source->socket,
3089                   socket_source->pollfd.revents & socket_source->condition,
3090                   user_data);
3091 }
3092
3093 static void
3094 socket_source_finalize (GSource *source)
3095 {
3096   GSocketSource *socket_source = (GSocketSource *)source;
3097   GSocket *socket;
3098
3099   socket = socket_source->socket;
3100
3101 #ifdef G_OS_WIN32
3102   remove_condition_watch (socket, &socket_source->condition);
3103 #endif
3104
3105   g_object_unref (socket);
3106
3107   if (socket_source->cancellable)
3108     {
3109       g_cancellable_release_fd (socket_source->cancellable);
3110       g_object_unref (socket_source->cancellable);
3111     }
3112 }
3113
3114 static gboolean
3115 socket_source_closure_callback (GSocket      *socket,
3116                                 GIOCondition  condition,
3117                                 gpointer      data)
3118 {
3119   GClosure *closure = data;
3120
3121   GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
3122   GValue result_value = G_VALUE_INIT;
3123   gboolean result;
3124
3125   g_value_init (&result_value, G_TYPE_BOOLEAN);
3126
3127   g_value_init (&params[0], G_TYPE_SOCKET);
3128   g_value_set_object (&params[0], socket);
3129   g_value_init (&params[1], G_TYPE_IO_CONDITION);
3130   g_value_set_flags (&params[1], condition);
3131
3132   g_closure_invoke (closure, &result_value, 2, params, NULL);
3133
3134   result = g_value_get_boolean (&result_value);
3135   g_value_unset (&result_value);
3136   g_value_unset (&params[0]);
3137   g_value_unset (&params[1]);
3138
3139   return result;
3140 }
3141
3142 static GSourceFuncs socket_source_funcs =
3143 {
3144   socket_source_prepare,
3145   socket_source_check,
3146   socket_source_dispatch,
3147   socket_source_finalize,
3148   (GSourceFunc)socket_source_closure_callback,
3149   (GSourceDummyMarshal)g_cclosure_marshal_generic,
3150 };
3151
3152 static GSource *
3153 socket_source_new (GSocket      *socket,
3154                    GIOCondition  condition,
3155                    GCancellable *cancellable)
3156 {
3157   GSource *source;
3158   GSocketSource *socket_source;
3159
3160 #ifdef G_OS_WIN32
3161   ensure_event (socket);
3162
3163   if (socket->priv->event == WSA_INVALID_EVENT)
3164     {
3165       g_warning ("Failed to create WSAEvent");
3166       return g_source_new (&broken_funcs, sizeof (GSource));
3167     }
3168 #endif
3169
3170   condition |= G_IO_HUP | G_IO_ERR;
3171
3172   source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
3173   g_source_set_name (source, "GSocket");
3174   socket_source = (GSocketSource *)source;
3175
3176   socket_source->socket = g_object_ref (socket);
3177   socket_source->condition = condition;
3178
3179   if (g_cancellable_make_pollfd (cancellable,
3180                                  &socket_source->cancel_pollfd))
3181     {
3182       socket_source->cancellable = g_object_ref (cancellable);
3183       g_source_add_poll (source, &socket_source->cancel_pollfd);
3184     }
3185
3186 #ifdef G_OS_WIN32
3187   add_condition_watch (socket, &socket_source->condition);
3188   socket_source->pollfd.fd = (gintptr) socket->priv->event;
3189 #else
3190   socket_source->pollfd.fd = socket->priv->fd;
3191 #endif
3192
3193   socket_source->pollfd.events = condition;
3194   socket_source->pollfd.revents = 0;
3195   g_source_add_poll (source, &socket_source->pollfd);
3196
3197   if (socket->priv->timeout)
3198     socket_source->timeout_time = g_get_monotonic_time () +
3199                                   socket->priv->timeout * 1000000;
3200
3201   else
3202     socket_source->timeout_time = 0;
3203
3204   return source;
3205 }
3206
3207 /**
3208  * g_socket_create_source: (skip)
3209  * @socket: a #GSocket
3210  * @condition: a #GIOCondition mask to monitor
3211  * @cancellable: (allow-none): a %GCancellable or %NULL
3212  *
3213  * Creates a %GSource that can be attached to a %GMainContext to monitor
3214  * for the availibility of the specified @condition on the socket.
3215  *
3216  * The callback on the source is of the #GSocketSourceFunc type.
3217  *
3218  * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
3219  * these conditions will always be reported output if they are true.
3220  *
3221  * @cancellable if not %NULL can be used to cancel the source, which will
3222  * cause the source to trigger, reporting the current condition (which
3223  * is likely 0 unless cancellation happened at the same time as a
3224  * condition change). You can check for this in the callback using
3225  * g_cancellable_is_cancelled().
3226  *
3227  * If @socket has a timeout set, and it is reached before @condition
3228  * occurs, the source will then trigger anyway, reporting %G_IO_IN or
3229  * %G_IO_OUT depending on @condition. However, @socket will have been
3230  * marked as having had a timeout, and so the next #GSocket I/O method
3231  * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
3232  *
3233  * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
3234  *
3235  * Since: 2.22
3236  */
3237 GSource *
3238 g_socket_create_source (GSocket      *socket,
3239                         GIOCondition  condition,
3240                         GCancellable *cancellable)
3241 {
3242   g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
3243
3244   return socket_source_new (socket, condition, cancellable);
3245 }
3246
3247 /**
3248  * g_socket_condition_check:
3249  * @socket: a #GSocket
3250  * @condition: a #GIOCondition mask to check
3251  *
3252  * Checks on the readiness of @socket to perform operations.
3253  * The operations specified in @condition are checked for and masked
3254  * against the currently-satisfied conditions on @socket. The result
3255  * is returned.
3256  *
3257  * Note that on Windows, it is possible for an operation to return
3258  * %G_IO_ERROR_WOULD_BLOCK even immediately after
3259  * g_socket_condition_check() has claimed that the socket is ready for
3260  * writing. Rather than calling g_socket_condition_check() and then
3261  * writing to the socket if it succeeds, it is generally better to
3262  * simply try writing to the socket right away, and try again later if
3263  * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
3264  *
3265  * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
3266  * these conditions will always be set in the output if they are true.
3267  *
3268  * This call never blocks.
3269  *
3270  * Returns: the @GIOCondition mask of the current state
3271  *
3272  * Since: 2.22
3273  */
3274 GIOCondition
3275 g_socket_condition_check (GSocket      *socket,
3276                           GIOCondition  condition)
3277 {
3278   g_return_val_if_fail (G_IS_SOCKET (socket), 0);
3279
3280   if (!check_socket (socket, NULL))
3281     return 0;
3282
3283 #ifdef G_OS_WIN32
3284   {
3285     GIOCondition current_condition;
3286
3287     condition |= G_IO_ERR | G_IO_HUP;
3288
3289     add_condition_watch (socket, &condition);
3290     current_condition = update_condition (socket);
3291     remove_condition_watch (socket, &condition);
3292     return condition & current_condition;
3293   }
3294 #else
3295   {
3296     GPollFD poll_fd;
3297     gint result;
3298     poll_fd.fd = socket->priv->fd;
3299     poll_fd.events = condition;
3300
3301     do
3302       result = g_poll (&poll_fd, 1, 0);
3303     while (result == -1 && get_socket_errno () == EINTR);
3304
3305     return poll_fd.revents;
3306   }
3307 #endif
3308 }
3309
3310 /**
3311  * g_socket_condition_wait:
3312  * @socket: a #GSocket
3313  * @condition: a #GIOCondition mask to wait for
3314  * @cancellable: (allow-none): a #GCancellable, or %NULL
3315  * @error: a #GError pointer, or %NULL
3316  *
3317  * Waits for @condition to become true on @socket. When the condition
3318  * is met, %TRUE is returned.
3319  *
3320  * If @cancellable is cancelled before the condition is met, or if the
3321  * socket has a timeout set and it is reached before the condition is
3322  * met, then %FALSE is returned and @error, if non-%NULL, is set to
3323  * the appropriate value (%G_IO_ERROR_CANCELLED or
3324  * %G_IO_ERROR_TIMED_OUT).
3325  *
3326  * Returns: %TRUE if the condition was met, %FALSE otherwise
3327  *
3328  * Since: 2.22
3329  */
3330 gboolean
3331 g_socket_condition_wait (GSocket       *socket,
3332                          GIOCondition   condition,
3333                          GCancellable  *cancellable,
3334                          GError       **error)
3335 {
3336   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3337
3338   if (!check_socket (socket, error))
3339     return FALSE;
3340
3341   if (g_cancellable_set_error_if_cancelled (cancellable, error))
3342     return FALSE;
3343
3344 #ifdef G_OS_WIN32
3345   {
3346     GIOCondition current_condition;
3347     WSAEVENT events[2];
3348     DWORD res, timeout;
3349     GPollFD cancel_fd;
3350     int num_events;
3351
3352     /* Always check these */
3353     condition |=  G_IO_ERR | G_IO_HUP;
3354
3355     add_condition_watch (socket, &condition);
3356
3357     num_events = 0;
3358     events[num_events++] = socket->priv->event;
3359
3360     if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
3361       events[num_events++] = (WSAEVENT)cancel_fd.fd;
3362
3363     if (socket->priv->timeout)
3364       timeout = socket->priv->timeout * 1000;
3365     else
3366       timeout = WSA_INFINITE;
3367
3368     current_condition = update_condition (socket);
3369     while ((condition & current_condition) == 0)
3370       {
3371         res = WSAWaitForMultipleEvents(num_events, events,
3372                                        FALSE, timeout, FALSE);
3373         if (res == WSA_WAIT_FAILED)
3374           {
3375             int errsv = get_socket_errno ();
3376
3377             g_set_error (error, G_IO_ERROR,
3378                          socket_io_error_from_errno (errsv),
3379                          _("Waiting for socket condition: %s"),
3380                          socket_strerror (errsv));
3381             break;
3382           }
3383         else if (res == WSA_WAIT_TIMEOUT)
3384           {
3385             g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3386                                  _("Socket I/O timed out"));
3387             break;
3388           }
3389
3390         if (g_cancellable_set_error_if_cancelled (cancellable, error))
3391           break;
3392
3393         current_condition = update_condition (socket);
3394       }
3395     remove_condition_watch (socket, &condition);
3396     if (num_events > 1)
3397       g_cancellable_release_fd (cancellable);
3398
3399     return (condition & current_condition) != 0;
3400   }
3401 #else
3402   {
3403     GPollFD poll_fd[2];
3404     gint result;
3405     gint num;
3406     gint timeout;
3407
3408     poll_fd[0].fd = socket->priv->fd;
3409     poll_fd[0].events = condition;
3410     num = 1;
3411
3412     if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
3413       num++;
3414
3415     if (socket->priv->timeout)
3416       timeout = socket->priv->timeout * 1000;
3417     else
3418       timeout = -1;
3419
3420     do
3421       result = g_poll (poll_fd, num, timeout);
3422     while (result == -1 && get_socket_errno () == EINTR);
3423     
3424     if (num > 1)
3425       g_cancellable_release_fd (cancellable);
3426
3427     if (result == 0)
3428       {
3429         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3430                              _("Socket I/O timed out"));
3431         return FALSE;
3432       }
3433
3434     return !g_cancellable_set_error_if_cancelled (cancellable, error);
3435   }
3436   #endif
3437 }
3438
3439 /**
3440  * g_socket_send_message:
3441  * @socket: a #GSocket
3442  * @address: a #GSocketAddress, or %NULL
3443  * @vectors: (array length=num_vectors): an array of #GOutputVector structs
3444  * @num_vectors: the number of elements in @vectors, or -1
3445  * @messages: (array length=num_messages) (allow-none): a pointer to an
3446  *   array of #GSocketControlMessages, or %NULL.
3447  * @num_messages: number of elements in @messages, or -1.
3448  * @flags: an int containing #GSocketMsgFlags flags
3449  * @cancellable: (allow-none): a %GCancellable or %NULL
3450  * @error: #GError for error reporting, or %NULL to ignore.
3451  *
3452  * Send data to @address on @socket.  This is the most complicated and
3453  * fully-featured version of this call. For easier use, see
3454  * g_socket_send() and g_socket_send_to().
3455  *
3456  * If @address is %NULL then the message is sent to the default receiver
3457  * (set by g_socket_connect()).
3458  *
3459  * @vectors must point to an array of #GOutputVector structs and
3460  * @num_vectors must be the length of this array. (If @num_vectors is -1,
3461  * then @vectors is assumed to be terminated by a #GOutputVector with a
3462  * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
3463  * that the sent data will be gathered from. Using multiple
3464  * #GOutputVector<!-- -->s is more memory-efficient than manually copying
3465  * data from multiple sources into a single buffer, and more
3466  * network-efficient than making multiple calls to g_socket_send().
3467  *
3468  * @messages, if non-%NULL, is taken to point to an array of @num_messages
3469  * #GSocketControlMessage instances. These correspond to the control
3470  * messages to be sent on the socket.
3471  * If @num_messages is -1 then @messages is treated as a %NULL-terminated
3472  * array.
3473  *
3474  * @flags modify how the message is sent. The commonly available arguments
3475  * for this are available in the #GSocketMsgFlags enum, but the
3476  * values there are the same as the system values, and the flags
3477  * are passed in as-is, so you can pass in system-specific flags too.
3478  *
3479  * If the socket is in blocking mode the call will block until there is
3480  * space for the data in the socket queue. If there is no space available
3481  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3482  * will be returned. To be notified when space is available, wait for the
3483  * %G_IO_OUT condition. Note though that you may still receive
3484  * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3485  * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3486  * very common due to the way the underlying APIs work.)
3487  *
3488  * On error -1 is returned and @error is set accordingly.
3489  *
3490  * Returns: Number of bytes written (which may be less than @size), or -1
3491  * on error
3492  *
3493  * Since: 2.22
3494  */
3495 gssize
3496 g_socket_send_message (GSocket                *socket,
3497                        GSocketAddress         *address,
3498                        GOutputVector          *vectors,
3499                        gint                    num_vectors,
3500                        GSocketControlMessage **messages,
3501                        gint                    num_messages,
3502                        gint                    flags,
3503                        GCancellable           *cancellable,
3504                        GError                **error)
3505 {
3506   GOutputVector one_vector;
3507   char zero;
3508
3509   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3510
3511   if (!check_socket (socket, error))
3512     return -1;
3513
3514   if (g_cancellable_set_error_if_cancelled (cancellable, error))
3515     return -1;
3516
3517   if (num_vectors == -1)
3518     {
3519       for (num_vectors = 0;
3520            vectors[num_vectors].buffer != NULL;
3521            num_vectors++)
3522         ;
3523     }
3524
3525   if (num_messages == -1)
3526     {
3527       for (num_messages = 0;
3528            messages != NULL && messages[num_messages] != NULL;
3529            num_messages++)
3530         ;
3531     }
3532
3533   if (num_vectors == 0)
3534     {
3535       zero = '\0';
3536
3537       one_vector.buffer = &zero;
3538       one_vector.size = 1;
3539       num_vectors = 1;
3540       vectors = &one_vector;
3541     }
3542
3543 #ifndef G_OS_WIN32
3544   {
3545     struct msghdr msg;
3546     gssize result;
3547
3548    msg.msg_flags = 0;
3549
3550     /* name */
3551     if (address)
3552       {
3553         msg.msg_namelen = g_socket_address_get_native_size (address);
3554         msg.msg_name = g_alloca (msg.msg_namelen);
3555         if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
3556           return -1;
3557       }
3558     else
3559       {
3560         msg.msg_name = NULL;
3561         msg.msg_namelen = 0;
3562       }
3563
3564     /* iov */
3565     {
3566       /* this entire expression will be evaluated at compile time */
3567       if (sizeof *msg.msg_iov == sizeof *vectors &&
3568           sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3569           G_STRUCT_OFFSET (struct iovec, iov_base) ==
3570           G_STRUCT_OFFSET (GOutputVector, buffer) &&
3571           sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3572           G_STRUCT_OFFSET (struct iovec, iov_len) ==
3573           G_STRUCT_OFFSET (GOutputVector, size))
3574         /* ABI is compatible */
3575         {
3576           msg.msg_iov = (struct iovec *) vectors;
3577           msg.msg_iovlen = num_vectors;
3578         }
3579       else
3580         /* ABI is incompatible */
3581         {
3582           gint i;
3583
3584           msg.msg_iov = g_newa (struct iovec, num_vectors);
3585           for (i = 0; i < num_vectors; i++)
3586             {
3587               msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
3588               msg.msg_iov[i].iov_len = vectors[i].size;
3589             }
3590           msg.msg_iovlen = num_vectors;
3591         }
3592     }
3593
3594     /* control */
3595     {
3596       struct cmsghdr *cmsg;
3597       gint i;
3598
3599       msg.msg_controllen = 0;
3600       for (i = 0; i < num_messages; i++)
3601         msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
3602
3603       if (msg.msg_controllen == 0)
3604         msg.msg_control = NULL;
3605       else
3606         {
3607           msg.msg_control = g_alloca (msg.msg_controllen);
3608           memset (msg.msg_control, '\0', msg.msg_controllen);
3609         }
3610
3611       cmsg = CMSG_FIRSTHDR (&msg);
3612       for (i = 0; i < num_messages; i++)
3613         {
3614           cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
3615           cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
3616           cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
3617           g_socket_control_message_serialize (messages[i],
3618                                               CMSG_DATA (cmsg));
3619           cmsg = CMSG_NXTHDR (&msg, cmsg);
3620         }
3621       g_assert (cmsg == NULL);
3622     }
3623
3624     while (1)
3625       {
3626         if (socket->priv->blocking &&
3627             !g_socket_condition_wait (socket,
3628                                       G_IO_OUT, cancellable, error))
3629           return -1;
3630
3631         result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
3632         if (result < 0)
3633           {
3634             int errsv = get_socket_errno ();
3635
3636             if (errsv == EINTR)
3637               continue;
3638
3639             if (socket->priv->blocking &&
3640                 (errsv == EWOULDBLOCK ||
3641                  errsv == EAGAIN))
3642               continue;
3643
3644             g_set_error (error, G_IO_ERROR,
3645                          socket_io_error_from_errno (errsv),
3646                          _("Error sending message: %s"), socket_strerror (errsv));
3647
3648             return -1;
3649           }
3650         break;
3651       }
3652
3653     return result;
3654   }
3655 #else
3656   {
3657     struct sockaddr_storage addr;
3658     guint addrlen;
3659     DWORD bytes_sent;
3660     int result;
3661     WSABUF *bufs;
3662     gint i;
3663
3664     /* Win32 doesn't support control messages.
3665        Actually this is possible for raw and datagram sockets
3666        via WSASendMessage on Vista or later, but that doesn't
3667        seem very useful */
3668     if (num_messages != 0)
3669       {
3670         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
3671                              _("GSocketControlMessage not supported on windows"));
3672         return -1;
3673       }
3674
3675     /* iov */
3676     bufs = g_newa (WSABUF, num_vectors);
3677     for (i = 0; i < num_vectors; i++)
3678       {
3679         bufs[i].buf = (char *)vectors[i].buffer;
3680         bufs[i].len = (gulong)vectors[i].size;
3681       }
3682
3683     /* name */
3684     addrlen = 0; /* Avoid warning */
3685     if (address)
3686       {
3687         addrlen = g_socket_address_get_native_size (address);
3688         if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
3689           return -1;
3690       }
3691
3692     while (1)
3693       {
3694         if (socket->priv->blocking &&
3695             !g_socket_condition_wait (socket,
3696                                       G_IO_OUT, cancellable, error))
3697           return -1;
3698
3699         if (address)
3700           result = WSASendTo (socket->priv->fd,
3701                               bufs, num_vectors,
3702                               &bytes_sent, flags,
3703                               (const struct sockaddr *)&addr, addrlen,
3704                               NULL, NULL);
3705         else
3706           result = WSASend (socket->priv->fd,
3707                             bufs, num_vectors,
3708                             &bytes_sent, flags,
3709                             NULL, NULL);
3710
3711         if (result != 0)
3712           {
3713             int errsv = get_socket_errno ();
3714
3715             if (errsv == WSAEINTR)
3716               continue;
3717
3718             if (errsv == WSAEWOULDBLOCK)
3719               win32_unset_event_mask (socket, FD_WRITE);
3720
3721             if (socket->priv->blocking &&
3722                 errsv == WSAEWOULDBLOCK)
3723               continue;
3724
3725             g_set_error (error, G_IO_ERROR,
3726                          socket_io_error_from_errno (errsv),
3727                          _("Error sending message: %s"), socket_strerror (errsv));
3728
3729             return -1;
3730           }
3731         break;
3732       }
3733
3734     return bytes_sent;
3735   }
3736 #endif
3737 }
3738
3739 /**
3740  * g_socket_receive_message:
3741  * @socket: a #GSocket
3742  * @address: (out) (allow-none): a pointer to a #GSocketAddress
3743  *     pointer, or %NULL
3744  * @vectors: (array length=num_vectors): an array of #GInputVector structs
3745  * @num_vectors: the number of elements in @vectors, or -1
3746  * @messages: (array length=num_messages) (allow-none): a pointer which
3747  *    may be filled with an array of #GSocketControlMessages, or %NULL
3748  * @num_messages: a pointer which will be filled with the number of
3749  *    elements in @messages, or %NULL
3750  * @flags: a pointer to an int containing #GSocketMsgFlags flags
3751  * @cancellable: (allow-none): a %GCancellable or %NULL
3752  * @error: a #GError pointer, or %NULL
3753  *
3754  * Receive data from a socket.  This is the most complicated and
3755  * fully-featured version of this call. For easier use, see
3756  * g_socket_receive() and g_socket_receive_from().
3757  *
3758  * If @address is non-%NULL then @address will be set equal to the
3759  * source address of the received packet.
3760  * @address is owned by the caller.
3761  *
3762  * @vector must point to an array of #GInputVector structs and
3763  * @num_vectors must be the length of this array.  These structs
3764  * describe the buffers that received data will be scattered into.
3765  * If @num_vectors is -1, then @vectors is assumed to be terminated
3766  * by a #GInputVector with a %NULL buffer pointer.
3767  *
3768  * As a special case, if @num_vectors is 0 (in which case, @vectors
3769  * may of course be %NULL), then a single byte is received and
3770  * discarded. This is to facilitate the common practice of sending a
3771  * single '\0' byte for the purposes of transferring ancillary data.
3772  *
3773  * @messages, if non-%NULL, will be set to point to a newly-allocated
3774  * array of #GSocketControlMessage instances or %NULL if no such
3775  * messages was received. These correspond to the control messages
3776  * received from the kernel, one #GSocketControlMessage per message
3777  * from the kernel. This array is %NULL-terminated and must be freed
3778  * by the caller using g_free() after calling g_object_unref() on each
3779  * element. If @messages is %NULL, any control messages received will
3780  * be discarded.
3781  *
3782  * @num_messages, if non-%NULL, will be set to the number of control
3783  * messages received.
3784  *
3785  * If both @messages and @num_messages are non-%NULL, then
3786  * @num_messages gives the number of #GSocketControlMessage instances
3787  * in @messages (ie: not including the %NULL terminator).
3788  *
3789  * @flags is an in/out parameter. The commonly available arguments
3790  * for this are available in the #GSocketMsgFlags enum, but the
3791  * values there are the same as the system values, and the flags
3792  * are passed in as-is, so you can pass in system-specific flags too
3793  * (and g_socket_receive_message() may pass system-specific flags out).
3794  *
3795  * As with g_socket_receive(), data may be discarded if @socket is
3796  * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
3797  * provide enough buffer space to read a complete message. You can pass
3798  * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
3799  * removing it from the receive queue, but there is no portable way to find
3800  * out the length of the message other than by reading it into a
3801  * sufficiently-large buffer.
3802  *
3803  * If the socket is in blocking mode the call will block until there
3804  * is some data to receive, the connection is closed, or there is an
3805  * error. If there is no data available and the socket is in
3806  * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
3807  * returned. To be notified when data is available, wait for the
3808  * %G_IO_IN condition.
3809  *
3810  * On error -1 is returned and @error is set accordingly.
3811  *
3812  * Returns: Number of bytes read, or 0 if the connection was closed by
3813  * the peer, or -1 on error
3814  *
3815  * Since: 2.22
3816  */
3817 gssize
3818 g_socket_receive_message (GSocket                 *socket,
3819                           GSocketAddress         **address,
3820                           GInputVector            *vectors,
3821                           gint                     num_vectors,
3822                           GSocketControlMessage ***messages,
3823                           gint                    *num_messages,
3824                           gint                    *flags,
3825                           GCancellable            *cancellable,
3826                           GError                 **error)
3827 {
3828   GInputVector one_vector;
3829   char one_byte;
3830
3831   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3832
3833   if (!check_socket (socket, error))
3834     return -1;
3835
3836   if (g_cancellable_set_error_if_cancelled (cancellable, error))
3837     return -1;
3838
3839   if (num_vectors == -1)
3840     {
3841       for (num_vectors = 0;
3842            vectors[num_vectors].buffer != NULL;
3843            num_vectors++)
3844         ;
3845     }
3846
3847   if (num_vectors == 0)
3848     {
3849       one_vector.buffer = &one_byte;
3850       one_vector.size = 1;
3851       num_vectors = 1;
3852       vectors = &one_vector;
3853     }
3854
3855 #ifndef G_OS_WIN32
3856   {
3857     struct msghdr msg;
3858     gssize result;
3859     struct sockaddr_storage one_sockaddr;
3860
3861     /* name */
3862     if (address)
3863       {
3864         msg.msg_name = &one_sockaddr;
3865         msg.msg_namelen = sizeof (struct sockaddr_storage);
3866       }
3867     else
3868       {
3869         msg.msg_name = NULL;
3870         msg.msg_namelen = 0;
3871       }
3872
3873     /* iov */
3874     /* this entire expression will be evaluated at compile time */
3875     if (sizeof *msg.msg_iov == sizeof *vectors &&
3876         sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3877         G_STRUCT_OFFSET (struct iovec, iov_base) ==
3878         G_STRUCT_OFFSET (GInputVector, buffer) &&
3879         sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3880         G_STRUCT_OFFSET (struct iovec, iov_len) ==
3881         G_STRUCT_OFFSET (GInputVector, size))
3882       /* ABI is compatible */
3883       {
3884         msg.msg_iov = (struct iovec *) vectors;
3885         msg.msg_iovlen = num_vectors;
3886       }
3887     else
3888       /* ABI is incompatible */
3889       {
3890         gint i;
3891
3892         msg.msg_iov = g_newa (struct iovec, num_vectors);
3893         for (i = 0; i < num_vectors; i++)
3894           {
3895             msg.msg_iov[i].iov_base = vectors[i].buffer;
3896             msg.msg_iov[i].iov_len = vectors[i].size;
3897           }
3898         msg.msg_iovlen = num_vectors;
3899       }
3900
3901     /* control */
3902     msg.msg_control = g_alloca (2048);
3903     msg.msg_controllen = 2048;
3904
3905     /* flags */
3906     if (flags != NULL)
3907       msg.msg_flags = *flags;
3908     else
3909       msg.msg_flags = 0;
3910
3911     /* We always set the close-on-exec flag so we don't leak file
3912      * descriptors into child processes.  Note that gunixfdmessage.c
3913      * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
3914      */
3915 #ifdef MSG_CMSG_CLOEXEC
3916     msg.msg_flags |= MSG_CMSG_CLOEXEC;
3917 #endif
3918
3919     /* do it */
3920     while (1)
3921       {
3922         if (socket->priv->blocking &&
3923             !g_socket_condition_wait (socket,
3924                                       G_IO_IN, cancellable, error))
3925           return -1;
3926
3927         result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
3928 #ifdef MSG_CMSG_CLOEXEC 
3929         if (result < 0 && get_socket_errno () == EINVAL)
3930           {
3931             /* We must be running on an old kernel.  Call without the flag. */
3932             msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
3933             result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
3934           }
3935 #endif
3936
3937         if (result < 0)
3938           {
3939             int errsv = get_socket_errno ();
3940
3941             if (errsv == EINTR)
3942               continue;
3943
3944             if (socket->priv->blocking &&
3945                 (errsv == EWOULDBLOCK ||
3946                  errsv == EAGAIN))
3947               continue;
3948
3949             g_set_error (error, G_IO_ERROR,
3950                          socket_io_error_from_errno (errsv),
3951                          _("Error receiving message: %s"), socket_strerror (errsv));
3952
3953             return -1;
3954           }
3955         break;
3956       }
3957
3958     /* decode address */
3959     if (address != NULL)
3960       {
3961         if (msg.msg_namelen > 0)
3962           *address = g_socket_address_new_from_native (msg.msg_name,
3963                                                        msg.msg_namelen);
3964         else
3965           *address = NULL;
3966       }
3967
3968     /* decode control messages */
3969     {
3970       GPtrArray *my_messages = NULL;
3971       struct cmsghdr *cmsg;
3972
3973       for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
3974         {
3975           GSocketControlMessage *message;
3976
3977           message = g_socket_control_message_deserialize (cmsg->cmsg_level,
3978                                                           cmsg->cmsg_type,
3979                                                           cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
3980                                                           CMSG_DATA (cmsg));
3981           if (message == NULL)
3982             /* We've already spewed about the problem in the
3983                deserialization code, so just continue */
3984             continue;
3985
3986           if (messages == NULL)
3987             {
3988               /* we have to do it this way if the user ignores the
3989                * messages so that we will close any received fds.
3990                */
3991               g_object_unref (message);
3992             }
3993           else
3994             {
3995               if (my_messages == NULL)
3996                 my_messages = g_ptr_array_new ();
3997               g_ptr_array_add (my_messages, message);
3998             }
3999         }
4000
4001       if (num_messages)
4002         *num_messages = my_messages != NULL ? my_messages->len : 0;
4003
4004       if (messages)
4005         {
4006           if (my_messages == NULL)
4007             {
4008               *messages = NULL;
4009             }
4010           else
4011             {
4012               g_ptr_array_add (my_messages, NULL);
4013               *messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
4014             }
4015         }
4016       else
4017         {
4018           g_assert (my_messages == NULL);
4019         }
4020     }
4021
4022     /* capture the flags */
4023     if (flags != NULL)
4024       *flags = msg.msg_flags;
4025
4026     return result;
4027   }
4028 #else
4029   {
4030     struct sockaddr_storage addr;
4031     int addrlen;
4032     DWORD bytes_received;
4033     DWORD win_flags;
4034     int result;
4035     WSABUF *bufs;
4036     gint i;
4037
4038     /* iov */
4039     bufs = g_newa (WSABUF, num_vectors);
4040     for (i = 0; i < num_vectors; i++)
4041       {
4042         bufs[i].buf = (char *)vectors[i].buffer;
4043         bufs[i].len = (gulong)vectors[i].size;
4044       }
4045
4046     /* flags */
4047     if (flags != NULL)
4048       win_flags = *flags;
4049     else
4050       win_flags = 0;
4051
4052     /* do it */
4053     while (1)
4054       {
4055         if (socket->priv->blocking &&
4056             !g_socket_condition_wait (socket,
4057                                       G_IO_IN, cancellable, error))
4058           return -1;
4059
4060         addrlen = sizeof addr;
4061         if (address)
4062           result = WSARecvFrom (socket->priv->fd,
4063                                 bufs, num_vectors,
4064                                 &bytes_received, &win_flags,
4065                                 (struct sockaddr *)&addr, &addrlen,
4066                                 NULL, NULL);
4067         else
4068           result = WSARecv (socket->priv->fd,
4069                             bufs, num_vectors,
4070                             &bytes_received, &win_flags,
4071                             NULL, NULL);
4072         if (result != 0)
4073           {
4074             int errsv = get_socket_errno ();
4075
4076             if (errsv == WSAEINTR)
4077               continue;
4078
4079             win32_unset_event_mask (socket, FD_READ);
4080
4081             if (socket->priv->blocking &&
4082                 errsv == WSAEWOULDBLOCK)
4083               continue;
4084
4085             g_set_error (error, G_IO_ERROR,
4086                          socket_io_error_from_errno (errsv),
4087                          _("Error receiving message: %s"), socket_strerror (errsv));
4088
4089             return -1;
4090           }
4091         win32_unset_event_mask (socket, FD_READ);
4092         break;
4093       }
4094
4095     /* decode address */
4096     if (address != NULL)
4097       {
4098         if (addrlen > 0)
4099           *address = g_socket_address_new_from_native (&addr, addrlen);
4100         else
4101           *address = NULL;
4102       }
4103
4104     /* capture the flags */
4105     if (flags != NULL)
4106       *flags = win_flags;
4107
4108     if (messages != NULL)
4109       *messages = NULL;
4110     if (num_messages != NULL)
4111       *num_messages = 0;
4112
4113     return bytes_received;
4114   }
4115 #endif
4116 }
4117
4118 /**
4119  * g_socket_get_credentials:
4120  * @socket: a #GSocket.
4121  * @error: #GError for error reporting, or %NULL to ignore.
4122  *
4123  * Returns the credentials of the foreign process connected to this
4124  * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
4125  * sockets).
4126  *
4127  * If this operation isn't supported on the OS, the method fails with
4128  * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
4129  * by reading the %SO_PEERCRED option on the underlying socket.
4130  *
4131  * Other ways to obtain credentials from a foreign peer includes the
4132  * #GUnixCredentialsMessage type and
4133  * g_unix_connection_send_credentials() /
4134  * g_unix_connection_receive_credentials() functions.
4135  *
4136  * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
4137  * that must be freed with g_object_unref().
4138  *
4139  * Since: 2.26
4140  */
4141 GCredentials *
4142 g_socket_get_credentials (GSocket   *socket,
4143                           GError   **error)
4144 {
4145   GCredentials *ret;
4146
4147   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
4148   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
4149
4150   ret = NULL;
4151
4152 #if defined(__linux__) || defined(__OpenBSD__)
4153   {
4154     socklen_t optlen;
4155 #if defined(__linux__)
4156     struct ucred native_creds;
4157     optlen = sizeof (struct ucred);
4158 #elif defined(__OpenBSD__)
4159     struct sockpeercred native_creds;
4160     optlen = sizeof (struct sockpeercred);
4161 #endif
4162     if (getsockopt (socket->priv->fd,
4163                     SOL_SOCKET,
4164                     SO_PEERCRED,
4165                     (void *)&native_creds,
4166                     &optlen) != 0)
4167       {
4168         int errsv = get_socket_errno ();
4169         g_set_error (error,
4170                      G_IO_ERROR,
4171                      socket_io_error_from_errno (errsv),
4172                      _("Unable to get pending error: %s"),
4173                      socket_strerror (errsv));
4174       }
4175     else
4176       {
4177         ret = g_credentials_new ();
4178         g_credentials_set_native (ret,
4179 #if defined(__linux__)
4180                                   G_CREDENTIALS_TYPE_LINUX_UCRED,
4181 #elif defined(__OpenBSD__)
4182                                   G_CREDENTIALS_TYPE_OPENBSD_SOCKPEERCRED,
4183 #endif
4184                                   &native_creds);
4185       }
4186   }
4187 #else
4188   g_set_error_literal (error,
4189                        G_IO_ERROR,
4190                        G_IO_ERROR_NOT_SUPPORTED,
4191                        _("g_socket_get_credentials not implemented for this OS"));
4192 #endif
4193
4194   return ret;
4195 }