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