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