-
-
Notifications
You must be signed in to change notification settings - Fork 270
Expand file tree
/
Copy pathportal-service.vala
More file actions
1543 lines (1241 loc) · 44.5 KB
/
portal-service.vala
File metadata and controls
1543 lines (1241 loc) · 44.5 KB
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
namespace Frida {
public class PortalService : Object {
public signal void node_connected (uint connection_id, SocketAddress remote_address);
public signal void node_joined (uint connection_id, Application application);
public signal void node_left (uint connection_id, Application application);
public signal void node_disconnected (uint connection_id, SocketAddress remote_address);
public signal void controller_connected (uint connection_id, SocketAddress remote_address);
public signal void controller_disconnected (uint connection_id, SocketAddress remote_address);
public signal void authenticated (uint connection_id, string session_info);
public signal void subscribe (uint connection_id);
public signal void message (uint connection_id, string json, Bytes? data);
public Device device {
get {
return _device;
}
}
private Device _device;
public EndpointParameters cluster_params {
get;
construct;
}
public EndpointParameters? control_params {
get;
construct;
}
private State state = STOPPED;
private WebService cluster_service;
private WebService? control_service;
private Gee.Map<uint, ConnectionEntry> connections = new Gee.HashMap<uint, ConnectionEntry> ();
private Gee.MultiMap<string, ConnectionEntry> tags = new Gee.HashMultiMap<string, ConnectionEntry> ();
private uint next_connection_id = 1;
private Gee.Map<DBusConnection, Peer> peers = new Gee.HashMap<DBusConnection, Peer> ();
private Gee.Map<uint, ClusterNode> node_by_pid = new Gee.HashMap<uint, ClusterNode> ();
private Gee.Map<string, ClusterNode> node_by_identifier = new Gee.HashMap<string, ClusterNode> ();
private Gee.Set<ControlChannel> spawn_gaters = new Gee.HashSet<ControlChannel> ();
private Gee.Map<uint, PendingSpawn> pending_spawn = new Gee.HashMap<uint, PendingSpawn> ();
private Gee.Map<AgentSessionId?, AgentSessionEntry> sessions =
new Gee.HashMap<AgentSessionId?, AgentSessionEntry> (AgentSessionId.hash, AgentSessionId.equal);
private Cancellable? io_cancellable;
private enum State {
STOPPED,
STARTING,
STARTED
}
public PortalService (EndpointParameters cluster_params, EndpointParameters? control_params = null) {
Object (cluster_params: cluster_params, control_params: control_params);
}
construct {
_device = new Device (null, "portal", "Portal", HostSessionProviderKind.LOCAL,
new PortalHostSessionProvider (this));
cluster_service = new WebService (cluster_params, CLUSTER);
cluster_service.incoming.connect (on_incoming_cluster_connection);
if (control_params != null) {
control_service = new WebService (control_params, CONTROL);
control_service.incoming.connect (on_incoming_control_connection);
}
}
public override void dispose () {
if (_device != null) {
Device d = _device;
_device = null;
teardown_device.begin (d);
}
base.dispose ();
}
private async void teardown_device (Device d) {
try {
yield d._do_close (SessionDetachReason.DEVICE_LOST, true, null);
} catch (IOError e) {
assert_not_reached ();
}
}
public async void start (Cancellable? cancellable = null) throws Error, IOError {
if (state != STOPPED)
throw new Error.INVALID_OPERATION ("Invalid operation");
state = STARTING;
io_cancellable = new Cancellable ();
try {
yield cluster_service.start (cancellable);
if (control_service != null)
yield control_service.start (cancellable);
state = STARTED;
} catch (GLib.Error e) {
throw new Error.ADDRESS_IN_USE ("%s", e.message);
} finally {
if (state != STARTED)
state = STOPPED;
}
}
public void start_sync (Cancellable? cancellable = null) throws Error, IOError {
create<StartTask> ().execute (cancellable);
}
private class StartTask : PortalServiceTask<void> {
protected override async void perform_operation () throws Error, IOError {
yield parent.start (cancellable);
}
}
public async void stop (Cancellable? cancellable = null) throws Error, IOError {
if (state != STARTED)
throw new Error.INVALID_OPERATION ("Invalid operation");
if (control_service != null)
control_service.stop ();
cluster_service.stop ();
if (io_cancellable != null)
io_cancellable.cancel ();
foreach (var peer in peers.values.to_array ())
peer.close ();
peers.clear ();
state = STOPPED;
}
public void stop_sync (Cancellable? cancellable = null) throws Error, IOError {
create<StopTask> ().execute (cancellable);
}
private class StopTask : PortalServiceTask<void> {
protected override async void perform_operation () throws Error, IOError {
yield parent.stop (cancellable);
}
}
public void kick (uint connection_id) {
MainContext context = get_main_context ();
if (context.is_owner ()) {
do_kick (connection_id);
} else {
var source = new IdleSource ();
source.set_callback (() => {
do_kick (connection_id);
return false;
});
source.attach (context);
}
}
private void do_kick (uint connection_id) {
ConnectionEntry? entry = connections[connection_id];
if (entry == null)
return;
entry.connection.close.begin (io_cancellable);
}
public void post (uint connection_id, string json, Bytes? data = null) {
MainContext context = get_main_context ();
if (context.is_owner ()) {
do_post (connection_id, json, data);
} else {
var source = new IdleSource ();
source.set_callback (() => {
do_post (connection_id, json, data);
return false;
});
source.attach (context);
}
}
private void do_post (uint connection_id, string json, Bytes? data) {
ConnectionEntry? entry = connections[connection_id];
if (entry != null)
entry.post (json, data);
}
public void narrowcast (string tag, string json, Bytes? data = null) {
MainContext context = get_main_context ();
if (context.is_owner ()) {
do_narrowcast (tag, json, data);
} else {
var source = new IdleSource ();
source.set_callback (() => {
do_narrowcast (tag, json, data);
return false;
});
source.attach (context);
}
}
private void do_narrowcast (string tag, string json, Bytes? data) {
foreach (ConnectionEntry entry in tags[tag])
entry.post (json, data);
}
public void broadcast (string json, Bytes? data = null) {
MainContext context = get_main_context ();
if (context.is_owner ()) {
do_broadcast (json, data);
} else {
var source = new IdleSource ();
source.set_callback (() => {
do_broadcast (json, data);
return false;
});
source.attach (context);
}
}
private void do_broadcast (string json, Bytes? data) {
var has_data = data != null;
var data_param = has_data ? data.get_data () : new uint8[0];
foreach (Peer peer in peers.values) {
ControlChannel? controller = peer as ControlChannel;
if (controller == null)
continue;
BusService bus = controller.bus;
if (bus.status != ATTACHED)
continue;
bus.message (json, has_data, data_param);
}
}
public string[]? enumerate_tags (uint connection_id) {
MainContext context = get_main_context ();
if (context.is_owner ()) {
return do_enumerate_tags (connection_id);
} else {
string[]? result = null;
bool completed = false;
var mutex = Mutex ();
var cond = Cond ();
var source = new IdleSource ();
source.set_callback (() => {
result = do_enumerate_tags (connection_id);
mutex.lock ();
completed = true;
cond.signal ();
mutex.unlock ();
return false;
});
source.attach (context);
mutex.lock ();
while (!completed)
cond.wait (mutex);
mutex.unlock ();
return result;
}
}
private string[]? do_enumerate_tags (uint connection_id) {
ConnectionEntry? entry = connections[connection_id];
if (entry == null)
return null;
Gee.Set<string>? tags = entry.tags;
if (tags == null)
return null;
string[] elements = tags.to_array ();
string[] strv = new string[elements.length + 1];
for (int i = 0; i != elements.length; i++)
strv[i] = elements[i];
strv.length = elements.length;
return strv;
}
public void tag (uint connection_id, string tag) {
MainContext context = get_main_context ();
if (context.is_owner ()) {
do_tag (connection_id, tag);
} else {
var source = new IdleSource ();
source.set_callback (() => {
do_tag (connection_id, tag);
return false;
});
source.attach (context);
}
}
private void do_tag (uint connection_id, string tag) {
ConnectionEntry? entry = connections[connection_id];
if (entry == null)
return;
tags[tag] = entry;
if (entry.tags == null)
entry.tags = new Gee.HashSet<string> ();
entry.tags.add (tag);
}
public void untag (uint connection_id, string tag) {
MainContext context = get_main_context ();
if (context.is_owner ()) {
do_untag (connection_id, tag);
} else {
var source = new IdleSource ();
source.set_callback (() => {
do_untag (connection_id, tag);
return false;
});
source.attach (context);
}
}
private void do_untag (uint connection_id, string tag) {
ConnectionEntry? entry = connections[connection_id];
if (entry == null)
return;
if (entry.tags == null)
return;
entry.tags.remove (tag);
tags.remove (tag, entry);
}
private T create<T> () {
return Object.new (typeof (T), parent: this);
}
private abstract class PortalServiceTask<T> : AsyncTask<T> {
public weak PortalService parent {
get;
construct;
}
}
private void on_incoming_cluster_connection (IOStream connection, SocketAddress remote_address) {
handle_incoming_connection.begin (connection, remote_address, cluster_params);
}
private void on_incoming_control_connection (IOStream connection, SocketAddress remote_address) {
handle_incoming_connection.begin (connection, remote_address, control_params);
}
private async void handle_incoming_connection (IOStream web_connection, SocketAddress remote_address,
EndpointParameters parameters) throws GLib.Error {
var connection = yield new DBusConnection (web_connection, null, DELAY_MESSAGE_PROCESSING, null, io_cancellable);
connection.on_closed.connect (on_connection_closed);
uint connection_id = register_connection (connection, remote_address, parameters);
Peer peer;
if (parameters.auth_service != null)
peer = setup_unauthorized_peer (connection_id, connection, parameters);
else
peer = yield setup_authorized_peer (connection_id, connection, parameters);
peers[connection] = peer;
}
private uint register_connection (DBusConnection connection, SocketAddress address,
EndpointParameters parameters) throws GLib.Error {
uint id = next_connection_id++;
var entry = new ConnectionEntry (connection, address, parameters);
connections[id] = entry;
if (parameters == cluster_params)
node_connected (id, address);
else
controller_connected (id, address);
return id;
}
private void on_connection_closed (DBusConnection connection, bool remote_peer_vanished, GLib.Error? error) {
Peer peer;
if (peers.unset (connection, out peer)) {
peer.close ();
uint id = peer.connection_id;
ConnectionEntry entry;
connections.unset (id, out entry);
Gee.Set<string> tags_to_remove = entry.tags;
if (tags_to_remove != null) {
foreach (string tag in tags_to_remove)
tags.remove (tag, entry);
}
if (entry.parameters == cluster_params)
node_disconnected (id, entry.address);
else
controller_disconnected (id, entry.address);
}
}
private Peer setup_unauthorized_peer (uint connection_id, DBusConnection connection, EndpointParameters parameters) {
var channel = new AuthenticationChannel (this, connection_id, connection, parameters);
try {
if (parameters == cluster_params) {
PortalSession portal_session = new UnauthorizedPortalSession ();
channel.take_registration (connection.register_object (ObjectPath.PORTAL_SESSION, portal_session));
} else {
HostSession host_session = new UnauthorizedHostSession ();
channel.take_registration (connection.register_object (ObjectPath.HOST_SESSION, host_session));
BusSession bus_session = new UnauthorizedBusSession ();
channel.take_registration (connection.register_object (ObjectPath.BUS_SESSION, bus_session));
}
} catch (GLib.Error e) {
assert_not_reached ();
}
connection.start_message_processing ();
return channel;
}
private async void promote_authentication_channel (AuthenticationChannel channel, string session_info) throws GLib.Error {
uint connection_id = channel.connection_id;
DBusConnection connection = channel.connection;
peers.unset (connection);
channel.close ();
peers[connection] = yield setup_authorized_peer (connection_id, connection, channel.parameters);
authenticated (connection_id, session_info);
}
private void kick_authentication_channel (AuthenticationChannel channel) {
var source = new IdleSource ();
source.set_callback (() => {
channel.connection.close.begin (io_cancellable);
return false;
});
source.attach (MainContext.get_thread_default ());
}
private async Peer setup_authorized_peer (uint connection_id, DBusConnection connection,
EndpointParameters parameters) throws GLib.Error {
Peer peer;
if (parameters == cluster_params)
peer = yield setup_cluster_node (connection_id, connection);
else
peer = setup_control_channel (connection_id, connection);
ConnectionEntry? entry = connections[peer.connection_id];
if (entry == null)
throw new Error.TRANSPORT ("Peer disconnected");
entry.peer = peer;
return peer;
}
private ControlChannel setup_control_channel (uint connection_id, DBusConnection connection) {
var channel = new ControlChannel (this, connection_id, connection);
connection.start_message_processing ();
return channel;
}
private void teardown_control_channel (ControlChannel channel) {
foreach (AgentSessionId id in channel.sessions) {
AgentSessionEntry entry = sessions[id];
AgentSession? session = entry.session;
if (entry.persist_timeout == 0 || session == null) {
sessions.unset (id);
if (session != null)
session.close.begin (io_cancellable);
} else {
entry.detach_controller ();
session.interrupt.begin (io_cancellable);
}
}
disable_spawn_gating (channel);
}
private async ClusterNode setup_cluster_node (uint connection_id, DBusConnection connection) throws GLib.Error {
var node = new ClusterNode (this, connection_id, connection);
node.session_closed.connect (on_agent_session_closed);
node.session_provider = yield connection.get_proxy (null, ObjectPath.AGENT_SESSION_PROVIDER, DO_NOT_LOAD_PROPERTIES,
io_cancellable);
connection.start_message_processing ();
return node;
}
private void teardown_cluster_node (ClusterNode node) {
var no_crash = CrashInfo.empty ();
foreach (var id in node.sessions) {
AgentSessionEntry entry = sessions[id];
ControlChannel? c = entry.controller;
if (c != null)
c.sessions.remove (id);
AgentSession? session = entry.session;
if (entry.persist_timeout == 0 || session == null) {
sessions.unset (id);
if (c != null)
c.agent_session_detached (id, SessionDetachReason.PROCESS_TERMINATED, no_crash);
} else {
entry.detach_node_and_controller ();
if (c != null)
c.agent_session_detached (id, SessionDetachReason.CONNECTION_TERMINATED, no_crash);
}
}
Application? app = node.application;
if (app != null) {
uint pid = app.pid;
node_left (node.connection_id, app);
node_by_pid.unset (pid);
node_by_identifier.unset (app.identifier);
PendingSpawn spawn;
if (pending_spawn.unset (pid, out spawn))
notify_spawn_removed (spawn);
}
}
private HostApplicationInfo[] enumerate_applications (HashTable<string, Variant> options,
ControlChannel requester) throws Error {
var opts = ApplicationQueryOptions._deserialize (options);
var scope = opts.scope;
Gee.List<Application> apps = new Gee.ArrayList<Application> ();
all_nodes_accessible_by (requester).foreach (node => {
apps.add (node.application);
return true;
});
apps = maybe_filter_apps_using_ids (apps, opts);
var result = new HostApplicationInfo[apps.size];
int i = 0;
foreach (var app in apps) {
result[i++] = HostApplicationInfo (app.identifier, app.name, app.pid,
(scope != MINIMAL) ? app.parameters : make_parameters_dict ());
}
return result;
}
private HostProcessInfo[] enumerate_processes (HashTable<string, Variant> options, ControlChannel requester) throws Error {
var opts = ProcessQueryOptions._deserialize (options);
var scope = opts.scope;
Gee.List<Application> apps = new Gee.ArrayList<Application> ();
all_nodes_accessible_by (requester).foreach (node => {
apps.add (node.application);
return true;
});
apps = maybe_filter_apps_using_pids (apps, opts);
var result = new HostProcessInfo[apps.size];
int i = 0;
foreach (var app in apps) {
result[i++] = HostProcessInfo (app.pid, app.name,
(scope != MINIMAL) ? app.parameters : make_parameters_dict ());
}
return result;
}
private Gee.List<Application> maybe_filter_apps_using_ids (Gee.List<Application> apps, ApplicationQueryOptions options) {
if (!options.has_selected_identifiers ())
return apps;
var app_by_identifier = new Gee.HashMap<string, Application> ();
foreach (var app in apps)
app_by_identifier[app.identifier] = app;
var filtered_apps = new Gee.ArrayList<Application> ();
options.enumerate_selected_identifiers (identifier => {
Application? app = app_by_identifier[identifier];
if (app != null)
filtered_apps.add (app);
});
return filtered_apps;
}
private Gee.List<Application> maybe_filter_apps_using_pids (Gee.List<Application> apps, ProcessQueryOptions options) {
if (!options.has_selected_pids ())
return apps;
var app_by_pid = new Gee.HashMap<uint, Application> ();
foreach (Application app in apps)
app_by_pid[app.pid] = app;
var filtered_apps = new Gee.ArrayList<Application> ();
options.enumerate_selected_pids (pid => {
Application? app = app_by_pid[pid];
if (app != null)
filtered_apps.add (app);
});
return filtered_apps;
}
private void enable_spawn_gating (ControlChannel requester) {
spawn_gaters.add (requester);
foreach (PendingSpawn spawn in pending_spawn.values) {
bool requester_has_access = find_node_accessible_by (requester, spawn.info.pid) != null;
if (requester_has_access)
spawn.pending_approvers.add (requester);
}
}
private void disable_spawn_gating (ControlChannel requester) {
if (spawn_gaters.remove (requester)) {
foreach (uint pid in pending_spawn.keys.to_array ())
resume (pid, requester);
}
}
private HostSpawnInfo[] enumerate_pending_spawn (ControlChannel requester) {
var result = new HostSpawnInfo[pending_spawn.size];
int i = 0;
foreach (PendingSpawn spawn in pending_spawn.values) {
if (spawn.pending_approvers.contains (requester))
result[i++] = spawn.info;
}
result.length = i;
return result;
}
private void resume (uint pid, ControlChannel requester) {
PendingSpawn? spawn = pending_spawn[pid];
if (spawn == null)
return;
var approvers = spawn.pending_approvers;
approvers.remove (requester);
if (approvers.is_empty) {
pending_spawn.unset (pid);
ClusterNode? node = node_by_pid[pid];
assert (node != null);
node.resume ();
notify_spawn_removed (spawn);
}
}
private void kill (uint pid, ControlChannel requester) {
ClusterNode? node = find_node_accessible_by (requester, pid);
if (node == null)
return;
node.kill ();
}
private void handle_bus_attach (uint connection_id) {
subscribe (connection_id);
}
private void handle_bus_message (uint connection_id, string json, Bytes? data) {
message (connection_id, json, data);
}
private async AgentSessionId attach (uint pid, HashTable<string, Variant> options, ControlChannel requester,
Cancellable? cancellable) throws Error, IOError {
ClusterNode? node = find_node_accessible_by (requester, pid);
if (node == null)
throw new Error.PROCESS_NOT_FOUND ("Unable to find process with pid %u", pid);
var id = AgentSessionId.generate ();
yield node.open_session (id, options, cancellable);
requester.sessions.add (id);
var opts = SessionOptions._deserialize (options);
var entry = new AgentSessionEntry (node, requester, id, opts.persist_timeout, io_cancellable);
sessions[id] = entry;
entry.expired.connect (on_agent_session_expired);
yield link_session (id, entry, requester, cancellable);
return id;
}
private async void reattach (AgentSessionId id, ControlChannel requester, Cancellable? cancellable) throws Error, IOError {
AgentSessionEntry? entry = sessions[id];
if (entry == null || entry.controller != null)
throw new Error.INVALID_OPERATION ("Invalid session ID");
if (entry.node == null)
throw new Error.INVALID_OPERATION ("Cluster node is temporarily unavailable");
entry.attach_controller (requester);
requester.sessions.add (id);
yield link_session (id, entry, requester, cancellable);
}
private async void link_session (AgentSessionId id, AgentSessionEntry entry, ControlChannel requester,
Cancellable? cancellable) throws Error, IOError {
DBusConnection node_connection = entry.node.connection;
AgentSession? session = entry.session;
if (session == null) {
try {
session = yield node_connection.get_proxy (null, ObjectPath.for_agent_session (id),
DO_NOT_LOAD_PROPERTIES, cancellable);
} catch (IOError e) {
throw_dbus_error (e);
}
entry.session = session;
}
DBusConnection? controller_connection = requester.connection;
if (controller_connection != null) {
AgentMessageSink sink;
try {
sink = yield controller_connection.get_proxy (null, ObjectPath.for_agent_message_sink (id),
DO_NOT_LOAD_PROPERTIES, cancellable);
} catch (IOError e) {
throw_dbus_error (e);
}
try {
entry.take_controller_registration (
controller_connection.register_object (ObjectPath.for_agent_session (id), session));
entry.take_node_registration (
node_connection.register_object (ObjectPath.for_agent_message_sink (id), sink));
} catch (IOError e) {
assert_not_reached ();
}
}
}
private async void handle_join_request (ClusterNode node, HostApplicationInfo app, SpawnStartState current_state,
AgentSessionId[] interrupted_sessions, HashTable<string, Variant> options, Cancellable? cancellable,
out SpawnStartState next_state) throws Error, IOError {
if (node.application != null)
throw new Error.PROTOCOL ("Already joined");
if (node.session_provider == null)
throw new Error.PROTOCOL ("Missing session provider");
Variant? acl = options["acl"];
if (acl != null) {
if (!acl.is_of_type (VariantType.STRING_ARRAY))
throw new Error.INVALID_ARGUMENT ("The 'acl' option must be a string array");
ConnectionEntry entry = connections[node.connection_id];
Gee.Set<string>? tags = entry.tags;
if (tags == null) {
tags = new Gee.HashSet<string> ();
entry.tags = tags;
}
tags.add_all_array (acl.get_strv ());
}
foreach (AgentSessionId id in interrupted_sessions) {
AgentSessionEntry? entry = sessions[id];
if (entry == null)
continue;
if (entry.node != null)
throw new Error.PROTOCOL ("Session already claimed");
entry.attach_node (node);
node.sessions.add (id);
}
uint pid = app.pid;
while (node_by_pid.has_key (pid))
pid++;
string real_identifier = app.identifier;
string candidate = real_identifier;
uint serial = 2;
while (node_by_identifier.has_key (candidate))
candidate = "%s[%u]".printf (real_identifier, serial++);
string identifier = candidate;
node.application = new Application (identifier, app.name, pid, app.parameters);
node_by_pid[pid] = node;
node_by_identifier[identifier] = node;
node_joined (node.connection_id, node.application);
if (current_state == SUSPENDED && !spawn_gaters.is_empty) {
var eligible_gaters = all_spawn_gaters_with_access_to (node);
if (eligible_gaters.has_next ()) {
next_state = SUSPENDED;
var spawn = new PendingSpawn (node, pid, identifier, eligible_gaters);
pending_spawn[pid] = spawn;
foreach (ControlChannel controller in spawn.pending_approvers) {
controller.spawn_added (spawn.info);
}
} else {
next_state = RUNNING;
}
} else {
next_state = RUNNING;
}
}
private void notify_spawn_removed (PendingSpawn spawn) {
all_spawn_gaters_with_access_to (spawn.node).foreach (controller => {
controller.spawn_removed (spawn.info);
return true;
});
}
private void on_agent_session_expired (AgentSessionEntry entry) {
sessions.unset (entry.id);
}
private void on_agent_session_closed (AgentSessionId id) {
AgentSessionEntry entry;
if (sessions.unset (id, out entry)) {
ControlChannel? controller = entry.controller;
if (controller != null) {
controller.sessions.remove (id);
controller.agent_session_detached (id, SessionDetachReason.APPLICATION_REQUESTED,
CrashInfo.empty ());
}
}
}
private Gee.Iterator<ClusterNode> all_nodes_accessible_by (ControlChannel requester) {
if (requester.is_local)
return node_by_pid.values.iterator ();
Gee.Set<string>? requester_tags = connections[requester.connection_id].tags;
return node_by_pid.values.filter (node => {
ConnectionEntry entry = connections[node.connection_id];
Gee.Set<string>? acl = entry.tags;
if (acl == null)
return true;
if (requester_tags == null)
return false;
return acl.any_match (tag => requester_tags.contains (tag));
});
}
private ClusterNode? find_node_accessible_by (ControlChannel requester, uint pid) {
ClusterNode? node = node_by_pid[pid];
if (node == null)
return null;
return can_access (node, requester) ? node : null;
}
private Gee.Iterator<ControlChannel> all_spawn_gaters_with_access_to (ClusterNode node) {
Gee.Set<string>? acl = connections[node.connection_id].tags;
if (acl == null)
return spawn_gaters.iterator ();
return spawn_gaters.filter (controller => {
if (controller.is_local)
return true;
Gee.Set<string> tags = connections[controller.connection_id].tags;
if (tags == null)
return false;
return acl.any_match (tag => tags.contains (tag));
});
}
private bool can_access (ClusterNode node, ControlChannel requester) {
if (requester.is_local)
return true;
Gee.Set<string>? acl = connections[node.connection_id].tags;
if (acl == null)
return true;
Gee.Set<string> requester_tags = connections[requester.connection_id].tags;
if (requester_tags == null)
return false;
return acl.any_match (tag => requester_tags.contains (tag));
}
private class PortalHostSessionProvider : Object, HostSessionProvider {
public weak PortalService parent {
get;
construct;
}
public string id {
get { return "portal"; }
}
public string name {
get { return _name; }
}
private string _name = "Portal";
public Variant? icon {
get { return _icon; }
}
private Variant _icon;
public HostSessionProviderKind kind {
get { return HostSessionProviderKind.LOCAL; }
}
private ControlChannel? channel;
public PortalHostSessionProvider (PortalService parent) {
Object (parent: parent);
}
construct {
var builder = new VariantBuilder (VariantType.VARDICT);
builder.add ("{sv}", "format", new Variant.string ("rgba"));
builder.add ("{sv}", "width", new Variant.int64 (16));
builder.add ("{sv}", "height", new Variant.int64 (16));
var image = new Bytes (Base64.decode ("AAAAAAAAAAAAAAAAOjo6Dzo6OhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOjo6TZCHbvlycnL4Ojo6iTo6OhMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOjo6aa6fdv7878f/+/Te/93d3f9xcXH3Ojo6gTo6Og8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOjo6F4KAfv//5Hn//fHK//r6+v/39/f/9/f3/9LS0v9kZGTzOjo6eDo6OgsAAAAAAAAAAAAAAAAAAAAAAAAAADo6Og6Tk5P/zc3N//z8/P/6+vr/8PDw/+7u7v/p6en/9PT0/8jIyP9XV1f2Ojo6SgAAAAAAAAAAAAAAAAAAAAA6OjoIb29v/8HBwf+5ubn/9/f3/+/v7//p6en/+Pj4/+np6f/o6Oj/4ODg/z09PcsAAAAAAAAAAAAAAAAAAAAAAAAAAjMzM1p8fHz/wsLC/7CwsP/x8fH/8/P0/9zc3f/09PT/+vr6/8vLy/9AQEDFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALS0tV2pqav7BwcH/rq6u/+bm5v/09PT/s7Oz/93d3f/R0dL/VVVVygAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAjIyNRWlpa+7+/v/+wsLD/oaGh/4iIiP9NTU7/VVVW/0BAQf89PT61Pj4/BgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABsbG09NTU32urq6/4yMjP9ycnL/Pj4//1BQUf9tbW7/XFxd/z4+P8M+Pj8PAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAExMTTD09PfBzc3P/LCwsvDAwMbVEREX/f3+A/6ioqf9tbW7zPj4/lAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANDQ0vGRkZggAAAAAAAAAAJycnh0NDRP2GhojujIyP4EtLS4k/Pz8YAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAjIyRoRUVFq21tbp5TU1ZUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACkpK10AAAAWAAAABgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="));
builder.add ("{sv}", "image", Variant.new_from_data (new VariantType ("ay"), image.get_data (), true, image));
_icon = builder.end ();
}
public async HostSession create (HostSessionOptions? options, Cancellable? cancellable) throws Error, IOError {
if (channel != null)
throw new Error.INVALID_OPERATION ("Already created");
channel = new ControlChannel (parent);
channel.agent_session_detached.connect (on_agent_session_detached);
return channel;
}
public async void destroy (HostSession host_session, Cancellable? cancellable) throws Error, IOError {
if (host_session != channel)
throw new Error.INVALID_ARGUMENT ("Invalid host session");
channel.agent_session_detached.disconnect (on_agent_session_detached);
HostSession session = channel;
channel.close ();
channel = null;
host_session_detached (session);
}
public async AgentSession link_agent_session (HostSession host_session, AgentSessionId id, AgentMessageSink sink,
Cancellable? cancellable) throws Error, IOError {
if (host_session != channel)
throw new Error.INVALID_ARGUMENT ("Invalid host session");
AgentSessionEntry entry = parent.sessions[id];
if (entry == null)
throw new Error.INVALID_ARGUMENT ("Invalid session ID");
try {
entry.take_node_registration (
entry.node.connection.register_object (ObjectPath.for_agent_message_sink (id), sink));
} catch (IOError e) {
assert_not_reached ();
}
return entry.session;
}
private void on_agent_session_detached (AgentSessionId id, SessionDetachReason reason, CrashInfo crash) {
agent_session_detached (id, reason, crash);
}
}