meta-xwayland.c 40.8 KB
Newer Older
1
2
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */

3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*
 * X Wayland Support
 *
 * Copyright (C) 2013 Intel Corporation
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
 * 02111-1307, USA.
 */

24
25
#include "config.h"

Jonas Ådahl's avatar
Jonas Ådahl committed
26
27
#include "wayland/meta-xwayland.h"
#include "wayland/meta-xwayland-private.h"
28
29

#include <errno.h>
Jonas Ådahl's avatar
Jonas Ådahl committed
30
31
#include <glib-unix.h>
#include <glib.h>
32
#include <sys/socket.h>
33
34
#include <sys/stat.h>
#include <sys/types.h>
35
#include <sys/un.h>
36
#if defined(HAVE_SYS_RANDOM)
37
#include <sys/random.h>
38
39
40
#elif defined(HAVE_LINUX_RANDOM)
#include <linux/random.h>
#endif
41
#include <unistd.h>
42
#include <X11/extensions/Xrandr.h>
43
#include <X11/Xauth.h>
44
45
46
#include <X11/Xlib-xcb.h>

#include <xcb/res.h>
47

48
#include "backends/meta-monitor-manager-private.h"
49
#include "backends/meta-settings-private.h"
Jonas Ådahl's avatar
Jonas Ådahl committed
50
#include "meta/main.h"
51
#include "meta/meta-backend.h"
52
#include "meta/meta-x11-errors.h"
53
#include "wayland/meta-xwayland-surface.h"
54
#include "x11/meta-x11-display-private.h"
55

56
57
58
59
60
61
#ifdef HAVE_XWAYLAND_LISTENFD
#define XWAYLAND_LISTENFD "-listenfd"
#else
#define XWAYLAND_LISTENFD "-listen"
#endif

62
63
64
#define X11_TMP_UNIX_DIR     "/tmp/.X11-unix"
#define X11_TMP_UNIX_PATH    "/tmp/.X11-unix/X"

65
66
static int display_number_override = -1;

67
68
static void meta_xwayland_stop_xserver (MetaXWaylandManager *manager);

69
static void
70
meta_xwayland_set_primary_output (MetaX11Display *x11_display);
71

72
73
74
void
meta_xwayland_associate_window_with_surface (MetaWindow          *window,
                                             MetaWaylandSurface  *surface)
75
{
76
  MetaDisplay *display = window->display;
77
  MetaXwaylandSurface *xwayland_surface;
78

79
  if (!meta_wayland_surface_assign_role (surface,
80
                                         META_TYPE_XWAYLAND_SURFACE,
81
                                         NULL))
82
83
84
85
86
87
88
89
    {
      wl_resource_post_error (surface->resource,
                              WL_DISPLAY_ERROR_INVALID_OBJECT,
                              "wl_surface@%d already has a different role",
                              wl_resource_get_id (surface->resource));
      return;
    }

90
91
  xwayland_surface = META_XWAYLAND_SURFACE (surface->role);
  meta_xwayland_surface_associate_with_window (xwayland_surface, window);
Jasper St. Pierre's avatar
Jasper St. Pierre committed
92

93
94
  /* Now that we have a surface check if it should have focus. */
  meta_display_sync_wayland_input_focus (display);
95
96
}

97
98
99
100
static gboolean
associate_window_with_surface_id (MetaXWaylandManager *manager,
                                  MetaWindow          *window,
                                  guint32              surface_id)
101
{
102
103
104
105
106
107
  struct wl_resource *resource;

  resource = wl_client_get_object (manager->client, surface_id);
  if (resource)
    {
      MetaWaylandSurface *surface = wl_resource_get_user_data (resource);
108
      meta_xwayland_associate_window_with_surface (window, surface);
109
110
111
112
113
114
115
116
117
      return TRUE;
    }
  else
    return FALSE;
}

void
meta_xwayland_handle_wl_surface_id (MetaWindow *window,
                                    guint32     surface_id)
118
{
119
120
121
122
123
  MetaWaylandCompositor *compositor = meta_wayland_compositor_get_default ();
  MetaXWaylandManager *manager = &compositor->xwayland_manager;

  if (!associate_window_with_surface_id (manager, window, surface_id))
    {
124
125
      /* No surface ID yet, schedule this association for whenever the
       * surface is made known.
126
       */
127
128
      meta_wayland_compositor_schedule_surface_association (compositor,
                                                            surface_id, window);
129
    }
130
131
}

132
133
134
135
136
137
138
139
140
gboolean
meta_xwayland_is_xwayland_surface (MetaWaylandSurface *surface)
{
  MetaWaylandCompositor *compositor = meta_wayland_compositor_get_default ();
  MetaXWaylandManager *manager = &compositor->xwayland_manager;

  return wl_resource_get_client (surface->resource) == manager->client;
}

141
142
143
static char *
meta_xwayland_get_exe_from_proc_entry (const char *proc_entry)
{
144
  g_autofree char *exepath = NULL;
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
  char *executable;
  char *p;

  exepath = g_file_read_link (proc_entry, NULL);
  if (!exepath)
    return NULL;

  p = strrchr (exepath, G_DIR_SEPARATOR);
  if (p)
    executable = g_strdup (++p);
  else
    executable = g_strdup (exepath);

  return executable;
}

static char *
meta_xwayland_get_exe_from_pid (uint32_t pid)
{
164
  g_autofree char *proc_entry = NULL;
165
166
167
168
169
170
171
172
173
174
175
  char *executable;

  proc_entry = g_strdup_printf ("/proc/%i/exe", pid);
  executable = meta_xwayland_get_exe_from_proc_entry (proc_entry);

  return executable;
}

static char *
meta_xwayland_get_self_exe (void)
{
176
  g_autofree char *proc_entry = NULL;
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
  char *executable;

  proc_entry = g_strdup_printf ("/proc/self/exe");
  executable = meta_xwayland_get_exe_from_proc_entry (proc_entry);

  return executable;
}

static gboolean
can_xwayland_ignore_exe (const char *executable,
                         const char *self)
{
  char ** ignore_executables;
  gboolean ret;

  if (!g_strcmp0 (executable, self))
    return TRUE;

  ignore_executables = g_strsplit_set (XWAYLAND_IGNORE_EXECUTABLES, ",", -1);
  ret = g_strv_contains ((const char * const *) ignore_executables, executable);
  g_strfreev (ignore_executables);

  return ret;
}

static uint32_t
meta_xwayland_get_client_pid (xcb_connection_t *xcb,
                              uint32_t          client)
{
  xcb_res_client_id_spec_t spec = { 0 };
  xcb_res_query_client_ids_cookie_t cookie;
  xcb_res_query_client_ids_reply_t *reply = NULL;
  uint32_t pid = 0, *value;

  spec.client = client;
  spec.mask = XCB_RES_CLIENT_ID_MASK_LOCAL_CLIENT_PID;

  cookie = xcb_res_query_client_ids (xcb, 1, &spec);
  reply = xcb_res_query_client_ids_reply (xcb, cookie, NULL);

  if (reply == NULL)
    return 0;

  xcb_res_client_id_value_iterator_t it;
  for (it = xcb_res_query_client_ids_ids_iterator (reply);
       it.rem;
       xcb_res_client_id_value_next (&it))
    {
      spec = it.data->spec;
      if (spec.mask & XCB_RES_CLIENT_ID_MASK_LOCAL_CLIENT_PID)
        {
          value = xcb_res_client_id_value_value (it.data);
          pid = *value;
          break;
        }
    }
  free (reply);

  return pid;
}

static gboolean
can_terminate_xwayland (Display *xdisplay)
{
  xcb_connection_t *xcb = XGetXCBConnection (xdisplay);
  xcb_res_query_clients_cookie_t cookie;
  xcb_res_query_clients_reply_t *reply = NULL;
  xcb_res_client_iterator_t it;
  gboolean can_terminate;
  char *self;

  cookie = xcb_res_query_clients (xcb);
  reply = xcb_res_query_clients_reply (xcb, cookie, NULL);

  /* Could not get the list of X11 clients, better not terminate Xwayland */
  if (reply == NULL)
    return FALSE;

  can_terminate = TRUE;
  self = meta_xwayland_get_self_exe ();
  for (it = xcb_res_query_clients_clients_iterator (reply);
       it.rem && can_terminate;
       xcb_res_client_next (&it))
    {
      uint32_t pid;
      char *executable;

      pid = meta_xwayland_get_client_pid (xcb, it.data->resource_base);
      if (pid == 0)
        {
          /* Unknown PID, don't risk terminating it */
          can_terminate = FALSE;
          break;
        }

      executable = meta_xwayland_get_exe_from_pid (pid);
      can_terminate = can_xwayland_ignore_exe (executable, self);
      g_free (executable);
    }
  free (reply);

  return can_terminate;
}

281
static gboolean
282
283
284
285
try_display (int      display,
             char   **filename_out,
             int     *fd_out,
             GError **error)
286
{
287
  gboolean ret = FALSE;
288
289
290
  char *filename;
  int fd;

291
292
293
294
295
296
  filename = g_strdup_printf ("/tmp/.X%d-lock", display);

 again:
  fd = open (filename, O_WRONLY | O_CLOEXEC | O_CREAT | O_EXCL, 0444);

  if (fd < 0 && errno == EEXIST)
297
    {
298
      char pid[11];
299
300
      char *end;
      pid_t other;
301
      int read_bytes;
302

303
      fd = open (filename, O_CLOEXEC, O_RDONLY);
304
      if (fd < 0)
305
        {
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
          g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno),
                       "Failed to open lock file %s: %s",
                       filename, g_strerror (errno));
          goto out;
        }

      read_bytes = read (fd, pid, 11);
      if (read_bytes != 11)
        {
          if (read_bytes < 0)
            {
              g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno),
                           "Failed to read from lock file %s: %s",
                           filename, g_strerror (errno));
            }
          else
            {
              g_set_error (error, G_IO_ERROR, G_IO_ERROR_PARTIAL_INPUT,
                           "Only read %d bytes (needed 11) from lock file: %s",
                           read_bytes, filename);
            }
327
328
329
330
          goto out;
        }
      close (fd);
      fd = -1;
331

332
      pid[10] = '\0';
333
334
      other = strtol (pid, &end, 0);
      if (end != pid + 10)
335
        {
336
337
          g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_DATA,
                       "Can't parse lock file %s", filename);
338
339
          goto out;
        }
340

341
342
      if (kill (other, 0) < 0 && errno == ESRCH)
        {
343
          /* Process is dead. Try unlinking the lock file and trying again. */
344
345
          if (unlink (filename) < 0)
            {
346
347
348
              g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno),
                           "Failed to unlink stale lock file %s: %s",
                           filename, g_strerror (errno));
349
              goto out;
Jasper St. Pierre's avatar
Jasper St. Pierre committed
350
            }
351

352
353
          goto again;
        }
354

355
356
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                   "Lock file %s is already occupied", filename);
357
358
359
360
      goto out;
    }
  else if (fd < 0)
    {
361
362
363
      g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno),
                  "Failed to create lock file %s: %s",
                  filename, g_strerror (errno));
364
365
      goto out;
    }
366

367
  ret = TRUE;
368

369
370
371
372
373
374
375
 out:
  if (!ret)
    {
      g_free (filename);
      filename = NULL;

      if (fd >= 0)
376
        {
377
378
          close (fd);
          fd = -1;
379
        }
380
381
382
383
384
385
386
387
    }

  *filename_out = filename;
  *fd_out = fd;
  return ret;
}

static char *
388
389
390
create_lock_file (int      display,
                  int     *display_out,
                  GError **error)
391
392
393
{
  char *filename;
  int fd;
394
  char pid[12];
395
  int size;
396
  int number_of_tries = 0;
397
  g_autoptr (GError) local_error = NULL;
398

399
  while (!try_display (display, &filename, &fd, &local_error))
400
    {
401
402
      meta_topic (META_DEBUG_WAYLAND,
                  "Failed to lock X11 display: %s", local_error->message);
403
      g_clear_error (&local_error);
404
      display++;
405
      number_of_tries++;
406

407
      /* If we can't get a display after 50 times, then something's wrong. Just
408
       * abort in this case. */
409
      if (number_of_tries >= 50)
410
411
412
413
414
415
        {
          g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                       "Gave up after trying to lock different "
                       "X11 display lock file 50 times");
          return NULL;
        }
416
417
418
    }

  /* Subtle detail: we use the pid of the wayland compositor, not the xserver
419
420
421
422
   * in the lock file. Another subtlety: snprintf returns the number of bytes
   * it _would've_ written without either the NUL or the size clamping, hence
   * the disparity in size. */
  size = snprintf (pid, 12, "%10d\n", getpid ());
423
  errno = 0;
424
425
  if (size != 11 || write (fd, pid, 11) != 11)
    {
426
427
428
429
430
431
432
433
434
435
436
437
      if (errno != 0)
        {
          g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno),
                       "Failed to write pid to lock file %s: %s",
                       filename, g_strerror (errno));
        }
      else
        {
          g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                       "Failed to write pid to lock file %s", filename);
        }

438
439
440
441
442
443
444
445
446
447
448
449
      unlink (filename);
      close (fd);
      g_free (filename);
      return NULL;
    }

  close (fd);

  *display_out = display;
  return filename;
}

450
static int
451
452
bind_to_abstract_socket (int      display,
                         GError **error)
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
{
  struct sockaddr_un addr;
  socklen_t size, name_size;
  int fd;

  fd = socket (PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0);
  if (fd < 0)
    {
      g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno),
                   "Failed to create socket: %s", g_strerror (errno));
      return -1;
    }

  addr.sun_family = AF_LOCAL;
  name_size = snprintf (addr.sun_path, sizeof addr.sun_path,
468
                        "%c%s%d", 0, X11_TMP_UNIX_PATH, display);
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
  size = offsetof (struct sockaddr_un, sun_path) + name_size;
  if (bind (fd, (struct sockaddr *) &addr, size) < 0)
    {
      g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno),
                   "Failed to bind to %s: %s",
                   addr.sun_path + 1, g_strerror (errno));
      close (fd);
      return -1;
    }

  if (listen (fd, 1) < 0)
    {
      g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno),
                   "Failed to listen to %s: %s",
                   addr.sun_path + 1, g_strerror (errno));
      close (fd);
      return -1;
    }

  return fd;
}

491
static int
492
493
bind_to_unix_socket (int      display,
                     GError **error)
494
495
496
497
498
499
500
{
  struct sockaddr_un addr;
  socklen_t size, name_size;
  int fd;

  fd = socket (PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0);
  if (fd < 0)
501
502
503
504
505
    {
      g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno),
                   "Failed to create socket: %s", g_strerror (errno));
      return -1;
    }
506
507
508

  addr.sun_family = AF_LOCAL;
  name_size = snprintf (addr.sun_path, sizeof addr.sun_path,
509
                        "%s%d", X11_TMP_UNIX_PATH, display) + 1;
510
511
512
513
  size = offsetof (struct sockaddr_un, sun_path) + name_size;
  unlink (addr.sun_path);
  if (bind (fd, (struct sockaddr *) &addr, size) < 0)
    {
514
515
516
      g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno),
                   "Failed to bind to %s: %s",
                   addr.sun_path, g_strerror (errno));
517
518
519
520
      close (fd);
      return -1;
    }

Jasper St. Pierre's avatar
Jasper St. Pierre committed
521
522
  if (listen (fd, 1) < 0)
    {
523
524
525
      g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno),
                   "Failed to listen to %s: %s",
                   addr.sun_path, g_strerror (errno));
526
527
528
      unlink (addr.sun_path);
      close (fd);
      return -1;
Jasper St. Pierre's avatar
Jasper St. Pierre committed
529
    }
530
531
532
533

  return fd;
}

534
static void
535
536
537
xserver_died (GObject      *source,
              GAsyncResult *result,
              gpointer      user_data)
538
{
539
  MetaWaylandCompositor *compositor = meta_wayland_compositor_get_default ();
540
  GSubprocess *proc = G_SUBPROCESS (source);
541
  MetaDisplay *display = meta_get_display ();
542
  g_autoptr (GError) error = NULL;
543
  MetaX11DisplayPolicy x11_display_policy;
544

545
546
  x11_display_policy =
    meta_context_get_x11_display_policy (compositor->context);
547
548
  if (!g_subprocess_wait_finish (proc, result, &error))
    {
549
550
551
552
      if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
        return;

      g_warning ("Failed to finish waiting for Xwayland: %s", error->message);
553
554
    }
  else if (!g_subprocess_get_successful (proc))
555
    {
556
      if (x11_display_policy == META_X11_DISPLAY_POLICY_MANDATORY)
557
558
559
560
561
        g_warning ("X Wayland crashed; exiting");
      else
        g_warning ("X Wayland crashed; attempting to recover");
    }

562
  if (x11_display_policy == META_X11_DISPLAY_POLICY_MANDATORY)
563
564
    {
      meta_exit (META_EXIT_ERROR);
565
    }
566
  else if (x11_display_policy == META_X11_DISPLAY_POLICY_ON_DEMAND)
567
    {
568
      g_autoptr (GError) error = NULL;
569

570
571
572
573
      if (display->x11_display)
        meta_display_shutdown_x11 (display);

      if (!meta_xwayland_init (&compositor->xwayland_manager,
574
                               compositor,
575
576
577
                               compositor->wayland_display,
                               &error))
        g_warning ("Failed to init X sockets: %s", error->message);
578
579
580
    }
}

581
582
583
584
585
586
587
588
589
590
static void
meta_xwayland_terminate (MetaXWaylandManager *manager)
{
  MetaDisplay *display = meta_get_display ();

  g_clear_handle_id (&manager->xserver_grace_period_id, g_source_remove);
  meta_display_shutdown_x11 (display);
  meta_xwayland_stop_xserver (manager);
}

591
592
593
594
static gboolean
shutdown_xwayland_cb (gpointer data)
{
  MetaXWaylandManager *manager = data;
595
  MetaDisplay *display = meta_get_display ();
596
597
598
599
  MetaBackend *backend = meta_get_backend ();

  if (!meta_settings_is_experimental_feature_enabled (meta_backend_get_settings (backend),
                                                      META_EXPERIMENTAL_FEATURE_AUTOCLOSE_XWAYLAND))
600
601
602
603
    {
      manager->xserver_grace_period_id = 0;
      return G_SOURCE_REMOVE;
    }
604

605
606
  if (display->x11_display &&
      !can_terminate_xwayland (display->x11_display->xdisplay))
607
    return G_SOURCE_CONTINUE;
608
609
610

  meta_verbose ("Shutting down Xwayland");
  manager->xserver_grace_period_id = 0;
611
  meta_xwayland_terminate (manager);
612
  return G_SOURCE_REMOVE;
613
614
}

615
616
617
static int
x_io_error (Display *display)
{
618
619
620
  MetaWaylandCompositor *compositor = meta_wayland_compositor_get_default ();
  MetaX11DisplayPolicy x11_display_policy;

621
  g_warning ("Connection to xwayland lost");
622

623
624
625
  x11_display_policy =
    meta_context_get_x11_display_policy (compositor->context);
  if (x11_display_policy == META_X11_DISPLAY_POLICY_MANDATORY)
626
    meta_exit (META_EXIT_ERROR);
627
628
629
630

  return 0;
}

631
632
633
634
635
636
static int
x_io_error_noop (Display *display)
{
  return 0;
}

637
638
#ifdef HAVE_XSETIOERROREXITHANDLER
static void
639
640
x_io_error_exit (Display *display,
                 void    *data)
641
{
642
  MetaXWaylandManager *manager = data;
643
644
645
646
647

  g_warning ("Xwayland just died, attempting to recover");
  manager->xserver_grace_period_id =
    g_idle_add (shutdown_xwayland_cb, manager);
}
648
649
650
651
652
653

static void
x_io_error_exit_noop (Display *display,
                      void    *data)
{
}
654
655
#endif

656
657
658
659
660
661
void
meta_xwayland_override_display_number (int number)
{
  display_number_override = number;
}

662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
static gboolean
ensure_x11_unix_perms (GError **error)
{
  struct stat buf;

  if (lstat (X11_TMP_UNIX_DIR, &buf) != 0)
    {
      g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno),
                   "Failed to check permissions on directory \"%s\": %s",
                   X11_TMP_UNIX_DIR, g_strerror (errno));
      return FALSE;
    }

  /* If the directory already exists, it should belong to root or ourselves ... */
  if (buf.st_uid != 0 && buf.st_uid != getuid ())
    {
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_PERMISSION_DENIED,
                   "Wrong ownership for directory \"%s\"",
                   X11_TMP_UNIX_DIR);
      return FALSE;
    }

  /* ... be writable ... */
  if ((buf.st_mode & 0022) != 0022)
    {
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_PERMISSION_DENIED,
                   "Directory \"%s\" is not writable",
                   X11_TMP_UNIX_DIR);
      return FALSE;
    }

  /* ... and have the sticky bit set */
  if ((buf.st_mode & 01000) != 01000)
    {
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_PERMISSION_DENIED,
                   "Directory \"%s\" is missing the sticky bit",
                   X11_TMP_UNIX_DIR);
      return FALSE;
    }

  return TRUE;
}

705
706
707
static gboolean
ensure_x11_unix_dir (GError **error)
{
708
  if (mkdir (X11_TMP_UNIX_DIR, 01777) != 0)
709
710
    {
      if (errno == EEXIST)
711
        return ensure_x11_unix_perms (error);
712
713

      g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno),
714
715
                   "Failed to create directory \"%s\": %s",
                   X11_TMP_UNIX_DIR, g_strerror (errno));
716
717
718
719
720
721
      return FALSE;
    }

  return TRUE;
}

722
static gboolean
723
724
open_display_sockets (MetaXWaylandManager  *manager,
                      int                   display_index,
725
                      int                  *abstract_fd_out,
726
727
                      int                  *unix_fd_out,
                      GError              **error)
728
{
729
  int abstract_fd, unix_fd;
730

731
  abstract_fd = bind_to_abstract_socket (display_index, error);
732
733
734
  if (abstract_fd < 0)
    return FALSE;

735
  unix_fd = bind_to_unix_socket (display_index, error);
736
  if (unix_fd < 0)
737
738
739
740
    {
      close (abstract_fd);
      return FALSE;
    }
741

742
  *abstract_fd_out = abstract_fd;
743
  *unix_fd_out = unix_fd;
744
745
746
747

  return TRUE;
}

748
static gboolean
749
750
choose_xdisplay (MetaXWaylandManager     *manager,
                 MetaXWaylandConnection  *connection,
751
                 int                     *display,
752
                 GError                 **error)
753
{
754
  int number_of_tries = 0;
755
  char *lock_file = NULL;
756

757
758
759
  if (!ensure_x11_unix_dir (error))
    return FALSE;

760
761
  do
    {
762
763
      g_autoptr (GError) local_error = NULL;

764
      lock_file = create_lock_file (*display, display, &local_error);
765
      if (!lock_file)
766
        {
767
768
          g_prefix_error (&local_error, "Failed to create an X lock file: ");
          g_propagate_error (error, g_steal_pointer (&local_error));
Jasper St. Pierre's avatar
Jasper St. Pierre committed
769
          return FALSE;
770
771
        }

772
      if (!open_display_sockets (manager, *display,
773
                                 &connection->abstract_fd,
774
                                 &connection->unix_fd,
775
                                 &local_error))
776
        {
777
          unlink (lock_file);
778

779
          if (++number_of_tries >= 50)
780
            {
781
782
              g_prefix_error (&local_error, "Failed to bind X11 socket: ");
              g_propagate_error (error, g_steal_pointer (&local_error));
783
              g_free (lock_file);
784
785
              return FALSE;
            }
786

787
          (*display)++;
788
          continue;
789
790
791
792
793
794
        }

      break;
    }
  while (1);

795
  connection->display_index = *display;
796
797
  connection->name = g_strdup_printf (":%d", connection->display_index);
  connection->lock_file = lock_file;
798

799
800
801
  return TRUE;
}

802
803
804
G_DEFINE_AUTOPTR_CLEANUP_FUNC (FILE, fclose)

static gboolean
805
806
prepare_auth_file (MetaXWaylandManager  *manager,
                   GError              **error)
807
808
809
810
811
812
813
814
815
816
817
818
{
  Xauth auth_entry = { 0 };
  g_autoptr (FILE) fp = NULL;
  char auth_data[16];
  int fd;

  manager->auth_file = g_build_filename (g_get_user_runtime_dir (),
                                         ".mutter-Xwaylandauth.XXXXXX",
                                         NULL);

  if (getrandom (auth_data, sizeof (auth_data), 0) != sizeof (auth_data))
    {
819
820
      g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno),
                   "Failed to get random data: %s", g_strerror (errno));
821
822
823
824
      return FALSE;
    }

  auth_entry.family = FamilyLocal;
825
  auth_entry.address = (char *) g_get_host_name ();
826
827
828
829
830
831
832
833
834
  auth_entry.address_length = strlen (auth_entry.address);
  auth_entry.name = (char *) "MIT-MAGIC-COOKIE-1";
  auth_entry.name_length = strlen (auth_entry.name);
  auth_entry.data = auth_data;
  auth_entry.data_length = sizeof (auth_data);

  fd = g_mkstemp (manager->auth_file);
  if (fd < 0)
    {
835
836
      g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno),
                   "Failed to open Xauthority file: %s", g_strerror (errno));
837
838
839
840
841
842
      return FALSE;
    }

  fp = fdopen (fd, "w+");
  if (!fp)
    {
843
844
      g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno),
                   "Failed to open Xauthority stream: %s", g_strerror (errno));
845
846
847
848
849
850
      close (fd);
      return FALSE;
    }

  if (!XauWriteAuth (fp, &auth_entry))
    {
851
852
      g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno),
                   "Error writing to Xauthority file: %s", g_strerror (errno));
853
854
855
856
857
858
      return FALSE;
    }

  auth_entry.family = FamilyWild;
  if (!XauWriteAuth (fp, &auth_entry))
    {
859
860
      g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno),
                   "Error writing to Xauthority file: %s", g_strerror (errno));
861
862
863
864
865
      return FALSE;
    }

  if (fflush (fp) == EOF)
    {
866
867
      g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno),
                   "Error writing to Xauthority file: %s", g_strerror (errno));
868
869
870
871
872
873
      return FALSE;
    }

  return TRUE;
}

874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
static void
add_local_user_to_xhost (Display *xdisplay)
{
  XHostAddress host_entry;
  XServerInterpretedAddress siaddr;

  siaddr.type = (char *) "localuser";
  siaddr.typelength = strlen (siaddr.type);
  siaddr.value = (char *) g_get_user_name();
  siaddr.valuelength = strlen (siaddr.value);

  host_entry.family = FamilyServerInterpreted;
  host_entry.address = (char *) &siaddr;

  XAddHost (xdisplay, &host_entry);
}

891
892
893
894
895
896
897
898
static void
on_init_x11_cb (MetaDisplay  *display,
                GAsyncResult *result,
                gpointer      user_data)
{
  g_autoptr (GError) error = NULL;

  if (!meta_display_init_x11_finish (display, result, &error))
899
    g_warning ("Failed to initialize X11 display: %s", error->message);
900
901
}

902
static gboolean
903
904
905
on_displayfd_ready (int          fd,
                    GIOCondition condition,
                    gpointer     user_data)
906
{
907
  GTask *task = user_data;
908

909
910
911
912
  /* The server writes its display name to the displayfd
   * socket when it's ready. We don't care about the data
   * in the socket, just that it wrote something, since
   * that means it's ready. */
913
  g_task_return_boolean (task, !!(condition & G_IO_IN));
914
  g_object_unref (task);
915

916
917
918
  return G_SOURCE_REMOVE;
}

919
920
921
922
923
924
925
926
static int
steal_fd (int *fd_ptr)
{
  int fd = *fd_ptr;
  *fd_ptr = -1;
  return fd;
}

927
928
929
930
931
void
meta_xwayland_start_xserver (MetaXWaylandManager *manager,
                             GCancellable        *cancellable,
                             GAsyncReadyCallback  callback,
                             gpointer             user_data)
932
{
933
934
935
936
937
938
939
940
  struct {
    const char *extension_name;
    MetaXwaylandExtension disable_extension;
  } x11_extension_names[] = {
    { "SECURITY", META_XWAYLAND_EXTENSION_SECURITY },
    { "XTEST", META_XWAYLAND_EXTENSION_XTEST },
  };

941
  int xwayland_client_fd[2];
942
  int displayfd[2];
943
  g_autoptr(GSubprocessLauncher) launcher = NULL;
944
945
  GSubprocessFlags flags;
  GError *error = NULL;
946
  g_autoptr (GTask) task = NULL;
947
948
949
950
951
  MetaBackend *backend;
  MetaSettings *settings;
  const char *args[32];
  int xwayland_disable_extensions;
  int i, j;
952
953
954
955

  task = g_task_new (NULL, cancellable, callback, user_data);
  g_task_set_source_tag (task, meta_xwayland_start_xserver);
  g_task_set_task_data (task, manager, NULL);
956

957
958
  /* We want xwayland to be a wayland client so we make a socketpair to setup a
   * wayland protocol connection. */
959
  if (socketpair (AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, xwayland_client_fd) < 0)
960
    {
961
962
963
964
965
      g_task_return_new_error (task,
                               G_IO_ERROR,
                               g_io_error_from_errno (errno),
                               "xwayland_client_fd socketpair failed");
      return;
966
967
    }

968
969
  if (socketpair (AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, displayfd) < 0)
    {
970
971
972
      close (xwayland_client_fd[0]);
      close (xwayland_client_fd[1]);

973
974
975
976
977
      g_task_return_new_error (task,
                               G_IO_ERROR,
                               g_io_error_from_errno (errno),
                               "displayfd socketpair failed");
      return;
978
979
    }

980
981
  /* xwayland, please. */
  flags = G_SUBPROCESS_FLAGS_NONE;
982

983
984
985
986
  if (getenv ("XWAYLAND_STFU"))
    {
      flags |= G_SUBPROCESS_FLAGS_STDOUT_SILENCE;
      flags |= G_SUBPROCESS_FLAGS_STDERR_SILENCE;
987
    }
988

989
990
991
992
993
  backend = meta_get_backend ();
  settings = meta_backend_get_settings (backend);
  xwayland_disable_extensions =
    meta_settings_get_xwayland_disable_extensions (settings);

994
995
  launcher = g_subprocess_launcher_new (flags);

996
997
998
999
1000
1001
1002
1003
1004
1005
  g_subprocess_launcher_take_fd (launcher,
                                 steal_fd (&xwayland_client_fd[1]), 3);
  g_subprocess_launcher_take_fd (launcher,
                                 steal_fd (&manager->public_connection.abstract_fd), 4);
  g_subprocess_launcher_take_fd (launcher,
                                 steal_fd (&manager->public_connection.unix_fd), 5);
  g_subprocess_launcher_take_fd (launcher,
                                 steal_fd (&displayfd[1]), 6);
  g_subprocess_launcher_take_fd (launcher,
                                 steal_fd (&manager->private_connection.abstract_fd), 7);
1006
1007

  g_subprocess_launcher_setenv (launcher, "WAYLAND_SOCKET", "3", TRUE);
1008

1009
1010
1011
1012
1013
1014
1015
1016
1017
  i = 0;
  args[i++] = XWAYLAND_PATH;
  args[i++] = manager->public_connection.name;
  args[i++] = "-rootless";
  args[i++] = "-noreset";
  args[i++] = "-accessx";
  args[i++] = "-core";
  args[i++] = "-auth";
  args[i++] = manager->auth_file;
1018
  args[i++] = XWAYLAND_LISTENFD;
1019
  args[i++] = "4";
1020
  args[i++] = XWAYLAND_LISTENFD;
1021
  args[i++] = "5";
1022
1023
  args[i++] = "-displayfd";
  args[i++] = "6";
1024
#ifdef HAVE_XWAYLAND_INITFD
1025
  args[i++] = "-initfd";
1026
  args[i++] = "7";
1027
#else
1028
  args[i++] = XWAYLAND_LISTENFD;
1029
  args[i++] = "7";
1030
#endif
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
  for (j = 0; j <  G_N_ELEMENTS (x11_extension_names); j++)
    {
      /* Make sure we don't go past the array size - We need room for
       * 2 arguments, plus the last NULL terminator.
       */
      if (i + 3 > G_N_ELEMENTS (args))
        break;

      if (xwayland_disable_extensions & x11_extension_names[j].disable_extension)
        {
          args[i++] = "-extension";
          args[i++] = x11_extension_names[j].extension_name;
        }
  }
  /* Terminator */
  args[i++] = NULL;

  manager->proc = g_subprocess_launcher_spawnv (launcher, args, &error);
1049

1050
  if (!manager->proc)
1051
    {
1052
1053
1054
      close (displayfd[0]);
      close (xwayland_client_fd[0]);

1055
1056
      g_task_return_error (task, error);
      return;
1057
    }
1058

1059
1060
1061
  manager->xserver_died_cancellable = g_cancellable_new ();
  g_subprocess_wait_async (manager->proc, manager->xserver_died_cancellable,
                           xserver_died, NULL);
1062
1063
  g_unix_fd_add (displayfd[0], G_IO_IN, on_displayfd_ready,
                 g_steal_pointer (&task));
1064
1065
  manager->client = wl_client_create (manager->wayland_display,
                                      xwayland_client_fd[0]);
1066
}
1067

1068
1069
1070
1071
1072
1073
1074
gboolean
meta_xwayland_start_xserver_finish (MetaXWaylandManager  *manager,
                                    GAsyncResult         *result,
                                    GError              **error)
{
  g_assert (g_task_get_source_tag (G_TASK (result)) ==
            meta_xwayland_start_xserver);
1075

1076
  return g_task_propagate_boolean (G_TASK (result), error);
1077
1078
}

1079
1080
1081
1082
1083
static gboolean
xdisplay_connection_activity_cb (gint         fd,
                                 GIOCondition cond,
                                 gpointer     user_data)
{
1084
  MetaXWaylandManager *manager = user_data;
1085
  MetaDisplay *display = meta_get_display ();
1086

1087
1088
  meta_display_init_x11 (display, NULL,
                         (GAsyncReadyCallback) on_init_x11_cb, NULL);
1089

1090
1091
1092
1093
  /* Stop watching both file descriptors */
  g_clear_handle_id (&manager->abstract_fd_watch_id, g_source_remove);
  g_clear_handle_id (&manager->unix_fd_watch_id, g_source_remove);

1094
1095
1096
  return G_SOURCE_REMOVE;
}

1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
static void
meta_xwayland_stop_xserver_timeout (MetaXWaylandManager *manager)
{
  if (manager->xserver_grace_period_id)
    return;

  manager->xserver_grace_period_id =
    g_timeout_add_seconds (10, shutdown_xwayland_cb, manager);
}

1107
1108
1109
1110
1111
1112
1113
1114
static void
window_unmanaged_cb (MetaWindow          *window,
                     MetaXWaylandManager *manager)
{
  manager->x11_windows = g_list_remove (manager->x11_windows, window);
  g_signal_handlers_disconnect_by_func (window,
                                        window_unmanaged_cb,
                                        manager);
1115
1116
1117
  if (!manager->x11_windows)
    {
      meta_verbose ("All X11 windows gone, setting shutdown timeout");
1118
      meta_xwayland_stop_xserver_timeout (manager);
1119
    }
1120
1121
1122
1123
1124
1125
1126
1127
1128
}

static void
window_created_cb (MetaDisplay         *display,
                   MetaWindow          *window,
                   MetaXWaylandManager *manager)
{
  /* Ignore all internal windows */
  if (!window->xwindow ||
1129
      meta_window_get_pid (window) == getpid ())
1130
1131
1132
1133
1134
    return;

  manager->x11_windows = g_list_prepend (manager->x11_windows, window);
  g_signal_connect (window, "unmanaged",
                    G_CALLBACK (window_unmanaged_cb), manager);
1135

1136
  g_clear_handle_id (&manager->xserver_grace_period_id, g_source_remove);
1137
1138
1139
1140
1141
1142
1143
1144
1145
}

static void
meta_xwayland_stop_xserver (MetaXWaylandManager *manager)
{
  if (manager->proc)
    g_subprocess_send_signal (manager->proc, SIGTERM);
  g_clear_object (&manager->xserver_died_cancellable);
  g_clear_object (&manager->proc);
1146
1147
}

1148
gboolean
1149
1150
1151
1152
meta_xwayland_init (MetaXWaylandManager    *manager,
                    MetaWaylandCompositor  *compositor,
                    struct wl_display      *wl_display,
                    GError                **error)
1153
{
1154
  MetaContext *context = compositor->context;
1155
  MetaX11DisplayPolicy policy;
1156
1157
1158
1159
1160
1161
1162
  int display = 0;

  if (display_number_override != -1)
    display = display_number_override;
  else if (g_getenv ("RUNNING_UNDER_GDM"))
    display = 1024;

1163

1164
  if (!manager->public_connection.name)
1165
    {
1166
      if (!choose_xdisplay (manager, &manager->public_connection, &display, error))
1167
        return FALSE;
1168
1169
1170

      display++;
      if (!choose_xdisplay (manager, &manager->private_connection, &display, error))
1171
        return FALSE;
1172

1173
      if (!prepare_auth_file (manager, error))
1174
        return FALSE;
1175
1176
1177
    }
  else
    {
1178
1179
      if (!open_display_sockets (manager,
                                 manager->public_connection.display_index,
1180
                                 &manager->public_connection.abstract_fd,
1181
                                 &manager->public_connection.unix_fd,
1182
                                 error))
1183
1184
1185
1186
        return FALSE;

      if (!open_display_sockets (manager,
                                 manager->private_connection.display_index,