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