Coverage Report

Created: 2025-07-23 08:13

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