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