/
flatpak-portal.c
3139 lines (2619 loc) · 104 KB
/
flatpak-portal.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
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
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* vi:set et sw=2 sts=2 cin cino=t0,f0,(0,{s,>2s,n-s,^-s,e-s:
* Copyright © 2018 Red Hat, Inc
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http:https://www.gnu.org/licenses/>.
*
* Authors:
* Alexander Larsson <[email protected]>
*/
#include "config.h"
/* NOTE: This code was copied mostly as-is from xdg-desktop-portal */
#include <locale.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <glib-unix.h>
#include <glib/gi18n-lib.h>
#include <gio/gio.h>
#include <gio/gunixfdlist.h>
#include <gio/gunixinputstream.h>
#include <gio/gunixoutputstream.h>
#include <gio/gdesktopappinfo.h>
#include "flatpak-portal-dbus.h"
#include "flatpak-portal.h"
#include "flatpak-dir-private.h"
#include "flatpak-utils-private.h"
#include "flatpak-transaction.h"
#include "flatpak-installation-private.h"
#include "flatpak-instance-private.h"
#include "flatpak-portal-app-info.h"
#include "flatpak-portal-error.h"
#include "flatpak-utils-base-private.h"
#include "portal-impl.h"
#include "flatpak-permission-dbus.h"
/* GLib 2.47.92 was the first release to define these in gdbus-codegen */
#if !GLIB_CHECK_VERSION (2, 47, 92)
G_DEFINE_AUTOPTR_CLEANUP_FUNC (PortalFlatpakProxy, g_object_unref)
G_DEFINE_AUTOPTR_CLEANUP_FUNC (PortalFlatpakSkeleton, g_object_unref)
G_DEFINE_AUTOPTR_CLEANUP_FUNC (PortalFlatpakUpdateMonitorProxy, g_object_unref)
G_DEFINE_AUTOPTR_CLEANUP_FUNC (PortalFlatpakUpdateMonitorSkeleton, g_object_unref)
#endif
#define IDLE_TIMEOUT_SECS 10 * 60
/* Should be roughly 2 seconds */
#define CHILD_STATUS_CHECK_ATTEMPTS 20
static GStrv original_environ = NULL;
static GHashTable *client_pid_data_hash = NULL;
static GDBusConnection *session_bus = NULL;
static GNetworkMonitor *network_monitor = NULL;
static gboolean no_idle_exit = FALSE;
static guint name_owner_id = 0;
static GMainLoop *main_loop;
static PortalFlatpak *portal;
static gboolean opt_verbose;
static int opt_poll_timeout;
static gboolean opt_poll_when_metered;
static FlatpakSpawnSupportFlags supports = 0;
G_LOCK_DEFINE (update_monitors); /* This protects the three variables below */
static GHashTable *update_monitors;
static guint update_monitors_timeout = 0;
static gboolean update_monitors_timeout_running_thread = FALSE;
/* Poll all update monitors twice an hour */
#define DEFAULT_UPDATE_POLL_TIMEOUT_SEC (30 * 60)
#define PERMISSION_TABLE "flatpak"
#define PERMISSION_ID "updates"
/* Instance IDs are 32-bit unsigned integers */
#define INSTANCE_ID_BUFFER_SIZE 16
typedef enum { UNSET, ASK, YES, NO } Permission;
typedef enum {
PROGRESS_STATUS_RUNNING = 0,
PROGRESS_STATUS_EMPTY = 1,
PROGRESS_STATUS_DONE = 2,
PROGRESS_STATUS_ERROR = 3
} UpdateStatus;
static XdpDbusPermissionStore *permission_store;
typedef struct {
GMutex lock; /* This protects the closed, running and installed state */
gboolean closed;
gboolean running; /* While this is set, don't close the monitor */
gboolean installing;
char *sender;
char *obj_path;
GCancellable *cancellable;
/* Static data */
char *name;
char *arch;
char *branch;
char *commit;
char *app_path;
/* Last reported values, starting at the instance commit */
char *reported_local_commit;
char *reported_remote_commit;
} UpdateMonitorData;
static gboolean check_all_for_updates_cb (void *data);
static gboolean has_update_monitors (void);
static UpdateMonitorData *update_monitor_get_data (PortalFlatpakUpdateMonitor *monitor);
static gboolean handle_close (PortalFlatpakUpdateMonitor *monitor,
GDBusMethodInvocation *invocation);
static gboolean handle_update (PortalFlatpakUpdateMonitor *monitor,
GDBusMethodInvocation *invocation,
const char *arg_window,
GVariant *arg_options);
static void
skeleton_died_cb (gpointer data)
{
g_info ("skeleton finalized, exiting");
g_main_loop_quit (main_loop);
}
static gboolean
unref_skeleton_in_timeout_cb (gpointer user_data)
{
static gboolean unreffed = FALSE;
g_info ("unreffing portal main ref");
if (!unreffed)
{
g_object_unref (portal);
unreffed = TRUE;
}
return G_SOURCE_REMOVE;
}
static void
unref_skeleton_in_timeout (void)
{
if (name_owner_id)
g_bus_unown_name (name_owner_id);
name_owner_id = 0;
/* After we've lost the name or idled we drop the main ref on the helper
so that we'll exit when it drops to zero. However, if there are
outstanding calls these will keep the refcount up during the
execution of them. We do the unref on a timeout to make sure
we're completely draining the queue of (stale) requests. */
g_timeout_add (500, unref_skeleton_in_timeout_cb, NULL);
}
static guint idle_timeout_id = 0;
static gboolean
idle_timeout_cb (gpointer user_data)
{
if (name_owner_id &&
g_hash_table_size (client_pid_data_hash) == 0 &&
!has_update_monitors ())
{
g_info ("Idle - unowning name");
unref_skeleton_in_timeout ();
}
idle_timeout_id = 0;
return G_SOURCE_REMOVE;
}
G_LOCK_DEFINE_STATIC (idle);
static void
schedule_idle_callback (void)
{
G_LOCK (idle);
if (!no_idle_exit)
{
if (idle_timeout_id != 0)
g_source_remove (idle_timeout_id);
idle_timeout_id = g_timeout_add_seconds (IDLE_TIMEOUT_SECS, idle_timeout_cb, NULL);
}
G_UNLOCK (idle);
}
typedef struct
{
GPid pid;
char *client;
guint child_watch;
gboolean watch_bus;
gboolean expose_or_share_pids;
} PidData;
static void
pid_data_free (PidData *data)
{
g_free (data->client);
g_free (data);
}
static void
child_watch_died (GPid pid,
gint status,
gpointer user_data)
{
PidData *pid_data = user_data;
g_autoptr(GVariant) signal_variant = NULL;
g_info ("Client Pid %d died", pid_data->pid);
signal_variant = g_variant_ref_sink (g_variant_new ("(uu)", pid, status));
g_dbus_connection_emit_signal (session_bus,
pid_data->client,
FLATPAK_PORTAL_PATH,
FLATPAK_PORTAL_INTERFACE,
"SpawnExited",
signal_variant,
NULL);
/* This frees the pid_data, so be careful */
g_hash_table_remove (client_pid_data_hash, GUINT_TO_POINTER (pid_data->pid));
/* This might have caused us to go to idle (zero children) */
schedule_idle_callback ();
}
typedef struct
{
int from;
int to;
int final;
} FdMapEntry;
typedef struct
{
FdMapEntry *fd_map;
gsize fd_map_len;
int instance_id_fd;
gboolean set_tty;
int tty;
int env_fd;
} ChildSetupData;
typedef struct
{
guint pid;
gchar buffer[INSTANCE_ID_BUFFER_SIZE];
} InstanceIdReadData;
typedef struct
{
FlatpakInstance *instance;
guint pid;
guint attempt;
} BwrapinfoWatcherData;
static void
bwrapinfo_watcher_data_free (BwrapinfoWatcherData* data)
{
g_object_unref (data->instance);
g_free (data);
}
G_DEFINE_AUTOPTR_CLEANUP_FUNC (BwrapinfoWatcherData, bwrapinfo_watcher_data_free)
static int
get_child_pid_relative_to_parent_sandbox (int pid,
GError **error)
{
g_autofree char *status_file_path = NULL;
g_autoptr(GFile) status_file = NULL;
g_autoptr(GFileInputStream) input_stream = NULL;
g_autoptr(GDataInputStream) data_stream = NULL;
int relative_pid = 0;
status_file_path = g_strdup_printf ("/proc/%u/status", pid);
status_file = g_file_new_for_path (status_file_path);
input_stream = g_file_read (status_file, NULL, error);
if (input_stream == NULL)
return 0;
data_stream = g_data_input_stream_new (G_INPUT_STREAM (input_stream));
while (TRUE)
{
g_autofree char *line = g_data_input_stream_read_line_utf8 (data_stream, NULL, NULL, error);
if (line == NULL)
break;
g_strchug (line);
if (g_str_has_prefix (line, "NSpid:"))
{
g_auto(GStrv) fields = NULL;
guint nfields = 0;
char *endptr = NULL;
fields = g_strsplit (line, "\t", -1);
nfields = g_strv_length (fields);
if (nfields < 3)
{
g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
"NSpid line has too few fields: %s", line);
return 0;
}
/* The second to last PID namespace is the one that spawned this process */
relative_pid = strtol (fields[nfields - 2], &endptr, 10);
if (*endptr)
{
g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
"Invalid parent-relative PID in NSpid line: %s", line);
return 0;
}
return relative_pid;
}
}
if (*error == NULL)
/* EOF was reached while reading the file */
g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND, "NSpid not found");
return 0;
}
static int
check_child_pid_status (void *user_data)
{
/* Stores a sequence of the time interval to use until the child PID is checked again.
In general from testing, bwrapinfo is never ready before 25ms have passed at minimum,
thus 25ms is the first interval, doubling until a max interval of 100ms is reached.
In addition, if the program is not available after 100ms for an extended period of time,
the timeout is further increased to a full second. */
static gint timeouts[] = {25, 50, 100};
g_autoptr(GVariant) signal_variant = NULL;
g_autoptr(BwrapinfoWatcherData) data = user_data;
PidData *pid_data;
guint pid;
int child_pid;
int relative_child_pid = 0;
pid = data->pid;
pid_data = g_hash_table_lookup (client_pid_data_hash, GUINT_TO_POINTER (pid));
/* Process likely already exited if pid_data == NULL, so don't send the
signal to avoid an awkward out-of-order SpawnExited -> SpawnStarted. */
if (pid_data == NULL)
{
g_warning ("%u already exited, skipping SpawnStarted", pid);
return G_SOURCE_REMOVE;
}
child_pid = flatpak_instance_get_child_pid (data->instance);
if (child_pid == 0)
{
gint timeout;
gboolean readd_timer = FALSE;
if (data->attempt >= CHILD_STATUS_CHECK_ATTEMPTS)
/* If too many attempts, use a 1 second timeout */
timeout = 1000;
else
timeout = timeouts[MIN (data->attempt, G_N_ELEMENTS (timeouts) - 1)];
g_info ("Failed to read child PID, trying again in %d ms", timeout);
/* The timer source only needs to be re-added if the timeout has changed,
which won't happen while staying on the 100 or 1000ms timeouts.
This test must happen *before* the attempt counter is incremented, since the
attempt counter represents the *current* timeout. */
readd_timer = data->attempt <= G_N_ELEMENTS (timeouts) || data->attempt == CHILD_STATUS_CHECK_ATTEMPTS;
data->attempt++;
/* Make sure the data isn't destroyed */
data = NULL;
if (readd_timer)
{
g_timeout_add (timeout, check_child_pid_status, user_data);
return G_SOURCE_REMOVE;
}
return G_SOURCE_CONTINUE;
}
/* Only send the child PID if it's exposed */
if (pid_data->expose_or_share_pids)
{
g_autoptr(GError) error = NULL;
relative_child_pid = get_child_pid_relative_to_parent_sandbox (child_pid, &error);
if (relative_child_pid == 0)
g_warning ("Failed to find relative PID for %d: %s", child_pid, error->message);
}
g_info ("Emitting SpawnStarted(%u, %d)", pid, relative_child_pid);
signal_variant = g_variant_ref_sink (g_variant_new ("(uu)", pid, relative_child_pid));
g_dbus_connection_emit_signal (session_bus,
pid_data->client,
FLATPAK_PORTAL_PATH,
FLATPAK_PORTAL_INTERFACE,
"SpawnStarted",
signal_variant,
NULL);
return G_SOURCE_REMOVE;
}
static void
instance_id_read_finish (GObject *source,
GAsyncResult *res,
gpointer user_data)
{
g_autoptr(GInputStream) stream = NULL;
g_autofree InstanceIdReadData *data = NULL;
g_autoptr(FlatpakInstance) instance = NULL;
g_autoptr(GError) error = NULL;
BwrapinfoWatcherData *watcher_data = NULL;
gssize bytes_read;
stream = G_INPUT_STREAM (source);
data = (InstanceIdReadData *) user_data;
bytes_read = g_input_stream_read_finish (stream, res, &error);
if (bytes_read <= 0)
{
/* 0 means EOF, so the process could never have been started. */
if (bytes_read == -1)
g_warning ("Failed to read instance id: %s", error->message);
return;
}
data->buffer[bytes_read] = 0;
instance = flatpak_instance_new_for_id (data->buffer);
watcher_data = g_new0 (BwrapinfoWatcherData, 1);
watcher_data->instance = g_steal_pointer (&instance);
watcher_data->pid = data->pid;
check_child_pid_status (watcher_data);
}
static void
drop_cloexec (int fd)
{
fcntl (fd, F_SETFD, 0);
}
static void
child_setup_func (gpointer user_data)
{
ChildSetupData *data = (ChildSetupData *) user_data;
FdMapEntry *fd_map = data->fd_map;
sigset_t set;
gsize i;
g_fdwalk_set_cloexec (3);
if (data->instance_id_fd != -1)
drop_cloexec (data->instance_id_fd);
if (data->env_fd != -1)
drop_cloexec (data->env_fd);
/* Unblock all signals */
sigemptyset (&set);
if (pthread_sigmask (SIG_SETMASK, &set, NULL) == -1)
{
g_warning ("Failed to unblock signals when starting child");
return;
}
/* Reset the handlers for all signals to their defaults. */
for (i = 1; i < NSIG; i++)
{
if (i != SIGSTOP && i != SIGKILL)
signal (i, SIG_DFL);
}
for (i = 0; i < data->fd_map_len; i++)
{
if (fd_map[i].from != fd_map[i].to)
{
dup2 (fd_map[i].from, fd_map[i].to);
close (fd_map[i].from);
}
}
/* Second pass in case we needed an in-between fd value to avoid conflicts */
for (i = 0; i < data->fd_map_len; i++)
{
if (fd_map[i].to != fd_map[i].final)
{
dup2 (fd_map[i].to, fd_map[i].final);
close (fd_map[i].to);
}
/* Ensure we inherit the final fd value */
drop_cloexec (fd_map[i].final);
}
/* We become our own session and process group, because it never makes sense
to share the flatpak-session-helper dbus activated process group */
setsid ();
setpgid (0, 0);
if (data->set_tty)
{
/* data->tty is our from fd which is closed at this point.
* so locate the destination fd and use it for the ioctl.
*/
for (i = 0; i < data->fd_map_len; i++)
{
if (fd_map[i].from == data->tty)
{
if (ioctl (fd_map[i].final, TIOCSCTTY, 0) == -1)
g_info ("ioctl(%d, TIOCSCTTY, 0) failed: %s",
fd_map[i].final, strerror (errno));
break;
}
}
}
}
static gboolean
is_valid_expose (const char *expose,
GError **error)
{
/* No subdirs or absolute paths */
if (expose[0] == '/')
{
g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
"Invalid sandbox expose: absolute paths not allowed");
return FALSE;
}
else if (strchr (expose, '/'))
{
g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
"Invalid sandbox expose: subdirectories not allowed");
return FALSE;
}
return TRUE;
}
static char *
filesystem_arg (const char *path,
gboolean readonly)
{
g_autoptr(GString) s = g_string_new ("--filesystem=");
const char *p;
for (p = path; *p != 0; p++)
{
if (*p == ':')
g_string_append (s, "\\:");
else
g_string_append_c (s, *p);
}
if (readonly)
g_string_append (s, ":ro");
return g_string_free (g_steal_pointer (&s), FALSE);
}
static char *
filesystem_sandbox_arg (const char *path,
const char *sandbox,
gboolean readonly)
{
g_autoptr(GString) s = g_string_new ("--filesystem=");
const char *p;
for (p = path; *p != 0; p++)
{
if (*p == ':')
g_string_append (s, "\\:");
else
g_string_append_c (s, *p);
}
g_string_append (s, "/sandbox/");
for (p = sandbox; *p != 0; p++)
{
if (*p == ':')
g_string_append (s, "\\:");
else
g_string_append_c (s, *p);
}
if (readonly)
g_string_append (s, ":ro");
return g_string_free (g_steal_pointer (&s), FALSE);
}
static char *
bubblewrap_remap_path (const char *path)
{
if (g_str_has_prefix (path, "/newroot/"))
path = path + strlen ("/newroot");
return g_strdup (path);
}
static char *
verify_proc_self_fd (const char *proc_path,
GError **error)
{
char path_buffer[PATH_MAX + 1];
ssize_t symlink_size;
symlink_size = readlink (proc_path, path_buffer, PATH_MAX);
if (symlink_size < 0)
return glnx_null_throw_errno_prefix (error, "readlink");
path_buffer[symlink_size] = 0;
/* All normal paths start with /, but some weird things
don't, such as socket:[27345] or anon_inode:[eventfd].
We don't support any of these */
if (path_buffer[0] != '/')
return glnx_null_throw (error, "%s resolves to non-absolute path %s",
proc_path, path_buffer);
/* File descriptors to actually deleted files have " (deleted)"
appended to them. This also happens to some fake fd types
like shmem which are "/<name> (deleted)". All such
files are considered invalid. Unfortunatelly this also
matches files with filenames that actually end in " (deleted)",
but there is not much to do about this. */
if (g_str_has_suffix (path_buffer, " (deleted)"))
return glnx_null_throw (error, "%s resolves to deleted path %s",
proc_path, path_buffer);
/* remap from sandbox to host if needed */
return bubblewrap_remap_path (path_buffer);
}
static char *
get_path_for_fd (int fd,
gboolean *writable_out,
GError **error)
{
g_autofree char *proc_path = NULL;
int fd_flags;
struct stat st_buf;
struct stat real_st_buf;
g_autofree char *path = NULL;
gboolean writable = FALSE;
int read_access_mode;
/* Must be able to get fd flags */
fd_flags = fcntl (fd, F_GETFL);
if (fd_flags == -1)
return glnx_null_throw_errno_prefix (error, "fcntl F_GETFL");
/* Must be O_PATH */
if ((fd_flags & O_PATH) != O_PATH)
return glnx_null_throw (error, "not opened with O_PATH");
/* We don't want to allow exposing symlinks, because if they are
* under the callers control they could be changed between now and
* starting the child allowing it to point anywhere, so enforce .
* and verify that stat is not a link.
*/
if ((fd_flags & O_) != O_)
return glnx_null_throw (error, "not opened with O_");
/* Must be able to fstat */
if (fstat (fd, &st_buf) < 0)
return glnx_null_throw_errno_prefix (error, "fstat");
/* As per above, no symlinks */
if (S_ISLNK (st_buf.st_mode))
return glnx_null_throw (error, "is a symbolic link");
proc_path = g_strdup_printf ("/proc/self/fd/%d", fd);
/* Must be able to read valid path from /proc/self/fd */
/* This is an absolute and (at least at open time) symlink-expanded path */
path = verify_proc_self_fd (proc_path, error);
if (path == NULL)
return NULL;
/* Verify that this is the same file as the app opened */
if (stat (path, &real_st_buf) < 0 ||
st_buf.st_dev != real_st_buf.st_dev ||
st_buf.st_ino != real_st_buf.st_ino)
{
/* Different files on the inside and the outside, reject the request */
return glnx_null_throw (error,
"different file inside and outside sandbox");
}
read_access_mode = R_OK;
if (S_ISDIR (st_buf.st_mode))
read_access_mode |= X_OK;
/* Must be able to access the path via the sandbox supplied O_PATH fd,
which applies the sandbox side mount options (like readonly). */
if (access (proc_path, read_access_mode) != 0)
return glnx_null_throw (error, "not %s in sandbox",
read_access_mode & X_OK ? "accessible" : "readable");
if (access (proc_path, W_OK) == 0)
writable = TRUE;
if (writable_out != NULL)
*writable_out = writable;
return g_steal_pointer (&path);
}
static gboolean
handle_spawn (PortalFlatpak *object,
GDBusMethodInvocation *invocation,
GUnixFDList *fd_list,
const gchar *arg_cwd_path,
const gchar *const *arg_argv,
GVariant *arg_fds,
GVariant *arg_envs,
guint arg_flags,
GVariant *arg_options)
{
g_autoptr(GError) error = NULL;
ChildSetupData child_setup_data = { NULL };
GPid pid;
PidData *pid_data;
InstanceIdReadData *instance_id_read_data = NULL;
gsize i, j, n_fds, n_envs;
const gint *fds = NULL;
gint fds_len = 0;
g_autoptr(GArray) fd_map = NULL;
g_auto(GStrv) env = NULL;
gint32 max_fd;
GKeyFile *app_info;
g_autoptr(GPtrArray) flatpak_argv = g_ptr_array_new_with_free_func (g_free);
g_autofree char *app_id = NULL;
g_autofree char *branch = NULL;
g_autofree char *arch = NULL;
g_autofree char *app_commit = NULL;
g_autofree char *runtime_ref = NULL;
g_auto(GStrv) runtime_parts = NULL;
g_autofree char *runtime_commit = NULL;
g_autofree char *instance_path = NULL;
g_autofree char *instance_id = NULL;
g_auto(GStrv) extra_args = NULL;
g_auto(GStrv) shares = NULL;
g_auto(GStrv) sockets = NULL;
g_auto(GStrv) devices = NULL;
g_auto(GStrv) unset_env = NULL;
g_auto(GStrv) sandbox_expose = NULL;
g_auto(GStrv) sandbox_expose_ro = NULL;
g_autoptr(FlatpakInstance) instance = NULL;
g_autoptr(GVariant) sandbox_expose_fd = NULL;
g_autoptr(GVariant) sandbox_expose_fd_ro = NULL;
g_autoptr(GVariant) app_fd = NULL;
g_autoptr(GVariant) usr_fd = NULL;
g_autoptr(GOutputStream) instance_id_out_stream = NULL;
guint sandbox_flags = 0;
gboolean sandboxed;
gboolean expose_pids;
gboolean share_pids;
gboolean notify_start;
gboolean devel;
gboolean empty_app;
g_autoptr(GString) env_string = g_string_new ("");
glnx_autofd int env_fd = -1;
const char *flatpak;
gboolean testing = FALSE;
child_setup_data.instance_id_fd = -1;
child_setup_data.env_fd = -1;
if (fd_list != NULL)
fds = g_unix_fd_list_peek_fds (fd_list, &fds_len);
app_info = g_object_get_data (G_OBJECT (invocation), "app-info");
g_assert (app_info != NULL);
app_id = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_APPLICATION,
FLATPAK_METADATA_KEY_NAME, NULL);
g_assert (app_id != NULL);
g_info ("spawn() called from app: '%s'", app_id);
if (*app_id == 0 && g_getenv ("FLATPAK_PORTAL_MOCK_FLATPAK") != NULL)
{
/* Pretend we had been called from an app for test purposes */
testing = TRUE;
g_info ("In unit tests, behaving as though app ID was com.example.App");
g_clear_pointer (&app_id, g_free);
app_id = g_strdup ("com.example.App");
}
if (*app_id == 0)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_INVALID_ARGS,
FLATPAK_PORTAL_INTERFACE ".Spawn only works in a flatpak");
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
if (*arg_cwd_path == 0)
arg_cwd_path = NULL;
if (arg_argv == NULL || *arg_argv == NULL)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_INVALID_ARGS,
"No command given");
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
if ((arg_flags & ~FLATPAK_SPAWN_FLAGS_ALL) != 0)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
"Unsupported flags enabled: 0x%x", arg_flags & ~FLATPAK_SPAWN_FLAGS_ALL);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
if (testing)
runtime_ref = g_strdup ("runtime/com.example.Runtime/m68k/1.0");
else
runtime_ref = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_APPLICATION,
FLATPAK_METADATA_KEY_RUNTIME, NULL);
if (runtime_ref == NULL)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
"No runtime found");
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
runtime_parts = g_strsplit (runtime_ref, "/", -1);
branch = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_BRANCH, NULL);
instance_path = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_INSTANCE_PATH, NULL);
arch = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_ARCH, NULL);
extra_args = g_key_file_get_string_list (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_EXTRA_ARGS, NULL, NULL);
app_commit = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_APP_COMMIT, NULL);
runtime_commit = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_RUNTIME_COMMIT, NULL);
shares = g_key_file_get_string_list (app_info, FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_SHARED, NULL, NULL);
sockets = g_key_file_get_string_list (app_info, FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_SOCKETS, NULL, NULL);
devices = g_key_file_get_string_list (app_info, FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_DEVICES, NULL, NULL);
devel = g_key_file_get_boolean (app_info, FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_DEVEL, NULL);
g_variant_lookup (arg_options, "sandbox-expose", "^as", &sandbox_expose);
g_variant_lookup (arg_options, "sandbox-expose-ro", "^as", &sandbox_expose_ro);
g_variant_lookup (arg_options, "sandbox-flags", "u", &sandbox_flags);
sandbox_expose_fd = g_variant_lookup_value (arg_options, "sandbox-expose-fd", G_VARIANT_TYPE ("ah"));
sandbox_expose_fd_ro = g_variant_lookup_value (arg_options, "sandbox-expose-fd-ro", G_VARIANT_TYPE ("ah"));
g_variant_lookup (arg_options, "unset-env", "^as", &unset_env);
app_fd = g_variant_lookup_value (arg_options, "app-fd", G_VARIANT_TYPE_HANDLE);
usr_fd = g_variant_lookup_value (arg_options, "usr-fd", G_VARIANT_TYPE_HANDLE);
if ((sandbox_flags & ~FLATPAK_SPAWN_SANDBOX_FLAGS_ALL) != 0)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
"Unsupported sandbox flags enabled: 0x%x", arg_flags & ~FLATPAK_SPAWN_SANDBOX_FLAGS_ALL);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
if (instance_path == NULL &&
((sandbox_expose != NULL && sandbox_expose[0] != NULL) ||
(sandbox_expose_ro != NULL && sandbox_expose_ro[0] != NULL)))
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_INVALID_ARGS,
"Invalid sandbox expose, caller has no instance path");
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
for (i = 0; sandbox_expose != NULL && sandbox_expose[i] != NULL; i++)
{
const char *expose = sandbox_expose[i];
g_info ("exposing %s", expose);
if (!is_valid_expose (expose, &error))
{
g_dbus_method_invocation_return_gerror (invocation, error);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
}
for (i = 0; sandbox_expose_ro != NULL && sandbox_expose_ro[i] != NULL; i++)
{
const char *expose = sandbox_expose_ro[i];
g_info ("exposing %s", expose);
if (!is_valid_expose (expose, &error))
{
g_dbus_method_invocation_return_gerror (invocation, error);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
}
g_info ("Running spawn command %s", arg_argv[0]);
n_fds = 0;
if (fds != NULL)
n_fds = g_variant_n_children (arg_fds);
fd_map = g_array_sized_new (FALSE, FALSE, sizeof (FdMapEntry), n_fds);
max_fd = -1;
for (i = 0; i < n_fds; i++)
{
FdMapEntry fd_map_entry;
gint32 handle, dest_fd;
int handle_fd;
g_variant_get_child (arg_fds, i, "{uh}", &dest_fd, &handle);
if (handle >= fds_len || handle < 0)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_INVALID_ARGS,
"No file descriptor for handle %d",
handle);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
handle_fd = fds[handle];
fd_map_entry.to = dest_fd;
fd_map_entry.from = handle_fd;
fd_map_entry.final = fd_map_entry.to;
g_array_append_val (fd_map, fd_map_entry);
/* If stdin/out/err is a tty we try to set it as the controlling
tty for the app, this way we can use this to run in a terminal. */
if ((dest_fd == 0 || dest_fd == 1 || dest_fd == 2) &&
!child_setup_data.set_tty &&
isatty (handle_fd))
{
child_setup_data.set_tty = TRUE;
child_setup_data.tty = handle_fd;
}
max_fd = MAX (max_fd, fd_map_entry.to);
max_fd = MAX (max_fd, fd_map_entry.from);
}
if (testing)
{
instance_id = g_strdup ("11223344");
}
else
{