-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathcog-launcher.c
More file actions
1608 lines (1398 loc) · 60.8 KB
/
cog-launcher.c
File metadata and controls
1608 lines (1398 loc) · 60.8 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
/*
* cog-launcher.c
* Copyright (C) 2021 Igalia S.L.
* Copyright (C) 2017-2018 Adrian Perez <aperez@igalia.com>
*
* SPDX-License-Identifier: MIT
*/
#include "cog-launcher.h"
#include <glib-unix.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#define HAVE_WEBKIT_NETWORK_PROXY_API WEBKIT_CHECK_VERSION(2, 32, 0)
#define HAVE_WEBKIT_AUTOPLAY WEBKIT_CHECK_VERSION(2, 30, 0)
enum webprocess_fail_action {
WEBPROCESS_FAIL_UNKNOWN = 0,
WEBPROCESS_FAIL_ERROR_PAGE,
WEBPROCESS_FAIL_EXIT,
WEBPROCESS_FAIL_EXIT_OK,
WEBPROCESS_FAIL_RESTART,
};
static struct {
char *home_uri;
union {
char *config_file;
GKeyFile *key_file;
};
gboolean version;
gboolean print_appid;
gboolean doc_viewer;
gdouble scale_factor;
gdouble device_scale_factor;
union {
GStrv dir_handlers;
GHashTable *handler_map;
};
GStrv arguments;
char *background_color;
char *platform_params;
union {
char *platform_name;
};
union {
char *filter_path;
WebKitUserContentFilter *filter;
};
union {
char *action_name;
enum webprocess_fail_action action_id;
} on_failure;
char *web_extensions_dir;
gboolean ignore_tls_errors;
#if !COG_USE_WPE2
gboolean enable_sandbox;
#endif
gboolean automation;
#if HAVE_WEBKIT_NETWORK_PROXY_API
char *proxy;
gchar **ignore_hosts;
#endif /* HAVE_WEBKIT_NETWORK_PROXY_API */
gboolean disable_key_bindings;
#if HAVE_WEBKIT_AUTOPLAY
WebKitAutoplayPolicy autoplay_policy;
#endif
} s_options = {
.scale_factor = 1.0,
.device_scale_factor = 1.0,
#if HAVE_WEBKIT_AUTOPLAY
.autoplay_policy = WEBKIT_AUTOPLAY_ALLOW_WITHOUT_SOUND,
#endif
};
#if !GLIB_CHECK_VERSION(2, 56, 0)
typedef void (*GClearHandleFunc)(guint handle_id);
# undef g_clear_handle_id
void
g_clear_handle_id(guint *tag_ptr, GClearHandleFunc clear_func)
{
guint _handle_id;
_handle_id = *tag_ptr;
if (_handle_id > 0) {
*tag_ptr = 0;
if (clear_func != NULL)
clear_func(_handle_id);
}
}
#endif
#if !GLIB_CHECK_VERSION(2, 58, 0)
# define G_SOURCE_FUNC(f) ((GSourceFunc) (void (*)(void))(f))
#endif
enum {
PROP_0,
PROP_AUTOMATED,
};
/**
* CogLauncher:
*
* Main application object.
*
* Wraps a [class@CogShell] into a [class@Gio.Application], and provides
* actions which can be remotely activated using the
* `org.freedesktop.Application` D-Bus interface.
*/
struct _CogLauncher {
GApplication parent;
CogShell *shell;
gboolean allow_all_requests;
gboolean automated;
WebKitSettings *web_settings;
#if COG_USE_WPE2
WebKitNetworkSession *network_session;
#else
WebKitWebsiteDataManager *web_data_manager;
#endif
#if COG_HAVE_MEM_PRESSURE
WebKitMemoryPressureSettings *web_mem_settings;
WebKitMemoryPressureSettings *net_mem_settings;
#endif /* COG_HAVE_MEM_PRESSURE */
guint sigint_source;
guint sigterm_source;
CogViewport *viewport;
};
G_DEFINE_TYPE(CogLauncher, cog_launcher, G_TYPE_APPLICATION)
static WebKitWebView *
cog_launcher_get_visible_view(CogLauncher *self)
{
g_return_val_if_fail(COG_IS_LAUNCHER(self), NULL);
return (WebKitWebView *) cog_viewport_get_visible_view(self->viewport);
}
static void
on_action_quit(G_GNUC_UNUSED GAction *action, G_GNUC_UNUSED GVariant *param, CogLauncher *launcher)
{
g_application_quit(G_APPLICATION(launcher));
}
static void
on_action_prev(G_GNUC_UNUSED GAction *action, G_GNUC_UNUSED GVariant *param, CogLauncher *launcher)
{
webkit_web_view_go_back(cog_launcher_get_visible_view(launcher));
}
static void
on_action_next(G_GNUC_UNUSED GAction *action, G_GNUC_UNUSED GVariant *param, CogLauncher *launcher)
{
webkit_web_view_go_forward(cog_launcher_get_visible_view(launcher));
}
static void
on_action_reload(G_GNUC_UNUSED GAction *action, G_GNUC_UNUSED GVariant *param, CogLauncher *launcher)
{
webkit_web_view_reload(cog_launcher_get_visible_view(launcher));
}
static void
on_action_open(G_GNUC_UNUSED GAction *action, GVariant *param, CogLauncher *launcher)
{
g_return_if_fail(g_variant_is_of_type(param, G_VARIANT_TYPE_STRING));
webkit_web_view_load_uri(cog_launcher_get_visible_view(launcher), g_variant_get_string(param, NULL));
}
static gboolean
on_signal_quit(CogLauncher *launcher)
{
g_application_quit(G_APPLICATION(launcher));
return G_SOURCE_CONTINUE;
}
static gboolean
on_permission_request(G_GNUC_UNUSED WebKitWebView *web_view, WebKitPermissionRequest *request, CogLauncher *launcher)
{
if (launcher->allow_all_requests)
webkit_permission_request_allow(request);
else
webkit_permission_request_deny(request);
return TRUE;
}
static void
cog_launcher_add_action(CogLauncher *launcher,
const char *name,
void (*callback)(GAction *, GVariant *, CogLauncher *),
const GVariantType *param_type)
{
g_assert(COG_IS_LAUNCHER(launcher));
g_assert_nonnull(name);
g_assert_nonnull(callback);
GSimpleAction *action = g_simple_action_new(name, param_type);
g_signal_connect(action, "activate", G_CALLBACK(callback), launcher);
g_action_map_add_action(G_ACTION_MAP(launcher), G_ACTION(action));
}
static void
cog_launcher_open(GApplication *application, GFile **files, int n_files, const char *hint)
{
g_assert(n_files);
if (n_files > 1)
g_warning("Requested opening %i files, opening only the first one", n_files);
g_autofree char *uri = g_file_get_uri(files[0]);
webkit_web_view_load_uri(cog_launcher_get_visible_view(COG_LAUNCHER(application)), uri);
}
static void *
on_web_view_create(WebKitWebView *web_view, WebKitNavigationAction *action)
{
webkit_web_view_load_request(web_view, webkit_navigation_action_get_request(action));
return NULL;
}
static WebKitWebView *
on_automation_session_create_web_view(WebKitAutomationSession *session, CogLauncher *launcher)
{
static bool first_time = true;
if (first_time) {
first_time = false;
return (WebKitWebView *) cog_viewport_get_visible_view(launcher->viewport);
}
#if HAVE_WEBKIT_AUTOPLAY
g_autoptr(WebKitWebsitePolicies) website_policies =
webkit_website_policies_new_with_policies("autoplay", s_options.autoplay_policy, NULL);
#endif /* HAVE_WEBKIT_AUTOPLAY */
g_autoptr(WebKitWebView) new_view =
(WebKitWebView *) cog_view_new("settings", cog_shell_get_web_settings(launcher->shell), "web-context",
cog_shell_get_web_context(launcher->shell), "is-controlled-by-automation", TRUE,
"zoom-level", s_options.scale_factor, "use-key-bindings", FALSE,
#if COG_USE_WPE2
"network-session", launcher->network_session,
#endif /* COG_USE_WPE2 */
#if HAVE_WEBKIT_AUTOPLAY
"website-policies", website_policies,
#endif /* HAVE_WEBKIT_AUTOPLAY */
NULL);
// FIXME New window should be new viewport
cog_viewport_add(launcher->viewport, (CogView *) new_view);
return new_view;
}
static void
on_automation_started(WebKitWebContext *context, WebKitAutomationSession *session, CogLauncher *launcher)
{
g_autoptr(WebKitApplicationInfo) info = webkit_application_info_new();
webkit_application_info_set_version(info, WEBKIT_MAJOR_VERSION, WEBKIT_MINOR_VERSION, WEBKIT_MICRO_VERSION);
webkit_automation_session_set_application_info(session, info);
g_signal_connect(session, "create-web-view", G_CALLBACK(on_automation_session_create_web_view), launcher);
}
static void
cog_launcher_set_preferred_languages(CogLauncher *self)
{
const gchar *const *locales;
const gchar **languages;
guint i, n, length;
/* build Accept-Language from locale, filtering out encodings */
locales = g_get_language_names();
length = g_strv_length((gchar **) g_get_language_names());
languages = g_new0(const gchar *, length + 1);
for (n = 0, i = 0; locales[i]; i++) {
const gchar *lang = locales[i];
if (!strcmp(lang, "C") || !strcmp(lang, "POSIX") || strchr(lang, '.'))
continue;
languages[n++] = lang;
}
webkit_web_context_set_preferred_languages(cog_shell_get_web_context(self->shell), languages);
g_free(languages);
}
static void
cog_launcher_startup(GApplication *application)
{
G_APPLICATION_CLASS(cog_launcher_parent_class)->startup(application);
/*
* We have to manually call g_application_hold(), otherwise nothing will
* prevent GApplication from shutting down immediately after startup.
*/
g_application_hold(application);
cog_init(s_options.platform_name, NULL);
CogLauncher *self = COG_LAUNCHER(application);
self->shell = g_object_new(
COG_TYPE_SHELL, "name", g_get_prgname(), "automated", self->automated, "web-settings", self->web_settings,
#if !COG_USE_WPE2
"web-data-manager", self->web_data_manager,
#endif
#if COG_HAVE_MEM_PRESSURE
"web-memory-settings", self->web_mem_settings, "network-memory-settings", self->net_mem_settings,
#endif /* COG_HAVE_MEM_PRESSURE */
NULL);
if (s_options.key_file) {
g_autoptr(GKeyFile) key_file = g_steal_pointer(&s_options.key_file);
g_object_set(self->shell, "config-file", key_file, NULL);
}
g_autoptr(GError) error = NULL;
if (!cog_platform_setup(cog_platform_get(), self->shell, s_options.platform_params, &error))
g_error("Cannot configure platform: %s", error->message);
WebKitWebContext *web_context = cog_shell_get_web_context(self->shell);
g_signal_connect(web_context, "automation-started", G_CALLBACK(on_automation_started), self);
if (s_options.doc_viewer)
webkit_web_context_set_cache_model(web_context, WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
#if COG_USE_WPE2
if (s_options.web_extensions_dir)
webkit_web_context_set_web_process_extensions_directory(web_context, s_options.web_extensions_dir);
#else
if (s_options.web_extensions_dir)
webkit_web_context_set_web_extensions_directory(web_context, s_options.web_extensions_dir);
webkit_web_context_set_sandbox_enabled(web_context, s_options.enable_sandbox);
#endif
g_clear_pointer(&s_options.web_extensions_dir, g_free);
g_object_set(self->shell, "device-scale-factor", s_options.device_scale_factor, NULL);
cog_launcher_set_preferred_languages(self);
if (s_options.handler_map) {
GHashTableIter i;
void *key, *value;
g_hash_table_iter_init(&i, s_options.handler_map);
while (g_hash_table_iter_next(&i, &key, &value)) {
cog_shell_set_request_handler(self->shell, key, value);
g_hash_table_iter_remove(&i);
}
g_clear_pointer(&s_options.handler_map, g_hash_table_destroy);
}
#if COG_USE_WPE2
if (!self->automated) {
webkit_network_session_set_tls_errors_policy(self->network_session,
s_options.ignore_tls_errors ? WEBKIT_TLS_ERRORS_POLICY_IGNORE
: WEBKIT_TLS_ERRORS_POLICY_FAIL);
}
#elif WEBKIT_CHECK_VERSION(2, 32, 0)
webkit_website_data_manager_set_tls_errors_policy(cog_launcher_get_web_data_manager(self),
s_options.ignore_tls_errors ? WEBKIT_TLS_ERRORS_POLICY_IGNORE
: WEBKIT_TLS_ERRORS_POLICY_FAIL);
#else
webkit_web_context_set_tls_errors_policy(cog_shell_get_web_context(self->shell),
s_options.ignore_tls_errors ? WEBKIT_TLS_ERRORS_POLICY_IGNORE
: WEBKIT_TLS_ERRORS_POLICY_FAIL);
#endif
#if HAVE_WEBKIT_AUTOPLAY
g_autoptr(WebKitWebsitePolicies) website_policies =
webkit_website_policies_new_with_policies("autoplay", s_options.autoplay_policy, NULL);
#endif
g_autoptr(CogView) view =
cog_view_new("settings", cog_shell_get_web_settings(self->shell), "web-context",
cog_shell_get_web_context(self->shell), "is-controlled-by-automation", self->automated,
"zoom-level", s_options.scale_factor, "use-key-bindings", !s_options.disable_key_bindings,
#if COG_USE_WPE2
"network-session", self->network_session,
#endif
#if HAVE_WEBKIT_AUTOPLAY
"website-policies", website_policies,
#endif
NULL);
cog_platform_init_web_view(cog_platform_get(), WEBKIT_WEB_VIEW(view));
g_signal_connect(view, "permission-request", G_CALLBACK(on_permission_request), self);
g_signal_connect(view, "create", G_CALLBACK(on_web_view_create), NULL);
if (s_options.filter) {
WebKitUserContentManager *manager = webkit_web_view_get_user_content_manager(WEBKIT_WEB_VIEW(view));
webkit_user_content_manager_add_filter(manager, s_options.filter);
g_clear_pointer(&s_options.filter, webkit_user_content_filter_unref);
}
if (s_options.background_color != NULL) {
WebKitColor color;
gboolean has_valid_color = webkit_color_parse(&color, s_options.background_color);
if (has_valid_color)
webkit_web_view_set_background_color(WEBKIT_WEB_VIEW(view), &color);
else
g_error("'%s' doesn't represent a valid #RRGGBBAA or CSS color format.", s_options.background_color);
}
g_clear_pointer(&s_options.background_color, g_free);
switch (s_options.on_failure.action_id) {
case WEBPROCESS_FAIL_ERROR_PAGE:
// Nothing else needed, the default error handler (connected
// below) already implements displaying an error page.
break;
case WEBPROCESS_FAIL_EXIT:
cog_web_view_connect_web_process_terminated_exit_handler(WEBKIT_WEB_VIEW(view), EXIT_FAILURE);
break;
case WEBPROCESS_FAIL_EXIT_OK:
cog_web_view_connect_web_process_terminated_exit_handler(WEBKIT_WEB_VIEW(view), EXIT_SUCCESS);
break;
case WEBPROCESS_FAIL_RESTART:
// TODO: Un-hardcode the 5 retries per second.
cog_web_view_connect_web_process_terminated_restart_handler(WEBKIT_WEB_VIEW(view), 5, 1000);
break;
default:
g_assert_not_reached();
}
cog_web_view_connect_default_progress_handlers(WEBKIT_WEB_VIEW(view));
cog_web_view_connect_default_error_handlers(WEBKIT_WEB_VIEW(view));
webkit_web_view_load_uri(WEBKIT_WEB_VIEW(view), s_options.home_uri);
g_clear_pointer(&s_options.home_uri, g_free);
self->viewport = cog_viewport_new();
cog_viewport_add(self->viewport, view);
}
static void
cog_launcher_activate(GApplication *application)
{
/* GApplication warns if activate is not handled. Usually this signal will focus a
window but this doesn't apply to many of our platforms so this is a noop. */
G_APPLICATION_CLASS(cog_launcher_parent_class)->activate(application);
}
static void
cog_launcher_dispose(GObject *object)
{
CogLauncher *launcher = COG_LAUNCHER(object);
g_clear_object(&launcher->shell);
g_clear_object(&launcher->viewport);
g_clear_handle_id(&launcher->sigint_source, g_source_remove);
g_clear_handle_id(&launcher->sigterm_source, g_source_remove);
g_clear_object(&launcher->web_settings);
#if COG_USE_WPE2
g_clear_object(&launcher->network_session);
#else
g_clear_object(&launcher->web_data_manager);
#endif
#if COG_HAVE_MEM_PRESSURE
g_clear_pointer(&launcher->web_mem_settings, webkit_memory_pressure_settings_free);
g_clear_pointer(&launcher->net_mem_settings, webkit_memory_pressure_settings_free);
#endif /* COG_HAVE_MEM_PRESSURE */
G_OBJECT_CLASS(cog_launcher_parent_class)->dispose(object);
}
#if COG_DBUS_SYSTEM_BUS
static void
on_system_bus_acquired(GDBusConnection *connection, const char *name, void *userdata)
{
g_autofree char *object_path =
cog_appid_to_dbus_object_path(g_application_get_application_id(G_APPLICATION(userdata)));
g_autoptr(GError) error = NULL;
if (!g_dbus_connection_export_action_group(connection, object_path, G_ACTION_GROUP(userdata), &error))
g_warning("Cannot expose remote control interface to system bus: %s", error->message);
}
static void
on_system_bus_name_acquired(G_GNUC_UNUSED GDBusConnection *connection, const char *name, G_GNUC_UNUSED void *userdata)
{
g_message("Acquired D-Bus well-known name %s", name);
}
static void
on_system_bus_name_lost(GDBusConnection *connection, const char *name, G_GNUC_UNUSED void *userdata)
{
if (connection) {
g_message("Lost D-Bus well-known name %s", name);
} else {
g_message("Lost D-Bus connection to system bus");
}
}
#endif // COG_DBUS_SYSTEM_BUS
#ifndef COG_DEFAULT_APPID
# define COG_DEFAULT_APPID "com.igalia." COG_DEFAULT_APPNAME
#endif /* !COG_DEFAULT_APPID */
static gboolean
option_entry_parse_cookie_jar(const char *option G_GNUC_UNUSED,
const char *value,
CogLauncher *launcher,
GError **error)
{
if (strcmp(value, "help") == 0) {
g_autoptr(GEnumClass) enum_class = g_type_class_ref(WEBKIT_TYPE_COOKIE_PERSISTENT_STORAGE);
for (unsigned i = 0; i < enum_class->n_values; i++)
g_print("%s\n", enum_class->values[i].value_nick);
exit(EXIT_SUCCESS);
g_assert_not_reached();
}
#if COG_USE_WPE2
if (launcher->automated) {
g_set_error_literal(error,
G_OPTION_ERROR,
G_OPTION_ERROR_BAD_VALUE,
"Cannot set persistent cookies in automation mode");
return FALSE;
}
#endif
g_autofree char *cookie_jar_path = NULL;
g_autofree char *format_name = g_strdup(value);
char *path = strchr(format_name, ':');
if (path) {
*path++ = '\0';
g_autoptr(GFile) cookie_jar = g_file_new_for_path(path);
cookie_jar_path = g_file_get_path(cookie_jar);
if (!g_file_is_native(cookie_jar)) {
g_set_error(error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE, "Path '%s' is not local", cookie_jar_path);
return FALSE;
}
GFileType file_type = g_file_query_file_type(cookie_jar, G_FILE_QUERY_INFO_NONE, NULL);
switch (file_type) {
case G_FILE_TYPE_UNKNOWN: // Does not exist yet, will be created.
case G_FILE_TYPE_REGULAR:
break;
default:
g_set_error(error,
G_OPTION_ERROR,
G_OPTION_ERROR_BAD_VALUE,
"Cannot use %s path '%s' for cookies",
cog_g_enum_get_nick(G_TYPE_FILE_TYPE, file_type),
cookie_jar_path);
return FALSE;
}
}
const GEnumValue *enum_value = cog_g_enum_get_value(WEBKIT_TYPE_COOKIE_PERSISTENT_STORAGE, format_name);
if (!enum_value) {
g_set_error(error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE, "Invalid cookie jar format '%s'", value);
return FALSE;
}
if (!cookie_jar_path) {
g_autofree char *file_name = g_strconcat("cookies.", format_name, NULL);
cookie_jar_path = g_build_filename(g_get_user_data_dir(), g_get_prgname(), file_name, NULL);
}
webkit_cookie_manager_set_persistent_storage(
#if COG_USE_WPE2
webkit_network_session_get_cookie_manager(launcher->network_session),
#else
webkit_website_data_manager_get_cookie_manager(launcher->web_data_manager),
#endif
cookie_jar_path, enum_value->value);
return TRUE;
}
typedef struct {
GMainLoop *loop;
WebKitCookieAcceptPolicy result;
} GetCookieAcceptPolicyData;
static void
on_got_cookie_accept_policy(WebKitCookieManager *manager, GAsyncResult *result, GetCookieAcceptPolicyData *data)
{
data->result = webkit_cookie_manager_get_accept_policy_finish(manager, result, NULL);
g_main_loop_quit(data->loop);
}
static WebKitCookieAcceptPolicy
cookie_manager_get_accept_policy(WebKitCookieManager *cookie_manager)
{
g_autoptr(GMainLoop) loop = g_main_loop_new(NULL, FALSE);
GetCookieAcceptPolicyData data = {.loop = loop};
webkit_cookie_manager_get_accept_policy(cookie_manager,
NULL, // GCancellable
(GAsyncReadyCallback) on_got_cookie_accept_policy,
&data);
g_main_loop_run(loop);
return data.result;
}
static gboolean
option_entry_parse_cookie_store(const char *option G_GNUC_UNUSED,
const char *value,
CogLauncher *launcher,
GError **error)
{
#if COG_USE_WPE2
WebKitCookieManager *cookie_manager =
launcher->network_session ? webkit_network_session_get_cookie_manager(launcher->network_session) : NULL;
#else
WebKitCookieManager *cookie_manager = webkit_website_data_manager_get_cookie_manager(launcher->web_data_manager);
#endif
if (strcmp(value, "help") == 0) {
const WebKitCookieAcceptPolicy default_mode = cookie_manager ? cookie_manager_get_accept_policy(cookie_manager)
: WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY;
g_autoptr(GEnumClass) enum_class = g_type_class_ref(WEBKIT_TYPE_COOKIE_ACCEPT_POLICY);
for (unsigned i = 0; i < enum_class->n_values; i++) {
const char *format = (enum_class->values[i].value == default_mode) ? "%s (default)\n" : "%s\n";
g_print(format, enum_class->values[i].value_nick);
}
exit(EXIT_SUCCESS);
g_assert_not_reached();
}
#if COG_USE_WPE2
if (!cookie_manager) {
g_set_error_literal(error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
"Cannot set cookie storing mode in automation mode");
return FALSE;
}
#endif
const GEnumValue *enum_value = cog_g_enum_get_value(WEBKIT_TYPE_COOKIE_ACCEPT_POLICY, value);
if (!enum_value) {
g_set_error(error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE, "Invalid cookie storing mode '%s'", value);
return FALSE;
}
webkit_cookie_manager_set_accept_policy(cookie_manager, enum_value->value);
return TRUE;
}
typedef void (*CookieFlagCallback)(SoupCookie *, gboolean);
static void
cookie_set_session(SoupCookie *cookie, gboolean session)
{
if (session)
soup_cookie_set_expires(cookie, NULL);
}
static inline CookieFlagCallback
option_entry_parse_cookie_add_get_flag_callback(const char *name)
{
static const struct {
const char *name;
CookieFlagCallback callback;
} flag_map[] = {
{"httponly", soup_cookie_set_http_only},
{"secure", soup_cookie_set_secure},
{"session", cookie_set_session},
};
for (unsigned i = 0; i < G_N_ELEMENTS(flag_map); i++)
if (strcmp(name, flag_map[i].name) == 0)
return flag_map[i].callback;
return NULL;
}
static void
on_cookie_added(WebKitCookieManager *cookie_manager, GAsyncResult *result, GMainLoop *loop)
{
g_autoptr(GError) error = NULL;
if (!webkit_cookie_manager_add_cookie_finish(cookie_manager, result, &error)) {
g_warning("Error setting cookie: %s", error->message);
}
g_main_loop_quit(loop);
}
static gboolean
option_entry_parse_cookie_add(const char *option G_GNUC_UNUSED,
const char *value,
CogLauncher *launcher,
GError **error G_GNUC_UNUSED)
{
#if COG_USE_WPE2
if (launcher->automated) {
g_set_error_literal(error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE, "Cannot add cookies in automation mode");
return FALSE;
}
#endif
g_autoptr(GMainLoop) loop = NULL;
g_autoptr(SoupCookie) cookie = NULL;
g_autofree char *domain = g_strdup(value);
char *flagstr = strchr(domain, ':');
if (!flagstr)
goto bad_format;
*flagstr++ = '\0';
char *contents = strchr(flagstr, ':');
if (!contents)
goto bad_format;
// The domain might include a port in the domain, in that
// case skip forward to the next colon after the port number.
if (g_ascii_isdigit(contents[1])) {
if (!(contents = strchr(contents + 1, ':')))
goto bad_format;
}
*contents++ = '\0';
// The contents of the cookie cannot be empty.
if (!contents[0])
goto bad_format;
cookie = soup_cookie_parse(contents, NULL);
if (!cookie)
goto bad_format;
soup_cookie_set_domain(cookie, domain);
// Go through the flags.
if (flagstr && flagstr[0]) {
g_auto(GStrv) flags = g_strsplit(flagstr, ",", -1);
for (unsigned i = 0; flags[i] != NULL; i++) {
// Skip the optional leading +/- signs.
const char *flag = flags[i];
gboolean flag_value = flag[0] != '-';
if (flag[0] == '+' || flag[0] == '-')
flag++;
const CookieFlagCallback flag_callback = option_entry_parse_cookie_add_get_flag_callback(flag);
if (!flag_callback) {
g_set_error(error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE, "Invalid cookie flag '%s'", flag);
return FALSE;
}
(*flag_callback)(cookie, flag_value);
}
}
// XXX: If the cookie has no path defined, conversion to WebKit's
// internal format will fail and the WebProcess will spit ouy
// a critical error -- and the cookie won't be set. Workaround
// the issue while this is not fixed inside WebKit.
if (!soup_cookie_get_path(cookie))
soup_cookie_set_path(cookie, "/");
// Adding a cookie is an asynchronous operation, so spin up an
// event loop until to block until the operation completes.
loop = g_main_loop_new(NULL, FALSE);
#if COG_USE_WPE2
WebKitCookieManager *cookie_manager = webkit_network_session_get_cookie_manager(launcher->network_session);
#else
WebKitCookieManager *cookie_manager = webkit_website_data_manager_get_cookie_manager(launcher->web_data_manager);
#endif
webkit_cookie_manager_add_cookie(cookie_manager,
cookie,
NULL, // GCancellable
(GAsyncReadyCallback) on_cookie_added,
loop);
g_main_loop_run(loop);
return TRUE;
bad_format:
g_set_error(error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE, "Invalid cookie specification '%s'", value);
return FALSE;
}
static GOptionEntry s_cookies_options[] = {
{
.long_name = "cookie-store",
.arg = G_OPTION_ARG_CALLBACK,
.arg_data = option_entry_parse_cookie_store,
.description = "How to store cookies. Pass 'help' for a list of modes.",
.arg_description = "MODE",
},
{
.long_name = "cookie-add",
.arg = G_OPTION_ARG_CALLBACK,
.arg_data = option_entry_parse_cookie_add,
.description = "Pre-set a cookie, available flags: httponly, secure, session.",
.arg_description = "DOMAIN:[FLAG,-FLAG,..]:CONTENTS",
},
{
.long_name = "cookie-jar",
.arg = G_OPTION_ARG_CALLBACK,
.arg_data = option_entry_parse_cookie_jar,
.description = "Enable persisting cookies to disk. Pass 'help' for a list of formats.",
.arg_description = "FORMAT[:PATH]",
},
{NULL}};
static void
cog_launcher_add_web_cookies_option_entries(CogLauncher *launcher)
{
g_return_if_fail(COG_IS_LAUNCHER(launcher));
g_autoptr(GOptionGroup) option_group =
g_option_group_new("cookies",
"Options which control storage and bahviour of cookies.\n",
"Show options for cookies",
launcher,
NULL);
g_option_group_add_entries(option_group, s_cookies_options);
g_application_add_option_group(G_APPLICATION(launcher), g_steal_pointer(&option_group));
}
#if COG_HAVE_MEM_PRESSURE
static WebKitMemoryPressureSettings *
mem_settings_pick(CogLauncher *launcher, const char *option)
{
if (strncmp(option, "--web-", 6) == 0)
return launcher->web_mem_settings;
if (strncmp(option, "--net-", 6) == 0)
return launcher->net_mem_settings;
g_assert_not_reached();
return NULL;
}
static gboolean
option_entry_parse_mem_limit(const char *option, const char *value, CogLauncher *launcher, GError **error)
{
errno = 0;
char *endp = NULL;
const uint64_t v = g_ascii_strtoull(value, &endp, 0);
if (errno || *endp != '\0' || v <= 0) {
g_set_error(error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE, "Invalid memory size value '%s'", value);
return FALSE;
}
webkit_memory_pressure_settings_set_memory_limit(mem_settings_pick(launcher, option), v);
return TRUE;
}
static gboolean
parse_mem_double(const char *value, double *r, gboolean up_to_one, GError **error)
{
errno = 0;
char *endp = NULL;
const double v = g_ascii_strtod(value, &endp);
if (errno || *endp != '\0' || v <= 0.0 || (up_to_one && v >= 1.0)) {
g_set_error(error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE, "Invalid value '%s'", value);
return FALSE;
}
*r = v;
return TRUE;
}
static void
set_mem_double(CogLauncher *launcher, const char *option, double v)
{
static const struct {
const char *name;
void (*set)(WebKitMemoryPressureSettings *, double);
} settings[] = {
{"check-interval", webkit_memory_pressure_settings_set_poll_interval},
{"conservative-threshold", webkit_memory_pressure_settings_set_conservative_threshold},
{"strict-threshold", webkit_memory_pressure_settings_set_strict_threshold},
{"kill-threshold", webkit_memory_pressure_settings_set_kill_threshold},
};
for (unsigned i = 0; i < G_N_ELEMENTS(settings); i++) {
if (strcmp(settings[i].name, option + 6) == 0) {
settings[i].set(mem_settings_pick(launcher, option), v);
return;
}
}
g_assert_not_reached();
}
static gboolean
option_entry_parse_mem_double(const char *option, const char *value, CogLauncher *launcher, GError **error)
{
double v;
if (!parse_mem_double(value, &v, FALSE, error))
return FALSE;
set_mem_double(launcher, option, v);
return TRUE;
}
static gboolean
option_entry_parse_mem_double_01(const char *option, const char *value, CogLauncher *launcher, GError **error)
{
double v;
if (!parse_mem_double(value, &v, TRUE, error))
return FALSE;
set_mem_double(launcher, option, v);
return TRUE;
}
static void
cog_launcher_add_mem_pressure_option_entries(CogLauncher *self)
{
static const GOptionEntry entries[] = {{
.long_name = "web-mem-limit",
.arg = G_OPTION_ARG_CALLBACK,
.arg_data = option_entry_parse_mem_limit,
.description = "Maximum amount of memory to use, in MiB.",
.arg_description = "SIZE",
},
{
.long_name = "web-check-interval",
.arg = G_OPTION_ARG_CALLBACK,
.arg_data = option_entry_parse_mem_double,
.description = "Interval of time between memory usage checks.",
.arg_description = "SECONDS",
},
{
.long_name = "web-conservative-threshold",
.arg = G_OPTION_ARG_CALLBACK,
.arg_data = option_entry_parse_mem_double_01,
.description = "Conservative threshold (default: 0.33).",
.arg_description = "(0..1)",
},
{
.long_name = "web-strict-threshold",
.arg = G_OPTION_ARG_CALLBACK,
.arg_data = option_entry_parse_mem_double_01,
.description = "Strict threshold (default: 0.5).",
.arg_description = "(0..1)",
},
{
.long_name = "web-kill-threshold",
.arg = G_OPTION_ARG_CALLBACK,
.arg_data = option_entry_parse_mem_double,
.description = "Kill threshold (default: 0).",
.arg_description = "(0..",
},
{
.long_name = "net-mem-limit",
.arg = G_OPTION_ARG_CALLBACK,
.arg_data = option_entry_parse_mem_limit,
.description = "Maximum amount of memory to use, in MiB.",
.arg_description = "SIZE",
},
{
.long_name = "net-check-interval",
.arg = G_OPTION_ARG_CALLBACK,
.arg_data = option_entry_parse_mem_double,
.description = "Interval of time between memory usage checks.",
.arg_description = "SECONDS",
},
{
.long_name = "net-conservative-threshold",
.arg = G_OPTION_ARG_CALLBACK,
.arg_data = option_entry_parse_mem_double_01,
.description = "Conservative threshold (default: 0.33).",
.arg_description = "(0..1)",
},
{
.long_name = "net-strict-threshold",
.arg = G_OPTION_ARG_CALLBACK,
.arg_data = option_entry_parse_mem_double_01,
.description = "Strict threshold (default: 0.5).",
.arg_description = "(0..1)",
},
{
.long_name = "net-kill-threshold",
.arg = G_OPTION_ARG_CALLBACK,
.arg_data = option_entry_parse_mem_double,
.description = "Kill threshold (default: 0).",
.arg_description = "(0..",
},
{NULL}};
GOptionGroup *group =
g_option_group_new("memory-limits",
"These options allow configuring WebKit's memory pressure handling mechanism.\n"
"\n"
" In particular, a limit for the maximum amount of memory to use can be set,\n"
" and thresholds relative to the limit which determine at which points memory\n"
" will be reclaimed. The conservative threshold is typically lower when reached\n"
" memory will be reclaimed; the strict threshold works in the same way but the\n"
" process is more aggressive. The kill threshold configures when worker processes\n"
" will be forcibly killed. Note that if there is no memory limit set, the other\n"
" settings are ignored.\n",
"Options to configure memory usage limits",
self,
NULL);
g_option_group_add_entries(group, entries);
g_application_add_option_group(G_APPLICATION(self), group);