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