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