Coverage Report

Created: 2025-07-01 07:09

/src/glib/gio/gsocket.c
Line
Count
Source (jump to first uncovered line)
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
 * Copyright © 2015 Collabora, Ltd.
7
 *
8
 * This library is free software; you can redistribute it and/or
9
 * modify it under the terms of the GNU Lesser General Public
10
 * License as published by the Free Software Foundation; either
11
 * version 2.1 of the License, or (at your option) any later version.
12
 *
13
 * This library is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16
 * Lesser General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU Lesser General
19
 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
20
 *
21
 * Authors: Christian Kellner <gicmo@gnome.org>
22
 *          Samuel Cormier-Iijima <sciyoshi@gmail.com>
23
 *          Ryan Lortie <desrt@desrt.ca>
24
 *          Alexander Larsson <alexl@redhat.com>
25
 *          Philip Withnall <philip.withnall@collabora.co.uk>
26
 */
27
28
#include "config.h"
29
30
#include "gsocket.h"
31
32
#ifdef G_OS_UNIX
33
#include "glib-unix.h"
34
#endif
35
36
#include <errno.h>
37
#include <signal.h>
38
#include <string.h>
39
#include <stdlib.h>
40
41
#ifndef G_OS_WIN32
42
# include <fcntl.h>
43
# include <unistd.h>
44
# include <sys/ioctl.h>
45
#endif
46
47
#ifdef HAVE_SIOCGIFADDR
48
#include <net/if.h>
49
#endif
50
51
#ifdef HAVE_SYS_FILIO_H
52
# include <sys/filio.h>
53
#endif
54
55
#ifdef G_OS_UNIX
56
#include <sys/uio.h>
57
#endif
58
59
#define GOBJECT_COMPILATION
60
#include "gobject/gtype-private.h" /* For _PRELUDE type define */
61
#undef GOBJECT_COMPILATION
62
#include "gcancellable.h"
63
#include "gdatagrambased.h"
64
#include "gioenumtypes.h"
65
#include "ginetaddress.h"
66
#include "ginetsocketaddress.h"
67
#include "ginitable.h"
68
#include "gioerror.h"
69
#include "gioenums.h"
70
#include "gioerror.h"
71
#include "gnetworkingprivate.h"
72
#include "gsocketaddress.h"
73
#include "gsocketcontrolmessage.h"
74
#include "gcredentials.h"
75
#include "gcredentialsprivate.h"
76
#include "glibintl.h"
77
#include "gioprivate.h"
78
79
/**
80
 * SECTION:gsocket
81
 * @short_description: Low-level socket object
82
 * @include: gio/gio.h
83
 * @see_also: #GInitable, [<gnetworking.h>][gio-gnetworking.h]
84
 *
85
 * A #GSocket is a low-level networking primitive. It is a more or less
86
 * direct mapping of the BSD socket API in a portable GObject based API.
87
 * It supports both the UNIX socket implementations and winsock2 on Windows.
88
 *
89
 * #GSocket is the platform independent base upon which the higher level
90
 * network primitives are based. Applications are not typically meant to
91
 * use it directly, but rather through classes like #GSocketClient,
92
 * #GSocketService and #GSocketConnection. However there may be cases where
93
 * direct use of #GSocket is useful.
94
 *
95
 * #GSocket implements the #GInitable interface, so if it is manually constructed
96
 * by e.g. g_object_new() you must call g_initable_init() and check the
97
 * results before using the object. This is done automatically in
98
 * g_socket_new() and g_socket_new_from_fd(), so these functions can return
99
 * %NULL.
100
 *
101
 * Sockets operate in two general modes, blocking or non-blocking. When
102
 * in blocking mode all operations (which don’t take an explicit blocking
103
 * parameter) block until the requested operation
104
 * is finished or there is an error. In non-blocking mode all calls that
105
 * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
106
 * To know when a call would successfully run you can call g_socket_condition_check(),
107
 * or g_socket_condition_wait(). You can also use g_socket_create_source() and
108
 * attach it to a #GMainContext to get callbacks when I/O is possible.
109
 * Note that all sockets are always set to non blocking mode in the system, and
110
 * blocking mode is emulated in GSocket.
111
 *
112
 * When working in non-blocking mode applications should always be able to
113
 * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
114
 * function said that I/O was possible. This can easily happen in case
115
 * of a race condition in the application, but it can also happen for other
116
 * reasons. For instance, on Windows a socket is always seen as writable
117
 * until a write returns %G_IO_ERROR_WOULD_BLOCK.
118
 *
119
 * #GSockets can be either connection oriented or datagram based.
120
 * For connection oriented types you must first establish a connection by
121
 * either connecting to an address or accepting a connection from another
122
 * address. For connectionless socket types the target/source address is
123
 * specified or received in each I/O operation.
124
 *
125
 * All socket file descriptors are set to be close-on-exec.
126
 *
127
 * Note that creating a #GSocket causes the signal %SIGPIPE to be
128
 * ignored for the remainder of the program. If you are writing a
129
 * command-line utility that uses #GSocket, you may need to take into
130
 * account the fact that your program will not automatically be killed
131
 * if it tries to write to %stdout after it has been closed.
132
 *
133
 * Like most other APIs in GLib, #GSocket is not inherently thread safe. To use
134
 * a #GSocket concurrently from multiple threads, you must implement your own
135
 * locking.
136
 *
137
 * Since: 2.22
138
 */
139
140
static void     g_socket_initable_iface_init (GInitableIface  *iface);
141
static gboolean g_socket_initable_init       (GInitable       *initable,
142
                GCancellable    *cancellable,
143
                GError         **error);
144
145
static void     g_socket_datagram_based_iface_init       (GDatagramBasedInterface *iface);
146
static gint     g_socket_datagram_based_receive_messages (GDatagramBased  *self,
147
                                                          GInputMessage   *messages,
148
                                                          guint            num_messages,
149
                                                          gint             flags,
150
                                                          gint64           timeout_us,
151
                                                          GCancellable    *cancellable,
152
                                                          GError         **error);
153
static gint     g_socket_datagram_based_send_messages    (GDatagramBased  *self,
154
                                                          GOutputMessage  *messages,
155
                                                          guint            num_messages,
156
                                                          gint             flags,
157
                                                          gint64           timeout_us,
158
                                                          GCancellable    *cancellable,
159
                                                          GError         **error);
160
static GSource *g_socket_datagram_based_create_source    (GDatagramBased           *self,
161
                                                          GIOCondition              condition,
162
                                                          GCancellable             *cancellable);
163
static GIOCondition g_socket_datagram_based_condition_check      (GDatagramBased   *datagram_based,
164
                                                                  GIOCondition      condition);
165
static gboolean     g_socket_datagram_based_condition_wait       (GDatagramBased   *datagram_based,
166
                                                                  GIOCondition      condition,
167
                                                                  gint64            timeout_us,
168
                                                                  GCancellable     *cancellable,
169
                                                                  GError          **error);
170
171
static GSocketAddress *
172
cache_recv_address (GSocket *socket, struct sockaddr *native, size_t native_len);
173
174
static gssize
175
g_socket_receive_message_with_timeout  (GSocket                 *socket,
176
                                        GSocketAddress         **address,
177
                                        GInputVector            *vectors,
178
                                        gint                     num_vectors,
179
                                        GSocketControlMessage ***messages,
180
                                        gint                    *num_messages,
181
                                        gint                    *flags,
182
                                        gint64                   timeout_us,
183
                                        GCancellable            *cancellable,
184
                                        GError                 **error);
185
static gint
186
g_socket_receive_messages_with_timeout (GSocket        *socket,
187
                                        GInputMessage  *messages,
188
                                        guint           num_messages,
189
                                        gint            flags,
190
                                        gint64          timeout_us,
191
                                        GCancellable   *cancellable,
192
                                        GError        **error);
193
static gint
194
g_socket_send_messages_with_timeout    (GSocket        *socket,
195
                                        GOutputMessage *messages,
196
                                        guint           num_messages,
197
                                        gint            flags,
198
                                        gint64          timeout_us,
199
                                        GCancellable   *cancellable,
200
                                        GError        **error);
201
202
enum
203
{
204
  PROP_0,
205
  PROP_FAMILY,
206
  PROP_TYPE,
207
  PROP_PROTOCOL,
208
  PROP_FD,
209
  PROP_BLOCKING,
210
  PROP_LISTEN_BACKLOG,
211
  PROP_KEEPALIVE,
212
  PROP_LOCAL_ADDRESS,
213
  PROP_REMOTE_ADDRESS,
214
  PROP_TIMEOUT,
215
  PROP_TTL,
216
  PROP_BROADCAST,
217
  PROP_MULTICAST_LOOPBACK,
218
  PROP_MULTICAST_TTL
219
};
220
221
/* Size of the receiver cache for g_socket_receive_from() */
222
0
#define RECV_ADDR_CACHE_SIZE 8
223
224
struct _GSocketPrivate
225
{
226
  GSocketFamily   family;
227
  GSocketType     type;
228
  GSocketProtocol protocol;
229
  gint            fd;
230
  gint            listen_backlog;
231
  guint           timeout;
232
  GError         *construct_error;
233
  GSocketAddress *remote_address;
234
  guint           inited : 1;
235
  guint           blocking : 1;
236
  guint           keepalive : 1;
237
  guint           closed : 1;
238
  guint           connected_read : 1;
239
  guint           connected_write : 1;
240
  guint           listening : 1;
241
  guint           timed_out : 1;
242
  guint           connect_pending : 1;
243
#ifdef G_OS_WIN32
244
  WSAEVENT        event;
245
  gboolean        waiting;
246
  DWORD           waiting_result;
247
  int             current_events;
248
  int             current_errors;
249
  int             selected_events;
250
  GList          *requested_conditions; /* list of requested GIOCondition * */
251
  GMutex          win32_source_lock;
252
  GCond           win32_source_cond;
253
#endif
254
255
  struct {
256
    GSocketAddress *addr;
257
    struct sockaddr *native;
258
    gsize native_len;
259
    guint64 last_used;
260
  } recv_addr_cache[RECV_ADDR_CACHE_SIZE];
261
};
262
263
_G_DEFINE_TYPE_EXTENDED_WITH_PRELUDE (GSocket, g_socket, G_TYPE_OBJECT, 0,
264
                                      /* Need a prelude for https://bugzilla.gnome.org/show_bug.cgi?id=674885 */
265
                                      g_type_ensure (G_TYPE_SOCKET_FAMILY);
266
                                      g_type_ensure (G_TYPE_SOCKET_TYPE);
267
                                      g_type_ensure (G_TYPE_SOCKET_PROTOCOL);
268
                                      g_type_ensure (G_TYPE_SOCKET_ADDRESS);
269
                                      /* And networking init is appropriate for the prelude */
270
                                      g_networking_init ();
271
                                      , /* And now the regular type init code */
272
                                      G_ADD_PRIVATE (GSocket)
273
                                      G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
274
                                                             g_socket_initable_iface_init);
275
                                      G_IMPLEMENT_INTERFACE (G_TYPE_DATAGRAM_BASED,
276
                                                             g_socket_datagram_based_iface_init));
277
278
static int
279
get_socket_errno (void)
280
0
{
281
0
#ifndef G_OS_WIN32
282
0
  return errno;
283
#else
284
  return WSAGetLastError ();
285
#endif
286
0
}
287
288
static GIOErrorEnum
289
socket_io_error_from_errno (int err)
290
0
{
291
#ifdef G_OS_WIN32
292
  return g_io_error_from_win32_error (err);
293
#else
294
0
  return g_io_error_from_errno (err);
295
0
#endif
296
0
}
297
298
static const char *
299
socket_strerror (int err)
300
0
{
301
0
#ifndef G_OS_WIN32
302
0
  return g_strerror (err);
303
#else
304
  const char *msg_ret;
305
  char *msg;
306
307
  msg = g_win32_error_message (err);
308
309
  msg_ret = g_intern_string (msg);
310
  g_free (msg);
311
312
  return msg_ret;
313
#endif
314
0
}
315
316
/* Wrapper around g_set_error() to avoid doing excess work */
317
#define socket_set_error_lazy(err, errsv, fmt)                          \
318
0
  G_STMT_START {                                                        \
319
0
    GError **__err = (err);                                             \
320
0
    int __errsv = (errsv);                                              \
321
0
                                                                        \
322
0
    if (__err)                                                          \
323
0
      {                                                                 \
324
0
        int __code = socket_io_error_from_errno (__errsv);              \
325
0
        const char *__strerr = socket_strerror (__errsv);               \
326
0
                                                                        \
327
0
        if (__code == G_IO_ERROR_WOULD_BLOCK)                           \
328
0
          g_set_error_literal (__err, G_IO_ERROR, __code, __strerr);    \
329
0
        else                                                            \
330
0
          g_set_error (__err, G_IO_ERROR, __code, fmt, __strerr);       \
331
0
      }                                                                 \
332
0
  } G_STMT_END
333
334
#ifdef G_OS_WIN32
335
#define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
336
static void
337
_win32_unset_event_mask (GSocket *socket, int mask)
338
{
339
  g_mutex_lock (&socket->priv->win32_source_lock);
340
  socket->priv->current_events &= ~mask;
341
  socket->priv->current_errors &= ~mask;
342
  g_mutex_unlock (&socket->priv->win32_source_lock);
343
}
344
#else
345
#define win32_unset_event_mask(_socket, _mask)
346
#endif
347
348
/* Windows has broken prototypes... */
349
#ifdef G_OS_WIN32
350
#define getsockopt(sockfd, level, optname, optval, optlen) \
351
  getsockopt (sockfd, level, optname, (gpointer) optval, (int*) optlen)
352
#define setsockopt(sockfd, level, optname, optval, optlen) \
353
  setsockopt (sockfd, level, optname, (gpointer) optval, optlen)
354
#define getsockname(sockfd, addr, addrlen) \
355
  getsockname (sockfd, addr, (int *)addrlen)
356
#define getpeername(sockfd, addr, addrlen) \
357
  getpeername (sockfd, addr, (int *)addrlen)
358
#define recv(sockfd, buf, len, flags) \
359
  recv (sockfd, (gpointer)buf, len, flags)
360
#endif
361
362
static gchar *
363
address_to_string (GSocketAddress *address)
364
0
{
365
0
  GString *ret = g_string_new ("");
366
367
0
  if (G_IS_INET_SOCKET_ADDRESS (address))
368
0
    {
369
0
      GInetSocketAddress *isa = G_INET_SOCKET_ADDRESS (address);
370
0
      GInetAddress *ia = g_inet_socket_address_get_address (isa);
371
0
      GSocketFamily family = g_inet_address_get_family (ia);
372
0
      gchar *tmp;
373
374
      /* Represent IPv6 addresses in URL style:
375
       * ::1 port 12345 -> [::1]:12345 */
376
0
      if (family == G_SOCKET_FAMILY_IPV6)
377
0
        g_string_append_c (ret, '[');
378
379
0
      tmp = g_inet_address_to_string (ia);
380
0
      g_string_append (ret, tmp);
381
0
      g_free (tmp);
382
383
0
      if (family == G_SOCKET_FAMILY_IPV6)
384
0
        {
385
0
          guint32 scope = g_inet_socket_address_get_scope_id (isa);
386
387
0
          if (scope != 0)
388
0
            g_string_append_printf (ret, "%%%u", scope);
389
390
0
          g_string_append_c (ret, ']');
391
0
        }
392
393
0
      g_string_append_c (ret, ':');
394
395
0
      g_string_append_printf (ret, "%u", g_inet_socket_address_get_port (isa));
396
0
    }
397
0
  else
398
0
    {
399
      /* For unknown address types, just show the type */
400
0
      g_string_append_printf (ret, "(%s)", G_OBJECT_TYPE_NAME (address));
401
0
    }
402
403
0
  return g_string_free (ret, FALSE);
404
0
}
405
406
static gboolean
407
check_socket (GSocket *socket,
408
        GError **error)
409
0
{
410
0
  if (!socket->priv->inited)
411
0
    {
412
0
      g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
413
0
                           _("Invalid socket, not initialized"));
414
0
      return FALSE;
415
0
    }
416
417
0
  if (socket->priv->construct_error)
418
0
    {
419
0
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
420
0
       _("Invalid socket, initialization failed due to: %s"),
421
0
       socket->priv->construct_error->message);
422
0
      return FALSE;
423
0
    }
424
425
0
  if (socket->priv->closed)
426
0
    {
427
0
      g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
428
0
         _("Socket is already closed"));
429
0
      return FALSE;
430
0
    }
431
432
0
  return TRUE;
433
0
}
434
435
static gboolean
436
check_timeout (GSocket *socket,
437
         GError **error)
438
0
{
439
0
  if (socket->priv->timed_out)
440
0
    {
441
0
      socket->priv->timed_out = FALSE;
442
0
      g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
443
0
         _("Socket I/O timed out"));
444
0
      return FALSE;
445
0
    }
446
447
0
  return TRUE;
448
0
}
449
450
static void
451
g_socket_details_from_fd (GSocket *socket)
452
0
{
453
0
  union {
454
0
    struct sockaddr_storage storage;
455
0
    struct sockaddr sa;
456
0
  } address;
457
0
  gint fd;
458
0
  guint addrlen;
459
0
  int value, family;
460
0
  int errsv;
461
462
0
  fd = socket->priv->fd;
463
0
  if (!g_socket_get_option (socket, SOL_SOCKET, SO_TYPE, &value, NULL))
464
0
    {
465
0
      errsv = get_socket_errno ();
466
0
      goto err;
467
0
    }
468
469
0
  switch (value)
470
0
    {
471
0
     case SOCK_STREAM:
472
0
      socket->priv->type = G_SOCKET_TYPE_STREAM;
473
0
      break;
474
475
0
     case SOCK_DGRAM:
476
0
      socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
477
0
      break;
478
479
0
     case SOCK_SEQPACKET:
480
0
      socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
481
0
      break;
482
483
0
     default:
484
0
      socket->priv->type = G_SOCKET_TYPE_INVALID;
485
0
      break;
486
0
    }
487
488
0
  addrlen = sizeof address;
489
0
  if (getsockname (fd, &address.sa, &addrlen) != 0)
490
0
    {
491
0
      errsv = get_socket_errno ();
492
0
      goto err;
493
0
    }
494
495
0
  if (addrlen > 0)
496
0
    {
497
0
      g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
498
0
    sizeof address.storage.ss_family <= addrlen);
499
0
      family = address.storage.ss_family;
500
0
    }
501
0
  else
502
0
    {
503
      /* On Solaris, this happens if the socket is not yet connected.
504
       * But we can use SO_DOMAIN as a workaround there.
505
       */
506
0
#ifdef SO_DOMAIN
507
0
      if (!g_socket_get_option (socket, SOL_SOCKET, SO_DOMAIN, &family, NULL))
508
0
  {
509
0
    errsv = get_socket_errno ();
510
0
    goto err;
511
0
  }
512
#else
513
      /* This will translate to G_IO_ERROR_FAILED on either unix or windows */
514
      errsv = -1;
515
      goto err;
516
#endif
517
0
    }
518
519
0
  switch (family)
520
0
    {
521
0
     case G_SOCKET_FAMILY_IPV4:
522
0
     case G_SOCKET_FAMILY_IPV6:
523
0
       socket->priv->family = address.storage.ss_family;
524
0
       switch (socket->priv->type)
525
0
   {
526
0
   case G_SOCKET_TYPE_STREAM:
527
0
     socket->priv->protocol = G_SOCKET_PROTOCOL_TCP;
528
0
     break;
529
530
0
   case G_SOCKET_TYPE_DATAGRAM:
531
0
     socket->priv->protocol = G_SOCKET_PROTOCOL_UDP;
532
0
     break;
533
534
0
   case G_SOCKET_TYPE_SEQPACKET:
535
0
     socket->priv->protocol = G_SOCKET_PROTOCOL_SCTP;
536
0
     break;
537
538
0
   default:
539
0
     break;
540
0
   }
541
0
       break;
542
543
0
     case G_SOCKET_FAMILY_UNIX:
544
0
       socket->priv->family = G_SOCKET_FAMILY_UNIX;
545
0
       socket->priv->protocol = G_SOCKET_PROTOCOL_DEFAULT;
546
0
       break;
547
548
0
     default:
549
0
       socket->priv->family = G_SOCKET_FAMILY_INVALID;
550
0
       break;
551
0
    }
552
553
0
  if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
554
0
    {
555
0
      addrlen = sizeof address;
556
0
      if (getpeername (fd, &address.sa, &addrlen) >= 0)
557
0
        {
558
0
          socket->priv->connected_read = TRUE;
559
0
          socket->priv->connected_write = TRUE;
560
0
        }
561
0
    }
562
563
0
  if (g_socket_get_option (socket, SOL_SOCKET, SO_KEEPALIVE, &value, NULL))
564
0
    {
565
0
      socket->priv->keepalive = !!value;
566
0
    }
567
0
  else
568
0
    {
569
      /* Can't read, maybe not supported, assume FALSE */
570
0
      socket->priv->keepalive = FALSE;
571
0
    }
572
573
0
  return;
574
575
0
 err:
576
0
  g_set_error (&socket->priv->construct_error, G_IO_ERROR,
577
0
         socket_io_error_from_errno (errsv),
578
0
         _("creating GSocket from fd: %s"),
579
0
         socket_strerror (errsv));
580
0
}
581
582
/* Wrapper around socket() that is shared with gnetworkmonitornetlink.c */
583
gint
584
g_socket (gint     domain,
585
          gint     type,
586
          gint     protocol,
587
          GError **error)
588
0
{
589
0
  int fd, errsv;
590
591
0
#ifdef SOCK_CLOEXEC
592
0
  fd = socket (domain, type | SOCK_CLOEXEC, protocol);
593
0
  errsv = errno;
594
0
  if (fd != -1)
595
0
    return fd;
596
597
  /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
598
0
  if (fd < 0 && (errsv == EINVAL || errsv == EPROTOTYPE))
599
0
#endif
600
0
    fd = socket (domain, type, protocol);
601
602
0
  if (fd < 0)
603
0
    {
604
0
      errsv = get_socket_errno ();
605
606
0
      g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
607
0
       _("Unable to create socket: %s"), socket_strerror (errsv));
608
0
      errno = errsv;
609
0
      return -1;
610
0
    }
611
612
0
#ifndef G_OS_WIN32
613
0
  {
614
0
    int flags;
615
616
    /* We always want to set close-on-exec to protect users. If you
617
       need to so some weird inheritance to exec you can re-enable this
618
       using lower level hacks with g_socket_get_fd(). */
619
0
    flags = fcntl (fd, F_GETFD, 0);
620
0
    if (flags != -1 &&
621
0
  (flags & FD_CLOEXEC) == 0)
622
0
      {
623
0
  flags |= FD_CLOEXEC;
624
0
  fcntl (fd, F_SETFD, flags);
625
0
      }
626
0
  }
627
#else
628
  if ((domain == AF_INET || domain == AF_INET6) && type == SOCK_DGRAM)
629
    {
630
      BOOL new_behavior = FALSE;
631
      DWORD bytes_returned = 0;
632
633
      /* Disable connection reset error on ICMP port unreachable. */
634
      WSAIoctl (fd, SIO_UDP_CONNRESET, &new_behavior, sizeof (new_behavior),
635
                NULL, 0, &bytes_returned, NULL, NULL);
636
    }
637
#endif
638
639
0
  return fd;
640
0
}
641
642
static gint
643
g_socket_create_socket (GSocketFamily   family,
644
      GSocketType     type,
645
      int             protocol,
646
      GError        **error)
647
0
{
648
0
  gint native_type;
649
650
0
  switch (type)
651
0
    {
652
0
     case G_SOCKET_TYPE_STREAM:
653
0
      native_type = SOCK_STREAM;
654
0
      break;
655
656
0
     case G_SOCKET_TYPE_DATAGRAM:
657
0
      native_type = SOCK_DGRAM;
658
0
      break;
659
660
0
     case G_SOCKET_TYPE_SEQPACKET:
661
0
      native_type = SOCK_SEQPACKET;
662
0
      break;
663
664
0
     default:
665
0
      g_assert_not_reached ();
666
0
    }
667
668
0
  if (family <= 0)
669
0
    {
670
0
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
671
0
                   _("Unable to create socket: %s"), _("Unknown family was specified"));
672
0
      return -1;
673
0
    }
674
675
0
  if (protocol == -1)
676
0
    {
677
0
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
678
0
       _("Unable to create socket: %s"), _("Unknown protocol was specified"));
679
0
      return -1;
680
0
    }
681
682
0
  return g_socket (family, native_type, protocol, error);
683
0
}
684
685
static void
686
g_socket_constructed (GObject *object)
687
0
{
688
0
  GSocket *socket = G_SOCKET (object);
689
690
0
  if (socket->priv->fd >= 0)
691
    /* create socket->priv info from the fd */
692
0
    g_socket_details_from_fd (socket);
693
694
0
  else
695
    /* create the fd from socket->priv info */
696
0
    socket->priv->fd = g_socket_create_socket (socket->priv->family,
697
0
                 socket->priv->type,
698
0
                 socket->priv->protocol,
699
0
                 &socket->priv->construct_error);
700
701
0
  if (socket->priv->fd != -1)
702
0
    {
703
0
#ifndef G_OS_WIN32
704
0
      GError *error = NULL;
705
#else
706
      gulong arg;
707
#endif
708
709
      /* Always use native nonblocking sockets, as Windows sets sockets to
710
       * nonblocking automatically in certain operations. This way we make
711
       * things work the same on all platforms.
712
       */
713
0
#ifndef G_OS_WIN32
714
0
      if (!g_unix_set_fd_nonblocking (socket->priv->fd, TRUE, &error))
715
0
        {
716
0
          g_warning ("Error setting socket nonblocking: %s", error->message);
717
0
          g_clear_error (&error);
718
0
        }
719
#else
720
      arg = TRUE;
721
722
      if (ioctlsocket (socket->priv->fd, FIONBIO, &arg) == SOCKET_ERROR)
723
        {
724
          int errsv = get_socket_errno ();
725
          g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
726
        }
727
#endif
728
729
#ifdef SO_NOSIGPIPE
730
      /* See note about SIGPIPE below. */
731
      g_socket_set_option (socket, SOL_SOCKET, SO_NOSIGPIPE, TRUE, NULL);
732
#endif
733
0
    }
734
0
}
735
736
static void
737
g_socket_get_property (GObject    *object,
738
           guint       prop_id,
739
           GValue     *value,
740
           GParamSpec *pspec)
741
0
{
742
0
  GSocket *socket = G_SOCKET (object);
743
0
  GSocketAddress *address;
744
745
0
  switch (prop_id)
746
0
    {
747
0
      case PROP_FAMILY:
748
0
  g_value_set_enum (value, socket->priv->family);
749
0
  break;
750
751
0
      case PROP_TYPE:
752
0
  g_value_set_enum (value, socket->priv->type);
753
0
  break;
754
755
0
      case PROP_PROTOCOL:
756
0
  g_value_set_enum (value, socket->priv->protocol);
757
0
  break;
758
759
0
      case PROP_FD:
760
0
  g_value_set_int (value, socket->priv->fd);
761
0
  break;
762
763
0
      case PROP_BLOCKING:
764
0
  g_value_set_boolean (value, socket->priv->blocking);
765
0
  break;
766
767
0
      case PROP_LISTEN_BACKLOG:
768
0
  g_value_set_int (value, socket->priv->listen_backlog);
769
0
  break;
770
771
0
      case PROP_KEEPALIVE:
772
0
  g_value_set_boolean (value, socket->priv->keepalive);
773
0
  break;
774
775
0
      case PROP_LOCAL_ADDRESS:
776
0
  address = g_socket_get_local_address (socket, NULL);
777
0
  g_value_take_object (value, address);
778
0
  break;
779
780
0
      case PROP_REMOTE_ADDRESS:
781
0
  address = g_socket_get_remote_address (socket, NULL);
782
0
  g_value_take_object (value, address);
783
0
  break;
784
785
0
      case PROP_TIMEOUT:
786
0
  g_value_set_uint (value, socket->priv->timeout);
787
0
  break;
788
789
0
      case PROP_TTL:
790
0
  g_value_set_uint (value, g_socket_get_ttl (socket));
791
0
  break;
792
793
0
      case PROP_BROADCAST:
794
0
  g_value_set_boolean (value, g_socket_get_broadcast (socket));
795
0
  break;
796
797
0
      case PROP_MULTICAST_LOOPBACK:
798
0
  g_value_set_boolean (value, g_socket_get_multicast_loopback (socket));
799
0
  break;
800
801
0
      case PROP_MULTICAST_TTL:
802
0
  g_value_set_uint (value, g_socket_get_multicast_ttl (socket));
803
0
  break;
804
805
0
      default:
806
0
  G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
807
0
    }
808
0
}
809
810
static void
811
g_socket_set_property (GObject      *object,
812
           guint         prop_id,
813
           const GValue *value,
814
           GParamSpec   *pspec)
815
0
{
816
0
  GSocket *socket = G_SOCKET (object);
817
818
0
  switch (prop_id)
819
0
    {
820
0
      case PROP_FAMILY:
821
0
  socket->priv->family = g_value_get_enum (value);
822
0
  break;
823
824
0
      case PROP_TYPE:
825
0
  socket->priv->type = g_value_get_enum (value);
826
0
  break;
827
828
0
      case PROP_PROTOCOL:
829
0
  socket->priv->protocol = g_value_get_enum (value);
830
0
  break;
831
832
0
      case PROP_FD:
833
0
  socket->priv->fd = g_value_get_int (value);
834
0
  break;
835
836
0
      case PROP_BLOCKING:
837
0
  g_socket_set_blocking (socket, g_value_get_boolean (value));
838
0
  break;
839
840
0
      case PROP_LISTEN_BACKLOG:
841
0
  g_socket_set_listen_backlog (socket, g_value_get_int (value));
842
0
  break;
843
844
0
      case PROP_KEEPALIVE:
845
0
  g_socket_set_keepalive (socket, g_value_get_boolean (value));
846
0
  break;
847
848
0
      case PROP_TIMEOUT:
849
0
  g_socket_set_timeout (socket, g_value_get_uint (value));
850
0
  break;
851
852
0
      case PROP_TTL:
853
0
  g_socket_set_ttl (socket, g_value_get_uint (value));
854
0
  break;
855
856
0
      case PROP_BROADCAST:
857
0
  g_socket_set_broadcast (socket, g_value_get_boolean (value));
858
0
  break;
859
860
0
      case PROP_MULTICAST_LOOPBACK:
861
0
  g_socket_set_multicast_loopback (socket, g_value_get_boolean (value));
862
0
  break;
863
864
0
      case PROP_MULTICAST_TTL:
865
0
  g_socket_set_multicast_ttl (socket, g_value_get_uint (value));
866
0
  break;
867
868
0
      default:
869
0
  G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
870
0
    }
871
0
}
872
873
static void
874
g_socket_finalize (GObject *object)
875
0
{
876
0
  GSocket *socket = G_SOCKET (object);
877
0
  gint i;
878
879
0
  g_clear_error (&socket->priv->construct_error);
880
881
0
  if (socket->priv->fd != -1 &&
882
0
      !socket->priv->closed)
883
0
    g_socket_close (socket, NULL);
884
885
0
  if (socket->priv->remote_address)
886
0
    g_object_unref (socket->priv->remote_address);
887
888
#ifdef G_OS_WIN32
889
  if (socket->priv->event != WSA_INVALID_EVENT)
890
    {
891
      WSACloseEvent (socket->priv->event);
892
      socket->priv->event = WSA_INVALID_EVENT;
893
    }
894
895
  g_assert (socket->priv->requested_conditions == NULL);
896
  g_mutex_clear (&socket->priv->win32_source_lock);
897
  g_cond_clear (&socket->priv->win32_source_cond);
898
#endif
899
900
0
  for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
901
0
    {
902
0
      if (socket->priv->recv_addr_cache[i].addr)
903
0
        {
904
0
          g_object_unref (socket->priv->recv_addr_cache[i].addr);
905
0
          g_free (socket->priv->recv_addr_cache[i].native);
906
0
        }
907
0
    }
908
909
0
  if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
910
0
    (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
911
0
}
912
913
static void
914
g_socket_class_init (GSocketClass *klass)
915
0
{
916
0
  GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
917
918
0
#ifdef SIGPIPE
919
  /* There is no portable, thread-safe way to avoid having the process
920
   * be killed by SIGPIPE when calling send() or sendmsg(), so we are
921
   * forced to simply ignore the signal process-wide.
922
   *
923
   * Even if we ignore it though, gdb will still stop if the app
924
   * receives a SIGPIPE, which can be confusing and annoying. So when
925
   * possible, we also use MSG_NOSIGNAL / SO_NOSIGPIPE elsewhere to
926
   * prevent the signal from occurring at all.
927
   */
928
0
  signal (SIGPIPE, SIG_IGN);
929
0
#endif
930
931
0
  gobject_class->finalize = g_socket_finalize;
932
0
  gobject_class->constructed = g_socket_constructed;
933
0
  gobject_class->set_property = g_socket_set_property;
934
0
  gobject_class->get_property = g_socket_get_property;
935
936
0
  g_object_class_install_property (gobject_class, PROP_FAMILY,
937
0
           g_param_spec_enum ("family",
938
0
                  P_("Socket family"),
939
0
                  P_("The sockets address family"),
940
0
                  G_TYPE_SOCKET_FAMILY,
941
0
                  G_SOCKET_FAMILY_INVALID,
942
0
                  G_PARAM_CONSTRUCT_ONLY |
943
0
                                                      G_PARAM_READWRITE |
944
0
                                                      G_PARAM_STATIC_STRINGS));
945
946
0
  g_object_class_install_property (gobject_class, PROP_TYPE,
947
0
           g_param_spec_enum ("type",
948
0
                  P_("Socket type"),
949
0
                  P_("The sockets type"),
950
0
                  G_TYPE_SOCKET_TYPE,
951
0
                  G_SOCKET_TYPE_STREAM,
952
0
                  G_PARAM_CONSTRUCT_ONLY |
953
0
                                                      G_PARAM_READWRITE |
954
0
                                                      G_PARAM_STATIC_STRINGS));
955
956
0
  g_object_class_install_property (gobject_class, PROP_PROTOCOL,
957
0
           g_param_spec_enum ("protocol",
958
0
                  P_("Socket protocol"),
959
0
                  P_("The id of the protocol to use, or -1 for unknown"),
960
0
                  G_TYPE_SOCKET_PROTOCOL,
961
0
                  G_SOCKET_PROTOCOL_UNKNOWN,
962
0
                  G_PARAM_CONSTRUCT_ONLY |
963
0
                                                      G_PARAM_READWRITE |
964
0
                                                      G_PARAM_STATIC_STRINGS));
965
966
0
  g_object_class_install_property (gobject_class, PROP_FD,
967
0
           g_param_spec_int ("fd",
968
0
                 P_("File descriptor"),
969
0
                 P_("The sockets file descriptor"),
970
0
                 G_MININT,
971
0
                 G_MAXINT,
972
0
                 -1,
973
0
                 G_PARAM_CONSTRUCT_ONLY |
974
0
                                                     G_PARAM_READWRITE |
975
0
                                                     G_PARAM_STATIC_STRINGS));
976
977
0
  g_object_class_install_property (gobject_class, PROP_BLOCKING,
978
0
           g_param_spec_boolean ("blocking",
979
0
               P_("blocking"),
980
0
               P_("Whether or not I/O on this socket is blocking"),
981
0
               TRUE,
982
0
               G_PARAM_READWRITE |
983
0
                                                         G_PARAM_STATIC_STRINGS));
984
985
0
  g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
986
0
           g_param_spec_int ("listen-backlog",
987
0
                 P_("Listen backlog"),
988
0
                 P_("Outstanding connections in the listen queue"),
989
0
                 0,
990
0
                 SOMAXCONN,
991
0
                 10,
992
0
                 G_PARAM_READWRITE |
993
0
                                                     G_PARAM_STATIC_STRINGS));
994
995
0
  g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
996
0
           g_param_spec_boolean ("keepalive",
997
0
               P_("Keep connection alive"),
998
0
               P_("Keep connection alive by sending periodic pings"),
999
0
               FALSE,
1000
0
               G_PARAM_READWRITE |
1001
0
                                                         G_PARAM_STATIC_STRINGS));
1002
1003
0
  g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
1004
0
           g_param_spec_object ("local-address",
1005
0
              P_("Local address"),
1006
0
              P_("The local address the socket is bound to"),
1007
0
              G_TYPE_SOCKET_ADDRESS,
1008
0
              G_PARAM_READABLE |
1009
0
                                                        G_PARAM_STATIC_STRINGS));
1010
1011
0
  g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
1012
0
           g_param_spec_object ("remote-address",
1013
0
              P_("Remote address"),
1014
0
              P_("The remote address the socket is connected to"),
1015
0
              G_TYPE_SOCKET_ADDRESS,
1016
0
              G_PARAM_READABLE |
1017
0
                                                        G_PARAM_STATIC_STRINGS));
1018
1019
  /**
1020
   * GSocket:timeout:
1021
   *
1022
   * The timeout in seconds on socket I/O
1023
   *
1024
   * Since: 2.26
1025
   */
1026
0
  g_object_class_install_property (gobject_class, PROP_TIMEOUT,
1027
0
           g_param_spec_uint ("timeout",
1028
0
                  P_("Timeout"),
1029
0
                  P_("The timeout in seconds on socket I/O"),
1030
0
                  0,
1031
0
                  G_MAXUINT,
1032
0
                  0,
1033
0
                  G_PARAM_READWRITE |
1034
0
                  G_PARAM_STATIC_STRINGS));
1035
1036
  /**
1037
   * GSocket:broadcast:
1038
   *
1039
   * Whether the socket should allow sending to broadcast addresses.
1040
   *
1041
   * Since: 2.32
1042
   */
1043
0
  g_object_class_install_property (gobject_class, PROP_BROADCAST,
1044
0
           g_param_spec_boolean ("broadcast",
1045
0
               P_("Broadcast"),
1046
0
               P_("Whether to allow sending to broadcast addresses"),
1047
0
               FALSE,
1048
0
               G_PARAM_READWRITE |
1049
0
                                                         G_PARAM_STATIC_STRINGS));
1050
1051
  /**
1052
   * GSocket:ttl:
1053
   *
1054
   * Time-to-live for outgoing unicast packets
1055
   *
1056
   * Since: 2.32
1057
   */
1058
0
  g_object_class_install_property (gobject_class, PROP_TTL,
1059
0
           g_param_spec_uint ("ttl",
1060
0
                  P_("TTL"),
1061
0
                  P_("Time-to-live of outgoing unicast packets"),
1062
0
                  0, G_MAXUINT, 0,
1063
0
                  G_PARAM_READWRITE |
1064
0
                  G_PARAM_STATIC_STRINGS));
1065
1066
  /**
1067
   * GSocket:multicast-loopback:
1068
   *
1069
   * Whether outgoing multicast packets loop back to the local host.
1070
   *
1071
   * Since: 2.32
1072
   */
1073
0
  g_object_class_install_property (gobject_class, PROP_MULTICAST_LOOPBACK,
1074
0
           g_param_spec_boolean ("multicast-loopback",
1075
0
               P_("Multicast loopback"),
1076
0
               P_("Whether outgoing multicast packets loop back to the local host"),
1077
0
               TRUE,
1078
0
               G_PARAM_READWRITE |
1079
0
                                                         G_PARAM_STATIC_STRINGS));
1080
1081
  /**
1082
   * GSocket:multicast-ttl:
1083
   *
1084
   * Time-to-live out outgoing multicast packets
1085
   *
1086
   * Since: 2.32
1087
   */
1088
0
  g_object_class_install_property (gobject_class, PROP_MULTICAST_TTL,
1089
0
           g_param_spec_uint ("multicast-ttl",
1090
0
                  P_("Multicast TTL"),
1091
0
                  P_("Time-to-live of outgoing multicast packets"),
1092
0
                  0, G_MAXUINT, 1,
1093
0
                  G_PARAM_READWRITE |
1094
0
                  G_PARAM_STATIC_STRINGS));
1095
0
}
1096
1097
static void
1098
g_socket_initable_iface_init (GInitableIface *iface)
1099
0
{
1100
0
  iface->init = g_socket_initable_init;
1101
0
}
1102
1103
static void
1104
g_socket_datagram_based_iface_init (GDatagramBasedInterface *iface)
1105
0
{
1106
0
  iface->receive_messages = g_socket_datagram_based_receive_messages;
1107
0
  iface->send_messages = g_socket_datagram_based_send_messages;
1108
0
  iface->create_source = g_socket_datagram_based_create_source;
1109
0
  iface->condition_check = g_socket_datagram_based_condition_check;
1110
0
  iface->condition_wait = g_socket_datagram_based_condition_wait;
1111
0
}
1112
1113
static void
1114
g_socket_init (GSocket *socket)
1115
0
{
1116
0
  socket->priv = g_socket_get_instance_private (socket);
1117
1118
0
  socket->priv->fd = -1;
1119
0
  socket->priv->blocking = TRUE;
1120
0
  socket->priv->listen_backlog = 10;
1121
0
  socket->priv->construct_error = NULL;
1122
#ifdef G_OS_WIN32
1123
  socket->priv->event = WSA_INVALID_EVENT;
1124
  g_mutex_init (&socket->priv->win32_source_lock);
1125
  g_cond_init (&socket->priv->win32_source_cond);
1126
#endif
1127
0
}
1128
1129
static gboolean
1130
g_socket_initable_init (GInitable *initable,
1131
      GCancellable *cancellable,
1132
      GError  **error)
1133
0
{
1134
0
  GSocket  *socket;
1135
1136
0
  g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
1137
1138
0
  socket = G_SOCKET (initable);
1139
1140
0
  if (cancellable != NULL)
1141
0
    {
1142
0
      g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1143
0
                           _("Cancellable initialization not supported"));
1144
0
      return FALSE;
1145
0
    }
1146
1147
0
  socket->priv->inited = TRUE;
1148
1149
0
  if (socket->priv->construct_error)
1150
0
    {
1151
0
      if (error)
1152
0
  *error = g_error_copy (socket->priv->construct_error);
1153
0
      return FALSE;
1154
0
    }
1155
1156
1157
0
  return TRUE;
1158
0
}
1159
1160
static gboolean
1161
check_datagram_based (GDatagramBased  *self,
1162
                      GError         **error)
1163
0
{
1164
0
  switch (g_socket_get_socket_type (G_SOCKET (self)))
1165
0
    {
1166
0
    case G_SOCKET_TYPE_INVALID:
1167
0
    case G_SOCKET_TYPE_STREAM:
1168
0
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1169
0
                   _("Cannot use datagram operations on a non-datagram "
1170
0
                     "socket."));
1171
0
      return FALSE;
1172
0
    case G_SOCKET_TYPE_DATAGRAM:
1173
0
    case G_SOCKET_TYPE_SEQPACKET:
1174
      /* Fall through. */
1175
0
      break;
1176
0
    }
1177
1178
  /* Due to us sharing #GSocketSource with the #GSocket implementation, it is
1179
   * pretty tricky to split out #GSocket:timeout so that it does not affect
1180
   * #GDatagramBased operations (but still affects #GSocket operations). It is
1181
   * not worth that effort — just disallow it and require the user to specify
1182
   * timeouts on a per-operation basis. */
1183
0
  if (g_socket_get_timeout (G_SOCKET (self)) != 0)
1184
0
    {
1185
0
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1186
0
                   _("Cannot use datagram operations on a socket with a "
1187
0
                     "timeout set."));
1188
0
      return FALSE;
1189
0
    }
1190
1191
0
  return TRUE;
1192
0
}
1193
1194
static gint
1195
g_socket_datagram_based_receive_messages (GDatagramBased  *self,
1196
                                          GInputMessage   *messages,
1197
                                          guint            num_messages,
1198
                                          gint             flags,
1199
                                          gint64           timeout_us,
1200
                                          GCancellable    *cancellable,
1201
                                          GError         **error)
1202
0
{
1203
0
  if (!check_datagram_based (self, error))
1204
0
    return FALSE;
1205
1206
0
  return g_socket_receive_messages_with_timeout (G_SOCKET (self), messages,
1207
0
                                                 num_messages, flags, timeout_us,
1208
0
                                                 cancellable, error);
1209
0
}
1210
1211
static gint
1212
g_socket_datagram_based_send_messages (GDatagramBased  *self,
1213
                                       GOutputMessage  *messages,
1214
                                       guint            num_messages,
1215
                                       gint             flags,
1216
                                       gint64           timeout_us,
1217
                                       GCancellable    *cancellable,
1218
                                       GError         **error)
1219
0
{
1220
0
  if (!check_datagram_based (self, error))
1221
0
    return FALSE;
1222
1223
0
  return g_socket_send_messages_with_timeout (G_SOCKET (self), messages,
1224
0
                                              num_messages, flags, timeout_us,
1225
0
                                              cancellable, error);
1226
0
}
1227
1228
static GSource *
1229
g_socket_datagram_based_create_source (GDatagramBased  *self,
1230
                                       GIOCondition     condition,
1231
                                       GCancellable    *cancellable)
1232
0
{
1233
0
  if (!check_datagram_based (self, NULL))
1234
0
    return NULL;
1235
1236
0
  return g_socket_create_source (G_SOCKET (self), condition, cancellable);
1237
0
}
1238
1239
static GIOCondition
1240
g_socket_datagram_based_condition_check (GDatagramBased  *datagram_based,
1241
                                         GIOCondition     condition)
1242
0
{
1243
0
  if (!check_datagram_based (datagram_based, NULL))
1244
0
    return G_IO_ERR;
1245
1246
0
  return g_socket_condition_check (G_SOCKET (datagram_based), condition);
1247
0
}
1248
1249
static gboolean
1250
g_socket_datagram_based_condition_wait (GDatagramBased  *datagram_based,
1251
                                        GIOCondition     condition,
1252
                                        gint64           timeout_us,
1253
                                        GCancellable    *cancellable,
1254
                                        GError         **error)
1255
0
{
1256
0
  if (!check_datagram_based (datagram_based, error))
1257
0
    return FALSE;
1258
1259
0
  return g_socket_condition_timed_wait (G_SOCKET (datagram_based), condition,
1260
0
                                        timeout_us, cancellable, error);
1261
0
}
1262
1263
/**
1264
 * g_socket_new:
1265
 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
1266
 * @type: the socket type to use.
1267
 * @protocol: the id of the protocol to use, or 0 for default.
1268
 * @error: #GError for error reporting, or %NULL to ignore.
1269
 *
1270
 * Creates a new #GSocket with the defined family, type and protocol.
1271
 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
1272
 * for the family and type is used.
1273
 *
1274
 * The @protocol is a family and type specific int that specifies what
1275
 * kind of protocol to use. #GSocketProtocol lists several common ones.
1276
 * Many families only support one protocol, and use 0 for this, others
1277
 * support several and using 0 means to use the default protocol for
1278
 * the family and type.
1279
 *
1280
 * The protocol id is passed directly to the operating
1281
 * system, so you can use protocols not listed in #GSocketProtocol if you
1282
 * know the protocol number used for it.
1283
 *
1284
 * Returns: a #GSocket or %NULL on error.
1285
 *     Free the returned object with g_object_unref().
1286
 *
1287
 * Since: 2.22
1288
 */
1289
GSocket *
1290
g_socket_new (GSocketFamily     family,
1291
        GSocketType       type,
1292
        GSocketProtocol   protocol,
1293
        GError          **error)
1294
0
{
1295
0
  return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1296
0
           NULL, error,
1297
0
           "family", family,
1298
0
           "type", type,
1299
0
           "protocol", protocol,
1300
0
           NULL));
1301
0
}
1302
1303
/**
1304
 * g_socket_new_from_fd:
1305
 * @fd: a native socket file descriptor.
1306
 * @error: #GError for error reporting, or %NULL to ignore.
1307
 *
1308
 * Creates a new #GSocket from a native file descriptor
1309
 * or winsock SOCKET handle.
1310
 *
1311
 * This reads all the settings from the file descriptor so that
1312
 * all properties should work. Note that the file descriptor
1313
 * will be set to non-blocking mode, independent on the blocking
1314
 * mode of the #GSocket.
1315
 *
1316
 * On success, the returned #GSocket takes ownership of @fd. On failure, the
1317
 * caller must close @fd themselves.
1318
 *
1319
 * Since GLib 2.46, it is no longer a fatal error to call this on a non-socket
1320
 * descriptor.  Instead, a GError will be set with code %G_IO_ERROR_FAILED
1321
 *
1322
 * Returns: a #GSocket or %NULL on error.
1323
 *     Free the returned object with g_object_unref().
1324
 *
1325
 * Since: 2.22
1326
 */
1327
GSocket *
1328
g_socket_new_from_fd (gint     fd,
1329
          GError **error)
1330
0
{
1331
0
  return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1332
0
           NULL, error,
1333
0
           "fd", fd,
1334
0
           NULL));
1335
0
}
1336
1337
/**
1338
 * g_socket_set_blocking:
1339
 * @socket: a #GSocket.
1340
 * @blocking: Whether to use blocking I/O or not.
1341
 *
1342
 * Sets the blocking mode of the socket. In blocking mode
1343
 * all operations (which don’t take an explicit blocking parameter) block until
1344
 * they succeed or there is an error. In
1345
 * non-blocking mode all functions return results immediately or
1346
 * with a %G_IO_ERROR_WOULD_BLOCK error.
1347
 *
1348
 * All sockets are created in blocking mode. However, note that the
1349
 * platform level socket is always non-blocking, and blocking mode
1350
 * is a GSocket level feature.
1351
 *
1352
 * Since: 2.22
1353
 */
1354
void
1355
g_socket_set_blocking (GSocket  *socket,
1356
           gboolean  blocking)
1357
0
{
1358
0
  g_return_if_fail (G_IS_SOCKET (socket));
1359
1360
0
  blocking = !!blocking;
1361
1362
0
  if (socket->priv->blocking == blocking)
1363
0
    return;
1364
1365
0
  socket->priv->blocking = blocking;
1366
0
  g_object_notify (G_OBJECT (socket), "blocking");
1367
0
}
1368
1369
/**
1370
 * g_socket_get_blocking:
1371
 * @socket: a #GSocket.
1372
 *
1373
 * Gets the blocking mode of the socket. For details on blocking I/O,
1374
 * see g_socket_set_blocking().
1375
 *
1376
 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
1377
 *
1378
 * Since: 2.22
1379
 */
1380
gboolean
1381
g_socket_get_blocking (GSocket *socket)
1382
0
{
1383
0
  g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1384
1385
0
  return socket->priv->blocking;
1386
0
}
1387
1388
/**
1389
 * g_socket_set_keepalive:
1390
 * @socket: a #GSocket.
1391
 * @keepalive: Value for the keepalive flag
1392
 *
1393
 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
1394
 * this flag is set on a socket, the system will attempt to verify that the
1395
 * remote socket endpoint is still present if a sufficiently long period of
1396
 * time passes with no data being exchanged. If the system is unable to
1397
 * verify the presence of the remote endpoint, it will automatically close
1398
 * the connection.
1399
 *
1400
 * This option is only functional on certain kinds of sockets. (Notably,
1401
 * %G_SOCKET_PROTOCOL_TCP sockets.)
1402
 *
1403
 * The exact time between pings is system- and protocol-dependent, but will
1404
 * normally be at least two hours. Most commonly, you would set this flag
1405
 * on a server socket if you want to allow clients to remain idle for long
1406
 * periods of time, but also want to ensure that connections are eventually
1407
 * garbage-collected if clients crash or become unreachable.
1408
 *
1409
 * Since: 2.22
1410
 */
1411
void
1412
g_socket_set_keepalive (GSocket  *socket,
1413
      gboolean  keepalive)
1414
0
{
1415
0
  GError *error = NULL;
1416
1417
0
  g_return_if_fail (G_IS_SOCKET (socket));
1418
1419
0
  keepalive = !!keepalive;
1420
0
  if (socket->priv->keepalive == keepalive)
1421
0
    return;
1422
1423
0
  if (!g_socket_set_option (socket, SOL_SOCKET, SO_KEEPALIVE,
1424
0
          keepalive, &error))
1425
0
    {
1426
0
      g_warning ("error setting keepalive: %s", error->message);
1427
0
      g_error_free (error);
1428
0
      return;
1429
0
    }
1430
1431
0
  socket->priv->keepalive = keepalive;
1432
0
  g_object_notify (G_OBJECT (socket), "keepalive");
1433
0
}
1434
1435
/**
1436
 * g_socket_get_keepalive:
1437
 * @socket: a #GSocket.
1438
 *
1439
 * Gets the keepalive mode of the socket. For details on this,
1440
 * see g_socket_set_keepalive().
1441
 *
1442
 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1443
 *
1444
 * Since: 2.22
1445
 */
1446
gboolean
1447
g_socket_get_keepalive (GSocket *socket)
1448
0
{
1449
0
  g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1450
1451
0
  return socket->priv->keepalive;
1452
0
}
1453
1454
/**
1455
 * g_socket_get_listen_backlog:
1456
 * @socket: a #GSocket.
1457
 *
1458
 * Gets the listen backlog setting of the socket. For details on this,
1459
 * see g_socket_set_listen_backlog().
1460
 *
1461
 * Returns: the maximum number of pending connections.
1462
 *
1463
 * Since: 2.22
1464
 */
1465
gint
1466
g_socket_get_listen_backlog  (GSocket *socket)
1467
0
{
1468
0
  g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1469
1470
0
  return socket->priv->listen_backlog;
1471
0
}
1472
1473
/**
1474
 * g_socket_set_listen_backlog:
1475
 * @socket: a #GSocket.
1476
 * @backlog: the maximum number of pending connections.
1477
 *
1478
 * Sets the maximum number of outstanding connections allowed
1479
 * when listening on this socket. If more clients than this are
1480
 * connecting to the socket and the application is not handling them
1481
 * on time then the new connections will be refused.
1482
 *
1483
 * Note that this must be called before g_socket_listen() and has no
1484
 * effect if called after that.
1485
 *
1486
 * Since: 2.22
1487
 */
1488
void
1489
g_socket_set_listen_backlog (GSocket *socket,
1490
           gint     backlog)
1491
0
{
1492
0
  g_return_if_fail (G_IS_SOCKET (socket));
1493
0
  g_return_if_fail (!socket->priv->listening);
1494
1495
0
  if (backlog != socket->priv->listen_backlog)
1496
0
    {
1497
0
      socket->priv->listen_backlog = backlog;
1498
0
      g_object_notify (G_OBJECT (socket), "listen-backlog");
1499
0
    }
1500
0
}
1501
1502
/**
1503
 * g_socket_get_timeout:
1504
 * @socket: a #GSocket.
1505
 *
1506
 * Gets the timeout setting of the socket. For details on this, see
1507
 * g_socket_set_timeout().
1508
 *
1509
 * Returns: the timeout in seconds
1510
 *
1511
 * Since: 2.26
1512
 */
1513
guint
1514
g_socket_get_timeout (GSocket *socket)
1515
0
{
1516
0
  g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1517
1518
0
  return socket->priv->timeout;
1519
0
}
1520
1521
/**
1522
 * g_socket_set_timeout:
1523
 * @socket: a #GSocket.
1524
 * @timeout: the timeout for @socket, in seconds, or 0 for none
1525
 *
1526
 * Sets the time in seconds after which I/O operations on @socket will
1527
 * time out if they have not yet completed.
1528
 *
1529
 * On a blocking socket, this means that any blocking #GSocket
1530
 * operation will time out after @timeout seconds of inactivity,
1531
 * returning %G_IO_ERROR_TIMED_OUT.
1532
 *
1533
 * On a non-blocking socket, calls to g_socket_condition_wait() will
1534
 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1535
 * created with g_socket_create_source() will trigger after
1536
 * @timeout seconds of inactivity, with the requested condition
1537
 * set, at which point calling g_socket_receive(), g_socket_send(),
1538
 * g_socket_check_connect_result(), etc, will fail with
1539
 * %G_IO_ERROR_TIMED_OUT.
1540
 *
1541
 * If @timeout is 0 (the default), operations will never time out
1542
 * on their own.
1543
 *
1544
 * Note that if an I/O operation is interrupted by a signal, this may
1545
 * cause the timeout to be reset.
1546
 *
1547
 * Since: 2.26
1548
 */
1549
void
1550
g_socket_set_timeout (GSocket *socket,
1551
          guint    timeout)
1552
0
{
1553
0
  g_return_if_fail (G_IS_SOCKET (socket));
1554
1555
0
  if (timeout != socket->priv->timeout)
1556
0
    {
1557
0
      socket->priv->timeout = timeout;
1558
0
      g_object_notify (G_OBJECT (socket), "timeout");
1559
0
    }
1560
0
}
1561
1562
/**
1563
 * g_socket_get_ttl:
1564
 * @socket: a #GSocket.
1565
 *
1566
 * Gets the unicast time-to-live setting on @socket; see
1567
 * g_socket_set_ttl() for more details.
1568
 *
1569
 * Returns: the time-to-live setting on @socket
1570
 *
1571
 * Since: 2.32
1572
 */
1573
guint
1574
g_socket_get_ttl (GSocket *socket)
1575
0
{
1576
0
  GError *error = NULL;
1577
0
  gint value;
1578
1579
0
  g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1580
1581
0
  if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1582
0
    {
1583
0
      g_socket_get_option (socket, IPPROTO_IP, IP_TTL,
1584
0
         &value, &error);
1585
0
    }
1586
0
  else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1587
0
    {
1588
0
      g_socket_get_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1589
0
         &value, &error);
1590
0
    }
1591
0
  else
1592
0
    g_return_val_if_reached (0);
1593
1594
0
  if (error)
1595
0
    {
1596
0
      g_warning ("error getting unicast ttl: %s", error->message);
1597
0
      g_error_free (error);
1598
0
      return 0;
1599
0
    }
1600
1601
0
  return value;
1602
0
}
1603
1604
/**
1605
 * g_socket_set_ttl:
1606
 * @socket: a #GSocket.
1607
 * @ttl: the time-to-live value for all unicast packets on @socket
1608
 *
1609
 * Sets the time-to-live for outgoing unicast packets on @socket.
1610
 * By default the platform-specific default value is used.
1611
 *
1612
 * Since: 2.32
1613
 */
1614
void
1615
g_socket_set_ttl (GSocket  *socket,
1616
                  guint     ttl)
1617
0
{
1618
0
  GError *error = NULL;
1619
1620
0
  g_return_if_fail (G_IS_SOCKET (socket));
1621
1622
0
  if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1623
0
    {
1624
0
      g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1625
0
         ttl, &error);
1626
0
    }
1627
0
  else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1628
0
    {
1629
0
      g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1630
0
         ttl, NULL);
1631
0
      g_socket_set_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1632
0
         ttl, &error);
1633
0
    }
1634
0
  else
1635
0
    g_return_if_reached ();
1636
1637
0
  if (error)
1638
0
    {
1639
0
      g_warning ("error setting unicast ttl: %s", error->message);
1640
0
      g_error_free (error);
1641
0
      return;
1642
0
    }
1643
1644
0
  g_object_notify (G_OBJECT (socket), "ttl");
1645
0
}
1646
1647
/**
1648
 * g_socket_get_broadcast:
1649
 * @socket: a #GSocket.
1650
 *
1651
 * Gets the broadcast setting on @socket; if %TRUE,
1652
 * it is possible to send packets to broadcast
1653
 * addresses.
1654
 *
1655
 * Returns: the broadcast setting on @socket
1656
 *
1657
 * Since: 2.32
1658
 */
1659
gboolean
1660
g_socket_get_broadcast (GSocket *socket)
1661
0
{
1662
0
  GError *error = NULL;
1663
0
  gint value;
1664
1665
0
  g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1666
1667
0
  if (!g_socket_get_option (socket, SOL_SOCKET, SO_BROADCAST,
1668
0
          &value, &error))
1669
0
    {
1670
0
      g_warning ("error getting broadcast: %s", error->message);
1671
0
      g_error_free (error);
1672
0
      return FALSE;
1673
0
    }
1674
1675
0
  return !!value;
1676
0
}
1677
1678
/**
1679
 * g_socket_set_broadcast:
1680
 * @socket: a #GSocket.
1681
 * @broadcast: whether @socket should allow sending to broadcast
1682
 *     addresses
1683
 *
1684
 * Sets whether @socket should allow sending to broadcast addresses.
1685
 * This is %FALSE by default.
1686
 *
1687
 * Since: 2.32
1688
 */
1689
void
1690
g_socket_set_broadcast (GSocket    *socket,
1691
                        gboolean    broadcast)
1692
0
{
1693
0
  GError *error = NULL;
1694
1695
0
  g_return_if_fail (G_IS_SOCKET (socket));
1696
1697
0
  broadcast = !!broadcast;
1698
1699
0
  if (!g_socket_set_option (socket, SOL_SOCKET, SO_BROADCAST,
1700
0
          broadcast, &error))
1701
0
    {
1702
0
      g_warning ("error setting broadcast: %s", error->message);
1703
0
      g_error_free (error);
1704
0
      return;
1705
0
    }
1706
1707
0
  g_object_notify (G_OBJECT (socket), "broadcast");
1708
0
}
1709
1710
/**
1711
 * g_socket_get_multicast_loopback:
1712
 * @socket: a #GSocket.
1713
 *
1714
 * Gets the multicast loopback setting on @socket; if %TRUE (the
1715
 * default), outgoing multicast packets will be looped back to
1716
 * multicast listeners on the same host.
1717
 *
1718
 * Returns: the multicast loopback setting on @socket
1719
 *
1720
 * Since: 2.32
1721
 */
1722
gboolean
1723
g_socket_get_multicast_loopback (GSocket *socket)
1724
0
{
1725
0
  GError *error = NULL;
1726
0
  gint value;
1727
1728
0
  g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1729
1730
0
  if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1731
0
    {
1732
0
      g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1733
0
         &value, &error);
1734
0
    }
1735
0
  else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1736
0
    {
1737
0
      g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1738
0
         &value, &error);
1739
0
    }
1740
0
  else
1741
0
    g_return_val_if_reached (FALSE);
1742
1743
0
  if (error)
1744
0
    {
1745
0
      g_warning ("error getting multicast loopback: %s", error->message);
1746
0
      g_error_free (error);
1747
0
      return FALSE;
1748
0
    }
1749
1750
0
  return !!value;
1751
0
}
1752
1753
/**
1754
 * g_socket_set_multicast_loopback:
1755
 * @socket: a #GSocket.
1756
 * @loopback: whether @socket should receive messages sent to its
1757
 *   multicast groups from the local host
1758
 *
1759
 * Sets whether outgoing multicast packets will be received by sockets
1760
 * listening on that multicast address on the same host. This is %TRUE
1761
 * by default.
1762
 *
1763
 * Since: 2.32
1764
 */
1765
void
1766
g_socket_set_multicast_loopback (GSocket    *socket,
1767
         gboolean    loopback)
1768
0
{
1769
0
  GError *error = NULL;
1770
1771
0
  g_return_if_fail (G_IS_SOCKET (socket));
1772
1773
0
  loopback = !!loopback;
1774
1775
0
  if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1776
0
    {
1777
0
      g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1778
0
         loopback, &error);
1779
0
    }
1780
0
  else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1781
0
    {
1782
0
      g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1783
0
         loopback, NULL);
1784
0
      g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1785
0
         loopback, &error);
1786
0
    }
1787
0
  else
1788
0
    g_return_if_reached ();
1789
1790
0
  if (error)
1791
0
    {
1792
0
      g_warning ("error setting multicast loopback: %s", error->message);
1793
0
      g_error_free (error);
1794
0
      return;
1795
0
    }
1796
1797
0
  g_object_notify (G_OBJECT (socket), "multicast-loopback");
1798
0
}
1799
1800
/**
1801
 * g_socket_get_multicast_ttl:
1802
 * @socket: a #GSocket.
1803
 *
1804
 * Gets the multicast time-to-live setting on @socket; see
1805
 * g_socket_set_multicast_ttl() for more details.
1806
 *
1807
 * Returns: the multicast time-to-live setting on @socket
1808
 *
1809
 * Since: 2.32
1810
 */
1811
guint
1812
g_socket_get_multicast_ttl (GSocket *socket)
1813
0
{
1814
0
  GError *error = NULL;
1815
0
  gint value;
1816
1817
0
  g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1818
1819
0
  if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1820
0
    {
1821
0
      g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1822
0
         &value, &error);
1823
0
    }
1824
0
  else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1825
0
    {
1826
0
      g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1827
0
         &value, &error);
1828
0
    }
1829
0
  else
1830
0
    g_return_val_if_reached (FALSE);
1831
1832
0
  if (error)
1833
0
    {
1834
0
      g_warning ("error getting multicast ttl: %s", error->message);
1835
0
      g_error_free (error);
1836
0
      return FALSE;
1837
0
    }
1838
1839
0
  return value;
1840
0
}
1841
1842
/**
1843
 * g_socket_set_multicast_ttl:
1844
 * @socket: a #GSocket.
1845
 * @ttl: the time-to-live value for all multicast datagrams on @socket
1846
 *
1847
 * Sets the time-to-live for outgoing multicast datagrams on @socket.
1848
 * By default, this is 1, meaning that multicast packets will not leave
1849
 * the local network.
1850
 *
1851
 * Since: 2.32
1852
 */
1853
void
1854
g_socket_set_multicast_ttl (GSocket  *socket,
1855
                            guint     ttl)
1856
0
{
1857
0
  GError *error = NULL;
1858
1859
0
  g_return_if_fail (G_IS_SOCKET (socket));
1860
1861
0
  if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1862
0
    {
1863
0
      g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1864
0
         ttl, &error);
1865
0
    }
1866
0
  else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1867
0
    {
1868
0
      g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1869
0
         ttl, NULL);
1870
0
      g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1871
0
         ttl, &error);
1872
0
    }
1873
0
  else
1874
0
    g_return_if_reached ();
1875
1876
0
  if (error)
1877
0
    {
1878
0
      g_warning ("error setting multicast ttl: %s", error->message);
1879
0
      g_error_free (error);
1880
0
      return;
1881
0
    }
1882
1883
0
  g_object_notify (G_OBJECT (socket), "multicast-ttl");
1884
0
}
1885
1886
/**
1887
 * g_socket_get_family:
1888
 * @socket: a #GSocket.
1889
 *
1890
 * Gets the socket family of the socket.
1891
 *
1892
 * Returns: a #GSocketFamily
1893
 *
1894
 * Since: 2.22
1895
 */
1896
GSocketFamily
1897
g_socket_get_family (GSocket *socket)
1898
0
{
1899
0
  g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1900
1901
0
  return socket->priv->family;
1902
0
}
1903
1904
/**
1905
 * g_socket_get_socket_type:
1906
 * @socket: a #GSocket.
1907
 *
1908
 * Gets the socket type of the socket.
1909
 *
1910
 * Returns: a #GSocketType
1911
 *
1912
 * Since: 2.22
1913
 */
1914
GSocketType
1915
g_socket_get_socket_type (GSocket *socket)
1916
0
{
1917
0
  g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1918
1919
0
  return socket->priv->type;
1920
0
}
1921
1922
/**
1923
 * g_socket_get_protocol:
1924
 * @socket: a #GSocket.
1925
 *
1926
 * Gets the socket protocol id the socket was created with.
1927
 * In case the protocol is unknown, -1 is returned.
1928
 *
1929
 * Returns: a protocol id, or -1 if unknown
1930
 *
1931
 * Since: 2.22
1932
 */
1933
GSocketProtocol
1934
g_socket_get_protocol (GSocket *socket)
1935
0
{
1936
0
  g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1937
1938
0
  return socket->priv->protocol;
1939
0
}
1940
1941
/**
1942
 * g_socket_get_fd:
1943
 * @socket: a #GSocket.
1944
 *
1945
 * Returns the underlying OS socket object. On unix this
1946
 * is a socket file descriptor, and on Windows this is
1947
 * a Winsock2 SOCKET handle. This may be useful for
1948
 * doing platform specific or otherwise unusual operations
1949
 * on the socket.
1950
 *
1951
 * Returns: the file descriptor of the socket.
1952
 *
1953
 * Since: 2.22
1954
 */
1955
int
1956
g_socket_get_fd (GSocket *socket)
1957
0
{
1958
0
  g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1959
1960
0
  return socket->priv->fd;
1961
0
}
1962
1963
/**
1964
 * g_socket_get_local_address:
1965
 * @socket: a #GSocket.
1966
 * @error: #GError for error reporting, or %NULL to ignore.
1967
 *
1968
 * Try to get the local address of a bound socket. This is only
1969
 * useful if the socket has been bound to a local address,
1970
 * either explicitly or implicitly when connecting.
1971
 *
1972
 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1973
 *     Free the returned object with g_object_unref().
1974
 *
1975
 * Since: 2.22
1976
 */
1977
GSocketAddress *
1978
g_socket_get_local_address (GSocket  *socket,
1979
          GError  **error)
1980
0
{
1981
0
  union {
1982
0
    struct sockaddr_storage storage;
1983
0
    struct sockaddr sa;
1984
0
  } buffer;
1985
0
  guint len = sizeof (buffer);
1986
1987
0
  g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1988
1989
0
  if (getsockname (socket->priv->fd, &buffer.sa, &len) < 0)
1990
0
    {
1991
0
      int errsv = get_socket_errno ();
1992
0
      g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1993
0
       _("could not get local address: %s"), socket_strerror (errsv));
1994
0
      return NULL;
1995
0
    }
1996
1997
0
  return g_socket_address_new_from_native (&buffer.storage, len);
1998
0
}
1999
2000
/**
2001
 * g_socket_get_remote_address:
2002
 * @socket: a #GSocket.
2003
 * @error: #GError for error reporting, or %NULL to ignore.
2004
 *
2005
 * Try to get the remote address of a connected socket. This is only
2006
 * useful for connection oriented sockets that have been connected.
2007
 *
2008
 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
2009
 *     Free the returned object with g_object_unref().
2010
 *
2011
 * Since: 2.22
2012
 */
2013
GSocketAddress *
2014
g_socket_get_remote_address (GSocket  *socket,
2015
           GError  **error)
2016
0
{
2017
0
  union {
2018
0
    struct sockaddr_storage storage;
2019
0
    struct sockaddr sa;
2020
0
  } buffer;
2021
0
  guint len = sizeof (buffer);
2022
2023
0
  g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
2024
2025
0
  if (socket->priv->connect_pending)
2026
0
    {
2027
0
      if (!g_socket_check_connect_result (socket, error))
2028
0
        return NULL;
2029
0
      else
2030
0
        socket->priv->connect_pending = FALSE;
2031
0
    }
2032
2033
0
  if (!socket->priv->remote_address)
2034
0
    {
2035
0
      if (getpeername (socket->priv->fd, &buffer.sa, &len) < 0)
2036
0
  {
2037
0
    int errsv = get_socket_errno ();
2038
0
    g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2039
0
           _("could not get remote address: %s"), socket_strerror (errsv));
2040
0
    return NULL;
2041
0
  }
2042
2043
0
      socket->priv->remote_address = g_socket_address_new_from_native (&buffer.storage, len);
2044
0
    }
2045
2046
0
  return g_object_ref (socket->priv->remote_address);
2047
0
}
2048
2049
/**
2050
 * g_socket_is_connected:
2051
 * @socket: a #GSocket.
2052
 *
2053
 * Check whether the socket is connected. This is only useful for
2054
 * connection-oriented sockets.
2055
 *
2056
 * If using g_socket_shutdown(), this function will return %TRUE until the
2057
 * socket has been shut down for reading and writing. If you do a non-blocking
2058
 * connect, this function will not return %TRUE until after you call
2059
 * g_socket_check_connect_result().
2060
 *
2061
 * Returns: %TRUE if socket is connected, %FALSE otherwise.
2062
 *
2063
 * Since: 2.22
2064
 */
2065
gboolean
2066
g_socket_is_connected (GSocket *socket)
2067
0
{
2068
0
  g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2069
2070
0
  return (socket->priv->connected_read || socket->priv->connected_write);
2071
0
}
2072
2073
/**
2074
 * g_socket_listen:
2075
 * @socket: a #GSocket.
2076
 * @error: #GError for error reporting, or %NULL to ignore.
2077
 *
2078
 * Marks the socket as a server socket, i.e. a socket that is used
2079
 * to accept incoming requests using g_socket_accept().
2080
 *
2081
 * Before calling this the socket must be bound to a local address using
2082
 * g_socket_bind().
2083
 *
2084
 * To set the maximum amount of outstanding clients, use
2085
 * g_socket_set_listen_backlog().
2086
 *
2087
 * Returns: %TRUE on success, %FALSE on error.
2088
 *
2089
 * Since: 2.22
2090
 */
2091
gboolean
2092
g_socket_listen (GSocket  *socket,
2093
     GError  **error)
2094
0
{
2095
0
  g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2096
2097
0
  if (!check_socket (socket, error))
2098
0
    return FALSE;
2099
2100
0
  if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
2101
0
    {
2102
0
      int errsv = get_socket_errno ();
2103
2104
0
      g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2105
0
       _("could not listen: %s"), socket_strerror (errsv));
2106
0
      return FALSE;
2107
0
    }
2108
2109
0
  socket->priv->listening = TRUE;
2110
2111
0
  return TRUE;
2112
0
}
2113
2114
/**
2115
 * g_socket_bind:
2116
 * @socket: a #GSocket.
2117
 * @address: a #GSocketAddress specifying the local address.
2118
 * @allow_reuse: whether to allow reusing this address
2119
 * @error: #GError for error reporting, or %NULL to ignore.
2120
 *
2121
 * When a socket is created it is attached to an address family, but it
2122
 * doesn't have an address in this family. g_socket_bind() assigns the
2123
 * address (sometimes called name) of the socket.
2124
 *
2125
 * It is generally required to bind to a local address before you can
2126
 * receive connections. (See g_socket_listen() and g_socket_accept() ).
2127
 * In certain situations, you may also want to bind a socket that will be
2128
 * used to initiate connections, though this is not normally required.
2129
 *
2130
 * If @socket is a TCP socket, then @allow_reuse controls the setting
2131
 * of the `SO_REUSEADDR` socket option; normally it should be %TRUE for
2132
 * server sockets (sockets that you will eventually call
2133
 * g_socket_accept() on), and %FALSE for client sockets. (Failing to
2134
 * set this flag on a server socket may cause g_socket_bind() to return
2135
 * %G_IO_ERROR_ADDRESS_IN_USE if the server program is stopped and then
2136
 * immediately restarted.)
2137
 *
2138
 * If @socket is a UDP socket, then @allow_reuse determines whether or
2139
 * not other UDP sockets can be bound to the same address at the same
2140
 * time. In particular, you can have several UDP sockets bound to the
2141
 * same address, and they will all receive all of the multicast and
2142
 * broadcast packets sent to that address. (The behavior of unicast
2143
 * UDP packets to an address with multiple listeners is not defined.)
2144
 *
2145
 * Returns: %TRUE on success, %FALSE on error.
2146
 *
2147
 * Since: 2.22
2148
 */
2149
gboolean
2150
g_socket_bind (GSocket         *socket,
2151
         GSocketAddress  *address,
2152
         gboolean         reuse_address,
2153
         GError         **error)
2154
0
{
2155
0
  union {
2156
0
    struct sockaddr_storage storage;
2157
0
    struct sockaddr sa;
2158
0
  } addr;
2159
0
  gboolean so_reuseaddr;
2160
0
#ifdef SO_REUSEPORT
2161
0
  gboolean so_reuseport;
2162
0
#endif
2163
2164
0
  g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2165
2166
0
  if (!check_socket (socket, error))
2167
0
    return FALSE;
2168
2169
0
  if (!g_socket_address_to_native (address, &addr.storage, sizeof addr, error))
2170
0
    return FALSE;
2171
2172
  /* On Windows, SO_REUSEADDR has the semantics we want for UDP
2173
   * sockets, but has nasty side effects we don't want for TCP
2174
   * sockets.
2175
   *
2176
   * On other platforms, we set SO_REUSEPORT, if it exists, for
2177
   * UDP sockets, and SO_REUSEADDR for all sockets, hoping that
2178
   * if SO_REUSEPORT doesn't exist, then SO_REUSEADDR will have
2179
   * the desired semantics on UDP (as it does on Linux, although
2180
   * Linux has SO_REUSEPORT too as of 3.9).
2181
   */
2182
2183
#ifdef G_OS_WIN32
2184
  so_reuseaddr = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
2185
#else
2186
0
  so_reuseaddr = !!reuse_address;
2187
0
#endif
2188
2189
0
#ifdef SO_REUSEPORT
2190
0
  so_reuseport = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
2191
0
#endif
2192
2193
  /* Ignore errors here, the only likely error is "not supported", and
2194
   * this is a "best effort" thing mainly.
2195
   */
2196
0
  g_socket_set_option (socket, SOL_SOCKET, SO_REUSEADDR, so_reuseaddr, NULL);
2197
0
#ifdef SO_REUSEPORT
2198
0
  g_socket_set_option (socket, SOL_SOCKET, SO_REUSEPORT, so_reuseport, NULL);
2199
0
#endif
2200
2201
0
  if (bind (socket->priv->fd, &addr.sa,
2202
0
      g_socket_address_get_native_size (address)) < 0)
2203
0
    {
2204
0
      int errsv = get_socket_errno ();
2205
0
      gchar *address_string = address_to_string (address);
2206
2207
0
      g_set_error (error,
2208
0
       G_IO_ERROR, socket_io_error_from_errno (errsv),
2209
0
       _("Error binding to address %s: %s"),
2210
0
       address_string, socket_strerror (errsv));
2211
0
      g_free (address_string);
2212
0
      return FALSE;
2213
0
    }
2214
2215
0
  return TRUE;
2216
0
}
2217
2218
#ifdef G_OS_WIN32
2219
static gulong
2220
g_socket_w32_get_adapter_ipv4_addr (const gchar *name_or_ip)
2221
{
2222
  ULONG bufsize = 15000; /* MS-recommended initial bufsize */
2223
  DWORD ret = ERROR_BUFFER_OVERFLOW;
2224
  unsigned int malloc_iterations = 0;
2225
  PIP_ADAPTER_ADDRESSES addr_buf = NULL, eth_adapter;
2226
  wchar_t *wchar_name_or_ip = NULL;
2227
  gulong ip_result;
2228
  NET_IFINDEX if_index;
2229
2230
  /*
2231
   * For Windows OS only - return adapter IPv4 address in network byte order.
2232
   *
2233
   * Input string can be either friendly name of adapter, IP address of adapter,
2234
   * indextoname, or fullname of adapter.
2235
   * Example:
2236
   *    192.168.1.109   ===> IP address given directly,
2237
   *                         convert directly with inet_addr() function
2238
   *    Wi-Fi           ===> Adapter friendly name "Wi-Fi",
2239
   *                         scan with GetAdapterAddresses and adapter->FriendlyName
2240
   *    ethernet_32774  ===> Adapter name as returned by if_indextoname
2241
   *    {33E8F5CD-BAEA-4214-BE13-B79AB8080CAB} ===> Adaptername,
2242
   *                         as returned in GetAdapterAddresses and adapter->AdapterName
2243
   */
2244
2245
  /* Step 1: Check if string is an IP address: */
2246
  ip_result = inet_addr (name_or_ip);
2247
  if (ip_result != INADDR_NONE)
2248
    return ip_result;  /* Success, IP address string was given directly */
2249
2250
  /*
2251
   *  Step 2: Check if name represents a valid Interface index (e.g. ethernet_75521)
2252
   *  function if_nametoindex will return >=1 if a valid index, or 0=no match
2253
   *  valid index will be used later in GetAdaptersAddress loop for lookup of adapter IP address
2254
   */
2255
  if_index = if_nametoindex (name_or_ip);
2256
2257
  /* Step 3: Prepare wchar string for friendly name comparison */
2258
  if (if_index == 0)
2259
    {
2260
      size_t if_name_len = strlen (name_or_ip);
2261
      if (if_name_len >= MAX_ADAPTER_NAME_LENGTH + 4)
2262
        return INADDR_NONE;
2263
      /* Name-check only needed if index=0... */
2264
      wchar_name_or_ip = (wchar_t *) g_try_malloc ((if_name_len + 1) * sizeof(wchar_t));
2265
      if (wchar_name_or_ip)
2266
        mbstowcs (wchar_name_or_ip, name_or_ip, if_name_len + 1);
2267
      /* NOTE: Even if malloc fails here, some comparisons can still be done later... so no exit here! */
2268
    }
2269
2270
  /*
2271
   *  Step 4: Allocate memory and get adapter addresses.
2272
   *  Buffer allocation loop recommended by MS, since size can be dynamic
2273
   *  https://docs.microsoft.com/en-us/windows/desktop/api/iphlpapi/nf-iphlpapi-getadaptersaddresses
2274
   */
2275
  #define MAX_ALLOC_ITERATIONS 3
2276
  do
2277
    {
2278
      malloc_iterations++;
2279
      addr_buf = (PIP_ADAPTER_ADDRESSES) g_try_realloc (addr_buf, bufsize);
2280
      if (addr_buf)
2281
        ret = GetAdaptersAddresses (AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX, NULL, addr_buf, &bufsize);
2282
    }
2283
  while (addr_buf &&
2284
           ret == ERROR_BUFFER_OVERFLOW &&
2285
           malloc_iterations < MAX_ALLOC_ITERATIONS);
2286
  #undef MAX_ALLOC_ITERATIONS
2287
2288
  if (addr_buf == 0 || ret != NO_ERROR)
2289
    {
2290
      g_free (addr_buf);
2291
      g_free (wchar_name_or_ip);
2292
      return INADDR_NONE;
2293
    }
2294
2295
  /* Step 5: Loop through adapters and check match for index or name */
2296
  for (eth_adapter = addr_buf; eth_adapter != NULL; eth_adapter = eth_adapter->Next)
2297
    {
2298
      /* Check if match for interface index/name: */
2299
      gboolean any_match = (if_index > 0) && (eth_adapter->IfIndex == if_index);
2300
2301
      /* Check if match for friendly name - but only if NO if_index! */
2302
      if (!any_match && if_index == 0 && eth_adapter->FriendlyName &&
2303
          eth_adapter->FriendlyName[0] != 0 && wchar_name_or_ip != NULL)
2304
        any_match = (_wcsicmp (eth_adapter->FriendlyName, wchar_name_or_ip) == 0);
2305
2306
      /* Check if match for adapter low level name - but only if NO if_index: */
2307
      if (!any_match && if_index == 0 && eth_adapter->AdapterName &&
2308
          eth_adapter->AdapterName[0] != 0)
2309
        any_match = (stricmp (eth_adapter->AdapterName, name_or_ip) == 0);
2310
2311
      if (any_match)
2312
        {
2313
          /* We have match for this adapter, lets get its local unicast IP address! */
2314
          PIP_ADAPTER_UNICAST_ADDRESS uni_addr;
2315
          for (uni_addr = eth_adapter->FirstUnicastAddress;
2316
              uni_addr != NULL; uni_addr = uni_addr->Next)
2317
            {
2318
              if (uni_addr->Address.lpSockaddr->sa_family == AF_INET)
2319
                {
2320
                  ip_result = ((PSOCKADDR_IN) uni_addr->Address.lpSockaddr)->sin_addr.S_un.S_addr;
2321
                  break; /* finished, exit unicast addr loop */
2322
                }
2323
            }
2324
        }
2325
    }
2326
2327
  g_free (addr_buf);
2328
  g_free (wchar_name_or_ip);
2329
2330
  return ip_result;
2331
}
2332
#endif
2333
2334
static gboolean
2335
g_socket_multicast_group_operation (GSocket       *socket,
2336
            GInetAddress  *group,
2337
                                    gboolean       source_specific,
2338
                                    const gchar   *iface,
2339
            gboolean       join_group,
2340
            GError       **error)
2341
0
{
2342
0
  const guint8 *native_addr;
2343
0
  gint optname, result;
2344
2345
0
  g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2346
0
  g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
2347
0
  g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
2348
2349
0
  if (!check_socket (socket, error))
2350
0
    return FALSE;
2351
2352
0
  native_addr = g_inet_address_to_bytes (group);
2353
0
  if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV4)
2354
0
    {
2355
0
#ifdef HAVE_IP_MREQN
2356
0
      struct ip_mreqn mc_req;
2357
#else
2358
      struct ip_mreq mc_req;
2359
#endif
2360
2361
0
      memset (&mc_req, 0, sizeof (mc_req));
2362
0
      memcpy (&mc_req.imr_multiaddr, native_addr, sizeof (struct in_addr));
2363
2364
0
#ifdef HAVE_IP_MREQN
2365
0
      if (iface)
2366
0
        mc_req.imr_ifindex = if_nametoindex (iface);
2367
0
      else
2368
0
        mc_req.imr_ifindex = 0;  /* Pick any.  */
2369
#elif defined(G_OS_WIN32)
2370
      if (iface)
2371
        mc_req.imr_interface.s_addr = g_socket_w32_get_adapter_ipv4_addr (iface);
2372
      else
2373
        mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2374
#else
2375
      mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2376
#endif
2377
2378
0
      if (source_specific)
2379
0
  {
2380
0
#ifdef IP_ADD_SOURCE_MEMBERSHIP
2381
0
    optname = join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
2382
#else
2383
    g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2384
           join_group ?
2385
           _("Error joining multicast group: %s") :
2386
           _("Error leaving multicast group: %s"),
2387
           _("No support for source-specific multicast"));
2388
    return FALSE;
2389
#endif
2390
0
  }
2391
0
      else
2392
0
        optname = join_group ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP;
2393
0
      result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
2394
0
         &mc_req, sizeof (mc_req));
2395
0
    }
2396
0
  else if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV6)
2397
0
    {
2398
0
      struct ipv6_mreq mc_req_ipv6;
2399
2400
0
      memset (&mc_req_ipv6, 0, sizeof (mc_req_ipv6));
2401
0
      memcpy (&mc_req_ipv6.ipv6mr_multiaddr, native_addr, sizeof (struct in6_addr));
2402
0
#ifdef HAVE_IF_NAMETOINDEX
2403
0
      if (iface)
2404
0
        mc_req_ipv6.ipv6mr_interface = if_nametoindex (iface);
2405
0
      else
2406
0
#endif
2407
0
        mc_req_ipv6.ipv6mr_interface = 0;
2408
2409
0
      optname = join_group ? IPV6_JOIN_GROUP : IPV6_LEAVE_GROUP;
2410
0
      result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
2411
0
         &mc_req_ipv6, sizeof (mc_req_ipv6));
2412
0
    }
2413
0
  else
2414
0
    g_return_val_if_reached (FALSE);
2415
2416
0
  if (result < 0)
2417
0
    {
2418
0
      int errsv = get_socket_errno ();
2419
2420
0
      g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2421
0
       join_group ?
2422
0
       _("Error joining multicast group: %s") :
2423
0
       _("Error leaving multicast group: %s"),
2424
0
       socket_strerror (errsv));
2425
0
      return FALSE;
2426
0
    }
2427
2428
0
  return TRUE;
2429
0
}
2430
2431
/**
2432
 * g_socket_join_multicast_group:
2433
 * @socket: a #GSocket.
2434
 * @group: a #GInetAddress specifying the group address to join.
2435
 * @iface: (nullable): Name of the interface to use, or %NULL
2436
 * @source_specific: %TRUE if source-specific multicast should be used
2437
 * @error: #GError for error reporting, or %NULL to ignore.
2438
 *
2439
 * Registers @socket to receive multicast messages sent to @group.
2440
 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2441
 * been bound to an appropriate interface and port with
2442
 * g_socket_bind().
2443
 *
2444
 * If @iface is %NULL, the system will automatically pick an interface
2445
 * to bind to based on @group.
2446
 *
2447
 * If @source_specific is %TRUE, source-specific multicast as defined
2448
 * in RFC 4604 is used. Note that on older platforms this may fail
2449
 * with a %G_IO_ERROR_NOT_SUPPORTED error.
2450
 *
2451
 * To bind to a given source-specific multicast address, use
2452
 * g_socket_join_multicast_group_ssm() instead.
2453
 *
2454
 * Returns: %TRUE on success, %FALSE on error.
2455
 *
2456
 * Since: 2.32
2457
 */
2458
gboolean
2459
g_socket_join_multicast_group (GSocket       *socket,
2460
             GInetAddress  *group,
2461
                               gboolean       source_specific,
2462
                               const gchar   *iface,
2463
             GError       **error)
2464
0
{
2465
0
  return g_socket_multicast_group_operation (socket, group, source_specific, iface, TRUE, error);
2466
0
}
2467
2468
/**
2469
 * g_socket_leave_multicast_group:
2470
 * @socket: a #GSocket.
2471
 * @group: a #GInetAddress specifying the group address to leave.
2472
 * @iface: (nullable): Interface used
2473
 * @source_specific: %TRUE if source-specific multicast was used
2474
 * @error: #GError for error reporting, or %NULL to ignore.
2475
 *
2476
 * Removes @socket from the multicast group defined by @group, @iface,
2477
 * and @source_specific (which must all have the same values they had
2478
 * when you joined the group).
2479
 *
2480
 * @socket remains bound to its address and port, and can still receive
2481
 * unicast messages after calling this.
2482
 *
2483
 * To unbind to a given source-specific multicast address, use
2484
 * g_socket_leave_multicast_group_ssm() instead.
2485
 *
2486
 * Returns: %TRUE on success, %FALSE on error.
2487
 *
2488
 * Since: 2.32
2489
 */
2490
gboolean
2491
g_socket_leave_multicast_group (GSocket       *socket,
2492
        GInetAddress  *group,
2493
                                gboolean       source_specific,
2494
                                const gchar   *iface,
2495
        GError       **error)
2496
0
{
2497
0
  return g_socket_multicast_group_operation (socket, group, source_specific, iface, FALSE, error);
2498
0
}
2499
2500
static gboolean
2501
g_socket_multicast_group_operation_ssm (GSocket       *socket,
2502
                                        GInetAddress  *group,
2503
                                        GInetAddress  *source_specific,
2504
                                        const gchar   *iface,
2505
                                        gboolean       join_group,
2506
                                        GError       **error)
2507
0
{
2508
0
  gint result;
2509
2510
0
  g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2511
0
  g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
2512
0
  g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
2513
0
  g_return_val_if_fail (iface == NULL || *iface != '\0', FALSE);
2514
0
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2515
2516
0
  if (!source_specific)
2517
0
    {
2518
0
      return g_socket_multicast_group_operation (socket, group, FALSE, iface,
2519
0
                                                 join_group, error);
2520
0
    }
2521
2522
0
  if (!check_socket (socket, error))
2523
0
    return FALSE;
2524
2525
0
  switch (g_inet_address_get_family (group))
2526
0
    {
2527
0
    case G_SOCKET_FAMILY_INVALID:
2528
0
    case G_SOCKET_FAMILY_UNIX:
2529
0
      {
2530
0
        g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2531
0
            join_group ?
2532
0
            _("Error joining multicast group: %s") :
2533
0
            _("Error leaving multicast group: %s"),
2534
0
            _("Unsupported socket family"));
2535
0
        return FALSE;
2536
0
      }
2537
0
      break;
2538
2539
0
    case G_SOCKET_FAMILY_IPV4:
2540
0
      {
2541
0
#ifdef IP_ADD_SOURCE_MEMBERSHIP
2542
2543
#ifdef BROKEN_IP_MREQ_SOURCE_STRUCT
2544
#define S_ADDR_FIELD(src) src.imr_interface
2545
#else
2546
0
#define S_ADDR_FIELD(src) src.imr_interface.s_addr
2547
0
#endif
2548
2549
0
        gint optname;
2550
0
        struct ip_mreq_source mc_req_src;
2551
2552
0
        if (g_inet_address_get_family (source_specific) !=
2553
0
            G_SOCKET_FAMILY_IPV4)
2554
0
          {
2555
0
            g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2556
0
                join_group ?
2557
0
                _("Error joining multicast group: %s") :
2558
0
                _("Error leaving multicast group: %s"),
2559
0
                _("source-specific not an IPv4 address"));
2560
0
            return FALSE;
2561
0
          }
2562
2563
0
        memset (&mc_req_src, 0, sizeof (mc_req_src));
2564
2565
        /* By default use the default IPv4 multicast interface. */
2566
0
        S_ADDR_FIELD(mc_req_src) = g_htonl (INADDR_ANY);
2567
2568
0
        if (iface)
2569
0
          {
2570
#if defined(G_OS_WIN32)
2571
            S_ADDR_FIELD(mc_req_src) = g_socket_w32_get_adapter_ipv4_addr (iface);
2572
#elif defined (HAVE_SIOCGIFADDR)
2573
            int ret;
2574
0
            struct ifreq ifr;
2575
0
            struct sockaddr_in *iface_addr;
2576
0
            size_t if_name_len = strlen (iface);
2577
2578
0
            memset (&ifr, 0, sizeof (ifr));
2579
2580
0
            if (if_name_len >= sizeof (ifr.ifr_name))
2581
0
              {
2582
0
                g_set_error (error, G_IO_ERROR,  G_IO_ERROR_FILENAME_TOO_LONG,
2583
0
                             _("Interface name too long"));
2584
0
                return FALSE;
2585
0
              }
2586
2587
0
            memcpy (ifr.ifr_name, iface, if_name_len);
2588
2589
            /* Get the IPv4 address of the given network interface name. */
2590
0
            ret = ioctl (socket->priv->fd, SIOCGIFADDR, &ifr);
2591
0
            if (ret < 0)
2592
0
              {
2593
0
                int errsv = errno;
2594
2595
0
                g_set_error (error, G_IO_ERROR,  g_io_error_from_errno (errsv),
2596
0
                             _("Interface not found: %s"), g_strerror (errsv));
2597
0
                return FALSE;
2598
0
              }
2599
2600
0
            iface_addr = (struct sockaddr_in *) &ifr.ifr_addr;
2601
0
            S_ADDR_FIELD(mc_req_src) = iface_addr->sin_addr.s_addr;
2602
0
#endif  /* defined(G_OS_WIN32) && defined (HAVE_IF_NAMETOINDEX) */
2603
0
          }
2604
0
        memcpy (&mc_req_src.imr_multiaddr, g_inet_address_to_bytes (group),
2605
0
                g_inet_address_get_native_size (group));
2606
0
        memcpy (&mc_req_src.imr_sourceaddr,
2607
0
                g_inet_address_to_bytes (source_specific),
2608
0
                g_inet_address_get_native_size (source_specific));
2609
2610
0
        optname =
2611
0
            join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
2612
0
        result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
2613
0
                             &mc_req_src, sizeof (mc_req_src));
2614
2615
0
#undef S_ADDR_FIELD
2616
2617
#else
2618
        g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2619
            join_group ?
2620
            _("Error joining multicast group: %s") :
2621
            _("Error leaving multicast group: %s"),
2622
            _("No support for IPv4 source-specific multicast"));
2623
        return FALSE;
2624
#endif  /* IP_ADD_SOURCE_MEMBERSHIP */
2625
0
      }
2626
0
      break;
2627
2628
0
    case G_SOCKET_FAMILY_IPV6:
2629
0
      {
2630
0
#ifdef MCAST_JOIN_SOURCE_GROUP
2631
0
        gboolean res;
2632
0
        gint optname;
2633
0
        struct group_source_req mc_req_src;
2634
0
        GSocketAddress *saddr_group, *saddr_source_specific;
2635
0
        guint iface_index = 0;
2636
2637
0
#if defined (HAVE_IF_NAMETOINDEX)
2638
0
        if (iface)
2639
0
          {
2640
0
            iface_index = if_nametoindex (iface);
2641
0
            if (iface_index == 0)
2642
0
              {
2643
0
                int errsv = errno;
2644
2645
0
                g_set_error (error, G_IO_ERROR,  g_io_error_from_errno (errsv),
2646
0
                             _("Interface not found: %s"), g_strerror (errsv));
2647
0
                return FALSE;
2648
0
              }
2649
0
          }
2650
0
#endif  /* defined (HAVE_IF_NAMETOINDEX) */
2651
0
        mc_req_src.gsr_interface = iface_index;
2652
2653
0
        saddr_group = g_inet_socket_address_new (group, 0);
2654
0
        res = g_socket_address_to_native (saddr_group, &mc_req_src.gsr_group,
2655
0
                                          sizeof (mc_req_src.gsr_group),
2656
0
                                          error);
2657
0
        g_object_unref (saddr_group);
2658
0
        if (!res)
2659
0
          return FALSE;
2660
2661
0
        saddr_source_specific = g_inet_socket_address_new (source_specific, 0);
2662
0
        res = g_socket_address_to_native (saddr_source_specific,
2663
0
                                          &mc_req_src.gsr_source,
2664
0
                                          sizeof (mc_req_src.gsr_source),
2665
0
                                          error);
2666
0
        g_object_unref (saddr_source_specific);
2667
2668
0
        if (!res)
2669
0
          return FALSE;
2670
2671
0
        optname =
2672
0
            join_group ? MCAST_JOIN_SOURCE_GROUP : MCAST_LEAVE_SOURCE_GROUP;
2673
0
        result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
2674
0
                             &mc_req_src, sizeof (mc_req_src));
2675
#else
2676
        g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2677
            join_group ?
2678
            _("Error joining multicast group: %s") :
2679
            _("Error leaving multicast group: %s"),
2680
            _("No support for IPv6 source-specific multicast"));
2681
        return FALSE;
2682
#endif  /* MCAST_JOIN_SOURCE_GROUP */
2683
0
      }
2684
0
      break;
2685
2686
0
    default:
2687
0
      g_return_val_if_reached (FALSE);
2688
0
    }
2689
2690
0
  if (result < 0)
2691
0
    {
2692
0
      int errsv = get_socket_errno ();
2693
2694
0
      g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2695
0
          join_group ?
2696
0
          _("Error joining multicast group: %s") :
2697
0
          _("Error leaving multicast group: %s"),
2698
0
           socket_strerror (errsv));
2699
0
      return FALSE;
2700
0
    }
2701
2702
0
  return TRUE;
2703
0
}
2704
2705
/**
2706
 * g_socket_join_multicast_group_ssm:
2707
 * @socket: a #GSocket.
2708
 * @group: a #GInetAddress specifying the group address to join.
2709
 * @source_specific: (nullable): a #GInetAddress specifying the
2710
 * source-specific multicast address or %NULL to ignore.
2711
 * @iface: (nullable): Name of the interface to use, or %NULL
2712
 * @error: #GError for error reporting, or %NULL to ignore.
2713
 *
2714
 * Registers @socket to receive multicast messages sent to @group.
2715
 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2716
 * been bound to an appropriate interface and port with
2717
 * g_socket_bind().
2718
 *
2719
 * If @iface is %NULL, the system will automatically pick an interface
2720
 * to bind to based on @group.
2721
 *
2722
 * If @source_specific is not %NULL, use source-specific multicast as
2723
 * defined in RFC 4604. Note that on older platforms this may fail
2724
 * with a %G_IO_ERROR_NOT_SUPPORTED error.
2725
 *
2726
 * Note that this function can be called multiple times for the same
2727
 * @group with different @source_specific in order to receive multicast
2728
 * packets from more than one source.
2729
 *
2730
 * Returns: %TRUE on success, %FALSE on error.
2731
 *
2732
 * Since: 2.56
2733
 */
2734
gboolean
2735
g_socket_join_multicast_group_ssm (GSocket       *socket,
2736
                                   GInetAddress  *group,
2737
                                   GInetAddress  *source_specific,
2738
                                   const gchar   *iface,
2739
                                   GError       **error)
2740
0
{
2741
0
  return g_socket_multicast_group_operation_ssm (socket, group,
2742
0
      source_specific, iface, TRUE, error);
2743
0
}
2744
2745
/**
2746
 * g_socket_leave_multicast_group_ssm:
2747
 * @socket: a #GSocket.
2748
 * @group: a #GInetAddress specifying the group address to leave.
2749
 * @source_specific: (nullable): a #GInetAddress specifying the
2750
 * source-specific multicast address or %NULL to ignore.
2751
 * @iface: (nullable): Name of the interface to use, or %NULL
2752
 * @error: #GError for error reporting, or %NULL to ignore.
2753
 *
2754
 * Removes @socket from the multicast group defined by @group, @iface,
2755
 * and @source_specific (which must all have the same values they had
2756
 * when you joined the group).
2757
 *
2758
 * @socket remains bound to its address and port, and can still receive
2759
 * unicast messages after calling this.
2760
 *
2761
 * Returns: %TRUE on success, %FALSE on error.
2762
 *
2763
 * Since: 2.56
2764
 */
2765
gboolean
2766
g_socket_leave_multicast_group_ssm (GSocket       *socket,
2767
                                    GInetAddress  *group,
2768
                                    GInetAddress  *source_specific,
2769
                                    const gchar   *iface,
2770
                                    GError       **error)
2771
0
{
2772
0
  return g_socket_multicast_group_operation_ssm (socket, group,
2773
0
      source_specific, iface, FALSE, error);
2774
0
}
2775
2776
/**
2777
 * g_socket_speaks_ipv4:
2778
 * @socket: a #GSocket
2779
 *
2780
 * Checks if a socket is capable of speaking IPv4.
2781
 *
2782
 * IPv4 sockets are capable of speaking IPv4.  On some operating systems
2783
 * and under some combinations of circumstances IPv6 sockets are also
2784
 * capable of speaking IPv4.  See RFC 3493 section 3.7 for more
2785
 * information.
2786
 *
2787
 * No other types of sockets are currently considered as being capable
2788
 * of speaking IPv4.
2789
 *
2790
 * Returns: %TRUE if this socket can be used with IPv4.
2791
 *
2792
 * Since: 2.22
2793
 **/
2794
gboolean
2795
g_socket_speaks_ipv4 (GSocket *socket)
2796
0
{
2797
0
  switch (socket->priv->family)
2798
0
    {
2799
0
    case G_SOCKET_FAMILY_IPV4:
2800
0
      return TRUE;
2801
2802
0
    case G_SOCKET_FAMILY_IPV6:
2803
0
#if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
2804
0
      {
2805
0
        gint v6_only;
2806
2807
0
        if (!g_socket_get_option (socket,
2808
0
          IPPROTO_IPV6, IPV6_V6ONLY,
2809
0
          &v6_only, NULL))
2810
0
          return FALSE;
2811
2812
0
        return !v6_only;
2813
0
      }
2814
#else
2815
      return FALSE;
2816
#endif
2817
2818
0
    default:
2819
0
      return FALSE;
2820
0
    }
2821
0
}
2822
2823
/**
2824
 * g_socket_accept:
2825
 * @socket: a #GSocket.
2826
 * @cancellable: (nullable): a %GCancellable or %NULL
2827
 * @error: #GError for error reporting, or %NULL to ignore.
2828
 *
2829
 * Accept incoming connections on a connection-based socket. This removes
2830
 * the first outstanding connection request from the listening socket and
2831
 * creates a #GSocket object for it.
2832
 *
2833
 * The @socket must be bound to a local address with g_socket_bind() and
2834
 * must be listening for incoming connections (g_socket_listen()).
2835
 *
2836
 * If there are no outstanding connections then the operation will block
2837
 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
2838
 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
2839
 *
2840
 * Returns: (transfer full): a new #GSocket, or %NULL on error.
2841
 *     Free the returned object with g_object_unref().
2842
 *
2843
 * Since: 2.22
2844
 */
2845
GSocket *
2846
g_socket_accept (GSocket       *socket,
2847
     GCancellable  *cancellable,
2848
     GError       **error)
2849
0
{
2850
0
  GSocket *new_socket;
2851
0
  gint ret;
2852
2853
0
  g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
2854
2855
0
  if (!check_socket (socket, error))
2856
0
    return NULL;
2857
2858
0
  if (!check_timeout (socket, error))
2859
0
    return NULL;
2860
2861
0
  while (TRUE)
2862
0
    {
2863
0
      if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
2864
0
  {
2865
0
    int errsv = get_socket_errno ();
2866
2867
0
    if (errsv == EINTR)
2868
0
      continue;
2869
2870
#ifdef WSAEWOULDBLOCK
2871
          if (errsv == WSAEWOULDBLOCK)
2872
#else
2873
0
          if (errsv == EWOULDBLOCK ||
2874
0
              errsv == EAGAIN)
2875
0
#endif
2876
0
            {
2877
0
              win32_unset_event_mask (socket, FD_ACCEPT);
2878
2879
0
              if (socket->priv->blocking)
2880
0
                {
2881
0
                  if (!g_socket_condition_wait (socket,
2882
0
                                                G_IO_IN, cancellable, error))
2883
0
                    return NULL;
2884
2885
0
                  continue;
2886
0
                }
2887
0
            }
2888
2889
0
    socket_set_error_lazy (error, errsv, _("Error accepting connection: %s"));
2890
0
    return NULL;
2891
0
  }
2892
0
      break;
2893
0
    }
2894
2895
0
  win32_unset_event_mask (socket, FD_ACCEPT);
2896
2897
#ifdef G_OS_WIN32
2898
  {
2899
    /* The socket inherits the accepting sockets event mask and even object,
2900
       we need to remove that */
2901
    WSAEventSelect (ret, NULL, 0);
2902
  }
2903
#else
2904
0
  {
2905
0
    int flags;
2906
2907
    /* We always want to set close-on-exec to protect users. If you
2908
       need to so some weird inheritance to exec you can re-enable this
2909
       using lower level hacks with g_socket_get_fd(). */
2910
0
    flags = fcntl (ret, F_GETFD, 0);
2911
0
    if (flags != -1 &&
2912
0
  (flags & FD_CLOEXEC) == 0)
2913
0
      {
2914
0
  flags |= FD_CLOEXEC;
2915
0
  fcntl (ret, F_SETFD, flags);
2916
0
      }
2917
0
  }
2918
0
#endif
2919
2920
0
  new_socket = g_socket_new_from_fd (ret, error);
2921
0
  if (new_socket == NULL)
2922
0
    {
2923
#ifdef G_OS_WIN32
2924
      closesocket (ret);
2925
#else
2926
0
      close (ret);
2927
0
#endif
2928
0
    }
2929
0
  else
2930
0
    new_socket->priv->protocol = socket->priv->protocol;
2931
2932
0
  return new_socket;
2933
0
}
2934
2935
/**
2936
 * g_socket_connect:
2937
 * @socket: a #GSocket.
2938
 * @address: a #GSocketAddress specifying the remote address.
2939
 * @cancellable: (nullable): a %GCancellable or %NULL
2940
 * @error: #GError for error reporting, or %NULL to ignore.
2941
 *
2942
 * Connect the socket to the specified remote address.
2943
 *
2944
 * For connection oriented socket this generally means we attempt to make
2945
 * a connection to the @address. For a connection-less socket it sets
2946
 * the default address for g_socket_send() and discards all incoming datagrams
2947
 * from other sources.
2948
 *
2949
 * Generally connection oriented sockets can only connect once, but
2950
 * connection-less sockets can connect multiple times to change the
2951
 * default address.
2952
 *
2953
 * If the connect call needs to do network I/O it will block, unless
2954
 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
2955
 * and the user can be notified of the connection finishing by waiting
2956
 * for the G_IO_OUT condition. The result of the connection must then be
2957
 * checked with g_socket_check_connect_result().
2958
 *
2959
 * Returns: %TRUE if connected, %FALSE on error.
2960
 *
2961
 * Since: 2.22
2962
 */
2963
gboolean
2964
g_socket_connect (GSocket         *socket,
2965
      GSocketAddress  *address,
2966
      GCancellable    *cancellable,
2967
      GError         **error)
2968
0
{
2969
0
  union {
2970
0
    struct sockaddr_storage storage;
2971
0
    struct sockaddr sa;
2972
0
  } buffer;
2973
2974
0
  g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2975
2976
0
  if (!check_socket (socket, error))
2977
0
    return FALSE;
2978
2979
0
  if (!g_socket_address_to_native (address, &buffer.storage, sizeof buffer, error))
2980
0
    return FALSE;
2981
2982
0
  if (socket->priv->remote_address)
2983
0
    g_object_unref (socket->priv->remote_address);
2984
0
  socket->priv->remote_address = g_object_ref (address);
2985
2986
0
  while (1)
2987
0
    {
2988
0
      if (connect (socket->priv->fd, &buffer.sa,
2989
0
       g_socket_address_get_native_size (address)) < 0)
2990
0
  {
2991
0
    int errsv = get_socket_errno ();
2992
2993
0
    if (errsv == EINTR)
2994
0
      continue;
2995
2996
0
#ifndef G_OS_WIN32
2997
0
    if (errsv == EINPROGRESS)
2998
#else
2999
    if (errsv == WSAEWOULDBLOCK)
3000
#endif
3001
0
      {
3002
0
              win32_unset_event_mask (socket, FD_CONNECT);
3003
3004
0
        if (socket->priv->blocking)
3005
0
    {
3006
0
      if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
3007
0
        {
3008
0
          if (g_socket_check_connect_result (socket, error))
3009
0
      break;
3010
0
        }
3011
0
    }
3012
0
        else
3013
0
                {
3014
0
                  g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
3015
0
                                       _("Connection in progress"));
3016
0
                  socket->priv->connect_pending = TRUE;
3017
0
                }
3018
0
      }
3019
0
    else
3020
0
      g_set_error_literal (error, G_IO_ERROR,
3021
0
         socket_io_error_from_errno (errsv),
3022
0
         socket_strerror (errsv));
3023
3024
0
    return FALSE;
3025
0
  }
3026
0
      break;
3027
0
    }
3028
3029
0
  win32_unset_event_mask (socket, FD_CONNECT);
3030
3031
0
  socket->priv->connected_read = TRUE;
3032
0
  socket->priv->connected_write = TRUE;
3033
3034
0
  return TRUE;
3035
0
}
3036
3037
/**
3038
 * g_socket_check_connect_result:
3039
 * @socket: a #GSocket
3040
 * @error: #GError for error reporting, or %NULL to ignore.
3041
 *
3042
 * Checks and resets the pending connect error for the socket.
3043
 * This is used to check for errors when g_socket_connect() is
3044
 * used in non-blocking mode.
3045
 *
3046
 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
3047
 *
3048
 * Since: 2.22
3049
 */
3050
gboolean
3051
g_socket_check_connect_result (GSocket  *socket,
3052
             GError  **error)
3053
0
{
3054
0
  int value;
3055
3056
0
  g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3057
3058
0
  if (!check_socket (socket, error))
3059
0
    return FALSE;
3060
3061
0
  if (!check_timeout (socket, error))
3062
0
    return FALSE;
3063
3064
0
  if (!g_socket_get_option (socket, SOL_SOCKET, SO_ERROR, &value, error))
3065
0
    {
3066
0
      g_prefix_error (error, _("Unable to get pending error: "));
3067
0
      return FALSE;
3068
0
    }
3069
3070
0
  if (value != 0)
3071
0
    {
3072
0
      g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
3073
0
                           socket_strerror (value));
3074
0
      if (socket->priv->remote_address)
3075
0
        {
3076
0
          g_object_unref (socket->priv->remote_address);
3077
0
          socket->priv->remote_address = NULL;
3078
0
        }
3079
0
      return FALSE;
3080
0
    }
3081
3082
0
  socket->priv->connected_read = TRUE;
3083
0
  socket->priv->connected_write = TRUE;
3084
3085
0
  return TRUE;
3086
0
}
3087
3088
/**
3089
 * g_socket_get_available_bytes:
3090
 * @socket: a #GSocket
3091
 *
3092
 * Get the amount of data pending in the OS input buffer, without blocking.
3093
 *
3094
 * If @socket is a UDP or SCTP socket, this will return the size of
3095
 * just the next packet, even if additional packets are buffered after
3096
 * that one.
3097
 *
3098
 * Note that on Windows, this function is rather inefficient in the
3099
 * UDP case, and so if you know any plausible upper bound on the size
3100
 * of the incoming packet, it is better to just do a
3101
 * g_socket_receive() with a buffer of that size, rather than calling
3102
 * g_socket_get_available_bytes() first and then doing a receive of
3103
 * exactly the right size.
3104
 *
3105
 * Returns: the number of bytes that can be read from the socket
3106
 * without blocking or truncating, or -1 on error.
3107
 *
3108
 * Since: 2.32
3109
 */
3110
gssize
3111
g_socket_get_available_bytes (GSocket *socket)
3112
0
{
3113
0
#ifndef SO_NREAD
3114
0
  const gint bufsize = 64 * 1024;
3115
0
  static guchar *buf = NULL;
3116
0
#endif
3117
#ifdef G_OS_WIN32
3118
  u_long avail;
3119
#else
3120
0
  gint avail;
3121
0
#endif
3122
3123
0
  g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3124
3125
0
  if (!check_socket (socket, NULL))
3126
0
    return -1;
3127
3128
#ifdef SO_NREAD
3129
  if (!g_socket_get_option (socket, SOL_SOCKET, SO_NREAD, &avail, NULL))
3130
      return -1;
3131
#else
3132
0
  if (socket->priv->type == G_SOCKET_TYPE_DATAGRAM)
3133
0
    {
3134
0
      if (G_UNLIKELY (g_once_init_enter (&buf)))
3135
0
        g_once_init_leave (&buf, g_malloc (bufsize));
3136
3137
      /* On datagram sockets, FIONREAD ioctl is not reliable because many
3138
       * systems add internal header size to the reported size, making it
3139
       * unusable for this function. */
3140
0
      avail = recv (socket->priv->fd, buf, bufsize, MSG_PEEK);
3141
0
      if (avail == -1)
3142
0
        {
3143
0
          int errsv = get_socket_errno ();
3144
#ifdef G_OS_WIN32
3145
          if (errsv == WSAEWOULDBLOCK)
3146
#else
3147
0
          if (errsv == EWOULDBLOCK || errsv == EAGAIN)
3148
0
#endif
3149
0
            avail = 0;
3150
0
        }
3151
0
    }
3152
0
  else
3153
0
    {
3154
#ifdef G_OS_WIN32
3155
      if (ioctlsocket (socket->priv->fd, FIONREAD, &avail) < 0)
3156
#else
3157
0
      if (ioctl (socket->priv->fd, FIONREAD, &avail) < 0)
3158
0
#endif
3159
0
        avail = -1;
3160
0
    }
3161
0
#endif
3162
3163
0
  return avail;
3164
0
}
3165
3166
/* Block on a timed wait for @condition until (@start_time + @timeout).
3167
 * Return %G_IO_ERROR_TIMED_OUT if the timeout is reached; otherwise %TRUE.
3168
 */
3169
static gboolean
3170
block_on_timeout (GSocket       *socket,
3171
                  GIOCondition   condition,
3172
                  gint64         timeout_us,
3173
                  gint64         start_time,
3174
                  GCancellable  *cancellable,
3175
                  GError       **error)
3176
0
{
3177
0
  gint64 wait_timeout = -1;
3178
3179
0
  g_return_val_if_fail (timeout_us != 0, TRUE);
3180
3181
  /* check if we've timed out or how much time to wait at most */
3182
0
  if (timeout_us >= 0)
3183
0
    {
3184
0
      gint64 elapsed = g_get_monotonic_time () - start_time;
3185
3186
0
      if (elapsed >= timeout_us)
3187
0
        {
3188
0
          g_set_error_literal (error,
3189
0
                               G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3190
0
                               _("Socket I/O timed out"));
3191
0
          return FALSE;
3192
0
        }
3193
3194
0
      wait_timeout = timeout_us - elapsed;
3195
0
    }
3196
3197
0
  return g_socket_condition_timed_wait (socket, condition, wait_timeout,
3198
0
                                        cancellable, error);
3199
0
}
3200
3201
static gssize
3202
g_socket_receive_with_timeout (GSocket       *socket,
3203
                               guint8        *buffer,
3204
                               gsize          size,
3205
                               gint64         timeout_us,
3206
                               GCancellable  *cancellable,
3207
                               GError       **error)
3208
0
{
3209
0
  gssize ret;
3210
0
  gint64 start_time;
3211
3212
0
  g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
3213
3214
0
  start_time = g_get_monotonic_time ();
3215
3216
0
  if (!check_socket (socket, error))
3217
0
    return -1;
3218
3219
0
  if (!check_timeout (socket, error))
3220
0
    return -1;
3221
3222
0
  if (g_cancellable_set_error_if_cancelled (cancellable, error))
3223
0
    return -1;
3224
3225
0
  while (1)
3226
0
    {
3227
0
      if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
3228
0
  {
3229
0
    int errsv = get_socket_errno ();
3230
3231
0
    if (errsv == EINTR)
3232
0
      continue;
3233
3234
#ifdef WSAEWOULDBLOCK
3235
          if (errsv == WSAEWOULDBLOCK)
3236
#else
3237
0
          if (errsv == EWOULDBLOCK ||
3238
0
              errsv == EAGAIN)
3239
0
#endif
3240
0
            {
3241
0
              win32_unset_event_mask (socket, FD_READ);
3242
3243
0
              if (timeout_us != 0)
3244
0
                {
3245
0
                  if (!block_on_timeout (socket, G_IO_IN, timeout_us, start_time,
3246
0
                                         cancellable, error))
3247
0
                    return -1;
3248
3249
0
                  continue;
3250
0
                }
3251
0
            }
3252
3253
0
    win32_unset_event_mask (socket, FD_READ);
3254
3255
0
    socket_set_error_lazy (error, errsv, _("Error receiving data: %s"));
3256
0
    return -1;
3257
0
  }
3258
3259
0
      win32_unset_event_mask (socket, FD_READ);
3260
3261
0
      break;
3262
0
    }
3263
3264
0
  return ret;
3265
0
}
3266
3267
/**
3268
 * g_socket_receive:
3269
 * @socket: a #GSocket
3270
 * @buffer: (array length=size) (element-type guint8) (out caller-allocates):
3271
 *     a buffer to read data into (which should be at least @size bytes long).
3272
 * @size: the number of bytes you want to read from the socket
3273
 * @cancellable: (nullable): a %GCancellable or %NULL
3274
 * @error: #GError for error reporting, or %NULL to ignore.
3275
 *
3276
 * Receive data (up to @size bytes) from a socket. This is mainly used by
3277
 * connection-oriented sockets; it is identical to g_socket_receive_from()
3278
 * with @address set to %NULL.
3279
 *
3280
 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
3281
 * g_socket_receive() will always read either 0 or 1 complete messages from
3282
 * the socket. If the received message is too large to fit in @buffer, then
3283
 * the data beyond @size bytes will be discarded, without any explicit
3284
 * indication that this has occurred.
3285
 *
3286
 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
3287
 * number of bytes, up to @size. If more than @size bytes have been
3288
 * received, the additional data will be returned in future calls to
3289
 * g_socket_receive().
3290
 *
3291
 * If the socket is in blocking mode the call will block until there
3292
 * is some data to receive, the connection is closed, or there is an
3293
 * error. If there is no data available and the socket is in
3294
 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
3295
 * returned. To be notified when data is available, wait for the
3296
 * %G_IO_IN condition.
3297
 *
3298
 * On error -1 is returned and @error is set accordingly.
3299
 *
3300
 * Returns: Number of bytes read, or 0 if the connection was closed by
3301
 * the peer, or -1 on error
3302
 *
3303
 * Since: 2.22
3304
 */
3305
gssize
3306
g_socket_receive (GSocket       *socket,
3307
      gchar         *buffer,
3308
      gsize          size,
3309
      GCancellable  *cancellable,
3310
      GError       **error)
3311
0
{
3312
0
  return g_socket_receive_with_timeout (socket, (guint8 *) buffer, size,
3313
0
                                        socket->priv->blocking ? -1 : 0,
3314
0
                                        cancellable, error);
3315
0
}
3316
3317
/**
3318
 * g_socket_receive_with_blocking:
3319
 * @socket: a #GSocket
3320
 * @buffer: (array length=size) (element-type guint8) (out caller-allocates):
3321
 *     a buffer to read data into (which should be at least @size bytes long).
3322
 * @size: the number of bytes you want to read from the socket
3323
 * @blocking: whether to do blocking or non-blocking I/O
3324
 * @cancellable: (nullable): a %GCancellable or %NULL
3325
 * @error: #GError for error reporting, or %NULL to ignore.
3326
 *
3327
 * This behaves exactly the same as g_socket_receive(), except that
3328
 * the choice of blocking or non-blocking behavior is determined by
3329
 * the @blocking argument rather than by @socket's properties.
3330
 *
3331
 * Returns: Number of bytes read, or 0 if the connection was closed by
3332
 * the peer, or -1 on error
3333
 *
3334
 * Since: 2.26
3335
 */
3336
gssize
3337
g_socket_receive_with_blocking (GSocket       *socket,
3338
        gchar         *buffer,
3339
        gsize          size,
3340
        gboolean       blocking,
3341
        GCancellable  *cancellable,
3342
        GError       **error)
3343
0
{
3344
0
  return g_socket_receive_with_timeout (socket, (guint8 *) buffer, size,
3345
0
                                        blocking ? -1 : 0, cancellable, error);
3346
0
}
3347
3348
/**
3349
 * g_socket_receive_from:
3350
 * @socket: a #GSocket
3351
 * @address: (out) (optional): a pointer to a #GSocketAddress
3352
 *     pointer, or %NULL
3353
 * @buffer: (array length=size) (element-type guint8) (out caller-allocates):
3354
 *     a buffer to read data into (which should be at least @size bytes long).
3355
 * @size: the number of bytes you want to read from the socket
3356
 * @cancellable: (nullable): a %GCancellable or %NULL
3357
 * @error: #GError for error reporting, or %NULL to ignore.
3358
 *
3359
 * Receive data (up to @size bytes) from a socket.
3360
 *
3361
 * If @address is non-%NULL then @address will be set equal to the
3362
 * source address of the received packet.
3363
 * @address is owned by the caller.
3364
 *
3365
 * See g_socket_receive() for additional information.
3366
 *
3367
 * Returns: Number of bytes read, or 0 if the connection was closed by
3368
 * the peer, or -1 on error
3369
 *
3370
 * Since: 2.22
3371
 */
3372
gssize
3373
g_socket_receive_from (GSocket         *socket,
3374
           GSocketAddress **address,
3375
           gchar           *buffer,
3376
           gsize            size,
3377
           GCancellable    *cancellable,
3378
           GError         **error)
3379
0
{
3380
0
  GInputVector v;
3381
3382
0
  v.buffer = buffer;
3383
0
  v.size = size;
3384
3385
0
  return g_socket_receive_message (socket,
3386
0
           address,
3387
0
           &v, 1,
3388
0
           NULL, 0, NULL,
3389
0
           cancellable,
3390
0
           error);
3391
0
}
3392
3393
/* See the comment about SIGPIPE above. */
3394
#ifdef MSG_NOSIGNAL
3395
0
#define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
3396
#else
3397
#define G_SOCKET_DEFAULT_SEND_FLAGS 0
3398
#endif
3399
3400
static gssize
3401
g_socket_send_with_timeout (GSocket       *socket,
3402
                            const guint8  *buffer,
3403
                            gsize          size,
3404
                            gint64         timeout_us,
3405
                            GCancellable  *cancellable,
3406
                            GError       **error)
3407
0
{
3408
0
  gssize ret;
3409
0
  gint64 start_time;
3410
3411
0
  g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
3412
3413
0
  start_time = g_get_monotonic_time ();
3414
3415
0
  if (!check_socket (socket, error))
3416
0
    return -1;
3417
3418
0
  if (!check_timeout (socket, error))
3419
0
    return -1;
3420
3421
0
  if (g_cancellable_set_error_if_cancelled (cancellable, error))
3422
0
    return -1;
3423
3424
0
  while (1)
3425
0
    {
3426
0
      if ((ret = send (socket->priv->fd, (const char *)buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
3427
0
  {
3428
0
    int errsv = get_socket_errno ();
3429
3430
0
    if (errsv == EINTR)
3431
0
      continue;
3432
3433
#ifdef WSAEWOULDBLOCK
3434
          if (errsv == WSAEWOULDBLOCK)
3435
#else
3436
0
          if (errsv == EWOULDBLOCK ||
3437
0
              errsv == EAGAIN)
3438
0
#endif
3439
0
            {
3440
0
              win32_unset_event_mask (socket, FD_WRITE);
3441
3442
0
              if (timeout_us != 0)
3443
0
                {
3444
0
                  if (!block_on_timeout (socket, G_IO_OUT, timeout_us, start_time,
3445
0
                                         cancellable, error))
3446
0
                    return -1;
3447
3448
0
                  continue;
3449
0
                }
3450
0
            }
3451
3452
0
    socket_set_error_lazy (error, errsv, _("Error sending data: %s"));
3453
0
    return -1;
3454
0
  }
3455
0
      break;
3456
0
    }
3457
3458
0
  return ret;
3459
0
}
3460
3461
/**
3462
 * g_socket_send:
3463
 * @socket: a #GSocket
3464
 * @buffer: (array length=size) (element-type guint8): the buffer
3465
 *     containing the data to send.
3466
 * @size: the number of bytes to send
3467
 * @cancellable: (nullable): a %GCancellable or %NULL
3468
 * @error: #GError for error reporting, or %NULL to ignore.
3469
 *
3470
 * Tries to send @size bytes from @buffer on the socket. This is
3471
 * mainly used by connection-oriented sockets; it is identical to
3472
 * g_socket_send_to() with @address set to %NULL.
3473
 *
3474
 * If the socket is in blocking mode the call will block until there is
3475
 * space for the data in the socket queue. If there is no space available
3476
 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3477
 * will be returned. To be notified when space is available, wait for the
3478
 * %G_IO_OUT condition. Note though that you may still receive
3479
 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3480
 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3481
 * very common due to the way the underlying APIs work.)
3482
 *
3483
 * On error -1 is returned and @error is set accordingly.
3484
 *
3485
 * Returns: Number of bytes written (which may be less than @size), or -1
3486
 * on error
3487
 *
3488
 * Since: 2.22
3489
 */
3490
gssize
3491
g_socket_send (GSocket       *socket,
3492
         const gchar   *buffer,
3493
         gsize          size,
3494
         GCancellable  *cancellable,
3495
         GError       **error)
3496
0
{
3497
0
  return g_socket_send_with_blocking (socket, buffer, size,
3498
0
              socket->priv->blocking,
3499
0
              cancellable, error);
3500
0
}
3501
3502
/**
3503
 * g_socket_send_with_blocking:
3504
 * @socket: a #GSocket
3505
 * @buffer: (array length=size) (element-type guint8): the buffer
3506
 *     containing the data to send.
3507
 * @size: the number of bytes to send
3508
 * @blocking: whether to do blocking or non-blocking I/O
3509
 * @cancellable: (nullable): a %GCancellable or %NULL
3510
 * @error: #GError for error reporting, or %NULL to ignore.
3511
 *
3512
 * This behaves exactly the same as g_socket_send(), except that
3513
 * the choice of blocking or non-blocking behavior is determined by
3514
 * the @blocking argument rather than by @socket's properties.
3515
 *
3516
 * Returns: Number of bytes written (which may be less than @size), or -1
3517
 * on error
3518
 *
3519
 * Since: 2.26
3520
 */
3521
gssize
3522
g_socket_send_with_blocking (GSocket       *socket,
3523
           const gchar   *buffer,
3524
           gsize          size,
3525
           gboolean       blocking,
3526
           GCancellable  *cancellable,
3527
           GError       **error)
3528
0
{
3529
0
  return g_socket_send_with_timeout (socket, (const guint8 *) buffer, size,
3530
0
                                     blocking ? -1 : 0, cancellable, error);
3531
0
}
3532
3533
/**
3534
 * g_socket_send_to:
3535
 * @socket: a #GSocket
3536
 * @address: (nullable): a #GSocketAddress, or %NULL
3537
 * @buffer: (array length=size) (element-type guint8): the buffer
3538
 *     containing the data to send.
3539
 * @size: the number of bytes to send
3540
 * @cancellable: (nullable): a %GCancellable or %NULL
3541
 * @error: #GError for error reporting, or %NULL to ignore.
3542
 *
3543
 * Tries to send @size bytes from @buffer to @address. If @address is
3544
 * %NULL then the message is sent to the default receiver (set by
3545
 * g_socket_connect()).
3546
 *
3547
 * See g_socket_send() for additional information.
3548
 *
3549
 * Returns: Number of bytes written (which may be less than @size), or -1
3550
 * on error
3551
 *
3552
 * Since: 2.22
3553
 */
3554
gssize
3555
g_socket_send_to (GSocket         *socket,
3556
      GSocketAddress  *address,
3557
      const gchar     *buffer,
3558
      gsize            size,
3559
      GCancellable    *cancellable,
3560
      GError         **error)
3561
0
{
3562
0
  GOutputVector v;
3563
3564
0
  v.buffer = buffer;
3565
0
  v.size = size;
3566
3567
0
  return g_socket_send_message (socket,
3568
0
        address,
3569
0
        &v, 1,
3570
0
        NULL, 0,
3571
0
        0,
3572
0
        cancellable,
3573
0
        error);
3574
0
}
3575
3576
/**
3577
 * g_socket_shutdown:
3578
 * @socket: a #GSocket
3579
 * @shutdown_read: whether to shut down the read side
3580
 * @shutdown_write: whether to shut down the write side
3581
 * @error: #GError for error reporting, or %NULL to ignore.
3582
 *
3583
 * Shut down part or all of a full-duplex connection.
3584
 *
3585
 * If @shutdown_read is %TRUE then the receiving side of the connection
3586
 * is shut down, and further reading is disallowed.
3587
 *
3588
 * If @shutdown_write is %TRUE then the sending side of the connection
3589
 * is shut down, and further writing is disallowed.
3590
 *
3591
 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
3592
 *
3593
 * One example where it is useful to shut down only one side of a connection is
3594
 * graceful disconnect for TCP connections where you close the sending side,
3595
 * then wait for the other side to close the connection, thus ensuring that the
3596
 * other side saw all sent data.
3597
 *
3598
 * Returns: %TRUE on success, %FALSE on error
3599
 *
3600
 * Since: 2.22
3601
 */
3602
gboolean
3603
g_socket_shutdown (GSocket   *socket,
3604
       gboolean   shutdown_read,
3605
       gboolean   shutdown_write,
3606
       GError   **error)
3607
0
{
3608
0
  int how;
3609
3610
0
  g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
3611
3612
0
  if (!check_socket (socket, error))
3613
0
    return FALSE;
3614
3615
  /* Do nothing? */
3616
0
  if (!shutdown_read && !shutdown_write)
3617
0
    return TRUE;
3618
3619
0
#ifndef G_OS_WIN32
3620
0
  if (shutdown_read && shutdown_write)
3621
0
    how = SHUT_RDWR;
3622
0
  else if (shutdown_read)
3623
0
    how = SHUT_RD;
3624
0
  else
3625
0
    how = SHUT_WR;
3626
#else
3627
  if (shutdown_read && shutdown_write)
3628
    how = SD_BOTH;
3629
  else if (shutdown_read)
3630
    how = SD_RECEIVE;
3631
  else
3632
    how = SD_SEND;
3633
#endif
3634
3635
0
  if (shutdown (socket->priv->fd, how) != 0)
3636
0
    {
3637
0
      int errsv = get_socket_errno ();
3638
0
      g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
3639
0
       _("Unable to shutdown socket: %s"), socket_strerror (errsv));
3640
0
      return FALSE;
3641
0
    }
3642
3643
0
  if (shutdown_read)
3644
0
    socket->priv->connected_read = FALSE;
3645
0
  if (shutdown_write)
3646
0
    socket->priv->connected_write = FALSE;
3647
3648
0
  return TRUE;
3649
0
}
3650
3651
/**
3652
 * g_socket_close:
3653
 * @socket: a #GSocket
3654
 * @error: #GError for error reporting, or %NULL to ignore.
3655
 *
3656
 * Closes the socket, shutting down any active connection.
3657
 *
3658
 * Closing a socket does not wait for all outstanding I/O operations
3659
 * to finish, so the caller should not rely on them to be guaranteed
3660
 * to complete even if the close returns with no error.
3661
 *
3662
 * Once the socket is closed, all other operations will return
3663
 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
3664
 * return an error.
3665
 *
3666
 * Sockets will be automatically closed when the last reference
3667
 * is dropped, but you might want to call this function to make sure
3668
 * resources are released as early as possible.
3669
 *
3670
 * Beware that due to the way that TCP works, it is possible for
3671
 * recently-sent data to be lost if either you close a socket while the
3672
 * %G_IO_IN condition is set, or else if the remote connection tries to
3673
 * send something to you after you close the socket but before it has
3674
 * finished reading all of the data you sent. There is no easy generic
3675
 * way to avoid this problem; the easiest fix is to design the network
3676
 * protocol such that the client will never send data "out of turn".
3677
 * Another solution is for the server to half-close the connection by
3678
 * calling g_socket_shutdown() with only the @shutdown_write flag set,
3679
 * and then wait for the client to notice this and close its side of the
3680
 * connection, after which the server can safely call g_socket_close().
3681
 * (This is what #GTcpConnection does if you call
3682
 * g_tcp_connection_set_graceful_disconnect(). But of course, this
3683
 * only works if the client will close its connection after the server
3684
 * does.)
3685
 *
3686
 * Returns: %TRUE on success, %FALSE on error
3687
 *
3688
 * Since: 2.22
3689
 */
3690
gboolean
3691
g_socket_close (GSocket  *socket,
3692
    GError  **error)
3693
0
{
3694
0
  int res;
3695
3696
0
  g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
3697
3698
0
  if (socket->priv->closed)
3699
0
    return TRUE; /* Multiple close not an error */
3700
3701
0
  if (!check_socket (socket, error))
3702
0
    return FALSE;
3703
3704
0
  while (1)
3705
0
    {
3706
#ifdef G_OS_WIN32
3707
      res = closesocket (socket->priv->fd);
3708
#else
3709
0
      res = close (socket->priv->fd);
3710
0
#endif
3711
0
      if (res == -1)
3712
0
  {
3713
0
    int errsv = get_socket_errno ();
3714
3715
0
    if (errsv == EINTR)
3716
0
      continue;
3717
3718
0
    g_set_error (error, G_IO_ERROR,
3719
0
           socket_io_error_from_errno (errsv),
3720
0
           _("Error closing socket: %s"),
3721
0
           socket_strerror (errsv));
3722
0
    return FALSE;
3723
0
  }
3724
0
      break;
3725
0
    }
3726
3727
0
  socket->priv->fd = -1;
3728
0
  socket->priv->connected_read = FALSE;
3729
0
  socket->priv->connected_write = FALSE;
3730
0
  socket->priv->closed = TRUE;
3731
0
  if (socket->priv->remote_address)
3732
0
    {
3733
0
      g_object_unref (socket->priv->remote_address);
3734
0
      socket->priv->remote_address = NULL;
3735
0
    }
3736
3737
0
  return TRUE;
3738
0
}
3739
3740
/**
3741
 * g_socket_is_closed:
3742
 * @socket: a #GSocket
3743
 *
3744
 * Checks whether a socket is closed.
3745
 *
3746
 * Returns: %TRUE if socket is closed, %FALSE otherwise
3747
 *
3748
 * Since: 2.22
3749
 */
3750
gboolean
3751
g_socket_is_closed (GSocket *socket)
3752
0
{
3753
0
  return socket->priv->closed;
3754
0
}
3755
3756
/* Broken source, used on errors */
3757
static gboolean
3758
broken_dispatch (GSource     *source,
3759
     GSourceFunc  callback,
3760
     gpointer     user_data)
3761
0
{
3762
0
  return TRUE;
3763
0
}
3764
3765
static GSourceFuncs broken_funcs =
3766
{
3767
  NULL,
3768
  NULL,
3769
  broken_dispatch,
3770
  NULL,
3771
  NULL,
3772
  NULL,
3773
};
3774
3775
#ifdef G_OS_WIN32
3776
static gint
3777
network_events_for_condition (GIOCondition condition)
3778
{
3779
  int event_mask = 0;
3780
3781
  if (condition & G_IO_IN)
3782
    event_mask |= (FD_READ | FD_ACCEPT);
3783
  if (condition & G_IO_OUT)
3784
    event_mask |= (FD_WRITE | FD_CONNECT);
3785
  event_mask |= FD_CLOSE;
3786
3787
  return event_mask;
3788
}
3789
3790
static void
3791
ensure_event (GSocket *socket)
3792
{
3793
  if (socket->priv->event == WSA_INVALID_EVENT)
3794
    socket->priv->event = WSACreateEvent();
3795
}
3796
3797
static void
3798
update_select_events (GSocket *socket)
3799
{
3800
  int event_mask;
3801
  GIOCondition *ptr;
3802
  GList *l;
3803
  WSAEVENT event;
3804
3805
  if (socket->priv->closed)
3806
    return;
3807
3808
  ensure_event (socket);
3809
3810
  event_mask = 0;
3811
  for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
3812
    {
3813
      ptr = l->data;
3814
      event_mask |= network_events_for_condition (*ptr);
3815
    }
3816
3817
  if (event_mask != socket->priv->selected_events)
3818
    {
3819
      /* If no events selected, disable event so we can unset
3820
   nonblocking mode */
3821
3822
      if (event_mask == 0)
3823
  event = NULL;
3824
      else
3825
  event = socket->priv->event;
3826
3827
      if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
3828
  socket->priv->selected_events = event_mask;
3829
    }
3830
}
3831
3832
static void
3833
add_condition_watch (GSocket      *socket,
3834
         GIOCondition *condition)
3835
{
3836
  g_mutex_lock (&socket->priv->win32_source_lock);
3837
  g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
3838
3839
  socket->priv->requested_conditions =
3840
    g_list_prepend (socket->priv->requested_conditions, condition);
3841
3842
  update_select_events (socket);
3843
  g_mutex_unlock (&socket->priv->win32_source_lock);
3844
}
3845
3846
static void
3847
remove_condition_watch (GSocket      *socket,
3848
      GIOCondition *condition)
3849
{
3850
  g_mutex_lock (&socket->priv->win32_source_lock);
3851
  g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
3852
3853
  socket->priv->requested_conditions =
3854
    g_list_remove (socket->priv->requested_conditions, condition);
3855
3856
  update_select_events (socket);
3857
  g_mutex_unlock (&socket->priv->win32_source_lock);
3858
}
3859
3860
static GIOCondition
3861
update_condition_unlocked (GSocket *socket)
3862
{
3863
  WSANETWORKEVENTS events;
3864
  GIOCondition condition;
3865
3866
  if (!socket->priv->closed &&
3867
      WSAEnumNetworkEvents (socket->priv->fd,
3868
          socket->priv->event,
3869
          &events) == 0)
3870
    {
3871
      socket->priv->current_events |= events.lNetworkEvents;
3872
      if (events.lNetworkEvents & FD_WRITE &&
3873
    events.iErrorCode[FD_WRITE_BIT] != 0)
3874
  socket->priv->current_errors |= FD_WRITE;
3875
      if (events.lNetworkEvents & FD_CONNECT &&
3876
    events.iErrorCode[FD_CONNECT_BIT] != 0)
3877
  socket->priv->current_errors |= FD_CONNECT;
3878
    }
3879
3880
  condition = 0;
3881
  if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
3882
    condition |= G_IO_IN;
3883
3884
  if (socket->priv->current_events & FD_CLOSE)
3885
    {
3886
      int r, errsv, buffer;
3887
3888
      r = recv (socket->priv->fd, &buffer, sizeof (buffer), MSG_PEEK);
3889
      if (r < 0)
3890
          errsv = get_socket_errno ();
3891
3892
      if (r > 0 ||
3893
          (r < 0 && errsv == WSAENOTCONN))
3894
        condition |= G_IO_IN;
3895
      else if (r == 0 ||
3896
               (r < 0 && (errsv == WSAESHUTDOWN || errsv == WSAECONNRESET ||
3897
                          errsv == WSAECONNABORTED || errsv == WSAENETRESET)))
3898
        condition |= G_IO_HUP;
3899
      else
3900
        condition |= G_IO_ERR;
3901
    }
3902
3903
  if (socket->priv->closed)
3904
    condition |= G_IO_HUP;
3905
3906
  /* Never report both G_IO_OUT and HUP, these are
3907
     mutually exclusive (can't write to a closed socket) */
3908
  if ((condition & G_IO_HUP) == 0 &&
3909
      socket->priv->current_events & FD_WRITE)
3910
    {
3911
      if (socket->priv->current_errors & FD_WRITE)
3912
  condition |= G_IO_ERR;
3913
      else
3914
  condition |= G_IO_OUT;
3915
    }
3916
  else
3917
    {
3918
      if (socket->priv->current_events & FD_CONNECT)
3919
  {
3920
    if (socket->priv->current_errors & FD_CONNECT)
3921
      condition |= (G_IO_HUP | G_IO_ERR);
3922
    else
3923
      condition |= G_IO_OUT;
3924
  }
3925
    }
3926
3927
  return condition;
3928
}
3929
3930
static GIOCondition
3931
update_condition (GSocket *socket)
3932
{
3933
  GIOCondition res;
3934
  g_mutex_lock (&socket->priv->win32_source_lock);
3935
  res = update_condition_unlocked (socket);
3936
  g_mutex_unlock (&socket->priv->win32_source_lock);
3937
  return res;
3938
}
3939
#endif
3940
3941
typedef struct {
3942
  GSource       source;
3943
#ifdef G_OS_WIN32
3944
  GPollFD       pollfd;
3945
#else
3946
  gpointer      fd_tag;
3947
#endif
3948
  GSocket      *socket;
3949
  GIOCondition  condition;
3950
} GSocketSource;
3951
3952
static gboolean
3953
socket_source_prepare (GSource *source,
3954
                       gint    *timeout)
3955
0
{
3956
0
  GSocketSource *socket_source = (GSocketSource *)source;
3957
3958
0
  *timeout = -1;
3959
3960
#ifdef G_OS_WIN32
3961
  if ((socket_source->pollfd.revents & G_IO_NVAL) != 0)
3962
    return TRUE;
3963
3964
  if (g_socket_is_closed (socket_source->socket))
3965
    {
3966
      g_source_remove_poll (source, &socket_source->pollfd);
3967
      socket_source->pollfd.revents = G_IO_NVAL;
3968
      return TRUE;
3969
    }
3970
3971
  return (update_condition (socket_source->socket) & socket_source->condition) != 0;
3972
#else
3973
0
  return g_socket_is_closed (socket_source->socket) && socket_source->fd_tag != NULL;
3974
0
#endif
3975
0
}
3976
3977
#ifdef G_OS_WIN32
3978
static gboolean
3979
socket_source_check_win32 (GSource *source)
3980
{
3981
  int timeout;
3982
3983
  return socket_source_prepare (source, &timeout);
3984
}
3985
#endif
3986
3987
static gboolean
3988
socket_source_dispatch (GSource     *source,
3989
      GSourceFunc  callback,
3990
      gpointer     user_data)
3991
0
{
3992
0
  GSocketSourceFunc func = (GSocketSourceFunc)callback;
3993
0
  GSocketSource *socket_source = (GSocketSource *)source;
3994
0
  GSocket *socket = socket_source->socket;
3995
0
  gint64 timeout;
3996
0
  guint events;
3997
0
  gboolean ret;
3998
3999
#ifdef G_OS_WIN32
4000
  events = update_condition (socket_source->socket);
4001
#else
4002
0
  if (g_socket_is_closed (socket_source->socket))
4003
0
    {
4004
0
      if (socket_source->fd_tag)
4005
0
        g_source_remove_unix_fd (source, socket_source->fd_tag);
4006
0
      socket_source->fd_tag = NULL;
4007
0
      events = G_IO_NVAL;
4008
0
    }
4009
0
  else
4010
0
    {
4011
0
      events = g_source_query_unix_fd (source, socket_source->fd_tag);
4012
0
    }
4013
0
#endif
4014
4015
0
  timeout = g_source_get_ready_time (source);
4016
0
  if (timeout >= 0 && timeout < g_source_get_time (source) &&
4017
0
      !g_socket_is_closed (socket_source->socket))
4018
0
    {
4019
0
      socket->priv->timed_out = TRUE;
4020
0
      events |= (G_IO_IN | G_IO_OUT);
4021
0
    }
4022
4023
0
  ret = (*func) (socket, events & socket_source->condition, user_data);
4024
4025
0
  if (socket->priv->timeout && !g_socket_is_closed (socket_source->socket))
4026
0
    g_source_set_ready_time (source, g_get_monotonic_time () + socket->priv->timeout * 1000000);
4027
0
  else
4028
0
    g_source_set_ready_time (source, -1);
4029
4030
0
  return ret;
4031
0
}
4032
4033
static void
4034
socket_source_finalize (GSource *source)
4035
0
{
4036
0
  GSocketSource *socket_source = (GSocketSource *)source;
4037
0
  GSocket *socket;
4038
4039
0
  socket = socket_source->socket;
4040
4041
#ifdef G_OS_WIN32
4042
  remove_condition_watch (socket, &socket_source->condition);
4043
#endif
4044
4045
0
  g_object_unref (socket);
4046
0
}
4047
4048
static gboolean
4049
socket_source_closure_callback (GSocket      *socket,
4050
        GIOCondition  condition,
4051
        gpointer      data)
4052
0
{
4053
0
  GClosure *closure = data;
4054
4055
0
  GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
4056
0
  GValue result_value = G_VALUE_INIT;
4057
0
  gboolean result;
4058
4059
0
  g_value_init (&result_value, G_TYPE_BOOLEAN);
4060
4061
0
  g_value_init (&params[0], G_TYPE_SOCKET);
4062
0
  g_value_set_object (&params[0], socket);
4063
0
  g_value_init (&params[1], G_TYPE_IO_CONDITION);
4064
0
  g_value_set_flags (&params[1], condition);
4065
4066
0
  g_closure_invoke (closure, &result_value, 2, params, NULL);
4067
4068
0
  result = g_value_get_boolean (&result_value);
4069
0
  g_value_unset (&result_value);
4070
0
  g_value_unset (&params[0]);
4071
0
  g_value_unset (&params[1]);
4072
4073
0
  return result;
4074
0
}
4075
4076
static GSourceFuncs socket_source_funcs =
4077
{
4078
  socket_source_prepare,
4079
#ifdef G_OS_WIN32
4080
  socket_source_check_win32,
4081
#else
4082
  NULL,
4083
#endif
4084
  socket_source_dispatch,
4085
  socket_source_finalize,
4086
  (GSourceFunc)socket_source_closure_callback,
4087
  NULL,
4088
};
4089
4090
static GSource *
4091
socket_source_new (GSocket      *socket,
4092
       GIOCondition  condition,
4093
       GCancellable *cancellable)
4094
0
{
4095
0
  GSource *source;
4096
0
  GSocketSource *socket_source;
4097
4098
#ifdef G_OS_WIN32
4099
  ensure_event (socket);
4100
4101
  if (socket->priv->event == WSA_INVALID_EVENT)
4102
    {
4103
      g_warning ("Failed to create WSAEvent");
4104
      return g_source_new (&broken_funcs, sizeof (GSource));
4105
    }
4106
#endif
4107
4108
0
  if (!check_socket (socket, NULL))
4109
0
    {
4110
0
      g_warning ("Socket check failed");
4111
0
      return g_source_new (&broken_funcs, sizeof (GSource));
4112
0
    }
4113
4114
0
  condition |= G_IO_HUP | G_IO_ERR | G_IO_NVAL;
4115
4116
0
  source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
4117
0
  g_source_set_name (source, "GSocket");
4118
0
  socket_source = (GSocketSource *)source;
4119
4120
0
  socket_source->socket = g_object_ref (socket);
4121
0
  socket_source->condition = condition;
4122
4123
0
  if (cancellable)
4124
0
    {
4125
0
      GSource *cancellable_source;
4126
4127
0
      cancellable_source = g_cancellable_source_new (cancellable);
4128
0
      g_source_add_child_source (source, cancellable_source);
4129
0
      g_source_set_dummy_callback (cancellable_source);
4130
0
      g_source_unref (cancellable_source);
4131
0
    }
4132
4133
#ifdef G_OS_WIN32
4134
  add_condition_watch (socket, &socket_source->condition);
4135
  socket_source->pollfd.fd = (gintptr) socket->priv->event;
4136
  socket_source->pollfd.events = condition;
4137
  socket_source->pollfd.revents = 0;
4138
  g_source_add_poll (source, &socket_source->pollfd);
4139
#else
4140
0
  socket_source->fd_tag = g_source_add_unix_fd (source, socket->priv->fd, condition);
4141
0
#endif
4142
4143
0
  if (socket->priv->timeout)
4144
0
    g_source_set_ready_time (source, g_get_monotonic_time () + socket->priv->timeout * 1000000);
4145
0
  else
4146
0
    g_source_set_ready_time (source, -1);
4147
4148
0
  return source;
4149
0
}
4150
4151
/**
4152
 * g_socket_create_source: (skip)
4153
 * @socket: a #GSocket
4154
 * @condition: a #GIOCondition mask to monitor
4155
 * @cancellable: (nullable): a %GCancellable or %NULL
4156
 *
4157
 * Creates a #GSource that can be attached to a %GMainContext to monitor
4158
 * for the availability of the specified @condition on the socket. The #GSource
4159
 * keeps a reference to the @socket.
4160
 *
4161
 * The callback on the source is of the #GSocketSourceFunc type.
4162
 *
4163
 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
4164
 * these conditions will always be reported output if they are true.
4165
 *
4166
 * @cancellable if not %NULL can be used to cancel the source, which will
4167
 * cause the source to trigger, reporting the current condition (which
4168
 * is likely 0 unless cancellation happened at the same time as a
4169
 * condition change). You can check for this in the callback using
4170
 * g_cancellable_is_cancelled().
4171
 *
4172
 * If @socket has a timeout set, and it is reached before @condition
4173
 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
4174
 * %G_IO_OUT depending on @condition. However, @socket will have been
4175
 * marked as having had a timeout, and so the next #GSocket I/O method
4176
 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
4177
 *
4178
 * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
4179
 *
4180
 * Since: 2.22
4181
 */
4182
GSource *
4183
g_socket_create_source (GSocket      *socket,
4184
      GIOCondition  condition,
4185
      GCancellable *cancellable)
4186
0
{
4187
0
  g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
4188
4189
0
  return socket_source_new (socket, condition, cancellable);
4190
0
}
4191
4192
/**
4193
 * g_socket_condition_check:
4194
 * @socket: a #GSocket
4195
 * @condition: a #GIOCondition mask to check
4196
 *
4197
 * Checks on the readiness of @socket to perform operations.
4198
 * The operations specified in @condition are checked for and masked
4199
 * against the currently-satisfied conditions on @socket. The result
4200
 * is returned.
4201
 *
4202
 * Note that on Windows, it is possible for an operation to return
4203
 * %G_IO_ERROR_WOULD_BLOCK even immediately after
4204
 * g_socket_condition_check() has claimed that the socket is ready for
4205
 * writing. Rather than calling g_socket_condition_check() and then
4206
 * writing to the socket if it succeeds, it is generally better to
4207
 * simply try writing to the socket right away, and try again later if
4208
 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
4209
 *
4210
 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
4211
 * these conditions will always be set in the output if they are true.
4212
 *
4213
 * This call never blocks.
4214
 *
4215
 * Returns: the @GIOCondition mask of the current state
4216
 *
4217
 * Since: 2.22
4218
 */
4219
GIOCondition
4220
g_socket_condition_check (GSocket      *socket,
4221
        GIOCondition  condition)
4222
0
{
4223
0
  g_return_val_if_fail (G_IS_SOCKET (socket), 0);
4224
4225
0
  if (!check_socket (socket, NULL))
4226
0
    return 0;
4227
4228
#ifdef G_OS_WIN32
4229
  {
4230
    GIOCondition current_condition;
4231
4232
    condition |= G_IO_ERR | G_IO_HUP;
4233
4234
    add_condition_watch (socket, &condition);
4235
    current_condition = update_condition (socket);
4236
    remove_condition_watch (socket, &condition);
4237
    return condition & current_condition;
4238
  }
4239
#else
4240
0
  {
4241
0
    GPollFD poll_fd;
4242
0
    gint result;
4243
0
    poll_fd.fd = socket->priv->fd;
4244
0
    poll_fd.events = condition;
4245
0
    poll_fd.revents = 0;
4246
4247
0
    do
4248
0
      result = g_poll (&poll_fd, 1, 0);
4249
0
    while (result == -1 && get_socket_errno () == EINTR);
4250
4251
0
    return poll_fd.revents;
4252
0
  }
4253
0
#endif
4254
0
}
4255
4256
/**
4257
 * g_socket_condition_wait:
4258
 * @socket: a #GSocket
4259
 * @condition: a #GIOCondition mask to wait for
4260
 * @cancellable: (nullable): a #GCancellable, or %NULL
4261
 * @error: a #GError pointer, or %NULL
4262
 *
4263
 * Waits for @condition to become true on @socket. When the condition
4264
 * is met, %TRUE is returned.
4265
 *
4266
 * If @cancellable is cancelled before the condition is met, or if the
4267
 * socket has a timeout set and it is reached before the condition is
4268
 * met, then %FALSE is returned and @error, if non-%NULL, is set to
4269
 * the appropriate value (%G_IO_ERROR_CANCELLED or
4270
 * %G_IO_ERROR_TIMED_OUT).
4271
 *
4272
 * See also g_socket_condition_timed_wait().
4273
 *
4274
 * Returns: %TRUE if the condition was met, %FALSE otherwise
4275
 *
4276
 * Since: 2.22
4277
 */
4278
gboolean
4279
g_socket_condition_wait (GSocket       *socket,
4280
       GIOCondition   condition,
4281
       GCancellable  *cancellable,
4282
       GError       **error)
4283
0
{
4284
0
  g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4285
4286
0
  return g_socket_condition_timed_wait (socket, condition, -1,
4287
0
          cancellable, error);
4288
0
}
4289
4290
/**
4291
 * g_socket_condition_timed_wait:
4292
 * @socket: a #GSocket
4293
 * @condition: a #GIOCondition mask to wait for
4294
 * @timeout_us: the maximum time (in microseconds) to wait, or -1
4295
 * @cancellable: (nullable): a #GCancellable, or %NULL
4296
 * @error: a #GError pointer, or %NULL
4297
 *
4298
 * Waits for up to @timeout_us microseconds for @condition to become true
4299
 * on @socket. If the condition is met, %TRUE is returned.
4300
 *
4301
 * If @cancellable is cancelled before the condition is met, or if
4302
 * @timeout_us (or the socket's #GSocket:timeout) is reached before the
4303
 * condition is met, then %FALSE is returned and @error, if non-%NULL,
4304
 * is set to the appropriate value (%G_IO_ERROR_CANCELLED or
4305
 * %G_IO_ERROR_TIMED_OUT).
4306
 *
4307
 * If you don't want a timeout, use g_socket_condition_wait().
4308
 * (Alternatively, you can pass -1 for @timeout_us.)
4309
 *
4310
 * Note that although @timeout_us is in microseconds for consistency with
4311
 * other GLib APIs, this function actually only has millisecond
4312
 * resolution, and the behavior is undefined if @timeout_us is not an
4313
 * exact number of milliseconds.
4314
 *
4315
 * Returns: %TRUE if the condition was met, %FALSE otherwise
4316
 *
4317
 * Since: 2.32
4318
 */
4319
gboolean
4320
g_socket_condition_timed_wait (GSocket       *socket,
4321
             GIOCondition   condition,
4322
             gint64         timeout_us,
4323
             GCancellable  *cancellable,
4324
             GError       **error)
4325
0
{
4326
0
  gint64 start_time;
4327
0
  gint64 timeout_ms;
4328
4329
0
  g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4330
4331
0
  if (!check_socket (socket, error))
4332
0
    return FALSE;
4333
4334
0
  if (g_cancellable_set_error_if_cancelled (cancellable, error))
4335
0
    return FALSE;
4336
4337
0
  if (socket->priv->timeout &&
4338
0
      (timeout_us < 0 || socket->priv->timeout < timeout_us / G_USEC_PER_SEC))
4339
0
    timeout_ms = (gint64) socket->priv->timeout * 1000;
4340
0
  else if (timeout_us != -1)
4341
0
    timeout_ms = timeout_us / 1000;
4342
0
  else
4343
0
    timeout_ms = -1;
4344
4345
0
  start_time = g_get_monotonic_time ();
4346
4347
#ifdef G_OS_WIN32
4348
  {
4349
    GIOCondition current_condition;
4350
    WSAEVENT events[2];
4351
    DWORD res;
4352
    GPollFD cancel_fd;
4353
    int num_events;
4354
4355
    /* Always check these */
4356
    condition |=  G_IO_ERR | G_IO_HUP;
4357
4358
    add_condition_watch (socket, &condition);
4359
4360
    num_events = 0;
4361
    events[num_events++] = socket->priv->event;
4362
4363
    if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
4364
      events[num_events++] = (WSAEVENT)cancel_fd.fd;
4365
4366
    if (timeout_ms == -1)
4367
      timeout_ms = WSA_INFINITE;
4368
4369
    g_mutex_lock (&socket->priv->win32_source_lock);
4370
    current_condition = update_condition_unlocked (socket);
4371
    while ((condition & current_condition) == 0)
4372
      {
4373
        if (!socket->priv->waiting)
4374
          {
4375
            socket->priv->waiting = TRUE;
4376
            socket->priv->waiting_result = 0;
4377
            g_mutex_unlock (&socket->priv->win32_source_lock);
4378
4379
            res = WSAWaitForMultipleEvents (num_events, events, FALSE, timeout_ms, FALSE);
4380
4381
            g_mutex_lock (&socket->priv->win32_source_lock);
4382
            socket->priv->waiting = FALSE;
4383
            socket->priv->waiting_result = res;
4384
            g_cond_broadcast (&socket->priv->win32_source_cond);
4385
          }
4386
        else
4387
          {
4388
            if (timeout_ms != WSA_INFINITE)
4389
              {
4390
                if (!g_cond_wait_until (&socket->priv->win32_source_cond, &socket->priv->win32_source_lock, timeout_ms))
4391
                  {
4392
                    res = WSA_WAIT_TIMEOUT;
4393
                    break;
4394
                  }
4395
                else
4396
                  {
4397
                    res = socket->priv->waiting_result;
4398
                  }
4399
              }
4400
            else
4401
              {
4402
                g_cond_wait (&socket->priv->win32_source_cond, &socket->priv->win32_source_lock);
4403
                res = socket->priv->waiting_result;
4404
              }
4405
          }
4406
4407
  if (res == WSA_WAIT_FAILED)
4408
    {
4409
      int errsv = get_socket_errno ();
4410
4411
      g_set_error (error, G_IO_ERROR,
4412
       socket_io_error_from_errno (errsv),
4413
       _("Waiting for socket condition: %s"),
4414
       socket_strerror (errsv));
4415
      break;
4416
    }
4417
  else if (res == WSA_WAIT_TIMEOUT)
4418
    {
4419
      g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
4420
         _("Socket I/O timed out"));
4421
      break;
4422
    }
4423
4424
  if (g_cancellable_set_error_if_cancelled (cancellable, error))
4425
    break;
4426
4427
        current_condition = update_condition_unlocked (socket);
4428
4429
  if (timeout_ms != WSA_INFINITE)
4430
    {
4431
      timeout_ms -= (g_get_monotonic_time () - start_time) * 1000;
4432
      if (timeout_ms < 0)
4433
        timeout_ms = 0;
4434
    }
4435
      }
4436
    g_mutex_unlock (&socket->priv->win32_source_lock);
4437
    remove_condition_watch (socket, &condition);
4438
    if (num_events > 1)
4439
      g_cancellable_release_fd (cancellable);
4440
4441
    return (condition & current_condition) != 0;
4442
  }
4443
#else
4444
0
  {
4445
0
    GPollFD poll_fd[2];
4446
0
    gint result;
4447
0
    gint num;
4448
4449
0
    poll_fd[0].fd = socket->priv->fd;
4450
0
    poll_fd[0].events = condition;
4451
0
    num = 1;
4452
4453
0
    if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
4454
0
      num++;
4455
4456
0
    while (TRUE)
4457
0
      {
4458
0
  int errsv;
4459
0
  result = g_poll (poll_fd, num, timeout_ms);
4460
0
  errsv = errno;
4461
0
  if (result != -1 || errsv != EINTR)
4462
0
    break;
4463
4464
0
  if (timeout_ms != -1)
4465
0
    {
4466
0
      timeout_ms -= (g_get_monotonic_time () - start_time) / 1000;
4467
0
      if (timeout_ms < 0)
4468
0
        timeout_ms = 0;
4469
0
    }
4470
0
      }
4471
    
4472
0
    if (num > 1)
4473
0
      g_cancellable_release_fd (cancellable);
4474
4475
0
    if (result == 0)
4476
0
      {
4477
0
  g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
4478
0
           _("Socket I/O timed out"));
4479
0
  return FALSE;
4480
0
      }
4481
4482
0
    return !g_cancellable_set_error_if_cancelled (cancellable, error);
4483
0
  }
4484
0
  #endif
4485
0
}
4486
4487
#ifndef G_OS_WIN32
4488
4489
#ifdef HAVE_QNX
4490
/* QNX has this weird upper limit, or at least used to back in the 6.x days.
4491
 * This was discovered empirically and doesn't appear to be mentioned in any
4492
 * of the official documentation. */
4493
# define G_SOCKET_CONTROL_BUFFER_SIZE_BYTES 2016
4494
#else
4495
0
# define G_SOCKET_CONTROL_BUFFER_SIZE_BYTES 2048
4496
#endif
4497
4498
/* Unfortunately these have to be macros rather than inline functions due to
4499
 * using alloca(). */
4500
0
#define output_message_to_msghdr(message, prev_message, msg, prev_msg, error) \
4501
0
G_STMT_START { \
4502
0
  const GOutputMessage  *_message = (message); \
4503
0
  const GOutputMessage *_prev_message = (prev_message); \
4504
0
  struct msghdr *_msg = (msg); \
4505
0
  const struct msghdr *_prev_msg = (prev_msg); \
4506
0
  GError **_error = (error); \
4507
0
 \
4508
0
  _msg->msg_flags = 0; \
4509
0
 \
4510
0
  /* name */ \
4511
0
  if (_prev_message != NULL && _prev_message->address == _message->address) \
4512
0
    { \
4513
0
      _msg->msg_name = _prev_msg->msg_name; \
4514
0
      _msg->msg_namelen = _prev_msg->msg_namelen; \
4515
0
    } \
4516
0
  else if (_message->address != NULL) \
4517
0
    { \
4518
0
      _msg->msg_namelen = g_socket_address_get_native_size (_message->address); \
4519
0
      _msg->msg_name = g_alloca (_msg->msg_namelen); \
4520
0
      if (!g_socket_address_to_native (_message->address, _msg->msg_name, \
4521
0
                                       _msg->msg_namelen, _error)) \
4522
0
        break; \
4523
0
    } \
4524
0
  else \
4525
0
    { \
4526
0
      _msg->msg_name = NULL; \
4527
0
      _msg->msg_namelen = 0; \
4528
0
    } \
4529
0
 \
4530
0
  /* iov */ \
4531
0
  { \
4532
0
    /* this entire expression will be evaluated at compile time */ \
4533
0
    if (sizeof *_msg->msg_iov == sizeof *_message->vectors && \
4534
0
        sizeof _msg->msg_iov->iov_base == sizeof _message->vectors->buffer && \
4535
0
        G_STRUCT_OFFSET (struct iovec, iov_base) == \
4536
0
        G_STRUCT_OFFSET (GOutputVector, buffer) && \
4537
0
        sizeof _msg->msg_iov->iov_len == sizeof _message->vectors->size && \
4538
0
        G_STRUCT_OFFSET (struct iovec, iov_len) == \
4539
0
        G_STRUCT_OFFSET (GOutputVector, size)) \
4540
0
      /* ABI is compatible */ \
4541
0
      { \
4542
0
        _msg->msg_iov = (struct iovec *) _message->vectors; \
4543
0
        _msg->msg_iovlen = _message->num_vectors; \
4544
0
      } \
4545
0
    else \
4546
0
      /* ABI is incompatible */ \
4547
0
      { \
4548
0
        guint i; \
4549
0
 \
4550
0
        _msg->msg_iov = g_newa (struct iovec, _message->num_vectors); \
4551
0
        for (i = 0; i < _message->num_vectors; i++) \
4552
0
          { \
4553
0
            _msg->msg_iov[i].iov_base = (void *) _message->vectors[i].buffer; \
4554
0
            _msg->msg_iov[i].iov_len = _message->vectors[i].size; \
4555
0
          } \
4556
0
        _msg->msg_iovlen = _message->num_vectors; \
4557
0
      } \
4558
0
  } \
4559
0
 \
4560
0
  /* control */ \
4561
0
  { \
4562
0
    struct cmsghdr *cmsg; \
4563
0
    guint i; \
4564
0
 \
4565
0
    _msg->msg_controllen = 0; \
4566
0
    for (i = 0; i < _message->num_control_messages; i++) \
4567
0
      _msg->msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (_message->control_messages[i])); \
4568
0
 \
4569
0
    if (_msg->msg_controllen == 0) \
4570
0
      _msg->msg_control = NULL; \
4571
0
    else \
4572
0
      { \
4573
0
        _msg->msg_control = g_alloca (_msg->msg_controllen); \
4574
0
        memset (_msg->msg_control, '\0', _msg->msg_controllen); \
4575
0
      } \
4576
0
 \
4577
0
    cmsg = CMSG_FIRSTHDR (_msg); \
4578
0
    for (i = 0; i < _message->num_control_messages; i++) \
4579
0
      { \
4580
0
        cmsg->cmsg_level = g_socket_control_message_get_level (_message->control_messages[i]); \
4581
0
        cmsg->cmsg_type = g_socket_control_message_get_msg_type (_message->control_messages[i]); \
4582
0
        cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (_message->control_messages[i])); \
4583
0
        g_socket_control_message_serialize (_message->control_messages[i], \
4584
0
                                            CMSG_DATA (cmsg)); \
4585
0
        cmsg = CMSG_NXTHDR (_msg, cmsg); \
4586
0
      } \
4587
0
    g_assert (cmsg == NULL); \
4588
0
  } \
4589
0
} G_STMT_END
4590
4591
0
#define input_message_to_msghdr(message, msg) \
4592
0
G_STMT_START { \
4593
0
  const GInputMessage  *_message = (message); \
4594
0
  struct msghdr *_msg = (msg); \
4595
0
 \
4596
0
  /* name */ \
4597
0
  if (_message->address) \
4598
0
    { \
4599
0
      _msg->msg_namelen = sizeof (struct sockaddr_storage); \
4600
0
      _msg->msg_name = g_alloca (_msg->msg_namelen); \
4601
0
    } \
4602
0
  else \
4603
0
    { \
4604
0
      _msg->msg_name = NULL; \
4605
0
      _msg->msg_namelen = 0; \
4606
0
    } \
4607
0
 \
4608
0
  /* iov */ \
4609
0
  /* this entire expression will be evaluated at compile time */ \
4610
0
  if (sizeof *_msg->msg_iov == sizeof *_message->vectors && \
4611
0
      sizeof _msg->msg_iov->iov_base == sizeof _message->vectors->buffer && \
4612
0
      G_STRUCT_OFFSET (struct iovec, iov_base) == \
4613
0
      G_STRUCT_OFFSET (GInputVector, buffer) && \
4614
0
      sizeof _msg->msg_iov->iov_len == sizeof _message->vectors->size && \
4615
0
      G_STRUCT_OFFSET (struct iovec, iov_len) == \
4616
0
      G_STRUCT_OFFSET (GInputVector, size)) \
4617
0
    /* ABI is compatible */ \
4618
0
    { \
4619
0
      _msg->msg_iov = (struct iovec *) _message->vectors; \
4620
0
      _msg->msg_iovlen = _message->num_vectors; \
4621
0
    } \
4622
0
  else \
4623
0
    /* ABI is incompatible */ \
4624
0
    { \
4625
0
      guint i; \
4626
0
 \
4627
0
      _msg->msg_iov = g_newa (struct iovec, _message->num_vectors); \
4628
0
      for (i = 0; i < _message->num_vectors; i++) \
4629
0
        { \
4630
0
          _msg->msg_iov[i].iov_base = _message->vectors[i].buffer; \
4631
0
          _msg->msg_iov[i].iov_len = _message->vectors[i].size; \
4632
0
        } \
4633
0
      _msg->msg_iovlen = _message->num_vectors; \
4634
0
    } \
4635
0
 \
4636
0
  /* control */ \
4637
0
  if (_message->control_messages == NULL) \
4638
0
    { \
4639
0
    _msg->msg_controllen = 0; \
4640
0
    _msg->msg_control = NULL; \
4641
0
    } \
4642
0
  else \
4643
0
    { \
4644
0
      _msg->msg_controllen = G_SOCKET_CONTROL_BUFFER_SIZE_BYTES; \
4645
0
      _msg->msg_control = g_alloca (_msg->msg_controllen); \
4646
0
    } \
4647
0
 \
4648
0
  /* flags */ \
4649
0
  _msg->msg_flags = _message->flags; \
4650
0
} G_STMT_END
4651
4652
static void
4653
input_message_from_msghdr (const struct msghdr  *msg,
4654
                           GInputMessage        *message,
4655
                           GSocket              *socket)
4656
0
{
4657
  /* decode address */
4658
0
  if (message->address != NULL)
4659
0
    {
4660
0
      *message->address = cache_recv_address (socket, msg->msg_name,
4661
0
                                              msg->msg_namelen);
4662
0
    }
4663
4664
  /* decode control messages */
4665
0
  {
4666
0
    GPtrArray *my_messages = NULL;
4667
0
    struct cmsghdr *cmsg;
4668
4669
0
    if (msg->msg_controllen >= sizeof (struct cmsghdr))
4670
0
      {
4671
0
        g_assert (message->control_messages != NULL);
4672
0
        for (cmsg = CMSG_FIRSTHDR (msg);
4673
0
             cmsg != NULL;
4674
0
             cmsg = CMSG_NXTHDR ((struct msghdr *) msg, cmsg))
4675
0
          {
4676
0
            GSocketControlMessage *control_message;
4677
4678
0
            control_message = g_socket_control_message_deserialize (cmsg->cmsg_level,
4679
0
                                                                    cmsg->cmsg_type,
4680
0
                                                                    cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
4681
0
                                                                    CMSG_DATA (cmsg));
4682
0
            if (control_message == NULL)
4683
              /* We've already spewed about the problem in the
4684
                 deserialization code, so just continue */
4685
0
              continue;
4686
4687
0
            if (my_messages == NULL)
4688
0
              my_messages = g_ptr_array_new ();
4689
0
            g_ptr_array_add (my_messages, control_message);
4690
0
           }
4691
0
      }
4692
4693
0
    if (message->num_control_messages)
4694
0
      *message->num_control_messages = my_messages != NULL ? my_messages->len : 0;
4695
4696
0
    if (message->control_messages)
4697
0
      {
4698
0
        if (my_messages == NULL)
4699
0
          {
4700
0
            *message->control_messages = NULL;
4701
0
          }
4702
0
        else
4703
0
          {
4704
0
            g_ptr_array_add (my_messages, NULL);
4705
0
            *message->control_messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
4706
0
          }
4707
0
      }
4708
0
    else
4709
0
      {
4710
0
        g_assert (my_messages == NULL);
4711
0
      }
4712
0
  }
4713
4714
  /* capture the flags */
4715
0
  message->flags = msg->msg_flags;
4716
0
}
4717
#endif
4718
4719
/**
4720
 * g_socket_send_message:
4721
 * @socket: a #GSocket
4722
 * @address: (nullable): a #GSocketAddress, or %NULL
4723
 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
4724
 * @num_vectors: the number of elements in @vectors, or -1
4725
 * @messages: (array length=num_messages) (nullable): a pointer to an
4726
 *   array of #GSocketControlMessages, or %NULL.
4727
 * @num_messages: number of elements in @messages, or -1.
4728
 * @flags: an int containing #GSocketMsgFlags flags, which may additionally
4729
 *    contain [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
4730
 * @cancellable: (nullable): a %GCancellable or %NULL
4731
 * @error: #GError for error reporting, or %NULL to ignore.
4732
 *
4733
 * Send data to @address on @socket.  For sending multiple messages see
4734
 * g_socket_send_messages(); for easier use, see
4735
 * g_socket_send() and g_socket_send_to().
4736
 *
4737
 * If @address is %NULL then the message is sent to the default receiver
4738
 * (set by g_socket_connect()).
4739
 *
4740
 * @vectors must point to an array of #GOutputVector structs and
4741
 * @num_vectors must be the length of this array. (If @num_vectors is -1,
4742
 * then @vectors is assumed to be terminated by a #GOutputVector with a
4743
 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
4744
 * that the sent data will be gathered from. Using multiple
4745
 * #GOutputVectors is more memory-efficient than manually copying
4746
 * data from multiple sources into a single buffer, and more
4747
 * network-efficient than making multiple calls to g_socket_send().
4748
 *
4749
 * @messages, if non-%NULL, is taken to point to an array of @num_messages
4750
 * #GSocketControlMessage instances. These correspond to the control
4751
 * messages to be sent on the socket.
4752
 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
4753
 * array.
4754
 *
4755
 * @flags modify how the message is sent. The commonly available arguments
4756
 * for this are available in the #GSocketMsgFlags enum, but the
4757
 * values there are the same as the system values, and the flags
4758
 * are passed in as-is, so you can pass in system-specific flags too.
4759
 *
4760
 * If the socket is in blocking mode the call will block until there is
4761
 * space for the data in the socket queue. If there is no space available
4762
 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
4763
 * will be returned. To be notified when space is available, wait for the
4764
 * %G_IO_OUT condition. Note though that you may still receive
4765
 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
4766
 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
4767
 * very common due to the way the underlying APIs work.)
4768
 *
4769
 * The sum of the sizes of each #GOutputVector in vectors must not be
4770
 * greater than %G_MAXSSIZE. If the message can be larger than this,
4771
 * then it is mandatory to use the g_socket_send_message_with_timeout()
4772
 * function.
4773
 *
4774
 * On error -1 is returned and @error is set accordingly.
4775
 *
4776
 * Returns: Number of bytes written (which may be less than @size), or -1
4777
 * on error
4778
 *
4779
 * Since: 2.22
4780
 */
4781
gssize
4782
g_socket_send_message (GSocket                *socket,
4783
           GSocketAddress         *address,
4784
           GOutputVector          *vectors,
4785
           gint                    num_vectors,
4786
           GSocketControlMessage **messages,
4787
           gint                    num_messages,
4788
           gint                    flags,
4789
           GCancellable           *cancellable,
4790
           GError                **error)
4791
0
{
4792
0
  GPollableReturn res;
4793
0
  gsize bytes_written = 0;
4794
0
  gsize vectors_size = 0;
4795
4796
0
  if (num_vectors != -1)
4797
0
    {
4798
0
      gint i;
4799
4800
0
      for (i = 0; i < num_vectors; i++)
4801
0
        {
4802
          /* No wrap-around for vectors_size */
4803
0
          if (vectors_size > vectors_size + vectors[i].size)
4804
0
            {
4805
0
              g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
4806
0
                           _("Unable to send message: %s"),
4807
0
                           _("Message vectors too large"));
4808
0
              return -1;
4809
0
            }
4810
4811
0
          vectors_size += vectors[i].size;
4812
0
        }
4813
0
    }
4814
0
  else
4815
0
    {
4816
0
      gsize i;
4817
4818
0
      for (i = 0; vectors[i].buffer != NULL; i++)
4819
0
        {
4820
          /* No wrap-around for vectors_size */
4821
0
          if (vectors_size > vectors_size + vectors[i].size)
4822
0
            {
4823
0
              g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
4824
0
                           _("Unable to send message: %s"),
4825
0
                           _("Message vectors too large"));
4826
0
              return -1;
4827
0
            }
4828
4829
0
          vectors_size += vectors[i].size;
4830
0
        }
4831
0
    }
4832
4833
  /* Check if vector's buffers are too big for gssize */
4834
0
  if (vectors_size > G_MAXSSIZE)
4835
0
    {
4836
0
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
4837
0
                   _("Unable to send message: %s"),
4838
0
                   _("Message vectors too large"));
4839
0
      return -1;
4840
0
    }
4841
4842
0
  res = g_socket_send_message_with_timeout (socket, address,
4843
0
                                            vectors, num_vectors,
4844
0
                                            messages, num_messages, flags,
4845
0
                                            socket->priv->blocking ? -1 : 0,
4846
0
                                            &bytes_written,
4847
0
                                            cancellable, error);
4848
4849
0
  g_assert (res != G_POLLABLE_RETURN_OK || bytes_written <= G_MAXSSIZE);
4850
4851
0
  if (res == G_POLLABLE_RETURN_WOULD_BLOCK)
4852
0
    {
4853
0
#ifndef G_OS_WIN32
4854
0
      socket_set_error_lazy (error, EWOULDBLOCK, _("Error sending message: %s"));
4855
#else
4856
      socket_set_error_lazy (error, WSAEWOULDBLOCK, _("Error sending message: %s"));
4857
#endif
4858
0
    }
4859
4860
0
  return res == G_POLLABLE_RETURN_OK ? (gssize) bytes_written : -1;
4861
0
}
4862
4863
/**
4864
 * g_socket_send_message_with_timeout:
4865
 * @socket: a #GSocket
4866
 * @address: (nullable): a #GSocketAddress, or %NULL
4867
 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
4868
 * @num_vectors: the number of elements in @vectors, or -1
4869
 * @messages: (array length=num_messages) (nullable): a pointer to an
4870
 *   array of #GSocketControlMessages, or %NULL.
4871
 * @num_messages: number of elements in @messages, or -1.
4872
 * @flags: an int containing #GSocketMsgFlags flags, which may additionally
4873
 *    contain [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
4874
 * @timeout_us: the maximum time (in microseconds) to wait, or -1
4875
 * @bytes_written: (out) (optional): location to store the number of bytes that were written to the socket
4876
 * @cancellable: (nullable): a %GCancellable or %NULL
4877
 * @error: #GError for error reporting, or %NULL to ignore.
4878
 *
4879
 * This behaves exactly the same as g_socket_send_message(), except that
4880
 * the choice of timeout behavior is determined by the @timeout_us argument
4881
 * rather than by @socket's properties.
4882
 *
4883
 * On error %G_POLLABLE_RETURN_FAILED is returned and @error is set accordingly, or
4884
 * if the socket is currently not writable %G_POLLABLE_RETURN_WOULD_BLOCK is
4885
 * returned. @bytes_written will contain 0 in both cases.
4886
 *
4887
 * Returns: %G_POLLABLE_RETURN_OK if all data was successfully written,
4888
 * %G_POLLABLE_RETURN_WOULD_BLOCK if the socket is currently not writable, or
4889
 * %G_POLLABLE_RETURN_FAILED if an error happened and @error is set.
4890
 *
4891
 * Since: 2.60
4892
 */
4893
GPollableReturn
4894
g_socket_send_message_with_timeout (GSocket                *socket,
4895
                                    GSocketAddress         *address,
4896
                                    const GOutputVector    *vectors,
4897
                                    gint                    num_vectors,
4898
                                    GSocketControlMessage **messages,
4899
                                    gint                    num_messages,
4900
                                    gint                    flags,
4901
                                    gint64                  timeout_us,
4902
                                    gsize                  *bytes_written,
4903
                                    GCancellable           *cancellable,
4904
                                    GError                **error)
4905
0
{
4906
0
  GOutputVector one_vector;
4907
0
  char zero;
4908
0
  gint64 start_time;
4909
4910
0
  if (bytes_written)
4911
0
    *bytes_written = 0;
4912
4913
0
  g_return_val_if_fail (G_IS_SOCKET (socket), G_POLLABLE_RETURN_FAILED);
4914
0
  g_return_val_if_fail (address == NULL || G_IS_SOCKET_ADDRESS (address), G_POLLABLE_RETURN_FAILED);
4915
0
  g_return_val_if_fail (num_vectors == 0 || vectors != NULL, G_POLLABLE_RETURN_FAILED);
4916
0
  g_return_val_if_fail (num_messages == 0 || messages != NULL, G_POLLABLE_RETURN_FAILED);
4917
0
  g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), G_POLLABLE_RETURN_FAILED);
4918
0
  g_return_val_if_fail (error == NULL || *error == NULL, G_POLLABLE_RETURN_FAILED);
4919
4920
0
  start_time = g_get_monotonic_time ();
4921
4922
0
  if (!check_socket (socket, error))
4923
0
    return G_POLLABLE_RETURN_FAILED;
4924
4925
0
  if (!check_timeout (socket, error))
4926
0
    return G_POLLABLE_RETURN_FAILED;
4927
4928
0
  if (g_cancellable_set_error_if_cancelled (cancellable, error))
4929
0
    return G_POLLABLE_RETURN_FAILED;
4930
4931
0
  if (num_vectors == -1)
4932
0
    {
4933
0
      for (num_vectors = 0;
4934
0
     vectors[num_vectors].buffer != NULL;
4935
0
     num_vectors++)
4936
0
  ;
4937
0
    }
4938
4939
0
  if (num_messages == -1)
4940
0
    {
4941
0
      for (num_messages = 0;
4942
0
     messages != NULL && messages[num_messages] != NULL;
4943
0
     num_messages++)
4944
0
  ;
4945
0
    }
4946
4947
0
  if (num_vectors == 0)
4948
0
    {
4949
0
      zero = '\0';
4950
4951
0
      one_vector.buffer = &zero;
4952
0
      one_vector.size = 1;
4953
0
      num_vectors = 1;
4954
0
      vectors = &one_vector;
4955
0
    }
4956
4957
0
#ifndef G_OS_WIN32
4958
0
  {
4959
0
    GOutputMessage output_message;
4960
0
    struct msghdr msg;
4961
0
    gssize result;
4962
0
    GError *child_error = NULL;
4963
4964
0
    output_message.address = address;
4965
0
    output_message.vectors = (GOutputVector *) vectors;
4966
0
    output_message.num_vectors = num_vectors;
4967
0
    output_message.bytes_sent = 0;
4968
0
    output_message.control_messages = messages;
4969
0
    output_message.num_control_messages = num_messages;
4970
4971
0
    output_message_to_msghdr (&output_message, NULL, &msg, NULL, &child_error);
4972
4973
0
    if (child_error != NULL)
4974
0
      {
4975
0
        g_propagate_error (error, child_error);
4976
0
        return G_POLLABLE_RETURN_FAILED;
4977
0
      }
4978
4979
0
    while (1)
4980
0
      {
4981
0
  result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
4982
0
  if (result < 0)
4983
0
    {
4984
0
      int errsv = get_socket_errno ();
4985
4986
0
      if (errsv == EINTR)
4987
0
        continue;
4988
4989
0
      if (errsv == EWOULDBLOCK || errsv == EAGAIN)
4990
0
              {
4991
0
                if (timeout_us != 0)
4992
0
                  {
4993
0
                    if (!block_on_timeout (socket, G_IO_OUT, timeout_us, start_time,
4994
0
                                           cancellable, error))
4995
0
                      return G_POLLABLE_RETURN_FAILED;
4996
4997
0
                    continue;
4998
0
                  }
4999
5000
0
                return G_POLLABLE_RETURN_WOULD_BLOCK;
5001
0
              }
5002
5003
0
            socket_set_error_lazy (error, errsv, _("Error sending message: %s"));
5004
0
            return G_POLLABLE_RETURN_FAILED;
5005
0
    }
5006
0
  break;
5007
0
      }
5008
5009
0
    if (bytes_written)
5010
0
      *bytes_written = result;
5011
5012
0
    return G_POLLABLE_RETURN_OK;
5013
0
  }
5014
#else
5015
  {
5016
    struct sockaddr_storage addr;
5017
    guint addrlen;
5018
    DWORD bytes_sent;
5019
    int result;
5020
    WSABUF *bufs;
5021
    gint i;
5022
5023
    /* Win32 doesn't support control messages.
5024
       Actually this is possible for raw and datagram sockets
5025
       via WSASendMessage on Vista or later, but that doesn't
5026
       seem very useful */
5027
    if (num_messages != 0)
5028
      {
5029
        g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
5030
                             _("GSocketControlMessage not supported on Windows"));
5031
  return G_POLLABLE_RETURN_FAILED;
5032
      }
5033
5034
    /* iov */
5035
    bufs = g_newa (WSABUF, num_vectors);
5036
    for (i = 0; i < num_vectors; i++)
5037
      {
5038
  bufs[i].buf = (char *)vectors[i].buffer;
5039
  bufs[i].len = (gulong)vectors[i].size;
5040
      }
5041
5042
    /* name */
5043
    addrlen = 0; /* Avoid warning */
5044
    if (address)
5045
      {
5046
  addrlen = g_socket_address_get_native_size (address);
5047
  if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
5048
    return G_POLLABLE_RETURN_FAILED;
5049
      }
5050
5051
    while (1)
5052
      {
5053
  if (address)
5054
    result = WSASendTo (socket->priv->fd,
5055
            bufs, num_vectors,
5056
            &bytes_sent, flags,
5057
            (const struct sockaddr *)&addr, addrlen,
5058
            NULL, NULL);
5059
  else
5060
    result = WSASend (socket->priv->fd,
5061
          bufs, num_vectors,
5062
          &bytes_sent, flags,
5063
          NULL, NULL);
5064
5065
  if (result != 0)
5066
    {
5067
      int errsv = get_socket_errno ();
5068
5069
      if (errsv == WSAEINTR)
5070
        continue;
5071
5072
      if (errsv == WSAEWOULDBLOCK)
5073
              {
5074
                win32_unset_event_mask (socket, FD_WRITE);
5075
5076
                if (timeout_us != 0)
5077
                  {
5078
                    if (!block_on_timeout (socket, G_IO_OUT, timeout_us,
5079
                                           start_time, cancellable, error))
5080
                      return G_POLLABLE_RETURN_FAILED;
5081
5082
                    continue;
5083
                  }
5084
5085
                return G_POLLABLE_RETURN_WOULD_BLOCK;
5086
              }
5087
5088
      socket_set_error_lazy (error, errsv, _("Error sending message: %s"));
5089
      return G_POLLABLE_RETURN_FAILED;
5090
    }
5091
  break;
5092
      }
5093
5094
    if (bytes_written)
5095
      *bytes_written = bytes_sent;
5096
    return G_POLLABLE_RETURN_OK;
5097
  }
5098
#endif
5099
0
}
5100
5101
/**
5102
 * g_socket_send_messages:
5103
 * @socket: a #GSocket
5104
 * @messages: (array length=num_messages): an array of #GOutputMessage structs
5105
 * @num_messages: the number of elements in @messages
5106
 * @flags: an int containing #GSocketMsgFlags flags, which may additionally
5107
 *    contain [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
5108
 * @cancellable: (nullable): a %GCancellable or %NULL
5109
 * @error: #GError for error reporting, or %NULL to ignore.
5110
 *
5111
 * Send multiple data messages from @socket in one go.  This is the most
5112
 * complicated and fully-featured version of this call. For easier use, see
5113
 * g_socket_send(), g_socket_send_to(), and g_socket_send_message().
5114
 *
5115
 * @messages must point to an array of #GOutputMessage structs and
5116
 * @num_messages must be the length of this array. Each #GOutputMessage
5117
 * contains an address to send the data to, and a pointer to an array of
5118
 * #GOutputVector structs to describe the buffers that the data to be sent
5119
 * for each message will be gathered from. Using multiple #GOutputVectors is
5120
 * more memory-efficient than manually copying data from multiple sources
5121
 * into a single buffer, and more network-efficient than making multiple
5122
 * calls to g_socket_send(). Sending multiple messages in one go avoids the
5123
 * overhead of making a lot of syscalls in scenarios where a lot of data
5124
 * packets need to be sent (e.g. high-bandwidth video streaming over RTP/UDP),
5125
 * or where the same data needs to be sent to multiple recipients.
5126
 *
5127
 * @flags modify how the message is sent. The commonly available arguments
5128
 * for this are available in the #GSocketMsgFlags enum, but the
5129
 * values there are the same as the system values, and the flags
5130
 * are passed in as-is, so you can pass in system-specific flags too.
5131
 *
5132
 * If the socket is in blocking mode the call will block until there is
5133
 * space for all the data in the socket queue. If there is no space available
5134
 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
5135
 * will be returned if no data was written at all, otherwise the number of
5136
 * messages sent will be returned. To be notified when space is available,
5137
 * wait for the %G_IO_OUT condition. Note though that you may still receive
5138
 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
5139
 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
5140
 * very common due to the way the underlying APIs work.)
5141
 *
5142
 * On error -1 is returned and @error is set accordingly. An error will only
5143
 * be returned if zero messages could be sent; otherwise the number of messages
5144
 * successfully sent before the error will be returned.
5145
 *
5146
 * Returns: number of messages sent, or -1 on error. Note that the number of
5147
 *     messages sent may be smaller than @num_messages if the socket is
5148
 *     non-blocking or if @num_messages was larger than UIO_MAXIOV (1024),
5149
 *     in which case the caller may re-try to send the remaining messages.
5150
 *
5151
 * Since: 2.44
5152
 */
5153
gint
5154
g_socket_send_messages (GSocket        *socket,
5155
            GOutputMessage *messages,
5156
            guint           num_messages,
5157
            gint            flags,
5158
            GCancellable   *cancellable,
5159
            GError        **error)
5160
0
{
5161
0
  return g_socket_send_messages_with_timeout (socket, messages, num_messages,
5162
0
                                              flags,
5163
0
                                              socket->priv->blocking ? -1 : 0,
5164
0
                                              cancellable, error);
5165
0
}
5166
5167
static gint
5168
g_socket_send_messages_with_timeout (GSocket        *socket,
5169
                                     GOutputMessage *messages,
5170
                                     guint           num_messages,
5171
                                     gint            flags,
5172
                                     gint64          timeout_us,
5173
                                     GCancellable   *cancellable,
5174
                                     GError        **error)
5175
0
{
5176
0
  gint64 start_time;
5177
5178
0
  g_return_val_if_fail (G_IS_SOCKET (socket), -1);
5179
0
  g_return_val_if_fail (num_messages == 0 || messages != NULL, -1);
5180
0
  g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), -1);
5181
0
  g_return_val_if_fail (error == NULL || *error == NULL, -1);
5182
5183
0
  start_time = g_get_monotonic_time ();
5184
5185
0
  if (!check_socket (socket, error))
5186
0
    return -1;
5187
5188
0
  if (!check_timeout (socket, error))
5189
0
    return -1;
5190
5191
0
  if (g_cancellable_set_error_if_cancelled (cancellable, error))
5192
0
    return -1;
5193
5194
0
  if (num_messages == 0)
5195
0
    return 0;
5196
5197
0
#if !defined (G_OS_WIN32) && defined (HAVE_SENDMMSG)
5198
0
  {
5199
0
    struct mmsghdr *msgvec;
5200
0
    guint i, num_sent;
5201
5202
    /* Clamp the number of vectors if more given than we can write in one go.
5203
     * The caller has to handle short writes anyway.
5204
     */
5205
0
    if (num_messages > G_IOV_MAX)
5206
0
      num_messages = G_IOV_MAX;
5207
5208
0
    msgvec = g_newa (struct mmsghdr, num_messages);
5209
5210
0
    for (i = 0; i < num_messages; ++i)
5211
0
      {
5212
0
        GOutputMessage *msg = &messages[i];
5213
0
        struct msghdr *msg_hdr = &msgvec[i].msg_hdr;
5214
0
        GError *child_error = NULL;
5215
5216
0
        msgvec[i].msg_len = 0;
5217
5218
0
        output_message_to_msghdr (msg, (i > 0) ? &messages[i - 1] : NULL,
5219
0
                                  msg_hdr, (i > 0) ? &msgvec[i - 1].msg_hdr : NULL,
5220
0
                                  &child_error);
5221
5222
0
        if (child_error != NULL)
5223
0
          {
5224
0
            g_propagate_error (error, child_error);
5225
0
            return -1;
5226
0
          }
5227
0
      }
5228
5229
0
    for (num_sent = 0; num_sent < num_messages;)
5230
0
      {
5231
0
        gint ret;
5232
5233
0
        ret = sendmmsg (socket->priv->fd, msgvec + num_sent, num_messages - num_sent,
5234
0
                        flags | G_SOCKET_DEFAULT_SEND_FLAGS);
5235
5236
0
        if (ret < 0)
5237
0
          {
5238
0
            int errsv = get_socket_errno ();
5239
5240
0
            if (errsv == EINTR)
5241
0
              continue;
5242
5243
0
            if (timeout_us != 0 &&
5244
0
                (errsv == EWOULDBLOCK ||
5245
0
                 errsv == EAGAIN))
5246
0
              {
5247
0
                if (!block_on_timeout (socket, G_IO_OUT, timeout_us, start_time,
5248
0
                                       cancellable, error))
5249
0
                  {
5250
0
                    if (num_sent > 0)
5251
0
                      {
5252
0
                        g_clear_error (error);
5253
0
                        break;
5254
0
                      }
5255
5256
0
                    return -1;
5257
0
                  }
5258
5259
0
                continue;
5260
0
              }
5261
5262
            /* If any messages were successfully sent, do not error. */
5263
0
            if (num_sent > 0)
5264
0
              break;
5265
5266
0
            socket_set_error_lazy (error, errsv, _("Error sending message: %s"));
5267
5268
0
            return -1;
5269
0
          }
5270
5271
0
        num_sent += ret;
5272
0
      }
5273
5274
0
    for (i = 0; i < num_sent; ++i)
5275
0
      messages[i].bytes_sent = msgvec[i].msg_len;
5276
5277
0
    return num_sent;
5278
0
  }
5279
#else
5280
  {
5281
    gssize result;
5282
    gint i;
5283
    gint64 wait_timeout;
5284
5285
    wait_timeout = timeout_us;
5286
5287
    for (i = 0; i < num_messages; ++i)
5288
      {
5289
        GOutputMessage *msg = &messages[i];
5290
        GError *msg_error = NULL;
5291
        GPollableReturn pollable_result;
5292
        gsize bytes_written = 0;
5293
5294
        pollable_result = g_socket_send_message_with_timeout (socket, msg->address,
5295
                                                              msg->vectors,
5296
                                                              msg->num_vectors,
5297
                                                              msg->control_messages,
5298
                                                              msg->num_control_messages,
5299
                                                              flags, wait_timeout,
5300
                                                              &bytes_written,
5301
                                                              cancellable, &msg_error);
5302
5303
        if (pollable_result == G_POLLABLE_RETURN_WOULD_BLOCK)
5304
          {
5305
#ifndef G_OS_WIN32
5306
            socket_set_error_lazy (&msg_error, EWOULDBLOCK, _("Error sending message: %s"));
5307
#else
5308
            socket_set_error_lazy (&msg_error, WSAEWOULDBLOCK, _("Error sending message: %s"));
5309
#endif
5310
          }
5311
5312
        result = pollable_result == G_POLLABLE_RETURN_OK ? bytes_written : -1;
5313
5314
        /* check if we've timed out or how much time to wait at most */
5315
        if (timeout_us > 0)
5316
          {
5317
            gint64 elapsed = g_get_monotonic_time () - start_time;
5318
            wait_timeout = MAX (timeout_us - elapsed, 1);
5319
          }
5320
5321
        if (result < 0)
5322
          {
5323
            /* if we couldn't send all messages, just return how many we did
5324
             * manage to send, provided we managed to send at least one */
5325
            if (i > 0)
5326
              {
5327
                g_error_free (msg_error);
5328
                return i;
5329
              }
5330
            else
5331
              {
5332
                g_propagate_error (error, msg_error);
5333
                return -1;
5334
              }
5335
          }
5336
5337
        msg->bytes_sent = result;
5338
      }
5339
5340
    return i;
5341
  }
5342
#endif
5343
0
}
5344
5345
static GSocketAddress *
5346
cache_recv_address (GSocket *socket, struct sockaddr *native, size_t native_len)
5347
0
{
5348
0
  GSocketAddress *saddr;
5349
0
  gint i;
5350
0
  guint64 oldest_time = G_MAXUINT64;
5351
0
  gint oldest_index = 0;
5352
5353
0
  if (native_len == 0)
5354
0
    return NULL;
5355
5356
0
  saddr = NULL;
5357
0
  for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
5358
0
    {
5359
0
      GSocketAddress *tmp = socket->priv->recv_addr_cache[i].addr;
5360
0
      gpointer tmp_native = socket->priv->recv_addr_cache[i].native;
5361
0
      gsize tmp_native_len = socket->priv->recv_addr_cache[i].native_len;
5362
5363
0
      if (!tmp)
5364
0
        continue;
5365
5366
0
      if (tmp_native_len != native_len)
5367
0
        continue;
5368
5369
0
      if (memcmp (tmp_native, native, native_len) == 0)
5370
0
        {
5371
0
          saddr = g_object_ref (tmp);
5372
0
          socket->priv->recv_addr_cache[i].last_used = g_get_monotonic_time ();
5373
0
          return saddr;
5374
0
        }
5375
5376
0
      if (socket->priv->recv_addr_cache[i].last_used < oldest_time)
5377
0
        {
5378
0
          oldest_time = socket->priv->recv_addr_cache[i].last_used;
5379
0
          oldest_index = i;
5380
0
        }
5381
0
    }
5382
5383
0
  saddr = g_socket_address_new_from_native (native, native_len);
5384
5385
0
  if (socket->priv->recv_addr_cache[oldest_index].addr)
5386
0
    {
5387
0
      g_object_unref (socket->priv->recv_addr_cache[oldest_index].addr);
5388
0
      g_free (socket->priv->recv_addr_cache[oldest_index].native);
5389
0
    }
5390
5391
0
  socket->priv->recv_addr_cache[oldest_index].native = g_memdup2 (native, native_len);
5392
0
  socket->priv->recv_addr_cache[oldest_index].native_len = native_len;
5393
0
  socket->priv->recv_addr_cache[oldest_index].addr = g_object_ref (saddr);
5394
0
  socket->priv->recv_addr_cache[oldest_index].last_used = g_get_monotonic_time ();
5395
5396
0
  return saddr;
5397
0
}
5398
5399
static gssize
5400
g_socket_receive_message_with_timeout (GSocket                 *socket,
5401
                                       GSocketAddress         **address,
5402
                                       GInputVector            *vectors,
5403
                                       gint                     num_vectors,
5404
                                       GSocketControlMessage ***messages,
5405
                                       gint                    *num_messages,
5406
                                       gint                    *flags,
5407
                                       gint64                   timeout_us,
5408
                                       GCancellable            *cancellable,
5409
                                       GError                 **error)
5410
0
{
5411
0
  GInputVector one_vector;
5412
0
  char one_byte;
5413
0
  gint64 start_time;
5414
5415
0
  g_return_val_if_fail (G_IS_SOCKET (socket), -1);
5416
5417
0
  start_time = g_get_monotonic_time ();
5418
5419
0
  if (!check_socket (socket, error))
5420
0
    return -1;
5421
5422
0
  if (!check_timeout (socket, error))
5423
0
    return -1;
5424
5425
0
  if (g_cancellable_set_error_if_cancelled (cancellable, error))
5426
0
    return -1;
5427
5428
0
  if (num_vectors == -1)
5429
0
    {
5430
0
      for (num_vectors = 0;
5431
0
     vectors[num_vectors].buffer != NULL;
5432
0
     num_vectors++)
5433
0
  ;
5434
0
    }
5435
5436
0
  if (num_vectors == 0)
5437
0
    {
5438
0
      one_vector.buffer = &one_byte;
5439
0
      one_vector.size = 1;
5440
0
      num_vectors = 1;
5441
0
      vectors = &one_vector;
5442
0
    }
5443
5444
0
#ifndef G_OS_WIN32
5445
0
  {
5446
0
    GInputMessage input_message;
5447
0
    struct msghdr msg;
5448
0
    gssize result;
5449
5450
0
    input_message.address = address;
5451
0
    input_message.vectors = vectors;
5452
0
    input_message.num_vectors = num_vectors;
5453
0
    input_message.bytes_received = 0;
5454
0
    input_message.flags = (flags != NULL) ? *flags : 0;
5455
0
    input_message.control_messages = messages;
5456
0
    input_message.num_control_messages = (guint *) num_messages;
5457
5458
    /* We always set the close-on-exec flag so we don't leak file
5459
     * descriptors into child processes.  Note that gunixfdmessage.c
5460
     * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
5461
     */
5462
0
#ifdef MSG_CMSG_CLOEXEC
5463
0
    input_message.flags |= MSG_CMSG_CLOEXEC;
5464
0
#endif
5465
5466
0
    input_message_to_msghdr (&input_message, &msg);
5467
5468
    /* do it */
5469
0
    while (1)
5470
0
      {
5471
0
  result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
5472
0
#ifdef MSG_CMSG_CLOEXEC 
5473
0
  if (result < 0 && get_socket_errno () == EINVAL)
5474
0
    {
5475
      /* We must be running on an old kernel.  Call without the flag. */
5476
0
      msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
5477
0
      result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
5478
0
    }
5479
0
#endif
5480
5481
0
  if (result < 0)
5482
0
    {
5483
0
      int errsv = get_socket_errno ();
5484
5485
0
      if (errsv == EINTR)
5486
0
        continue;
5487
5488
0
      if (timeout_us != 0 &&
5489
0
    (errsv == EWOULDBLOCK ||
5490
0
     errsv == EAGAIN))
5491
0
        {
5492
0
                if (!block_on_timeout (socket, G_IO_IN, timeout_us, start_time,
5493
0
                                       cancellable, error))
5494
0
                  return -1;
5495
5496
0
                continue;
5497
0
        }
5498
5499
0
      socket_set_error_lazy (error, errsv, _("Error receiving message: %s"));
5500
0
      return -1;
5501
0
    }
5502
0
  break;
5503
0
      }
5504
5505
0
    input_message_from_msghdr (&msg, &input_message, socket);
5506
5507
0
    if (flags != NULL)
5508
0
      *flags = input_message.flags;
5509
5510
0
    return result;
5511
0
  }
5512
#else
5513
  {
5514
    struct sockaddr_storage addr;
5515
    int addrlen;
5516
    DWORD bytes_received;
5517
    DWORD win_flags;
5518
    int result;
5519
    WSABUF *bufs;
5520
    gint i;
5521
5522
    /* iov */
5523
    bufs = g_newa (WSABUF, num_vectors);
5524
    for (i = 0; i < num_vectors; i++)
5525
      {
5526
  bufs[i].buf = (char *)vectors[i].buffer;
5527
  bufs[i].len = (gulong)vectors[i].size;
5528
      }
5529
5530
    /* flags */
5531
    if (flags != NULL)
5532
      win_flags = *flags;
5533
    else
5534
      win_flags = 0;
5535
5536
    /* do it */
5537
    while (1)
5538
      {
5539
        /* addrlen has to be of type int because that’s how WSARecvFrom() is defined */
5540
        G_STATIC_ASSERT (sizeof addr <= G_MAXINT);
5541
5542
  addrlen = sizeof addr;
5543
  if (address)
5544
    result = WSARecvFrom (socket->priv->fd,
5545
        bufs, num_vectors,
5546
        &bytes_received, &win_flags,
5547
        (struct sockaddr *)&addr, &addrlen,
5548
        NULL, NULL);
5549
  else
5550
    result = WSARecv (socket->priv->fd,
5551
          bufs, num_vectors,
5552
          &bytes_received, &win_flags,
5553
          NULL, NULL);
5554
  if (result != 0)
5555
    {
5556
      int errsv = get_socket_errno ();
5557
5558
      if (errsv == WSAEINTR)
5559
        continue;
5560
5561
      win32_unset_event_mask (socket, FD_READ);
5562
5563
            if (errsv == WSAEWOULDBLOCK)
5564
              {
5565
                if (timeout_us != 0)
5566
                  {
5567
                    if (!block_on_timeout (socket, G_IO_IN, timeout_us,
5568
                                           start_time, cancellable, error))
5569
                      return -1;
5570
5571
                    continue;
5572
                  }
5573
              }
5574
5575
      socket_set_error_lazy (error, errsv, _("Error receiving message: %s"));
5576
      return -1;
5577
    }
5578
        win32_unset_event_mask (socket, FD_READ);
5579
  break;
5580
      }
5581
5582
    /* decode address */
5583
    if (address != NULL)
5584
      {
5585
        *address = cache_recv_address (socket, (struct sockaddr *)&addr, addrlen);
5586
      }
5587
5588
    /* capture the flags */
5589
    if (flags != NULL)
5590
      *flags = win_flags;
5591
5592
    if (messages != NULL)
5593
      *messages = NULL;
5594
    if (num_messages != NULL)
5595
      *num_messages = 0;
5596
5597
    return bytes_received;
5598
  }
5599
#endif
5600
0
}
5601
5602
/**
5603
 * g_socket_receive_messages:
5604
 * @socket: a #GSocket
5605
 * @messages: (array length=num_messages): an array of #GInputMessage structs
5606
 * @num_messages: the number of elements in @messages
5607
 * @flags: an int containing #GSocketMsgFlags flags for the overall operation,
5608
 *    which may additionally contain
5609
 *    [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
5610
 * @cancellable: (nullable): a %GCancellable or %NULL
5611
 * @error: #GError for error reporting, or %NULL to ignore
5612
 *
5613
 * Receive multiple data messages from @socket in one go.  This is the most
5614
 * complicated and fully-featured version of this call. For easier use, see
5615
 * g_socket_receive(), g_socket_receive_from(), and g_socket_receive_message().
5616
 *
5617
 * @messages must point to an array of #GInputMessage structs and
5618
 * @num_messages must be the length of this array. Each #GInputMessage
5619
 * contains a pointer to an array of #GInputVector structs describing the
5620
 * buffers that the data received in each message will be written to. Using
5621
 * multiple #GInputVectors is more memory-efficient than manually copying data
5622
 * out of a single buffer to multiple sources, and more system-call-efficient
5623
 * than making multiple calls to g_socket_receive(), such as in scenarios where
5624
 * a lot of data packets need to be received (e.g. high-bandwidth video
5625
 * streaming over RTP/UDP).
5626
 *
5627
 * @flags modify how all messages are received. The commonly available
5628
 * arguments for this are available in the #GSocketMsgFlags enum, but the
5629
 * values there are the same as the system values, and the flags
5630
 * are passed in as-is, so you can pass in system-specific flags too. These
5631
 * flags affect the overall receive operation. Flags affecting individual
5632
 * messages are returned in #GInputMessage.flags.
5633
 *
5634
 * The other members of #GInputMessage are treated as described in its
5635
 * documentation.
5636
 *
5637
 * If #GSocket:blocking is %TRUE the call will block until @num_messages have
5638
 * been received, or the end of the stream is reached.
5639
 *
5640
 * If #GSocket:blocking is %FALSE the call will return up to @num_messages
5641
 * without blocking, or %G_IO_ERROR_WOULD_BLOCK if no messages are queued in the
5642
 * operating system to be received.
5643
 *
5644
 * In blocking mode, if #GSocket:timeout is positive and is reached before any
5645
 * messages are received, %G_IO_ERROR_TIMED_OUT is returned, otherwise up to
5646
 * @num_messages are returned. (Note: This is effectively the
5647
 * behaviour of `MSG_WAITFORONE` with recvmmsg().)
5648
 *
5649
 * To be notified when messages are available, wait for the
5650
 * %G_IO_IN condition. Note though that you may still receive
5651
 * %G_IO_ERROR_WOULD_BLOCK from g_socket_receive_messages() even if you were
5652
 * previously notified of a %G_IO_IN condition.
5653
 *
5654
 * If the remote peer closes the connection, any messages queued in the
5655
 * operating system will be returned, and subsequent calls to
5656
 * g_socket_receive_messages() will return 0 (with no error set).
5657
 *
5658
 * On error -1 is returned and @error is set accordingly. An error will only
5659
 * be returned if zero messages could be received; otherwise the number of
5660
 * messages successfully received before the error will be returned.
5661
 *
5662
 * Returns: number of messages received, or -1 on error. Note that the number
5663
 *     of messages received may be smaller than @num_messages if in non-blocking
5664
 *     mode, if the peer closed the connection, or if @num_messages
5665
 *     was larger than `UIO_MAXIOV` (1024), in which case the caller may re-try
5666
 *     to receive the remaining messages.
5667
 *
5668
 * Since: 2.48
5669
 */
5670
gint
5671
g_socket_receive_messages (GSocket        *socket,
5672
                           GInputMessage  *messages,
5673
                           guint           num_messages,
5674
                           gint            flags,
5675
                           GCancellable   *cancellable,
5676
                           GError        **error)
5677
0
{
5678
0
  if (!check_socket (socket, error) ||
5679
0
      !check_timeout (socket, error))
5680
0
    return -1;
5681
5682
0
  return g_socket_receive_messages_with_timeout (socket, messages, num_messages,
5683
0
                                                 flags,
5684
0
                                                 socket->priv->blocking ? -1 : 0,
5685
0
                                                 cancellable, error);
5686
0
}
5687
5688
static gint
5689
g_socket_receive_messages_with_timeout (GSocket        *socket,
5690
                                        GInputMessage  *messages,
5691
                                        guint           num_messages,
5692
                                        gint            flags,
5693
                                        gint64          timeout_us,
5694
                                        GCancellable   *cancellable,
5695
                                        GError        **error)
5696
0
{
5697
0
  gint64 start_time;
5698
5699
0
  g_return_val_if_fail (G_IS_SOCKET (socket), -1);
5700
0
  g_return_val_if_fail (num_messages == 0 || messages != NULL, -1);
5701
0
  g_return_val_if_fail (cancellable == NULL ||
5702
0
                        G_IS_CANCELLABLE (cancellable), -1);
5703
0
  g_return_val_if_fail (error == NULL || *error == NULL, -1);
5704
5705
0
  start_time = g_get_monotonic_time ();
5706
5707
0
  if (!check_socket (socket, error))
5708
0
    return -1;
5709
5710
0
  if (!check_timeout (socket, error))
5711
0
    return -1;
5712
5713
0
  if (g_cancellable_set_error_if_cancelled (cancellable, error))
5714
0
    return -1;
5715
5716
0
  if (num_messages == 0)
5717
0
    return 0;
5718
5719
0
#if !defined (G_OS_WIN32) && defined (HAVE_RECVMMSG)
5720
0
  {
5721
0
    struct mmsghdr *msgvec;
5722
0
    guint i, num_received;
5723
5724
    /* Clamp the number of vectors if more given than we can write in one go.
5725
     * The caller has to handle short writes anyway.
5726
     */
5727
0
    if (num_messages > G_IOV_MAX)
5728
0
      num_messages = G_IOV_MAX;
5729
5730
0
    msgvec = g_newa (struct mmsghdr, num_messages);
5731
5732
0
    for (i = 0; i < num_messages; ++i)
5733
0
      {
5734
0
        GInputMessage *msg = &messages[i];
5735
0
        struct msghdr *msg_hdr = &msgvec[i].msg_hdr;
5736
5737
0
        input_message_to_msghdr (msg, msg_hdr);
5738
0
        msgvec[i].msg_len = 0;
5739
0
      }
5740
5741
    /* We always set the close-on-exec flag so we don't leak file
5742
     * descriptors into child processes.  Note that gunixfdmessage.c
5743
     * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
5744
     */
5745
0
#ifdef MSG_CMSG_CLOEXEC
5746
0
    flags |= MSG_CMSG_CLOEXEC;
5747
0
#endif
5748
5749
0
    for (num_received = 0; num_received < num_messages;)
5750
0
      {
5751
0
        gint ret;
5752
5753
        /* We operate in non-blocking mode and handle the timeout ourselves. */
5754
0
        ret = recvmmsg (socket->priv->fd,
5755
0
                        msgvec + num_received,
5756
0
                        num_messages - num_received,
5757
0
                        flags | G_SOCKET_DEFAULT_SEND_FLAGS, NULL);
5758
0
#ifdef MSG_CMSG_CLOEXEC
5759
0
        if (ret < 0 && get_socket_errno () == EINVAL)
5760
0
          {
5761
            /* We must be running on an old kernel. Call without the flag. */
5762
0
            flags &= ~(MSG_CMSG_CLOEXEC);
5763
0
            ret = recvmmsg (socket->priv->fd,
5764
0
                            msgvec + num_received,
5765
0
                            num_messages - num_received,
5766
0
                            flags | G_SOCKET_DEFAULT_SEND_FLAGS, NULL);
5767
0
          }
5768
0
#endif
5769
5770
0
        if (ret < 0)
5771
0
          {
5772
0
            int errsv = get_socket_errno ();
5773
5774
0
            if (errsv == EINTR)
5775
0
              continue;
5776
5777
0
            if (timeout_us != 0 &&
5778
0
                (errsv == EWOULDBLOCK ||
5779
0
                 errsv == EAGAIN))
5780
0
              {
5781
0
                if (!block_on_timeout (socket, G_IO_IN, timeout_us, start_time,
5782
0
                                       cancellable, error))
5783
0
                  {
5784
0
                    if (num_received > 0)
5785
0
                      {
5786
0
                        g_clear_error (error);
5787
0
                        break;
5788
0
                      }
5789
5790
0
                    return -1;
5791
0
                  }
5792
5793
0
                continue;
5794
0
              }
5795
5796
            /* If any messages were successfully received, do not error. */
5797
0
            if (num_received > 0)
5798
0
              break;
5799
5800
0
            socket_set_error_lazy (error, errsv,
5801
0
                                   _("Error receiving message: %s"));
5802
5803
0
            return -1;
5804
0
          }
5805
0
        else if (ret == 0)
5806
0
          {
5807
            /* EOS. */
5808
0
            break;
5809
0
          }
5810
5811
0
        num_received += ret;
5812
0
      }
5813
5814
0
    for (i = 0; i < num_received; ++i)
5815
0
      {
5816
0
        input_message_from_msghdr (&msgvec[i].msg_hdr, &messages[i], socket);
5817
0
        messages[i].bytes_received = msgvec[i].msg_len;
5818
0
      }
5819
5820
0
    return num_received;
5821
0
  }
5822
#else
5823
  {
5824
    guint i;
5825
    gint64 wait_timeout;
5826
5827
    wait_timeout = timeout_us;
5828
5829
    for (i = 0; i < num_messages; i++)
5830
      {
5831
        GInputMessage *msg = &messages[i];
5832
        gssize len;
5833
        GError *msg_error = NULL;
5834
5835
        msg->flags = flags;  /* in-out parameter */
5836
5837
        len = g_socket_receive_message_with_timeout (socket,
5838
                                                     msg->address,
5839
                                                     msg->vectors,
5840
                                                     msg->num_vectors,
5841
                                                     msg->control_messages,
5842
                                                     (gint *) msg->num_control_messages,
5843
                                                     &msg->flags,
5844
                                                     wait_timeout,
5845
                                                     cancellable,
5846
                                                     &msg_error);
5847
5848
        /* check if we've timed out or how much time to wait at most */
5849
        if (timeout_us > 0)
5850
          {
5851
            gint64 elapsed = g_get_monotonic_time () - start_time;
5852
            wait_timeout = MAX (timeout_us - elapsed, 1);
5853
          }
5854
5855
        if (len >= 0)
5856
          msg->bytes_received = len;
5857
5858
        if (i != 0 &&
5859
            (g_error_matches (msg_error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK) ||
5860
             g_error_matches (msg_error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT)))
5861
          {
5862
            g_clear_error (&msg_error);
5863
            break;
5864
          }
5865
5866
        if (msg_error != NULL)
5867
          {
5868
            g_propagate_error (error, msg_error);
5869
            return -1;
5870
          }
5871
5872
        if (len == 0)
5873
          break;
5874
      }
5875
5876
    return i;
5877
  }
5878
#endif
5879
0
}
5880
5881
/**
5882
 * g_socket_receive_message:
5883
 * @socket: a #GSocket
5884
 * @address: (out) (optional): a pointer to a #GSocketAddress
5885
 *     pointer, or %NULL
5886
 * @vectors: (array length=num_vectors): an array of #GInputVector structs
5887
 * @num_vectors: the number of elements in @vectors, or -1
5888
 * @messages: (array length=num_messages) (out) (optional) (nullable): a pointer
5889
 *    which may be filled with an array of #GSocketControlMessages, or %NULL
5890
 * @num_messages: (out): a pointer which will be filled with the number of
5891
 *    elements in @messages, or %NULL
5892
 * @flags: (inout): a pointer to an int containing #GSocketMsgFlags flags,
5893
 *    which may additionally contain
5894
 *    [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
5895
 * @cancellable: a %GCancellable or %NULL
5896
 * @error: a #GError pointer, or %NULL
5897
 *
5898
 * Receive data from a socket.  For receiving multiple messages, see
5899
 * g_socket_receive_messages(); for easier use, see
5900
 * g_socket_receive() and g_socket_receive_from().
5901
 *
5902
 * If @address is non-%NULL then @address will be set equal to the
5903
 * source address of the received packet.
5904
 * @address is owned by the caller.
5905
 *
5906
 * @vector must point to an array of #GInputVector structs and
5907
 * @num_vectors must be the length of this array.  These structs
5908
 * describe the buffers that received data will be scattered into.
5909
 * If @num_vectors is -1, then @vectors is assumed to be terminated
5910
 * by a #GInputVector with a %NULL buffer pointer.
5911
 *
5912
 * As a special case, if @num_vectors is 0 (in which case, @vectors
5913
 * may of course be %NULL), then a single byte is received and
5914
 * discarded. This is to facilitate the common practice of sending a
5915
 * single '\0' byte for the purposes of transferring ancillary data.
5916
 *
5917
 * @messages, if non-%NULL, will be set to point to a newly-allocated
5918
 * array of #GSocketControlMessage instances or %NULL if no such
5919
 * messages was received. These correspond to the control messages
5920
 * received from the kernel, one #GSocketControlMessage per message
5921
 * from the kernel. This array is %NULL-terminated and must be freed
5922
 * by the caller using g_free() after calling g_object_unref() on each
5923
 * element. If @messages is %NULL, any control messages received will
5924
 * be discarded.
5925
 *
5926
 * @num_messages, if non-%NULL, will be set to the number of control
5927
 * messages received.
5928
 *
5929
 * If both @messages and @num_messages are non-%NULL, then
5930
 * @num_messages gives the number of #GSocketControlMessage instances
5931
 * in @messages (ie: not including the %NULL terminator).
5932
 *
5933
 * @flags is an in/out parameter. The commonly available arguments
5934
 * for this are available in the #GSocketMsgFlags enum, but the
5935
 * values there are the same as the system values, and the flags
5936
 * are passed in as-is, so you can pass in system-specific flags too
5937
 * (and g_socket_receive_message() may pass system-specific flags out).
5938
 * Flags passed in to the parameter affect the receive operation; flags returned
5939
 * out of it are relevant to the specific returned message.
5940
 *
5941
 * As with g_socket_receive(), data may be discarded if @socket is
5942
 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
5943
 * provide enough buffer space to read a complete message. You can pass
5944
 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
5945
 * removing it from the receive queue, but there is no portable way to find
5946
 * out the length of the message other than by reading it into a
5947
 * sufficiently-large buffer.
5948
 *
5949
 * If the socket is in blocking mode the call will block until there
5950
 * is some data to receive, the connection is closed, or there is an
5951
 * error. If there is no data available and the socket is in
5952
 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
5953
 * returned. To be notified when data is available, wait for the
5954
 * %G_IO_IN condition.
5955
 *
5956
 * On error -1 is returned and @error is set accordingly.
5957
 *
5958
 * Returns: Number of bytes read, or 0 if the connection was closed by
5959
 * the peer, or -1 on error
5960
 *
5961
 * Since: 2.22
5962
 */
5963
gssize
5964
g_socket_receive_message (GSocket                 *socket,
5965
        GSocketAddress         **address,
5966
        GInputVector            *vectors,
5967
        gint                     num_vectors,
5968
        GSocketControlMessage ***messages,
5969
        gint                    *num_messages,
5970
        gint                    *flags,
5971
        GCancellable            *cancellable,
5972
        GError                 **error)
5973
0
{
5974
0
  return g_socket_receive_message_with_timeout (socket, address, vectors,
5975
0
                                                 num_vectors, messages,
5976
0
                                                 num_messages, flags,
5977
0
                                                 socket->priv->blocking ? -1 : 0,
5978
0
                                                 cancellable, error);
5979
0
}
5980
5981
/**
5982
 * g_socket_get_credentials:
5983
 * @socket: a #GSocket.
5984
 * @error: #GError for error reporting, or %NULL to ignore.
5985
 *
5986
 * Returns the credentials of the foreign process connected to this
5987
 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
5988
 * sockets).
5989
 *
5990
 * If this operation isn't supported on the OS, the method fails with
5991
 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
5992
 * by reading the %SO_PEERCRED option on the underlying socket.
5993
 *
5994
 * This method can be expected to be available on the following platforms:
5995
 *
5996
 * - Linux since GLib 2.26
5997
 * - OpenBSD since GLib 2.30
5998
 * - Solaris, Illumos and OpenSolaris since GLib 2.40
5999
 * - NetBSD since GLib 2.42
6000
 * - macOS, tvOS, iOS since GLib 2.66
6001
 *
6002
 * Other ways to obtain credentials from a foreign peer includes the
6003
 * #GUnixCredentialsMessage type and
6004
 * g_unix_connection_send_credentials() /
6005
 * g_unix_connection_receive_credentials() functions.
6006
 *
6007
 * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
6008
 * that must be freed with g_object_unref().
6009
 *
6010
 * Since: 2.26
6011
 */
6012
GCredentials *
6013
g_socket_get_credentials (GSocket   *socket,
6014
                          GError   **error)
6015
0
{
6016
0
  GCredentials *ret;
6017
6018
0
  g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
6019
0
  g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6020
6021
0
  if (!check_socket (socket, error))
6022
0
    return NULL;
6023
6024
0
  ret = NULL;
6025
6026
0
#if G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED
6027
6028
0
#ifdef SO_PEERCRED
6029
0
  {
6030
0
    guint8 native_creds_buf[G_CREDENTIALS_NATIVE_SIZE];
6031
0
    socklen_t optlen = sizeof (native_creds_buf);
6032
6033
0
    if (getsockopt (socket->priv->fd,
6034
0
                    SOL_SOCKET,
6035
0
                    SO_PEERCRED,
6036
0
                    native_creds_buf,
6037
0
                    &optlen) == 0)
6038
0
      {
6039
0
        ret = g_credentials_new ();
6040
0
        g_credentials_set_native (ret,
6041
0
                                  G_CREDENTIALS_NATIVE_TYPE,
6042
0
                                  native_creds_buf);
6043
0
      }
6044
0
  }
6045
#elif G_CREDENTIALS_USE_APPLE_XUCRED
6046
  {
6047
    struct xucred cred;
6048
    socklen_t optlen = sizeof (cred);
6049
6050
    if (getsockopt (socket->priv->fd,
6051
                    SOL_LOCAL,
6052
                    LOCAL_PEERCRED,
6053
                    &cred,
6054
                    &optlen) == 0
6055
        && optlen != 0)
6056
      {
6057
        if (cred.cr_version == XUCRED_VERSION)
6058
          {
6059
            ret = g_credentials_new ();
6060
            g_credentials_set_native (ret,
6061
                                      G_CREDENTIALS_NATIVE_TYPE,
6062
                                      &cred);
6063
          }
6064
        else
6065
          {
6066
            g_set_error (error,
6067
                         G_IO_ERROR,
6068
                         G_IO_ERROR_NOT_SUPPORTED,
6069
                         /* No point in translating this! */
6070
                         "struct xucred cr_version %u != %u",
6071
                         cred.cr_version, XUCRED_VERSION);
6072
            /* Reuse a translatable string we already have */
6073
            g_prefix_error (error,
6074
                            _("Unable to read socket credentials: %s"),
6075
                            "");
6076
6077
            return NULL;
6078
          }
6079
      }
6080
    else if (optlen == 0 || errno == EINVAL)
6081
      {
6082
        g_set_error (error,
6083
                     G_IO_ERROR,
6084
                     G_IO_ERROR_NOT_SUPPORTED,
6085
                     _("Unable to read socket credentials: %s"),
6086
                     "unsupported socket type");
6087
        return NULL;
6088
      }
6089
  }
6090
#elif G_CREDENTIALS_USE_NETBSD_UNPCBID
6091
  {
6092
    struct unpcbid cred;
6093
    socklen_t optlen = sizeof (cred);
6094
6095
    if (getsockopt (socket->priv->fd,
6096
                    0,
6097
                    LOCAL_PEEREID,
6098
                    &cred,
6099
                    &optlen) == 0)
6100
      {
6101
        ret = g_credentials_new ();
6102
        g_credentials_set_native (ret,
6103
                                  G_CREDENTIALS_NATIVE_TYPE,
6104
                                  &cred);
6105
      }
6106
  }
6107
#elif G_CREDENTIALS_USE_SOLARIS_UCRED
6108
  {
6109
    ucred_t *ucred = NULL;
6110
6111
    if (getpeerucred (socket->priv->fd, &ucred) == 0)
6112
      {
6113
        ret = g_credentials_new ();
6114
        g_credentials_set_native (ret,
6115
                                  G_CREDENTIALS_TYPE_SOLARIS_UCRED,
6116
                                  ucred);
6117
        ucred_free (ucred);
6118
      }
6119
  }
6120
#else
6121
  #error "G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED is set but this is no code for this platform"
6122
#endif
6123
6124
0
  if (!ret)
6125
0
    {
6126
0
      int errsv = get_socket_errno ();
6127
6128
0
      g_set_error (error,
6129
0
                   G_IO_ERROR,
6130
0
                   socket_io_error_from_errno (errsv),
6131
0
                   _("Unable to read socket credentials: %s"),
6132
0
                   socket_strerror (errsv));
6133
0
    }
6134
6135
#else
6136
6137
  g_set_error_literal (error,
6138
                       G_IO_ERROR,
6139
                       G_IO_ERROR_NOT_SUPPORTED,
6140
                       _("g_socket_get_credentials not implemented for this OS"));
6141
#endif
6142
6143
0
  return ret;
6144
0
}
6145
6146
/**
6147
 * g_socket_get_option:
6148
 * @socket: a #GSocket
6149
 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
6150
 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
6151
 * @value: (out): return location for the option value
6152
 * @error: #GError for error reporting, or %NULL to ignore.
6153
 *
6154
 * Gets the value of an integer-valued option on @socket, as with
6155
 * getsockopt(). (If you need to fetch a  non-integer-valued option,
6156
 * you will need to call getsockopt() directly.)
6157
 *
6158
 * The [<gio/gnetworking.h>][gio-gnetworking.h]
6159
 * header pulls in system headers that will define most of the
6160
 * standard/portable socket options. For unusual socket protocols or
6161
 * platform-dependent options, you may need to include additional
6162
 * headers.
6163
 *
6164
 * Note that even for socket options that are a single byte in size,
6165
 * @value is still a pointer to a #gint variable, not a #guchar;
6166
 * g_socket_get_option() will handle the conversion internally.
6167
 *
6168
 * Returns: success or failure. On failure, @error will be set, and
6169
 *   the system error value (`errno` or WSAGetLastError()) will still
6170
 *   be set to the result of the getsockopt() call.
6171
 *
6172
 * Since: 2.36
6173
 */
6174
gboolean
6175
g_socket_get_option (GSocket  *socket,
6176
         gint      level,
6177
         gint      optname,
6178
         gint     *value,
6179
         GError  **error)
6180
0
{
6181
0
  guint size;
6182
6183
0
  g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
6184
6185
  /* g_socket_get_option() is called during socket init, so skip the init checks
6186
   * in check_socket() */
6187
0
  if (socket->priv->inited && !check_socket (socket, error))
6188
0
    return FALSE;
6189
6190
0
  *value = 0;
6191
0
  size = sizeof (gint);
6192
0
  if (getsockopt (socket->priv->fd, level, optname, value, &size) != 0)
6193
0
    {
6194
0
      int errsv = get_socket_errno ();
6195
6196
0
      g_set_error_literal (error,
6197
0
         G_IO_ERROR,
6198
0
         socket_io_error_from_errno (errsv),
6199
0
         socket_strerror (errsv));
6200
0
#ifndef G_OS_WIN32
6201
      /* Reset errno in case the caller wants to look at it */
6202
0
      errno = errsv;
6203
0
#endif
6204
0
      return FALSE;
6205
0
    }
6206
6207
#if G_BYTE_ORDER == G_BIG_ENDIAN
6208
  /* If the returned value is smaller than an int then we need to
6209
   * slide it over into the low-order bytes of *value.
6210
   */
6211
  if (size != sizeof (gint))
6212
    *value = *value >> (8 * (sizeof (gint) - size));
6213
#endif
6214
6215
0
  return TRUE;
6216
0
}
6217
6218
/**
6219
 * g_socket_set_option:
6220
 * @socket: a #GSocket
6221
 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
6222
 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
6223
 * @value: the value to set the option to
6224
 * @error: #GError for error reporting, or %NULL to ignore.
6225
 *
6226
 * Sets the value of an integer-valued option on @socket, as with
6227
 * setsockopt(). (If you need to set a non-integer-valued option,
6228
 * you will need to call setsockopt() directly.)
6229
 *
6230
 * The [<gio/gnetworking.h>][gio-gnetworking.h]
6231
 * header pulls in system headers that will define most of the
6232
 * standard/portable socket options. For unusual socket protocols or
6233
 * platform-dependent options, you may need to include additional
6234
 * headers.
6235
 *
6236
 * Returns: success or failure. On failure, @error will be set, and
6237
 *   the system error value (`errno` or WSAGetLastError()) will still
6238
 *   be set to the result of the setsockopt() call.
6239
 *
6240
 * Since: 2.36
6241
 */
6242
gboolean
6243
g_socket_set_option (GSocket  *socket,
6244
         gint      level,
6245
         gint      optname,
6246
         gint      value,
6247
         GError  **error)
6248
0
{
6249
0
  gint errsv;
6250
6251
0
  g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
6252
6253
  /* g_socket_set_option() is called during socket init, so skip the init checks
6254
   * in check_socket() */
6255
0
  if (socket->priv->inited && !check_socket (socket, error))
6256
0
    return FALSE;
6257
6258
0
  if (setsockopt (socket->priv->fd, level, optname, &value, sizeof (gint)) == 0)
6259
0
    return TRUE;
6260
6261
#if !defined (__linux__) && !defined (G_OS_WIN32)
6262
  /* Linux and Windows let you set a single-byte value from an int,
6263
   * but most other platforms don't.
6264
   */
6265
  if (errno == EINVAL && value >= SCHAR_MIN && value <= CHAR_MAX)
6266
    {
6267
#if G_BYTE_ORDER == G_BIG_ENDIAN
6268
      value = value << (8 * (sizeof (gint) - 1));
6269
#endif
6270
      if (setsockopt (socket->priv->fd, level, optname, &value, 1) == 0)
6271
        return TRUE;
6272
    }
6273
#endif
6274
6275
0
  errsv = get_socket_errno ();
6276
6277
0
  g_set_error_literal (error,
6278
0
                       G_IO_ERROR,
6279
0
                       socket_io_error_from_errno (errsv),
6280
0
                       socket_strerror (errsv));
6281
0
#ifndef G_OS_WIN32
6282
0
  errno = errsv;
6283
0
#endif
6284
0
  return FALSE;
6285
0
}