Coverage Report

Created: 2025-07-23 08:13

/src/pango/subprojects/glib/gio/gdbusprivate.c
Line
Count
Source (jump to first uncovered line)
1
/* GDBus - GLib D-Bus Library
2
 *
3
 * Copyright (C) 2008-2010 Red Hat, Inc.
4
 *
5
 * SPDX-License-Identifier: LGPL-2.1-or-later
6
 *
7
 * This library is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11
 *
12
 * This library is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
 * Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General
18
 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
19
 *
20
 * Author: David Zeuthen <davidz@redhat.com>
21
 */
22
23
#include "config.h"
24
25
#include <stdlib.h>
26
#include <string.h>
27
28
#include "gdbusauthobserver.h"
29
#include "gdbusconnection.h"
30
#include "gdbusdaemon.h"
31
#include "gdbuserror.h"
32
#include "gdbusintrospection.h"
33
#include "gdbusmessage.h"
34
#include "gdbusprivate.h"
35
#include "gdbusproxy.h"
36
#include "ginputstream.h"
37
#include "gioenumtypes.h"
38
#include "giomodule-priv.h"
39
#include "giostream.h"
40
#include "giotypes.h"
41
#include "glib-private.h"
42
#include "glib/gstdio.h"
43
#include "gmemoryinputstream.h"
44
#include "gsocket.h"
45
#include "gsocketaddress.h"
46
#include "gsocketconnection.h"
47
#include "gsocketcontrolmessage.h"
48
#include "gsocketoutputstream.h"
49
#include "gtask.h"
50
51
#ifdef G_OS_UNIX
52
#include "gunixfdmessage.h"
53
#include "gunixconnection.h"
54
#include "gunixcredentialsmessage.h"
55
#endif
56
57
#ifdef G_OS_WIN32
58
#include <windows.h>
59
#include <io.h>
60
#include <conio.h>
61
#include "gwin32sid.h"
62
#endif
63
64
#include "glibintl.h"
65
66
static gboolean _g_dbus_worker_do_initial_read (gpointer data);
67
static void schedule_pending_close (GDBusWorker *worker);
68
69
/* ---------------------------------------------------------------------------------------------------- */
70
71
gchar *
72
_g_dbus_hexdump (const gchar *data, gsize len, guint indent)
73
0
{
74
0
 guint n, m;
75
0
 GString *ret;
76
77
0
 ret = g_string_new (NULL);
78
79
0
 for (n = 0; n < len; n += 16)
80
0
   {
81
0
     g_string_append_printf (ret, "%*s%04x: ", indent, "", n);
82
83
0
     for (m = n; m < n + 16; m++)
84
0
       {
85
0
         if (m > n && (m%4) == 0)
86
0
           g_string_append_c (ret, ' ');
87
0
         if (m < len)
88
0
           g_string_append_printf (ret, "%02x ", (guchar) data[m]);
89
0
         else
90
0
           g_string_append (ret, "   ");
91
0
       }
92
93
0
     g_string_append (ret, "   ");
94
95
0
     for (m = n; m < len && m < n + 16; m++)
96
0
       g_string_append_c (ret, g_ascii_isprint (data[m]) ? data[m] : '.');
97
98
0
     g_string_append_c (ret, '\n');
99
0
   }
100
101
0
 return g_string_free (ret, FALSE);
102
0
}
103
104
/* ---------------------------------------------------------------------------------------------------- */
105
106
/* Unfortunately ancillary messages are discarded when reading from a
107
 * socket using the GSocketInputStream abstraction. So we provide a
108
 * very GInputStream-ish API that uses GSocket in this case (very
109
 * similar to GSocketInputStream).
110
 */
111
112
typedef struct
113
{
114
  void *buffer;
115
  gsize count;
116
117
  GSocketControlMessage ***messages;
118
  gint *num_messages;
119
} ReadWithControlData;
120
121
static void
122
read_with_control_data_free (ReadWithControlData *data)
123
0
{
124
0
  g_slice_free (ReadWithControlData, data);
125
0
}
126
127
static gboolean
128
_g_socket_read_with_control_messages_ready (GSocket      *socket,
129
                                            GIOCondition  condition,
130
                                            gpointer      user_data)
131
0
{
132
0
  GTask *task = user_data;
133
0
  ReadWithControlData *data = g_task_get_task_data (task);
134
0
  GError *error;
135
0
  gssize result;
136
0
  GInputVector vector;
137
138
0
  error = NULL;
139
0
  vector.buffer = data->buffer;
140
0
  vector.size = data->count;
141
0
  result = g_socket_receive_message (socket,
142
0
                                     NULL, /* address */
143
0
                                     &vector,
144
0
                                     1,
145
0
                                     data->messages,
146
0
                                     data->num_messages,
147
0
                                     NULL,
148
0
                                     g_task_get_cancellable (task),
149
0
                                     &error);
150
151
0
  if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
152
0
    {
153
0
      g_error_free (error);
154
0
      return TRUE;
155
0
    }
156
157
0
  g_assert (result >= 0 || error != NULL);
158
0
  if (result >= 0)
159
0
    g_task_return_int (task, result);
160
0
  else
161
0
    g_task_return_error (task, error);
162
0
  g_object_unref (task);
163
164
0
  return FALSE;
165
0
}
166
167
static void
168
_g_socket_read_with_control_messages (GSocket                 *socket,
169
                                      void                    *buffer,
170
                                      gsize                    count,
171
                                      GSocketControlMessage ***messages,
172
                                      gint                    *num_messages,
173
                                      gint                     io_priority,
174
                                      GCancellable            *cancellable,
175
                                      GAsyncReadyCallback      callback,
176
                                      gpointer                 user_data)
177
0
{
178
0
  GTask *task;
179
0
  ReadWithControlData *data;
180
0
  GSource *source;
181
182
0
  data = g_slice_new0 (ReadWithControlData);
183
0
  data->buffer = buffer;
184
0
  data->count = count;
185
0
  data->messages = messages;
186
0
  data->num_messages = num_messages;
187
188
0
  task = g_task_new (socket, cancellable, callback, user_data);
189
0
  g_task_set_source_tag (task, _g_socket_read_with_control_messages);
190
0
  g_task_set_name (task, "[gio] D-Bus read");
191
0
  g_task_set_task_data (task, data, (GDestroyNotify) read_with_control_data_free);
192
193
0
  if (g_socket_condition_check (socket, G_IO_IN))
194
0
    {
195
0
      if (!_g_socket_read_with_control_messages_ready (socket, G_IO_IN, task))
196
0
        return;
197
0
    }
198
199
0
  source = g_socket_create_source (socket,
200
0
                                   G_IO_IN | G_IO_HUP | G_IO_ERR,
201
0
                                   cancellable);
202
0
  g_task_attach_source (task, source, (GSourceFunc) _g_socket_read_with_control_messages_ready);
203
0
  g_source_unref (source);
204
0
}
205
206
static gssize
207
_g_socket_read_with_control_messages_finish (GSocket       *socket,
208
                                             GAsyncResult  *result,
209
                                             GError       **error)
210
0
{
211
0
  g_return_val_if_fail (G_IS_SOCKET (socket), -1);
212
0
  g_return_val_if_fail (g_task_is_valid (result, socket), -1);
213
214
0
  return g_task_propagate_int (G_TASK (result), error);
215
0
}
216
217
/* ---------------------------------------------------------------------------------------------------- */
218
219
/* Work-around for https://bugzilla.gnome.org/show_bug.cgi?id=674885
220
   and see also the original https://bugzilla.gnome.org/show_bug.cgi?id=627724  */
221
222
static GPtrArray *ensured_classes = NULL;
223
224
static void
225
ensure_type (GType gtype)
226
0
{
227
0
  g_ptr_array_add (ensured_classes, g_type_class_ref (gtype));
228
0
}
229
230
static void
231
release_required_types (void)
232
0
{
233
0
  g_ptr_array_foreach (ensured_classes, (GFunc) g_type_class_unref, NULL);
234
0
  g_ptr_array_unref (ensured_classes);
235
0
  ensured_classes = NULL;
236
0
}
237
238
static void
239
ensure_required_types (void)
240
0
{
241
0
  g_assert (ensured_classes == NULL);
242
0
  ensured_classes = g_ptr_array_new ();
243
  /* Generally in this list, you should initialize types which are used as
244
   * properties first, then the class which has them. For example, GDBusProxy
245
   * has a type of GDBusConnection, so we initialize GDBusConnection first.
246
   * And because GDBusConnection has a property of type GDBusConnectionFlags,
247
   * we initialize that first.
248
   *
249
   * Similarly, GSocket has a type of GSocketAddress.
250
   *
251
   * We don't fill out the whole dependency tree right now because in practice
252
   * it tends to be just types that GDBus use that cause pain, and there
253
   * is work on a more general approach in https://bugzilla.gnome.org/show_bug.cgi?id=674885
254
   */
255
0
  ensure_type (G_TYPE_TASK);
256
0
  ensure_type (G_TYPE_MEMORY_INPUT_STREAM);
257
0
  ensure_type (G_TYPE_DBUS_CONNECTION_FLAGS);
258
0
  ensure_type (G_TYPE_DBUS_CAPABILITY_FLAGS);
259
0
  ensure_type (G_TYPE_DBUS_AUTH_OBSERVER);
260
0
  ensure_type (G_TYPE_DBUS_CONNECTION);
261
0
  ensure_type (G_TYPE_DBUS_PROXY);
262
0
  ensure_type (G_TYPE_SOCKET_FAMILY);
263
0
  ensure_type (G_TYPE_SOCKET_TYPE);
264
0
  ensure_type (G_TYPE_SOCKET_PROTOCOL);
265
0
  ensure_type (G_TYPE_SOCKET_ADDRESS);
266
0
  ensure_type (G_TYPE_SOCKET);
267
0
}
268
/* ---------------------------------------------------------------------------------------------------- */
269
270
typedef struct
271
{
272
  gint refcount;  /* (atomic) */
273
  GThread *thread;
274
  GMainContext *context;
275
  GMainLoop *loop;
276
} SharedThreadData;
277
278
static gpointer
279
gdbus_shared_thread_func (gpointer user_data)
280
0
{
281
0
  SharedThreadData *data = user_data;
282
283
0
  g_main_context_push_thread_default (data->context);
284
0
  g_main_loop_run (data->loop);
285
0
  g_main_context_pop_thread_default (data->context);
286
287
0
  release_required_types ();
288
289
0
  return NULL;
290
0
}
291
292
/* ---------------------------------------------------------------------------------------------------- */
293
294
static SharedThreadData *
295
_g_dbus_shared_thread_ref (void)
296
0
{
297
0
  static SharedThreadData *shared_thread_data = 0;
298
299
0
  if (g_once_init_enter_pointer (&shared_thread_data))
300
0
    {
301
0
      SharedThreadData *data;
302
303
0
      data = g_new0 (SharedThreadData, 1);
304
0
      data->refcount = 0;
305
      
306
0
      data->context = g_main_context_new ();
307
0
      data->loop = g_main_loop_new (data->context, FALSE);
308
0
      data->thread = g_thread_new ("gdbus",
309
0
                                   gdbus_shared_thread_func,
310
0
                                   data);
311
      /* We can cast between gsize and gpointer safely */
312
0
      g_once_init_leave_pointer (&shared_thread_data, data);
313
0
    }
314
315
0
  g_atomic_int_inc (&shared_thread_data->refcount);
316
0
  return shared_thread_data;
317
0
}
318
319
static void
320
_g_dbus_shared_thread_unref (SharedThreadData *data)
321
0
{
322
  /* TODO: actually destroy the shared thread here */
323
#if 0
324
  g_assert (data != NULL);
325
  if (g_atomic_int_dec_and_test (&data->refcount))
326
    {
327
      g_main_loop_quit (data->loop);
328
      //g_thread_join (data->thread);
329
      g_main_loop_unref (data->loop);
330
      g_main_context_unref (data->context);
331
    }
332
#endif
333
0
}
334
335
/* ---------------------------------------------------------------------------------------------------- */
336
337
typedef enum {
338
    PENDING_NONE = 0,
339
    PENDING_WRITE,
340
    PENDING_FLUSH,
341
    PENDING_CLOSE
342
} OutputPending;
343
344
struct GDBusWorker
345
{
346
  gint                                ref_count;  /* (atomic) */
347
348
  SharedThreadData                   *shared_thread_data;
349
350
  /* really a boolean, but GLib 2.28 lacks atomic boolean ops */
351
  gint                                stopped;  /* (atomic) */
352
353
  /* TODO: frozen (e.g. G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) currently
354
   * only affects messages received from the other peer (since GDBusServer is the
355
   * only user) - we might want it to affect messages sent to the other peer too?
356
   */
357
  gboolean                            frozen;
358
  GDBusCapabilityFlags                capabilities;
359
  GQueue                             *received_messages_while_frozen;
360
361
  GIOStream                          *stream;
362
  GCancellable                       *cancellable;
363
  GDBusWorkerMessageReceivedCallback  message_received_callback;
364
  GDBusWorkerMessageAboutToBeSentCallback message_about_to_be_sent_callback;
365
  GDBusWorkerDisconnectedCallback     disconnected_callback;
366
  gpointer                            user_data;
367
368
  /* if not NULL, stream is GSocketConnection */
369
  GSocket *socket;
370
371
  /* used for reading */
372
  GMutex                              read_lock;
373
  gchar                              *read_buffer;
374
  gsize                               read_buffer_allocated_size;
375
  gsize                               read_buffer_cur_size;
376
  gsize                               read_buffer_bytes_wanted;
377
  GUnixFDList                        *read_fd_list;
378
  GSocketControlMessage             **read_ancillary_messages;
379
  gint                                read_num_ancillary_messages;
380
381
  /* Whether an async write, flush or close, or none of those, is pending.
382
   * Only the worker thread may change its value, and only with the write_lock.
383
   * Other threads may read its value when holding the write_lock.
384
   * The worker thread may read its value at any time.
385
   */
386
  OutputPending                       output_pending;
387
  /* used for writing */
388
  GMutex                              write_lock;
389
  /* queue of MessageToWriteData, protected by write_lock */
390
  GQueue                             *write_queue;
391
  /* protected by write_lock */
392
  guint64                             write_num_messages_written;
393
  /* number of messages we'd written out last time we flushed;
394
   * protected by write_lock
395
   */
396
  guint64                             write_num_messages_flushed;
397
  /* list of FlushData, protected by write_lock */
398
  GList                              *write_pending_flushes;
399
  /* list of CloseData, protected by write_lock */
400
  GList                              *pending_close_attempts;
401
  /* no lock - only used from the worker thread */
402
  gboolean                            close_expected;
403
};
404
405
static void _g_dbus_worker_unref (GDBusWorker *worker);
406
407
/* ---------------------------------------------------------------------------------------------------- */
408
409
typedef struct
410
{
411
  GMutex  mutex;
412
  GCond   cond;
413
  guint64 number_to_wait_for;
414
  gboolean finished;
415
  GError *error;
416
} FlushData;
417
418
struct _MessageToWriteData ;
419
typedef struct _MessageToWriteData MessageToWriteData;
420
421
static void message_to_write_data_free (MessageToWriteData *data);
422
423
static void read_message_print_transport_debug (gssize bytes_read,
424
                                                GDBusWorker *worker);
425
426
static void write_message_print_transport_debug (gssize bytes_written,
427
                                                 MessageToWriteData *data);
428
429
typedef struct {
430
    GDBusWorker *worker;
431
    GTask *task;
432
} CloseData;
433
434
static void close_data_free (CloseData *close_data)
435
0
{
436
0
  g_clear_object (&close_data->task);
437
438
0
  _g_dbus_worker_unref (close_data->worker);
439
0
  g_slice_free (CloseData, close_data);
440
0
}
441
442
/* ---------------------------------------------------------------------------------------------------- */
443
444
static GDBusWorker *
445
_g_dbus_worker_ref (GDBusWorker *worker)
446
0
{
447
0
  g_atomic_int_inc (&worker->ref_count);
448
0
  return worker;
449
0
}
450
451
static void
452
_g_dbus_worker_unref (GDBusWorker *worker)
453
0
{
454
0
  if (g_atomic_int_dec_and_test (&worker->ref_count))
455
0
    {
456
0
      g_assert (worker->write_pending_flushes == NULL);
457
458
0
      _g_dbus_shared_thread_unref (worker->shared_thread_data);
459
460
0
      g_object_unref (worker->stream);
461
462
0
      g_mutex_clear (&worker->read_lock);
463
0
      g_object_unref (worker->cancellable);
464
0
      if (worker->read_fd_list != NULL)
465
0
        g_object_unref (worker->read_fd_list);
466
467
0
      g_queue_free_full (worker->received_messages_while_frozen, (GDestroyNotify) g_object_unref);
468
0
      g_mutex_clear (&worker->write_lock);
469
0
      g_queue_free_full (worker->write_queue, (GDestroyNotify) message_to_write_data_free);
470
0
      g_free (worker->read_buffer);
471
472
0
      g_free (worker);
473
0
    }
474
0
}
475
476
static void
477
_g_dbus_worker_emit_disconnected (GDBusWorker  *worker,
478
                                  gboolean      remote_peer_vanished,
479
                                  GError       *error)
480
0
{
481
0
  if (!g_atomic_int_get (&worker->stopped))
482
0
    worker->disconnected_callback (worker, remote_peer_vanished, error, worker->user_data);
483
0
}
484
485
static void
486
_g_dbus_worker_emit_message_received (GDBusWorker  *worker,
487
                                      GDBusMessage *message)
488
0
{
489
0
  if (!g_atomic_int_get (&worker->stopped))
490
0
    worker->message_received_callback (worker, message, worker->user_data);
491
0
}
492
493
static GDBusMessage *
494
_g_dbus_worker_emit_message_about_to_be_sent (GDBusWorker  *worker,
495
                                              GDBusMessage *message)
496
0
{
497
0
  GDBusMessage *ret;
498
0
  if (!g_atomic_int_get (&worker->stopped))
499
0
    ret = worker->message_about_to_be_sent_callback (worker, g_steal_pointer (&message), worker->user_data);
500
0
  else
501
0
    ret = g_steal_pointer (&message);
502
0
  return ret;
503
0
}
504
505
/* can only be called from private thread with read-lock held - takes ownership of @message */
506
static void
507
_g_dbus_worker_queue_or_deliver_received_message (GDBusWorker  *worker,
508
                                                  GDBusMessage *message)
509
0
{
510
0
  if (worker->frozen || g_queue_get_length (worker->received_messages_while_frozen) > 0)
511
0
    {
512
      /* queue up */
513
0
      g_queue_push_tail (worker->received_messages_while_frozen, g_steal_pointer (&message));
514
0
    }
515
0
  else
516
0
    {
517
      /* not frozen, nor anything in queue */
518
0
      _g_dbus_worker_emit_message_received (worker, message);
519
0
      g_clear_object (&message);
520
0
    }
521
0
}
522
523
/* called in private thread shared by all GDBusConnection instances (without read-lock held) */
524
static gboolean
525
unfreeze_in_idle_cb (gpointer user_data)
526
0
{
527
0
  GDBusWorker *worker = user_data;
528
0
  GDBusMessage *message;
529
530
0
  g_mutex_lock (&worker->read_lock);
531
0
  if (worker->frozen)
532
0
    {
533
0
      while ((message = g_queue_pop_head (worker->received_messages_while_frozen)) != NULL)
534
0
        {
535
0
          _g_dbus_worker_emit_message_received (worker, message);
536
0
          g_clear_object (&message);
537
0
        }
538
0
      worker->frozen = FALSE;
539
0
    }
540
0
  else
541
0
    {
542
0
      g_assert (g_queue_get_length (worker->received_messages_while_frozen) == 0);
543
0
    }
544
0
  g_mutex_unlock (&worker->read_lock);
545
0
  return FALSE;
546
0
}
547
548
/* can be called from any thread */
549
void
550
_g_dbus_worker_unfreeze (GDBusWorker *worker)
551
0
{
552
0
  GSource *idle_source;
553
0
  idle_source = g_idle_source_new ();
554
0
  g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
555
0
  g_source_set_callback (idle_source,
556
0
                         unfreeze_in_idle_cb,
557
0
                         _g_dbus_worker_ref (worker),
558
0
                         (GDestroyNotify) _g_dbus_worker_unref);
559
0
  g_source_set_static_name (idle_source, "[gio] unfreeze_in_idle_cb");
560
0
  g_source_attach (idle_source, worker->shared_thread_data->context);
561
0
  g_source_unref (idle_source);
562
0
}
563
564
/* ---------------------------------------------------------------------------------------------------- */
565
566
static void _g_dbus_worker_do_read_unlocked (GDBusWorker *worker);
567
568
/* called in private thread shared by all GDBusConnection instances (without read-lock held) */
569
static void
570
_g_dbus_worker_do_read_cb (GInputStream  *input_stream,
571
                           GAsyncResult  *res,
572
                           gpointer       user_data)
573
0
{
574
0
  GDBusWorker *worker = user_data;
575
0
  GError *error;
576
0
  gssize bytes_read;
577
578
0
  g_mutex_lock (&worker->read_lock);
579
580
  /* If already stopped, don't even process the reply */
581
0
  if (g_atomic_int_get (&worker->stopped))
582
0
    goto out;
583
584
0
  error = NULL;
585
0
  if (worker->socket == NULL)
586
0
    bytes_read = g_input_stream_read_finish (g_io_stream_get_input_stream (worker->stream),
587
0
                                             res,
588
0
                                             &error);
589
0
  else
590
0
    bytes_read = _g_socket_read_with_control_messages_finish (worker->socket,
591
0
                                                              res,
592
0
                                                              &error);
593
0
  if (worker->read_num_ancillary_messages > 0)
594
0
    {
595
0
      gint n;
596
0
      for (n = 0; n < worker->read_num_ancillary_messages; n++)
597
0
        {
598
0
          GSocketControlMessage *control_message = G_SOCKET_CONTROL_MESSAGE (worker->read_ancillary_messages[n]);
599
600
0
          if (FALSE)
601
0
            {
602
0
            }
603
0
#ifdef G_OS_UNIX
604
0
          else if (G_IS_UNIX_FD_MESSAGE (control_message))
605
0
            {
606
0
              GUnixFDMessage *fd_message;
607
0
              gint *fds;
608
0
              gint num_fds;
609
610
0
              fd_message = G_UNIX_FD_MESSAGE (control_message);
611
0
              fds = g_unix_fd_message_steal_fds (fd_message, &num_fds);
612
0
              if (worker->read_fd_list == NULL)
613
0
                {
614
0
                  worker->read_fd_list = g_unix_fd_list_new_from_array (fds, num_fds);
615
0
                }
616
0
              else
617
0
                {
618
0
                  gint n;
619
0
                  for (n = 0; n < num_fds; n++)
620
0
                    {
621
                      /* TODO: really want a append_steal() */
622
0
                      g_unix_fd_list_append (worker->read_fd_list, fds[n], NULL);
623
0
                      (void) g_close (fds[n], NULL);
624
0
                    }
625
0
                }
626
0
              g_free (fds);
627
0
            }
628
0
          else if (G_IS_UNIX_CREDENTIALS_MESSAGE (control_message))
629
0
            {
630
              /* do nothing */
631
0
            }
632
0
#endif
633
0
          else
634
0
            {
635
0
              if (error == NULL)
636
0
                {
637
0
                  g_set_error (&error,
638
0
                               G_IO_ERROR,
639
0
                               G_IO_ERROR_FAILED,
640
0
                               "Unexpected ancillary message of type %s received from peer",
641
0
                               g_type_name (G_TYPE_FROM_INSTANCE (control_message)));
642
0
                  _g_dbus_worker_emit_disconnected (worker, TRUE, error);
643
0
                  g_error_free (error);
644
0
                  g_object_unref (control_message);
645
0
                  n++;
646
0
                  while (n < worker->read_num_ancillary_messages)
647
0
                    g_object_unref (worker->read_ancillary_messages[n++]);
648
0
                  g_free (worker->read_ancillary_messages);
649
0
                  goto out;
650
0
                }
651
0
            }
652
0
          g_object_unref (control_message);
653
0
        }
654
0
      g_free (worker->read_ancillary_messages);
655
0
    }
656
657
0
  if (bytes_read == -1)
658
0
    {
659
0
      if (G_UNLIKELY (_g_dbus_debug_transport ()))
660
0
        {
661
0
          _g_dbus_debug_print_lock ();
662
0
          g_print ("========================================================================\n"
663
0
                   "GDBus-debug:Transport:\n"
664
0
                   "  ---- READ ERROR on stream of type %s:\n"
665
0
                   "  ---- %s %d: %s\n",
666
0
                   g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_input_stream (worker->stream))),
667
0
                   g_quark_to_string (error->domain), error->code,
668
0
                   error->message);
669
0
          _g_dbus_debug_print_unlock ();
670
0
        }
671
672
      /* Every async read that uses this callback uses worker->cancellable
673
       * as its GCancellable. worker->cancellable gets cancelled if and only
674
       * if the GDBusConnection tells us to close (either via
675
       * _g_dbus_worker_stop, which is called on last-unref, or directly),
676
       * so a cancelled read must mean our connection was closed locally.
677
       *
678
       * If we're closing, other errors are possible - notably,
679
       * G_IO_ERROR_CLOSED can be seen if we close the stream with an async
680
       * read in-flight. It seems sensible to treat all read errors during
681
       * closing as an expected thing that doesn't trip exit-on-close.
682
       *
683
       * Because close_expected can't be set until we get into the worker
684
       * thread, but the cancellable is signalled sooner (from another
685
       * thread), we do still need to check the error.
686
       */
687
0
      if (worker->close_expected ||
688
0
          g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
689
0
        _g_dbus_worker_emit_disconnected (worker, FALSE, NULL);
690
0
      else
691
0
        _g_dbus_worker_emit_disconnected (worker, TRUE, error);
692
693
0
      g_error_free (error);
694
0
      goto out;
695
0
    }
696
697
#if 0
698
  g_debug ("read %d bytes (is_closed=%d blocking=%d condition=0x%02x) stream %p, %p",
699
           (gint) bytes_read,
700
           g_socket_is_closed (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream))),
701
           g_socket_get_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream))),
702
           g_socket_condition_check (g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream)),
703
                                     G_IO_IN | G_IO_OUT | G_IO_HUP),
704
           worker->stream,
705
           worker);
706
#endif
707
708
  /* The read failed, which could mean the dbus-daemon was sent SIGTERM. */
709
0
  if (bytes_read == 0)
710
0
    {
711
0
      g_set_error (&error,
712
0
                   G_IO_ERROR,
713
0
                   G_IO_ERROR_FAILED,
714
0
                   "Underlying GIOStream returned 0 bytes on an async read");
715
0
      _g_dbus_worker_emit_disconnected (worker, TRUE, error);
716
0
      g_error_free (error);
717
0
      goto out;
718
0
    }
719
720
0
  read_message_print_transport_debug (bytes_read, worker);
721
722
0
  worker->read_buffer_cur_size += bytes_read;
723
0
  if (worker->read_buffer_bytes_wanted == worker->read_buffer_cur_size)
724
0
    {
725
      /* OK, got what we asked for! */
726
0
      if (worker->read_buffer_bytes_wanted == 16)
727
0
        {
728
0
          gssize message_len;
729
          /* OK, got the header - determine how many more bytes are needed */
730
0
          error = NULL;
731
0
          message_len = g_dbus_message_bytes_needed ((guchar *) worker->read_buffer,
732
0
                                                     16,
733
0
                                                     &error);
734
0
          if (message_len == -1)
735
0
            {
736
0
              g_warning ("_g_dbus_worker_do_read_cb: error determining bytes needed: %s", error->message);
737
0
              _g_dbus_worker_emit_disconnected (worker, FALSE, error);
738
0
              g_error_free (error);
739
0
              goto out;
740
0
            }
741
742
0
          worker->read_buffer_bytes_wanted = message_len;
743
0
          _g_dbus_worker_do_read_unlocked (worker);
744
0
        }
745
0
      else
746
0
        {
747
0
          GDBusMessage *message;
748
0
          error = NULL;
749
750
          /* TODO: use connection->priv->auth to decode the message */
751
752
0
          message = g_dbus_message_new_from_blob ((guchar *) worker->read_buffer,
753
0
                                                  worker->read_buffer_cur_size,
754
0
                                                  worker->capabilities,
755
0
                                                  &error);
756
0
          if (message == NULL)
757
0
            {
758
0
              gchar *s;
759
0
              s = _g_dbus_hexdump (worker->read_buffer, worker->read_buffer_cur_size, 2);
760
0
              g_warning ("Error decoding D-Bus message of %" G_GSIZE_FORMAT " bytes\n"
761
0
                         "The error is: %s\n"
762
0
                         "The payload is as follows:\n"
763
0
                         "%s",
764
0
                         worker->read_buffer_cur_size,
765
0
                         error->message,
766
0
                         s);
767
0
              g_free (s);
768
0
              _g_dbus_worker_emit_disconnected (worker, FALSE, error);
769
0
              g_error_free (error);
770
0
              goto out;
771
0
            }
772
773
0
#ifdef G_OS_UNIX
774
0
          if (worker->read_fd_list != NULL)
775
0
            {
776
0
              g_dbus_message_set_unix_fd_list (message, worker->read_fd_list);
777
0
              g_object_unref (worker->read_fd_list);
778
0
              worker->read_fd_list = NULL;
779
0
            }
780
0
#endif
781
782
0
          if (G_UNLIKELY (_g_dbus_debug_message ()))
783
0
            {
784
0
              gchar *s;
785
0
              _g_dbus_debug_print_lock ();
786
0
              g_print ("========================================================================\n"
787
0
                       "GDBus-debug:Message:\n"
788
0
                       "  <<<< RECEIVED D-Bus message (%" G_GSIZE_FORMAT " bytes)\n",
789
0
                       worker->read_buffer_cur_size);
790
0
              s = g_dbus_message_print (message, 2);
791
0
              g_print ("%s", s);
792
0
              g_free (s);
793
0
              if (G_UNLIKELY (_g_dbus_debug_payload ()))
794
0
                {
795
0
                  s = _g_dbus_hexdump (worker->read_buffer, worker->read_buffer_cur_size, 2);
796
0
                  g_print ("%s\n", s);
797
0
                  g_free (s);
798
0
                }
799
0
              _g_dbus_debug_print_unlock ();
800
0
            }
801
802
          /* yay, got a message, go deliver it */
803
0
          _g_dbus_worker_queue_or_deliver_received_message (worker, g_steal_pointer (&message));
804
805
          /* start reading another message! */
806
0
          worker->read_buffer_bytes_wanted = 0;
807
0
          worker->read_buffer_cur_size = 0;
808
0
          _g_dbus_worker_do_read_unlocked (worker);
809
0
        }
810
0
    }
811
0
  else
812
0
    {
813
      /* didn't get all the bytes we requested - so repeat the request... */
814
0
      _g_dbus_worker_do_read_unlocked (worker);
815
0
    }
816
817
0
 out:
818
0
  g_mutex_unlock (&worker->read_lock);
819
820
  /* check if there is any pending close */
821
0
  schedule_pending_close (worker);
822
823
  /* gives up the reference acquired when calling g_input_stream_read_async() */
824
0
  _g_dbus_worker_unref (worker);
825
0
}
826
827
/* called in private thread shared by all GDBusConnection instances (with read-lock held) */
828
static void
829
_g_dbus_worker_do_read_unlocked (GDBusWorker *worker)
830
0
{
831
  /* Note that we do need to keep trying to read even if close_expected is
832
   * true, because only failing a read causes us to signal 'closed'.
833
   */
834
835
  /* if bytes_wanted is zero, it means start reading a message */
836
0
  if (worker->read_buffer_bytes_wanted == 0)
837
0
    {
838
0
      worker->read_buffer_cur_size = 0;
839
0
      worker->read_buffer_bytes_wanted = 16;
840
0
    }
841
842
  /* ensure we have a (big enough) buffer */
843
0
  if (worker->read_buffer == NULL || worker->read_buffer_bytes_wanted > worker->read_buffer_allocated_size)
844
0
    {
845
      /* TODO: 4096 is randomly chosen; might want a better chosen default minimum */
846
0
      worker->read_buffer_allocated_size = MAX (worker->read_buffer_bytes_wanted, 4096);
847
0
      worker->read_buffer = g_realloc (worker->read_buffer, worker->read_buffer_allocated_size);
848
0
    }
849
850
0
  if (worker->socket == NULL)
851
0
    g_input_stream_read_async (g_io_stream_get_input_stream (worker->stream),
852
0
                               worker->read_buffer + worker->read_buffer_cur_size,
853
0
                               worker->read_buffer_bytes_wanted - worker->read_buffer_cur_size,
854
0
                               G_PRIORITY_DEFAULT,
855
0
                               worker->cancellable,
856
0
                               (GAsyncReadyCallback) _g_dbus_worker_do_read_cb,
857
0
                               _g_dbus_worker_ref (worker));
858
0
  else
859
0
    {
860
0
      worker->read_ancillary_messages = NULL;
861
0
      worker->read_num_ancillary_messages = 0;
862
0
      _g_socket_read_with_control_messages (worker->socket,
863
0
                                            worker->read_buffer + worker->read_buffer_cur_size,
864
0
                                            worker->read_buffer_bytes_wanted - worker->read_buffer_cur_size,
865
0
                                            &worker->read_ancillary_messages,
866
0
                                            &worker->read_num_ancillary_messages,
867
0
                                            G_PRIORITY_DEFAULT,
868
0
                                            worker->cancellable,
869
0
                                            (GAsyncReadyCallback) _g_dbus_worker_do_read_cb,
870
0
                                            _g_dbus_worker_ref (worker));
871
0
    }
872
0
}
873
874
/* called in private thread shared by all GDBusConnection instances (without read-lock held) */
875
static gboolean
876
_g_dbus_worker_do_initial_read (gpointer data)
877
0
{
878
0
  GDBusWorker *worker = data;
879
0
  g_mutex_lock (&worker->read_lock);
880
0
  _g_dbus_worker_do_read_unlocked (worker);
881
0
  g_mutex_unlock (&worker->read_lock);
882
0
  return FALSE;
883
0
}
884
885
/* ---------------------------------------------------------------------------------------------------- */
886
887
struct _MessageToWriteData
888
{
889
  GDBusWorker  *worker;
890
  GDBusMessage *message;  /* (owned) */
891
  gchar        *blob;
892
  gsize         blob_size;
893
894
  gsize         total_written;
895
  GTask        *task;  /* (owned) and (nullable) before writing starts and after g_task_return_*() is called */
896
};
897
898
static void
899
message_to_write_data_free (MessageToWriteData *data)
900
0
{
901
0
  _g_dbus_worker_unref (data->worker);
902
0
  g_clear_object (&data->message);
903
0
  g_free (data->blob);
904
905
  /* The task must either not have been created, or have been created, returned
906
   * and finalised by now. */
907
0
  g_assert (data->task == NULL);
908
909
0
  g_slice_free (MessageToWriteData, data);
910
0
}
911
912
/* ---------------------------------------------------------------------------------------------------- */
913
914
static void write_message_continue_writing (MessageToWriteData *data);
915
916
/* called in private thread shared by all GDBusConnection instances
917
 *
918
 * write-lock is not held on entry
919
 * output_pending is PENDING_WRITE on entry
920
 * @user_data is (transfer full)
921
 */
922
static void
923
write_message_async_cb (GObject      *source_object,
924
                        GAsyncResult *res,
925
                        gpointer      user_data)
926
0
{
927
0
  MessageToWriteData *data = g_steal_pointer (&user_data);
928
0
  gssize bytes_written;
929
0
  GError *error;
930
931
  /* The ownership of @data is a bit odd in this function: it’s (transfer full)
932
   * when the function is called, but the code paths which call g_task_return_*()
933
   * on @data->task will indirectly cause it to be freed, because @data is
934
   * always guaranteed to be the user_data in the #GTask. So that’s why it looks
935
   * like @data is not always freed on every code path in this function. */
936
937
0
  error = NULL;
938
0
  bytes_written = g_output_stream_write_finish (G_OUTPUT_STREAM (source_object),
939
0
                                                res,
940
0
                                                &error);
941
0
  if (bytes_written == -1)
942
0
    {
943
0
      GTask *task = g_steal_pointer (&data->task);
944
0
      g_task_return_error (task, error);
945
0
      g_clear_object (&task);
946
0
      goto out;
947
0
    }
948
0
  g_assert (bytes_written > 0); /* zero is never returned */
949
950
0
  write_message_print_transport_debug (bytes_written, data);
951
952
0
  data->total_written += bytes_written;
953
0
  g_assert (data->total_written <= data->blob_size);
954
0
  if (data->total_written == data->blob_size)
955
0
    {
956
0
      GTask *task = g_steal_pointer (&data->task);
957
0
      g_task_return_boolean (task, TRUE);
958
0
      g_clear_object (&task);
959
0
      goto out;
960
0
    }
961
962
0
  write_message_continue_writing (g_steal_pointer (&data));
963
964
0
 out:
965
0
  ;
966
0
}
967
968
/* called in private thread shared by all GDBusConnection instances
969
 *
970
 * write-lock is not held on entry
971
 * output_pending is PENDING_WRITE on entry
972
 */
973
#ifdef G_OS_UNIX
974
static gboolean
975
on_socket_ready (GSocket      *socket,
976
                 GIOCondition  condition,
977
                 gpointer      user_data)
978
0
{
979
0
  MessageToWriteData *data = g_steal_pointer (&user_data);
980
0
  write_message_continue_writing (g_steal_pointer (&data));
981
0
  return G_SOURCE_REMOVE;
982
0
}
983
#endif
984
985
/* called in private thread shared by all GDBusConnection instances
986
 *
987
 * write-lock is not held on entry
988
 * output_pending is PENDING_WRITE on entry
989
 * @data is (transfer full)
990
 */
991
static void
992
write_message_continue_writing (MessageToWriteData *data)
993
0
{
994
0
  GOutputStream *ostream;
995
0
#ifdef G_OS_UNIX
996
0
  GUnixFDList *fd_list;
997
0
#endif
998
999
  /* The ownership of @data is a bit odd in this function: it’s (transfer full)
1000
   * when the function is called, but the code paths which call g_task_return_*()
1001
   * on @data->task will indirectly cause it to be freed, because @data is
1002
   * always guaranteed to be the user_data in the #GTask. So that’s why it looks
1003
   * like @data is not always freed on every code path in this function. */
1004
1005
0
  ostream = g_io_stream_get_output_stream (data->worker->stream);
1006
0
#ifdef G_OS_UNIX
1007
0
  fd_list = g_dbus_message_get_unix_fd_list (data->message);
1008
0
#endif
1009
1010
0
  g_assert (!g_output_stream_has_pending (ostream));
1011
0
  g_assert_cmpint (data->total_written, <, data->blob_size);
1012
1013
0
  if (FALSE)
1014
0
    {
1015
0
    }
1016
0
#ifdef G_OS_UNIX
1017
0
  else if (G_IS_SOCKET_OUTPUT_STREAM (ostream) && data->total_written == 0)
1018
0
    {
1019
0
      GOutputVector vector;
1020
0
      GSocketControlMessage *control_message;
1021
0
      gssize bytes_written;
1022
0
      GError *error;
1023
1024
0
      vector.buffer = data->blob;
1025
0
      vector.size = data->blob_size;
1026
1027
0
      control_message = NULL;
1028
0
      if (fd_list != NULL && g_unix_fd_list_get_length (fd_list) > 0)
1029
0
        {
1030
0
          if (!(data->worker->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING))
1031
0
            {
1032
0
              GTask *task = g_steal_pointer (&data->task);
1033
0
              g_task_return_new_error_literal (task,
1034
0
                                               G_IO_ERROR,
1035
0
                                               G_IO_ERROR_FAILED,
1036
0
                                               "Tried sending a file descriptor "
1037
0
                                               "but remote peer does not support "
1038
0
                                               "this capability");
1039
0
              g_clear_object (&task);
1040
0
              goto out;
1041
0
            }
1042
0
          control_message = g_unix_fd_message_new_with_fd_list (fd_list);
1043
0
        }
1044
1045
0
      error = NULL;
1046
0
      bytes_written = g_socket_send_message (data->worker->socket,
1047
0
                                             NULL, /* address */
1048
0
                                             &vector,
1049
0
                                             1,
1050
0
                                             control_message != NULL ? &control_message : NULL,
1051
0
                                             control_message != NULL ? 1 : 0,
1052
0
                                             G_SOCKET_MSG_NONE,
1053
0
                                             data->worker->cancellable,
1054
0
                                             &error);
1055
0
      if (control_message != NULL)
1056
0
        g_object_unref (control_message);
1057
1058
0
      if (bytes_written == -1)
1059
0
        {
1060
          /* Handle WOULD_BLOCK by waiting until there's room in the buffer */
1061
0
          if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
1062
0
            {
1063
0
              GSource *source;
1064
0
              source = g_socket_create_source (data->worker->socket,
1065
0
                                               G_IO_OUT | G_IO_HUP | G_IO_ERR,
1066
0
                                               data->worker->cancellable);
1067
0
              g_source_set_callback (source,
1068
0
                                     (GSourceFunc) on_socket_ready,
1069
0
                                     g_steal_pointer (&data),
1070
0
                                     NULL); /* GDestroyNotify */
1071
0
              g_source_attach (source, g_main_context_get_thread_default ());
1072
0
              g_source_unref (source);
1073
0
              g_error_free (error);
1074
0
              goto out;
1075
0
            }
1076
0
          else
1077
0
            {
1078
0
              GTask *task = g_steal_pointer (&data->task);
1079
0
              g_task_return_error (task, error);
1080
0
              g_clear_object (&task);
1081
0
              goto out;
1082
0
            }
1083
0
        }
1084
0
      g_assert (bytes_written > 0); /* zero is never returned */
1085
1086
0
      write_message_print_transport_debug (bytes_written, data);
1087
1088
0
      data->total_written += bytes_written;
1089
0
      g_assert (data->total_written <= data->blob_size);
1090
0
      if (data->total_written == data->blob_size)
1091
0
        {
1092
0
          GTask *task = g_steal_pointer (&data->task);
1093
0
          g_task_return_boolean (task, TRUE);
1094
0
          g_clear_object (&task);
1095
0
          goto out;
1096
0
        }
1097
1098
0
      write_message_continue_writing (g_steal_pointer (&data));
1099
0
    }
1100
0
#endif
1101
0
  else
1102
0
    {
1103
0
#ifdef G_OS_UNIX
1104
0
      if (data->total_written == 0 && fd_list != NULL)
1105
0
        {
1106
          /* We were trying to write byte 0 of the message, which needs
1107
           * the fd list to be attached to it, but this connection doesn't
1108
           * support doing that. */
1109
0
          GTask *task = g_steal_pointer (&data->task);
1110
0
          g_task_return_new_error (task,
1111
0
                                   G_IO_ERROR,
1112
0
                                   G_IO_ERROR_FAILED,
1113
0
                                   "Tried sending a file descriptor on unsupported stream of type %s",
1114
0
                                   g_type_name (G_TYPE_FROM_INSTANCE (ostream)));
1115
0
          g_clear_object (&task);
1116
0
          goto out;
1117
0
        }
1118
0
#endif
1119
1120
0
      g_output_stream_write_async (ostream,
1121
0
                                   (const gchar *) data->blob + data->total_written,
1122
0
                                   data->blob_size - data->total_written,
1123
0
                                   G_PRIORITY_DEFAULT,
1124
0
                                   data->worker->cancellable,
1125
0
                                   write_message_async_cb,
1126
0
                                   data);  /* steal @data */
1127
0
    }
1128
0
#ifdef G_OS_UNIX
1129
0
 out:
1130
0
#endif
1131
0
  ;
1132
0
}
1133
1134
/* called in private thread shared by all GDBusConnection instances
1135
 *
1136
 * write-lock is not held on entry
1137
 * output_pending is PENDING_WRITE on entry
1138
 */
1139
static void
1140
write_message_async (GDBusWorker         *worker,
1141
                     MessageToWriteData  *data,
1142
                     GAsyncReadyCallback  callback,
1143
                     gpointer             user_data)
1144
0
{
1145
0
  data->task = g_task_new (NULL, NULL, callback, user_data);
1146
0
  g_task_set_source_tag (data->task, write_message_async);
1147
0
  g_task_set_name (data->task, "[gio] D-Bus write message");
1148
0
  data->total_written = 0;
1149
0
  write_message_continue_writing (g_steal_pointer (&data));
1150
0
}
1151
1152
/* called in private thread shared by all GDBusConnection instances (with write-lock held) */
1153
static gboolean
1154
write_message_finish (GAsyncResult   *res,
1155
                      GError        **error)
1156
0
{
1157
0
  g_return_val_if_fail (g_task_is_valid (res, NULL), FALSE);
1158
1159
0
  return g_task_propagate_boolean (G_TASK (res), error);
1160
0
}
1161
/* ---------------------------------------------------------------------------------------------------- */
1162
1163
static void continue_writing (GDBusWorker *worker);
1164
1165
typedef struct
1166
{
1167
  GDBusWorker *worker;
1168
  GList *flushers;
1169
} FlushAsyncData;
1170
1171
static void
1172
flush_data_list_complete (const GList  *flushers,
1173
                          const GError *error)
1174
0
{
1175
0
  const GList *l;
1176
1177
0
  for (l = flushers; l != NULL; l = l->next)
1178
0
    {
1179
0
      FlushData *f = l->data;
1180
1181
0
      f->error = error != NULL ? g_error_copy (error) : NULL;
1182
1183
0
      g_mutex_lock (&f->mutex);
1184
0
      f->finished = TRUE;
1185
0
      g_cond_signal (&f->cond);
1186
0
      g_mutex_unlock (&f->mutex);
1187
0
    }
1188
0
}
1189
1190
/* called in private thread shared by all GDBusConnection instances
1191
 *
1192
 * write-lock is not held on entry
1193
 * output_pending is PENDING_FLUSH on entry
1194
 */
1195
static void
1196
ostream_flush_cb (GObject      *source_object,
1197
                  GAsyncResult *res,
1198
                  gpointer      user_data)
1199
0
{
1200
0
  FlushAsyncData *data = user_data;
1201
0
  GError *error;
1202
1203
0
  error = NULL;
1204
0
  g_output_stream_flush_finish (G_OUTPUT_STREAM (source_object),
1205
0
                                res,
1206
0
                                &error);
1207
1208
0
  if (error == NULL)
1209
0
    {
1210
0
      if (G_UNLIKELY (_g_dbus_debug_transport ()))
1211
0
        {
1212
0
          _g_dbus_debug_print_lock ();
1213
0
          g_print ("========================================================================\n"
1214
0
                   "GDBus-debug:Transport:\n"
1215
0
                   "  ---- FLUSHED stream of type %s\n",
1216
0
                   g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_output_stream (data->worker->stream))));
1217
0
          _g_dbus_debug_print_unlock ();
1218
0
        }
1219
0
    }
1220
1221
  /* Make sure we tell folks that we don't have additional
1222
     flushes pending */
1223
0
  g_mutex_lock (&data->worker->write_lock);
1224
0
  data->worker->write_num_messages_flushed = data->worker->write_num_messages_written;
1225
0
  g_assert (data->worker->output_pending == PENDING_FLUSH);
1226
0
  data->worker->output_pending = PENDING_NONE;
1227
0
  g_mutex_unlock (&data->worker->write_lock);
1228
1229
0
  g_assert (data->flushers != NULL);
1230
0
  flush_data_list_complete (data->flushers, error);
1231
0
  g_list_free (data->flushers);
1232
0
  if (error != NULL)
1233
0
    g_error_free (error);
1234
1235
  /* OK, cool, finally kick off the next write */
1236
0
  continue_writing (data->worker);
1237
1238
0
  _g_dbus_worker_unref (data->worker);
1239
0
  g_free (data);
1240
0
}
1241
1242
/* called in private thread shared by all GDBusConnection instances
1243
 *
1244
 * write-lock is not held on entry
1245
 * output_pending is PENDING_FLUSH on entry
1246
 */
1247
static void
1248
start_flush (FlushAsyncData *data)
1249
0
{
1250
0
  g_output_stream_flush_async (g_io_stream_get_output_stream (data->worker->stream),
1251
0
                               G_PRIORITY_DEFAULT,
1252
0
                               data->worker->cancellable,
1253
0
                               ostream_flush_cb,
1254
0
                               data);
1255
0
}
1256
1257
/* called in private thread shared by all GDBusConnection instances
1258
 *
1259
 * write-lock is held on entry
1260
 * output_pending is PENDING_NONE on entry
1261
 */
1262
static void
1263
message_written_unlocked (GDBusWorker *worker,
1264
                          MessageToWriteData *message_data)
1265
0
{
1266
0
  if (G_UNLIKELY (_g_dbus_debug_message ()))
1267
0
    {
1268
0
      gchar *s;
1269
0
      _g_dbus_debug_print_lock ();
1270
0
      g_print ("========================================================================\n"
1271
0
               "GDBus-debug:Message:\n"
1272
0
               "  >>>> SENT D-Bus message (%" G_GSIZE_FORMAT " bytes)\n",
1273
0
               message_data->blob_size);
1274
0
      s = g_dbus_message_print (message_data->message, 2);
1275
0
      g_print ("%s", s);
1276
0
      g_free (s);
1277
0
      if (G_UNLIKELY (_g_dbus_debug_payload ()))
1278
0
        {
1279
0
          s = _g_dbus_hexdump (message_data->blob, message_data->blob_size, 2);
1280
0
          g_print ("%s\n", s);
1281
0
          g_free (s);
1282
0
        }
1283
0
      _g_dbus_debug_print_unlock ();
1284
0
    }
1285
1286
0
  worker->write_num_messages_written += 1;
1287
0
}
1288
1289
/* called in private thread shared by all GDBusConnection instances
1290
 *
1291
 * write-lock is held on entry
1292
 * output_pending is PENDING_NONE on entry
1293
 *
1294
 * Returns: non-%NULL, setting @output_pending, if we need to flush now
1295
 */
1296
static FlushAsyncData *
1297
prepare_flush_unlocked (GDBusWorker *worker)
1298
0
{
1299
0
  GList *l;
1300
0
  GList *ll;
1301
0
  GList *flushers;
1302
1303
0
  flushers = NULL;
1304
0
  for (l = worker->write_pending_flushes; l != NULL; l = ll)
1305
0
    {
1306
0
      FlushData *f = l->data;
1307
0
      ll = l->next;
1308
1309
0
      if (f->number_to_wait_for == worker->write_num_messages_written)
1310
0
        {
1311
0
          flushers = g_list_append (flushers, f);
1312
0
          worker->write_pending_flushes = g_list_delete_link (worker->write_pending_flushes, l);
1313
0
        }
1314
0
    }
1315
0
  if (flushers != NULL)
1316
0
    {
1317
0
      g_assert (worker->output_pending == PENDING_NONE);
1318
0
      worker->output_pending = PENDING_FLUSH;
1319
0
    }
1320
1321
0
  if (flushers != NULL)
1322
0
    {
1323
0
      FlushAsyncData *data;
1324
1325
0
      data = g_new0 (FlushAsyncData, 1);
1326
0
      data->worker = _g_dbus_worker_ref (worker);
1327
0
      data->flushers = flushers;
1328
0
      return data;
1329
0
    }
1330
1331
0
  return NULL;
1332
0
}
1333
1334
/* called in private thread shared by all GDBusConnection instances
1335
 *
1336
 * write-lock is not held on entry
1337
 * output_pending is PENDING_WRITE on entry
1338
 * @user_data is (transfer full)
1339
 */
1340
static void
1341
write_message_cb (GObject       *source_object,
1342
                  GAsyncResult  *res,
1343
                  gpointer       user_data)
1344
0
{
1345
0
  MessageToWriteData *data = user_data;
1346
0
  GError *error;
1347
1348
0
  g_mutex_lock (&data->worker->write_lock);
1349
0
  g_assert (data->worker->output_pending == PENDING_WRITE);
1350
0
  data->worker->output_pending = PENDING_NONE;
1351
1352
0
  error = NULL;
1353
0
  if (!write_message_finish (res, &error))
1354
0
    {
1355
0
      g_mutex_unlock (&data->worker->write_lock);
1356
1357
      /* TODO: handle */
1358
0
      _g_dbus_worker_emit_disconnected (data->worker, TRUE, error);
1359
0
      g_error_free (error);
1360
1361
0
      g_mutex_lock (&data->worker->write_lock);
1362
0
    }
1363
1364
0
  message_written_unlocked (data->worker, data);
1365
1366
0
  g_mutex_unlock (&data->worker->write_lock);
1367
1368
0
  continue_writing (data->worker);
1369
1370
0
  message_to_write_data_free (data);
1371
0
}
1372
1373
/* called in private thread shared by all GDBusConnection instances
1374
 *
1375
 * write-lock is not held on entry
1376
 * output_pending is PENDING_CLOSE on entry
1377
 */
1378
static void
1379
iostream_close_cb (GObject      *source_object,
1380
                   GAsyncResult *res,
1381
                   gpointer      user_data)
1382
0
{
1383
0
  GDBusWorker *worker = user_data;
1384
0
  GError *error = NULL;
1385
0
  GList *pending_close_attempts, *pending_flush_attempts;
1386
0
  GQueue *send_queue;
1387
1388
0
  g_io_stream_close_finish (worker->stream, res, &error);
1389
1390
0
  g_mutex_lock (&worker->write_lock);
1391
1392
0
  pending_close_attempts = worker->pending_close_attempts;
1393
0
  worker->pending_close_attempts = NULL;
1394
1395
0
  pending_flush_attempts = worker->write_pending_flushes;
1396
0
  worker->write_pending_flushes = NULL;
1397
1398
0
  send_queue = worker->write_queue;
1399
0
  worker->write_queue = g_queue_new ();
1400
1401
0
  g_assert (worker->output_pending == PENDING_CLOSE);
1402
0
  worker->output_pending = PENDING_NONE;
1403
1404
  /* Ensure threads waiting for pending flushes to finish will be unblocked. */
1405
0
  worker->write_num_messages_flushed =
1406
0
    worker->write_num_messages_written + g_list_length(pending_flush_attempts);
1407
1408
0
  g_mutex_unlock (&worker->write_lock);
1409
1410
0
  while (pending_close_attempts != NULL)
1411
0
    {
1412
0
      CloseData *close_data = pending_close_attempts->data;
1413
1414
0
      pending_close_attempts = g_list_delete_link (pending_close_attempts,
1415
0
                                                   pending_close_attempts);
1416
1417
0
      if (close_data->task != NULL)
1418
0
        {
1419
0
          if (error != NULL)
1420
0
            g_task_return_error (close_data->task, g_error_copy (error));
1421
0
          else
1422
0
            g_task_return_boolean (close_data->task, TRUE);
1423
0
        }
1424
1425
0
      close_data_free (close_data);
1426
0
    }
1427
1428
0
  g_clear_error (&error);
1429
1430
  /* all messages queued for sending are discarded */
1431
0
  g_queue_free_full (send_queue, (GDestroyNotify) message_to_write_data_free);
1432
  /* all queued flushes fail */
1433
0
  error = g_error_new (G_IO_ERROR, G_IO_ERROR_CANCELLED,
1434
0
                       _("Operation was cancelled"));
1435
0
  flush_data_list_complete (pending_flush_attempts, error);
1436
0
  g_list_free (pending_flush_attempts);
1437
0
  g_clear_error (&error);
1438
1439
0
  _g_dbus_worker_unref (worker);
1440
0
}
1441
1442
/* called in private thread shared by all GDBusConnection instances
1443
 *
1444
 * write-lock is not held on entry
1445
 * output_pending must be PENDING_NONE on entry
1446
 */
1447
static void
1448
continue_writing (GDBusWorker *worker)
1449
0
{
1450
0
  MessageToWriteData *data;
1451
0
  FlushAsyncData *flush_async_data;
1452
1453
0
 write_next:
1454
  /* we mustn't try to write two things at once */
1455
0
  g_assert (worker->output_pending == PENDING_NONE);
1456
1457
0
  g_mutex_lock (&worker->write_lock);
1458
1459
0
  data = NULL;
1460
0
  flush_async_data = NULL;
1461
1462
  /* if we want to close the connection, that takes precedence */
1463
0
  if (worker->pending_close_attempts != NULL)
1464
0
    {
1465
0
      GInputStream *input = g_io_stream_get_input_stream (worker->stream);
1466
1467
0
      if (!g_input_stream_has_pending (input))
1468
0
        {
1469
0
          worker->close_expected = TRUE;
1470
0
          worker->output_pending = PENDING_CLOSE;
1471
1472
0
          g_io_stream_close_async (worker->stream, G_PRIORITY_DEFAULT,
1473
0
                                   NULL, iostream_close_cb,
1474
0
                                   _g_dbus_worker_ref (worker));
1475
0
        }
1476
0
    }
1477
0
  else
1478
0
    {
1479
0
      flush_async_data = prepare_flush_unlocked (worker);
1480
1481
0
      if (flush_async_data == NULL)
1482
0
        {
1483
0
          data = g_queue_pop_head (worker->write_queue);
1484
1485
0
          if (data != NULL)
1486
0
            worker->output_pending = PENDING_WRITE;
1487
0
        }
1488
0
    }
1489
1490
0
  g_mutex_unlock (&worker->write_lock);
1491
1492
  /* Note that write_lock is only used for protecting the @write_queue
1493
   * and @output_pending fields of the GDBusWorker struct ... which we
1494
   * need to modify from arbitrary threads in _g_dbus_worker_send_message().
1495
   *
1496
   * Therefore, it's fine to drop it here when calling back into user
1497
   * code and then writing the message out onto the GIOStream since this
1498
   * function only runs on the worker thread.
1499
   */
1500
1501
0
  if (flush_async_data != NULL)
1502
0
    {
1503
0
      start_flush (flush_async_data);
1504
0
      g_assert (data == NULL);
1505
0
    }
1506
0
  else if (data != NULL)
1507
0
    {
1508
0
      GDBusMessage *old_message;
1509
0
      guchar *new_blob;
1510
0
      gsize new_blob_size;
1511
0
      GError *error;
1512
1513
0
      old_message = data->message;
1514
0
      data->message = _g_dbus_worker_emit_message_about_to_be_sent (worker, data->message);
1515
0
      if (data->message == old_message)
1516
0
        {
1517
          /* filters had no effect - do nothing */
1518
0
        }
1519
0
      else if (data->message == NULL)
1520
0
        {
1521
          /* filters dropped message */
1522
0
          g_mutex_lock (&worker->write_lock);
1523
0
          worker->output_pending = PENDING_NONE;
1524
0
          g_mutex_unlock (&worker->write_lock);
1525
0
          message_to_write_data_free (data);
1526
0
          goto write_next;
1527
0
        }
1528
0
      else
1529
0
        {
1530
          /* filters altered the message -> re-encode */
1531
0
          error = NULL;
1532
0
          new_blob = g_dbus_message_to_blob (data->message,
1533
0
                                             &new_blob_size,
1534
0
                                             worker->capabilities,
1535
0
                                             &error);
1536
0
          if (new_blob == NULL)
1537
0
            {
1538
              /* if filter make the GDBusMessage unencodeable, just complain on stderr and send
1539
               * the old message instead
1540
               */
1541
0
              g_warning ("Error encoding GDBusMessage with serial %d altered by filter function: %s",
1542
0
                         g_dbus_message_get_serial (data->message),
1543
0
                         error->message);
1544
0
              g_error_free (error);
1545
0
            }
1546
0
          else
1547
0
            {
1548
0
              g_free (data->blob);
1549
0
              data->blob = (gchar *) new_blob;
1550
0
              data->blob_size = new_blob_size;
1551
0
            }
1552
0
        }
1553
1554
0
      write_message_async (worker,
1555
0
                           data,
1556
0
                           write_message_cb,
1557
0
                           data);  /* takes ownership of @data as user_data */
1558
0
    }
1559
0
}
1560
1561
/* called in private thread shared by all GDBusConnection instances
1562
 *
1563
 * write-lock is not held on entry
1564
 * output_pending may be anything
1565
 */
1566
static gboolean
1567
continue_writing_in_idle_cb (gpointer user_data)
1568
0
{
1569
0
  GDBusWorker *worker = user_data;
1570
1571
  /* Because this is the worker thread, we can read this struct member
1572
   * without holding the lock: no other thread ever modifies it.
1573
   */
1574
0
  if (worker->output_pending == PENDING_NONE)
1575
0
    continue_writing (worker);
1576
1577
0
  return FALSE;
1578
0
}
1579
1580
/*
1581
 * @write_data: (transfer full) (nullable):
1582
 * @flush_data: (transfer full) (nullable):
1583
 * @close_data: (transfer full) (nullable):
1584
 *
1585
 * Can be called from any thread
1586
 *
1587
 * write_lock is held on entry
1588
 * output_pending may be anything
1589
 */
1590
static void
1591
schedule_writing_unlocked (GDBusWorker        *worker,
1592
                           MessageToWriteData *write_data,
1593
                           FlushData          *flush_data,
1594
                           CloseData          *close_data)
1595
0
{
1596
0
  if (write_data != NULL)
1597
0
    g_queue_push_tail (worker->write_queue, write_data);
1598
1599
0
  if (flush_data != NULL)
1600
0
    worker->write_pending_flushes = g_list_prepend (worker->write_pending_flushes, flush_data);
1601
1602
0
  if (close_data != NULL)
1603
0
    worker->pending_close_attempts = g_list_prepend (worker->pending_close_attempts,
1604
0
                                                     close_data);
1605
1606
  /* If we had output pending, the next bit of output will happen
1607
   * automatically when it finishes, so we only need to do this
1608
   * if nothing was pending.
1609
   *
1610
   * The idle callback will re-check that output_pending is still
1611
   * PENDING_NONE, to guard against output starting before the idle.
1612
   */
1613
0
  if (worker->output_pending == PENDING_NONE)
1614
0
    {
1615
0
      GSource *idle_source;
1616
0
      idle_source = g_idle_source_new ();
1617
0
      g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1618
0
      g_source_set_callback (idle_source,
1619
0
                             continue_writing_in_idle_cb,
1620
0
                             _g_dbus_worker_ref (worker),
1621
0
                             (GDestroyNotify) _g_dbus_worker_unref);
1622
0
      g_source_set_static_name (idle_source, "[gio] continue_writing_in_idle_cb");
1623
0
      g_source_attach (idle_source, worker->shared_thread_data->context);
1624
0
      g_source_unref (idle_source);
1625
0
    }
1626
0
}
1627
1628
static void
1629
schedule_pending_close (GDBusWorker *worker)
1630
0
{
1631
0
  g_mutex_lock (&worker->write_lock);
1632
0
  if (worker->pending_close_attempts)
1633
0
    schedule_writing_unlocked (worker, NULL, NULL, NULL);
1634
0
  g_mutex_unlock (&worker->write_lock);
1635
0
}
1636
1637
/* ---------------------------------------------------------------------------------------------------- */
1638
1639
/* can be called from any thread - steals blob
1640
 *
1641
 * write_lock is not held on entry
1642
 * output_pending may be anything
1643
 */
1644
void
1645
_g_dbus_worker_send_message (GDBusWorker    *worker,
1646
                             GDBusMessage   *message,
1647
                             gchar          *blob,
1648
                             gsize           blob_len)
1649
0
{
1650
0
  MessageToWriteData *data;
1651
1652
0
  g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1653
0
  g_return_if_fail (blob != NULL);
1654
0
  g_return_if_fail (blob_len > 16);
1655
1656
0
  data = g_slice_new0 (MessageToWriteData);
1657
0
  data->worker = _g_dbus_worker_ref (worker);
1658
0
  data->message = g_object_ref (message);
1659
0
  data->blob = blob; /* steal! */
1660
0
  data->blob_size = blob_len;
1661
1662
0
  g_mutex_lock (&worker->write_lock);
1663
0
  schedule_writing_unlocked (worker, data, NULL, NULL);
1664
0
  g_mutex_unlock (&worker->write_lock);
1665
0
}
1666
1667
/* ---------------------------------------------------------------------------------------------------- */
1668
1669
GDBusWorker *
1670
_g_dbus_worker_new (GIOStream                              *stream,
1671
                    GDBusCapabilityFlags                    capabilities,
1672
                    gboolean                                initially_frozen,
1673
                    GDBusWorkerMessageReceivedCallback      message_received_callback,
1674
                    GDBusWorkerMessageAboutToBeSentCallback message_about_to_be_sent_callback,
1675
                    GDBusWorkerDisconnectedCallback         disconnected_callback,
1676
                    gpointer                                user_data)
1677
0
{
1678
0
  GDBusWorker *worker;
1679
0
  GSource *idle_source;
1680
1681
0
  g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
1682
0
  g_return_val_if_fail (message_received_callback != NULL, NULL);
1683
0
  g_return_val_if_fail (message_about_to_be_sent_callback != NULL, NULL);
1684
0
  g_return_val_if_fail (disconnected_callback != NULL, NULL);
1685
1686
0
  worker = g_new0 (GDBusWorker, 1);
1687
0
  worker->ref_count = 1;
1688
1689
0
  g_mutex_init (&worker->read_lock);
1690
0
  worker->message_received_callback = message_received_callback;
1691
0
  worker->message_about_to_be_sent_callback = message_about_to_be_sent_callback;
1692
0
  worker->disconnected_callback = disconnected_callback;
1693
0
  worker->user_data = user_data;
1694
0
  worker->stream = g_object_ref (stream);
1695
0
  worker->capabilities = capabilities;
1696
0
  worker->cancellable = g_cancellable_new ();
1697
0
  worker->output_pending = PENDING_NONE;
1698
1699
0
  worker->frozen = initially_frozen;
1700
0
  worker->received_messages_while_frozen = g_queue_new ();
1701
1702
0
  g_mutex_init (&worker->write_lock);
1703
0
  worker->write_queue = g_queue_new ();
1704
1705
0
  if (G_IS_SOCKET_CONNECTION (worker->stream))
1706
0
    worker->socket = g_socket_connection_get_socket (G_SOCKET_CONNECTION (worker->stream));
1707
1708
0
  worker->shared_thread_data = _g_dbus_shared_thread_ref ();
1709
1710
  /* begin reading */
1711
0
  idle_source = g_idle_source_new ();
1712
0
  g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1713
0
  g_source_set_callback (idle_source,
1714
0
                         _g_dbus_worker_do_initial_read,
1715
0
                         _g_dbus_worker_ref (worker),
1716
0
                         (GDestroyNotify) _g_dbus_worker_unref);
1717
0
  g_source_set_static_name (idle_source, "[gio] _g_dbus_worker_do_initial_read");
1718
0
  g_source_attach (idle_source, worker->shared_thread_data->context);
1719
0
  g_source_unref (idle_source);
1720
1721
0
  return worker;
1722
0
}
1723
1724
/* ---------------------------------------------------------------------------------------------------- */
1725
1726
/* can be called from any thread
1727
 *
1728
 * write_lock is not held on entry
1729
 * output_pending may be anything
1730
 */
1731
void
1732
_g_dbus_worker_close (GDBusWorker         *worker,
1733
                      GTask               *task)
1734
0
{
1735
0
  CloseData *close_data;
1736
1737
0
  close_data = g_slice_new0 (CloseData);
1738
0
  close_data->worker = _g_dbus_worker_ref (worker);
1739
0
  close_data->task = (task == NULL ? NULL : g_object_ref (task));
1740
1741
  /* Don't set worker->close_expected here - we're in the wrong thread.
1742
   * It'll be set before the actual close happens.
1743
   */
1744
0
  g_cancellable_cancel (worker->cancellable);
1745
0
  g_mutex_lock (&worker->write_lock);
1746
0
  schedule_writing_unlocked (worker, NULL, NULL, close_data);
1747
0
  g_mutex_unlock (&worker->write_lock);
1748
0
}
1749
1750
/* This can be called from any thread - frees worker. Note that
1751
 * callbacks might still happen if called from another thread than the
1752
 * worker - use your own synchronization primitive in the callbacks.
1753
 *
1754
 * write_lock is not held on entry
1755
 * output_pending may be anything
1756
 */
1757
void
1758
_g_dbus_worker_stop (GDBusWorker *worker)
1759
0
{
1760
0
  g_atomic_int_set (&worker->stopped, TRUE);
1761
1762
  /* Cancel any pending operations and schedule a close of the underlying I/O
1763
   * stream in the worker thread
1764
   */
1765
0
  _g_dbus_worker_close (worker, NULL);
1766
1767
  /* _g_dbus_worker_close holds a ref until after an idle in the worker
1768
   * thread has run, so we no longer need to unref in an idle like in
1769
   * commit 322e25b535
1770
   */
1771
0
  _g_dbus_worker_unref (worker);
1772
0
}
1773
1774
/* ---------------------------------------------------------------------------------------------------- */
1775
1776
/* can be called from any thread (except the worker thread) - blocks
1777
 * calling thread until all queued outgoing messages are written and
1778
 * the transport has been flushed
1779
 *
1780
 * write_lock is not held on entry
1781
 * output_pending may be anything
1782
 */
1783
gboolean
1784
_g_dbus_worker_flush_sync (GDBusWorker    *worker,
1785
                           GCancellable   *cancellable,
1786
                           GError        **error)
1787
0
{
1788
0
  gboolean ret;
1789
0
  FlushData *data;
1790
0
  guint64 pending_writes;
1791
1792
0
  data = NULL;
1793
0
  ret = TRUE;
1794
1795
0
  g_mutex_lock (&worker->write_lock);
1796
1797
  /* if the queue is empty, no write is in-flight and we haven't written
1798
   * anything since the last flush, then there's nothing to wait for
1799
   */
1800
0
  pending_writes = g_queue_get_length (worker->write_queue);
1801
1802
  /* if a write is in-flight, we shouldn't be satisfied until the first
1803
   * flush operation that follows it
1804
   */
1805
0
  if (worker->output_pending == PENDING_WRITE)
1806
0
    pending_writes += 1;
1807
1808
0
  if (pending_writes > 0 ||
1809
0
      worker->write_num_messages_written != worker->write_num_messages_flushed)
1810
0
    {
1811
0
      data = g_new0 (FlushData, 1);
1812
0
      g_mutex_init (&data->mutex);
1813
0
      g_cond_init (&data->cond);
1814
0
      data->number_to_wait_for = worker->write_num_messages_written + pending_writes;
1815
0
      data->finished = FALSE;
1816
0
      g_mutex_lock (&data->mutex);
1817
1818
0
      schedule_writing_unlocked (worker, NULL, data, NULL);
1819
0
    }
1820
0
  g_mutex_unlock (&worker->write_lock);
1821
1822
0
  if (data != NULL)
1823
0
    {
1824
      /* Wait for flush operations to finish. */
1825
0
      while (!data->finished)
1826
0
        {
1827
0
          g_cond_wait (&data->cond, &data->mutex);
1828
0
        }
1829
1830
0
      g_mutex_unlock (&data->mutex);
1831
0
      g_cond_clear (&data->cond);
1832
0
      g_mutex_clear (&data->mutex);
1833
0
      if (data->error != NULL)
1834
0
        {
1835
0
          ret = FALSE;
1836
0
          g_propagate_error (error, data->error);
1837
0
        }
1838
0
      g_free (data);
1839
0
    }
1840
1841
0
  return ret;
1842
0
}
1843
1844
/* ---------------------------------------------------------------------------------------------------- */
1845
1846
0
#define G_DBUS_DEBUG_AUTHENTICATION (1<<0)
1847
0
#define G_DBUS_DEBUG_TRANSPORT      (1<<1)
1848
0
#define G_DBUS_DEBUG_MESSAGE        (1<<2)
1849
0
#define G_DBUS_DEBUG_PAYLOAD        (1<<3)
1850
0
#define G_DBUS_DEBUG_CALL           (1<<4)
1851
0
#define G_DBUS_DEBUG_SIGNAL         (1<<5)
1852
0
#define G_DBUS_DEBUG_INCOMING       (1<<6)
1853
0
#define G_DBUS_DEBUG_RETURN         (1<<7)
1854
0
#define G_DBUS_DEBUG_EMISSION       (1<<8)
1855
0
#define G_DBUS_DEBUG_ADDRESS        (1<<9)
1856
0
#define G_DBUS_DEBUG_PROXY          (1<<10)
1857
1858
static gint _gdbus_debug_flags = 0;
1859
1860
gboolean
1861
_g_dbus_debug_authentication (void)
1862
0
{
1863
0
  _g_dbus_initialize ();
1864
0
  return (_gdbus_debug_flags & G_DBUS_DEBUG_AUTHENTICATION) != 0;
1865
0
}
1866
1867
gboolean
1868
_g_dbus_debug_transport (void)
1869
0
{
1870
0
  _g_dbus_initialize ();
1871
0
  return (_gdbus_debug_flags & G_DBUS_DEBUG_TRANSPORT) != 0;
1872
0
}
1873
1874
gboolean
1875
_g_dbus_debug_message (void)
1876
0
{
1877
0
  _g_dbus_initialize ();
1878
0
  return (_gdbus_debug_flags & G_DBUS_DEBUG_MESSAGE) != 0;
1879
0
}
1880
1881
gboolean
1882
_g_dbus_debug_payload (void)
1883
0
{
1884
0
  _g_dbus_initialize ();
1885
0
  return (_gdbus_debug_flags & G_DBUS_DEBUG_PAYLOAD) != 0;
1886
0
}
1887
1888
gboolean
1889
_g_dbus_debug_call (void)
1890
0
{
1891
0
  _g_dbus_initialize ();
1892
0
  return (_gdbus_debug_flags & G_DBUS_DEBUG_CALL) != 0;
1893
0
}
1894
1895
gboolean
1896
_g_dbus_debug_signal (void)
1897
0
{
1898
0
  _g_dbus_initialize ();
1899
0
  return (_gdbus_debug_flags & G_DBUS_DEBUG_SIGNAL) != 0;
1900
0
}
1901
1902
gboolean
1903
_g_dbus_debug_incoming (void)
1904
0
{
1905
0
  _g_dbus_initialize ();
1906
0
  return (_gdbus_debug_flags & G_DBUS_DEBUG_INCOMING) != 0;
1907
0
}
1908
1909
gboolean
1910
_g_dbus_debug_return (void)
1911
0
{
1912
0
  _g_dbus_initialize ();
1913
0
  return (_gdbus_debug_flags & G_DBUS_DEBUG_RETURN) != 0;
1914
0
}
1915
1916
gboolean
1917
_g_dbus_debug_emission (void)
1918
0
{
1919
0
  _g_dbus_initialize ();
1920
0
  return (_gdbus_debug_flags & G_DBUS_DEBUG_EMISSION) != 0;
1921
0
}
1922
1923
gboolean
1924
_g_dbus_debug_address (void)
1925
0
{
1926
0
  _g_dbus_initialize ();
1927
0
  return (_gdbus_debug_flags & G_DBUS_DEBUG_ADDRESS) != 0;
1928
0
}
1929
1930
gboolean
1931
_g_dbus_debug_proxy (void)
1932
0
{
1933
0
  _g_dbus_initialize ();
1934
0
  return (_gdbus_debug_flags & G_DBUS_DEBUG_PROXY) != 0;
1935
0
}
1936
1937
G_LOCK_DEFINE_STATIC (print_lock);
1938
1939
void
1940
_g_dbus_debug_print_lock (void)
1941
0
{
1942
0
  G_LOCK (print_lock);
1943
0
}
1944
1945
void
1946
_g_dbus_debug_print_unlock (void)
1947
0
{
1948
0
  G_UNLOCK (print_lock);
1949
0
}
1950
1951
/**
1952
 * _g_dbus_initialize:
1953
 *
1954
 * Does various one-time init things such as
1955
 *
1956
 *  - registering the G_DBUS_ERROR error domain
1957
 *  - parses the G_DBUS_DEBUG environment variable
1958
 */
1959
void
1960
_g_dbus_initialize (void)
1961
0
{
1962
0
  static gsize initialized = 0;
1963
1964
0
  if (g_once_init_enter (&initialized))
1965
0
    {
1966
0
      const gchar *debug;
1967
1968
      /* Ensure the domain is registered. */
1969
0
      g_dbus_error_quark ();
1970
1971
0
      debug = g_getenv ("G_DBUS_DEBUG");
1972
0
      if (debug != NULL)
1973
0
        {
1974
0
          const GDebugKey keys[] = {
1975
0
            { "authentication", G_DBUS_DEBUG_AUTHENTICATION },
1976
0
            { "transport",      G_DBUS_DEBUG_TRANSPORT      },
1977
0
            { "message",        G_DBUS_DEBUG_MESSAGE        },
1978
0
            { "payload",        G_DBUS_DEBUG_PAYLOAD        },
1979
0
            { "call",           G_DBUS_DEBUG_CALL           },
1980
0
            { "signal",         G_DBUS_DEBUG_SIGNAL         },
1981
0
            { "incoming",       G_DBUS_DEBUG_INCOMING       },
1982
0
            { "return",         G_DBUS_DEBUG_RETURN         },
1983
0
            { "emission",       G_DBUS_DEBUG_EMISSION       },
1984
0
            { "address",        G_DBUS_DEBUG_ADDRESS        },
1985
0
            { "proxy",          G_DBUS_DEBUG_PROXY          }
1986
0
          };
1987
1988
0
          _gdbus_debug_flags = g_parse_debug_string (debug, keys, G_N_ELEMENTS (keys));
1989
0
          if (_gdbus_debug_flags & G_DBUS_DEBUG_PAYLOAD)
1990
0
            _gdbus_debug_flags |= G_DBUS_DEBUG_MESSAGE;
1991
0
        }
1992
1993
      /* Work-around for https://bugzilla.gnome.org/show_bug.cgi?id=627724 */
1994
0
      ensure_required_types ();
1995
1996
0
      g_once_init_leave (&initialized, 1);
1997
0
    }
1998
0
}
1999
2000
/* ---------------------------------------------------------------------------------------------------- */
2001
2002
GVariantType *
2003
_g_dbus_compute_complete_signature (GDBusArgInfo **args)
2004
0
{
2005
0
  const GVariantType *arg_types[256];
2006
0
  guint n;
2007
2008
0
  if (args)
2009
0
    for (n = 0; args[n] != NULL; n++)
2010
0
      {
2011
        /* DBus places a hard limit of 255 on signature length.
2012
         * therefore number of args must be less than 256.
2013
         */
2014
0
        g_assert (n < 256);
2015
2016
0
        arg_types[n] = G_VARIANT_TYPE (args[n]->signature);
2017
2018
0
        if G_UNLIKELY (arg_types[n] == NULL)
2019
0
          return NULL;
2020
0
      }
2021
0
  else
2022
0
    n = 0;
2023
2024
0
  return g_variant_type_new_tuple (arg_types, n);
2025
0
}
2026
2027
/* ---------------------------------------------------------------------------------------------------- */
2028
2029
#ifdef G_OS_WIN32
2030
2031
#define DBUS_DAEMON_ADDRESS_INFO L"DBusDaemonAddressInfo"
2032
#define DBUS_DAEMON_MUTEX L"DBusDaemonMutex"
2033
#define UNIQUE_DBUS_INIT_MUTEX L"UniqueDBusInitMutex"
2034
#define DBUS_AUTOLAUNCH_MUTEX L"DBusAutolaunchMutex"
2035
2036
static void
2037
release_mutex (HANDLE mutex)
2038
{
2039
  ReleaseMutex (mutex);
2040
  CloseHandle (mutex);
2041
}
2042
2043
static HANDLE
2044
acquire_mutex (const wchar_t *mutexname)
2045
{
2046
  HANDLE mutex;
2047
  DWORD res;
2048
2049
  mutex = CreateMutex (NULL, FALSE, mutexname);
2050
  if (!mutex)
2051
    return 0;
2052
2053
  res = WaitForSingleObject (mutex, INFINITE);
2054
  switch (res)
2055
    {
2056
    case WAIT_ABANDONED:
2057
      release_mutex (mutex);
2058
      return 0;
2059
    case WAIT_FAILED:
2060
    case WAIT_TIMEOUT:
2061
      return 0;
2062
    }
2063
2064
  return mutex;
2065
}
2066
2067
static gboolean
2068
is_mutex_owned (const wchar_t *mutexname)
2069
{
2070
  HANDLE mutex;
2071
  gboolean res = FALSE;
2072
2073
  mutex = CreateMutex (NULL, FALSE, mutexname);
2074
  if (WaitForSingleObject (mutex, 10) == WAIT_TIMEOUT)
2075
    res = TRUE;
2076
  else
2077
    ReleaseMutex (mutex);
2078
  CloseHandle (mutex);
2079
2080
  return res;
2081
}
2082
2083
static char *
2084
read_shm (const wchar_t *shm_name)
2085
{
2086
  HANDLE shared_mem;
2087
  char *shared_data;
2088
  char *res;
2089
  int i;
2090
2091
  res = NULL;
2092
2093
  for (i = 0; i < 20; i++)
2094
    {
2095
      shared_mem = OpenFileMapping (FILE_MAP_READ, FALSE, shm_name);
2096
      if (shared_mem != 0)
2097
  break;
2098
      Sleep (100);
2099
    }
2100
2101
  if (shared_mem != 0)
2102
    {
2103
      shared_data = MapViewOfFile (shared_mem, FILE_MAP_READ, 0, 0, 0);
2104
      /* It looks that a race is possible here:
2105
       * if the dbus process already created mapping but didn't fill it
2106
       * the code below may read incorrect address.
2107
       * Also this is a bit complicated by the fact that
2108
       * any change in the "synchronization contract" between processes
2109
       * should be accompanied with renaming all of used win32 named objects:
2110
       * otherwise libgio-2.0-0.dll of different versions shipped with
2111
       * different apps may break each other due to protocol difference.
2112
       */
2113
      if (shared_data != NULL)
2114
  {
2115
    res = g_strdup (shared_data);
2116
    UnmapViewOfFile (shared_data);
2117
  }
2118
      CloseHandle (shared_mem);
2119
    }
2120
2121
  return res;
2122
}
2123
2124
static HANDLE
2125
set_shm (const wchar_t *shm_name, const char *value)
2126
{
2127
  HANDLE shared_mem;
2128
  char *shared_data;
2129
2130
  shared_mem = CreateFileMapping (INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
2131
                                  0, strlen (value) + 1, shm_name);
2132
  if (shared_mem == 0)
2133
    return 0;
2134
2135
  shared_data = MapViewOfFile (shared_mem, FILE_MAP_WRITE, 0, 0, 0 );
2136
  if (shared_data == NULL)
2137
    return 0;
2138
2139
  strcpy (shared_data, value);
2140
2141
  UnmapViewOfFile (shared_data);
2142
2143
  return shared_mem;
2144
}
2145
2146
/* These keep state between publish_session_bus and unpublish_session_bus */
2147
static HANDLE published_daemon_mutex;
2148
static HANDLE published_shared_mem;
2149
2150
static gboolean
2151
publish_session_bus (const char *address)
2152
{
2153
  HANDLE init_mutex;
2154
2155
  init_mutex = acquire_mutex (UNIQUE_DBUS_INIT_MUTEX);
2156
2157
  published_daemon_mutex = CreateMutex (NULL, FALSE, DBUS_DAEMON_MUTEX);
2158
  if (WaitForSingleObject (published_daemon_mutex, 10 ) != WAIT_OBJECT_0)
2159
    {
2160
      release_mutex (init_mutex);
2161
      CloseHandle (published_daemon_mutex);
2162
      published_daemon_mutex = NULL;
2163
      return FALSE;
2164
    }
2165
2166
  published_shared_mem = set_shm (DBUS_DAEMON_ADDRESS_INFO, address);
2167
  if (!published_shared_mem)
2168
    {
2169
      release_mutex (init_mutex);
2170
      CloseHandle (published_daemon_mutex);
2171
      published_daemon_mutex = NULL;
2172
      return FALSE;
2173
    }
2174
2175
  release_mutex (init_mutex);
2176
  return TRUE;
2177
}
2178
2179
static void
2180
unpublish_session_bus (void)
2181
{
2182
  HANDLE init_mutex;
2183
2184
  init_mutex = acquire_mutex (UNIQUE_DBUS_INIT_MUTEX);
2185
2186
  CloseHandle (published_shared_mem);
2187
  published_shared_mem = NULL;
2188
2189
  release_mutex (published_daemon_mutex);
2190
  published_daemon_mutex = NULL;
2191
2192
  release_mutex (init_mutex);
2193
}
2194
2195
static void
2196
wait_console_window (void)
2197
{
2198
  FILE *console = g_fopen ("CONOUT$", "we");
2199
2200
  SetConsoleTitleW (L"gdbus-daemon output. Type any character to close this window.");
2201
  fprintf (console, _("(Type any character to close this window)\n"));
2202
  fflush (console);
2203
  _getch ();
2204
}
2205
2206
static void
2207
open_console_window (void)
2208
{
2209
  if (((HANDLE) _get_osfhandle (fileno (stdout)) == INVALID_HANDLE_VALUE ||
2210
       (HANDLE) _get_osfhandle (fileno (stderr)) == INVALID_HANDLE_VALUE) && AllocConsole ())
2211
    {
2212
      if ((HANDLE) _get_osfhandle (fileno (stdout)) == INVALID_HANDLE_VALUE)
2213
        freopen ("CONOUT$", "w", stdout);
2214
2215
      if ((HANDLE) _get_osfhandle (fileno (stderr)) == INVALID_HANDLE_VALUE)
2216
        freopen ("CONOUT$", "w", stderr);
2217
2218
      SetConsoleTitleW (L"gdbus-daemon debug output.");
2219
2220
      atexit (wait_console_window);
2221
    }
2222
}
2223
2224
static void
2225
idle_timeout_cb (GDBusDaemon *daemon, gpointer user_data)
2226
{
2227
  GMainLoop *loop = user_data;
2228
  g_main_loop_quit (loop);
2229
}
2230
2231
/* Satisfies STARTF_FORCEONFEEDBACK */
2232
static void
2233
turn_off_the_starting_cursor (void)
2234
{
2235
  MSG msg;
2236
  BOOL bRet;
2237
2238
  PostQuitMessage (0);
2239
2240
  while ((bRet = GetMessage (&msg, 0, 0, 0)) != 0)
2241
    {
2242
      if (bRet == -1)
2243
        continue;
2244
2245
      TranslateMessage (&msg);
2246
      DispatchMessage (&msg);
2247
    }
2248
}
2249
2250
void __stdcall
2251
g_win32_run_session_bus (void* hwnd, void* hinst, const char* cmdline, int cmdshow)
2252
{
2253
  GDBusDaemon *daemon;
2254
  GMainLoop *loop;
2255
  const char *address;
2256
  GError *error = NULL;
2257
2258
  turn_off_the_starting_cursor ();
2259
2260
  if (g_getenv ("GDBUS_DAEMON_DEBUG") != NULL)
2261
    open_console_window ();
2262
2263
  address = "nonce-tcp:";
2264
  daemon = _g_dbus_daemon_new (address, NULL, &error);
2265
  if (daemon == NULL)
2266
    {
2267
      g_printerr ("Can't init bus: %s\n", error->message);
2268
      g_error_free (error);
2269
      return;
2270
    }
2271
2272
  loop = g_main_loop_new (NULL, FALSE);
2273
2274
  /* There is a subtle detail with "idle-timeout" signal of dbus daemon:
2275
   * It is fired on idle after last client disconnection,
2276
   * but (at least with glib 2.59.1) it is NEVER fired
2277
   * if no clients connect to daemon at all.
2278
   * This may lead to infinite run of this daemon process.
2279
   */
2280
  g_signal_connect (daemon, "idle-timeout", G_CALLBACK (idle_timeout_cb), loop);
2281
2282
  if (publish_session_bus (_g_dbus_daemon_get_address (daemon)))
2283
    {
2284
      g_main_loop_run (loop);
2285
2286
      unpublish_session_bus ();
2287
    }
2288
2289
  g_main_loop_unref (loop);
2290
  g_object_unref (daemon);
2291
}
2292
2293
static gboolean autolaunch_binary_absent = FALSE;
2294
2295
static wchar_t *
2296
find_dbus_process_path (void)
2297
{
2298
  wchar_t *dbus_path;
2299
  gchar *exe_path = GLIB_PRIVATE_CALL (g_win32_find_helper_executable_path) ("gdbus.exe", _g_io_win32_get_module ());
2300
  dbus_path = g_utf8_to_utf16 (exe_path, -1, NULL, NULL, NULL);
2301
  g_free (exe_path);
2302
2303
  if (dbus_path == NULL)
2304
    return NULL;
2305
2306
  if (GetFileAttributesW (dbus_path) == INVALID_FILE_ATTRIBUTES)
2307
    {
2308
      g_free (dbus_path);
2309
      return NULL;
2310
    }
2311
2312
  return dbus_path;
2313
}
2314
2315
gchar *
2316
_g_dbus_win32_get_session_address_dbus_launch (GError **error)
2317
{
2318
  HANDLE autolaunch_mutex, init_mutex;
2319
  char *address = NULL;
2320
2321
  autolaunch_mutex = acquire_mutex (DBUS_AUTOLAUNCH_MUTEX);
2322
2323
  init_mutex = acquire_mutex (UNIQUE_DBUS_INIT_MUTEX);
2324
2325
  if (is_mutex_owned (DBUS_DAEMON_MUTEX))
2326
    address = read_shm (DBUS_DAEMON_ADDRESS_INFO);
2327
2328
  release_mutex (init_mutex);
2329
2330
  if (address == NULL && !autolaunch_binary_absent)
2331
    {
2332
      wchar_t *dbus_path = find_dbus_process_path ();
2333
      if (dbus_path == NULL)
2334
        {
2335
          /* warning won't be raised another time
2336
           * since autolaunch_binary_absent would be already set.
2337
           */
2338
          autolaunch_binary_absent = TRUE;
2339
          g_warning ("win32 session dbus binary not found");
2340
        }
2341
      else
2342
        {
2343
          PROCESS_INFORMATION pi = { 0 };
2344
          STARTUPINFOW si = { 0 };
2345
          BOOL res = FALSE;
2346
          wchar_t args[MAX_PATH * 2 + 100] = { 0 };
2347
          wchar_t working_dir[MAX_PATH + 2] = { 0 };
2348
          wchar_t *p;
2349
2350
          wcscpy (working_dir, dbus_path);
2351
          p = wcsrchr (working_dir, L'\\');
2352
          if (p != NULL)
2353
            *p = L'\0';
2354
2355
          wcscpy (args, L"\"");
2356
          wcscat (args, dbus_path);
2357
          wcscat (args, L"\" ");
2358
#define _L_PREFIX_FOR_EXPANDED(arg) L##arg
2359
#define _L_PREFIX(arg) _L_PREFIX_FOR_EXPANDED (arg)
2360
          wcscat (args, _L_PREFIX (_GDBUS_ARG_WIN32_RUN_SESSION_BUS));
2361
#undef _L_PREFIX
2362
#undef _L_PREFIX_FOR_EXPANDED
2363
2364
          res = CreateProcessW (dbus_path, args,
2365
                                0, 0, FALSE,
2366
                                NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW | DETACHED_PROCESS,
2367
                                0, working_dir,
2368
                                &si, &pi);
2369
2370
          if (res)
2371
            {
2372
              address = read_shm (DBUS_DAEMON_ADDRESS_INFO);
2373
              if (address == NULL)
2374
                g_warning ("%S dbus binary failed to launch bus, maybe incompatible version", dbus_path);
2375
            }
2376
2377
          g_free (dbus_path);
2378
        }
2379
    }
2380
2381
  release_mutex (autolaunch_mutex);
2382
2383
  if (address == NULL)
2384
    g_set_error (error,
2385
     G_IO_ERROR,
2386
     G_IO_ERROR_FAILED,
2387
     _("Session dbus not running, and autolaunch failed"));
2388
2389
  return address;
2390
}
2391
2392
#endif
2393
2394
/* ---------------------------------------------------------------------------------------------------- */
2395
2396
gchar *
2397
_g_dbus_get_machine_id (GError **error)
2398
0
{
2399
#ifdef G_OS_WIN32
2400
  HW_PROFILE_INFO info;
2401
  char *guid, *src, *dest, *res;
2402
  int i;
2403
2404
  if (!GetCurrentHwProfile (&info))
2405
    {
2406
      char *message = g_win32_error_message (GetLastError ());
2407
      g_set_error (error,
2408
       G_IO_ERROR,
2409
       G_IO_ERROR_FAILED,
2410
       _("Unable to get Hardware profile: %s"), message);
2411
      g_free (message);
2412
      return NULL;
2413
    }
2414
2415
  if (!(guid = g_utf16_to_utf8 (info.szHwProfileGuid, -1, NULL, NULL, NULL)))
2416
    return NULL;
2417
2418
  /* Guid is of the form: {12340001-4980-1920-6788-123456789012} */
2419
  src = guid;
2420
2421
  res = g_malloc (32+1);
2422
  dest = res;
2423
2424
  src++; /* Skip { */
2425
  for (i = 0; i < 8; i++)
2426
    *dest++ = *src++;
2427
  src++; /* Skip - */
2428
  for (i = 0; i < 4; i++)
2429
    *dest++ = *src++;
2430
  src++; /* Skip - */
2431
  for (i = 0; i < 4; i++)
2432
    *dest++ = *src++;
2433
  src++; /* Skip - */
2434
  for (i = 0; i < 4; i++)
2435
    *dest++ = *src++;
2436
  src++; /* Skip - */
2437
  for (i = 0; i < 12; i++)
2438
    *dest++ = *src++;
2439
  *dest = 0;
2440
2441
  g_free (guid);
2442
2443
  return res;
2444
#else
2445
0
  gchar *ret = NULL;
2446
0
  GError *first_error = NULL;
2447
0
  gsize i;
2448
0
  gboolean non_zero = FALSE;
2449
2450
  /* Copy what dbus.git does: allow the /var/lib path to be configurable at
2451
   * build time, but hard-code the system-wide machine ID path in /etc. */
2452
0
  const gchar *var_lib_path = LOCALSTATEDIR "/lib/dbus/machine-id";
2453
0
  const gchar *etc_path = "/etc/machine-id";
2454
2455
0
  if (!g_file_get_contents (var_lib_path,
2456
0
                            &ret,
2457
0
                            NULL,
2458
0
                            &first_error) &&
2459
0
      !g_file_get_contents (etc_path,
2460
0
                            &ret,
2461
0
                            NULL,
2462
0
                            NULL))
2463
0
    {
2464
0
      g_propagate_prefixed_error (error, g_steal_pointer (&first_error),
2465
                                  /* Translators: Both placeholders are file paths */
2466
0
                                  _("Unable to load %s or %s: "),
2467
0
                                  var_lib_path, etc_path);
2468
0
      return NULL;
2469
0
    }
2470
2471
  /* ignore the error from the first try, if any */
2472
0
  g_clear_error (&first_error);
2473
2474
  /* Validate the machine ID. From `man 5 machine-id`:
2475
   * > The machine ID is a single newline-terminated, hexadecimal, 32-character,
2476
   * > lowercase ID. When decoded from hexadecimal, this corresponds to a
2477
   * > 16-byte/128-bit value. This ID may not be all zeros.
2478
   */
2479
0
  for (i = 0; ret[i] != '\0' && ret[i] != '\n'; i++)
2480
0
    {
2481
      /* Break early if it’s invalid. */
2482
0
      if (!g_ascii_isxdigit (ret[i]) || g_ascii_isupper (ret[i]))
2483
0
        break;
2484
2485
0
      if (ret[i] != '0')
2486
0
        non_zero = TRUE;
2487
0
    }
2488
2489
0
  if (i != 32 || ret[i] != '\n' || ret[i + 1] != '\0' || !non_zero)
2490
0
    {
2491
0
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
2492
0
                   "Invalid machine ID in %s or %s",
2493
0
                   var_lib_path, etc_path);
2494
0
      g_free (ret);
2495
0
      return NULL;
2496
0
    }
2497
2498
  /* Strip trailing newline. */
2499
0
  ret[32] = '\0';
2500
2501
0
  return g_steal_pointer (&ret);
2502
0
#endif
2503
0
}
2504
2505
/* ---------------------------------------------------------------------------------------------------- */
2506
2507
gchar *
2508
_g_dbus_enum_to_string (GType enum_type, gint value)
2509
0
{
2510
0
  gchar *ret;
2511
0
  GEnumClass *klass;
2512
0
  GEnumValue *enum_value;
2513
2514
0
  klass = g_type_class_ref (enum_type);
2515
0
  enum_value = g_enum_get_value (klass, value);
2516
0
  if (enum_value != NULL)
2517
0
    ret = g_strdup (enum_value->value_nick);
2518
0
  else
2519
0
    ret = g_strdup_printf ("unknown (value %d)", value);
2520
0
  g_type_class_unref (klass);
2521
0
  return ret;
2522
0
}
2523
2524
/* ---------------------------------------------------------------------------------------------------- */
2525
2526
static void
2527
write_message_print_transport_debug (gssize bytes_written,
2528
                                     MessageToWriteData *data)
2529
0
{
2530
0
  if (G_LIKELY (!_g_dbus_debug_transport ()))
2531
0
    goto out;
2532
2533
0
  _g_dbus_debug_print_lock ();
2534
0
  g_print ("========================================================================\n"
2535
0
           "GDBus-debug:Transport:\n"
2536
0
           "  >>>> WROTE %" G_GSSIZE_FORMAT " bytes of message with serial %d and\n"
2537
0
           "       size %" G_GSIZE_FORMAT " from offset %" G_GSIZE_FORMAT " on a %s\n",
2538
0
           bytes_written,
2539
0
           g_dbus_message_get_serial (data->message),
2540
0
           data->blob_size,
2541
0
           data->total_written,
2542
0
           g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_output_stream (data->worker->stream))));
2543
0
  _g_dbus_debug_print_unlock ();
2544
0
 out:
2545
0
  ;
2546
0
}
2547
2548
/* ---------------------------------------------------------------------------------------------------- */
2549
2550
static void
2551
read_message_print_transport_debug (gssize bytes_read,
2552
                                    GDBusWorker *worker)
2553
0
{
2554
0
  gsize size;
2555
0
  gint32 serial;
2556
0
  gint32 message_length;
2557
2558
0
  if (G_LIKELY (!_g_dbus_debug_transport ()))
2559
0
    goto out;
2560
2561
0
  size = bytes_read + worker->read_buffer_cur_size;
2562
0
  serial = 0;
2563
0
  message_length = 0;
2564
0
  if (size >= 16)
2565
0
    message_length = g_dbus_message_bytes_needed ((guchar *) worker->read_buffer, size, NULL);
2566
0
  if (size >= 1)
2567
0
    {
2568
0
      switch (worker->read_buffer[0])
2569
0
        {
2570
0
        case 'l':
2571
0
          if (size >= 12)
2572
0
            serial = GUINT32_FROM_LE (((guint32 *) worker->read_buffer)[2]);
2573
0
          break;
2574
0
        case 'B':
2575
0
          if (size >= 12)
2576
0
            serial = GUINT32_FROM_BE (((guint32 *) worker->read_buffer)[2]);
2577
0
          break;
2578
0
        default:
2579
          /* an error will be set elsewhere if this happens */
2580
0
          goto out;
2581
0
        }
2582
0
    }
2583
2584
0
    _g_dbus_debug_print_lock ();
2585
0
  g_print ("========================================================================\n"
2586
0
           "GDBus-debug:Transport:\n"
2587
0
           "  <<<< READ %" G_GSSIZE_FORMAT " bytes of message with serial %d and\n"
2588
0
           "       size %d to offset %" G_GSIZE_FORMAT " from a %s\n",
2589
0
           bytes_read,
2590
0
           serial,
2591
0
           message_length,
2592
0
           worker->read_buffer_cur_size,
2593
0
           g_type_name (G_TYPE_FROM_INSTANCE (g_io_stream_get_input_stream (worker->stream))));
2594
0
  _g_dbus_debug_print_unlock ();
2595
0
 out:
2596
0
  ;
2597
0
}
2598
2599
/* ---------------------------------------------------------------------------------------------------- */
2600
2601
gboolean
2602
_g_signal_accumulator_false_handled (GSignalInvocationHint *ihint,
2603
                                     GValue                *return_accu,
2604
                                     const GValue          *handler_return,
2605
                                     gpointer               dummy)
2606
0
{
2607
0
  gboolean continue_emission;
2608
0
  gboolean signal_return;
2609
2610
0
  signal_return = g_value_get_boolean (handler_return);
2611
0
  g_value_set_boolean (return_accu, signal_return);
2612
0
  continue_emission = signal_return;
2613
2614
0
  return continue_emission;
2615
0
}
2616
2617
/* ---------------------------------------------------------------------------------------------------- */
2618
2619
static void
2620
append_nibble (GString *s, gint val)
2621
0
{
2622
0
  g_string_append_c (s, val >= 10 ? ('a' + val - 10) : ('0' + val));
2623
0
}
2624
2625
/* ---------------------------------------------------------------------------------------------------- */
2626
2627
gchar *
2628
_g_dbus_hexencode (const gchar *str,
2629
                   gsize        str_len)
2630
0
{
2631
0
  gsize n;
2632
0
  GString *s;
2633
2634
0
  s = g_string_new (NULL);
2635
0
  for (n = 0; n < str_len; n++)
2636
0
    {
2637
0
      gint val;
2638
0
      gint upper_nibble;
2639
0
      gint lower_nibble;
2640
2641
0
      val = ((const guchar *) str)[n];
2642
0
      upper_nibble = val >> 4;
2643
0
      lower_nibble = val & 0x0f;
2644
2645
0
      append_nibble (s, upper_nibble);
2646
0
      append_nibble (s, lower_nibble);
2647
0
    }
2648
2649
0
  return g_string_free (s, FALSE);
2650
0
}