Fix synchronization issue with atoms
[surf.git] / surf.c
1 /* See LICENSE file for copyright and license details.
2  *
3  * To understand surf, start reading main().
4  */
5 #include <sys/file.h>
6 #include <sys/types.h>
7 #include <sys/wait.h>
8 #include <glib.h>
9 #include <libgen.h>
10 #include <limits.h>
11 #include <pwd.h>
12 #include <regex.h>
13 #include <signal.h>
14 #include <stdarg.h>
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #include <unistd.h>
19
20 #include <gdk/gdk.h>
21 #include <gdk/gdkkeysyms.h>
22 #include <gdk/gdkx.h>
23 #include <glib/gstdio.h>
24 #include <gtk/gtk.h>
25 #include <gtk/gtkx.h>
26 #include <gcr/gcr.h>
27 #include <JavaScriptCore/JavaScript.h>
28 #include <webkit2/webkit2.h>
29 #include <X11/X.h>
30 #include <X11/Xatom.h>
31
32 #include "arg.h"
33
34 #define LENGTH(x)               (sizeof(x) / sizeof(x[0]))
35 #define CLEANMASK(mask)         (mask & (MODKEY|GDK_SHIFT_MASK))
36 #define SETB(p, s)              [p] = { { .b = s }, }
37 #define SETI(p, s)              [p] = { { .i = s }, }
38 #define SETV(p, s)              [p] = { { .v = s }, }
39 #define SETF(p, s)              [p] = { { .f = s }, }
40 #define FSETB(p, s)             [p] = { { .b = s }, 1 }
41 #define FSETI(p, s)             [p] = { { .i = s }, 1 }
42 #define FSETV(p, s)             [p] = { { .v = s }, 1 }
43 #define FSETF(p, s)             [p] = { { .f = s }, 1 }
44 #define CSETB(p, s)             [p] = (Parameter){ { .b = s }, 1 }
45 #define CSETI(p, s)             [p] = (Parameter){ { .i = s }, 1 }
46 #define CSETV(p, s)             [p] = (Parameter){ { .v = s }, 1 }
47 #define CSETF(p, s)             [p] = (Parameter){ { .f = s }, 1 }
48
49 enum { AtomFind, AtomGo, AtomUri, AtomLast };
50
51 enum {
52         OnDoc   = WEBKIT_HIT_TEST_RESULT_CONTEXT_DOCUMENT,
53         OnLink  = WEBKIT_HIT_TEST_RESULT_CONTEXT_LINK,
54         OnImg   = WEBKIT_HIT_TEST_RESULT_CONTEXT_IMAGE,
55         OnMedia = WEBKIT_HIT_TEST_RESULT_CONTEXT_MEDIA,
56         OnEdit  = WEBKIT_HIT_TEST_RESULT_CONTEXT_EDITABLE,
57         OnBar   = WEBKIT_HIT_TEST_RESULT_CONTEXT_SCROLLBAR,
58         OnSel   = WEBKIT_HIT_TEST_RESULT_CONTEXT_SELECTION,
59         OnAny   = OnDoc | OnLink | OnImg | OnMedia | OnEdit | OnBar | OnSel,
60 };
61
62 typedef enum {
63         AcceleratedCanvas,
64         CaretBrowsing,
65         Certificate,
66         CookiePolicies,
67         DiskCache,
68         DefaultCharset,
69         DNSPrefetch,
70         FontSize,
71         FrameFlattening,
72         Geolocation,
73         HideBackground,
74         Inspector,
75         Java,
76         JavaScript,
77         KioskMode,
78         LoadImages,
79         MediaManualPlay,
80         Plugins,
81         PreferredLanguages,
82         RunInFullscreen,
83         ScrollBars,
84         ShowIndicators,
85         SiteQuirks,
86         SmoothScrolling,
87         SpellChecking,
88         SpellLanguages,
89         StrictTLS,
90         Style,
91         ZoomLevel,
92         ParameterLast,
93 } ParamName;
94
95 typedef union {
96         int b;
97         int i;
98         float f;
99         const void *v;
100 } Arg;
101
102 typedef struct {
103         Arg val;
104         int force;
105 } Parameter;
106
107 typedef struct Client {
108         GtkWidget *win;
109         WebKitWebView *view;
110         WebKitWebInspector *inspector;
111         WebKitFindController *finder;
112         WebKitHitTestResult *mousepos;
113         GTlsCertificate *cert, *failedcert;
114         GTlsCertificateFlags tlserr;
115         Window xid;
116         int progress, fullscreen, https, insecure, errorpage;
117         const char *title, *overtitle, *targeturi;
118         const char *needle;
119         struct Client *next;
120 } Client;
121
122 typedef struct {
123         guint mod;
124         guint keyval;
125         void (*func)(Client *c, const Arg *a);
126         const Arg arg;
127 } Key;
128
129 typedef struct {
130         unsigned int target;
131         unsigned int mask;
132         guint button;
133         void (*func)(Client *c, const Arg *a, WebKitHitTestResult *h);
134         const Arg arg;
135         unsigned int stopevent;
136 } Button;
137
138 typedef struct {
139         const char *uri;
140         Parameter config[ParameterLast];
141         regex_t re;
142 } UriParameters;
143
144 typedef struct {
145         char *regex;
146         char *file;
147         regex_t re;
148 } SiteSpecific;
149
150 /* Surf */
151 static void usage(void);
152 static void die(const char *errstr, ...);
153 static void setup(void);
154 static void sigchld(int unused);
155 static void sighup(int unused);
156 static char *buildfile(const char *path);
157 static char *buildpath(const char *path);
158 static const char *getuserhomedir(const char *user);
159 static const char *getcurrentuserhomedir(void);
160 static Client *newclient(Client *c);
161 static void loaduri(Client *c, const Arg *a);
162 static const char *geturi(Client *c);
163 static void setatom(Client *c, int a, const char *v);
164 static const char *getatom(Client *c, int a);
165 static void updatetitle(Client *c);
166 static void gettogglestats(Client *c);
167 static void getpagestats(Client *c);
168 static WebKitCookieAcceptPolicy cookiepolicy_get(void);
169 static char cookiepolicy_set(const WebKitCookieAcceptPolicy p);
170 static void seturiparameters(Client *c, const char *uri);
171 static void setparameter(Client *c, int refresh, ParamName p, const Arg *a);
172 static const char *getcert(const char *uri);
173 static void setcert(Client *c, const char *file);
174 static const char *getstyle(const char *uri);
175 static void setstyle(Client *c, const char *file);
176 static void runscript(Client *c);
177 static void evalscript(Client *c, const char *jsstr, ...);
178 static void updatewinid(Client *c);
179 static void handleplumb(Client *c, const char *uri);
180 static void newwindow(Client *c, const Arg *a, int noembed);
181 static void spawn(Client *c, const Arg *a);
182 static void destroyclient(Client *c);
183 static void cleanup(void);
184
185 /* GTK/WebKit */
186 static WebKitWebView *newview(Client *c, WebKitWebView *rv);
187 static void initwebextensions(WebKitWebContext *wc, Client *c);
188 static GtkWidget *createview(WebKitWebView *v, WebKitNavigationAction *a,
189                              Client *c);
190 static gboolean buttonreleased(GtkWidget *w, GdkEvent *e, Client *c);
191 static GdkFilterReturn processx(GdkXEvent *xevent, GdkEvent *event,
192                                 gpointer d);
193 static gboolean winevent(GtkWidget *w, GdkEvent *e, Client *c);
194 static void showview(WebKitWebView *v, Client *c);
195 static GtkWidget *createwindow(Client *c);
196 static gboolean loadfailedtls(WebKitWebView *v, gchar *uri,
197                               GTlsCertificate *cert,
198                               GTlsCertificateFlags err, Client *c);
199 static void loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c);
200 static void progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c);
201 static void titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c);
202 static void mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h,
203                                guint modifiers, Client *c);
204 static gboolean permissionrequested(WebKitWebView *v,
205                                     WebKitPermissionRequest *r, Client *c);
206 static gboolean decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
207                              WebKitPolicyDecisionType dt, Client *c);
208 static void decidenavigation(WebKitPolicyDecision *d, Client *c);
209 static void decidenewwindow(WebKitPolicyDecision *d, Client *c);
210 static void decideresource(WebKitPolicyDecision *d, Client *c);
211 static void insecurecontent(WebKitWebView *v, WebKitInsecureContentEvent e,
212                             Client *c);
213 static void downloadstarted(WebKitWebContext *wc, WebKitDownload *d,
214                             Client *c);
215 static void responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c);
216 static void download(Client *c, WebKitURIResponse *r);
217 static void closeview(WebKitWebView *v, Client *c);
218 static void destroywin(GtkWidget* w, Client *c);
219
220 /* Hotkeys */
221 static void pasteuri(GtkClipboard *clipboard, const char *text, gpointer d);
222 static void reload(Client *c, const Arg *a);
223 static void print(Client *c, const Arg *a);
224 static void showcert(Client *c, const Arg *a);
225 static void clipboard(Client *c, const Arg *a);
226 static void zoom(Client *c, const Arg *a);
227 static void scroll(Client *c, const Arg *a);
228 static void navigate(Client *c, const Arg *a);
229 static void stop(Client *c, const Arg *a);
230 static void toggle(Client *c, const Arg *a);
231 static void togglefullscreen(Client *c, const Arg *a);
232 static void togglecookiepolicy(Client *c, const Arg *a);
233 static void toggleinspector(Client *c, const Arg *a);
234 static void find(Client *c, const Arg *a);
235
236 /* Buttons */
237 static void clicknavigate(Client *c, const Arg *a, WebKitHitTestResult *h);
238 static void clicknewwindow(Client *c, const Arg *a, WebKitHitTestResult *h);
239 static void clickexternplayer(Client *c, const Arg *a, WebKitHitTestResult *h);
240
241 static char winid[64];
242 static char togglestats[12];
243 static char pagestats[2];
244 static Atom atoms[AtomLast];
245 static Window embed;
246 static int showxid;
247 static int cookiepolicy;
248 static Display *dpy;
249 static Client *clients;
250 static GdkDevice *gdkkb;
251 static char *stylefile;
252 static const char *useragent;
253 static Parameter *curconfig;
254 char *argv0;
255
256 /* configuration, allows nested code to access above variables */
257 #include "config.h"
258
259 void
260 usage(void)
261 {
262         die("usage: surf [-bBdDfFgGiIkKmMnNpPsStTvwxX]\n"
263             "[-a cookiepolicies ] [-c cookiefile] [-C stylefile] [-e xid]\n"
264             "[-r scriptfile] [-u useragent] [-z zoomlevel] [uri]\n");
265 }
266
267 void
268 die(const char *errstr, ...)
269 {
270         va_list ap;
271
272         va_start(ap, errstr);
273         vfprintf(stderr, errstr, ap);
274         va_end(ap);
275         exit(1);
276 }
277
278 void
279 setup(void)
280 {
281         GdkDisplay *gdpy;
282         int i, j;
283
284         /* clean up any zombies immediately */
285         sigchld(0);
286         if (signal(SIGHUP, sighup) == SIG_ERR)
287                 die("Can't install SIGHUP handler");
288
289         if (!(dpy = XOpenDisplay(NULL)))
290                 die("Can't open default display");
291
292         /* atoms */
293         atoms[AtomFind] = XInternAtom(dpy, "_SURF_FIND", False);
294         atoms[AtomGo] = XInternAtom(dpy, "_SURF_GO", False);
295         atoms[AtomUri] = XInternAtom(dpy, "_SURF_URI", False);
296
297         gtk_init(NULL, NULL);
298
299         gdpy = gdk_display_get_default();
300
301         curconfig = defconfig;
302
303         /* dirs and files */
304         cookiefile = buildfile(cookiefile);
305         scriptfile = buildfile(scriptfile);
306         cachedir   = buildpath(cachedir);
307         certdir    = buildpath(certdir);
308
309         gdkkb = gdk_seat_get_keyboard(gdk_display_get_default_seat(gdpy));
310
311         for (i = 0; i < LENGTH(certs); ++i) {
312                 if (!regcomp(&(certs[i].re), certs[i].regex, REG_EXTENDED)) {
313                         certs[i].file = g_strconcat(certdir, "/", certs[i].file,
314                                                     NULL);
315                 } else {
316                         fprintf(stderr, "Could not compile regex: %s\n",
317                                 certs[i].regex);
318                         certs[i].regex = NULL;
319                 }
320         }
321
322         if (!stylefile) {
323                 styledir = buildpath(styledir);
324                 for (i = 0; i < LENGTH(styles); ++i) {
325                         if (!regcomp(&(styles[i].re), styles[i].regex,
326                             REG_EXTENDED)) {
327                                 styles[i].file = g_strconcat(styledir, "/",
328                                                     styles[i].file, NULL);
329                         } else {
330                                 fprintf(stderr, "Could not compile regex: %s\n",
331                                         styles[i].regex);
332                                 styles[i].regex = NULL;
333                         }
334                 }
335                 g_free(styledir);
336         } else {
337                 stylefile = buildfile(stylefile);
338         }
339
340         for (i = 0; i < LENGTH(uriparams); ++i) {
341                 if (!regcomp(&(uriparams[i].re), uriparams[i].uri,
342                     REG_EXTENDED)) {
343                         /* copy default parameters if they are not already set
344                          * or if they are forced */
345                         for (j = 0; j < ParameterLast; ++j) {
346                                 if (!uriparams[i].config[j].force ||
347                                     defconfig[j].force)
348                                         uriparams[i].config[j] = defconfig[j];
349                         }
350                 } else {
351                         fprintf(stderr, "Could not compile regex: %s\n",
352                                 uriparams[i].uri);
353                         uriparams[i].uri = NULL;
354                 }
355         }
356 }
357
358 void
359 sigchld(int unused)
360 {
361         if (signal(SIGCHLD, sigchld) == SIG_ERR)
362                 die("Can't install SIGCHLD handler");
363         while (waitpid(-1, NULL, WNOHANG) > 0)
364                 ;
365 }
366
367 void
368 sighup(int unused)
369 {
370         Arg a = { .b = 0 };
371         Client *c;
372
373         for (c = clients; c; c = c->next)
374                 reload(c, &a);
375 }
376
377 char *
378 buildfile(const char *path)
379 {
380         char *dname, *bname, *bpath, *fpath;
381         FILE *f;
382
383         dname = g_path_get_dirname(path);
384         bname = g_path_get_basename(path);
385
386         bpath = buildpath(dname);
387         g_free(dname);
388
389         fpath = g_build_filename(bpath, bname, NULL);
390         g_free(bpath);
391         g_free(bname);
392
393         if (!(f = fopen(fpath, "a")))
394                 die("Could not open file: %s\n", fpath);
395
396         g_chmod(fpath, 0600); /* always */
397         fclose(f);
398
399         return fpath;
400 }
401
402 static const char*
403 getuserhomedir(const char *user)
404 {
405         struct passwd *pw = getpwnam(user);
406
407         if (!pw)
408                 die("Can't get user %s login information.\n", user);
409
410         return pw->pw_dir;
411 }
412
413 static const char*
414 getcurrentuserhomedir(void)
415 {
416         const char *homedir;
417         const char *user;
418         struct passwd *pw;
419
420         homedir = getenv("HOME");
421         if (homedir)
422                 return homedir;
423
424         user = getenv("USER");
425         if (user)
426                 return getuserhomedir(user);
427
428         pw = getpwuid(getuid());
429         if (!pw)
430                 die("Can't get current user home directory\n");
431
432         return pw->pw_dir;
433 }
434
435 char *
436 buildpath(const char *path)
437 {
438         char *apath, *name, *p, *fpath;
439         const char *homedir;
440
441         if (path[0] == '~') {
442                 if (path[1] == '/' || path[1] == '\0') {
443                         p = (char *)&path[1];
444                         homedir = getcurrentuserhomedir();
445                 } else {
446                         if ((p = strchr(path, '/')))
447                                 name = g_strndup(&path[1], --p - path);
448                         else
449                                 name = g_strdup(&path[1]);
450
451                         homedir = getuserhomedir(name);
452                         g_free(name);
453                 }
454                 apath = g_build_filename(homedir, p, NULL);
455         } else {
456                 apath = g_strdup(path);
457         }
458
459         /* creating directory */
460         if (g_mkdir_with_parents(apath, 0700) < 0)
461                 die("Could not access directory: %s\n", apath);
462
463         fpath = realpath(apath, NULL);
464         g_free(apath);
465
466         return fpath;
467 }
468
469 Client *
470 newclient(Client *rc)
471 {
472         Client *c;
473
474         if (!(c = calloc(1, sizeof(Client))))
475                 die("Cannot malloc!\n");
476
477         c->next = clients;
478         clients = c;
479
480         c->progress = 100;
481         c->view = newview(c, rc ? rc->view : NULL);
482
483         return c;
484 }
485
486 void
487 loaduri(Client *c, const Arg *a)
488 {
489         struct stat st;
490         char *url, *path;
491         const char *uri = a->v;
492
493         if (g_strcmp0(uri, "") == 0)
494                 return;
495
496         if (g_str_has_prefix(uri, "http://")  ||
497             g_str_has_prefix(uri, "https://") ||
498             g_str_has_prefix(uri, "file://")  ||
499             g_str_has_prefix(uri, "about:")) {
500                 url = g_strdup(uri);
501         } else if (!stat(uri, &st) && (path = realpath(uri, NULL))) {
502                 url = g_strdup_printf("file://%s", path);
503                 free(path);
504         } else {
505                 url = g_strdup_printf("http://%s", uri);
506         }
507
508         setatom(c, AtomUri, url);
509
510         if (strcmp(url, geturi(c)) == 0) {
511                 reload(c, a);
512         } else {
513                 webkit_web_view_load_uri(c->view, url);
514                 updatetitle(c);
515         }
516
517         g_free(url);
518 }
519
520 const char *
521 geturi(Client *c)
522 {
523         const char *uri;
524
525         if (!(uri = webkit_web_view_get_uri(c->view)))
526                 uri = "about:blank";
527         return uri;
528 }
529
530 void
531 setatom(Client *c, int a, const char *v)
532 {
533         XChangeProperty(dpy, c->xid,
534                         atoms[a], XA_STRING, 8, PropModeReplace,
535                         (unsigned char *)v, strlen(v) + 1);
536         XSync(dpy, False);
537 }
538
539 const char *
540 getatom(Client *c, int a)
541 {
542         static char buf[BUFSIZ];
543         Atom adummy;
544         int idummy;
545         unsigned long ldummy;
546         unsigned char *p = NULL;
547
548         XSync(dpy, False);
549         XGetWindowProperty(dpy, c->xid, atoms[a], 0L, BUFSIZ, False, XA_STRING,
550                            &adummy, &idummy, &ldummy, &ldummy, &p);
551         if (p)
552                 strncpy(buf, (char *)p, LENGTH(buf) - 1);
553         else
554                 buf[0] = '\0';
555         XFree(p);
556
557         return buf;
558 }
559
560 void
561 updatetitle(Client *c)
562 {
563         char *title;
564         const char *name = c->overtitle ? c->overtitle :
565                            c->title ? c->title : "";
566
567         if (curconfig[ShowIndicators].val.b) {
568                 gettogglestats(c);
569                 getpagestats(c);
570
571                 if (c->progress != 100)
572                         title = g_strdup_printf("[%i%%] %s:%s | %s",
573                                 c->progress, togglestats, pagestats, name);
574                 else
575                         title = g_strdup_printf("%s:%s | %s",
576                                 togglestats, pagestats, name);
577
578                 gtk_window_set_title(GTK_WINDOW(c->win), title);
579                 g_free(title);
580         } else {
581                 gtk_window_set_title(GTK_WINDOW(c->win), name);
582         }
583 }
584
585 void
586 gettogglestats(Client *c)
587 {
588         togglestats[0] = cookiepolicy_set(cookiepolicy_get());
589         togglestats[1] = curconfig[CaretBrowsing].val.b ?   'C' : 'c';
590         togglestats[2] = curconfig[Geolocation].val.b ?     'G' : 'g';
591         togglestats[3] = curconfig[DiskCache].val.b ?       'D' : 'd';
592         togglestats[4] = curconfig[LoadImages].val.b ?      'I' : 'i';
593         togglestats[5] = curconfig[JavaScript].val.b ?      'S' : 's';
594         togglestats[6] = curconfig[Plugins].val.b ?         'V' : 'v';
595         togglestats[7] = curconfig[Style].val.b ?           'M' : 'm';
596         togglestats[8] = curconfig[FrameFlattening].val.b ? 'F' : 'f';
597         togglestats[9] = curconfig[Certificate].val.b ?     'X' : 'x';
598         togglestats[10] = curconfig[StrictTLS].val.b ?      'T' : 't';
599         togglestats[11] = '\0';
600 }
601
602 void
603 getpagestats(Client *c)
604 {
605         if (c->https)
606                 pagestats[0] = (c->tlserr || c->insecure) ?  'U' : 'T';
607         else
608                 pagestats[0] = '-';
609         pagestats[1] = '\0';
610 }
611
612 WebKitCookieAcceptPolicy
613 cookiepolicy_get(void)
614 {
615         switch (((char *)curconfig[CookiePolicies].val.v)[cookiepolicy]) {
616         case 'a':
617                 return WEBKIT_COOKIE_POLICY_ACCEPT_NEVER;
618         case '@':
619                 return WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY;
620         default: /* fallthrough */
621         case 'A':
622                 return WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS;
623         }
624 }
625
626 char
627 cookiepolicy_set(const WebKitCookieAcceptPolicy p)
628 {
629         switch (p) {
630         case WEBKIT_COOKIE_POLICY_ACCEPT_NEVER:
631                 return 'a';
632         case WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY:
633                 return '@';
634         default: /* fallthrough */
635         case WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS:
636                 return 'A';
637         }
638 }
639
640 void
641 seturiparameters(Client *c, const char *uri)
642 {
643         Parameter *newconfig = NULL;
644         int i;
645
646         for (i = 0; i < LENGTH(uriparams); ++i) {
647                 if (uriparams[i].uri &&
648                     !regexec(&(uriparams[i].re), uri, 0, NULL, 0)) {
649                         newconfig = uriparams[i].config;
650                         break;
651                 }
652         }
653
654         if (!newconfig)
655                 newconfig = defconfig;
656         if (newconfig == curconfig)
657                 return;
658
659         for (i = 0; i < ParameterLast; ++i) {
660                 if (defconfig[i].force)
661                         continue;
662                 if (newconfig[i].force)
663                         setparameter(c, 0, i, &newconfig[i].val);
664                 else if (curconfig[i].force)
665                         setparameter(c, 0, i, &defconfig[i].val);
666         }
667
668         curconfig = newconfig;
669 }
670
671 void
672 setparameter(Client *c, int refresh, ParamName p, const Arg *a)
673 {
674         GdkRGBA bgcolor = { 0 };
675         WebKitSettings *s = webkit_web_view_get_settings(c->view);
676
677         switch (p) {
678         case AcceleratedCanvas:
679                 webkit_settings_set_enable_accelerated_2d_canvas(s, a->b);
680                 break;
681         case CaretBrowsing:
682                 webkit_settings_set_enable_caret_browsing(s, a->b);
683                 refresh = 0;
684                 break;
685         case Certificate:
686                 if (a->b)
687                         setcert(c, geturi(c));
688                 return; /* do not update */
689         case CookiePolicies:
690                 webkit_cookie_manager_set_accept_policy(
691                     webkit_web_context_get_cookie_manager(
692                     webkit_web_view_get_context(c->view)),
693                     cookiepolicy_get());
694                 refresh = 0;
695                 break;
696         case DiskCache:
697                 webkit_web_context_set_cache_model(
698                     webkit_web_view_get_context(c->view), a->b ?
699                     WEBKIT_CACHE_MODEL_WEB_BROWSER :
700                     WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
701                 return; /* do not update */
702         case DefaultCharset:
703                 webkit_settings_set_default_charset(s, a->v);
704                 return; /* do not update */
705         case DNSPrefetch:
706                 webkit_settings_set_enable_dns_prefetching(s, a->b);
707                 return; /* do not update */
708         case FontSize:
709                 webkit_settings_set_default_font_size(s, a->i);
710                 return; /* do not update */
711         case FrameFlattening:
712                 webkit_settings_set_enable_frame_flattening(s, a->b);
713                 break;
714         case Geolocation:
715                 refresh = 0;
716                 break;
717         case HideBackground:
718                 if (a->b)
719                         webkit_web_view_set_background_color(c->view, &bgcolor);
720                 return; /* do not update */
721         case Inspector:
722                 webkit_settings_set_enable_developer_extras(s, a->b);
723                 return; /* do not update */
724         case Java:
725                 webkit_settings_set_enable_java(s, a->b);
726                 return; /* do not update */
727         case JavaScript:
728                 webkit_settings_set_enable_javascript(s, a->b);
729                 break;
730         case KioskMode:
731                 return; /* do nothing */
732         case LoadImages:
733                 webkit_settings_set_auto_load_images(s, a->b);
734                 break;
735         case MediaManualPlay:
736                 webkit_settings_set_media_playback_requires_user_gesture(s, a->b);
737                 break;
738         case Plugins:
739                 webkit_settings_set_enable_plugins(s, a->b);
740                 break;
741         case PreferredLanguages:
742                 return; /* do nothing */
743         case RunInFullscreen:
744                 return; /* do nothing */
745         case ScrollBars:
746                 /* Disabled until we write some WebKitWebExtension for
747                  * manipulating the DOM directly.
748                 enablescrollbars = !enablescrollbars;
749                 evalscript(c, "document.documentElement.style.overflow = '%s'",
750                     enablescrollbars ? "auto" : "hidden");
751                 */
752                 return; /* do not update */
753         case ShowIndicators:
754                 break;
755         case SmoothScrolling:
756                 webkit_settings_set_enable_smooth_scrolling(s, a->b);
757                 return; /* do not update */
758         case SiteQuirks:
759                 webkit_settings_set_enable_site_specific_quirks(s, a->b);
760                 break;
761         case SpellChecking:
762                 webkit_web_context_set_spell_checking_enabled(
763                     webkit_web_view_get_context(c->view), a->b);
764                 return; /* do not update */
765         case SpellLanguages:
766                 return; /* do nothing */
767         case StrictTLS:
768                 webkit_web_context_set_tls_errors_policy(
769                     webkit_web_view_get_context(c->view), a->b ?
770                     WEBKIT_TLS_ERRORS_POLICY_FAIL :
771                     WEBKIT_TLS_ERRORS_POLICY_IGNORE);
772                 break;
773         case Style:
774                 if (a->b)
775                         setstyle(c, getstyle(geturi(c)));
776                 else
777                         webkit_user_content_manager_remove_all_style_sheets(
778                             webkit_web_view_get_user_content_manager(c->view));
779                 refresh = 0;
780                 break;
781         case ZoomLevel:
782                 webkit_web_view_set_zoom_level(c->view, a->f);
783                 return; /* do not update */
784         default:
785                 return; /* do nothing */
786         }
787
788         updatetitle(c);
789         if (refresh)
790                 reload(c, a);
791 }
792
793 const char *
794 getcert(const char *uri)
795 {
796         int i;
797
798         for (i = 0; i < LENGTH(certs); ++i) {
799                 if (certs[i].regex &&
800                     !regexec(&(certs[i].re), uri, 0, NULL, 0))
801                         return certs[i].file;
802         }
803
804         return NULL;
805 }
806
807 void
808 setcert(Client *c, const char *uri)
809 {
810         const char *file = getcert(uri);
811         char *host;
812         GTlsCertificate *cert;
813
814         if (!file)
815                 return;
816
817         if (!(cert = g_tls_certificate_new_from_file(file, NULL))) {
818                 fprintf(stderr, "Could not read certificate file: %s\n", file);
819                 return;
820         }
821
822         if ((uri = strstr(uri, "https://"))) {
823                 uri += sizeof("https://") - 1;
824                 host = g_strndup(uri, strchr(uri, '/') - uri);
825                 webkit_web_context_allow_tls_certificate_for_host(
826                     webkit_web_view_get_context(c->view), cert, host);
827                 g_free(host);
828         }
829
830         g_object_unref(cert);
831
832 }
833
834 const char *
835 getstyle(const char *uri)
836 {
837         int i;
838
839         if (stylefile)
840                 return stylefile;
841
842         for (i = 0; i < LENGTH(styles); ++i) {
843                 if (styles[i].regex &&
844                     !regexec(&(styles[i].re), uri, 0, NULL, 0))
845                         return styles[i].file;
846         }
847
848         return "";
849 }
850
851 void
852 setstyle(Client *c, const char *file)
853 {
854         gchar *style;
855
856         if (!g_file_get_contents(file, &style, NULL, NULL)) {
857                 fprintf(stderr, "Could not read style file: %s\n", file);
858                 return;
859         }
860
861         webkit_user_content_manager_add_style_sheet(
862             webkit_web_view_get_user_content_manager(c->view),
863             webkit_user_style_sheet_new(style,
864             WEBKIT_USER_CONTENT_INJECT_ALL_FRAMES,
865             WEBKIT_USER_STYLE_LEVEL_USER,
866             NULL, NULL));
867
868         g_free(style);
869 }
870
871 void
872 runscript(Client *c)
873 {
874         gchar *script;
875         gsize l;
876
877         if (g_file_get_contents(scriptfile, &script, &l, NULL) && l)
878                 evalscript(c, script);
879         g_free(script);
880 }
881
882 void
883 evalscript(Client *c, const char *jsstr, ...)
884 {
885         va_list ap;
886         gchar *script;
887
888         va_start(ap, jsstr);
889         script = g_strdup_vprintf(jsstr, ap);
890         va_end(ap);
891
892         webkit_web_view_run_javascript(c->view, script, NULL, NULL, NULL);
893         g_free(script);
894 }
895
896 void
897 updatewinid(Client *c)
898 {
899         snprintf(winid, LENGTH(winid), "%lu", c->xid);
900 }
901
902 void
903 handleplumb(Client *c, const char *uri)
904 {
905         Arg a = (Arg)PLUMB(uri);
906         spawn(c, &a);
907 }
908
909 void
910 newwindow(Client *c, const Arg *a, int noembed)
911 {
912         int i = 0;
913         char tmp[64];
914         const char *cmd[29], *uri;
915         const Arg arg = { .v = cmd };
916
917         cmd[i++] = argv0;
918         cmd[i++] = "-a";
919         cmd[i++] = curconfig[CookiePolicies].val.v;
920         cmd[i++] = curconfig[ScrollBars].val.b ? "-B" : "-b";
921         if (cookiefile && g_strcmp0(cookiefile, "")) {
922                 cmd[i++] = "-c";
923                 cmd[i++] = cookiefile;
924         }
925         if (stylefile && g_strcmp0(stylefile, "")) {
926                 cmd[i++] = "-C";
927                 cmd[i++] = stylefile;
928         }
929         cmd[i++] = curconfig[DiskCache].val.b ? "-D" : "-d";
930         if (embed && !noembed) {
931                 cmd[i++] = "-e";
932                 snprintf(tmp, LENGTH(tmp), "%lu", embed);
933                 cmd[i++] = tmp;
934         }
935         cmd[i++] = curconfig[RunInFullscreen].val.b ? "-F" : "-f" ;
936         cmd[i++] = curconfig[Geolocation].val.b ?     "-G" : "-g" ;
937         cmd[i++] = curconfig[LoadImages].val.b ?      "-I" : "-i" ;
938         cmd[i++] = curconfig[KioskMode].val.b ?       "-K" : "-k" ;
939         cmd[i++] = curconfig[Style].val.b ?           "-M" : "-m" ;
940         cmd[i++] = curconfig[Inspector].val.b ?       "-N" : "-n" ;
941         cmd[i++] = curconfig[Plugins].val.b ?         "-P" : "-p" ;
942         if (scriptfile && g_strcmp0(scriptfile, "")) {
943                 cmd[i++] = "-r";
944                 cmd[i++] = scriptfile;
945         }
946         cmd[i++] = curconfig[JavaScript].val.b ? "-S" : "-s";
947         cmd[i++] = curconfig[StrictTLS].val.b ? "-T" : "-t";
948         if (fulluseragent && g_strcmp0(fulluseragent, "")) {
949                 cmd[i++] = "-u";
950                 cmd[i++] = fulluseragent;
951         }
952         if (showxid)
953                 cmd[i++] = "-w";
954         cmd[i++] = curconfig[Certificate].val.b ? "-X" : "-x" ;
955         /* do not keep zoom level */
956         cmd[i++] = "--";
957         if ((uri = a->v))
958                 cmd[i++] = uri;
959         cmd[i] = NULL;
960
961         spawn(c, &arg);
962 }
963
964 void
965 spawn(Client *c, const Arg *a)
966 {
967         if (fork() == 0) {
968                 if (dpy)
969                         close(ConnectionNumber(dpy));
970                 setsid();
971                 execvp(((char **)a->v)[0], (char **)a->v);
972                 fprintf(stderr, "%s: execvp %s", argv0, ((char **)a->v)[0]);
973                 perror(" failed");
974                 exit(1);
975         }
976 }
977
978 void
979 destroyclient(Client *c)
980 {
981         Client *p;
982
983         webkit_web_view_stop_loading(c->view);
984         /* Not needed, has already been called
985         gtk_widget_destroy(c->win);
986          */
987
988         for (p = clients; p && p->next != c; p = p->next)
989                 ;
990         if (p)
991                 p->next = c->next;
992         else
993                 clients = c->next;
994         free(c);
995 }
996
997 void
998 cleanup(void)
999 {
1000         while (clients)
1001                 destroyclient(clients);
1002         g_free(cookiefile);
1003         g_free(scriptfile);
1004         g_free(stylefile);
1005         g_free(cachedir);
1006         XCloseDisplay(dpy);
1007 }
1008
1009 WebKitWebView *
1010 newview(Client *c, WebKitWebView *rv)
1011 {
1012         WebKitWebView *v;
1013         WebKitSettings *settings;
1014         WebKitUserContentManager *contentmanager;
1015         WebKitWebContext *context;
1016
1017         /* Webview */
1018         if (rv) {
1019                 v = WEBKIT_WEB_VIEW(
1020                     webkit_web_view_new_with_related_view(rv));
1021         } else {
1022                 settings = webkit_settings_new_with_settings(
1023                    "auto-load-images", curconfig[LoadImages].val.b,
1024                    "default-charset", curconfig[DefaultCharset].val.v,
1025                    "default-font-size", curconfig[FontSize].val.i,
1026                    "enable-caret-browsing", curconfig[CaretBrowsing].val.b,
1027                    "enable-developer-extras", curconfig[Inspector].val.b,
1028                    "enable-dns-prefetching", curconfig[DNSPrefetch].val.b,
1029                    "enable-frame-flattening", curconfig[FrameFlattening].val.b,
1030                    "enable-html5-database", curconfig[DiskCache].val.b,
1031                    "enable-html5-local-storage", curconfig[DiskCache].val.b,
1032                    "enable-java", curconfig[Java].val.b,
1033                    "enable-javascript", curconfig[JavaScript].val.b,
1034                    "enable-plugins", curconfig[Plugins].val.b,
1035                    "enable-accelerated-2d-canvas", curconfig[AcceleratedCanvas].val.b,
1036                    "enable-site-specific-quirks", curconfig[SiteQuirks].val.b,
1037                    "enable-smooth-scrolling", curconfig[SmoothScrolling].val.b,
1038                    "media-playback-requires-user-gesture", curconfig[MediaManualPlay].val.b,
1039                    NULL);
1040 /* For more interesting settings, have a look at
1041  * http://webkitgtk.org/reference/webkit2gtk/stable/WebKitSettings.html */
1042
1043                 if (strcmp(fulluseragent, "")) {
1044                         webkit_settings_set_user_agent(settings, fulluseragent);
1045                 } else if (surfuseragent) {
1046                         webkit_settings_set_user_agent_with_application_details(
1047                             settings, "Surf", VERSION);
1048                 }
1049                 useragent = webkit_settings_get_user_agent(settings);
1050
1051                 contentmanager = webkit_user_content_manager_new();
1052
1053                 context = webkit_web_context_new_with_website_data_manager(
1054                           webkit_website_data_manager_new(
1055                           "base-cache-directory", cachedir,
1056                           "base-data-directory", cachedir,
1057                           NULL));
1058
1059                 /* rendering process model, can be a shared unique one
1060                  * or one for each view */
1061                 webkit_web_context_set_process_model(context,
1062                     WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES);
1063                 /* TLS */
1064                 webkit_web_context_set_tls_errors_policy(context,
1065                     curconfig[StrictTLS].val.b ? WEBKIT_TLS_ERRORS_POLICY_FAIL :
1066                     WEBKIT_TLS_ERRORS_POLICY_IGNORE);
1067                 /* disk cache */
1068                 webkit_web_context_set_cache_model(context,
1069                     curconfig[DiskCache].val.b ? WEBKIT_CACHE_MODEL_WEB_BROWSER :
1070                     WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
1071
1072                 /* Currently only works with text file to be compatible with curl */
1073                 webkit_cookie_manager_set_persistent_storage(
1074                     webkit_web_context_get_cookie_manager(context), cookiefile,
1075                     WEBKIT_COOKIE_PERSISTENT_STORAGE_TEXT);
1076                 /* cookie policy */
1077                 webkit_cookie_manager_set_accept_policy(
1078                     webkit_web_context_get_cookie_manager(context),
1079                     cookiepolicy_get());
1080                 /* languages */
1081                 webkit_web_context_set_preferred_languages(context,
1082                     curconfig[PreferredLanguages].val.v);
1083                 webkit_web_context_set_spell_checking_languages(context,
1084                     curconfig[SpellLanguages].val.v);
1085                 webkit_web_context_set_spell_checking_enabled(context,
1086                     curconfig[SpellChecking].val.b);
1087
1088                 g_signal_connect(G_OBJECT(context), "download-started",
1089                                  G_CALLBACK(downloadstarted), c);
1090                 g_signal_connect(G_OBJECT(context), "initialize-web-extensions",
1091                                  G_CALLBACK(initwebextensions), c);
1092
1093                 v = g_object_new(WEBKIT_TYPE_WEB_VIEW,
1094                     "settings", settings,
1095                     "user-content-manager", contentmanager,
1096                     "web-context", context,
1097                     NULL);
1098         }
1099
1100         g_signal_connect(G_OBJECT(v), "notify::estimated-load-progress",
1101                          G_CALLBACK(progresschanged), c);
1102         g_signal_connect(G_OBJECT(v), "notify::title",
1103                          G_CALLBACK(titlechanged), c);
1104         g_signal_connect(G_OBJECT(v), "button-release-event",
1105                          G_CALLBACK(buttonreleased), c);
1106         g_signal_connect(G_OBJECT(v), "close",
1107                         G_CALLBACK(closeview), c);
1108         g_signal_connect(G_OBJECT(v), "create",
1109                          G_CALLBACK(createview), c);
1110         g_signal_connect(G_OBJECT(v), "decide-policy",
1111                          G_CALLBACK(decidepolicy), c);
1112         g_signal_connect(G_OBJECT(v), "insecure-content-detected",
1113                          G_CALLBACK(insecurecontent), c);
1114         g_signal_connect(G_OBJECT(v), "load-failed-with-tls-errors",
1115                          G_CALLBACK(loadfailedtls), c);
1116         g_signal_connect(G_OBJECT(v), "load-changed",
1117                          G_CALLBACK(loadchanged), c);
1118         g_signal_connect(G_OBJECT(v), "mouse-target-changed",
1119                          G_CALLBACK(mousetargetchanged), c);
1120         g_signal_connect(G_OBJECT(v), "permission-request",
1121                          G_CALLBACK(permissionrequested), c);
1122         g_signal_connect(G_OBJECT(v), "ready-to-show",
1123                          G_CALLBACK(showview), c);
1124
1125         return v;
1126 }
1127
1128 void
1129 initwebextensions(WebKitWebContext *wc, Client *c)
1130 {
1131         webkit_web_context_set_web_extensions_directory(wc, WEBEXTDIR);
1132 }
1133
1134 GtkWidget *
1135 createview(WebKitWebView *v, WebKitNavigationAction *a, Client *c)
1136 {
1137         Client *n;
1138
1139         switch (webkit_navigation_action_get_navigation_type(a)) {
1140         case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1141                 /*
1142                  * popup windows of type “other” are almost always triggered
1143                  * by user gesture, so inverse the logic here
1144                  */
1145 /* instead of this, compare destination uri to mouse-over uri for validating window */
1146                 if (webkit_navigation_action_is_user_gesture(a))
1147                         return NULL;
1148         case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1149         case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1150         case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1151         case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1152         case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
1153                 n = newclient(c);
1154                 break;
1155         default:
1156                 return NULL;
1157         }
1158
1159         return GTK_WIDGET(n->view);
1160 }
1161
1162 gboolean
1163 buttonreleased(GtkWidget *w, GdkEvent *e, Client *c)
1164 {
1165         WebKitHitTestResultContext element;
1166         int i;
1167
1168         element = webkit_hit_test_result_get_context(c->mousepos);
1169
1170         for (i = 0; i < LENGTH(buttons); ++i) {
1171                 if (element & buttons[i].target &&
1172                     e->button.button == buttons[i].button &&
1173                     CLEANMASK(e->button.state) == CLEANMASK(buttons[i].mask) &&
1174                     buttons[i].func) {
1175                         buttons[i].func(c, &buttons[i].arg, c->mousepos);
1176                         return buttons[i].stopevent;
1177                 }
1178         }
1179
1180         return FALSE;
1181 }
1182
1183 GdkFilterReturn
1184 processx(GdkXEvent *e, GdkEvent *event, gpointer d)
1185 {
1186         Client *c = (Client *)d;
1187         XPropertyEvent *ev;
1188         Arg a;
1189
1190         if (((XEvent *)e)->type == PropertyNotify) {
1191                 ev = &((XEvent *)e)->xproperty;
1192                 if (ev->state == PropertyNewValue) {
1193                         if (ev->atom == atoms[AtomFind]) {
1194                                 find(c, NULL);
1195
1196                                 return GDK_FILTER_REMOVE;
1197                         } else if (ev->atom == atoms[AtomGo]) {
1198                                 a.v = getatom(c, AtomGo);
1199                                 loaduri(c, &a);
1200
1201                                 return GDK_FILTER_REMOVE;
1202                         }
1203                 }
1204         }
1205         return GDK_FILTER_CONTINUE;
1206 }
1207
1208 gboolean
1209 winevent(GtkWidget *w, GdkEvent *e, Client *c)
1210 {
1211         int i;
1212
1213         switch (e->type) {
1214         case GDK_ENTER_NOTIFY:
1215                 c->overtitle = c->targeturi;
1216                 updatetitle(c);
1217                 break;
1218         case GDK_KEY_PRESS:
1219                 if (!curconfig[KioskMode].val.b) {
1220                         for (i = 0; i < LENGTH(keys); ++i) {
1221                                 if (gdk_keyval_to_lower(e->key.keyval) ==
1222                                     keys[i].keyval &&
1223                                     CLEANMASK(e->key.state) == keys[i].mod &&
1224                                     keys[i].func) {
1225                                         updatewinid(c);
1226                                         keys[i].func(c, &(keys[i].arg));
1227                                         return TRUE;
1228                                 }
1229                         }
1230                 }
1231         case GDK_LEAVE_NOTIFY:
1232                 c->overtitle = NULL;
1233                 updatetitle(c);
1234                 break;
1235         case GDK_WINDOW_STATE:
1236                 if (e->window_state.changed_mask ==
1237                     GDK_WINDOW_STATE_FULLSCREEN)
1238                         c->fullscreen = e->window_state.new_window_state &
1239                                         GDK_WINDOW_STATE_FULLSCREEN;
1240                 break;
1241         default:
1242                 break;
1243         }
1244
1245         return FALSE;
1246 }
1247
1248 void
1249 showview(WebKitWebView *v, Client *c)
1250 {
1251         GdkRGBA bgcolor = { 0 };
1252         GdkWindow *gwin;
1253
1254         c->finder = webkit_web_view_get_find_controller(c->view);
1255         c->inspector = webkit_web_view_get_inspector(c->view);
1256
1257         c->win = createwindow(c);
1258
1259         gtk_container_add(GTK_CONTAINER(c->win), GTK_WIDGET(c->view));
1260         gtk_widget_show_all(c->win);
1261         gtk_widget_grab_focus(GTK_WIDGET(c->view));
1262
1263         gwin = gtk_widget_get_window(GTK_WIDGET(c->win));
1264         c->xid = gdk_x11_window_get_xid(gwin);
1265         updatewinid(c);
1266         if (showxid) {
1267                 gdk_display_sync(gtk_widget_get_display(c->win));
1268                 puts(winid);
1269         }
1270
1271         if (curconfig[HideBackground].val.b)
1272                 webkit_web_view_set_background_color(c->view, &bgcolor);
1273
1274         if (!curconfig[KioskMode].val.b) {
1275                 gdk_window_set_events(gwin, GDK_ALL_EVENTS_MASK);
1276                 gdk_window_add_filter(gwin, processx, c);
1277         }
1278
1279         if (curconfig[RunInFullscreen].val.b)
1280                 togglefullscreen(c, NULL);
1281
1282         if (curconfig[ZoomLevel].val.f != 1.0)
1283                 webkit_web_view_set_zoom_level(c->view,
1284                                                curconfig[ZoomLevel].val.f);
1285
1286         setatom(c, AtomFind, "");
1287         setatom(c, AtomUri, "about:blank");
1288 }
1289
1290 GtkWidget *
1291 createwindow(Client *c)
1292 {
1293         char *wmstr;
1294         GtkWidget *w;
1295
1296         if (embed) {
1297                 w = gtk_plug_new(embed);
1298         } else {
1299                 w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1300
1301                 wmstr = g_path_get_basename(argv0);
1302                 gtk_window_set_wmclass(GTK_WINDOW(w), wmstr, "Surf");
1303                 g_free(wmstr);
1304
1305                 wmstr = g_strdup_printf("%s[%lu]", "Surf",
1306                         webkit_web_view_get_page_id(c->view));
1307                 gtk_window_set_role(GTK_WINDOW(w), wmstr);
1308                 g_free(wmstr);
1309
1310                 gtk_window_set_default_size(GTK_WINDOW(w), winsize[0], winsize[1]);
1311         }
1312
1313         g_signal_connect(G_OBJECT(w), "destroy",
1314                          G_CALLBACK(destroywin), c);
1315         g_signal_connect(G_OBJECT(w), "enter-notify-event",
1316                          G_CALLBACK(winevent), c);
1317         g_signal_connect(G_OBJECT(w), "key-press-event",
1318                          G_CALLBACK(winevent), c);
1319         g_signal_connect(G_OBJECT(w), "leave-notify-event",
1320                          G_CALLBACK(winevent), c);
1321         g_signal_connect(G_OBJECT(w), "window-state-event",
1322                          G_CALLBACK(winevent), c);
1323
1324         return w;
1325 }
1326
1327 gboolean
1328 loadfailedtls(WebKitWebView *v, gchar *uri, GTlsCertificate *cert,
1329               GTlsCertificateFlags err, Client *c)
1330 {
1331         GString *errmsg = g_string_new(NULL);
1332         gchar *html, *pem;
1333
1334         c->failedcert = g_object_ref(cert);
1335         c->tlserr = err;
1336         c->errorpage = 1;
1337
1338         if (err & G_TLS_CERTIFICATE_UNKNOWN_CA)
1339                 g_string_append(errmsg,
1340                     "The signing certificate authority is not known.<br>");
1341         if (err & G_TLS_CERTIFICATE_BAD_IDENTITY)
1342                 g_string_append(errmsg,
1343                     "The certificate does not match the expected identity "
1344                     "of the site that it was retrieved from.<br>");
1345         if (err & G_TLS_CERTIFICATE_NOT_ACTIVATED)
1346                 g_string_append(errmsg,
1347                     "The certificate's activation time "
1348                     "is still in the future.<br>");
1349         if (err & G_TLS_CERTIFICATE_EXPIRED)
1350                 g_string_append(errmsg, "The certificate has expired.<br>");
1351         if (err & G_TLS_CERTIFICATE_REVOKED)
1352                 g_string_append(errmsg,
1353                     "The certificate has been revoked according to "
1354                     "the GTlsConnection's certificate revocation list.<br>");
1355         if (err & G_TLS_CERTIFICATE_INSECURE)
1356                 g_string_append(errmsg,
1357                     "The certificate's algorithm is considered insecure.<br>");
1358         if (err & G_TLS_CERTIFICATE_GENERIC_ERROR)
1359                 g_string_append(errmsg,
1360                     "Some error occurred validating the certificate.<br>");
1361
1362         g_object_get(cert, "certificate-pem", &pem, NULL);
1363         html = g_strdup_printf("<p>Could not validate TLS for “%s”<br>%s</p>"
1364                                "<p>You can inspect the following certificate "
1365                                "with Ctrl-t (default keybinding).</p>"
1366                                "<p><pre>%s</pre></p>", uri, errmsg->str, pem);
1367         g_free(pem);
1368         g_string_free(errmsg, TRUE);
1369
1370         webkit_web_view_load_alternate_html(c->view, html, uri, NULL);
1371         g_free(html);
1372
1373         return TRUE;
1374 }
1375
1376 void
1377 loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c)
1378 {
1379         const char *uri = geturi(c);
1380
1381         switch (e) {
1382         case WEBKIT_LOAD_STARTED:
1383                 setatom(c, AtomUri, uri);
1384                 c->title = uri;
1385                 c->https = c->insecure = 0;
1386                 seturiparameters(c, uri);
1387                 if (c->errorpage)
1388                         c->errorpage = 0;
1389                 else
1390                         g_clear_object(&c->failedcert);
1391                 break;
1392         case WEBKIT_LOAD_REDIRECTED:
1393                 setatom(c, AtomUri, uri);
1394                 c->title = uri;
1395                 seturiparameters(c, uri);
1396                 break;
1397         case WEBKIT_LOAD_COMMITTED:
1398                 c->https = webkit_web_view_get_tls_info(c->view, &c->cert,
1399                                                         &c->tlserr);
1400                 break;
1401         case WEBKIT_LOAD_FINISHED:
1402                 /* Disabled until we write some WebKitWebExtension for
1403                  * manipulating the DOM directly.
1404                 evalscript(c, "document.documentElement.style.overflow = '%s'",
1405                     enablescrollbars ? "auto" : "hidden");
1406                 */
1407                 runscript(c);
1408                 break;
1409         }
1410         updatetitle(c);
1411 }
1412
1413 void
1414 progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c)
1415 {
1416         c->progress = webkit_web_view_get_estimated_load_progress(c->view) *
1417                       100;
1418         updatetitle(c);
1419 }
1420
1421 void
1422 titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c)
1423 {
1424         c->title = webkit_web_view_get_title(c->view);
1425         updatetitle(c);
1426 }
1427
1428 void
1429 mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h, guint modifiers,
1430     Client *c)
1431 {
1432         WebKitHitTestResultContext hc = webkit_hit_test_result_get_context(h);
1433
1434         /* Keep the hit test to know where is the pointer on the next click */
1435         c->mousepos = h;
1436
1437         if (hc & OnLink)
1438                 c->targeturi = webkit_hit_test_result_get_link_uri(h);
1439         else if (hc & OnImg)
1440                 c->targeturi = webkit_hit_test_result_get_image_uri(h);
1441         else if (hc & OnMedia)
1442                 c->targeturi = webkit_hit_test_result_get_media_uri(h);
1443         else
1444                 c->targeturi = NULL;
1445
1446         c->overtitle = c->targeturi;
1447         updatetitle(c);
1448 }
1449
1450 gboolean
1451 permissionrequested(WebKitWebView *v, WebKitPermissionRequest *r, Client *c)
1452 {
1453         if (WEBKIT_IS_GEOLOCATION_PERMISSION_REQUEST(r)) {
1454                 if (curconfig[Geolocation].val.b)
1455                         webkit_permission_request_allow(r);
1456                 else
1457                         webkit_permission_request_deny(r);
1458                 return TRUE;
1459         }
1460
1461         return FALSE;
1462 }
1463
1464 gboolean
1465 decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
1466     WebKitPolicyDecisionType dt, Client *c)
1467 {
1468         switch (dt) {
1469         case WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION:
1470                 decidenavigation(d, c);
1471                 break;
1472         case WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION:
1473                 decidenewwindow(d, c);
1474                 break;
1475         case WEBKIT_POLICY_DECISION_TYPE_RESPONSE:
1476                 decideresource(d, c);
1477                 break;
1478         default:
1479                 webkit_policy_decision_ignore(d);
1480                 break;
1481         }
1482         return TRUE;
1483 }
1484
1485 void
1486 decidenavigation(WebKitPolicyDecision *d, Client *c)
1487 {
1488         WebKitNavigationAction *a =
1489             webkit_navigation_policy_decision_get_navigation_action(
1490             WEBKIT_NAVIGATION_POLICY_DECISION(d));
1491
1492         switch (webkit_navigation_action_get_navigation_type(a)) {
1493         case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1494         case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1495         case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1496         case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1497         case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED: /* fallthrough */
1498         case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1499         default:
1500                 /* Do not navigate to links with a "_blank" target (popup) */
1501                 if (webkit_navigation_policy_decision_get_frame_name(
1502                     WEBKIT_NAVIGATION_POLICY_DECISION(d))) {
1503                         webkit_policy_decision_ignore(d);
1504                 } else {
1505                         /* Filter out navigation to different domain ? */
1506                         /* get action→urirequest, copy and load in new window+view
1507                          * on Ctrl+Click ? */
1508                         webkit_policy_decision_use(d);
1509                 }
1510                 break;
1511         }
1512 }
1513
1514 void
1515 decidenewwindow(WebKitPolicyDecision *d, Client *c)
1516 {
1517         Arg arg;
1518         WebKitNavigationAction *a =
1519             webkit_navigation_policy_decision_get_navigation_action(
1520             WEBKIT_NAVIGATION_POLICY_DECISION(d));
1521
1522
1523         switch (webkit_navigation_action_get_navigation_type(a)) {
1524         case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1525         case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1526         case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1527         case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1528         case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
1529                 /* Filter domains here */
1530 /* If the value of “mouse-button” is not 0, then the navigation was triggered by a mouse event.
1531  * test for link clicked but no button ? */
1532                 arg.v = webkit_uri_request_get_uri(
1533                         webkit_navigation_action_get_request(a));
1534                 newwindow(c, &arg, 0);
1535                 break;
1536         case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1537         default:
1538                 break;
1539         }
1540
1541         webkit_policy_decision_ignore(d);
1542 }
1543
1544 void
1545 decideresource(WebKitPolicyDecision *d, Client *c)
1546 {
1547         int i, isascii = 1;
1548         WebKitResponsePolicyDecision *r = WEBKIT_RESPONSE_POLICY_DECISION(d);
1549         WebKitURIResponse *res =
1550             webkit_response_policy_decision_get_response(r);
1551         const gchar *uri = webkit_uri_response_get_uri(res);
1552
1553         if (g_str_has_suffix(uri, "/favicon.ico")) {
1554                 webkit_policy_decision_ignore(d);
1555                 return;
1556         }
1557
1558         if (!g_str_has_prefix(uri, "http://")
1559             && !g_str_has_prefix(uri, "https://")
1560             && !g_str_has_prefix(uri, "about:")
1561             && !g_str_has_prefix(uri, "file://")
1562             && !g_str_has_prefix(uri, "data:")
1563             && !g_str_has_prefix(uri, "blob:")
1564             && strlen(uri) > 0) {
1565                 for (i = 0; i < strlen(uri); i++) {
1566                         if (!g_ascii_isprint(uri[i])) {
1567                                 isascii = 0;
1568                                 break;
1569                         }
1570                 }
1571                 if (isascii) {
1572                         handleplumb(c, uri);
1573                         webkit_policy_decision_ignore(d);
1574                         return;
1575                 }
1576         }
1577
1578         if (webkit_response_policy_decision_is_mime_type_supported(r)) {
1579                 webkit_policy_decision_use(d);
1580         } else {
1581                 webkit_policy_decision_ignore(d);
1582                 download(c, res);
1583         }
1584 }
1585
1586 void
1587 insecurecontent(WebKitWebView *v, WebKitInsecureContentEvent e, Client *c)
1588 {
1589         c->insecure = 1;
1590 }
1591
1592 void
1593 downloadstarted(WebKitWebContext *wc, WebKitDownload *d, Client *c)
1594 {
1595         g_signal_connect(G_OBJECT(d), "notify::response",
1596                          G_CALLBACK(responsereceived), c);
1597 }
1598
1599 void
1600 responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c)
1601 {
1602         download(c, webkit_download_get_response(d));
1603         webkit_download_cancel(d);
1604 }
1605
1606 void
1607 download(Client *c, WebKitURIResponse *r)
1608 {
1609         Arg a = (Arg)DOWNLOAD(webkit_uri_response_get_uri(r), geturi(c));
1610         spawn(c, &a);
1611 }
1612
1613 void
1614 closeview(WebKitWebView *v, Client *c)
1615 {
1616         gtk_widget_destroy(c->win);
1617 }
1618
1619 void
1620 destroywin(GtkWidget* w, Client *c)
1621 {
1622         destroyclient(c);
1623         if (!clients)
1624                 gtk_main_quit();
1625 }
1626
1627 void
1628 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d)
1629 {
1630         Arg a = {.v = text };
1631         if (text)
1632                 loaduri((Client *) d, &a);
1633 }
1634
1635 void
1636 reload(Client *c, const Arg *a)
1637 {
1638         if (a->b)
1639                 webkit_web_view_reload_bypass_cache(c->view);
1640         else
1641                 webkit_web_view_reload(c->view);
1642 }
1643
1644 void
1645 print(Client *c, const Arg *a)
1646 {
1647         webkit_print_operation_run_dialog(webkit_print_operation_new(c->view),
1648                                           GTK_WINDOW(c->win));
1649 }
1650
1651 void
1652 showcert(Client *c, const Arg *a)
1653 {
1654         GTlsCertificate *cert = c->failedcert ? c->failedcert : c->cert;
1655         GcrCertificate *gcrt;
1656         GByteArray *crt;
1657         GtkWidget *win;
1658         GcrCertificateWidget *wcert;
1659
1660         if (!cert)
1661                 return;
1662
1663         g_object_get(cert, "certificate", &crt, NULL);
1664         gcrt = gcr_simple_certificate_new(crt->data, crt->len);
1665         g_byte_array_unref(crt);
1666
1667         win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1668         wcert = gcr_certificate_widget_new(gcrt);
1669         g_object_unref(gcrt);
1670
1671         gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(wcert));
1672         gtk_widget_show_all(win);
1673 }
1674
1675 void
1676 clipboard(Client *c, const Arg *a)
1677 {
1678         if (a->b) { /* load clipboard uri */
1679                 gtk_clipboard_request_text(gtk_clipboard_get(
1680                                            GDK_SELECTION_PRIMARY),
1681                                            pasteuri, c);
1682         } else { /* copy uri */
1683                 gtk_clipboard_set_text(gtk_clipboard_get(
1684                                        GDK_SELECTION_PRIMARY), c->targeturi
1685                                        ? c->targeturi : geturi(c), -1);
1686         }
1687 }
1688
1689 void
1690 zoom(Client *c, const Arg *a)
1691 {
1692         if (a->i > 0)
1693                 webkit_web_view_set_zoom_level(c->view,
1694                                                curconfig[ZoomLevel].val.f + 0.1);
1695         else if (a->i < 0)
1696                 webkit_web_view_set_zoom_level(c->view,
1697                                                curconfig[ZoomLevel].val.f - 0.1);
1698         else
1699                 webkit_web_view_set_zoom_level(c->view, 1.0);
1700
1701         curconfig[ZoomLevel].val.f = webkit_web_view_get_zoom_level(c->view);
1702 }
1703
1704 void
1705 scroll(Client *c, const Arg *a)
1706 {
1707         GdkEvent *ev = gdk_event_new(GDK_KEY_PRESS);
1708
1709         gdk_event_set_device(ev, gdkkb);
1710         ev->key.window = gtk_widget_get_window(GTK_WIDGET(c->win));
1711         ev->key.state = GDK_CONTROL_MASK;
1712         ev->key.time = GDK_CURRENT_TIME;
1713
1714         switch (a->i) {
1715         case 'd':
1716                 ev->key.keyval = GDK_KEY_Down;
1717                 break;
1718         case 'D':
1719                 ev->key.keyval = GDK_KEY_Page_Down;
1720                 break;
1721         case 'l':
1722                 ev->key.keyval = GDK_KEY_Left;
1723                 break;
1724         case 'r':
1725                 ev->key.keyval = GDK_KEY_Right;
1726                 break;
1727         case 'U':
1728                 ev->key.keyval = GDK_KEY_Page_Up;
1729                 break;
1730         case 'u':
1731                 ev->key.keyval = GDK_KEY_Up;
1732                 break;
1733         }
1734
1735         gdk_event_put(ev);
1736 }
1737
1738 void
1739 navigate(Client *c, const Arg *a)
1740 {
1741         if (a->i < 0)
1742                 webkit_web_view_go_back(c->view);
1743         else if (a->i > 0)
1744                 webkit_web_view_go_forward(c->view);
1745 }
1746
1747 void
1748 stop(Client *c, const Arg *a)
1749 {
1750         webkit_web_view_stop_loading(c->view);
1751 }
1752
1753 void
1754 toggle(Client *c, const Arg *a)
1755 {
1756         curconfig[a->i].val.b ^= 1;
1757         setparameter(c, 1, (ParamName)a->i, &curconfig[a->i].val);
1758 }
1759
1760 void
1761 togglefullscreen(Client *c, const Arg *a)
1762 {
1763         /* toggling value is handled in winevent() */
1764         if (c->fullscreen)
1765                 gtk_window_unfullscreen(GTK_WINDOW(c->win));
1766         else
1767                 gtk_window_fullscreen(GTK_WINDOW(c->win));
1768 }
1769
1770 void
1771 togglecookiepolicy(Client *c, const Arg *a)
1772 {
1773         ++cookiepolicy;
1774         cookiepolicy %= strlen(curconfig[CookiePolicies].val.v);
1775
1776         setparameter(c, 0, CookiePolicies, NULL);
1777 }
1778
1779 void
1780 toggleinspector(Client *c, const Arg *a)
1781 {
1782         if (webkit_web_inspector_is_attached(c->inspector))
1783                 webkit_web_inspector_close(c->inspector);
1784         else if (curconfig[Inspector].val.b)
1785                 webkit_web_inspector_show(c->inspector);
1786 }
1787
1788 void
1789 find(Client *c, const Arg *a)
1790 {
1791         const char *s, *f;
1792
1793         if (a && a->i) {
1794                 if (a->i > 0)
1795                         webkit_find_controller_search_next(c->finder);
1796                 else
1797                         webkit_find_controller_search_previous(c->finder);
1798         } else {
1799                 s = getatom(c, AtomFind);
1800                 f = webkit_find_controller_get_search_text(c->finder);
1801
1802                 if (g_strcmp0(f, s) == 0) /* reset search */
1803                         webkit_find_controller_search(c->finder, "", findopts,
1804                                                       G_MAXUINT);
1805
1806                 webkit_find_controller_search(c->finder, s, findopts,
1807                                               G_MAXUINT);
1808
1809                 if (strcmp(s, "") == 0)
1810                         webkit_find_controller_search_finish(c->finder);
1811         }
1812 }
1813
1814 void
1815 clicknavigate(Client *c, const Arg *a, WebKitHitTestResult *h)
1816 {
1817         navigate(c, a);
1818 }
1819
1820 void
1821 clicknewwindow(Client *c, const Arg *a, WebKitHitTestResult *h)
1822 {
1823         Arg arg;
1824
1825         arg.v = webkit_hit_test_result_get_link_uri(h);
1826         newwindow(c, &arg, a->b);
1827 }
1828
1829 void
1830 clickexternplayer(Client *c, const Arg *a, WebKitHitTestResult *h)
1831 {
1832         Arg arg;
1833
1834         arg = (Arg)VIDEOPLAY(webkit_hit_test_result_get_media_uri(h));
1835         spawn(c, &arg);
1836 }
1837
1838 int
1839 main(int argc, char *argv[])
1840 {
1841         Arg arg;
1842         Client *c;
1843
1844         memset(&arg, 0, sizeof(arg));
1845
1846         /* command line args */
1847         ARGBEGIN {
1848         case 'a':
1849                 defconfig CSETV(CookiePolicies, EARGF(usage()));
1850                 break;
1851         case 'b':
1852                 defconfig CSETB(ScrollBars, 0);
1853                 break;
1854         case 'B':
1855                 defconfig CSETB(ScrollBars, 1);
1856                 break;
1857         case 'c':
1858                 cookiefile = EARGF(usage());
1859                 break;
1860         case 'C':
1861                 stylefile = EARGF(usage());
1862                 break;
1863         case 'd':
1864                 defconfig CSETB(DiskCache, 0);
1865                 break;
1866         case 'D':
1867                 defconfig CSETB(DiskCache, 1);
1868                 break;
1869         case 'e':
1870                 embed = strtol(EARGF(usage()), NULL, 0);
1871                 break;
1872         case 'f':
1873                 defconfig CSETB(RunInFullscreen, 0);
1874                 break;
1875         case 'F':
1876                 defconfig CSETB(RunInFullscreen, 1);
1877                 break;
1878         case 'g':
1879                 defconfig CSETB(Geolocation, 0);
1880                 break;
1881         case 'G':
1882                 defconfig CSETB(Geolocation, 1);
1883                 break;
1884         case 'i':
1885                 defconfig CSETB(LoadImages, 0);
1886                 break;
1887         case 'I':
1888                 defconfig CSETB(LoadImages, 1);
1889                 break;
1890         case 'k':
1891                 defconfig CSETB(KioskMode, 0);
1892                 break;
1893         case 'K':
1894                 defconfig CSETB(KioskMode, 1);
1895                 break;
1896         case 'm':
1897                 defconfig CSETB(Style, 0);
1898                 break;
1899         case 'M':
1900                 defconfig CSETB(Style, 1);
1901                 break;
1902         case 'n':
1903                 defconfig CSETB(Inspector, 0);
1904                 break;
1905         case 'N':
1906                 defconfig CSETB(Inspector, 1);
1907                 break;
1908         case 'p':
1909                 defconfig CSETB(Plugins, 0);
1910                 break;
1911         case 'P':
1912                 defconfig CSETB(Plugins, 1);
1913                 break;
1914         case 'r':
1915                 scriptfile = EARGF(usage());
1916                 break;
1917         case 's':
1918                 defconfig CSETB(JavaScript, 0);
1919                 break;
1920         case 'S':
1921                 defconfig CSETB(JavaScript, 1);
1922                 break;
1923         case 't':
1924                 defconfig CSETB(StrictTLS, 0);
1925                 break;
1926         case 'T':
1927                 defconfig CSETB(StrictTLS, 1);
1928                 break;
1929         case 'u':
1930                 fulluseragent = EARGF(usage());
1931                 break;
1932         case 'v':
1933                 die("surf-"VERSION", see LICENSE for © details\n");
1934         case 'w':
1935                 showxid = 1;
1936                 break;
1937         case 'x':
1938                 defconfig CSETB(Certificate, 0);
1939                 break;
1940         case 'X':
1941                 defconfig CSETB(Certificate, 1);
1942                 break;
1943         case 'z':
1944                 defconfig CSETF(ZoomLevel, strtof(EARGF(usage()), NULL));
1945                 break;
1946         default:
1947                 usage();
1948         } ARGEND;
1949         if (argc > 0)
1950                 arg.v = argv[0];
1951         else
1952                 arg.v = "about:blank";
1953
1954         setup();
1955         c = newclient(NULL);
1956         showview(NULL, c);
1957
1958         loaduri(c, &arg);
1959         updatetitle(c);
1960
1961         gtk_main();
1962         cleanup();
1963
1964         return 0;
1965 }