-
-
Notifications
You must be signed in to change notification settings - Fork 304
Expand file tree
/
Copy pathagent.vala
More file actions
1698 lines (1360 loc) · 47 KB
/
Copy pathagent.vala
File metadata and controls
1698 lines (1360 loc) · 47 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.Agent {
public void main (string agent_parameters, ref Frida.UnloadPolicy unload_policy, void * injector_state) {
if (Runner.shared_instance == null)
Runner.create_and_run (agent_parameters, ref unload_policy, injector_state);
else
Runner.resume_after_transition (ref unload_policy, injector_state);
}
private enum StopReason {
UNLOAD,
PROCESS_TRANSITION
}
private class Runner : Object, ProcessInvader, AgentSessionProvider, ExitHandler, ForkHandler, SpawnHandler {
public static Runner shared_instance = null;
public static Mutex shared_mutex;
private static string? cached_agent_path = null;
private static Gum.MemoryRange cached_agent_range;
public string agent_parameters {
get;
construct;
}
public string? agent_path {
get;
construct;
}
public string? emulated_agent_path {
get;
set;
}
public StopReason stop_reason {
get;
set;
default = UNLOAD;
}
public bool is_eternal {
get {
return _is_eternal;
}
}
private bool _is_eternal = false;
private bool stop_thread_on_unload = true;
private Gum.ThreadId agent_tid;
private void * agent_pthread;
private Thread<bool>? agent_gthread;
private MainContext main_context;
private MainLoop main_loop;
private DBusConnection connection;
private AgentController? controller;
private Error? start_error = null;
private bool unloading = false;
private uint filter_id = 0;
private uint registration_id = 0;
private uint pending_calls = 0;
private Promise<bool> pending_close;
private Gee.Map<AgentSessionId?, LiveAgentSession> sessions =
new Gee.HashMap<AgentSessionId?, LiveAgentSession> (AgentSessionId.hash, AgentSessionId.equal);
private Gee.Map<AgentSessionId?, EmulatedAgentSession> emulated_sessions =
new Gee.HashMap<AgentSessionId?, EmulatedAgentSession> (AgentSessionId.hash, AgentSessionId.equal);
private Gee.Map<DBusConnection, DirectConnection> direct_connections =
new Gee.HashMap<DBusConnection, DirectConnection> ();
private Gee.Map<PortalMembershipId?, PortalClient> portal_clients =
new Gee.HashMap<PortalMembershipId?, PortalClient> (PortalMembershipId.hash, PortalMembershipId.equal);
private uint next_portal_membership_id = 1;
private Gee.ArrayList<Gum.Script> eternalized_scripts = new Gee.ArrayList<Gum.Script> ();
private Gum.MemoryRange agent_range;
private Gum.ScriptBackend? qjs_backend;
private Gum.ScriptBackend? v8_backend;
private ExitMonitor? exit_monitor;
private Gum.Interceptor interceptor;
private Gum.Exceptor? exceptor;
private uint child_gating_subscriber_count = 0;
private ForkMonitor? fork_monitor;
private FileDescriptorGuard fd_guard;
private ThreadListCloaker? thread_list_cloaker;
private FDListCloaker? fd_list_cloaker;
private uint fork_parent_pid;
private uint fork_child_pid;
private HostChildId fork_child_id;
private uint fork_parent_injectee_id;
private uint fork_child_injectee_id;
private Socket fork_child_socket;
private HostChildId specialized_child_id;
private uint specialized_injectee_id;
private string? specialized_pipe_address;
private TransitionRecoveryState transition_recovery_state;
private Mutex transition_mutex;
private Cond transition_cond;
private SpawnMonitor? spawn_monitor;
private ThreadSuspendMonitor? thread_suspend_monitor;
private delegate void CompletionNotify ();
private enum TransitionRecoveryState {
RECOVERING,
RECOVERED
}
private enum ForkActor {
PARENT,
CHILD
}
public static void create_and_run (string agent_parameters, ref Frida.UnloadPolicy unload_policy,
void * opaque_injector_state) {
Environment._init ();
{
Gum.MemoryRange? mapped_range = null;
#if DARWIN
var injector_state = (DarwinInjectorState *) opaque_injector_state;
if (injector_state != null)
mapped_range = injector_state.mapped_range;
#endif
if (cached_agent_path == null) {
cached_agent_range = detect_own_range_and_path (mapped_range, out cached_agent_path);
Gum.Cloak.add_range (cached_agent_range);
}
var fdt_padder = FileDescriptorTablePadder.obtain ();
#if LINUX || FREEBSD
var injector_state = (PosixInjectorState *) opaque_injector_state;
if (injector_state != null) {
fdt_padder.move_descriptor_if_needed (ref injector_state.fifo_fd);
Gum.Cloak.add_file_descriptor (injector_state.fifo_fd);
}
#endif
#if LINUX
var linjector_state = (LinuxInjectorState *) opaque_injector_state;
string? agent_parameters_with_transport_uri = null;
if (linjector_state != null) {
int agent_ctrlfd = linjector_state->agent_ctrlfd;
linjector_state->agent_ctrlfd = -1;
fdt_padder.move_descriptor_if_needed (ref agent_ctrlfd);
Gum.Cloak.add_file_descriptor (agent_ctrlfd);
agent_parameters_with_transport_uri = "socket:%d%s".printf (agent_ctrlfd, agent_parameters);
agent_parameters = agent_parameters_with_transport_uri;
}
#endif
var ignore_scope = new ThreadIgnoreScope (FRIDA_THREAD);
shared_instance = new Runner (agent_parameters, cached_agent_path, cached_agent_range);
try {
shared_instance.run ((owned) fdt_padder);
} catch (Error e) {
GLib.info ("Unable to start agent: %s", e.message);
}
if (shared_instance.stop_reason == PROCESS_TRANSITION) {
#if LINUX || FREEBSD
if (injector_state != null)
Gum.Cloak.remove_file_descriptor (injector_state.fifo_fd);
#endif
unload_policy = DEFERRED;
return;
} else if (shared_instance.is_eternal) {
unload_policy = RESIDENT;
shared_instance.keep_running_eternalized ();
return;
} else {
release_shared_instance ();
}
ignore_scope = null;
}
Environment._deinit ();
}
public static void resume_after_transition (ref Frida.UnloadPolicy unload_policy, void * opaque_injector_state) {
{
#if LINUX || FREEBSD
var injector_state = (PosixInjectorState *) opaque_injector_state;
if (injector_state != null) {
FileDescriptorTablePadder.obtain ().move_descriptor_if_needed (ref injector_state.fifo_fd);
Gum.Cloak.add_file_descriptor (injector_state.fifo_fd);
}
#endif
var ignore_scope = new ThreadIgnoreScope (FRIDA_THREAD);
shared_instance.run_after_transition ();
if (shared_instance.stop_reason == PROCESS_TRANSITION) {
#if LINUX || FREEBSD
if (injector_state != null)
Gum.Cloak.remove_file_descriptor (injector_state.fifo_fd);
#endif
unload_policy = DEFERRED;
return;
} else if (shared_instance.is_eternal) {
unload_policy = RESIDENT;
shared_instance.keep_running_eternalized ();
return;
} else {
release_shared_instance ();
}
ignore_scope = null;
}
Environment._deinit ();
}
private static void release_shared_instance () {
shared_mutex.lock ();
var instance = shared_instance;
shared_instance = null;
shared_mutex.unlock ();
instance = null;
}
private Runner (string agent_parameters, string? agent_path, Gum.MemoryRange agent_range) {
Object (agent_parameters: agent_parameters, agent_path: agent_path);
this.agent_range = agent_range;
}
construct {
agent_tid = Gum.Process.get_current_thread_id ();
agent_pthread = get_current_pthread ();
main_context = MainContext.default ();
main_loop = new MainLoop (main_context);
}
~Runner () {
var interceptor = this.interceptor;
interceptor.begin_transaction ();
disable_child_gating ();
exceptor = null;
exit_monitor = null;
interceptor.end_transaction ();
interceptor.begin_transaction ();
thread_suspend_monitor = null;
invalidate_dbus_context ();
interceptor.end_transaction ();
}
private void run (owned FileDescriptorTablePadder padder) throws Error {
main_context.push_thread_default ();
start.begin ((owned) padder);
main_loop.run ();
main_context.pop_thread_default ();
if (start_error != null)
throw start_error;
}
private async void start (owned FileDescriptorTablePadder padder) {
string[] tokens = agent_parameters.split ("|");
unowned string transport_uri = tokens[0];
bool enable_exceptor = true;
#if DARWIN
enable_exceptor = !Gum.Darwin.query_hardened ();
#endif
bool enable_exit_monitor = true;
bool enable_thread_suspend_monitor = true;
foreach (unowned string option in tokens[1:]) {
if (option == "eternal")
ensure_eternalized ();
else if (option == "sticky")
stop_thread_on_unload = false;
else if (option == "exceptor:off")
enable_exceptor = false;
else if (option == "exit-monitor:off")
enable_exit_monitor = false;
else if (option == "thread-suspend-monitor:off")
enable_thread_suspend_monitor = false;
}
if (!enable_exceptor)
Gum.Exceptor.disable ();
{
var interceptor = Gum.Interceptor.obtain ();
interceptor.begin_transaction ();
if (enable_exit_monitor)
exit_monitor = new ExitMonitor (this, main_context);
if (enable_thread_suspend_monitor)
thread_suspend_monitor = new ThreadSuspendMonitor (this);
this.interceptor = interceptor;
this.exceptor = Gum.Exceptor.obtain ();
interceptor.end_transaction ();
}
try {
yield setup_connection_with_transport_uri (transport_uri);
} catch (Error e) {
start_error = e;
main_loop.quit ();
return;
}
Gum.ScriptBackend.get_scheduler ().push_job_on_js_thread (Priority.DEFAULT, () => {
schedule_idle (start.callback);
});
yield;
padder = null;
}
private void keep_running_eternalized () {
agent_gthread = new Thread<bool> ("frida-eternal-agent", () => {
var ignore_scope = new ThreadIgnoreScope (FRIDA_THREAD);
agent_tid = Gum.Process.get_current_thread_id ();
main_context.push_thread_default ();
main_loop.run ();
main_context.pop_thread_default ();
ignore_scope = null;
return true;
});
}
private bool supports_async_exit () {
// Avoid deadlocking in case a fork() happened that we weren't made aware of.
return Gum.Process.has_thread (agent_tid);
}
private async void prepare_to_exit () {
yield prepare_for_termination (TerminationReason.EXIT);
}
public void prepare_to_exit_sync () {
}
private void run_after_transition () {
agent_tid = Gum.Process.get_current_thread_id ();
agent_pthread = get_current_pthread ();
stop_reason = UNLOAD;
transition_mutex.lock ();
transition_mutex.unlock ();
main_context.push_thread_default ();
main_loop.run ();
main_context.pop_thread_default ();
}
private void prepare_to_fork () {
var fdt_padder = FileDescriptorTablePadder.obtain ();
schedule_idle (() => {
do_prepare_to_fork.begin ();
return false;
});
stop_agent_thread ();
suspend_subsystems ();
fdt_padder = null;
}
private async void do_prepare_to_fork () {
stop_reason = PROCESS_TRANSITION;
#if !WINDOWS
if (controller != null) {
try {
fork_parent_pid = get_process_id ();
fork_child_id = yield controller.prepare_to_fork (fork_parent_pid, null,
out fork_parent_injectee_id, out fork_child_injectee_id, out fork_child_socket);
} catch (GLib.Error e) {
#if ANDROID
error ("Oops, SELinux rule probably missing for your system. Symptom: %s", e.message);
#else
error ("%s", e.message);
#endif
}
}
#endif
main_loop.quit ();
}
private void recover_from_fork_in_parent () {
recover_from_fork (ForkActor.PARENT, null);
}
private void recover_from_fork_in_child (string? identifier) {
recover_from_fork (ForkActor.CHILD, identifier);
}
private void recover_from_fork (ForkActor actor, string? identifier) {
var fdt_padder = FileDescriptorTablePadder.obtain ();
if (actor == PARENT) {
resume_subsystems ();
} else if (actor == CHILD) {
resume_subsystems_in_child ();
fork_child_pid = get_process_id ();
try {
acquire_child_gating ();
} catch (Error e) {
assert_not_reached ();
}
discard_connections ();
}
transition_mutex.lock ();
transition_recovery_state = RECOVERING;
schedule_idle (() => {
recreate_agent_thread_after_fork.begin (actor);
return false;
});
main_context.push_thread_default ();
main_loop.run ();
main_context.pop_thread_default ();
schedule_idle (() => {
finish_recovery_from_fork.begin (actor, identifier);
return false;
});
while (transition_recovery_state != RECOVERED)
transition_cond.wait (transition_mutex);
transition_mutex.unlock ();
fdt_padder = null;
}
private static void suspend_subsystems () {
#if !WINDOWS
GumJS.prepare_to_fork ();
Gum.prepare_to_fork ();
GIOFork.prepare_to_fork ();
GLibFork.prepare_to_fork ();
#endif
}
private static void resume_subsystems () {
#if !WINDOWS
GLibFork.recover_from_fork_in_parent ();
GIOFork.recover_from_fork_in_parent ();
Gum.recover_from_fork_in_parent ();
GumJS.recover_from_fork_in_parent ();
#endif
}
private static void resume_subsystems_in_child () {
#if !WINDOWS
GLibFork.recover_from_fork_in_child ();
GIOFork.recover_from_fork_in_child ();
Gum.recover_from_fork_in_child ();
GumJS.recover_from_fork_in_child ();
#endif
}
private void stop_agent_thread () {
if (agent_gthread != null) {
agent_gthread.join ();
agent_gthread = null;
} else if (agent_pthread != null) {
join_pthread (agent_pthread);
}
agent_pthread = null;
}
private async void recreate_agent_thread_after_fork (ForkActor actor) {
uint pid, injectee_id;
if (actor == PARENT) {
pid = fork_parent_pid;
injectee_id = fork_parent_injectee_id;
} else if (actor == CHILD) {
yield flush_all_sessions ();
if (fork_child_socket != null) {
var stream = SocketConnection.factory_create_connection (fork_child_socket);
try {
yield setup_connection_with_stream (stream);
} catch (Error e) {
assert_not_reached ();
}
}
pid = fork_child_pid;
injectee_id = fork_child_injectee_id;
} else {
assert_not_reached ();
}
if (controller != null) {
try {
yield controller.recreate_agent_thread (pid, injectee_id, null);
} catch (GLib.Error e) {
assert_not_reached ();
}
} else {
agent_gthread = new Thread<bool> ("frida-eternal-agent", () => {
var ignore_scope = new ThreadIgnoreScope (FRIDA_THREAD);
run_after_transition ();
ignore_scope = null;
return true;
});
}
main_loop.quit ();
}
private async void finish_recovery_from_fork (ForkActor actor, string? identifier) {
if (actor == CHILD && controller != null) {
var info = HostChildInfo (fork_child_pid, fork_parent_pid, ChildOrigin.FORK);
if (identifier != null)
info.identifier = identifier;
var controller_proxy = controller as DBusProxy;
var previous_timeout = controller_proxy.get_default_timeout ();
controller_proxy.set_default_timeout (int.MAX);
try {
yield controller.wait_for_permission_to_resume (fork_child_id, info, null);
} catch (GLib.Error e) {
// The connection will/did get closed and we will unload...
}
controller_proxy.set_default_timeout (previous_timeout);
}
if (actor == CHILD)
release_child_gating ();
fork_parent_pid = 0;
fork_child_pid = 0;
fork_child_id = HostChildId (0);
fork_parent_injectee_id = 0;
fork_child_injectee_id = 0;
fork_child_socket = null;
transition_mutex.lock ();
transition_recovery_state = RECOVERED;
transition_cond.signal ();
transition_mutex.unlock ();
}
private void prepare_to_specialize (string identifier) {
schedule_idle (() => {
do_prepare_to_specialize.begin (identifier);
return false;
});
stop_agent_thread ();
discard_connections ();
suspend_subsystems ();
}
private async void do_prepare_to_specialize (string identifier) {
stop_reason = PROCESS_TRANSITION;
if (controller != null) {
try {
specialized_child_id = yield controller.prepare_to_specialize (get_process_id (), identifier, null,
out specialized_injectee_id, out specialized_pipe_address);
} catch (GLib.Error e) {
error ("%s", e.message);
}
}
main_loop.quit ();
}
private void recover_from_specialization (string identifier) {
resume_subsystems ();
transition_mutex.lock ();
transition_recovery_state = RECOVERING;
schedule_idle (() => {
recreate_agent_thread_after_specialization.begin ();
return false;
});
main_context.push_thread_default ();
main_loop.run ();
main_context.pop_thread_default ();
schedule_idle (() => {
finish_recovery_from_specialization.begin (identifier);
return false;
});
while (transition_recovery_state != RECOVERED)
transition_cond.wait (transition_mutex);
transition_mutex.unlock ();
}
private async void recreate_agent_thread_after_specialization () {
if (specialized_pipe_address != null) {
try {
yield setup_connection_with_transport_uri (specialized_pipe_address);
yield controller.recreate_agent_thread (get_process_id (), specialized_injectee_id, null);
} catch (GLib.Error e) {
assert_not_reached ();
}
} else {
agent_gthread = new Thread<bool> ("frida-eternal-agent", () => {
var ignore_scope = new ThreadIgnoreScope (FRIDA_THREAD);
run_after_transition ();
ignore_scope = null;
return true;
});
}
main_loop.quit ();
}
private async void finish_recovery_from_specialization (string identifier) {
if (controller != null) {
uint pid = get_process_id ();
uint parent_pid = pid;
var info = HostChildInfo (pid, parent_pid, ChildOrigin.EXEC);
info.identifier = identifier;
var controller_proxy = controller as DBusProxy;
var previous_timeout = controller_proxy.get_default_timeout ();
controller_proxy.set_default_timeout (int.MAX);
try {
yield controller.wait_for_permission_to_resume (specialized_child_id, info, null);
} catch (GLib.Error e) {
// The connection will/did get closed and we will unload...
}
controller_proxy.set_default_timeout (previous_timeout);
}
specialized_child_id = HostChildId (0);
specialized_injectee_id = 0;
specialized_pipe_address = null;
transition_mutex.lock ();
transition_recovery_state = RECOVERED;
transition_cond.signal ();
transition_mutex.unlock ();
}
private async void prepare_to_exec (HostChildInfo * info) {
yield prepare_for_termination (TerminationReason.EXEC);
if (controller == null)
return;
try {
yield controller.prepare_to_exec (*info, null);
} catch (GLib.Error e) {
}
}
private async void cancel_exec (uint pid) {
unprepare_for_termination ();
if (controller == null)
return;
try {
yield controller.cancel_exec (pid, null);
} catch (GLib.Error e) {
}
}
private async void acknowledge_spawn (HostChildInfo * info, SpawnStartState start_state) {
if (controller == null)
return;
try {
yield controller.acknowledge_spawn (*info, start_state, null);
} catch (GLib.Error e) {
}
}
public SpawnStartState query_current_spawn_state () {
return RUNNING;
}
public Gum.MemoryRange get_memory_range () {
return agent_range;
}
public Gum.ScriptBackend get_script_backend (ScriptRuntime runtime) throws Error {
switch (runtime) {
case DEFAULT:
break;
case QJS:
if (qjs_backend == null) {
qjs_backend = Gum.ScriptBackend.obtain_qjs ();
if (qjs_backend == null) {
throw new Error.NOT_SUPPORTED (
"QuickJS runtime not available due to build configuration");
}
}
return qjs_backend;
case V8:
if (v8_backend == null) {
v8_backend = Gum.ScriptBackend.obtain_v8 ();
if (v8_backend == null) {
throw new Error.NOT_SUPPORTED (
"V8 runtime not available due to build configuration");
}
}
return v8_backend;
}
try {
return get_script_backend (QJS);
} catch (Error e) {
}
return get_script_backend (V8);
}
public Gum.ScriptBackend? get_active_script_backend () {
return (v8_backend != null) ? v8_backend : qjs_backend;
}
private async void open (AgentSessionId id, HashTable<string, Variant> options,
Cancellable? cancellable) throws Error, IOError {
if (unloading)
throw new Error.INVALID_OPERATION ("Agent is unloading");
var opts = SessionOptions._deserialize (options);
AgentMessageSink sink;
try {
sink = yield connection.get_proxy (null, ObjectPath.for_agent_message_sink (id), DO_NOT_LOAD_PROPERTIES,
cancellable);
} catch (IOError e) {
throw_dbus_error (e);
}
if (opts.realm == EMULATED) {
string? path = opts.emulated_agent_path;
if (path == null)
throw new Error.NOT_SUPPORTED ("Emulated realm is not supported on this OS");
if (emulated_agent_path == null)
emulated_agent_path = path;
AgentSessionProvider emulated_provider = yield get_emulated_provider (cancellable);
var emulated_opts = new SessionOptions ();
emulated_opts.persist_timeout = opts.persist_timeout;
try {
yield emulated_provider.open (id, emulated_opts._serialize (), cancellable);
} catch (GLib.Error e) {
throw_dbus_error (e);
}
var emulated_connection = ((DBusProxy) emulated_provider).get_connection ();
var emulated_session = new EmulatedAgentSession (emulated_connection);
string session_path = ObjectPath.for_agent_session (id);
string sink_path = ObjectPath.for_agent_message_sink (id);
AgentSession session;
try {
session = yield emulated_connection.get_proxy (null, session_path, DO_NOT_LOAD_PROPERTIES,
cancellable);
} catch (IOError e) {
throw_dbus_error (e);
}
try {
emulated_session.session_registration_id = connection.register_object (session_path, session);
emulated_session.sink_registration_id = emulated_connection.register_object (sink_path, sink);
} catch (IOError e) {
assert_not_reached ();
}
emulated_sessions[id] = emulated_session;
return;
}
MainContext dbus_context = yield get_dbus_context ();
var session = new LiveAgentSession (this, id, opts.persist_timeout, sink, dbus_context);
sessions[id] = session;
session.closed.connect (on_session_closed);
session.script_eternalized.connect (on_script_eternalized);
try {
session.registration_id = connection.register_object (ObjectPath.for_agent_session (id),
(AgentSession) session);
} catch (IOError io_error) {
assert_not_reached ();
}
opened (id);
}
private void detach_emulated_session (EmulatedAgentSession session) {
connection.unregister_object (session.session_registration_id);
session.connection.unregister_object (session.sink_registration_id);
}
private async void close_all_sessions () {
uint pending = 1;
var handlers = new Gee.HashMap<BaseAgentSession, ulong> ();
CompletionNotify on_complete = () => {
pending--;
if (pending == 0)
schedule_idle (close_all_sessions.callback);
};
foreach (var session in sessions.values.to_array ()) {
pending++;
handlers[session] = session.closed.connect (session => {
session.disconnect (handlers[session]);
on_complete ();
});
session.close.begin (null);
}
on_complete ();
yield;
assert (sessions.is_empty);
on_complete = null;
}
private async void flush_all_sessions () {
uint pending = 1;
CompletionNotify on_complete = () => {
pending--;
if (pending == 0)
schedule_idle (flush_all_sessions.callback);
};
foreach (var session in sessions.values.to_array ()) {
pending++;
flush_session.begin (session, on_complete);
}
on_complete ();
yield;
on_complete = null;
}
private async void flush_session (LiveAgentSession session, CompletionNotify on_complete) {
yield session.flush ();
on_complete ();
}
private void on_session_closed (BaseAgentSession base_session) {
LiveAgentSession session = (LiveAgentSession) base_session;
closed (session.id);
unregister_session (session);
session.script_eternalized.disconnect (on_script_eternalized);
session.closed.disconnect (on_session_closed);
sessions.unset (session.id);
foreach (var dc in direct_connections.values) {
if (dc.session == session) {
detach_and_steal_direct_dbus_connection (dc.connection);
break;
}
}
}
private void unregister_session (LiveAgentSession session) {
var id = session.registration_id;
if (id != 0) {
connection.unregister_object (id);
session.registration_id = 0;
}
}
private void on_script_eternalized (Gum.Script script) {
eternalized_scripts.add (script);
ensure_eternalized ();
}
#if !WINDOWS
private async void migrate (AgentSessionId id, Socket to_socket, Cancellable? cancellable) throws Error, IOError {
if (emulated_sessions.has_key (id)) {
AgentSessionProvider emulated_provider = yield get_emulated_provider (cancellable);
try {
yield emulated_provider.migrate (id, to_socket, cancellable);
} catch (GLib.Error e) {
throw_dbus_error (e);
}
return;
}
if (!sessions.has_key (id))
throw new Error.INVALID_ARGUMENT ("Invalid session ID");
var session = sessions[id];
var dc = new DirectConnection (session);
DBusConnection connection;
AgentMessageSink sink;
try {
connection = yield new DBusConnection (SocketConnection.factory_create_connection (to_socket), null,
DELAY_MESSAGE_PROCESSING, null, cancellable);
sink = yield connection.get_proxy (null, ObjectPath.for_agent_message_sink (id), DO_NOT_LOAD_PROPERTIES,
cancellable);
} catch (GLib.Error e) {
throw new Error.TRANSPORT ("%s", e.message);
}
dc.connection = connection;
try {
dc.registration_id = connection.register_object (ObjectPath.for_agent_session (id), (AgentSession) session);
} catch (IOError io_error) {
assert_not_reached ();
}
session.message_sink = sink;
connection.start_message_processing ();
this.connection.unregister_object (session.registration_id);
session.registration_id = 0;
direct_connections[connection] = dc;
connection.on_closed.connect (on_direct_connection_closed);
}
#endif
private void on_direct_connection_closed (DBusConnection connection, bool remote_peer_vanished, GLib.Error? error) {
var dc = detach_and_steal_direct_dbus_connection (connection);
dc.session.close.begin (null);
}
private DirectConnection detach_and_steal_direct_dbus_connection (DBusConnection connection) {
connection.on_closed.disconnect (on_direct_connection_closed);
DirectConnection dc;
bool found = direct_connections.unset (connection, out dc);
assert (found);
connection.unregister_object (dc.registration_id);
return dc;
}
private async void unload (Cancellable? cancellable) throws Error, IOError {
if (unloading)
throw new Error.INVALID_OPERATION ("Agent is already unloading");
unloading = true;
perform_unload.begin ();
}