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